Implementing the collatz function using Python

守給你的承諾、 提交于 2019-11-28 12:26:40
  1. You're doing arithmetic on a string, not an integer.

  2. There's no need to have a global variable. Pass an argument to a function, and have it return a value accordingly.


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)

There are several problems here, but the one causing your Exception is that you use the seqNum in the function, which is what input() returned. And input() returns a string (at least on Python 3). And for strings the % is the "formatting operator" which also explains the exception message, which talked about "string formatting".

You could write it as follows (using number instead of 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)
Bobby Durrett

seqNum is a string.

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

It seems that you should pass i to your function instead of seqNum.

And in your function remove all references to seqNum and use number instead.

Hi I'm new to coding and also looking at this exercise. If it's helpful here is the approach I took using 1 x function + 2 x while loops. I also notice the program didn't handle a zero value well as an input:

# This program runs the Collatz sequence - Automate book, Chapter 3 practice project
# It includes the 'Input Validaton' additional exercise
# It also inlcudes a further test for zero value input as this makes collatz non-terminating

def collatz(number):
    #test even
    if number % 2 == 0:
        return number // 2
    #or implicit it is odd
    else:
        return 3 * number + 1

# Get the user input and validate - loop continues until non-zero integer entered
while True:
    try:
        print('Enter a non-zero number')
        number = int(input())
        if number == 0:
            continue
        else:
            break
    except ValueError:
        print('Error: You must enter and integer')

# Iterate over the input number until it == 1              
while number != 1:
    # return value assigned to global var
    number = collatz(number) 
    # output the result of collatz to screen
    print(number)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!