Return Inorder Traversal list - python

I'm trying to return list from inorder traversal and below is my code. If my input is [1,2,3] and output should be [3,1,2], but I'm returning value none. Can you please suggest what is wrong in my code? Thanks.
def inorderTraversal(currentNode,output=None):
if output==None:
output=[]
if currentNode.left:
return inorderTraversal(currentNode.left,output)
return output.append(currentNode.data)
if currentNode.right:
return inorderTraversal(currentNode.right,output)

The problem is this line:
return output.append(currentNode.data)
You are returning the value of append but that is None. append changes the list but it does not return the new value of the list. Do this instead.
output.append(currentNode.data)
return output

Related

How can I make my list return each element only once in a list?

So I wrote this code to return back every string in the given lst: list once. Here is my code
def make_unique(lst: list[str]):
s = []
for x in lst:
if lst.count(x) == 1:
s.append(x)
else:
return(x)
return s
When I put in the input:
print(make_unique(lst=['row','mun','row']))
The output returns
row
but I want my output to return
['row','mun']
which is basically all the strings in the list printed once.
How can I do this??
Why not you try this one line short code to remove duplicates from your list and make it unique
def make_unique(lst):
return list(dict.fromkeys(lst))
print(make_unique(['row','mun','row'])) #['row','mun']
Easy way to do this is turn the list into a set. A set only shows each item once and thats what you want.
lst=['row','mun','row']
setLst = set(lst)
for elem in setLst:
print(elem)
You can use set.
lst=['row','mun','row']
print(set(lst))

How to get first satisfied return value for a collection?

I am new to Scala. I have a HashSet, when I iterate over it, I apply a recursive function to the element. How can I get the first satisfied function return value?
I tried collections.find(...).map(...), but cannot extract the return value inside the function in find(), and I don't want map to run these recursive function again.
def Rec(myObject, acc: list):
if myObject.size == 1:
return acc
elif len(myObject.myList) == 0:
return None
else:
for e in myObject.myList:
#func is another function that create a new object whose size is smaller and changes myList attribute
newObject = func(myObject, e)
acc.append(e)
res = Rec(newObject, acc)
if res:
return res
return None
So, my question is how to convert above python code to idiomatic scala code.
EDIT:
For example:
I want to write like this:
list.find(e=>Rec(e).isDefined).map(e=>Rec(e).get)
Rec() is a function that returns an option. And I want to extract the result of Rec(e) in find(...) when it finds, so I don't have to recalculate it in the map(...)
If I understand correctly, you have a List of elements of some (unspecified) type and you want to process each element only until the first non-None result.
Something like this?
myObject.myList //List of elements
.view //evaluate lazily
.flatMap(rec) //pass to the rec() func, flatten away all None results
.headOption //Some(<1st good result>) or None
In this case rec() is invoked only until the first non-None result is returned, or until the end of the list if no non-None result is produced.

How to implement DFS with recursive function on JSON dict of tree?

I use a recursive Depth-First-Search function to traverse a tree where each node has an index.
During traversing, I need to assign one node (whose type is dict) to a variable to further process from outer scope.
It seems that I use a useless assignment. What is the most efficient way to do that?
def dfs(json_tree, index, result):
if json_tree['index'] == index:
result = json_tree['index'] ## not work!
return
if 'children' not in json_tree:
return
for c in json_tree['children']:
dfs(c, index, result)
Try returning result instead. Note that I changed your function signature. This will also short-circuit the search as soon as index is found.
def dfs(json_tree, index):
if json_tree['index'] == index:
return json_tree['index']
if 'children' not in json_tree:
return None
for c in json_tree['children']:
result = dfs(c, index)
if result is not None:
return result
return None
Edit: Updated with a final return path in case index is never found.

Using simple Recursion to create a list

I want every element in l(which is a list) to be added to a.
When I run the function, it gives me '[]' every time. How can I fix this?
def sim(l):
a = []
if len(l)>0:
a = a.append(l.pop())
l.pop()
return sim(l)
return a
Several things are wrong:
You shouldn't use lowercase L for a variable name - it looks like one
At the top of the function you assign an empty list to a - ultimately sim will be called with an empty list, then a will be assigned an empty list, the conditional statement will fail and sim will return an empty list.
Inside the conditional statement you assign the return value of list.append() to a. The return value is None so whatever a was before, it gets wiped out.
Inside the conditional statement you pop() two items out of your control list
An empty list has a boolean value of false so there is no need to explicitly check its length,
def sim(el, a = None):
if el:
a.append(el.pop())
return sim(el, a)
return a
I was taught to write the base case of a recursive function as the first statement:
def sim(el, a = None):
if not el:
return a
a.append(el.pop())
return sim(el, a)
append() doesn't return anything but does update the existing list. In other words, by trying to assign the result of the append() method, you're setting a to nothing after you have already appended the item.
Your Code :def sim(l):
a = []
when you call Function recursively return sim(l) every time it is call sim(l) and a=[] is empty.
Try This :
def sim(l,a):
if len(l)>0:
a.append(l.pop())
print a
return sim(l,a)
return a
Is this a homework assignment where you're required to do it in a certain (overly complicated) way? Because if not, you can add one list to another in Python like so:
>>> l = [1, 2, 3]
>>> a = []
>>> a.extend(l)
>>> a
[1, 2, 3]

Debbugging-For fixing a function

I am debugging the following function:
def buggy_dedup_sort_by_len(input):
unique = list(set(input))
return unique.sort(key=len)
the list is sorted but the unique.sort(key=len) is returning nothing.
wont the function list.sort return anything.How can I fix it???
sort returns None because it mutates the list in-place. Try:
def buggy_dedup_sort_by_len(input):
unique = list(set(input))
unique.sort(key=len)
return unique
Alternatively, use sorted, which does return a list.
def buggy_dedup_sort_by_len(input):
unique = list(set(input))
return sorted(unique, key=len)

Categories