I've created a program where the output prints as, for example, 36, 6, 2, 1
.
I want it to print [36, 6, 2, 1]
.
This is my current code:
def collatz(n):
print(n, end = ', ')
while (n > 1):
if n % 2 == 0:
n=int(n**0.5)
else:
n=int(n**1.5)
if n == 1:
print(1)
else:
print(n, end = ', ')
I am not sure what to edit at this point as I've tried a lot messing with the print statements and I have seen in other posts where print(*n, ...)
was used but I get the error:
TypeError: print() argument after * must be a sequence, not int.
Which I get why it wouldn't work so I'm lost at this point.
The best way would be to create a list and append the values of n
to the list. In this way you can take the advantage of the builtin functionality of str(list)
which automatically adds [
and ]
to the end while printing.
A sample code can be
def collatz(n):
templist = [n]
while (n > 1):
if n % 2 == 0:
n=int(n**0.5)
else:
n=int(n**1.5)
if n == 1:
templist.append(1)
else:
templist.append(n)
print(templist)
Now when you run collatz(36)
you get [36, 6, 2, 1]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments