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
Advertisement
Answer
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