Binary trees- pseudo codes? - data-structures

I'm trying to write this pseudo code for checking whether a data-structure based on trees
is a binary tree.
I'm having a little problem with understanding this pseudo code form.
This is what I wrote:
Is-Binary(x)
if (x=null) {Then Return True
}
else {
if (x.Right<>Null) {Then
if (x.key<x.right.key){Then
Is-Binary(x.Right)}
else {Return False}}
if (x.Left<>Null) {Then
if (x.key>x.Left.key){Then
Is-binart(x.Left)}
else {Return False}}
}
My question: Can I assume that after the first true will be accepted, the program wont finish?
What does the return means here? will it sum up all the true/false and give the final soulotion (based on the fact that true*false=false?)
If so, what else can I do?
Thank you

You'll only get one result, either true or false, because you're not accumulating anything. Assuming you're starting from the top of a tree, say you only go one level deep, you'll only get true or false as a result. Then, if you get another level deeper (with another call), you're just facing the same possibilities: True, false, or deeper in the tree.
[Edit, after further observation:] Unless I'm mistaken, you'll get True the first time you hit a null, which might never happen because you never call Is-Binary on a null-value.
So if X is null you get true, else you get false.

Related

Why does this work when it looks like it's missing some return calls (DFS)?

def dfs(s,d):
def dfs_helper(s,d):
if s==d:
return True
if s in visited:
return False
visited.add(s)
for c in graph[s]:
dfs_helper(c,d)
return False
visited = set()
return dfs_helper(s,d)
I'm not sure why the above code is correct. I saw this in a paper but shouldn't it say return dfs_helper(c,d) instead of just dfs_helper(c,d) when looping through all the neighbors? Otherwise, how do we return anything all the way up since I thought returns only take you one level up to the immediate caller.
I.e. if we have a graph with edges (A,B), (A,C), and (C,D), I get why the dfs_helper(D,D) returns True, but when we run dfs_helper(C,D), we just run dfs_helper(D,D) but we aren't RETURNING dfs_helper(D,D) so True does not get passed back up. Shouldn't that be the case? And if not, why is that so?
Fixed this. It turns out I was on the right track.
I needed to change from
for c in graph[s]:
dfs_helper(c,d)
to
for c in graph[s]:
if dfs_helper(c,d): return True

Unexpected output using hashing

Hello everyone lately I encountered quite an easy algorithm problem which at my great surprise I encountered a difficulty. The task was to return true if a particular array contained a duplicate element else false
Actually I don't understand why my program produces an unexpected output . I know many other solutions to solve that problem but I want to understand why this solutions doesn't not work . And it returns False from input [1,2,3,1]
In facts it's always returns false nor matter the input. It never passes the condition in the try statement
dic = {}
for i in range(0,len(nums)):
try:
if dic[nums[i]]:
return True
except:
dic[nums[i]] = i
return False
It wouldn't always return False. It would return True if your duplicated value is NOT at the start of nums (which I assume is a list of numbers).
Notice that on line dic[nums[i]] = i on the first iteration you are updating your dictionary with i equals to 0. That is why later on you can't catch the case in which your duplicated value is at the start of the list.

Huffman decoding (in Scala)

I'm trying to write an algorithm to perform Huffman decoding. I am doing it in Scala - it's an assignment for a Coursera course and I don't want to violate the honor code, so the below is pseudocode rather than Scala.
The algorithm I have written takes in a tree tree and a list of bits bits, and is supposed to return the message. However, when I try it on the provided tree, I get a NoSuchElementException (head of empty list). I can't see why.
I know that my code could be tidied up a bit - I'm still very new to functional programming so I've written it in a way that makes sense to me, rather than, probably, in the most compact way.
def decode(tree, bits) [returns a list of chars]: {
def dc(aTree, someBits, charList) [returns a list of chars]: {
if aTree is a leaf:
if someBits is empty: return char(leaf) + charList
else: dc(aTree, someBits, char(leaf) + charList)
else aTree is a fork:
if someBits.head is 0: dc(leftFork, someBits.tail, charList)
else someBits is 1: dc(rightFork, someBits.tail, charList)
}
dc(tree, bits, [empty list])
}
Thanks in advance for your help. It's my first time on StackOverflow, so I probably have some learning to do as to how best to use the site.
If I understand it correctly, you want to go through forks (with directions from bits) until you will find a leaf. Then you are adding leaf value to your char list and from this point you want to repeat steps.
If I am right, then you should pass original tree to your helper method, not a leftFork or rightFork, which are leafs now.
So it would be something like:
if aTree is a leaf:
if someBits is empty: return char(leaf) + charList
else: dc(tree, someBits, char(leaf) + charList)

If/ Else, test true first or false first

I have a rather specific question.
Say I am at the end of a function, and am determining whether to return true or false.
I would like to do this using an if/else statement, and have two options: (examples are in pseudocode)
1) Check if worked first:
if(resultVar != error){
return true;
}else{
return false;
}
2) Check if it failed first:
if(resultVar == error){
return false;
}else{
return true;
}
My question is simple: Which case is better (faster? cleaner?)?
I am really looking at the if/else itself, disregarding that the example is returning (but thanks for the answers)
The function is more likely to want to return true than false.
I realize that these two cases do the exact same thing, but are just 'reversed' in the order of which they do things. I would like to know if either one has any advantage over the other, whether one is ever so slightly faster, or follows a convention more closely, etc.
I also realize that this is extremely nitpicky, I just didn't know if there is any difference, and which would be best (if it matters).
Clarifications:
A comparison needs to be done to return a boolean. The fact that of what the examples are returning is less relevant than how the comparison happens.
This is by far the cleanest:
return resultvar != error;
The only difference in both examples may be the implementation of the operator. A != operator inverses the operation result. So it adds an overhead, but very small one. The == is a straight comparison.
But depending on what you plan to do on the If/else, if there is simply assigning a value to a variable, then the conditional ternary operator (?) is faster. For complex multi value decisions, a switch/case is more flexible, but slower.
This will be faster in your case:
return (resultVar == error) ? false : true;
This will depend entirely on the language and the compiler. There is no specific answer. In C for instance, both of these would be encoded rather like:
return (resultVar!=error);
by any decent compiler.
Put true first, because it potentially eleiminates a JUMP command in assembly. However, the difference is negligible, since it's an else, rather than an else if. There may /technically be a difference/, but you will see no performance difference in this case.

OR between two function call

What is the meaning of a || between two function call
like
{
//some code
return Find(n.left,req)||Find(n.right,req);
}
http://www.careercup.com/question?id=7560692
can some one help me to understand . Many thanks in advance.
It means that it returns true if one of the two functions is true (or both of them).
Depends on the programming language, the method calls Find(n.left,req) -> if it's true - returns true. if it's false, it calls Find(n.right,req) and returns its Boolean value.
In Java (and C and C#) || means "lazy or". The single stroke | also means "or", but operates slightly differently.
To calculate a||b, the computer calculates the truth value (true or false) of a, and if a is true it returns the value true without bothering to calculate b, hence the word "lazy". Only if a is false, will it checks b to see if it is true (and so if a or b is true).
To calculate a|b, the computer works out the value of a and b first, then "ors" the answers together.
The "lazy or" || is more efficient, because it sometimes does not need to calculate b at all. The only reason you might want to use a|b is if b is actually a function (method) call, and because of some side-effect of the method you want to be sure it executes exactly once. I personally consider this poor programming technique, and on the very few occasions that I want b to always be explicitly calculated I do this explicitly and then use a lazy or.
Eg consider a function or method foo() which returns a boolean. Instead of
boolean x = a|foo(something);
I would write
boolean c=foo(something);
boolean x = a||c;
Which explicitly calls foo() exactly once, so you know what is going on.
Much better programming practice, IMHO. Indeed the best practice would be to eliminate the side effect in foo() entirely, but sometimes that's hard to do.
If you are using lazy or || think about the order you evaluate it in. If a is easy to calculate and usually true, a||b will be more efficient than b||a, as most of the time a simple calculation for a is all that is needed. Conversely if b is usually false and is difficult to calculate, b||a will not be much more efficient than a|b. If one of a or b is a constant and the other a method call, you should have the constant as the first term a||foo() rather than foo()||a as a method call will always be slower than using a simple local variable.
Hope this helps.
Peter Webb
return Find(n.left,req)||Find(n.right,req);
means execute first find {Find(n.left,req)} and return true if it returns true or
execute second find return the value true if it return true, otherwise false.

Resources