Random notes while re-studying CS and DS while job hunting.

xrange vs range looping

For long for loops with no need to track iteration use:


In [1]:
for _ in xrange(10):
    print "Do something"


Do something
Do something
Do something
Do something
Do something
Do something
Do something
Do something
Do something
Do something

This will loop through 10 times, but the iteration variable won't be unused as it was never assigned. Also, xrange returns a type of iterator, whereas range returns a full list that can take a lot of memory for large loops.

Automating variable names

To assign a variable name and value in a loop fasion, use vars()[variable name as a string] = variable value. Such as:


In [5]:
for i in range(1,10):
    vars()['x'+str(i)] = i

You can see the variables in memory with:


In [6]:
print repr(dir())


['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__name__', '_dh', '_i', '_i1', '_i2', '_i3', '_i4', '_i5', '_i6', '_ih', '_ii', '_iii', '_oh', '_sh', 'exit', 'get_ipython', 'i', 'quit', 'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9']

In [7]:
print repr(x1)
print repr(x5)


1
5

Binary numbers and Python operators

A good review of Python operators can be found here

The wiki reviewing bitwise operations here OR here

Note that binary numbers follow:

2^4| 2^3| 2^2| 2^1| 2^0

1 0 -> 2+0 = 2

1 1 1 -> 4+2+1 = 7

1 0 1 0 1 -> 16+0+4+0+1 = 21

1 1 1 1 0 -> 16+8+4+2+0 = 30

Convert numbers from base 10 to binary with bin()


In [8]:
bin(21)[2:]


Out[8]:
'10101'

Ensuring two binary numbers are the same length


In [10]:
a = 123
b = 234
a, b = bin(a)[2:], bin(b)[2:]
print "Before evening their lengths:\n{}\n{}".format(a,b)
diff = len(a)-len(b)
if diff > 0:
    b = '0' * diff + b
elif diff < 0:
    a = '0' * abs(diff) + a
print "After evening their lengths:\n{}\n{}".format(a,b)


Before evening their lengths:
1111011
11101010
After evening their lengths:
01111011
11101010

For bitwise or:


In [12]:
s = ''
for i in range(len(a)):
    s += str(int(a[i]) | int(b[i]))
print "{}\n{}\n{}\n{}".format(a, b, '-'*len(a), s)


01111011
11101010
--------
11111011

bitwise or is |, xor is ^, and is &, complement (switch 0's to 1's, and 1's to 0's) is ~, binary shift left (move binary number two digits to left by adding zeros to its right) is <<, right >>

Convert the resulting binary number to base 10:


In [13]:
sum(map(lambda x: 2**x[0] if int(x[1]) else 0, enumerate(reversed(s))))


Out[13]:
251

Building a 'stack' in Python


In [14]:
class Stack:
     def __init__(self):
         self.items = []

     def isEmpty(self):
         return self.items == []

     def push(self, item):
         self.items.append(item)

     def pop(self):
         return self.items.pop()

     def peek(self):
         return self.items[len(self.items)-1]

     def size(self):
         return len(self.items)

In [20]:
s=Stack()

print repr(s.isEmpty())+'\n'
s.push(4)
s.push('dog')
print repr(s.peek())+'\n'
s.push(True)
print repr(s.size())+'\n'
print repr(s.isEmpty())+'\n'
s.push(8.4)
print repr(s.pop())+'\n'
print repr(s.pop())+'\n'
print repr(s.size())+'\n'


True

'dog'

3

False

8.4

True

2


In [ ]:


In [ ]: