2017-08-31 83 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)