Library: pygame[edit]
Translation of: C
import pygame, sys
from pygame.locals import *
from math import sin, cos, radians

pygame.init()

WINDOWSIZE = 250
TIMETICK = 100
BOBSIZE = 15

window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))
pygame.display.set_caption("Pendulum")

screen = pygame.display.get_surface()
screen.fill((255,255,255))

PIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)
SWINGLENGTH = PIVOT[1]*4

class BobMass(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.theta = 45
        self.dtheta = 0
        self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),
                                PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),
                                1,1)
        self.draw()

    def recomputeAngle(self):
        scaling = 3000.0/(SWINGLENGTH**2)

        firstDDtheta = -sin(radians(self.theta))*scaling
        midDtheta = self.dtheta + firstDDtheta
        midtheta = self.theta + (self.dtheta + midDtheta)/2.0

        midDDtheta = -sin(radians(midtheta))*scaling
        midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2
        midtheta = self.theta + (self.dtheta + midDtheta)/2

        midDDtheta = -sin(radians(midtheta)) * scaling
        lastDtheta = midDtheta + midDDtheta
        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0

        lastDDtheta = -sin(radians(lasttheta)) * scaling
        lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0
        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0

        self.dtheta = lastDtheta
        self.theta = lasttheta
        self.rect = pygame.Rect(PIVOT[0]-
                                SWINGLENGTH*sin(radians(self.theta)),
                                PIVOT[1]+
                                SWINGLENGTH*cos(radians(self.theta)),1,1)

    def draw(self):
        pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)
        pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)
        pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)
        pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))

    def update(self):
        self.recomputeAngle()
        screen.fill((255,255,255))
        self.draw()

bob = BobMass()

TICK = USEREVENT + 2
pygame.time.set_timer(TICK, TIMETICK)

def input(events):
    for event in events:
        if event.type == QUIT:
            sys.exit(0)
        elif event.type == TICK:
            bob.update()

while True:
    input(pygame.event.get())
    pygame.display.flip()

Python: using tkinter[edit]
''' Python 3.6.5 code using Tkinter graphical user interface.'''

from tkinter import *
import math

class Animation:
    def __init__(self, gw):
        self.window = gw
        self.xoff, self.yoff = 300, 100
        self.angle = 0
        self.sina = math.sin(self.angle)
        self.cosa = math.cos(self.angle)
        self.rodhyp = 170
        self.bobr = 30
        self.bobhyp = self.rodhyp + self.bobr
        self.rodx0, self.rody0 = self.xoff, self.yoff
        self.ra = self.rodx0
        self.rb = self.rody0
        self.rc = self.xoff + self.rodhyp*self.sina
        self.rd = self.yoff + self.rodhyp*self.cosa
        self.ba = self.xoff - self.bobr + self.bobhyp*self.sina
        self.bb = self.yoff - self.bobr + self.bobhyp*self.cosa
        self.bc = self.xoff + self.bobr + self.bobhyp*self.sina
        self.bd = self.yoff + self.bobr + self.bobhyp*self.cosa
        self.da = math.pi / 360

        # create / fill canvas:
        self.cnv = Canvas(gw, bg='lemon chiffon')
        self.cnv.pack(fill=BOTH, expand=True)

        self.cnv.create_line(0, 100, 600, 100,
                             fill='dodger blue',
                             width=3)
        radius = 8
        self.cnv.create_oval(300-radius, 100-radius,
                             300+radius, 100+radius,
                             fill='navy')

        self.bob = self.cnv.create_oval(self.ba,
                                        self.bb,
                                        self.bc,
                                        self.bd,
                                        fill='red',
                                        width=2)

        self.rod = self.cnv.create_line(self.ra,
                                        self.rb,
                                        self.rc,
                                        self.rd,
                                        fill='dodger blue',
                                        width=6)

        self.animate()

    def animate(self):
        if abs(self.angle) > math.pi / 2:
            self.da = - self.da
        self.angle += self.da
        self.sina = math.sin(self.angle)
        self.cosa = math.cos(self.angle)
        self.ra = self.rodx0
        self.rb = self.rody0
        self.rc = self.xoff + self.rodhyp*self.sina
        self.rd = self.yoff + self.rodhyp*self.cosa
        self.ba = self.xoff - self.bobr + self.bobhyp*self.sina
        self.bb = self.yoff - self.bobr + self.bobhyp*self.cosa
        self.bc = self.xoff + self.bobr + self.bobhyp*self.sina
        self.bd = self.yoff + self.bobr + self.bobhyp*self.cosa

        self.cnv.coords(self.rod,
                        self.ra,
                        self.rb,
                        self.rc,
                        self.rd)
        self.cnv.coords(self.bob,
                        self.ba,
                        self.bb,
                        self.bc,
                        self.bd)
        self.window.update()
        self.cnv.after(5, self.animate)

root = Tk()
root.title('Pendulum')
root.geometry('600x400+100+50')
root.resizable(False, False)
a = Animation(root)
root.mainloop()

create and animate a simple physical model of a gravity pendulum.


Works with: Python version 2.6+Works with: Python version 3.0+
>>> import json
>>> data = json.loads('{ "foo": 1, "bar": [10, "apples"] }')
>>> sample = { "blue": [1,2], "ocean": "water" }
>>> json_string = json.dumps(sample)
>>> json_string
'{"blue": [1, 2], "ocean": "water"}'
>>> sample
{'blue': [1, 2], 'ocean': 'water'}
>>> data
{'foo': 1, 'bar': [10, 'apples']}

>>> true = True; false = False; null = None
>>> data = eval('{ "foo": 1, "bar": [10, "apples"] }')
>>> data
{'foo': 1, 'bar': [10, 'apples']}

"Load a JSON string into a data structure, create a new data structure, serialize it into JSON using objects and arrays, and ensure the JSON is valid. Also, it demonstrates an alternative (not recommended) way to parse JSON using eval() in Python."


from decimal import Decimal, getcontext

def nthroot (n, A, precision):
    getcontext().prec = precision

    n = Decimal(n)
    x_0 = A / n #step 1: make a while guess.
    x_1 = 1     #need it to exist before step 2
    while True:
        #step 2:
        x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1))))
        if x_0 == x_1:
            return x_1

print nthroot(5, 34, 10)
print nthroot(10,42, 20)
print nthroot(2, 5, 400)

Works with: Python version 3.7
'''Nth Root'''

from decimal import Decimal, getcontext
from operator import eq

# nthRoot :: Int -> Int -> Int -> Real
def nthRoot(precision):
    '''The nth root of x at the given precision.'''
    def go(n, x):
        getcontext().prec = precision
        dcn = Decimal(n)

        def same(ab):
            return eq(*ab)

        def step(ab):
            a, b = ab
            predn = pred(dcn)
            return (
                b,
                reciprocal(dcn) * (
                    predn * a + (
                        x / (a ** predn)
                    )
                )
            )
        return until(same)(step)(
            (x / dcn, 1)
        )[0]
    return lambda n: lambda x: go(n, x)

# --------------------------TEST---------------------------
def main():
    '''Nth roots at various precisions'''

    def xShow(tpl):
        p, n, x = tpl
        return rootName(n) + (
            ' of ' + str(x) + ' at precision ' + str(p)
        )

    def f(tpl):
        p, n, x = tpl
        return nthRoot(p)(n)(x)

    print(
        fTable(main.__doc__ + ':\n')(xShow)(str)(f)(
            [(10, 5, 34), (20, 10, 42), (30, 2, 5)]
        )
    )

# -------------------------DISPLAY-------------------------

# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
    '''Heading -> x display function -> fx display function ->
       f -> xs -> tabular string.
    '''
    def go(xShow, fxShow, f, xs):
        ys = [xShow(x) for x in xs]
        w = max(map(len, ys))
        return s + '\n' + '\n'.join(map(
            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
            xs, ys
        ))
    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
        xShow, fxShow, f, xs
    )

# -------------------------GENERIC-------------------------

# rootName :: Int -> String
def rootName(n):
    '''English ordinal suffix.'''
    return ['identity', 'square root', 'cube root'][n - 1] if (
        4 > n or 1 > n
    ) else (str(n) + 'th root')

# pred ::  Enum a => a -> a
def pred(x):
    '''The predecessor of a value. For numeric types, (- 1).'''
    return x - 1

# reciprocal :: Num -> Num
def reciprocal(x):
    '''Arithmetic reciprocal of x.'''
    return 1 / x

# until :: (a -> Bool) -> (a -> a) -> a -> a
def until(p):
    '''The result of repeatedly applying f until p holds.
       The initial seed value is x.
    '''
    def go(f, x):
        v = x
        while not p(v):
            v = f(v)
        return v
    return lambda f: lambda x: go(f, x)

if __name__ == '__main__':
    main()

Implement the principal nth root algorithm for a positive real number A.


Works with: Python version 2.5
import socket
host = socket.gethostname()

"Determines and outputs the hostname of the current system where the routine is running."


Finite iteration[edit]
def Leonardo(L_Zero, L_One, Add, Amount):
    terms = [L_Zero,L_One]
    while len(terms) < Amount:
        new = terms[-1] + terms[-2]
        new += Add
        terms.append(new)
    return terms

out = ""
print "First 25 Leonardo numbers:"
for term in Leonardo(1,1,1,25):
    out += str(term) + " "
print out

out = ""
print "Leonardo numbers with fibonacci parameters:"
for term in Leonardo(0,1,0,25):
    out += str(term) + " "
print out

The code generates the first 25 Leonardo numbers, starting from L(0). It allows the initial two Leonardo numbers (L(0) and L(1)) and the add number to be specified, with 1 as the default add number. The code also provides the functionality to generate the Fibonacci sequence by setting 0 and 1 for L(0) and L(1), and 0 for the add number. Additionally, it includes a Python generator for producing a non-finite stream of Leonardo numbers.


Python: Original, with output[edit]

'''
 The 24 Game

 Given any four digits in the range 1 to 9, which may have repetitions,
 Using just the +, -, *, and / operators; and the possible use of
 brackets, (), show how to make an answer of 24.

 An answer of "q" will quit the game.
 An answer of "!" will generate a new set of four digits.
 Otherwise you are repeatedly asked for an expression until it evaluates to 24

 Note: you cannot form multiple digit numbers from the supplied digits,
 so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.

'''

from __future__ import division, print_function
import random, ast, re
import sys

if sys.version_info[0] < 3: input = raw_input

def choose4():
    'four random digits >0 as characters'
    return [str(random.randint(1,9)) for i in range(4)]

def welcome(digits):
    print (__doc__)
    print ("Your four digits: " + ' '.join(digits))

def check(answer, digits):
    allowed = set('() +-*/\t'+''.join(digits))
    ok = all(ch in allowed for ch in answer) and \
         all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
         and not re.search('\d\d', answer)
    if ok:
        try:
            ast.parse(answer)
        except:
            ok = False
    return ok

def main():
    digits = choose4()
    welcome(digits)
    trial = 0
    answer = ''
    chk = ans = False
    while not (chk and ans == 24):
        trial +=1
        answer = input("Expression %i: " % trial)
        chk = check(answer, digits)
        if answer.lower() == 'q':
            break
        if answer == '!':
            digits = choose4()
            print ("New digits:", ' '.join(digits))
            continue
        if not chk:
            print ("The input '%s' was wonky!" % answer)
        else:
            ans = eval(answer)
            print (" = ", ans)
            if ans == 24:
                print ("Thats right!")
    print ("Thank you and goodbye")

if __name__ == '__main__': main()

generate and display four random digits from 1 to 9, prompt the player to form an arithmetic expression using these digits exactly once, and check if the expression evaluates to 24. The allowed operations are addition, subtraction, multiplication, and division with floating point or rational arithmetic. The program does not generate or test the validity of the expression.


def encode(input_string):
    count = 1
    prev = None
    lst = []
    for character in input_string:
        if character != prev:
            if prev:
                entry = (prev, count)
                lst.append(entry)
            count = 1
            prev = character
        else:
            count += 1
    else:
        try:
            entry = (character, count)
            lst.append(entry)
            return (lst, 0)
        except Exception as e:
            print("Exception encountered {e}".format(e=e))
            return (e, 1)

def decode(lst):
    q = []
    for character, count in lst:
        q.append(character * count)
    return ''.join(q)

#Method call
value = encode("aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa")
if value[1] == 0:
    print("Encoded value is {}".format(value[0]))
    decode(value[0])

Works with: Python version 2.4
from itertools import groupby
def encode(input_string):
    return [(len(list(g)), k) for k,g in groupby(input_string)]

def decode(lst):
    return ''.join(c * n for n,c in lst)

encode("aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa")
decode([(5, 'a'), (6, 'h'), (7, 'm'), (1, 'u'), (7, 'i'), (6, 'a')])

from re import sub

def encode(text):
    '''
    Doctest:
        >>> encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW')
        '12W1B12W3B24W1B14W'
    '''
    return sub(r'(.)\1*', lambda m: str(len(m.group(0))) + m.group(1),
               text)

def decode(text):
    '''
    Doctest:
        >>> decode('12W1B12W3B24W1B14W')
        'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'
    '''
    return sub(r'(\d+)(\D)', lambda m: m.group(2) * int(m.group(1)),
               text)

textin = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
assert decode(encode(textin)) == textin

The code compresses a string of uppercase characters by encoding repeated sequences of the same character with the length of the sequence followed by the character. It also provides a function to reverse this compression. For example, the string "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" is compressed to "12W1B12W3B24W1B14W". The code uses regular expressions for both encoding and decoding processes.


s1 = "hello"
print s1 + " world"

s2 = s1 + " world"
print s2

The code initializes two string variables, one with a predefined text value and the other as a concatenation of the original string with another string literal. It also demonstrates the use of the 'join' method for efficient string concatenation when dealing with multiple strings, using a specific string as a separator.


import urllib
s = 'http://foo/bar/'
s = urllib.quote(s)

"Implements a function to convert a given string into URL encoding format. It converts special, control, and extended characters into a percent symbol followed by a two-digit hexadecimal code. Characters requiring conversion include ASCII control codes, ASCII symbols, and extended characters with codes of 128 and above. The function also supports variations such as lowercase escapes and different encoding standards like RFC 3986 and HTML 5. An optional feature includes the use of an exception string for symbols that don't require conversion."


'''Common sorted list'''

from itertools import chain

# ------------------------- TEST -------------------------
# main :: IO ()
def main():
    '''Sorted union of lists'''

    print(
        sorted(nub(concat([
            [5, 1, 3, 8, 9, 4, 8, 7],
            [3, 5, 9, 8, 4],
            [1, 3, 7, 9]
        ])))
    )

# ----------------------- GENERIC ------------------------

# concat :: [[a]] -> [a]
# concat :: [String] -> String
def concat(xs):
    '''The concatenation of all the elements in a list.
    '''
    return list(chain(*xs))

# nub :: [a] -> [a]
def nub(xs):
    '''A list containing the same elements as xs,
       without duplicates, in the order of their
       first occurrence.
    '''
    return list(dict.fromkeys(xs))

# MAIN ---
if __name__ == '__main__':
    main()

generates a common sorted list with unique elements from multiple integer arrays.


#        NAME, WEIGHT, VALUE (for this weight)
items = [("beef",    3.8, 36.0),
         ("pork",    5.4, 43.0),
         ("ham",     3.6, 90.0),
         ("greaves", 2.4, 45.0),
         ("flitch",  4.0, 30.0),
         ("brawn",   2.5, 56.0),
         ("welt",    3.7, 67.0),
         ("salami",  3.0, 95.0),
         ("sausage", 5.9, 98.0)]

MAXWT = 15.0

sorted_items = sorted(((value/amount, amount, name)
                       for name, amount, value in items),
                      reverse = True)
wt = val = 0
bagged = []
for unit_value, amount, name in sorted_items:
    portion = min(MAXWT - wt, amount)
    wt     += portion
    addval  = portion * unit_value
    val    += addval
    bagged += [(name, portion, addval)]
    if wt >= MAXWT:
        break

print("    ITEM   PORTION VALUE")
print("\n".join("%10s %6.2f %6.2f" % item for item in bagged))
print("\nTOTAL WEIGHT: %5.2f\nTOTAL VALUE: %5.2f" % (wt, val))

    ITEM   PORTION VALUE
    salami   3.00  95.00
       ham   3.60  90.00
     brawn   2.50  56.00
   greaves   2.40  45.00
      welt   3.50  63.38

TOTAL WEIGHT: 15.00
TOTAL VALUE: 349.38

implement a solution for the continuous knapsack problem. The thief can select and cut items from a butcher's shop to maximize profit without exceeding a total weight of 15 kg. The items' value reduces proportionally when cut. The solution uses a greedy algorithm to select items based on their value per unit weight.


Python 3.X Using defaultdict[edit]

>>> import urllib.request
>>> from collections import defaultdict
>>> words = urllib.request.urlopen('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt').read().split()
>>> anagram = defaultdict(list) # map sorted chars to anagrams
>>> for word in words:
	anagram[tuple(sorted(word))].append( word )

>>> count = max(len(ana) for ana in anagram.values())
>>> for ana in anagram.values():
	if len(ana) >= count:
		print ([x.decode() for x in ana])

Python 2.7 version[edit]

>>> import urllib
>>> from collections import defaultdict
>>> words = urllib.urlopen('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt').read().split()
>>> len(words)
25104
>>> anagram = defaultdict(list) # map sorted chars to anagrams
>>> for word in words:
	anagram[tuple(sorted(word))].append( word )

>>> count = max(len(ana) for ana in anagram.itervalues())
>>> for ana in anagram.itervalues():
	if len(ana) >= count:
		print ana

['angel', 'angle', 'galen', 'glean', 'lange']
['alger', 'glare', 'lager', 'large', 'regal']
['caret', 'carte', 'cater', 'crate', 'trace']
['evil', 'levi', 'live', 'veil', 'vile']
['elan', 'lane', 'lean', 'lena', 'neal']
['abel', 'able', 'bale', 'bela', 'elba']
>>> count
5
>>>

Python: Using groupby[edit]
Translation of: Haskell
Works with: Python version 2.6 sort and then group using groupby()
>>> import urllib, itertools
>>> words = urllib.urlopen('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt').read().split()
>>> len(words)
25104
>>> anagrams = [list(g) for k,g in itertools.groupby(sorted(words, key=sorted), key=sorted)]

>>> count = max(len(ana) for ana in anagrams)
>>> for ana in anagrams:
	if len(ana) >= count:
		print ana

['abel', 'able', 'bale', 'bela', 'elba']
['caret', 'carte', 'cater', 'crate', 'trace']
['angel', 'angle', 'galen', 'glean', 'lange']
['alger', 'glare', 'lager', 'large', 'regal']
['elan', 'lane', 'lean', 'lena', 'neal']
['evil', 'levi', 'live', 'veil', 'vile']
>>> count
5
>>>

Works with: Python version 3.7
'''Largest anagram groups found in list of words.'''

from os.path import expanduser
from itertools import groupby
from operator import eq

# main :: IO ()
def main():
    '''Largest anagram groups in local unixdict.txt'''

    print(unlines(
        largestAnagramGroups(
            lines(readFile('unixdict.txt'))
        )
    ))

# largestAnagramGroups :: [String] -> [[String]]
def largestAnagramGroups(ws):
    '''A list of the anagram groups of
       of the largest size found in a
       given list of words.
    '''

    # wordChars :: String -> (String, String)
    def wordChars(w):
        '''A word paired with its
           AZ sorted characters
        '''
        return (''.join(sorted(w)), w)

    groups = list(map(
        compose(list)(snd),
        groupby(
            sorted(
                map(wordChars, ws),
                key=fst
            ),
            key=fst
        )
    ))

    intMax = max(map(len, groups))
    return list(map(
        compose(unwords)(curry(map)(snd)),
        filter(compose(curry(eq)(intMax))(len), groups)
    ))

# GENERIC -------------------------------------------------

# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
    '''Right to left function composition.'''
    return lambda f: lambda x: g(f(x))

# curry :: ((a, b) -> c) -> a -> b -> c
def curry(f):
    '''A curried function derived
       from an uncurried function.'''
    return lambda a: lambda b: f(a, b)

# fst :: (a, b) -> a
def fst(tpl):
    '''First member of a pair.'''
    return tpl[0]

# lines :: String -> [String]
def lines(s):
    '''A list of strings,
       (containing no newline characters)
       derived from a single new-line delimited string.'''
    return s.splitlines()

# from os.path import expanduser
# readFile :: FilePath -> IO String
def readFile(fp):
    '''The contents of any file at the path
       derived by expanding any ~ in fp.'''
    with open(expanduser(fp), 'r', encoding='utf-8') as f:
        return f.read()

# snd :: (a, b) -> b
def snd(tpl):
    '''Second member of a pair.'''
    return tpl[1]

# unlines :: [String] -> String
def unlines(xs):
    '''A single string derived by the intercalation
       of a list of strings with the newline character.'''
    return '\n'.join(xs)

# unwords :: [String] -> String
def unwords(xs):
    '''A space-separated string derived from
       a list of words.'''
    return ' '.join(xs)

# MAIN ---
if __name__ == '__main__':
    main()

"Find the largest sets of anagrams from a given word list using Python 3.2 or 2.7, with optimization for speed by avoiding the use of sorted as a key and using a local unixdict.txt file."


def in_carpet(x, y):
    while True:
        if x == 0 or y == 0:
            return True
        elif x % 3 == 1 and y % 3 == 1:
            return False

        x /= 3
        y /= 3

def carpet(n):
    for i in xrange(3 ** n):
        for j in xrange(3 ** n):
            if in_carpet(i, j):
                print '*',
            else:
                print ' ',
        print

Translation of: Ruby
def sierpinski_carpet(n):
  carpet = ["#"]
  for i in xrange(n):
    carpet = [x + x + x for x in carpet] + \
             [x + x.replace("#"," ") + x for x in carpet] + \
             [x + x + x for x in carpet]
  return "\n".join(carpet)

print sierpinski_carpet(3)

Translation of: Haskell
Works with: Python version 3.7
'''Iterations of the Sierpinski carpet'''

from itertools import chain, islice
from inspect import signature
from operator import add

# sierpinskiCarpet :: Int -> [String]
def sierpinskiCarpet(n):
    '''A string representing the nth
       iteration of a Sierpinski carpet.
    '''
    f = zipWith(add)
    g = flip(f)

    # weave :: [String] -> [String]
    def weave(xs):
        return bind([
            xs,
            [' ' * len(s) for s in xs],
            xs
        ])(compose(g(xs))(f(xs)))

    return index(
        iterate(weave)(['▓▓'])
    )(n)

# TEST ----------------------------------------------------
def main():
    '''Test iteration of the Sierpinski carpet'''

    levels = enumFromTo(0)(3)
    t = ' ' * (
        len(' -> ') +
        max(map(compose(len)(str), levels))
    )
    print(
        fTable(__doc__ + ':')(lambda x: '\n' + str(x))(
            lambda xs: xs[0] + '\n' + (
                unlines(map(lambda x: t + x, xs[1:])))
        )
        (sierpinskiCarpet)(levels)
    )

# GENERIC -------------------------------------------------

# bind (>>=) :: [a] -> (a -> [b]) -> [b]
def bind(xs):
    '''List monad injection operator.
       Two computations sequentially composed,
       with any value produced by the first
       passed as an argument to the second.'''
    return lambda f: list(chain.from_iterable(
        map(f, xs)
    ))

# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
    '''Right to left function composition.'''
    return lambda f: lambda x: g(f(x))

# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
    '''Integer enumeration from m to n.'''
    return lambda n: list(range(m, 1 + n))

# flip :: (a -> b -> c) -> b -> a -> c
def flip(f):
    '''The (curried or uncurried) function f with its
       arguments reversed.'''
    if 1 < len(signature(f).parameters):
        return lambda a, b: f(b, a)
    else:
        return lambda a: lambda b: f(b)(a)

# index (!!) :: [a] -> Int -> a
def index(xs):
    '''Item at given (zero-based) index.'''
    return lambda n: None if 0 > n else (
        xs[n] if (
            hasattr(xs, "__getitem__")
        ) else next(islice(xs, n, None))
    )

# iterate :: (a -> a) -> a -> Gen [a]
def iterate(f):
    '''An infinite list of repeated
       applications of f to x.
    '''
    def go(x):
        v = x
        while True:
            yield v
            v = f(v)
    return lambda x: go(x)

# unlines :: [String] -> String
def unlines(xs):
    '''A single string derived by the intercalation
       of a list of strings with the newline character.'''
    return '\n'.join(xs)

# zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
def zipWith(f):
    '''A list constructed by zipping with a
       custom function, rather than with the
       default tuple constructor.'''
    return lambda xs: lambda ys: (
        map(f, xs, ys)
    )

# OUTPUT FORMATTING ---------------------------------------

# fTable :: String -> (a -> String) ->
#                     (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
    '''Heading -> x display function -> fx display function ->
                     f -> xs -> tabular string.
    '''
    def go(xShow, fxShow, f, xs):
        ys = [xShow(x) for x in xs]
        w = max(map(len, ys))
        return s + '\n' + '\n'.join(map(
            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
            xs, ys
        ))
    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
        xShow, fxShow, f, xs
    )

# MAIN ---
if __name__ == '__main__':
    main()

generate an ASCII-art or graphical representation of a Sierpinski carpet of a given order N, where the placement of whitespace and non-whitespace characters is crucial. The non-whitespace characters can be any character, not necessarily '#'. The code also includes a version that defines a Sierpinski carpet weave declaratively using generic abstractions like zipWith and bind.


from heapq import heappush, heappop, heapify
from collections import defaultdict

def encode(symb2freq):
    """Huffman encode the given dict mapping symbols to weights"""
    heap = [[wt, [sym, ""]] for sym, wt in symb2freq.items()]
    heapify(heap)
    while len(heap) > 1:
        lo = heappop(heap)
        hi = heappop(heap)
        for pair in lo[1:]:
            pair[1] = '0' + pair[1]
        for pair in hi[1:]:
            pair[1] = '1' + pair[1]
        heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])
    return sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p))

txt = "this is an example for huffman encoding"
symb2freq = defaultdict(int)
for ch in txt:
    symb2freq[ch] += 1
# in Python 3.1+:
# symb2freq = collections.Counter(txt)
huff = encode(symb2freq)
print "Symbol\tWeight\tHuffman Code"
for p in huff:
    print "%s\t%s\t%s" % (p[0], symb2freq[p[0]], p[1])

The code generates a Huffman encoding for each character in a given string. It first creates a tree of nodes based on the frequency of each character, with higher frequency characters having fewer bits in their encoding. The code then traverses the binary tree from root to leaves, assigning and accumulating a '0' for one branch and a '1' for the other at each node. The accumulated zeros and ones at each leaf constitute the Huffman encoding for those characters. The output is a table of characters and their corresponding Huffman encoding, sorted first on length of the code, then on the symbols. The code also includes a method for handling end of file symbols and padding bits for file operations.


Library: Tkinter[edit]
Works with: Python version 3.7
from functools import partial
import tkinter as tk

def on_click(label: tk.Label,
             counter: tk.IntVar) -> None:
    counter.set(counter.get() + 1)
    label["text"] = f"Number of clicks: {counter.get()}"

def main():
    window = tk.Tk()
    window.geometry("200x50+100+100")
    label = tk.Label(master=window,
                     text="There have been no clicks yet")
    label.pack()
    counter = tk.IntVar()
    update_counter = partial(on_click,
                             label=label,
                             counter=counter)
    button = tk.Button(master=window,
                       text="click me",
                       command=update_counter)
    button.pack()
    window.mainloop()

if __name__ == '__main__':
    main()

import tkinter as tk

class ClickCounter(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        tk.Pack.config(self)
        self.label = tk.Label(self, text='There have been no clicks yet')
        self.label.pack()
        self.button = tk.Button(self,
                                text='click me',
                                command=self.click)
        self.button.pack()
        self.count = 0

    def click(self):
        self.count += 1
        self.label['text'] = f'Number of clicks: {self.count}'

if __name__ == "__main__":
    ClickCounter().mainloop()

Library: PyQt[edit]
from functools import partial
from itertools import count

from PyQt5.QtWidgets import (QApplication,
                             QLabel,
                             QPushButton,
                             QWidget)
from PyQt5.QtCore import QRect

LABEL_GEOMETRY = QRect(0, 15, 200, 25)
BUTTON_GEOMETRY = QRect(50, 50, 100, 25)

def on_click(_, label, counter=count(1)):
    label.setText(f"Number of clicks: {next(counter)}")

def main():
    application = QApplication([])
    window = QWidget()
    label = QLabel(text="There have been no clicks yet",
                   parent=window)
    label.setGeometry(LABEL_GEOMETRY)
    button = QPushButton(text="click me",
                         parent=window)
    button.setGeometry(BUTTON_GEOMETRY)
    update_counter = partial(on_click,
                             label=label)
    button.clicked.connect(update_counter)
    window.show()
    application.lastWindowClosed.connect(window.close)
    application.exec_()

if __name__ == '__main__':
    main()

Library: wxPython[edit]
import wx

class ClickCounter(wx.Frame):
    def __init__(self):
        super().__init__(parent=None)
        self.count = 0
        self.button = wx.Button(parent=self,
                                label="Click me!")
        self.label = wx.StaticText(parent=self,
                                   label="There have been no clicks yet")
        self.Bind(event=wx.EVT_BUTTON,
                  handler=self.click,
                  source=self.button)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(window=self.button,
                       proportion=1,
                       flag=wx.EXPAND)
        self.sizer.Add(window=self.label,
                       proportion=1,
                       flag=wx.EXPAND)
        self.SetSizer(self.sizer)
        self.sizer.Fit(self)

    def click(self, _):
        self.count += 1
        self.label.SetLabel(f"Count: {self.count}")

if __name__ == '__main__':
    app = wx.App()
    frame = ClickCounter()
    frame.Show()
    app.MainLoop()

implement a windowed application with a label and a button. The label initially displays "There have been no clicks yet". When the button labeled "click me" is clicked, the label updates to show the number of times the button has been clicked.


for i in xrange(10, -1, -1):
    print i
List comprehension[edit]
[i for i in xrange(10, -1, -1)]
import pprint
pprint.pprint([i for i in xrange(10, -1, -1)])

The code performs a countdown from 10 to 0 using a downward for loop.


Works with: Python version 3
Translation of: Haskell
'''Vigenere encryption and decryption'''

from itertools import starmap, cycle

def encrypt(message, key):
    '''Vigenere encryption of message using key.'''

    # Converted to uppercase.
    # Non-alpha characters stripped out.
    message = filter(str.isalpha, message.upper())

    def enc(c, k):
        '''Single letter encryption.'''

        return chr(((ord(k) + ord(c) - 2 * ord('A')) % 26) + ord('A'))

    return ''.join(starmap(enc, zip(message, cycle(key))))

def decrypt(message, key):
    '''Vigenere decryption of message using key.'''

    def dec(c, k):
        '''Single letter decryption.'''

        return chr(((ord(c) - ord(k) - 2 * ord('A')) % 26) + ord('A'))

    return ''.join(starmap(dec, zip(message, cycle(key))))

def main():
    '''Demonstration'''

    text = 'Beware the Jabberwock, my son! The jaws that bite, ' + (
           'the claws that catch!'
    )
    key = 'VIGENERECIPHER'

    encr = encrypt(text, key)
    decr = decrypt(encr, key)

    print(text)
    print(encr)
    print(decr)

if __name__ == '__main__':
    main()

Implement both encryption and decryption of a Vigenère cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. Any different handling of non-alphabetic characters is noted.


Works with: Python version 2.x
for i in xrange(2, 9, 2):
    print "%d," % i,
print "who do we appreciate?"
Works with: Python version 3.x
for i in range(2, 9, 2):
    print("%d, " % i, end="")
print("who do we appreciate?")

demonstrate a for-loop with a step-value greater than one.


class Ref(object):
    def __init__(self, value=None):
        self.value = value

def harmonic_sum(i, lo, hi, term):
    # term is passed by-name, and so is i
    temp = 0
    i.value = lo
    while i.value <= hi:  # Python "for" loop creates a distinct which
        temp += term() # would not be shared with the passed "i"
        i.value += 1   # Here the actual passed "i" is incremented.
    return temp

i = Ref()

# note the correspondence between the mathematical notation and the
# call to sum it's almost as good as sum(1/i for i in range(1,101))
print harmonic_sum(i, 1, 100, lambda: 1.0/i.value)

def harmonic_sum(i, lo, hi, term):
    return sum(term() for i[0] in range(lo, hi + 1))

i = [0]
print(harmonic_sum(i, 1, 100, lambda: 1.0 / i[0]))

def harmonic_sum(i, lo, hi, term):
    return sum(eval(term) for i[0] in range(lo, hi + 1))

i = [0]
print(harmonic_sum(i, 1, 100, "1.0 / i[0]"))

"Implement Jensen's Device, a programming technique that illustrates the concept of call by name. The code calculates the 100th harmonic number using a sum procedure that takes four parameters. It exploits call by name to re-evaluate an expression passed as a parameter in the caller's context every time the corresponding formal parameter's value is required. The result is the correct harmonic number, 5.18737751764."


Library: PIL
import Image, ImageDraw

image = Image.new("RGB", (256, 256))
drawingTool = ImageDraw.Draw(image)

for x in range(256):
    for y in range(256):
        drawingTool.point((x, y), (0, x^y, 0))

del drawingTool
image.save("xorpic.png", "PNG")

generate a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, as described in the Munching Squares programming task.


from random import shuffle, randrange

def make_maze(w = 16, h = 8):
    vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
    ver = [["|  "] * w + ['|'] for _ in range(h)] + [[]]
    hor = [["+--"] * w + ['+'] for _ in range(h + 1)]

    def walk(x, y):
        vis[y][x] = 1

        d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
        shuffle(d)
        for (xx, yy) in d:
            if vis[yy][xx]: continue
            if xx == x: hor[max(y, yy)][x] = "+  "
            if yy == y: ver[y][max(x, xx)] = "   "
            walk(xx, yy)

    walk(randrange(w), randrange(h))

    s = ""
    for (a, b) in zip(hor, ver):
        s += ''.join(a + ['\n'] + b + ['\n'])
    return s

if __name__ == '__main__':
    print(make_maze())

generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.


are designed to continuously calculate and output the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. The calculation of Pi is not based on any built-in constants or functions.


"Function to compare two numerical lists lexicographically and return true if the first list should be ordered before the second, false otherwise."


Python: Explicitly recursive[edit]
Works with: Python version 2.5
def ack1(M, N):
   return (N + 1) if M == 0 else (
      ack1(M-1, 1) if N == 0 else ack1(M-1, ack1(M, N-1)))

from functools import lru_cache

@lru_cache(None)
def ack2(M, N):
    if M == 0:
        return N + 1
    elif N == 0:
        return ack2(M - 1, 1)
    else:
        return ack2(M - 1, ack2(M, N - 1))

Example of use:
>>> import sys
>>> sys.setrecursionlimit(3000)
>>> ack1(0,0)
1
>>> ack1(3,4)
125
>>> ack2(0,0)
1
>>> ack2(3,4)
125

def ack2(M, N):
   return (N + 1)   if M == 0 else (
          (N + 2)   if M == 1 else (
          (2*N + 3) if M == 2 else (
          (8*(2**N - 1) + 5) if M == 3 else (
          ack2(M-1, 1) if N == 0 else ack2(M-1, ack2(M, N-1))))))

Python: Without recursive function calls[edit]

from collections import deque

def ack_ix(m, n):
    "Paddy3118's iterative with optimisations on m"

    stack = deque([])
    stack.extend([m, n])

    while  len(stack) > 1:
        n, m = stack.pop(), stack.pop()

        if   m == 0:
            stack.append(n + 1)
        elif m == 1:
            stack.append(n + 2)
        elif m == 2:
            stack.append(2*n + 3)
        elif m == 3:
            stack.append(2**(n + 3) - 3)
        elif n == 0:
            stack.extend([m-1, 1])
        else:
            stack.extend([m-1, m, n-1])

    return stack[0]

Implement the Ackermann function, a non-primitive recursive function that always terminates and never takes negative arguments. The function returns the value of A(m, n) with preferred arbitrary precision due to its rapid growth. The implementation also confirms results with Mathematica for ack(4,1) and ack(4,2). The function uses an explicit stack to replace explicit recursive function calls.


implement an algorithm to compute the Gamma function using numerical integration, Lanczos approximation, or Stirling's approximation. It also compares the results with built-in/library function if available.


Python: Raymond Hettingers permutations based solution[edit]

from itertools import permutations

n = 8
cols = range(n)
for vec in permutations(cols):
    if n == len(set(vec[i]+i for i in cols)) \
         == len(set(vec[i]-i for i in cols)):
        print ( vec )

def board(vec):
    print ("\n".join('.' * i + 'Q' + '.' * (n-i-1) for i in vec) + "\n===\n")

With the solution represented as a vector with one queen in each row, we don't have to check to see if two queens are on the same row. By using a permutation generator, we know that no value in the vector is repeated, so we don't have to check to see if two queens are on the same column. Since rook moves don't need to be checked, we only need to check bishop moves.
The technique for checking the diagonals is to add or subtract the column number from each entry, so any two entries on the same diagonal will have the same value (in other words, the sum or difference is unique for each diagonal). Now all we have to do is make sure that the diagonals for each of the eight queens are distinct. So, we put them in a set (which eliminates duplicates) and check that the set length is eight (no duplicates were removed).
Any permutation with non-overlapping diagonals is a solution. So, we print it and continue checking other permutations.

Python: Alternative Solution[edit]

Works with: Python version 2.6, 3.x
# From: http://wiki.python.org/moin/SimplePrograms, with permission from the author, Steve Howell
BOARD_SIZE = 8

def under_attack(col, queens):
    return col in queens or \
           any(abs(col - x) == len(queens)-i for i,x in enumerate(queens))

def solve(n):
    solutions = [[]]
    for row in range(n):
        solutions = [solution+[i+1]
                       for solution in solutions
                       for i in range(BOARD_SIZE)
                       if not under_attack(i+1, solution)]
    return solutions

for answer in solve(BOARD_SIZE): print(list(enumerate(answer, start=1)))
Python: Simple Backtracking Solution[edit]

Works with: Python version 2.6, 3.x
BOARD_SIZE = 8

def under_attack(col, queens):
    return col in queens or \
           any(abs(col - x) == len(queens)-i for i,x in enumerate(queens))

def solve(n):
    solutions = [[]]
    for row in range(n):
        solutions = (solution+[i+1]
                       for solution in solutions # first for clause is evaluated immediately,
                                                 # so "solutions" is correctly captured
                       for i in range(BOARD_SIZE)
                       if not under_attack(i+1, solution))
    return solutions

answers = solve(BOARD_SIZE)
first_answer = next(answers)
print(list(enumerate(first_answer, start=1)))
Python: Simple Backtracking Solution (Niklaus Wirth Algorithm)[edit]

def queens(n, i, a, b, c):
    if i < n:
        for j in range(n):
            if j not in a and i + j not in b and i - j not in c:
                yield from queens(n, i + 1, a + [j], b + [i + j], c + [i - j])
    else:
        yield a

for solution in queens(8, 0, [], [], []):
    print(solution)

def queens(x, i, a, b, c):
    if a:  # a is not empty
        for j in a:
            if i + j not in b and i - j not in c:
                yield from queens(x + [j], i + 1, a - {j}, b | {i + j}, c | {i - j})
    else:
        yield x

for solution in queens([], 0, set(range(8)), set(), set()):
    print(solution)
Python: backtracking on permutations[edit]

def queens(n):
    a = list(range(n))
    up = [True]*(2*n - 1)
    down = [True]*(2*n - 1)
    def sub(i):
        if i == n:
            yield tuple(a)
        else:
            for k in range(i, n):
                j = a[k]
                p = i + j
                q = i - j + n - 1
                if up[p] and down[q]:
                    up[p] = down[q] = False
                    a[i], a[k] = a[k], a[i]
                    yield from sub(i + 1)
                    up[p] = down[q] = True
                    a[i], a[k] = a[k], a[i]
    yield from sub(0)

#Count solutions for n=8:
sum(1 for p in queens(8))
92

def queens_lex(n):
    a = list(range(n))
    up = [True]*(2*n - 1)
    down = [True]*(2*n - 1)
    def sub(i):
        if i == n:
            yield tuple(a)
        else:
            for k in range(i, n):
                a[i], a[k] = a[k], a[i]
                j = a[i]
                p = i + j
                q = i - j + n - 1
                if up[p] and down[q]:
                    up[p] = down[q] = False
                    yield from sub(i + 1)
                    up[p] = down[q] = True
            x = a[i]
            for k in range(i + 1, n):
                a[k - 1] = a[k]
            a[n - 1] = x
    yield from sub(0)

next(queens(31))
(0, 2, 4, 1, 3, 8, 10, 12, 14, 6, 17, 21, 26, 28, 25, 27, 24, 30, 7, 5, 29, 15, 13, 11, 9, 18, 22, 19, 23, 16, 20)

next(queens_lex(31))
(0, 2, 4, 1, 3, 8, 10, 12, 14, 5, 17, 22, 25, 27, 30, 24, 26, 29, 6, 16, 28, 13, 9, 7, 19, 11, 15, 18, 21, 23, 20)

#Compare to A065188
#1, 3, 5, 2, 4, 9, 11, 13, 15, 6, 8, 19, 7, 22, 10, 25, 27, 29, 31, 12, 14, 35, 37, ...
Python: fold/reduce[edit]

Works with: Python version 3.7
'''N Queens problem'''

from functools import reduce
from itertools import chain

# queenPuzzle :: Int -> Int -> [[Int]]
def queenPuzzle(nCols):
    '''All board patterns of this dimension
       in which no two Queens share a row,
       column, or diagonal.
    '''
    def go(nRows):
        lessRows = nRows - 1
        return reduce(
            lambda a, xys: a + reduce(
                lambda b, iCol: b + [xys + [iCol]] if (
                    safe(lessRows, iCol, xys)
                ) else b,
                enumFromTo(1)(nCols),
                []
            ),
            go(lessRows),
            []
        ) if 0 < nRows else [[]]
    return go

# safe :: Int -> Int -> [Int] -> Bool
def safe(iRow, iCol, pattern):
    '''True if no two queens in the pattern
       share a row, column or diagonal.
    '''
    def p(sc, sr):
        return (iCol == sc) or (
            sc + sr == (iCol + iRow)
        ) or (sc - sr == (iCol - iRow))
    return not any(map(p, pattern, range(0, iRow)))

# ------------------------- TEST -------------------------
# main :: IO ()
def main():
    '''Number of solutions for boards of various sizes'''

    n = 5
    xs = queenPuzzle(n)(n)

    print(
        str(len(xs)) + ' solutions for a {n} * {n} board:\n'.format(n=n)
    )
    print(showBoards(10)(xs))

    print(
        fTable(
            '\n\n' + main.__doc__ + ':\n'
        )(str)(lambda n: str(n).rjust(3, ' '))(
            lambda n: len(queenPuzzle(n)(n))
        )(enumFromTo(1)(10))
    )

# ---------------------- FORMATTING ----------------------

# showBoards :: Int -> [[Int]] -> String
def showBoards(nCols):
    '''String representation, with N columns
       of a set of board patterns.
    '''
    def showBlock(b):
        return '\n'.join(map(intercalate('  '), zip(*b)))

    def go(bs):
        return '\n\n'.join(map(
            showBlock,
            chunksOf(nCols)([
                showBoard(b) for b in bs
            ])
        ))
    return go

# showBoard :: [Int] -> String
def showBoard(xs):
    '''String representation of a Queens board.'''
    lng = len(xs)

    def showLine(n):
        return ('.' * (n - 1)) + '♛' + ('.' * (lng - n))
    return map(showLine, xs)

# fTable :: String -> (a -> String) ->
#                     (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
    '''Heading -> x display function -> fx display function ->
                     f -> xs -> tabular string.
    '''
    def go(xShow, fxShow, f, xs):
        ys = [xShow(x) for x in xs]
        w = max(map(len, ys))
        return s + '\n' + '\n'.join(map(
            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
            xs, ys
        ))
    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
        xShow, fxShow, f, xs
    )

# ----------------------- GENERIC ------------------------

# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
    '''Integer enumeration from m to n.'''
    return lambda n: range(m, 1 + n)

# chunksOf :: Int -> [a] -> [[a]]
def chunksOf(n):
    '''A series of lists of length n, subdividing the
       contents of xs. Where the length of xs is not evenly
       divible, the final list will be shorter than n.
    '''
    return lambda xs: reduce(
        lambda a, i: a + [xs[i:n + i]],
        range(0, len(xs), n), []
    ) if 0 < n else []

# intercalate :: [a] -> [[a]] -> [a]
# intercalate :: String -> [String] -> String
def intercalate(x):
    '''The concatenation of xs
       interspersed with copies of x.
    '''
    return lambda xs: x.join(xs) if isinstance(x, str) else list(
        chain.from_iterable(
            reduce(lambda a, v: a + [x, v], xs[1:], [xs[0]])
        )
    ) if xs else []

# MAIN ---
if __name__ == '__main__':
    main()

The code solves the N-queens puzzle by generating all possible solutions. It uses the itertools module and presents the output in vector form. The code also includes a backtracking solution and a translation of Niklaus Wirth's solution into Python. The algorithm can be improved by using sets instead of lists. The solutions are returned as a generator and the code allows for graphic display of results. It also lists the number of solutions found for boards of various sizes.


demonstrate how to concatenate two arrays in the given language, either using the + operator or the list.extend method, which is typically implemented with the += operator.


Brute force algorithm[edit]
from itertools import combinations

def anycomb(items):
    ' return combinations of any length from the items '
    return ( comb
             for r in range(1, len(items)+1)
             for comb in combinations(items, r)
             )

def totalvalue(comb):
    ' Totalise a particular combination of items'
    totwt = totval = 0
    for item, wt, val in comb:
        totwt  += wt
        totval += val
    return (totval, -totwt) if totwt <= 400 else (0, 0)

items = (
    ("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160),
    ("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40),
    ("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30),
    ("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40),
    ("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75),
    ("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12),
    ("socks", 4, 50), ("book", 30, 10),
    )
bagged = max( anycomb(items), key=totalvalue) # max val or min wt if values equal
print("Bagged the following items\n  " +
      '\n  '.join(sorted(item for item,_,_ in bagged)))
val, wt = totalvalue(bagged)
print("for a total value of %i and a total weight of %i" % (val, -wt))

The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (or 400 dag). It considers the weight and value of each item, ensuring the total weight does not exceed the limit and the total value is maximized. The code uses the 0-1 Knapsack problem approach, reducing the number of comparisons from N! to 2^N. It does not allow for cutting or diminishing the items.


import copy

guyprefers = {
 'abe':  ['abi', 'eve', 'cath', 'ivy', 'jan', 'dee', 'fay', 'bea', 'hope', 'gay'],
 'bob':  ['cath', 'hope', 'abi', 'dee', 'eve', 'fay', 'bea', 'jan', 'ivy', 'gay'],
 'col':  ['hope', 'eve', 'abi', 'dee', 'bea', 'fay', 'ivy', 'gay', 'cath', 'jan'],
 'dan':  ['ivy', 'fay', 'dee', 'gay', 'hope', 'eve', 'jan', 'bea', 'cath', 'abi'],
 'ed':   ['jan', 'dee', 'bea', 'cath', 'fay', 'eve', 'abi', 'ivy', 'hope', 'gay'],
 'fred': ['bea', 'abi', 'dee', 'gay', 'eve', 'ivy', 'cath', 'jan', 'hope', 'fay'],
 'gav':  ['gay', 'eve', 'ivy', 'bea', 'cath', 'abi', 'dee', 'hope', 'jan', 'fay'],
 'hal':  ['abi', 'eve', 'hope', 'fay', 'ivy', 'cath', 'jan', 'bea', 'gay', 'dee'],
 'ian':  ['hope', 'cath', 'dee', 'gay', 'bea', 'abi', 'fay', 'ivy', 'jan', 'eve'],
 'jon':  ['abi', 'fay', 'jan', 'gay', 'eve', 'bea', 'dee', 'cath', 'ivy', 'hope']}
galprefers = {
 'abi':  ['bob', 'fred', 'jon', 'gav', 'ian', 'abe', 'dan', 'ed', 'col', 'hal'],
 'bea':  ['bob', 'abe', 'col', 'fred', 'gav', 'dan', 'ian', 'ed', 'jon', 'hal'],
 'cath': ['fred', 'bob', 'ed', 'gav', 'hal', 'col', 'ian', 'abe', 'dan', 'jon'],
 'dee':  ['fred', 'jon', 'col', 'abe', 'ian', 'hal', 'gav', 'dan', 'bob', 'ed'],
 'eve':  ['jon', 'hal', 'fred', 'dan', 'abe', 'gav', 'col', 'ed', 'ian', 'bob'],
 'fay':  ['bob', 'abe', 'ed', 'ian', 'jon', 'dan', 'fred', 'gav', 'col', 'hal'],
 'gay':  ['jon', 'gav', 'hal', 'fred', 'bob', 'abe', 'col', 'ed', 'dan', 'ian'],
 'hope': ['gav', 'jon', 'bob', 'abe', 'ian', 'dan', 'hal', 'ed', 'col', 'fred'],
 'ivy':  ['ian', 'col', 'hal', 'gav', 'fred', 'bob', 'abe', 'ed', 'jon', 'dan'],
 'jan':  ['ed', 'hal', 'gav', 'abe', 'bob', 'jon', 'col', 'ian', 'fred', 'dan']}

guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())

def check(engaged):
    inverseengaged = dict((v,k) for k,v in engaged.items())
    for she, he in engaged.items():
        shelikes = galprefers[she]
        shelikesbetter = shelikes[:shelikes.index(he)]
        helikes = guyprefers[he]
        helikesbetter = helikes[:helikes.index(she)]
        for guy in shelikesbetter:
            guysgirl = inverseengaged[guy]
            guylikes = guyprefers[guy]
            if guylikes.index(guysgirl) > guylikes.index(she):
                print("%s and %s like each other better than "
                      "their present partners: %s and %s, respectively"
                      % (she, guy, he, guysgirl))
                return False
        for gal in helikesbetter:
            girlsguy = engaged[gal]
            gallikes = galprefers[gal]
            if gallikes.index(girlsguy) > gallikes.index(he):
                print("%s and %s like each other better than "
                      "their present partners: %s and %s, respectively"
                      % (he, gal, she, girlsguy))
                return False
    return True

def matchmaker():
    guysfree = guys[:]
    engaged  = {}
    guyprefers2 = copy.deepcopy(guyprefers)
    galprefers2 = copy.deepcopy(galprefers)
    while guysfree:
        guy = guysfree.pop(0)
        guyslist = guyprefers2[guy]
        gal = guyslist.pop(0)
        fiance = engaged.get(gal)
        if not fiance:
            # She's free
            engaged[gal] = guy
            print("  %s and %s" % (guy, gal))
        else:
            # The bounder proposes to an engaged lass!
            galslist = galprefers2[gal]
            if galslist.index(fiance) > galslist.index(guy):
                # She prefers new guy
                engaged[gal] = guy
                print("  %s dumped %s for %s" % (gal, fiance, guy))
                if guyprefers2[fiance]:
                    # Ex has more girls to try
                    guysfree.append(fiance)
            else:
                # She is faithful to old fiance
                if guyslist:
                    # Look again
                    guysfree.append(guy)
    return engaged

print('\nEngagements:')
engaged = matchmaker()

print('\nCouples:')
print('  ' + ',\n  '.join('%s is engaged to %s' % couple
                          for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
      if check(engaged) else 'Engagement stability check FAILED')

print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
    print('  %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
      if check(engaged) else 'Engagement stability check FAILED')

"Implement the Gale-Shapley algorithm to solve the Stable Marriage problem. The program takes as input the preferences of ten men and ten women, and outputs a stable set of engagements. It then perturbs this set to form an unstable set of engagements and checks this new set for stability."


>>> def a(answer):
	print("  # Called function a(%r) -> %r" % (answer, answer))
	return answer

>>> def b(answer):
	print("  # Called function b(%r) -> %r" % (answer, answer))
	return answer

>>> for i in (False, True):
	for j in (False, True):
		print ("\nCalculating: x = a(i) and b(j)")
		x = a(i) and b(j)
		print ("Calculating: y = a(i) or  b(j)")
		y = a(i) or  b(j)

Calculating: x = a(i) and b(j)
  # Called function a(False) -> False
Calculating: y = a(i) or  b(j)
  # Called function a(False) -> False
  # Called function b(False) -> False

Calculating: x = a(i) and b(j)
  # Called function a(False) -> False
Calculating: y = a(i) or  b(j)
  # Called function a(False) -> False
  # Called function b(True) -> True

Calculating: x = a(i) and b(j)
  # Called function a(True) -> True
  # Called function b(False) -> False
Calculating: y = a(i) or  b(j)
  # Called function a(True) -> True

Calculating: x = a(i) and b(j)
  # Called function a(True) -> True
  # Called function b(True) -> True
Calculating: y = a(i) or  b(j)
  # Called function a(True) -> True

>>> for i in (False, True):
	for j in (False, True):
		print ("\nCalculating: x = a(i) and b(j) using x = b(j) if a(i) else False")
		x = b(j) if a(i) else False
		print ("Calculating: y = a(i) or  b(j) using y = b(j) if not a(i) else True")
		y = b(j) if not a(i) else True

Calculating: x = a(i) and b(j) using x = b(j) if a(i) else False
  # Called function a(False) -> False
Calculating: y = a(i) or  b(j) using y = b(j) if not a(i) else True
  # Called function a(False) -> False
  # Called function b(False) -> False

Calculating: x = a(i) and b(j) using x = b(j) if a(i) else False
  # Called function a(False) -> False
Calculating: y = a(i) or  b(j) using y = b(j) if not a(i) else True
  # Called function a(False) -> False
  # Called function b(True) -> True

Calculating: x = a(i) and b(j) using x = b(j) if a(i) else False
  # Called function a(True) -> True
  # Called function b(False) -> False
Calculating: y = a(i) or  b(j) using y = b(j) if not a(i) else True
  # Called function a(True) -> True

Calculating: x = a(i) and b(j) using x = b(j) if a(i) else False
  # Called function a(True) -> True
  # Called function b(True) -> True
Calculating: y = a(i) or  b(j) using y = b(j) if not a(i) else True
  # Called function a(True) -> True

The code defines two functions, a and b, which take a boolean value as input, return the same value, and print their names when called. It then uses short-circuit evaluation to calculate the values of two boolean expressions, x = a(i) and b(j) and y = a(i) or b(j), in such a way that function b is only called when necessary. If the language does not support short-circuit evaluation, this is achieved using nested if statements.


<output> convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. </output>


Python: Iterative, with tests[edit]
'''
Note that this code is broken, e.g., it won't work when
blocks = [("A", "B"), ("A","C")] and the word is "AB", where the answer
should be True, but the code returns False.
'''
blocks = [("B", "O"),
          ("X", "K"),
          ("D", "Q"),
          ("C", "P"),
          ("N", "A"),
          ("G", "T"),
          ("R", "E"),
          ("T", "G"),
          ("Q", "D"),
          ("F", "S"),
          ("J", "W"),
          ("H", "U"),
          ("V", "I"),
          ("A", "N"),
          ("O", "B"),
          ("E", "R"),
          ("F", "S"),
          ("L", "Y"),
          ("P", "C"),
          ("Z", "M")]

def can_make_word(word, block_collection=blocks):
    """
    Return True if `word` can be made from the blocks in `block_collection`.

    >>> can_make_word("")
    False
    >>> can_make_word("a")
    True
    >>> can_make_word("bark")
    True
    >>> can_make_word("book")
    False
    >>> can_make_word("treat")
    True
    >>> can_make_word("common")
    False
    >>> can_make_word("squad")
    True
    >>> can_make_word("coNFused")
    True
    """
    if not word:
        return False

    blocks_remaining = block_collection[:]
    for char in word.upper():
        for block in blocks_remaining:
            if char in block:
                blocks_remaining.remove(block)
                break
        else:
            return False
    return True

if __name__ == "__main__":
    import doctest
    doctest.testmod()
    print(", ".join("'%s': %s" % (w, can_make_word(w)) for w in
                    ["", "a", "baRk", "booK", "treat",
                     "COMMON", "squad", "Confused"]))

The code implements a function that checks if a given word can be spelled using a predefined collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether the word can be formed or not. It also handles the case of an empty string input.


Python 3.x, 2.5 and later 2.x versions

>>> import hashlib
>>> # RFC 1321    test suite:
>>> tests = (
  (b"", 'd41d8cd98f00b204e9800998ecf8427e'),
  (b"a", '0cc175b9c0f1b6a831c399e269772661'),
  (b"abc", '900150983cd24fb0d6963f7d28e17f72'),
  (b"message digest", 'f96b697d7cb7938d525a2f31aaf161d0'),
  (b"abcdefghijklmnopqrstuvwxyz", 'c3fcd3d76192e4007dfb496cca67e13b'),
  (b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 'd174ab98d277d9f5a5611c2c9f419d9f'),
  (b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", '57edf4a22be3c955ac49da2e2107b67a') )
>>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden

>>>

Python 2.5 and later

>>> import hashlib
>>> print hashlib.md5("The quick brown fox jumped over the lazy dog's back").hexdigest()
e38ca1d920c4b8b8d3946b2c72f01680

Pre-2.5; removed in 3.x

>>> import md5
>>> print md5.md5("The quick brown fox jumped over the lazy dog's back").hexdigest()
e38ca1d920c4b8b8d3946b2c72f01680

"Encode a string using MD5 algorithm and optionally validate the implementation using IETF RFC (1321) test values. However, consider using stronger alternatives like SHA-256 or SHA-3 for production-grade cryptography due to MD5's known weaknesses."


sort a list of Object Identifiers (OIDs). OIDs are dot-separated strings of non-negative integers. The sorting is done lexicographically based on the numeric value of each field. The input is split and each part is mapped to an integer to prevent string comparison.


import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("localhost", 256))
sock.sendall("hello socket world")
sock.close()

opens a socket to localhost on port 256, sends the message "hello socket world", and then closes the socket.


Python: POSIX[edit]

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

sendemail(from_addr    = 'python@RC.net',
          to_addr_list = ['RC@gmail.com'],
          cc_addr_list = ['RC@xx.co.uk'],
          subject      = 'Howdy',
          message      = 'Howdy from a python function',
          login        = 'pythonuser',
          password     = 'XXXXX')

Sample Email received:
Message-ID: <4a4a1e78.0717d00a.1ba8.ffcfdbdd@xx.google.com>
Date: Tue, 30 Jun 2009 22:04:56 -0700 (PDT)
From: python@RC.net
To: RC@gmail.com
Cc: RC@xx.co.uk
Subject: Howdy

Howdy from a python function

Python: Windows[edit]

import win32com.client

def sendmail(to, title, body):
    olMailItem = 0
    ol = win32com.client.Dispatch("Outlook.Application")
    msg = ol.CreateItem(olMailItem)
    msg.To = to
    msg.Subject = title
    msg.Body = body
    msg.Send()
    ol.Quit()

sendmail("somebody@somewhere", "Title", "Hello")

The code defines a function for sending an email, allowing parameters to set the From, To, Cc addresses, the Subject, and the message text, with optional fields for server name and login details. It returns a dictionary of any addresses it couldn't forward to, while other connection issues raise errors. The solution is portable across different operating systems and has been tested on Windows and all POSIX platforms. It uses the Outlook COM server with the Pywin32 library.


import sys
for n in xrange(sys.maxint):
    print oct(n)

generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.


a, b = b, a

def swap(a, b):
    return b, a

implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. This function is designed to work with both statically and dynamically typed languages, with certain constraints for type compatibility. The function does not support swapping between incompatible types such as string and integer. The function also handles issues related to parametric polymorphism in static languages. In Python, the function returns a new pair with the elements' order switched, as tuples are immutable.


def is_palindrome(s):
  return s == s[::-1]

def is_palindrome(s):
  low = 0
  high = len(s) - 1
  while low < high:
    if not s[low].isalpha():
      low += 1
    elif not s[high].isalpha():
      high -= 1
    else:
      if s[low].lower() != s[high].lower():
        return False
      else:
        low += 1
        high -= 1
        return True

def is_palindrome_r(s):
  if len(s) <= 1:
    return True
  elif s[0] != s[-1]:
    return False
  else:
    return is_palindrome_r(s[1:-1])

def is_palindrome_r2(s):
  return not s or s[0] == s[-1] and is_palindrome_r2(s[1:-1])

def test(f, good, bad):
  assert all(f(x) for x in good)
  assert not any(f(x) for x in bad)
  print '%s passed all %d tests' % (f.__name__, len(good)+len(bad))

pals = ('', 'a', 'aa', 'aba', 'abba')
notpals = ('aA', 'abA', 'abxBa', 'abxxBa')
for ispal in is_palindrome, is_palindrome_r, is_palindrome_r2:
  test(ispal, pals, notpals)

def p_loop():
  import re, string
  re1=""       # Beginning of Regex
  re2=""       # End of Regex
  pal=raw_input("Please Enter a word or phrase: ")
  pd = pal.replace(' ','')
  for c in string.punctuation:
     pd = pd.replace(c,"")
  if pal == "" :
    return -1
  c=len(pd)   # Count of chars.
  loops = (c+1)/2
  for x in range(loops):
    re1 = re1 + "(\w)"
    if (c%2 == 1 and x == 0):
       continue
    p = loops - x
    re2 = re2 + "\\" + str(p)
  regex= re1+re2+"$"   # regex is like "(\w)(\w)(\w)\2\1$"
  #print(regex)  # To test regex before re.search
  m = re.search(r'^'+regex,pd,re.IGNORECASE)
  if (m):
     print("\n   "+'"'+pal+'"')
     print("   is a Palindrome\n")
     return 1
  else:
     print("Nope!")
     return 0

'''Palindrome detection'''

# isPalindrome :: String -> Bool
def isPalindrome(s):
    '''True if the string is unchanged under reversal.
       (The left half is a reflection of the right half)
    '''
    d, m = divmod(len(s), 2)
    return s[0:d] == s[d + m:][::-1]

# ------------------------- TEST -------------------------
# main :: IO ()
def main():
    '''Test'''

    print('\n'.join(
        f'{repr(s)} -> {isPalindrome(cleaned(s))}' for s in [
            "",
            "a",
            "ab",
            "aba",
            "abba",
            "In girum imus nocte et consumimur igni"
        ]
    ))

# cleaned :: String -> String
def cleaned(s):
    '''A lower-case copy of s, with spaces pruned.'''
    return [c.lower() for c in s if ' ' != c]

# MAIN ---
if __name__ == '__main__':
    main()

The code includes a function to check if a given sequence of characters is a palindrome. It supports Unicode characters and can detect inexact palindromes by ignoring white-space, punctuation, and case differences. The code uses string reversal technique and recursive function for palindrome detection. It also includes a test function for palindrome using regular expressions in Python 2.7 and a method to check the left half against a reflection of the right half. An unknown technique called "Twiddle Indexing" is also used.


demonstrate how to retrieve a specific environment variable from a process using the os.environ dictionary. The variables available may differ based on the system, but common ones on Unix include PATH, HOME, and USER.


Translation of: Javascript
# Aamrun, 11th July 2022

def F(n,x,y):
  if n==0:
    return x + y
  elif y==0:
    return x
  else:
    return F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y)

print("F(1,3,3) = ", F(1,3,3))

F(1,3,3) =  35

implement the Sudan function, a non-primitive recursive function. This function takes two inputs (x, y) and returns their sum for the base case. For other cases, it follows a specific recursive pattern as defined in the task.