Skip to content

Instantly share code, notes, and snippets.

View nasturtus's full-sized avatar

Santosh.S.N nasturtus

View GitHub Profile
# Priority Queues
# From: https://dbader.org/blog/priority-queues-in-python
# Sorted list
sl = []
sl.append((3, 'Sleep'))
sl.append((1, 'Eat'))
sl.append((2, 'Code'))
sl.sort(reverse=True)
# http://greenteapress.com/thinkpython2/html/thinkpython2005.html
import turtle
import math
def polygon(t, n, length):
angle = 360 / n
print(angle)
for i in range(n):
# http://greenteapress.com/thinkpython2/html/thinkpython2005.html
import turtle
def polygon(t, n, length):
angle = 360 / n
for i in range(n):
t.fd(length)
t.lt(angle)
# Illustrate timeit to time code snippets.
import timeit
# timeit should be callable and requires two arguments:
# a string and number of iterations.
# A basic timeit
print(timeit.timeit('10 + 2', number=1000000))
# Start a webserver in a jiffy.
Run python -m http.server 8000 from the directory containing index.html
Open browser window and enter localhost:8000 on the address bar to open index.html
# Generators vs List Comprehension
# References:
# 1. https://pythonprogramming.net/list-comprehension-generators-intermediate-python-tutorial/
# 2. The following is from reuven@lerner.co.il:
# That's why using a generator expression, which acts as an iterator, is often such an attractive option in Python:
# Rather than waiting for the entire thing to execute, and then returning a large list, we return the instructions
# that create a new list. In doing so, we save memory and execution time, allowing x to get something back faster.
# The fact that creating a generator expression is often just a matter of replacing the square brackets ( '[' and ']' )
# with regular parentheses ( '(' and ')' ) makes it a no-brainer in many situations.
# Zip it up!
# Reference:
# https://pythonprogramming.net/list-comprehension-generators-intermediate-python-tutorial/
a = [10, 20, 30]
b = [40, 50, 60]
print(zip(a, b))
print(list(zip(a, b)))
# Illustrating idemptotence
# An operation is idempotent if f(x) => n, f(f(x)) => n, f(f(f(x))) => n ..
# Reference:
# Corey Schafer https://www.youtube.com/watch?v=UaKZ4wKytcA
# The following is not idempotent since the results from square(n)
# and square(square(n)) differ.
def square(n):
# The goal of str() is readbility.
# The goal of repr() is to be unambiguous.
# The goal of type() is, well..to display the type.
# Reference: Corey Schafer https://www.youtube.com/watch?v=5cvM-crlDvg
from datetime import datetime
a = datetime.now()
print(str(a))
# Decorator without arguments
def decorator_function(func):
def wrapper_function(*args, **kwargs):
print("Before function: {}".format(func.__name__))
return func(*args, **kwargs)
return wrapper_function
@decorator_function
def greeting(name, greeting):