In [1]:
for _ in xrange(10):
print "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.
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 [7]:
print repr(x1)
print repr(x5)
A good review of Python operators can be found here: http://www.programiz.com/python-programming/operators
The wiki reviewing bitwise operations here: https://en.wikipedia.org/wiki/Bitwise_operation
OR
http://www.math.grin.edu/~rebelsky/Courses/152/97F/Readings/student-binary
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]:
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)
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)
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]:
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'
In [ ]:
In [ ]: