def divisors(n): return [div for div in range(1,n) if n % div == 0] from math import ceil def divisors2(n): divs = [1] for m in range(2, ceil(n ** 0.5)):#1 and n**0.5 will be handled separately. why? if n % m == 0: divs += [m, n // m] if n % n ** 0.5 == 0: divs += [int(n ** 0.5)] return divs print(divisors(36)) print(sorted(divisors2(36))) import time help(time.clock) print(time.clock()) print(time.clock()) n = 1234567890 tic = time.clock() divisors(n) toc = time.clock() print("divisors: ",(toc-tic)) tic = time.clock() divisors2(n) toc = time.clock() print("divisors2:",(toc-tic)) x_bin = "11110" x_bin = x_bin[::-1] # reverse it so that LSB is on the left for the iteration x_dec = 0 for k in range(len(x_bin)): bit = int(x_bin[k]) print(k,bit) x_dec += bit * 2**k print(x_dec) x_dec = 42 x_bin = '' while x_dec > 0: bit = x_dec % 2 x_bin = str(bit) + x_bin x_dec = x_dec // 2 print(x_bin) bin(42) int('101010',2) hex(42) int('2a',16) def convert_base(n,b): '''convert_base(integer, integer) -> string Return the textual representation of n (decimal) in base 2 <= b <= 10. ''' result = '' while n > 0: digit = n % b n = n // b print(digit) result = str(digit) + result return result convert_base(23,12) 1+12+12**2 convert_base(10,16) def convert_base(n,b): '''convert_base(integer, integer) -> string Return the textual representation of n (decimal) in base 2 <= b <= 10. ''' assert 2 <= b <= 36 if n == 0: result = '0' elif n < 0: result = '-' else: result = '' n = abs(n) while n > 0: digit = n % b n = n // b # str(digit) only works for b <= 10 result = '0123456789abcdefghijklmnopqrstuvwxyz'[digit] + result return result convert_base(23,12) convert_base(10,6) convert_base(10,16) convert_base(40,32) convert_base(0,5) convert_base(100,55)