Skip to content

Instantly share code, notes, and snippets.

View juanarrivillaga's full-sized avatar

Juan juanarrivillaga

View GitHub Profile
@juanarrivillaga
juanarrivillaga / for_loop.py
Created March 8, 2017 19:30
What does a Python for-loop do?
# If we were to implement a Python for-loop in Python,
for x in my_iterable:
do_stuff(x)
# it would be equivalent to the following:
iterator = iter(my_iterable)
while True:
try:
def random_items(lst):
lst = lst[:] # copy so original list is not mutated
while True:
random.shuffle(lst)
yield from lst
# Python 2 can't use `yield from`
def random_items_py2(lst):
lst = lst[:]
while True:
@juanarrivillaga
juanarrivillaga / adder.py
Last active March 12, 2017 22:35
higher order functions
def adder(x):
def add_x(n):
return n + x
return add_x
add_1 = adder(1)
add_2 = adder(2)
add_42 = adder(42)
x = 10
import timeit
import pickle
import json
s = """{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
n = """12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
from timeit import timeit
from collections import deque
import string
def for_gen():
for i in range(100000):
yield i
def while_gen():
i = 0
while i < 1000000:
"""
An exampe quicksort implementation, demonstrating pythonic style
(albeit using inefficient `+` to concatenate lists...)
"""
def quicksort(seq):
if len(seq) <= 1:
return seq
pivot, *rest = seq
smaller = quicksort([x for x in rest if x <= pivot])
larger = quicksort([x for x in rest if x > pivot])
import string
from collections import deque
from itertools import islice
consumer = deque(maxlen=0)
consume = consumer.extend
def generator(iterable, steps, consume=consume):
it = iter(iterable)
yield next(it)
# So, consider:
>>> class SomeClass:
... var = 'foo'
...
>>> x = SomeClass()
>>> x.var
'foo'
>>> SomeClass.var
'foo'
from itertools import chain
from more_itertools import unique_everseen
# don't materialize into a list!
ci = zip(item_name, instance_id, contract_number, serial_number, item_status, product_group_description, item_end_date5))
co = zip(item_name2, instance_id2, contract_number2, serial_number2, item_status2, product_group_description2, item_end_date6))
# use itertools.chain instead of list-concatenation if you want to chain to iterables!
# You should, *use snake_case*, it's the PEP8 recommended way. If you *do* want to use camelCase
# the don't mix snake_case and camelCase. Use one or the other. Preferablly snake_case :)