Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import pickle
- import os
- hailrecord = {1:0, 2:1}
- def is_int(s):
- try:
- int(s)
- return True
- except ValueError:
- return False
- def hailstone(n, prt, opt):
- if n < 1:
- print "Pick a positive number, dummy."
- return -1
- elif not is_int(n):
- print "That's not a number, dummy."
- return -1
- else:
- n = int(n)
- steps = 0
- while n <> 1:
- if opt:
- if n in hailrecord:
- return hailrecord[n] + steps
- if prt: print n,
- steps += 1
- if n % 2 == 0:
- n = n / 2
- else:
- n = n * 3 + 1
- if prt: print n
- return steps
- if __name__ == '__main__':
- if (len(sys.argv) < 2 or len(sys.argv) > 3):
- print "You done goofed!"
- sys.exit(1)
- else:
- if sys.argv[1] == "find":
- goal = int(sys.argv[2])
- if not is_int(goal):
- print "That goal's not a number, dummy."
- sys.exit(1)
- else:
- if not os.path.exists("hail.pck"):
- with open("hail.pck", "w") as file:
- pickle.dump(hailrecord, file)
- print "Created new dictionary."
- else:
- size = os.path.getsize("hail.pck")
- print "Loading dictionary:",
- print "%.2f" % (size / 1048576.0), "MiB"
- with open("hail.pck", "r") as file:
- hailrecord = pickle.load(file)
- print "Dictionary loaded."
- num = 2
- s = 0
- while s < goal:
- num += 1
- if num in hailrecord:
- temp = hailrecord[num]
- else:
- temp = hailstone(num, False, True)
- hailrecord[num] = temp
- if temp > 0 and temp > s:
- s = temp
- elif temp < 0:
- sys.exit(2)
- hailstone(num, True, False)
- print num, "has a hailstone sequence of length", s
- print "Saving dictionary:",
- print "%.3f" % (len(hailrecord) / 1000.0), "K entries"
- with open("hail.pck", "w") as file:
- pickle.dump(hailrecord, file)
- print "Dictionary saved."
- else:
- num = sys.argv[1]
- hailstone(num, True, False)
Advertisement
Add Comment
Please, Sign In to add comment