2017-08-31 172 views
5

我目前有麻烦“自动无聊的东西”完成这个挑战在Collat​​z功能:实现使用Python

Image of the challenge

我的代码是:

def collatz(number): 
    global seqNum 
    if (seqNum % 2 == 0): 
     return seqNum // 2 
    elif (seqNum % 2 == 1): 
     return 3 * seqNum + 1 


print('What number would you like to use?') 
seqNum = input() 
number = int(seqNum) 
i = number 

while i > 1: 
    collatz(seqNum) 
    print(number) 

而且我得到这个错误:

"Traceback (most recent call last): 
    File "C:/Users/Administrative/AppData/Local/Programs/Python/Python36-32/collatzSeq.py", line 15, in <module> 
    collatz(seqNum) 
    File "C:/Users/Administrative/AppData/Local/Programs/Python/Python36-32/collatzSeq.py", line 3, in collatz 
    if (seqNum % 2 == 0): 
TypeError: not all arguments converted during string formatting" 

我知道我在做SOMETHIN G写错了我的代码,但我不明白它到底是什么。任何和所有的帮助,非常感谢!

我也是使用python 3

+0

你不使用你的说法。我想你想使用数字,而不是SEQNUM。而这不起作用,因为输入返回一个字符串,这不是一个数字。此外,你并不需要一个'elif',你可以使用'else',因为唯一的其他可能的值是1. – jszakmeister

+0

^并且在那里摆脱全局声明,这不是帮助 – FreshPow

回答

4
  1. 你正在做算术的字符串,而不是一个整数。

  2. 有没有必要有一个global变量。将一个参数传递给一个函数,并让它相应地返回一个值。


def collatz(number): 
    if (number % 2 == 0): 
     return number // 2 

    elif (number % 2 == 1): 
     return 3 * number + 1 

print('What number would you like to use?') 

i = int(input()) 
while i > 1:  
    i = collatz(i) 
    print(i) 
+0

另外我有一个关于这个问题:所以你写了“while True”,因为我调用collat​​z()函数并且该函数没有可能的False值?我也可以在以后使用任何表情吗?所以如果我想要,我可以写假,1 <2等?对不起,只是试图帮助自己了解这个 – Xert01998

+0

愚蠢的问题我跑了12并收到完整的序列?我很迷惑 – Xert01998

1

seqNum是一个字符串。

>>> "3" % 2 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: not all arguments converted during string formatting 
>>> 
+0

...解决方法是使用'number'。 –

+0

我认为这不符合该问题的真正答案。 –

+1

@cᴏʟᴅsᴘᴇᴇᴅ好吧,从纯粹的技术角度来讲,这个_does_回答了这个问题。这将解决OP发布的错误。然而,有人可能会说这是一个次优的答案。 –

0

看来,你应该通过i给你的函数,而不是seqNum

并在您的函数中删除所有对seqNum的引用,并使用number来代替。

3

这里有几个问题,但在导致你的例外是,您在功能,这是input()返回使用seqNum。并且input()返回一个字符串(至少在Python 3上)。 strings the %是“格式化操作符”,它也解释了异常消息,它讨论了“字符串格式化”。

如下你可以把它写(使用number代替seqNum):

def collatz(number): 
    # you pass the number to the function and you return, so no need for global   
    if number % 2 == 0:  # python doesn't need parenthesis for "if"s 
     return number // 2 
    else:      # it can only be even OR odd so no need to calculate the modulo again 
     return 3 * number + 1 

# You can put the question as argument for "input" instead of printing it 
seqNum = input('What number would you like to use?') 
number = int(seqNum) 

while number > 1 : 
    number = collatz(number) # assign the result of the function to "number" 
    print(number)