print a binary tree how to fix the build_balanced_bst function - python

def str_tree(atree,indent_char ='.',indent_delta=2):
def str_tree_1(indent,atree):
if atree == None:
return ''
else:
answer = ''
answer += str_tree_1(indent+indent_delta,atree.right)
answer += indent*indent_char+str(atree.value)+'\n'
answer += str_tree_1(indent+indent_delta,atree.left)
return answer
return str_tree_1(0,atree)
def build_balanced_bst(l):
if len(l) == 0:
return None
else:
mid = (len(l)-1)/2
if mid >= 1:
build_balanced_bst(l[:mid])
build_balanced_bst(l[mid:])
else:
return
I am working on the build_balanced_bst(l), the build_balanced_bst(l) takes a list of unique values that are sorted in increasing order. calling build_ballanced_bst( list(irange(1,10)) returns a binary search tree of height 3 that would print as:
......10
....9
..8
......7
....6
5
......4
....3
..2
....1
the str_tree function is used to print what the build_balanced_bst() function returns. my str_tree function is correct, I cannot change it. I can only change the build_balanced_bst() function.
I used the middle value in the list as the root’s value. when I try to call the build_balanced_bst(l) in the below, it does not print anything.
l = list(irange(1,10))
t = build_balanced_bst(l)
print('Tree is\n',str_tree(t),sep='')
can someone help me to fix my build_balanced_bst(l) function? many thanks.

str_tree() doesn't do anything: It just defines a nested function and implicitly returns None.
As a start, you can have str_tree do something:
def str_tree(atree, indent_char ='.', indent_delta=2):
def str_tree_1(indent, atree):
# Note that str_tree_1 doesn't use the indent argument
if atree == None:
return ''
return str_tree_1(indent_delta, atree)
But this is just a start.

Related

a program to check if a reversed string is a palindrome or not using Stack Machine in python

can u help me to solve the following
am trying to get a string input from user, then push the string into the StackMachine so as to check the validity of the string. if the String passes the rules defined, the output string from the StackMachine is to be checked if its a palindrome or not ..this is what i have tried so far
note you can only use the function in the StackMachine class and not another method to determine the validity of the string. The condition to accept a string is that you have read all the input string and the stack is empty
```
class StackMachine(object):
SMRules = {} # dictionary of SM rules
def __init__(self):
self.Stack = ['S'] # populate stack with initial 'S'
self.size = 1 # set size of stack to 1
self.SMRules = {} # Place rules here
def pop(self):
if len(self.Stack) <1:
pass
else:
self.Stack.pop(0)
self.size-= 1 # reduce stack size by 1
return
def peek(self):
ss = ""
if len(self.Stack) < 1:
return ""
else:
ss = self.Stack
return ss[0]
def stackIsEmpty(self):
if len(self.Stack) == 0:
return True
else:
return False
def push(self,str):
sStr = str[::-1] # slicing
for chr in sStr:
self.Stack.insert(0,chr) # push string onto top of stack
self.size = len(self.Stack)
return
def printStack(self):
print("Stack: [",end='')
for item in self.Stack:
print(item,end='')
print("]")
return
def printRules(self):
print("SM Rules:")
rn = 1
for key, value in self.SMRules.items():
print("Rule",rn,"%4s" % key,"|", value)
rn += 1
return
def main():
Stk = StackMachine()
text =str(input('Please enter the string: '))
for character in text:
Stk.push(character)
reversed_text = ''
while not Stk.stackIsEmpty():
reversed_text = reversed_text + Stk.pop()
if text == reversed_text:
print('The string is a palindrome.')
else:
print('The string is not a palindrome.')
if __name__ == '__main__':
main()
Am getting the following Error and i dont know how to solve it
```
File "C:\Users\user\Stack-Machine\StackMachine.py", line 91, in main
reversed_text = reversed_text + Stk.pop()
TypeError: can only concatenate str (not "NoneType") to str`enter code here`
my question is
1.how do I solve the error?
2.how to print string chracter by character from the stackMachine
3.successfully check if the processed string from the Stack Machine is a palindrome or not
As defined, StackMachine.pop() returns None.
When you do reversed_text + Stk.pop(), even though reversed_text is a string, Stk.pop() is None, which causes the TypeError you are seeing.
Why do you need to use the so called StackMachine class to check if a string is a palindrome? There are simpler ways to check if a string is a palindrome.
If all you want to do is get a string input and determine whether it's a palindrome, you can do so like this:
text = input()
isPalindrome = text == text[::-1]

Height of Binary Tree?

I'm trying to implement a recursive method to calculate the height of a binary tree. Here is the "height"-code:
def HeightOfTree(self):
if self.root is None:
return 0
else:
ans=self._HeightOfTree(self.root)
return ans
def _HeightOfTree(self,currentNode):
if currentNode.hasleftChild():
lheight=1+self._HeightOfTree(currentNode.leftChild)
if currentNode.hasrightChild():
rheight=1+self._HeightOfTree(currentNode.rightChild)
if lheight > rheight:
return (lheight+1)
else:
return (rheight+1)
When I try to call the function, I get the following error msg:
UnboundLocalError: local variable 'lheight' referenced before assignment
How can I fix this problem ?
If you're setting the value of a variable in an if block and you try to use it later, make sure that it's declared before the block so that if the if doesn't happen, it still exists.
Wrong:
if False:
x = 3
print(x)
# UnboundLocalError
Right:
x = 0
if False:
x = 3
print(x)
# 0
You are getting the UnboundLocalError because the values rheight and lheight are not created in the case that leftChild or rightChild are None.
It would be simpler if you defined a base case of _HeightOfTree(None) == 0:
def _HeightOfTree(self,currentNode):
if currentNode is None:
return 0
return 1 + max(self._HeightOfTree(currentNode.leftChild), self._HeightOfTree(currentNode.rightChild))

How to not return nonType in this definition?

How can I return the value of total_square only when quasi_gen==0? If I put another return statement to the case where quasi_gen>0, then it always returns zero.
def count_boxes(quasi_gen, initial_list):
total_square=0
new_list=[]
new_list=[box * 2 for box in initial_list]
concatenate_list=initial_list+new_list
if quasi_gen>0:
quasi_gen-=1
count_boxes(quasi_gen, concatenate_list)
elif quasi_gen==0:
total_square=(sum(elem for elem in concatenate_list))
return(total_square)
count_boxes(4, [2,2])
Not sure what you're trying to do but first of all you should safe guard against quasi_gen < 0
you also don't need to do all those useless resets, in short, try this:
def count_boxes(quasi_gen, initial_list):
concatenate_list=initial_list + [box * 2 for box in initial_list]
if quasi_gen < 0:
return 0 # ?
if quasi_gen > 0:
return count_boxes(quasi_gen - 1, concatenate_list)
return(sum(elem for elem in concatenate_list))
You have to call return on the first if/else branch:
if quasi_gen>0:
quasi_gen-=1
return count_boxes(quasi_gen, concatenate_list)
Like this you will be returning the result of the recursive call.

Printing a binary tree in the specific format

def str_tree(atree,indent_char ='.',indent_delta=2):
def str_tree_1(indent,atree):
if atree == None:
return ''
else:
answer = ''
answer += str_tree_1(indent+indent_delta,atree.right)
answer += indent*indent_char+str(atree.value)+'\n'
answer += str_tree_1(indent+indent_delta,atree.left)
return answer
return str_tree_1(0,atree)
def build_balanced_bst(l):
d = []
if len(l) == 0:
return None
else:
mid = (len(l)-1)//2
if mid >= 1:
d.append(build_balanced_bst(l[:mid]))
d.append(build_balanced_bst(l[mid:]))
else:
return d
The build_balanced_bst(l) takes in a list of unique values that are sorted in increasing order. It returns a reference to the root of a well-balanced binary search tree. For example, calling build_ballanced_bst( list(irange(1,10)) returns a binary search tree of height 3 that would print as:
......10
....9
..8
......7
....6
5
......4
....3
..2
....1
The str_tree function prints what the build_balanced_bst function returns
I am working on the build_balanced_bst(l) function to make it apply to the str_tree function. I used the middle value in the list as the root’s value.
But when I call the function as the way below:
l = list(irange(1,10))
t = build_balanced_bst(l)
print('Tree is\n',str_tree(t),sep='')
it doesn't print anything. Can someone help me to fix my build_balanced_bst(l) function?
Keeping the str_tree method as it is, here's the remaining code.
class Node:
"""Represents a single node in the tree"""
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def build_balanced_bst(lt):
"""
Find the middle element in the sorted list
and make it root.
Do same for left half and right half recursively.
"""
if len(lt) == 1:
return Node(lt[0])
if len(lt) == 0:
return None
mid = (len(lt)-1)//2
left = build_balanced_bst(lt[:mid])
right = build_balanced_bst(lt[mid+1:])
root = Node(lt[mid], left, right)
return root
ordered_list = list(range(1,11))
bst=build_balanced_bst(ordered_list)
bst_repr = str_tree(bst)
print(bst_repr)
The output comes out as follows:
......10
....9
..8
......7
....6
5
......4
....3
..2
....1

Can I create a master function in Python to take a single line of other functions?

I have two functions that contain mostly the same code. One returns "True" if the array passed in contains all positive numbers while the other returns "True" if the array contains all numbers that are divisible by 10.
I want to combine these two functions into a function like this:
def master_function(array, function):
for i in array:
if function:
result = True
else:
result = False
break
print(result)
return result
The only part that would vary is the "function" in the If statement. When I write functions with the missing line they don't get called as the program executes.
def positive_integers(array):
i >= 0
def divisible_by_10(array):
i%10 == 0
The test code isn't executed either.
master_function([10,20,30,35],divisible_by_10)
Your functions aren't returning anything, and you need to give them access to i:
def positive_integers(i):
return i >= 0
def divisible_by_10(i):
return not i%10
def master_function(array, function):
for i in array:
if function(i):
result = True
else:
result = False
break
print(result)
return result
Your function don't return anything. Also, you need read about all and any:
def positive_integers(array):
return all(i >= 0 for i in array)
def divisible_by_10(array):
return all(i % 10 == 0 for i in array)
def master_function(array, function):
return function(array)
def master_function(array, function):
for i in array:
print str(i)
if function(i):
result = True
else:
result = False
print(result)
return result
def positive_integers(i):
if i >= 0:
return True
def divisible_by_10(i):
if i%10 == 0:
return True
master_function([10,20,30,35],divisible_by_10)

Categories

Resources