GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — python/collatz_problem at master · utubun/python Expand file tree/ Copy pathcollatz_problemMore file actions 40 lines (36 loc) · 2.03 KB / Copy pathcollatz_problemFile metadata and controls40 lines (36 loc) · 2.03 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 def map_builder(chain, map_dct): ''' (list, dictionary) -> dictionary Precondition: chain[0] is a number equall to existing key in dictionary. This function takes arguments chain (list of numbers) and map_dct (dictionary {num:num}) and creates new entries in dictionary with keys equal to numbers from chain[1:] and values assigned to sum of preexisted key's value and 1, 2,...n according to the position of the element in chain. ''' for (i, j) in zip(chain[1:], range(1,len(chain))): map_dct[i] = map_dct[chain[0]] + j return map_dct def hailstone_seq(n): ''' (int) -> dictionary For each element from range(2, n+1) this function create dictionary with keys corresponding to the element and value corresponding to the length of the hailstone sequence generated by this number. All the numbers which appears in hailstone sequence during calculations are excluded from the input set n {[2...n]} (we already know length for every such chain). ''' map_dct = {1:1} n = set(range(2, n+1)) chain = [n.pop()] while len(n) >= 0: if chain[0] in map_dct: # Found number in map_dct? map_dct = map_builder(chain, map_dct) # Assign length values for rest of numbers n -= set(chain) # Delete all numbers from the input set if len(n) == 0: # Stop if the sat is empty break chain = [n.pop()] # Take the element from input set continue # Why did I write it here?! Aliens! else: chain.insert(0, chain[0]%2 == 0 and chain[0]//2 or int(chain[0]*3+1)) #Find next element golden_key = max(map_dct, key = map_dct.get) # Find key with max value print("It's a nummber " + str(golden_key) + # Say how do you love her! "\nChain length is " + str(map_dct[golden_key])) |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |