简体   繁体   English

减少到零的步数

[英]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.你好,我有这个步骤问题,我想看看我可以在哪里改进我的代码,以获得将任何 integer 减少到零所需的步骤数。 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?我相信你们都知道这个过程,但只是为了澄清......如果数字是偶数,我们除以2,加一个步骤,如果数字是奇数我们减去,再加一个步骤......有人可以让我知道我错过了什么吗?

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.当您编写诸如x / 2之类的行时, Python 将计算该除法的结果。 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 :您需要执行与step += 1相同的操作,这相当于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.如果你不这样做,变量int永远不会改变值。 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.结果,while 循环将永远运行,因为abs(int) > 0永远保持这种情况。

Another note, int is a built-in type and has special meaning.另请注意, int是内置类型,具有特殊含义。 It is heavily recommended to not use it, or any other such type, as names for your variables.强烈建议不要使用它或任何其他此类类型作为变量的名称。 Consider writing integer instead:考虑改写integer

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 .您没有更新您的计数器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.应该解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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