Amr4AOT
Amr4AOT

Reputation: 53

Recursion depth exceeded in comparison

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

Upvotes: 0

Views: 104

Answers (1)

sid-m
sid-m

Reputation: 1554

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)

Upvotes: 1

Related Questions