Home > OS >  How do I make the output of the collatz look like a list and labled?
How do I make the output of the collatz look like a list and labled?

Time:03-04

#I want this code to output....    
def Collatz(n): 
 
    while n != 1: 
        print(n, end = ', ') 
 
        if n & 1: 
            n = 3 * n   1
 
        else: 
            n = n // 2
    print(n) 
 
Collatz(777) 

I want it to look like:

  1. 777
  2. 2332
  3. 1166
  4. 583

CodePudding user response:

You can use an extra variable, here i, to print lables.

Also, I removed end parameter so that it print line by line. In addition, I used f-string for printing format. For more detail, please see https://realpython.com/python-f-strings/

def Collatz(n):
    i = 1 # for lables
    while n != 1:
        print(f'{i}. {n}')
        if n & 1:
            n = 3 * n   1
        else:
            n = n // 2
        i =1

Collatz(777)

#1. 777
#2. 2332
#3. 1166
#4. 583
#5. 1750
#6. 875
#7. 2626
#8. 1313
#...
  • Related