I am fresh in learning Python and wanted to try something after watching a video on YouTube by Veritasium titled "The Simplest Math Problem No One Can Solve"
essentially:
If x is even, divide x by 2
If x is odd, times 3 then plus 1
keep repeating until x = 1
So I wrote this piece of code to get the list of results for a range of numbers
val = int(input("Enter a Number"))
def threexplus1(x, count = 1, mylist=[]):
if x == 1:
mylist.append(x)
return count, mylist
elif x%2==0:
mylist.append(x)
return threexplus1(int(x/2), count+1)
else:
mylist.append(x)
return threexplus1(int(x*3+1), count+1)
for x in range (1,val+1):
print (x)
print (threexplus1(x))
input
4
The output I want is not the output I hope for
The current Output:
Enter a Number 4
1
(1, [1])
2
(2, [1, 2, 1])
3
(8, [1, 2, 1, 3, 10, 5, 16, 8, 4, 2, 1])
4
(3, [1, 2, 1, 3, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1])
The output I wanted:
Enter a Number 4
1
(1, [1])
2
(2, [2, 1])
3
(8, [3, 10, 5, 16, 8, 4, 2, 1])
4
(3, [4, 2, 1])
I am wondering why mylist doesn't refresh/clear itself when it is called recursively?