Commits

Janto Dreijer committed 9c0820b

add bin() and base()

Comments (0)

Files changed (1)

 __all__ = []
 
 import os
-from math import exp, atan, atan2, pi
+from math import exp, atan, atan2, pi, log
 from itertools import repeat, count, imap
 from random import random
 import types
 import copy
 import sys
 from time import clock
+import string
 
 try:
 	import psyco
 # maths
 # -------------------------------------------------------------
 
+__all__.append("base")
+def base(x, base):
+	"""
+		>>> base(0, 2)
+		'0'
+		>>> base(1, 2)
+		'1'
+		>>> n = 10203050364
+		>>> base(n, 2) == bin(n)
+		True
+		>>> int(base(n, 16), 16) == n
+		True
+	"""
+	base_values = dict(zip(range(base), string.digits+string.uppercase))
+	digits = []
+	while 1:
+		x, digit = divmod(x, base)
+		digits.append(base_values[digit])
+		if x == 0:
+			break
+	return "".join(map(str, reversed(digits)))
+
+__all__.append("bin")
+def bin(x):
+	"""
+		>>> bin(0)
+		'0'
+		>>> bin(1)
+		'1'
+		>>> bin(2)
+		'10'
+		>>> bin(10)
+		'1010'
+		>>> x = 10000101010323
+		>>> int(bin(x), 2) == x
+		True
+	"""
+	digits = []
+	while 1:
+		digits.append(x & 0x01)
+		x >>= 1
+		if x == 0:
+			break
+	return "".join(map(str, reversed(digits)))
+
 __all__.append("angle")
 def angle(complex):
 	"""Returns angle where 2*pi > angle >=0