Skip to content

Instantly share code, notes, and snippets.

@SZanlongo
SZanlongo / circlesOverlap.py
Last active August 29, 2015 14:06
Check if two circles overlap
# Check if two circles overlap
def is_overlap(circle1, circle2):
distance = ((circle1.x - circle2.x) ** 2 + (circle1.y - circle2.y) ** 2) ** 0.5
return distance < circle1.r + circle2.r
@SZanlongo
SZanlongo / gcd.py
Created September 18, 2014 01:57
Find greatest common divisor
# https://stackoverflow.com/questions/691946/short-and-useful-python-snippets
def gcd(a, b):
while(b):
a, b = b, a % b
return a
print gcd (54, 24)
@SZanlongo
SZanlongo / pythonServer.py
Created September 18, 2014 01:58
Simple web server for files in the current directory
python -m SimpleHTTPServer
@SZanlongo
SZanlongo / 2Dmatrix.py
Created September 18, 2014 01:59
2D Matrix
# https://stackoverflow.com/questions/691946/short-and-useful-python-snippets
# Create 2-dimensional matrix
lst_2d = [[0] * 3 for i in xrange(3)]
print lst_2d
# Assign a value within the matrix
lst_2d[0][0] = 5
print lst_2d
@SZanlongo
SZanlongo / enumerate.py
Created September 18, 2014 02:00
Enumerate items in list
# https://stackoverflow.com/questions/691946/short-and-useful-python-snippets
# Allows you to have access to the indexes of the elements within a for loop
l = ['a', 'b', 'c', 'd', 'e', 'f']
for (index, value) in enumerate(l):
print index, value
@SZanlongo
SZanlongo / transposeIterable.py
Created September 18, 2014 02:01
Transpose iterable
# https://stackoverflow.com/questions/691946/short-and-useful-python-snippets
a = [[1, 2, 3], [4, 5, 6]]
print zip(*a)
# Same with dicts
d = {"a":1, "b":2, "c":3}
print zip(*d.iteritems())
@SZanlongo
SZanlongo / flattenList.py
Created September 18, 2014 02:01
Flatten matrix
# https://stackoverflow.com/questions/691946/short-and-useful-python-snippets
lol = [['a', 'b'], ['c'], ['d', 'e', 'f']]
for outer in lol:
for inner in outer:
print inner
@SZanlongo
SZanlongo / lineEmpty.py
Created September 18, 2014 02:02
Check if a line is empty
# https://stackoverflow.com/questions/691946/short-and-useful-python-snippets
line = ""
if not line.strip():
print 'empty'
@SZanlongo
SZanlongo / dedupeList.py
Created September 18, 2014 02:02
Remove duplicates from a List
# https://stackoverflow.com/questions/691946/short-and-useful-python-snippets
L = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
print list(set(L))
@SZanlongo
SZanlongo / intsFromString.py
Created September 18, 2014 02:03
Get integers from a string (space seperated)
# https://stackoverflow.com/questions/691946/short-and-useful-python-snippets
S = "1 2 2 3 3 3 4 4 4 4"
print [int(x) for x in S.split()]