Sam
Sam

Reputation: 11

Python Recursive Code (Beginner)

I'm currently trying to create a code that calculates how long a spaceship will take to travel a certain distance, every minute it will jump half the remaining distance. If there is a distance of less than 1 meter left, it will only take one more minute.

def space_time(d,t=0):

    if d <= 1:
        print("- It takes 1 minute to travel", d, "meters")
    elif d > 1:
        t = t + 1
        return space_time(d / 2, t)
    else:
        t = t + 1
        print("- ", t, "minutes to travel", d, "meters")


(space_time(10))

Output:

- It takes 1 minute to travel 0.625 meters

Process finished with exit code 0

I can see that my problem is the t = t + 1. My idea for this was every time the function is repeated it would add 1 to t which would signify 1 minute. But currently its not working. Any help would be greatly appreciated.

Upvotes: 0

Views: 91

Answers (2)

Kewl
Kewl

Reputation: 3417

There's a couple of problems here. For one, your 'elif' statement is checking the same condition as your if! I think you want 'greater than'.

Second, you are always setting t to 0 at the beginning, and not passing that back with the recursive loop. The original d is also not passed back.

Finally, I'm not sure what the else statement is supposed to be catching.

EDIT: If 0 < d < 1, then it takes one more minute. The last else captures this now.

def space_time(d_0,d=None,t=0):
    if d is None:
        d = d_0
    if d <= 0:
        print("- It takes", t, "minutes to travel" , d_0, "meters")

    elif d > 1:
        t = t + 1
        return space_time(d_0,d/2,t)

    else:
        print("- It takes", t + 1, "minutes to travel" , d_0, "meters")

(space_time(10))

Output:

- It takes 5 minutes to travel 10 meters

Upvotes: 1

JonasAnon
JonasAnon

Reputation: 195

A problem is that it is impossible for the "elif d <= 1:" statement to get called, because the condition is exactly the same as the "if" condition above, which means this code will never be runned. You probably should change the "elif" to "if" if you want them both to be executed, or even better, merge them together

    if d <= 1:
    print("- It takes 1 minute to travel" , d, "meters")

    elif d <= 1:
    t = t + 1
    return space_time(d/2)

Upvotes: 1

Related Questions