import os

os.remove("output.txt")
os.rmdir("docs")
os.remove("/output.txt")
os.rmdir("/docs")
---
from collections import defaultdict

rep = {"a": {1: "A", 2: "B", 4: "C", 5: "D"}, "b": {1: "E"}, "r": {2: "F"}}


def trstring(oldstring, repdict):
    seen, newchars = defaultdict(lambda: 1, {}), []
    for c in oldstring:
        i = seen[c]
        newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c)
        seen[c] += 1
    return "".join(newchars)


print("abracadabra ->", trstring("abracadabra", rep))
---
from livewires import *

horiz = 640
vert = 480
pruh = vert / 4
dpp = 255.0
begin_graphics(width=horiz, height=vert, title="Gray stripes", background=Colour.black)


def ty_pruhy(each):
    hiy = each[0] * pruh
    loy = hiy - pruh
    krok = horiz / each[1]
    piecol = 255.0 / (each[1] - 1)
    for x in xrange(0, each[1]):
        barva = Colour(piecol * x / dpp, piecol * x / dpp, piecol * x / dpp)
        set_colour(barva)
        if each[2]:
            box(x * krok, hiy, x * krok + krok, loy, filled=1)
        else:
            box(horiz - x * krok, hiy, horiz - ((x + 1) * krok), loy, filled=1)


source = [[4, 8, True], [3, 16, False], [2, 32, True], [1, 64, False]]
for each in source:
    ty_pruhy(each)

while keys_pressed() != [" "]:
    pass
---
def genfizzbuzz(factorwords, numbers):
    factorwords.sort(key=lambda factor_and_word: factor_and_word[0])
    lines = []
    for num in numbers:
        words = "".join(word for factor, word in factorwords if (num % factor) == 0)
        lines.append(words if words else str(num))
    return "\n".join(lines)


if __name__ == "__main__":
    print(genfizzbuzz([(5, "Buzz"), (3, "Fizz"), (7, "Baxx")], range(1, 21)))
---
def spiral(n):
    dx,dy = 1,0
    x,y = 0,0
    myarray = [[None]* n for j in range(n)]
    for i in xrange(n**2):
        myarray[x][y] = i
        nx,ny = x+dx, y+dy
        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:
            x,y = nx,ny
        else:
            dx,dy = -dy,dx
            x,y = x+dx, y+dy
    return myarray

def printspiral(myarray):
    n = range(len(myarray))
    for y in n:
        for x in n:
            print "%2i" % myarray[x][y],
        print

printspiral(spiral(5))
---
class Foo:
     def __init__(self):
        "Foo's initialization method's documentation"

def bar():

if __name__ == "__main__":
    print (__doc__)
    print (Foo.__doc__)
    print (Foo.__init__.__doc__)
    print (bar.__doc__)
---
s = [1, 2, 2, 3, 4, 4, 5]

for i in range(len(s)):
    curr = s[i]
    if i > 0 and curr == prev:
        print(i)
    prev = curr
---
def binomialCoeff(n, k):
    result = 1
    for i in range(1, k + 1):
        result = result * (n - i + 1) / i
    return result


if __name__ == "__main__":
    print(binomialCoeff(5, 3))
---
>>> src = "hello"
>>> a = src
>>> b = src[:]
>>> import copy
>>> c = copy.copy(src)
>>> d = copy.deepcopy(src)
>>> src is a is b is c is d
True
---
funcs = []
for i in range(10):
    funcs.append(lambda: i * i)
print funcs[3]()
---
from fractions import Fraction


def fractran(
    n,
    fstring="17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,"
    "77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,"
    "13 / 11, 15 / 14, 15 / 2, 55 / 1",
):
    flist = [Fraction(f) for f in fstring.replace(" ", "").split(",")]

    n = Fraction(n)
    while True:
        yield n.numerator
        for f in flist:
            if (n * f).denominator == 1:
                break
        else:
            break
        n *= f


if __name__ == "__main__":
    n, m = 2, 15
    print(
        "First %i members of fractran(%i):\n  " % (m, n)
        + ", ".join(str(f) for f, i in zip(fractran(n), range(m)))
    )
---
with open("xxx.txt") as f:
    for i, line in enumerate(f):
        if i == 6:
            break
    else:
        print("Not 7 lines in file")
        line = None
---
>>> import tempfile
>>> invisible = tempfile.TemporaryFile()
>>> invisible.name
'<fdopen>'
>>> visible = tempfile.NamedTemporaryFile()
>>> visible.name
'/tmp/tmpZNfc_s'
>>> visible.close()
>>> invisible.close()
---
from collections import deque


def simplemovingaverage(period):
    assert period == int(period) and period > 0, "Period must be an integer >0"

    summ = n = 0.0
    values = deque([0.0] * period)

    def sma(x):
        nonlocal summ, n

        values.append(x)
        summ += x - values.popleft()
        n = min(n + 1, period)
        return summ / n

    return sma
---
import numpy

h = [-8, -9, -3, -1, -6, 7]
f = [-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1]
g = [
    24,
    75,
    71,
    -34,
    3,
    22,
    -45,
    23,
    245,
    25,
    52,
    25,
    -67,
    -96,
    96,
    31,
    55,
    36,
    29,
    -43,
    -7,
]


def shift_bit_length(x):
    return 1 << (x - 1).bit_length()


def conv(a, b):
    p = len(a)
    q = len(b)
    n = p + q - 1
    r = shift_bit_length(n)
    y = numpy.fft.ifft(numpy.fft.fft(a, r) * numpy.fft.fft(b, r), r)
    return numpy.trim_zeros(numpy.around(numpy.real(y), decimals=6))


def deconv(a, b):
    p = len(a)
    q = len(b)
    n = p - q + 1
    r = shift_bit_length(max(p, q))
    y = numpy.fft.ifft(numpy.fft.fft(a, r) / numpy.fft.fft(b, r), r)
    return numpy.trim_zeros(numpy.around(numpy.real(y), decimals=6))


print(conv(h, f))


print(deconv(g, f))


print(deconv(g, h))
---
m = ((1, 1, 1, 1), (2, 4, 8, 16), (3, 9, 27, 81), (4, 16, 64, 256), (5, 25, 125, 625))
print(zip(*m))
---
n = 1024
while n > 0:
    print(n)
    n //= 2
---
def _commentstripper(txt, delim):
    "Strips first nest of block comments"

    deliml, delimr = delim
    out = ""
    if deliml in txt:
        indx = txt.index(deliml)
        out += txt[:indx]
        txt = txt[indx + len(deliml) :]
        txt = _commentstripper(txt, delim)
        assert delimr in txt, "Cannot find closing comment delimiter in " + txt
        indx = txt.index(delimr)
        out += txt[(indx + len(delimr)) :]
    else:
        out = txt
    return out


def commentstripper(txt, delim=("/*", "*/")):
    "Strips nests of block comments"

    deliml, delimr = delim
    while deliml in txt:
        txt = _commentstripper(txt, delim)
    return txt
---
import binascii
import functools
import hashlib

digits58 = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"


def b58(n):
    return b58(n // 58) + digits58[n % 58 : n % 58 + 1] if n else b""


def public_point_to_address(x, y):
    c = b"\x04" + binascii.unhexlify(x) + binascii.unhexlify(y)
    r = hashlib.new("ripemd160")
    r.update(hashlib.sha256(c).digest())
    c = b"\x00" + r.digest()
    d = hashlib.sha256(hashlib.sha256(c).digest()).digest()
    return b58(functools.reduce(lambda n, b: n << 8 | b, c + d[:4]))


if __name__ == "__main__":
    print(
        public_point_to_address(
            b"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
            b"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6",
        )
    )
---
for n in range(99, 0, -1):
    if n == 1:
        n_minus_1 = "No more"
        s = ""
        s2 = "s"
    elif n == 2:
        n_minus_1 = n - 1
        s = "s"
        s2 = ""
    else:
        n_minus_1 = n - 1
        s = "s"
        s2 = "s"

    print(VERSE.format(n=n, s=s, s2=s2, n_minus_1=n_minus_1))
---
class Node(object):
    def __init__(self, data=None, prev=None, next=None):
        self.prev = prev
        self.next = next
        self.data = data

    def __str__(self):
        return str(self.data)

    def __repr__(self):
        return repr(self.data)

    def iter_forward(self):
        c = self
        while c != None:
            yield c
            c = c.next

    def iter_backward(self):
        c = self
        while c != None:
            yield c
            c = c.prev
---
from ctypes import Structure, c_int

rs232_9pin = "_0 CD RD TD DTR SG DSR RTS CTS RI".split()
rs232_25pin = (
    "_0  PG  TD  RD  RTS CTS DSR SG  CD  pos neg"
    "_11 SCD SCS STD TC  SRD RC"
    "_18 SRS DTR SQD RI DRS XTC"
).split()


class RS232_9pin(Structure):
    _fields_ = [(__, c_int, 1) for __ in rs232_9pin]


class RS232_25pin(Structure):
    _fields_ = [(__, c_int, 1) for __ in rs232_25pin]
---
from __future__ import print_function


def path(n, p={1: 0}, lvl=[[1]]):
    if not n:
        return []
    while n not in p:
        q = []
        for x, y in ((x, x + y) for x in lvl[0] for y in path(x) if not x + y in p):
            p[y] = x
            q.append(y)
        lvl[0] = q

    return path(p[n]) + [n]


def tree_pow(x, n):
    r, p = {0: 1, 1: x}, 0
    for i in path(n):
        r[i] = r[i - p] * r[p]
        p = i
    return r[n]


def show_pow(x, n):
    fmt = "%d: %s\n" + ["%g^%d = %f", "%d^%d = %d"][x == int(x)] + "\n"
    print(fmt % (n, repr(path(n)), x, n, tree_pow(x, n)))


for x in range(18):
    show_pow(2, x)
show_pow(3, 191)
show_pow(1.1, 81)
---
def randomGenerator(seed=1):
    max_int32 = (1 << 31) - 1
    seed = seed & max_int32

    while True:
        seed = (seed * 214013 + 2531011) & max_int32
        yield seed >> 16


def deal(seed):
    nc = 52
    cards = list(range(nc - 1, -1, -1))
    rnd = randomGenerator(seed)
    for i, r in zip(range(nc), rnd):
        j = (nc - 1) - r % (nc - i)
        cards[i], cards[j] = cards[j], cards[i]
    return cards


def show(cards):
    l = ["A23456789TJQK"[int(c / 4)] + "CDHS"[c % 4] for c in cards]
    for i in range(0, len(cards), 8):
        print(" ".join(l[i : i + 8]))


if __name__ == "__main__":
    from sys import argv

    seed = int(argv[1]) if len(argv) == 2 else 11982
    print("Hand {}".format(seed))
    deck = deal(seed)
    show(deck)
---
import random, tkMessageBox
from Tkinter import *

window = Tk()
window.geometry("300x50+100+100")
options = {"padx": 5, "pady": 5}
s = StringVar()
s.set(1)


def increase():
    s.set(int(s.get()) + 1)


def rand():
    if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"):
        s.set(random.randrange(0, 5000))


def update(e):
    if not e.char.isdigit():
        tkMessageBox.showerror("Error", "Invalid input !")
        return "break"


e = Entry(text=s)
e.grid(column=0, row=0, **options)
e.bind("<Key>", update)
b1 = Button(text="Increase", command=increase, **options)
b1.grid(column=1, row=0, **options)
b2 = Button(text="Random", command=rand, **options)
b2.grid(column=2, row=0, **options)
mainloop()
---
def subtract(x, y):
    return x - y


subtract(5, 3)
subtract(y=3, x=5)
---
import ctypes

libc = ctypes.CDLL("/lib/libc.so.6")
libc.strcmp("abc", "def")
libc.strcmp("hello", "hello")
---
cR = [1]
cS = [2]


def extend_RS():
    x = cR[len(cR) - 1] + cS[len(cR) - 1]
    cR.append(x)
    cS += range(cS[-1] + 1, x)
    cS.append(x + 1)


def ff_R(n):
    assert n > 0
    while n > len(cR):
        extend_RS()
    return cR[n - 1]


def ff_S(n):
    assert n > 0
    while n > len(cS):
        extend_RS()
    return cS[n - 1]


print([ff_R(i) for i in range(1, 11)])

s = {}
for i in range(1, 1001):
    s[i] = 0
for i in range(1, 41):
    del s[ff_R(i)]
for i in range(1, 961):
    del s[ff_S(i)]

print("Ok")
---
majors = "north east south west".split()
majors *= 2
quarter1 = "N,N by E,N-NE,NE by N,NE,NE by E,E-NE,E by N".split(",")
quarter2 = [p.replace("NE", "EN") for p in quarter1]


def degrees2compasspoint(d):
    d = (d % 360) + 360 / 64
    majorindex, minor = divmod(d, 90.0)
    majorindex = int(majorindex)
    minorindex = int((minor * 4) // 45)
    p1, p2 = majors[majorindex : majorindex + 2]
    if p1 in {"north", "south"}:
        q = quarter1
    else:
        q = quarter2
    return q[minorindex].replace("N", p1).replace("E", p2).capitalize()


if __name__ == "__main__":
    for i in range(33):
        d = i * 11.25
        m = i % 3
        if m == 1:
            d += 5.62
        elif m == 2:
            d -= 5.62
        n = i % 32 + 1
        print("%2i %-18s %7.2f°" % (n, degrees2compasspoint(d), d))
---
from functools import reduce
from itertools import count, islice


def sylvester():
    def go(n):
        return 1 + reduce(lambda a, x: a * go(x), range(0, n), 1) if 0 != n else 2

    return map(go, count(0))


def main():

    print("First 10 terms of OEIS A000058:")
    xs = list(islice(sylvester(), 10))
    print("\n".join([str(x) for x in xs]))

    print("\nSum of the reciprocals of the first 10 terms:")
    print(reduce(lambda a, x: a + 1 / x, xs, 0))


if __name__ == "__main__":
    main()
---
for a, b, steps, func in ((0.0, 1.0, 100, cube), (1.0, 100.0, 1000, reciprocal)):
    for rule in (left_rect, mid_rect, right_rect, trapezium, simpson):
        print(
            "%s integrated using %s\n  from %r to %r (%i steps) = %r"
            % (
                func.__name__,
                rule.__name__,
                a,
                b,
                steps,
                integrate(func, a, b, steps, rule),
            )
        )
    a, b = Fraction.from_float(a), Fraction.from_float(b)
    for rule in (left_rect, mid_rect, right_rect, trapezium, simpson):
        print(
            "%s integrated using %s\n  from %r to %r (%i steps and fractions) = %r"
            % (
                func.__name__,
                rule.__name__,
                a,
                b,
                steps,
                float(integrate(func, a, b, steps, rule)),
            )
        )

for a, b, steps, func in (
    (1.0, 5000.0, 5000000, identity),
    (1.0, 6000.0, 6000000, identity),
):
    for rule in (left_rect, mid_rect, right_rect, trapezium, simpson):
        print(
            "%s integrated using %s\n  from %r to %r (%i steps) = %r"
            % (
                func.__name__,
                rule.__name__,
                a,
                b,
                steps,
                integrate(func, a, b, steps, rule),
            )
        )
    a, b = Fraction.from_float(a), Fraction.from_float(b)
    for rule in (left_rect, mid_rect, right_rect, trapezium, simpson):
        print(
            "%s integrated using %s\n  from %r to %r (%i steps and fractions) = %r"
            % (
                func.__name__,
                rule.__name__,
                a,
                b,
                steps,
                float(integrate(func, a, b, steps, rule)),
            )
        )
---
import curses
from random import randint


stdscr = curses.initscr()
for rows in range(10):
    line = "".join([chr(randint(41, 90)) for i in range(10)])
    stdscr.addstr(line + "\n")

icol = 3 - 1
irow = 6 - 1
ch = stdscr.instr(irow, icol, 1).decode(encoding="utf-8")

stdscr.move(irow, icol + 10)
stdscr.addstr("Character at column 3, row 6 = " + ch + "\n")
stdscr.getch()

curses.endwin()
---
import random, pprint
from itertools import product, combinations

N_DRAW = 9
N_GOAL = N_DRAW // 2

deck = list(product("red green purple".split(),
                    "one two three".split(),
                    "oval squiggle diamond".split(),
                    "solid open striped".split()))

sets = []
while len(sets) != N_GOAL:
    draw = random.sample(deck, N_DRAW)
    sets = [cs for cs in combinations(draw, 3)
            if all(len(set(t)) in [1, 3] for t in zip(*cs))]

print "Dealt %d cards:" % len(draw)
pprint.pprint(draw)
print "\nContaining %d sets:" % len(sets)
pprint.pprint(sets)
---
from itertools import combinations as comb


def statistic(ab, a):
    sumab, suma = sum(ab), sum(a)
    return suma / len(a) - (sumab - suma) / (len(ab) - len(a))


def permutationTest(a, b):
    ab = a + b
    Tobs = statistic(ab, a)
    under = 0
    for count, perm in enumerate(comb(ab, len(a)), 1):
        if statistic(ab, perm) <= Tobs:
            under += 1
    return under * 100.0 / count


treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]
controlGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]
under = permutationTest(treatmentGroup, controlGroup)
print("under=%.2f%%, over=%.2f%%" % (under, 100.0 - under))
---
>>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))
DLLs
Doc
LICENSE.txt
Lib
NEWS.txt
README.txt
Scripts
Tools
include
libs
python.exe
pythonw.exe
tcl
>>>
---
from wxPython.wx import *

  class MyApp(wxApp):
    def OnInit(self):
      frame = wxFrame(NULL, -1, "Hello from wxPython")
      frame.Show(true)
      self.SetTopWindow(frame)
      return true

  app = MyApp(0)
  app.MainLoop()
---
def ludic(nmax=100000):
    yield 1
    lst = list(range(2, nmax + 1))
    while lst:
        yield lst[0]
        del lst[:: lst[0]]


ludics = [l for l in ludic()]

print("First 25 ludic primes:")
print(ludics[:25])
print("\nThere are %i ludic numbers <= 1000" % sum(1 for l in ludics if l <= 1000))
print("\n2000'th..2005'th ludic primes:")
print(ludics[2000 - 1 : 2005])

n = 250
triplets = [
    (x, x + 2, x + 6)
    for x in ludics
    if x + 6 < n and x + 2 in ludics and x + 6 in ludics
]
print("\nThere are %i triplets less than %i:\n  %r" % (len(triplets), n, triplets))
---
from random import randrange


def knuth_shuffle(x):
    for i in range(len(x) - 1, 0, -1):
        j = randrange(i + 1)
        x[i], x[j] = x[j], x[i]


x = list(range(10))
knuth_shuffle(x)
print("shuffled:", x)
---
def step_up1():
    deficit = 1
    while deficit > 0:
        if step():
            deficit -= 1
        else:
            deficit += 1
---
import turtle as t


def sier(n, length):
    if n == 0:
        return
    for i in range(3):
        sier(n - 1, length / 2)
        t.fd(length)
        t.rt(120)
---
>>> def stripchars(s, chars):
...     return s.translate(None, chars)
...
>>> stripchars("She was a soul stripper. She took my heart!", "aei")
'Sh ws  soul strppr. Sh took my hrt!'
---
from __future__ import print_function
import random


def randN(N):
    "1,0 random generator factory with 1 appearing 1/N'th of the time"
    return lambda: random.randrange(N) == 0


def unbiased(biased):
    "uses a biased() generator of 1 or 0, to create an unbiased one"
    this, that = biased(), biased()
    while this == that:
        this, that = biased(), biased()
    return this


if __name__ == "__main__":
    from collections import namedtuple

    Stats = namedtuple("Stats", "count1 count0 percent")

    for N in range(3, 7):
        biased = randN(N)
        v = [biased() for x in range(1000000)]
        v1, v0 = v.count(1), v.count(0)
        print("Biased(%i)  = %r" % (N, Stats(v1, v0, 100.0 * v1 / (v1 + v0))))

        v = [unbiased(biased) for x in range(1000000)]
        v1, v0 = v.count(1), v.count(0)
        print("  Unbiased = %r" % (Stats(v1, v0, 100.0 * v1 / (v1 + v0)),))
---
bar = "▁▂▃▄▅▆▇█"
barcount = len(bar)


def sparkline(numbers):
    mn, mx = min(numbers), max(numbers)
    extent = mx - mn
    sparkline = "".join(
        bar[min([barcount - 1, int((n - mn) / extent * barcount)])] for n in numbers
    )
    return mn, mx, sparkline


if __name__ == "__main__":
    import re

    for line in (
        "0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;"
        "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;"
        "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 "
    ).split(";"):
        print("\nNumbers:", line)
        numbers = [float(n) for n in re.split(r"[\s,]+", line.strip())]
        mn, mx, sp = sparkline(numbers)
        print("  min: %5f; max: %5f" % (mn, mx))
        print("  " + sp)
---
def quick_sort(sequence):
    lesser = []
    equal = []
    greater = []
    if len(sequence) <= 1:
        return sequence
    pivot = sequence[0]
    for element in sequence:
        if element < pivot:
            lesser.append(element)
        elif element > pivot:
            greater.append(element)
        else:
            equal.append(element)
    lesser = quick_sort(lesser)
    greater = quick_sort(greater)
    return lesser + equal + greater


a = [4, 65, 2, -31, 0, 99, 83, 782, 1]
a = quick_sort(a)
---
from __future__ import print_function


def getDifference(b1, b2):
    r = (b2 - b1) % 360.0
    if r >= 180.0:
        r -= 360.0
    return r


if __name__ == "__main__":
    print("Input in -180 to +180 range")
    print(getDifference(20.0, 45.0))
    print(getDifference(-45.0, 45.0))
    print(getDifference(-85.0, 90.0))
    print(getDifference(-95.0, 90.0))
    print(getDifference(-45.0, 125.0))
    print(getDifference(-45.0, 145.0))
    print(getDifference(-45.0, 125.0))
    print(getDifference(-45.0, 145.0))
    print(getDifference(29.4803, -88.6381))
    print(getDifference(-78.3251, -159.036))

    print("Input in wider range")
    print(getDifference(-70099.74233810938, 29840.67437876723))
    print(getDifference(-165313.6666297357, 33693.9894517456))
    print(getDifference(1174.8380510598456, -154146.66490124757))
    print(getDifference(60175.77306795546, 42213.07192354373))
---
def char2value(c):
  assert c not in 'AEIOU', "No vowels"
  return int(c, 36)

sedolweight = [1,3,1,7,3,9]

def checksum(sedol):
    tmp = sum(map(lambda ch, weight: char2value(ch) * weight,
                  sedol, sedolweight)
               )
    return str((-tmp) % 10)

    print sedol + checksum(sedol)
---
>>> def printargs(*positionalargs, **keywordargs):
	print "POSITIONAL ARGS:\n  " + "\n  ".join(repr(x) for x in positionalargs)
	print "KEYWORD ARGS:\n  " + '\n  '.join(
		"%r = %r" % (k,v) for k,v in keywordargs.iteritems())

	
>>> printargs(1,'a',1+0j, fee='fi', fo='fum')
POSITIONAL ARGS:
  1
  'a'
  (1+0j)
KEYWORD ARGS:
  'fee' = 'fi'
  'fo' = 'fum'
>>> alist = [1,'a',1+0j]
>>> adict = {'fee':'fi', 'fo':'fum'}
>>> printargs(*alist, **adict)
POSITIONAL ARGS:
  1
  'a'
  (1+0j)
KEYWORD ARGS:
  'fee' = 'fi'
  'fo' = 'fum'
>>>
---
import __main__, os


def isOnlyInstance():
    return (
        os.system(
            "(( $(ps -ef | grep python | grep '["
            + __main__.__file__[0]
            + "]"
            + __main__.__file__[1:]
            + "' | wc -l) > 1 ))"
        )
        != 0
    )
---
import Tkinter as tk


def showxy(event):
    xm, ym = event.x, event.y
    str1 = "mouse at x=%d  y=%d" % (xm, ym)
    root.title(str1)
    x, y, delta = 100, 100, 10
    frame.config(bg="red" if abs(xm - x) < delta and abs(ym - y) < delta else "yellow")


root = tk.Tk()
frame = tk.Frame(root, bg="yellow", width=300, height=200)
frame.bind("<Motion>", showxy)
frame.pack()

root.mainloop()
---
import smtplib


def sendemail(
    from_addr,
    to_addr_list,
    cc_addr_list,
    subject,
    message,
    login,
    password,
    smtpserver="smtp.gmail.com:587",
):
    header = "From: %s\n" % from_addr
    header += "To: %s\n" % ",".join(to_addr_list)
    header += "Cc: %s\n" % ",".join(cc_addr_list)
    header += "Subject: %s\n\n" % subject
    message = header + message

    server = smtplib.SMTP(smtpserver)
    server.starttls()
    server.login(login, password)
    problems = server.sendmail(from_addr, to_addr_list, message)
    server.quit()
    return problems
---
def tau(n):
    assert isinstance(n, int) and 0 < n
    ans, i, j = 0, 1, 1
    while i * i <= n:
        if 0 == n % i:
            ans += 1
            j = n // i
            if j != i:
                ans += 1
        i += 1
    return ans


def is_tau_number(n):
    assert isinstance(n, int)
    if n <= 0:
        return False
    return 0 == n % tau(n)


if __name__ == "__main__":
    n = 1
    ans = []
    while len(ans) < 100:
        if is_tau_number(n):
            ans.append(n)
        n += 1
    print(ans)
---
lines = (
    py.replace("#", "<<<")
    .replace(" ", "X")
    .replace("X", "   ")
    .replace("\n", " Y")
    .replace("< ", "<>")
    .split("Y")
)

for i, l in enumerate(lines):
    print("  " * (len(lines) - i) + l)
---
import os

pid = os.fork()
if pid > 0:
else:
---
import random
from typing import List, Callable, Optional


def modifier(x: float) -> float:
    return 2 * (0.5 - x) if x < 0.5 else 2 * (x - 0.5)


def modified_random_distribution(
    modifier: Callable[[float], float], n: int
) -> List[float]:
    d: List[float] = []
    while len(d) < n:
        r1 = prob = random.random()
        if random.random() < modifier(prob):
            d.append(r1)
    return d


if __name__ == "__main__":
    from collections import Counter

    data = modified_random_distribution(modifier, 50_000)
    bins = 15
    counts = Counter(d // (1 / bins) for d in data)
    mx = max(counts.values())
    print("   BIN, COUNTS, DELTA: HISTOGRAM\n")
    last: Optional[float] = None
    for b, count in sorted(counts.items()):
        delta = "N/A" if last is None else str(count - last)
        print(
            f"  {b / bins:5.2f},  {count:4},  {delta:>4}: {'#' * int(40 * count / mx)}"
        )
        last = count
---
def is_numeric(s):
    try:
        float(s)
        return True
    except (ValueError, TypeError):
        return False


is_numeric("123.0")
---
from itertools import islice


def lfact():
    yield 0
    fact, summ, n = 1, 0, 1
    while 1:
        fact, summ, n = fact * n, summ + fact, n + 1
        yield summ


print("first 11:\n  %r" % [lf for i, lf in zip(range(11), lfact())])
print("20 through 110 (inclusive) by tens:")
for lf in islice(lfact(), 20, 111, 10):
    print(lf)
print(
    "Digits in 1,000 through 10,000 (inclusive) by thousands:\n  %r"
    % [len(str(lf)) for lf in islice(lfact(), 1000, 10001, 1000)]
)
---
cities = [
    {"name": "Lagos", "population": 21.0},
    {"name": "Cairo", "population": 15.2},
    {"name": "Kinshasa-Brazzaville", "population": 11.3},
    {"name": "Greater Johannesburg", "population": 7.55},
    {"name": "Mogadishu", "population": 5.85},
    {"name": "Khartoum-Omdurman", "population": 4.98},
    {"name": "Dar Es Salaam", "population": 4.7},
    {"name": "Alexandria", "population": 4.58},
    {"name": "Abidjan", "population": 4.4},
    {"name": "Casablanca", "population": 3.98},
]


def first(query):
    return next(query, None)


print(
    first(
        index for index, city in enumerate(cities) if city["name"] == "Dar Es Salaam"
    ),
    first(city["name"] for city in cities if city["population"] < 5),
    first(city["population"] for city in cities if city["name"][0] == "A"),
    sep="\n",
)
---
import urllib
page = urllib.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
for line in page:
    if ' UTC' in line:
        print line.strip()[4:]
        break
page.close()
---
def _convert_fortran_shapes():
    point = Pt
    pts = (point(0,0), point(10,0), point(10,10), point(0,10),
           point(2.5,2.5), point(7.5,2.5), point(7.5,7.5), point(2.5,7.5),
           point(0,5), point(10,5),
           point(3,0), point(7,0), point(7,10), point(3,10))
    p = (point(5,5), point(5, 8), point(-10, 5), point(0,5), point(10,5),
         point(8,5), point(10,10) )

    def create_polygon(pts,vertexindex):
        return [tuple(Edge(pts[vertexindex[i]-1], pts[vertexindex[i+1]-1])
                       for i in range(0, len(vertexindex), 2) )]
    polys=[]
    polys += create_polygon(pts, ( 1,2, 2,3, 3,4, 4,1 ) )
    polys += create_polygon(pts, ( 1,2, 2,3, 3,4, 4,1, 5,6, 6,7, 7,8, 8,5 ) )
    polys += create_polygon(pts, ( 1,5, 5,4, 4,8, 8,7, 7,3, 3,2, 2,5 ) )
    polys += create_polygon(pts, ( 11,12, 12,10, 10,13, 13,14, 14,9, 9,11 ) )

    names = ( "square", "square_hole", "strange", "exagon" )
    polys = [Poly(name, edges)
             for name, edges in zip(names, polys)]
    print 'polys = ['
    for p in polys:
        print "  Poly(name='%s', edges=(" % p.name
        print '   ', ',\n    '.join(str(e) for e in p.edges) + '\n    )),'
    print '  ]'
 _convert_fortran_shapes()
---
>>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0

>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>>
---
import itertools


def writedat(filename, x, y, xprecision=3, yprecision=5):
    with open(filename, "w") as f:
        for a, b in itertools.izip(x, y):
            print >> f, "%.*g\t%.*g" % (xprecision, a, yprecision, b)
---
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]

>>> import pylab
>>> pylab.plot(x, y, 'bo')
>>> pylab.savefig('qsort-range-10-9.png')
---
import sys

if "UTF-8" in sys.stdout.encoding:
    print("△")
else:
    raise Exception("Terminal can't handle UTF-8")
---
from collections import defaultdict
from itertools import product
from pprint import pprint as pp

cube2n = {x**3: x for x in range(1, 1201)}
sum2cubes = defaultdict(set)
for c1, c2 in product(cube2n, cube2n):
    if c1 >= c2:
        sum2cubes[c1 + c2].add((cube2n[c1], cube2n[c2]))

taxied = sorted((k, v) for k, v in sum2cubes.items() if len(v) >= 2)

for t in enumerate(taxied[:25], 1):
    pp(t)
print("...")
for t in enumerate(taxied[2000 - 1 : 2000 + 6], 2000):
    pp(t)
---
from __future__ import division
import matplotlib.pyplot as plt
import random

mean, stddev, size = 50, 4, 100000
data = [random.gauss(mean, stddev) for c in range(size)]

mn = sum(data) / size
sd = (sum(x * x for x in data) / size - (sum(data) / size) ** 2) ** 0.5

print(
    "Sample mean = %g; Stddev = %g; max = %g; min = %g for %i values"
    % (mn, sd, max(data), min(data), size)
)

plt.hist(data, bins=50)
---
from math import log, modf, floor


def p(l, n, pwr=2):
    l = int(abs(l))
    digitcount = floor(log(l, 10))
    log10pwr = log(pwr, 10)
    raised, found = -1, 0
    while found < n:
        raised += 1
        firstdigits = floor(10 ** (modf(log10pwr * raised)[0] + digitcount))
        if firstdigits == l:
            found += 1
    return raised


if __name__ == "__main__":
    for l, n in [(12, 1), (12, 2), (123, 45), (123, 12345), (123, 678910)]:
        print(f"p({l}, {n}) =", p(l, n))
---
def ncsub(seq, s=0):
    if seq:
        x = seq[:1]
        xs = seq[1:]
        p2 = s % 2
        p1 = not p2
        return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2)
    else:
        return [[]] if s >= 3 else []
---
import datetime, calendar

DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"]


def ddate(year, month, day):
    today = datetime.date(year, month, day)
    is_leap_year = calendar.isleap(year)
    if is_leap_year and month == 2 and day == 29:
        return "St. Tib's Day, YOLD " + (year + 1166)

    day_of_year = today.timetuple().tm_yday - 1

    if is_leap_year and day_of_year >= 60:
        day_of_year -= 1  # Compensate for St. Tib's Day

    season, dday = divmod(day_of_year, 73)
    return "%s %d, YOLD %d" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
---
import os

os.path.isfile("input.txt")
os.path.isfile("/input.txt")
os.path.isdir("docs")
os.path.isdir("/docs")
---
digits = "0123456789abcdefghijklmnopqrstuvwxyz"


def baseN(num, b):
    result = []
    while num >= b:
        num, d = divmod(num, b)
        result.append(digits[d])
    result.append(digits[num])
    return "".join(result[::-1])
---
import sys


def main():
    program = sys.argv[0]
    print("Program: %s" % program)


if __name__ == "__main__":
    main()
---
myDict = {"hello": 13, "world": 31, "!": 71}

for key, value in myDict.items():
    print("key = %s, value = %s" % (key, value))

for key in myDict:
    print("key = %s" % key)
for key in myDict.keys():
    print("key = %s" % key)

for value in myDict.values():
    print("value = %s" % value)
---
from fractions import Fraction


def harmonic_series():
    n, h = Fraction(1), Fraction(1)
    while True:
        yield h
        h += 1 / (n + 1)
        n += 1


if __name__ == "__main__":
    from itertools import islice

    for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)):
        print(n, "/", d)
---
val = 0
while True:
   val +=1
   print val
   if val % 6 == 0: break
---
from __future__ import print_function, division

WIDTH = 81
HEIGHT = 5

lines = []


def cantor(start, len, index):
    seg = len // 3
    if seg == 0:
        return None
    for it in range(HEIGHT - index):
        i = index + it
        for jt in range(seg):
            j = start + seg + jt
            pos = i * WIDTH + j
            lines[pos] = " "
    cantor(start, seg, index + 1)
    cantor(start + seg * 2, seg, index + 1)
    return None


lines = ["*"] * (WIDTH * HEIGHT)
cantor(0, WIDTH, 1)

for i in range(HEIGHT):
    beg = WIDTH * i
    print("".join(lines[beg : beg + WIDTH]))
---
def recurse(counter):
    print(counter)
    counter += 1
    recurse(counter)
---
from itertools import product

xx = "-5 +5".split()
pp = "2 3".split()
texts = "-x**p -(x)**p (-x)**p -(x**p)".split()

print("Integer variable exponentiation")
for x, p in product(xx, pp):
    print(f"  x,p = {x:2},{p}; ", end=" ")
    x, p = int(x), int(p)
    print("; ".join(f"{t} =={eval(t):4}" for t in texts))

print("\nBonus integer literal exponentiation")
X, P = "xp"
xx.insert(0, " 5")
texts.insert(0, "x**p")
for x, p in product(xx, pp):
    texts2 = [t.replace(X, x).replace(P, p) for t in texts]
    print(" ", "; ".join(f"{t2} =={eval(t2):4}" for t2 in texts2))
---
from datetime import date
from calendar import isleap


def weekday(d):
    days = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
    ]
    dooms = [[3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5], [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]]

    c = d.year // 100
    r = d.year % 100
    s = r // 12
    t = r % 12
    c_anchor = (5 * (c % 4) + 2) % 7
    doomsday = (s + t + (t // 4) + c_anchor) % 7
    anchorday = dooms[isleap(d.year)][d.month - 1]
    weekday = (doomsday + d.day - anchorday + 7) % 7
    return days[weekday]


dates = [
    date(*x)
    for x in [
        (1800, 1, 6),
        (1875, 3, 29),
        (1915, 12, 7),
        (1970, 12, 23),
        (2043, 5, 14),
        (2077, 2, 12),
        (2101, 4, 2),
    ]
]

for d in dates:
    tense = "was" if d < date.today() else "is" if d == date.today() else "will be"
    print("{} {} a {}".format(d.strftime("%B %d, %Y"), tense, weekday(d)))
---
import numpy as np

a = np.array([[1, 2], [3, 4]], order="C")
b = np.array([[1, 2], [3, 4]], order="F")
np.reshape(a, (4,))
np.reshape(b, (4,))
np.reshape(b, (4,), order="A")
---
from itertools import permutations


def solve():
    c, p, f, s = "\\,Police,Fire,Sanitation".split(",")
    print(f"{c:>3}  {p:^6} {f:^4} {s:^10}")
    c = 1
    for p, f, s in permutations(range(1, 8), r=3):
        if p + s + f == 12 and p % 2 == 0:
            print(f"{c:>3}: {p:^6} {f:^4} {s:^10}")
            c += 1


if __name__ == "__main__":
    solve()