Skip to content

Instantly share code, notes, and snippets.

View poros's full-sized avatar

Antonio Uccio Verardi poros

View GitHub Profile
@poros
poros / in_find_string.py
Created October 4, 2015 13:45
Find a substring is in a string
'lmnop' in 'abcdefghijklmnopqrstuvwxyz'
index = 'python'.find('on') # 4
@poros
poros / try_except_else_finally.py
Created October 4, 2015 14:04
Complete exception handling
try:
f = open(filename, 'r')
except IOError as e:
print 'cannot open ', filename
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except:
log.exception("Unexpected error")
# print "Unexpected error:", sys.exc_info()[0]
raise
else:
@poros
poros / comprehension.py
Created October 4, 2015 14:09
List/dict/set comprehensions
[x**2 for x in (2,4,6)]
{x: x**2 for x in (2, 4, 6)}
{x for x in 'abracadabra' if x not in 'abc'}
@poros
poros / nested_list_comprehensions.py
Created October 4, 2015 14:47
Nested list comprehensions
matrix = [[1,2,3]] * 4
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
# FLATTEN THE MATRIX
flatten = []
for row in matrix:
for i in range(3):
flatten.append(row[i])
[row[i] for row in matrix for i in range(3)]
@poros
poros / enumerate.py
Created October 4, 2015 14:55
Loop over a collection and indexes
for i in range(len(colors)):
print i, colors[i]
for i, colors in enumerate(colors):
print i, colors
# retuns enumerate object, not a list
@poros
poros / zip.py
Created October 4, 2015 15:02
Loop over two collections
n = min(len(names), len(colors))
for i in range(n):
print names[i], colors[i]
for names, color in zip(names, colors):
print name, color
#collections.izip is the iterator version
@poros
poros / defaultdict.py
Created October 4, 2015 15:46
Grouping with dictionaries
d = {}
for name in names:
key = len(name)
if key not in d:
d[key] = []
d[key].append(name)
# slightly better
d = {}
@poros
poros / counter.py
Created October 4, 2015 16:03
Counting with dictionaries
colors = ['green', 'blue', 'green', 'red', 'blue', 'green']
d = {}
for color in colors:
if color not in d:
d[color] = 0
d[color] += 1
# slighlty better
@poros
poros / chainmap.py
Created October 4, 2015 16:16
Overriding dictionaries
d = defaults.copy()
d.update(os.environ)
d.update(command_line_arguments)
# PYTHON3 ONLY!!!
from collections import ChainMap
d = ChainMap(command_line_arguments, os.environ, defaults)
# it's view, not a real dictionary. if you want something equivalent to a new one
d = ChainMap({}, command_line_arguments, os.environ, defaults)
@poros
poros / multiple_vars.py
Created October 4, 2015 16:31
Update multiple state variables at once
def fibonacci(n):
x = 0
y = 1
for i in range(n):
print x
tmp = y
y = x + y
x = tmp