Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing the collatz function using Python

I am currently having trouble completing this challenge in "Automate the boring stuff":

Image of the challenge

My code is:

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)

And I am getting this error:

"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"

I know I am doing SOMETHING wrong with how I wrote my code but I don't understand what it is exactly. Any and all help is greatly appreciated!

Also I am using python 3.

like image 301
Xert01998 Avatar asked Aug 31 '17 21:08

Xert01998


1 Answers

  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)
like image 69
cs95 Avatar answered Sep 20 '22 22:09

cs95