Skip to content

Instantly share code, notes, and snippets.

View dawranliou's full-sized avatar

Daw-Ran Liou dawranliou

View GitHub Profile
from itertools import count
numbers = count()
next(numbers) # 0
next(numbers) # 1
next(numbers) # 2
next(numbers) # 3
#...
def number_generator():
i = 0
while True:
yield i
i += 1
numbers = number_generator()
next(numbers) # 0
next(numbers) # 1
next(numbers) # 2
next(numbers) # 3
>>> range(10)
range(0, 10)
# Use list() to evaluate the range object
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
user=> (range 10)
(0 1 2 3 4 5 6 7 8 9)
user=> range
#object[clojure.core$range xxxxxxxx]
;; Don't do this in your repl!
;; (range)
;; Do this instead
user=> (take 4 (range))
(0 1 2 3)
from time import perf_counter
from array import array
from contextlib import contextmanager
@contextmanager
def timing(label: str):
t0 = perf_counter()
yield lambda: (label, t1 - t0)
t1 = perf_counter()
@dawranliou
dawranliou / ping_port.py
Created January 23, 2017 23:30
Application pinger
import socket
def ping(host, port):
"""A generator to ping a particular application.
Return True if the destination port is occupied
Example:
>>> # ping application at port 99
>>> pinger = ping('127.0.0.1', 99)
>>> # When there's no application ruuning
@dawranliou
dawranliou / projecteuler.py
Created January 8, 2017 18:05
My utility functions to help me solve Project Euler problems
"Utilities to help solving problems."
import itertools
import functools
from collections import Counter
from operator import mul, pow
def prime_factors(num):
""" Yield the factors of a given number."""
i = 2
while i * i <= num:
@dawranliou
dawranliou / binary-tree-traverse.py
Created December 7, 2016 01:25
Practice Python's yield from expression
class Node:
def __init__(self, v):
self.v = v
self.l = None
self.r = None
def __repr__(self):
return '<Node %d>' % self.v
def children(node):
@dawranliou
dawranliou / mortgage_calculator.py
Created October 13, 2016 02:44
Simple program to calculate monthly payment and total payment
import argparse
def total_payment(principal, monthly_rate, payment_months):
return principal * (1 + monthly_rate) ** payment_months
def monthly_payment(principal, monthly_rate, payment_months):
weighted_month = ((1 + monthly_rate) ** payment_months - 1) / monthly_rate
return total_payment(principal, monthly_rate, payment_months) / weighted_month
print('--------------------------------------------')