collatz.py


Below is the syntax highlighted version of collatz.py from §2.3 Recursion.


#-----------------------------------------------------------------------
# collatz.py
#-----------------------------------------------------------------------

import stdio
import sys

#-----------------------------------------------------------------------

# Write to standard output the collatz sequence of n.

def collatz(n):
    stdio.write(str(n) + ' ')
    if n == 1:
        return
    elif n % 2 == 0:
        collatz(n // 2)
    else:
        collatz(3*n + 1)

#-----------------------------------------------------------------------

# Accept integer command-line argument n. Write to standard output
# the collatz sequence of n.

def main():
    n = int(sys.argv[1])
    collatz(n)
    stdio.writeln()

if __name__ == '__main__':
    main()
    
    
#-----------------------------------------------------------------------
  
# python collatz.py 7
# 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 


Copyright © 2000–2015, Robert Sedgewick, Kevin Wayne, and Robert Dondero.
Last updated: Fri Oct 20 20:45:16 EDT 2017.