def collatz_dict ( n, C ): ## collatz_dict() adds the Collatz sequence for n to an existing dict. # from collatz import collatz if ( not C ): C = {} while ( not ( n in C ) ): Tn = collatz ( n ) C[n] = Tn n = Tn # # Doing this extra step makes the dictionary appear sorted in the # first item. # C = dict ( sorted ( C.items(), key = lambda item : item[0] ) ) return C def collatz_dict_test ( ): C = {} n = 341 C = collatz_dict ( n, C ) print ( ' Start with n = 341' ) print ( C ) n = 84 C = collatz_dict ( n, C ) print ( '' ) print ( ' Add n = 84' ) print ( C ) return if ( __name__ == "__main__" ): collatz_dict_test ( )