# collatzify: int -> int # transform a number via the rules of the collatz sequence def collatzify(n): return n/2 if n % 2 == 0 else 3*n + 1 # collatzSequence: int -> [int] # generate the collatz sequence starting at the given number def collatzSequence(number): seqSoFar = [number] while number > 1: number = collatzify(number) seqSoFar.append(number) return seqSoFar # frequency: int, [int] -> int # count the number of occurences of a number in a list def frequency(soughtNumber, numberList): counter = 0 for x in numberList: if x == soughtNumber: counter = counter + 1 return counter # histogram: [int] -> [int] # compute the histogram of a given list def histogram(numberList): # return a list of frequency counts from 0 to max(numberList) highest = max(numberList) current = 0 theHistogram = [] while current <= highest: theHistogram.append(frequency(current, numberList)) current = current + 1 return theHistogram # collatzHistogram: int -> [int] # compute a histogram of the lengths of all collatz sequences # starting at 1 and going to the input number (inclusive). def collatzHistogram(numberOfNumbers): collatzLengths = [] for n in range(1, numberOfNumbers+1): collatzLengths.append(len(collatzSequence(n))) return histogram(collatzLengths) # printHist: [int] -> None # print out a histogram to the terminal def printHist(aHistogram): theMax = max(aHistogram) for i, count in enumerate(aHistogram): print ("%s: " % i) + "#" * int(round(100.0 * count / theMax)) ''' These tests won't run in Pythonfiddle, but here they are anyway if __name__ == "__main__": from unittest import test test(8, collatzify(16)) test(14, collatzify(28)) test(10, collatzify(3)) test([1], collatzSequence(1)) test([5,16,8,4,2,1], collatzSequence(5)) test([7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1], collatzSequence(7)) test(0, frequency(5,[1,2,3,4])) test(1, frequency(3,[1,2,3,4])) test(5, frequency(6,[1,6,6,6,6,7,6])) test([1,1,1,1,1,1,1,1,1,1], histogram(range(10))) test([1,2,2,0,1,0,1,3,1,1,0,0,0,0,0,0,0,0,0,1], histogram([6,4,2,8,7,7,9,0,1,1,2,7,19])) test([0]*25 + [1], histogram([25])) test([0,1,1], collatzHistogram(2)) test([0,1,1,1,0,0,1,0,1], collatzHistogram(5)) test([0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1], collatzHistogram(10)) '''
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question