school/cs142/lab04/loops.py
2016-04-06 20:45:34 -07:00

54 lines
1.6 KiB
Python

import random
import time
def get_numbers(pow2, compliment):
numbers = []
constant = compliment
for i in (0, 1):
for j in (0, 1):
for k in (0, 1):
for l in (0, 1):
if pow2 == 0:
cur_digits = (i, j, k, l, constant)
if pow2 == 1:
cur_digits = (i, j, k, constant, l)
if pow2 == 2:
cur_digits = (i, j, constant, k, l)
if pow2 == 3:
cur_digits = (i, constant, j, k, l)
if pow2 == 4:
cur_digits = (constant, i, j, k, l)
numbers.append(cur_digits)
return numbers
print "example of how to use randomness to determine compliment"
a_few_tries = xrange(3)
for i in a_few_tries:
compliment = random.randint(0, 3026) % 2
for i in get_numbers(pow2=0, compliment=compliment):
print i
print "for loop to print out all numbers from 2^0 to 2^5"
for i in (0, 1):
for j in (0, 1):
for k in (0, 1):
for l in (0, 1):
for m in (0, 1):
for n in (0, 1):
print i, j, k, l, m
print "example function to convert a string in binary to integers: (see source)"
def bin2int(s):
total = 0
for i in xrange(len(s)):
if s[i] == '1':
total += 2**(len(s) - i - 1)
return total
print "here I test out the bin2int func defined above:"
test_cases = ('1010', '1011', '0100', '1000', '0111')
for test in test_cases:
print test, bin2int(test), int(test, 2)