adding parenthesis in recursive function - python

I'm simply looking to add a parenthesis at the end of my recursive function.. I'm literally just missing the final parenthesis, but I can't figure out how to add it in! Any help is greatly appreciated!
My code:
def sum( n ):
if n == 0:
return '1'
elif n == 1:
return '(1+1)'
elif n == 2:
return '((1+1)+(1+1))'
elif n == 3:
return '(((1+1)+(1+1))+((1+1)+(1+1)))'
else:
return '((((1+1)+(1+1))+((1+1)+(1+1)))' + ')'sum_power2( n - 1 )

Just switch the order in the last row, so it would be
def sum_power2( n ):
if n == 0:
return '1'
elif n == 1:
return '(1+1)'
elif n == 2:
return '((1+1)+(1+1))'
elif n == 3:
return '(((1+1)+(1+1))+((1+1)+(1+1)))'
else:
return '((((1+1)+(1+1))+((1+1)+(1+1)))' + sum_power2( n - 1 )+')'

Try this:
def sum_power(n,tmp=''):
tmp = '1' if not tmp else '(' + tmp + '+' + tmp + ')'
if n == 0:
return tmp
else:
n -= 1
return sum_power(n,tmp)
print(sum_power(2))

Related

How to remove 1 as a coefficient on my Python Code?

I have been looking at my code for awhile and need to return a polynomial given a dictionary. The polynomial output should not have any 1's as coefficients. Her e is my code:
class Polynomial:
# Constructor
def __init__(self, polyDict):
self.polyDict = polyDict
# String Method
def __str__(self):
polyStr = ""
firstTerm = True
for exp, coeff in sorted(self.polyDict.items(), reverse=True):
if coeff == 0:
continue
if firstTerm:
if coeff > 0:
polyStr += str(coeff)
else:
polyStr += str(coeff)
if exp > 1:
polyStr += "x^" + str(exp)
elif exp == 1:
polyStr += "x"
firstTerm = False
else:
if coeff > 0:
polyStr += "+" + str(coeff)
else:
polyStr += str(coeff)
if exp > 1:
polyStr += "x^" + str(exp)
elif exp == 1:
polyStr += "x"
return polyStr
print(Polynomial({6:-3, 5:6, 4:-1, 3:-2, 2:0, 1:1, 0:-3}))
I am unsure what else to try. I've staired at the code for a couple hours and dont know what to add.
I think this combines as much as can be combined.
class Polynomial:
# Constructor
def __init__(self, polyDict):
self.polyDict = polyDict
# String Method
def __str__(self):
polyStr = ""
firstTerm = True
for exp, coeff in sorted(self.polyDict.items(), reverse=True):
if coeff == 0:
continue
if coeff < -1 or (firstTerm and coeff > 1):
polyStr += str(coeff)
elif coeff == -1:
polyStr += '-'
elif coeff == 1:
if not firstTerm:
polyStr += '+'
else:
polyStr += '+'+str(coeff)
firstTerm = False
if exp > 1:
polyStr += "x^"+str(exp)
elif exp == 1:
polyStr += "x"
return polyStr
print(Polynomial({6:-3, 5:6, 4:-1, 3:-2, 2:0, 1:1, 0:-3}))

Python program to convert infix to prefix notation

I keep on getting an IndexError: list index out of range, return self.data[-1] # the last element in the list; I think I know what is causing this but I have no clue how to fix it
Here is the Stack Class I used:
class Stack:
# LIFO Stack implementation using a Python list as underlying storage.
def __init__(self):
self.data =[]
def __len__(self):
return len(self.data)
def is_empty(self):
return len(self.data)==0
def push(self, e):
self.data.append(e)
def top(self):
return self.data[-1]
def pop(self):
return self.data.pop()
And the corresponding code I made:
def operatorpriority(x):
if x == "+" or x == "-":
return 1
elif x == "*" or x == "/":
return 2
else:
return 3
return 0
def polishnotation(A):
# Converts Infix to Prefix Notation
stack = Stack()
stack.push(')')
A = A + '('
output = ""
for i in range(len(A)-1, -1, -1):
print(i)
if A[i].isnumeric() == True:
output+=A[i]
elif A[i] == ")":
stack.push(A[i])
elif A[i] == "-" or A[i] == "+" or A[i] == "*" or A[i] == "/" or A[i] == "^":
if A[i] == "^":
while operatorpriority(A[i]) <= operatorpriority(stack.top()):
output+=stack.pop()
else:
while operatorpriority(A[i]) < operatorpriority(stack.top()):
output+=stack.pop()
stack.push(A[i])
elif A[i] == "(":
while stack.is_empty()== False:
if stack.top() != "(":
output+=stack.pop()
stack.pop()
while stack.is_empty()== False:
output+=stack.pop()
print(output)
InfixInput = input("Input infix notation: ")
polishnotation(InfixInput)
Sample Input:
(a+b)*(c-d)
Expected Output:
*+ab-cd
You have A = A + '('. That adds at the wrong end. Just do A = '('+A+')' and skip the extra push.
You are giving ')' the same priority as '^'. In operatorpriority, your else: should be elif x =='^':.
In your elif A[i] == "(" clause, you are popping until '('. That's the wrong type of parens. And you don't break out of that loop until the stack is empty. You need to break when you get to a ')'.
Your example shows (a+b)*(c+d), but your code only allows digits. I haven't changed that.
This works:
class Stack:
# LIFO Stack implementation using a Python list as underlying storage.
def __init__(self):
self.data =[]
def __len__(self):
return len(self.data)
def is_empty(self):
return len(self.data)==0
def push(self, e):
self.data.append(e)
def top(self):
return self.data[-1]
def pop(self):
return self.data.pop()
def operatorpriority(x):
if x in "+-":
return 1
elif x in "*/":
return 2
elif x in "^":
return 3
return 0
def polishnotation(A):
# Converts Infix to Prefix Notation
stack = Stack()
A = '(' + A + ')'
output = ""
for c in A[::-1]:
print(c)
if c.isnumeric():
output+=c
elif c == ")":
stack.push(c)
elif c in "+-*/^":
if c == "^":
while operatorpriority(c) <= operatorpriority(stack.top()):
output+=stack.pop()
else:
while operatorpriority(c) < operatorpriority(stack.top()):
output+=stack.pop()
stack.push(c)
elif c == "(":
while not stack.is_empty():
c1 = stack.pop()
if c1 == ')':
break
output+=c1
while not stack.is_empty():
output+=stack.pop()
return output
print(polishnotation('(3+4)*(5+6)'))

Calling a Fibonacci function

When I call this function from the client by writing FIBONACCI, it won't show the result:
def FIBONACCI(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return FIBONACCI(n-1) + FIBONACCI(n-2)
It seems like you wrote a working function, but didn't call it, and print the result. This code should do the job:
def FIBONACCI(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return FIBONACCI(n-1) + FIBONACCI(n-2)
if __name__ == '__main__':
print(FIBONACCI(10))

Python Recursion Double letters

So what the task is, is that your supposed to write a recursion function that counts the amount of "double" letters in a string, So for example the string "hmmm" would return 1 and the string "hmmmm" would return 2 and that a string "abb" would return 1. My code is here:
def num_double_letters(astr):
if astr == "" or len(astr) == 1:
return 0
elif len(astr) == 2:
if astr[0] == astr[1]:
return 1 + num_double_letters(astr[1:])
else:
return 0 + num_double_letters(astr[1:])
elif astr[0] != astr[1]:
return 0 + num_double_letters(astr[1:])
elif astr[0] == astr[1] != astr[2]:
return 1 + num_double_letters(astr[1:])
elif astr[0] == astr[1] == astr[2]:
return 0 + num_double_letters(astr[1:])
My problem is that a string with 4 same letters = 1 when its supposed to = 2. And also is there a cleaner way to do this?
I think you've made it a bit complicated for yourself... there's no need to go deeper into the recursion once the length of your string is 2, and you want to advance by 2, not 1 when you find a double to count the way I think you do. Try this:
def num_double_letters(astr):
if astr == "" or len(astr) == 1:
return 0
elif len(astr) == 2:
if astr[0] == astr[1]:
return 1
else:
return 0
elif astr[0] != astr[1]:
return 0 + num_double_letters(astr[1:])
elif astr[0] == astr[1]:
return 1 + num_double_letters(astr[2:])
print(num_double_letters('hmm'))
print(num_double_letters('hmmm'))
print(num_double_letters('hmmmm'))
Output:
1
1
2
You might consider the following more Pythonic and concise:
def num_double_letters(astr):
if len(astr) < 2:
return 0
if astr[0] == astr[1]:
return 1 + num_double_letters(astr[2:])
return num_double_letters(astr[1:])

Binary Subtraction - Python

I want to make a binary calculator and I have a problem with the subtraction part. Here is my code (I have tried to adapt one for sum that I've found on this website).
maxlen = max(len(s1), len(s2))
s1 = s1.zfill(maxlen)
s2 = s2.zfill(maxlen)
result = ''
carry = 0
i = maxlen - 1
while(i >= 0):
s = int(s1[i]) - int(s2[i])
if s <= 0:
if carry == 0 and s != 0:
carry = 1
result = result + "1"
else:
result = result + "0"
else:
if carry == 1:
result = result + "0"
carry = 0
else:
result = result + "1"
i = i - 1
if carry>0:
result = result + "1"
return result[::-1]
The program works fine with some binaries subtraction but it fails with others.
Can someone please help me because I can't find the mistake? Thanks a lot.
Short answer: Your code is wrong for the case when s1[i] == s2[i] and carry == 1.
Longer answer: You should restructure your code to have three separate cases for s==-1, s==0, and s==1, and then branch on the value of carry within each case:
if s == -1: # 0-1
if carry == 0:
...
else:
...
elif s == 0: # 1-1 or 0-0
if carry == 0:
...
else:
...
else: # 1-0
if carry == 0:
...
else:
...
This way you have a separate block for each possibility, so there is no chance of overlooking a case like you did on your first attempt.
I hope the answer below it helps.
def binarySubstration(str1,str2):
if len(str1) == 0:
return
if len(str2) == 0:
return
str1,str2 = normaliseString(str1,str2)
startIdx = 0
endIdx = len(str1) - 1
carry = [0] * len(str1)
result = ''
while endIdx >= startIdx:
x = int(str1[endIdx])
y = int(str2[endIdx])
sub = (carry[endIdx] + x) - y
if sub == -1:
result += '1'
carry[endIdx-1] = -1
elif sub == 1:
result += '1'
elif sub == 0:
result += '0'
else:
raise Exception('Error')
endIdx -= 1
return result[::-1]
normalising the strings
def normaliseString(str1,str2):
diff = abs((len(str1) - len(str2)))
if diff != 0:
if len(str1) < len(str2):
str1 = ('0' * diff) + str1
else:
str2 = ('0' * diff) + str2
return [str1,str2]

Categories

Resources