Recursion depth exceeded in comparison - python

The program has two functions human_pyramid(no_of_people) that will take no_of_people in the base as argument and will return the weight of the total pyramid
x
x x x
X X X X X <=== this is the argument (no_of_people = 5)
the weight of each person is taken 50 and the function will return 450
def human_pyramid(no_of_people):
if no_of_people == 1:
return 50
else:
return no_of_people*(50)+human_pyramid(no_of_people-2)
The second fucntion takes max_weight as an argument and returns the number of people that can form the human pyramid without exceeding max weight.
def find_maximum_people(max_weight):
no_of_people=0
while human_tower(no_of_people) <= max_weight:
no_of_people +=1
return no_of_people
max_people=find_maximum_people(1000)
print(max_people)
I'm getting an RecursionError on the line while human_tower(no_of_people) <= max_weight: and
return no_of_people*(50)+human_pyramid(no_of_people-2)
but running the function human_pyramid(no_of_people) on its own it runs fine

if no_of_people == 1:
return 50
else :
return no_of_people*(50)+human_pyramid(no_of_people-2)
the condition no_of_people == 1 will become True only if the value originally passed is odd.
As a solution you may add one more base case for when no_of_people == 0
if no_of_people == 1:
return 50
elif no_of_people == 0:
return 0
else :
return no_of_people*(50)+human_pyramid(no_of_people-2)

Related

***Time limit exceeded*** error on python program

when i try to print this line:
print(perfect_square(0))
i should get True but instead i get a time limit exceeded error and i dont know how to fix it.
i tried chaging it to an elif statment instead of 2 separate if statements but i still get that error
This is my current code:
def perfect_square(n):
s = 1
while s != n:
if s*s == n:
return True
elif s == 0:
return True
else:
s +=1
return False
def perfect_cube(n):
s = 1
while s != n:
if s*s * s == n:
return True
elif s == 0:
return True
else:
s +=1
return False
Seems quite clear to me why the perfect_square(0) and perfect_cube(0) cases cause an infinite loop. You start s=1 and always increment it s+=1. It will never be equal to n=0 so you get an infinitely running program. Maybe try making checks for invalid values of n?
def perfect_cube(n):
if n < 1: return False
# ...

Python Perfect Number

In this Python Question, I should get False if the the number is not perfect. instead, I'm getting "None". What should I change?
def perfect(number):
sum = 0
is_perfect = False
if number < 0:
return is_perfect
for i in range(1, number):
if(number % i == 0):
sum = sum + i
if (sum == number):
is_perfect = True
return is_perfect
print(perfect(8))
You should return False at the End otherwise None is getting returned implicitly:
def perfect(number):
...
for i in range(1, number):
...
return False
Hi your problem is that you have no return when you don't match if (sum == number):..
so, the simplest solution is to add an return False at the end. But also your sum condition is inside the for that's not fine because you can encounter a fake perfect
like 24... so be carefull about that condition
edit 0 is not a perfect number so add the condition to first if
def perfect(number):
sum = 0
is_perfect = False
if number <= 0:
return is_perfect
for i in range(1, number):
if(number % i == 0):
sum = sum + i
if (sum == number):
is_perfect = True
return is_perfect
return False
I would totally reshape your code to make it a litle more clear:
def is_perfect(number):
acum= 0
if number <= 0:
return False
for i in range(1, number):
if(number % i == 0):
acum += i
return (acum == number) #return true if the condition match, False if not
#just to check function
print([(i,is_perfect(i)) for i in range(1,100) if is_perfect(i)])
#output
[(6, True), (28, True)]

How do I count the number of recursive calls for n-queens problem?

I have the following code for solving the n-queens problem and I am supposed to count the number of recursive calls made. I have a function called ConstructCandidates to get the candidate solutions and I am trying to count the number of recursive calls it makes. I was wondering if I am counting the recursive calls correctly as I am not sure if I am doing this correctly.
def createChessBoard(boardSize):
chessBoard = [0]*boardSize
for index in range(boardSize):
chessBoard[index] = [0]*boardSize
return chessBoard
def isSolution(results, numberOfQueens):
if numberOfQueens==n:
for r in results:
for row in r:
print(row)
print()
return numberOfQueens>len(results)
def safeToPlaceQueen(chessBoard, boardRow, boardColumn, boardSize):
for indexColumn in range(boardColumn):
if chessBoard[boardRow][indexColumn] == 1:
return False
indexRow, indexColumn = boardRow, boardColumn
while indexRow >= 0 and indexColumn >= 0:
if chessBoard[indexRow][indexColumn] == 1:
return False
indexRow-=1
indexColumn-=1
diagonalRow, diagonalColumn = boardRow,boardColumn
while diagonalRow < boardSize and diagonalColumn >= 0:
if chessBoard[diagonalRow][diagonalColumn] == 1:
return False
diagonalRow+=1
diagonalColumn-=1
return True
def ConstructCandidates(chessBoard, columnLength, boardSize):
global recursionCounter
if columnLength >= boardSize:
return
for row in range(boardSize):
if safeToPlaceQueen(chessBoard, row, columnLength, boardSize):
chessBoard[row][columnLength] = 1
if columnLength == boardSize-1:
Process(chessBoard)
chessBoard[row][columnLength] = 0
return
#recursively call ConstructCandidates to find more candidate solutions
ConstructCandidates(chessBoard, columnLength+1, boardSize)
chessBoard[row][columnLength] = 0
recursionCounter+=1
def Process(chessBoard):
global results
solutions = copy.deepcopy(chessBoard)
results.append(solutions)
global count
count= len(results)
def isFinished():
if count >0:
return False
n = 8
chessBoard = createChessBoard(n)
results = []
recursionCounter =0
ConstructCandidates(chessBoard, 0, n)
isSolution(results, n)
if isFinished() is False:
print("All possible solutions without the Queen being in danger have been found")
print("The total number of possible solutions for",n,"Queens is:",len(results))
print("The total number of recursive calls to solve the problem of",n,"Queens is:",recursionCounter)
If I am not doing this correctly would someone be able to show me how? The current result I get for 8-queens is 1964

Resetting Collatz Counter on Each New Recursion

I made a code that measure number of steps it takes to return to 1 in a Collatz Conjecture. Here Is my code
counter = 0
def collatz(n):
global counter
counter += 1
if n <= 0 :
return "Invalid Number"
elif n == 1 :
return counter
elif n % 2 == 1 :
n = 3*n + 1
return collatz(n)
elif n % 2 == 0 :
n = n/2
return collatz(n)
print(collatz(9921615699))
print(collatz(9921615699))
I expect the Last two print commands to print 311 and 311. Instead, they print 311 and 622. I guess that was easy enough to see in the code what is wrong. How can i fix that? how can counter reset each time a command is completed and not when the function is run.
Instead of using global variable you could make the counter a parameter with default value:
def collatz(n, counter=0):
counter += 1
if n <= 0 :
return "Invalid Number"
elif n == 1 :
return counter
elif n % 2 == 1 :
n = 3*n + 1
return collatz(n, counter)
elif n % 2 == 0 :
n = n/2
return collatz(n, counter)
You're using recursion, so just use it properly:
def collatz(n, counter=0):
counter += 1
if n <= 0 :
return "Invalid Number"
elif n == 1 :
return counter
elif n % 2 == 1 :
n = 3*n + 1
return collatz(n, counter)
elif n % 2 == 0 :
n = n/2
return collatz(n, counter)
print(collatz(9921615699))
print(collatz(9921615699))
You were using global in your original version which is usually not what you want to do. You got to see first-hand why.
You could have reset the counter, e.g.
result = counter
counter = 0
return result
But that's pretty nasty, let's not do that. When you're implementing a recursive algorithm there's probably no good reason to have a global variable.

Maximum recursion depth exceeded in python for calculates the exponential

I have tried this version is correct:
def recurPowerNew(base, exp):
if exp == 0:
return 1
elif exp > 0 and exp % 2 == 1:
return base * recurPowerNew(base, exp-1)
elif exp > 0 and exp % 2 == 0:
return recurPowerNew(base * base, exp / 2)
while this version appears error:
def recurPowerNew(base, exp):
if exp == 0:
return 1
elif exp > 0 and exp % 2 == 1:
return base * recurPowerNew(base, exp-1)
elif exp > 0 and exp % 2 == 0:
return recurPowerNew(recurPowerNew(base, 2), exp / 2)
The difference is the last elif.
Can anyone figure out why?
On the last elif in the second version, you are calling your recursive function with itself as an argument. This is leading to recursion within recursion, which will run so many times that it exceeds the maximum recursion depth.

Categories

Resources