# syntactic sugar for easily counting data
# https://docs.python.org/2/library/collections.html#collections.Counter
from collections import Counter
APPLE = 'apple'
BANANA = 'banana'
c = Counter([APPLE, BANANA])
print c # Counter({'apple': 1, 'banana': 1})
c.clear()
print c # Counter()
print c.get(APPLE) # None
# print sum(c.values())
c[APPLE] += 1
c[APPLE] += 1
print c.get(APPLE) # 1
c[BANANA] += 1
print c # Counter({'apple': 2, 'banana': 1})
sorted_list = c.most_common()
if sorted_list:
print 'max:', sorted_list.pop(0) # max: ('apple', 2)
- - -
for i in xrange( 10 ): # creates an iterator counting from 0 to 10 (more memory efficient than creating the whole list in memory)
x = 0.1 * i
print x, # trailing comma removes the default print newline
for i in [ 2 , 3 , 6 , 14 ]: # has an index variable i, uses the values from the list, ends with a colon
print i , "=" , hex(i)
range( 7, 1000, 7 ) # returns an actual list of multiples of 7 under 1000
for i in xrange( 10, -1, -1): # xrange cannot go beyond values of C integer, so for very large use range()
print i # counts down from 10 to 0
for i in reversed( xrange( 10 ) ): # reversed changes the order of the xrange iterator
print i # counts down from 9 to 0
print "\n\nwhile if i==8 break" \
" \ means code line print continued"
i = 5
# infinite loop
while 1: # usually better as while True:
print i
i += 1
if i == 8:
print i
break
print "range( 2 , 5 ) start stop before with if else is elif"
for i in range( 2 , 5 ):
if i ==2:
print "i == 2"
elif i==3:
print "elif i==" , i , "commas"
else:
print i
import math
print "\n\nmath.sqrt( 88 ) = " , math.sqrt( 88 )
fastconcat = ''.join( ["fast" , "string" , "list" , "concat"] ) # takes a list and joins it with no input
print fastconcat
# outputs [x, 3, b] , in python 3 the map uses generator so it's performant =)
mylist = [ 'x', 3, 'b' ]
print '[%s]' % ', '.join( map( str, mylist ) ) # default str function is applied to all elements in the list
# Using a generator is the minimal memory footprint and allows access to the index and the value
def reverse_enum(L):
for index in reversed(xrange(len(L))):
yield index, L[index]
L = ['foo', 'bar', 'bas']
for index, item in reverse_enum(L):
print index, item
counter = 0
while( counter < 50 ):
sys.stdout.write( '.' )
counter = counter + 1
if counter % 10 == 0:
print '\n'