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)
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 [ ]: