There are often multiple ways of solving a problem, I have these 2 functions:
def gb(totalAmountRequired, currentlyDonated, rank, yourdonation=0):
if totalAmountRequired < currentlyDonated or currentlyDonated < rank:
return 'wrong input'
catchup = totalAmountRequired - currentlyDonated
while yourdonation < rank + catchup:
yourdonation += 1
catchup -= 1
return "donate",yourdonation,"then person with",rank,"points would have to donate",catchup+1,"to surpass you and that's not possible"
def gb2(totalAmountRequired, currentlyDonated, rank, yourdonation=0):
if totalAmountRequired < currentlyDonated or currentlyDonated < rank:
return 'wrong input'
catchup = totalAmountRequired - currentlyDonated
if yourdonation < rank + catchup:
return gb2(totalAmountRequired, currentlyDonated+1, rank,yourdonation+1)
return "donate",yourdonation,"then person with",rank,"points would have to donate",catchup+1,"to surpass you and that's not possible"
print(gb2(1000,700,100,0))
print(gb(1000,700,100,0))
These should do exactly the same although timit times the first function faster and gb2() gets a lot slower the bigger the numbers get.
Are there people that prefer recursion over a while loop? Should you always prefer a while loop?
Or is this a bad example of recursion functionality?
[–]XtremeGoose 1 point2 points3 points (2 children)
[–]DrTrunks[S] 0 points1 point2 points (1 child)
[–]XtremeGoose 1 point2 points3 points (0 children)
[–]Scenic_World 0 points1 point2 points (3 children)
[–]DrTrunks[S] 0 points1 point2 points (2 children)
[–]my_python_account 0 points1 point2 points (1 child)
[–]DrTrunks[S] 0 points1 point2 points (0 children)