简体   繁体   中英

Number of steps to reduce to zero

Hello I have this steps problem and I am trying to see where I can improve my code to get the number of steps it takes to reduce any integer down to zero. I'm sure you all know the process, but just for clarification...if the number is even, we divide by 2, adding a step, and if the number is odd we subtract, adding another step...Can someone let me know what im missing?

def steps_to_zero(int):
    step = 0
    while (abs(int) > 0):
        if int % 2 == 0:
            int / 2
        else:
            int - 1
        step += 1
    return step

When you write a line such as x / 2 , Python will calculate the result of that division. However, you aren't saving the result of the division anywhere!

You need to do the same thing you're doing with step += 1 , which is equivalent to step = step + 1 :

def steps_to_zero(int):
    step = 0
    while (abs(int) > 0):
        if int % 2 == 0:
            int /= 2 # Same as int = int / 2
        else:
            int -= 1 # Same as int = int - 1
        step += 1 # Same as step = step + 1
    return step

If you don't do this, the variable int never changes values. It keeps the value it had at the start. And as a result, the while-loop keeps running forever, since abs(int) > 0 stays the case forever.

Another note, int is a built-in type and has special meaning. It is heavily recommended to not use it, or any other such type, as names for your variables. Consider writing integer instead:

def steps_to_zero(integer):
    step = 0
    while (abs(integer) > 0):
        if integer % 2 == 0:
            integer /= 2 # Same as integer = integer / 2
        else:
            integer -= 1 # Same as integer = integer - 1
        step += 1 # Same as step = step + 1
    return step

You're not updating your counter int . You need to store it back to itself, or you'll be looping forever.

def steps_to_zero(int):
    step = 0
    while (abs(int) > 0):
        if int % 2 == 0:
            int = int / 2
        else:
            int = int - 1
        step += 1
    return step

Should solve it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM