title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Chaocipher
Python 3.7
Description: The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ;Task: Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
'''Chaocipher''' from itertools import chain, cycle, islice # chao :: String -> String -> Bool -> String -> String def chao(l): '''Chaocipher encoding or decoding for the given left and right 'wheels'. A ciphertext is returned if the boolean flag is True, and a plaintext if the flag is False. ''' def go(l, r, plain, xxs): if xxs: (src, dst) = (l, r) if plain else (r, l) (x, xs) = (xxs[0], xxs[1:]) def chaoProcess(n): return [dst[n]] + go( shifted(1)(14)(rotated(n, l)), compose(shifted(2)(14))(shifted(0)(26))( rotated(n, r) ), plain, xs ) return maybe('')(chaoProcess)( elemIndex(x)(src) ) else: return [] return lambda r: lambda plain: lambda xxs: concat(go( l, r, plain, xxs )) # rotated :: Int -> [a] -> [a] def rotated(z, s): '''Rotation of string s by z characters.''' return take(len(s))( drop(z)( cycle(s) ) ) # shifted :: Int -> Int -> [a] -> [a] def shifted(src): '''The string s with a set of its characters cyclically shifted from a source index to a destination index. ''' def go(dst, s): (a, b) = splitAt(dst)(s) (x, y) = splitAt(src)(a) return concat([x, rotated(1, y), b]) return lambda dst: lambda s: go(dst, s) # TEST ---------------------------------------------------- # main :: IO () def main(): '''Print the plain text, followed by a corresponding cipher text, and a decode of that cipher text. ''' chaoWheels = chao( "HXUCZVAMDSLKPEFJRIGTWOBNYQ" )( "PTLNBQDEOYSFAVZKGJRIHWXUMC" ) plainText = "WELLDONEISBETTERTHANWELLSAID" cipherText = chaoWheels(False)(plainText) print(plainText) print(cipherText) print( chaoWheels(True)(cipherText) ) # GENERIC ------------------------------------------------- # Just :: a -> Maybe a def Just(x): '''Constructor for an inhabited Maybe (option type) value. Wrapper containing the result of a computation. ''' return {'type': 'Maybe', 'Nothing': False, 'Just': x} # Nothing :: Maybe a def Nothing(): '''Constructor for an empty Maybe (option type) value. Empty wrapper returned where a computation is not possible. ''' return {'type': 'Maybe', 'Nothing': True} # compose (<<<) :: (b -> c) -> (a -> b) -> a -> c def compose(g): '''Right to left function composition.''' return lambda f: lambda x: g(f(x)) # concat :: [[a]] -> [a] # concat :: [String] -> String def concat(xs): '''The concatenation of all the elements in a list or iterable. ''' def f(ys): zs = list(chain(*ys)) return ''.join(zs) if isinstance(ys[0], str) else zs return ( f(xs) if isinstance(xs, list) else ( chain.from_iterable(xs) ) ) if xs else [] # drop :: Int -> [a] -> [a] # drop :: Int -> String -> String def drop(n): '''The sublist of xs beginning at (zero-based) index n. ''' def go(xs): if isinstance(xs, (list, tuple, str)): return xs[n:] else: take(n)(xs) return xs return lambda xs: go(xs) # elemIndex :: Eq a => a -> [a] -> Maybe Int def elemIndex(x): '''Just the index of the first element in xs which is equal to x, or Nothing if there is no such element. ''' def go(xs): try: return Just(xs.index(x)) except ValueError: return Nothing() return lambda xs: go(xs) # maybe :: b -> (a -> b) -> Maybe a -> b def maybe(v): '''Either the default value v, if m is Nothing, or the application of f to x, where m is Just(x). ''' return lambda f: lambda m: v if None is m or m.get('Nothing') else ( f(m.get('Just')) ) # splitAt :: Int -> [a] -> ([a], [a]) def splitAt(n): '''A tuple pairing the prefix of length n with the rest of xs. ''' return lambda xs: (xs[0:n], xs[n:]) # take :: Int -> [a] -> [a] # take :: Int -> String -> String def take(n): '''The prefix of xs of length n, or xs itself if n > length xs. ''' return lambda xs: ( xs[0:n] if isinstance(xs, (list, tuple)) else list(islice(xs, n)) ) # MAIN --- if __name__ == '__main__': main()
Chaos game
Python
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. ;Task Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. ;See also * The Game of Chaos
import argparse import random import shapely.geometry as geometry import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def main(args): # Styles plt.style.use("ggplot") # Creating figure fig = plt.figure() line, = plt.plot([], [], ".") # Limit axes plt.xlim(0, 1) plt.ylim(0, 1) # Titles title = "Chaos Game" plt.title(title) fig.canvas.set_window_title(title) # Getting data data = get_data(args.frames) # Creating animation line_ani = animation.FuncAnimation( fig=fig, func=update_line, frames=args.frames, fargs=(data, line), interval=args.interval, repeat=False ) # To save the animation install ffmpeg and uncomment # line_ani.save("chaos_game.gif") plt.show() def get_data(n): """ Get data to plot """ leg = 1 triangle = get_triangle(leg) cur_point = gen_point_within_poly(triangle) data = [] for _ in range(n): data.append((cur_point.x, cur_point.y)) cur_point = next_point(triangle, cur_point) return data def get_triangle(n): """ Create right triangle """ ax = ay = 0.0 a = ax, ay bx = 0.5 * n by = 0.75 * (n ** 2) b = bx, by cx = n cy = 0.0 c = cx, cy triangle = geometry.Polygon([a, b, c]) return triangle def gen_point_within_poly(poly): """ Generate random point inside given polygon """ minx, miny, maxx, maxy = poly.bounds while True: x = random.uniform(minx, maxx) y = random.uniform(miny, maxy) point = geometry.Point(x, y) if point.within(poly): return point def next_point(poly, point): """ Generate next point according to chaos game rules """ vertices = poly.boundary.coords[:-1] # Last point is the same as the first one random_vertex = geometry.Point(random.choice(vertices)) line = geometry.linestring.LineString([point, random_vertex]) return line.centroid def update_line(num, data, line): """ Update line with new points """ new_data = zip(*data[:num]) or [(), ()] line.set_data(new_data) return line, if __name__ == "__main__": arg_parser = argparse.ArgumentParser(description="Chaos Game by Suenweek (c) 2017") arg_parser.add_argument("-f", dest="frames", type=int, default=1000) arg_parser.add_argument("-i", dest="interval", type=int, default=10) main(arg_parser.parse_args())
Check Machin-like formulas
Python
Machin-like formulas are useful for efficiently computing numerical approximations for \pi ;Task: Verify the following Machin-like formulas are correct by calculating the value of '''tan''' (''right hand side)'' for each equation using exact arithmetic and showing they equal '''1''': : {\pi\over4} = \arctan{1\over2} + \arctan{1\over3} : {\pi\over4} = 2 \arctan{1\over3} + \arctan{1\over7} : {\pi\over4} = 4 \arctan{1\over5} - \arctan{1\over239} : {\pi\over4} = 5 \arctan{1\over7} + 2 \arctan{3\over79} : {\pi\over4} = 5 \arctan{29\over278} + 7 \arctan{3\over79} : {\pi\over4} = \arctan{1\over2} + \arctan{1\over5} + \arctan{1\over8} : {\pi\over4} = 4 \arctan{1\over5} - \arctan{1\over70} + \arctan{1\over99} : {\pi\over4} = 5 \arctan{1\over7} + 4 \arctan{1\over53} + 2 \arctan{1\over4443} : {\pi\over4} = 6 \arctan{1\over8} + 2 \arctan{1\over57} + \arctan{1\over239} : {\pi\over4} = 8 \arctan{1\over10} - \arctan{1\over239} - 4 \arctan{1\over515} : {\pi\over4} = 12 \arctan{1\over18} + 8 \arctan{1\over57} - 5 \arctan{1\over239} : {\pi\over4} = 16 \arctan{1\over21} + 3 \arctan{1\over239} + 4 \arctan{3\over1042} : {\pi\over4} = 22 \arctan{1\over28} + 2 \arctan{1\over443} - 5 \arctan{1\over1393} - 10 \arctan{1\over11018} : {\pi\over4} = 22 \arctan{1\over38} + 17 \arctan{7\over601} + 10 \arctan{7\over8149} : {\pi\over4} = 44 \arctan{1\over57} + 7 \arctan{1\over239} - 12 \arctan{1\over682} + 24 \arctan{1\over12943} : {\pi\over4} = 88 \arctan{1\over172} + 51 \arctan{1\over239} + 32 \arctan{1\over682} + 44 \arctan{1\over5357} + 68 \arctan{1\over12943} and confirm that the following formula is ''incorrect'' by showing '''tan''' (''right hand side)'' is ''not'' '''1''': : {\pi\over4} = 88 \arctan{1\over172} + 51 \arctan{1\over239} + 32 \arctan{1\over682} + 44 \arctan{1\over5357} + 68 \arctan{1\over12944} These identities are useful in calculating the values: : \tan(a + b) = {\tan(a) + \tan(b) \over 1 - \tan(a) \tan(b)} : \tan\left(\arctan{a \over b}\right) = {a \over b} : \tan(-a) = -\tan(a) You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that ''{-3 pi \over 4} < right hand side < {5 pi \over 4}'' due to ''\tan()'' periodicity.
import re from fractions import Fraction from pprint import pprint as pp equationtext = '''\ pi/4 = arctan(1/2) + arctan(1/3) pi/4 = 2*arctan(1/3) + arctan(1/7) pi/4 = 4*arctan(1/5) - arctan(1/239) pi/4 = 5*arctan(1/7) + 2*arctan(3/79) pi/4 = 5*arctan(29/278) + 7*arctan(3/79) pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8) pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99) pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443) pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239) pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515) pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239) pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042) pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018) pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149) pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943) pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943) pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944) ''' def parse_eqn(equationtext=equationtext): eqn_re = re.compile(r"""(?mx) (?P<lhs> ^ \s* pi/4 \s* = \s*)? # LHS of equation (?: # RHS \s* (?P<sign> [+-])? \s* (?: (?P<mult> \d+) \s* \*)? \s* arctan\( (?P<numer> \d+) / (?P<denom> \d+) )""") found = eqn_re.findall(equationtext) machins, part = [], [] for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext): if lhs and part: machins.append(part) part = [] part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1), Fraction(int(numer), (int(denom) if denom else 1)) ) ) machins.append(part) return machins def tans(xs): xslen = len(xs) if xslen == 1: return tanEval(*xs[0]) aa, bb = xs[:xslen//2], xs[xslen//2:] a, b = tans(aa), tans(bb) return (a + b) / (1 - a * b) def tanEval(coef, f): if coef == 1: return f if coef < 0: return -tanEval(-coef, f) ca = coef // 2 cb = coef - ca a, b = tanEval(ca, f), tanEval(cb, f) return (a + b) / (1 - a * b) if __name__ == '__main__': machins = parse_eqn() #pp(machins, width=160) for machin, eqn in zip(machins, equationtext.split('\n')): ans = tans(machin) print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))
Check input device is a terminal
Python
Demonstrate how to check whether the input device is a terminal or not. ;Related task: * [[Check output device is a terminal]]
from sys import stdin if stdin.isatty(): print("Input comes from tty.") else: print("Input doesn't come from tty.")
Check output device is a terminal
Python
Demonstrate how to check whether the output device is a terminal or not. ;Related task: * [[Check input device is a terminal]]
from sys import stdout if stdout.isatty(): print 'The output device is a teletype. Or something like a teletype.' else: print 'The output device isn\'t like a teletype.'
Cheryl's birthday
Python 3
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. ;Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. ;Related task: * [[Sum and Product Puzzle]] ;References * Wikipedia article of the same name. * Tuple Relational Calculus
'''Cheryl's Birthday''' from itertools import groupby from re import split # main :: IO () def main(): '''Derivation of the date.''' month, day = 0, 1 print( # (3 :: A "Then I also know") # (A's month contains only one remaining day) uniquePairing(month)( # (2 :: B "I know now") # (B's day is paired with only one remaining month) uniquePairing(day)( # (1 :: A "I know that Bernard does not know") # (A's month is not among those with unique days) monthsWithUniqueDays(False)([ # 0 :: Cheryl's list: tuple(x.split()) for x in split( ', ', 'May 15, May 16, May 19, ' + 'June 17, June 18, ' + 'July 14, July 16, ' + 'Aug 14, Aug 15, Aug 17' ) ]) ) ) ) # ------------------- QUERY FUNCTIONS -------------------- # monthsWithUniqueDays :: Bool -> [(Month, Day)] -> [(Month, Day)] def monthsWithUniqueDays(blnInclude): '''The subset of months with (or without) unique days. ''' def go(xs): month, day = 0, 1 months = [fst(x) for x in uniquePairing(day)(xs)] return [ md for md in xs if blnInclude or not (md[month] in months) ] return go # uniquePairing :: DatePart -> [(Month, Day)] -> [(Month, Day)] def uniquePairing(i): '''Subset of months (or days) with a unique intersection. ''' def go(xs): def inner(md): dct = md[i] uniques = [ k for k in dct.keys() if 1 == len(dct[k]) ] return [tpl for tpl in xs if tpl[i] in uniques] return inner return ap(bindPairs)(go) # bindPairs :: [(Month, Day)] -> # ((Dict String [String], Dict String [String]) # -> [(Month, Day)]) -> [(Month, Day)] def bindPairs(xs): '''List monad injection operator for lists of (Month, Day) pairs. ''' return lambda f: f( ( dictFromPairs(xs), dictFromPairs( [(b, a) for (a, b) in xs] ) ) ) # dictFromPairs :: [(Month, Day)] -> Dict Text [Text] def dictFromPairs(xs): '''A dictionary derived from a list of month day pairs. ''' return { k: [snd(x) for x in m] for k, m in groupby( sorted(xs, key=fst), key=fst ) } # ----------------------- GENERIC ------------------------ # ap :: (a -> b -> c) -> (a -> b) -> a -> c def ap(f): '''Applicative instance for functions. ''' def go(g): def fxgx(x): return f(x)( g(x) ) return fxgx return go # fst :: (a, b) -> a def fst(tpl): '''First component of a pair. ''' return tpl[0] # snd :: (a, b) -> b def snd(tpl): '''Second component of a pair. ''' return tpl[1] if __name__ == '__main__': main()
Chinese remainder theorem
Python
Suppose n_1, n_2, \ldots, n_k are positive [[integer]]s that are pairwise co-prime. Then, for any given sequence of integers a_1, a_2, \dots, a_k, there exists an integer x solving the following system of simultaneous congruences: ::: \begin{align} x &\equiv a_1 \pmod{n_1} \\ x &\equiv a_2 \pmod{n_2} \\ &{}\ \ \vdots \\ x &\equiv a_k \pmod{n_k} \end{align} Furthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\ldots n_k. ;Task: Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution s where 0 \leq s \leq n_1n_2\ldots n_k. ''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2]. '''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: ::: x \equiv a_i \pmod{n_i} \quad\mathrm{for}\; i = 1, \ldots, k Again, to begin, the product N = n_1n_2 \ldots n_k is defined. Then a solution x can be found as follows: For each i, the integers n_i and N/n_i are co-prime. Using the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. Then, one solution to the system of simultaneous congruences is: ::: x = \sum_{i=1}^k a_i s_i N/n_i and the minimal solution, ::: x \pmod{N}.
# Python 2.7 def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Chinese remainder theorem
Python 3.7
Suppose n_1, n_2, \ldots, n_k are positive [[integer]]s that are pairwise co-prime. Then, for any given sequence of integers a_1, a_2, \dots, a_k, there exists an integer x solving the following system of simultaneous congruences: ::: \begin{align} x &\equiv a_1 \pmod{n_1} \\ x &\equiv a_2 \pmod{n_2} \\ &{}\ \ \vdots \\ x &\equiv a_k \pmod{n_k} \end{align} Furthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\ldots n_k. ;Task: Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution s where 0 \leq s \leq n_1n_2\ldots n_k. ''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2]. '''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: ::: x \equiv a_i \pmod{n_i} \quad\mathrm{for}\; i = 1, \ldots, k Again, to begin, the product N = n_1n_2 \ldots n_k is defined. Then a solution x can be found as follows: For each i, the integers n_i and N/n_i are co-prime. Using the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. Then, one solution to the system of simultaneous congruences is: ::: x = \sum_{i=1}^k a_i s_i N/n_i and the minimal solution, ::: x \pmod{N}.
'''Chinese remainder theorem''' from operator import (add, mul) from functools import reduce # cnRemainder :: [Int] -> [Int] -> Either String Int def cnRemainder(ms): '''Chinese remainder theorem. (moduli, residues) -> Either explanation or solution ''' def go(ms, rs): mp = numericProduct(ms) cms = [(mp // x) for x in ms] def possibleSoln(invs): return Right( sum(map( mul, cms, map(mul, rs, invs) )) % mp ) return bindLR( zipWithEither(modMultInv)(cms)(ms) )(possibleSoln) return lambda rs: go(ms, rs) # modMultInv :: Int -> Int -> Either String Int def modMultInv(a, b): '''Modular multiplicative inverse.''' x, y = eGcd(a, b) return Right(x) if 1 == (a * x + b * y) else ( Left('no modular inverse for ' + str(a) + ' and ' + str(b)) ) # egcd :: Int -> Int -> (Int, Int) def eGcd(a, b): '''Extended greatest common divisor.''' def go(a, b): if 0 == b: return (1, 0) else: q, r = divmod(a, b) (s, t) = go(b, r) return (t, s - q * t) return go(a, b) # TEST ---------------------------------------------------- # main :: IO () def main(): '''Tests of soluble and insoluble cases.''' print( fTable( __doc__ + ':\n\n (moduli, residues) -> ' + ( 'Either solution or explanation\n' ) )(repr)( either(compose(quoted("'"))(curry(add)('No solution: ')))( compose(quoted(' '))(repr) ) )(uncurry(cnRemainder))([ ([10, 4, 12], [11, 12, 13]), ([11, 12, 13], [10, 4, 12]), ([10, 4, 9], [11, 22, 19]), ([3, 5, 7], [2, 3, 2]), ([2, 3, 2], [3, 5, 7]) ]) ) # GENERIC ------------------------------------------------- # Left :: a -> Either a b def Left(x): '''Constructor for an empty Either (option type) value with an associated string.''' return {'type': 'Either', 'Right': None, 'Left': x} # Right :: b -> Either a b def Right(x): '''Constructor for a populated Either (option type) value''' return {'type': 'Either', 'Left': None, 'Right': x} # any :: (a -> Bool) -> [a] -> Bool def any_(p): '''True if p(x) holds for at least one item in xs.''' def go(xs): for x in xs: if p(x): return True return False return lambda xs: go(xs) # bindLR (>>=) :: Either a -> (a -> Either b) -> Either b def bindLR(m): '''Either monad injection operator. Two computations sequentially composed, with any value produced by the first passed as an argument to the second.''' return lambda mf: ( mf(m.get('Right')) if None is m.get('Left') else m ) # 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) # either :: (a -> c) -> (b -> c) -> Either a b -> c def either(fl): '''The application of fl to e if e is a Left value, or the application of fr to e if e is a Right value.''' return lambda fr: lambda e: fl(e['Left']) if ( None is e['Right'] ) else fr(e['Right']) # fTable :: String -> (a -> String) -> # (b -> String) -> (a -> b) -> [a] -> String def fTable(s): '''Heading -> x display function -> fx display function -> f -> value list -> tabular string.''' def go(xShow, fxShow, f, xs): w = max(map(compose(len)(xShow), xs)) return s + '\n' + '\n'.join([ xShow(x).rjust(w, ' ') + (' -> ') + fxShow(f(x)) for x in xs ]) return lambda xShow: lambda fxShow: lambda f: lambda xs: go( xShow, fxShow, f, xs ) # numericProduct :: [Num] -> Num def numericProduct(xs): '''The arithmetic product of all numbers in xs.''' return reduce(mul, xs, 1) # partitionEithers :: [Either a b] -> ([a],[b]) def partitionEithers(lrs): '''A list of Either values partitioned into a tuple of two lists, with all Left elements extracted into the first list, and Right elements extracted into the second list. ''' def go(a, x): ls, rs = a r = x.get('Right') return (ls + [x.get('Left')], rs) if None is r else ( ls, rs + [r] ) return reduce(go, lrs, ([], [])) # quoted :: Char -> String -> String def quoted(c): '''A string flanked on both sides by a specified quote character. ''' return lambda s: c + s + c # uncurry :: (a -> b -> c) -> ((a, b) -> c) def uncurry(f): '''A function over a tuple, derived from a curried function.''' return lambda xy: f(xy[0])(xy[1]) # zipWithEither :: (a -> b -> Either String c) # -> [a] -> [b] -> Either String [c] def zipWithEither(f): '''Either a list of results if f succeeds with every pair in the zip of xs and ys, or an explanatory string if any application of f returns no result. ''' def go(xs, ys): ls, rs = partitionEithers(map(f, xs, ys)) return Left(ls[0]) if ls else Right(rs) return lambda xs: lambda ys: go(xs, ys) # MAIN --- if __name__ == '__main__': main()
Chinese zodiac
Python from Ruby
Determine the Chinese zodiac sign and related associations for a given year. Traditionally, the Chinese have counted years using two lists of labels, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades. Years cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit. The celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang. Thus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin. ;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). ;Requisite information: * The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. * The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. * Each element gets two consecutive years; a yang followed by a yin. * The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from. Thus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. ;Information for optional task: * The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". * The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).
# coding: utf-8 from __future__ import print_function from datetime import datetime pinyin = { '甲': 'jiă', '乙': 'yĭ', '丙': 'bĭng', '丁': 'dīng', '戊': 'wù', '己': 'jĭ', '庚': 'gēng', '辛': 'xīn', '壬': 'rén', '癸': 'gŭi', '子': 'zĭ', '丑': 'chŏu', '寅': 'yín', '卯': 'măo', '辰': 'chén', '巳': 'sì', '午': 'wŭ', '未': 'wèi', '申': 'shēn', '酉': 'yŏu', '戌': 'xū', '亥': 'hài' } animals = ['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake', 'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig'] elements = ['Wood', 'Fire', 'Earth', 'Metal', 'Water'] celestial = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'] terrestrial = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'] aspects = ['yang', 'yin'] def calculate(year): BASE = 4 year = int(year) cycle_year = year - BASE stem_number = cycle_year % 10 stem_han = celestial[stem_number] stem_pinyin = pinyin[stem_han] element_number = stem_number // 2 element = elements[element_number] branch_number = cycle_year % 12 branch_han = terrestrial[branch_number] branch_pinyin = pinyin[branch_han] animal = animals[branch_number] aspect_number = cycle_year % 2 aspect = aspects[aspect_number] index = cycle_year % 60 + 1 print("{}: {}{} ({}-{}, {} {}; {} - year {} of the cycle)" .format(year, stem_han, branch_han, stem_pinyin, branch_pinyin, element, animal, aspect, index)) current_year = datetime.now().year years = [1935, 1938, 1968, 1972, 1976, current_year] for year in years: calculate(year)
Chinese zodiac
Python 3.7
Determine the Chinese zodiac sign and related associations for a given year. Traditionally, the Chinese have counted years using two lists of labels, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades. Years cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit. The celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang. Thus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin. ;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). ;Requisite information: * The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. * The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. * Each element gets two consecutive years; a yang followed by a yin. * The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from. Thus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. ;Information for optional task: * The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". * The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).
'''Chinese zodiac''' from functools import (reduce) from datetime import datetime # TRADITIONAL STRINGS ------------------------------------- # zodiacNames :: Dict def zodiacNames(): '''天干 tiangan – 10 heavenly stems 地支 dizhi – 12 terrestrial branches 五行 wuxing – 5 elements 生肖 shengxiao – 12 symbolic animals 阴阳 yinyang - dark and light ''' return dict( zip( ['tian', 'di', 'wu', 'sx', 'yy'], map( lambda tpl: list( zip(* [tpl[0]] + list( map( lambda x: x.split(), tpl[1:]) )) ), [ # 天干 tiangan – 10 heavenly stems ('甲乙丙丁戊己庚辛壬癸', 'jiă yĭ bĭng dīng wù jĭ gēng xīn rén gŭi'), # 地支 dizhi – 12 terrestrial branches ('子丑寅卯辰巳午未申酉戌亥', 'zĭ chŏu yín măo chén sì wŭ wèi shēn yŏu xū hài'), # 五行 wuxing – 5 elements ('木火土金水', 'mù huǒ tǔ jīn shuǐ', 'wood fire earth metal water'), # 十二生肖 shengxiao – 12 symbolic animals ('鼠牛虎兔龍蛇馬羊猴鸡狗豬', 'shǔ niú hǔ tù lóng shé mǎ yáng hóu jī gǒu zhū', 'rat ox tiger rabbit dragon snake horse goat ' + 'monkey rooster dog pig' ), # 阴阳 yinyang ('阳阴', 'yáng yīn') ] ))) # zodiacYear :: Dict -> [[String]] def zodiacYear(dct): '''A string of strings containing the Chinese zodiac tokens for a given year. ''' def tokens(y): iYear = y - 4 iStem = iYear % 10 iBranch = iYear % 12 (hStem, pStem) = dct['tian'][iStem] (hBranch, pBranch) = dct['di'][iBranch] yy = iYear % 2 return [ [str(y), '', ''], [ hStem + hBranch, pStem + pBranch, str((iYear % 60) + 1) + '/60' ], list(dct['wu'][iStem // 2]), list(dct['sx'][iBranch]), list(dct['yy'][int(yy)]) + ['dark' if yy else 'light'] ] return lambda year: tokens(year) # TEST ---------------------------------------------------- # main :: IO () def main(): '''Writing out wiki tables displaying Chinese zodiac details for a given list of years. ''' print('\n'.join( list(map( zodiacTable(zodiacNames()), [ 1935, 1938, 1949, 1968, 1972, 1976, datetime.now().year ] )) )) # WIKI TABLES -------------------------------------------- # zodiacTable :: Dict -> Int -> String def zodiacTable(tokens): '''A wiki table displaying Chinese zodiac details for a a given year. ''' return lambda y: wikiTable({ 'class': 'wikitable', 'colwidth': '70px' })(transpose(zodiacYear(tokens)(y))) # wikiTable :: Dict -> [[a]] -> String def wikiTable(opts): '''List of lists rendered as a wiki table string.''' def colWidth(): return 'width:' + opts['colwidth'] + '; ' if ( 'colwidth' in opts ) else '' def cellStyle(): return opts['cell'] if 'cell' in opts else '' return lambda rows: '{| ' + reduce( lambda a, k: ( a + k + '="' + opts[k] + '" ' if k in opts else a ), ['class', 'style'], '' ) + '\n' + '\n|-\n'.join( '\n'.join( ('|' if (0 != i and ('cell' not in opts)) else ( '|style="' + colWidth() + cellStyle() + '"|' )) + ( str(x) or ' ' ) for x in row ) for i, row in enumerate(rows) ) + '\n|}\n\n' # GENERIC ------------------------------------------------- # transpose :: Matrix a -> Matrix a def transpose(m): '''The rows and columns of the argument transposed. (The matrix containers and rows can be lists or tuples).''' if m: inner = type(m[0]) z = zip(*m) return (type(m))( map(inner, z) if tuple != inner else z ) else: return m # MAIN --- if __name__ == '__main__': main()
Church numerals
Python 3.7
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. * '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. * '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)''' * '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))''' * and each successive Church numeral applies its first argument one additional time to its second argument, '''f(f(f(x)))''', '''f(f(f(f(x))))''' ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: * Church Zero, * a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), * functions for Addition, Multiplication and Exponentiation over Church numerals, * a function to convert integers to corresponding Church numerals, * and a function to convert Church numerals to corresponding integers. You should: * Derive Church numerals three and four in terms of Church zero and a Church successor function. * use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, * similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, * convert each result back to an integer, and return it or print it to the console.
'''Church numerals''' from itertools import repeat from functools import reduce # ----- CHURCH ENCODINGS OF NUMERALS AND OPERATIONS ------ def churchZero(): '''The identity function. No applications of any supplied f to its argument. ''' return lambda f: identity def churchSucc(cn): '''The successor of a given Church numeral. One additional application of f. Equivalent to the arithmetic addition of one. ''' return lambda f: compose(f)(cn(f)) def churchAdd(m): '''The arithmetic sum of two Church numerals.''' return lambda n: lambda f: compose(m(f))(n(f)) def churchMult(m): '''The arithmetic product of two Church numerals.''' return lambda n: compose(m)(n) def churchExp(m): '''Exponentiation of Church numerals. m^n''' return lambda n: n(m) def churchFromInt(n): '''The Church numeral equivalent of a given integer. ''' return lambda f: ( foldl (compose) (identity) (replicate(n)(f)) ) # OR, alternatively: def churchFromInt_(n): '''The Church numeral equivalent of a given integer, by explicit recursion. ''' if 0 == n: return churchZero() else: return churchSucc(churchFromInt(n - 1)) def intFromChurch(cn): '''The integer equivalent of a given Church numeral. ''' return cn(succ)(0) # ------------------------- TEST ------------------------- # main :: IO () def main(): 'Tests' cThree = churchFromInt(3) cFour = churchFromInt(4) print(list(map(intFromChurch, [ churchAdd(cThree)(cFour), churchMult(cThree)(cFour), churchExp(cFour)(cThree), churchExp(cThree)(cFour), ]))) # ------------------ GENERIC FUNCTIONS ------------------- # compose (flip (.)) :: (a -> b) -> (b -> c) -> a -> c def compose(f): '''A left to right composition of two functions f and g''' return lambda g: lambda x: g(f(x)) # foldl :: (a -> b -> a) -> a -> [b] -> a def foldl(f): '''Left to right reduction of a list, using the binary operator f, and starting with an initial value a. ''' def go(acc, xs): return reduce(lambda a, x: f(a)(x), xs, acc) return lambda acc: lambda xs: go(acc, xs) # identity :: a -> a def identity(x): '''The identity function.''' return x # replicate :: Int -> a -> [a] def replicate(n): '''A list of length n in which every element has the value x. ''' return lambda x: repeat(x, n) # succ :: Enum a => a -> a def succ(x): '''The successor of a value. For numeric types, (1 +). ''' return 1 + x if isinstance(x, int) else ( chr(1 + ord(x)) ) if __name__ == '__main__': main()
Circles of given radius through two points
Python
2 circles with a given radius through 2 points in 2D space. Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. ;Exceptions: # r==0.0 should be treated as never describing circles (except in the case where the points are coincident). # If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. # If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language. # If the points are too far apart then no circles can be drawn. ;Task detail: * Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''. * Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 ;Related task: * [[Total circles area]]. ;See also: * Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
from collections import namedtuple from math import sqrt Pt = namedtuple('Pt', 'x, y') Circle = Cir = namedtuple('Circle', 'x, y, r') def circles_from_p1p2r(p1, p2, r): 'Following explanation at http://mathforum.org/library/drmath/view/53027.html' if r == 0.0: raise ValueError('radius of zero') (x1, y1), (x2, y2) = p1, p2 if p1 == p2: raise ValueError('coincident points gives infinite number of Circles') # delta x, delta y between points dx, dy = x2 - x1, y2 - y1 # dist between points q = sqrt(dx**2 + dy**2) if q > 2.0*r: raise ValueError('separation of points > diameter') # halfway point x3, y3 = (x1+x2)/2, (y1+y2)/2 # distance along the mirror line d = sqrt(r**2-(q/2)**2) # One answer c1 = Cir(x = x3 - d*dy/q, y = y3 + d*dx/q, r = abs(r)) # The other answer c2 = Cir(x = x3 + d*dy/q, y = y3 - d*dx/q, r = abs(r)) return c1, c2 if __name__ == '__main__': for p1, p2, r in [(Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 2.0), (Pt(0.0000, 2.0000), Pt(0.0000, 0.0000), 1.0), (Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 2.0), (Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 0.5), (Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 0.0)]: print('Through points:\n %r,\n %r\n and radius %f\nYou can construct the following circles:' % (p1, p2, r)) try: print(' %r\n %r\n' % circles_from_p1p2r(p1, p2, r)) except ValueError as v: print(' ERROR: %s\n' % (v.args[0],))
Cistercian numerals
Python
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''. ;How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number: :* The '''upper-right''' quadrant represents the '''ones''' place. :* The '''upper-left''' quadrant represents the '''tens''' place. :* The '''lower-right''' quadrant represents the '''hundreds''' place. :* The '''lower-left''' quadrant represents the '''thousands''' place. Please consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg] ;Task :* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile). :* Use the routine to show the following Cistercian numerals: ::* 0 ::* 1 ::* 20 ::* 300 ::* 4000 ::* 5555 ::* 6789 ::* And a number of your choice! ;Notes Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output. ;See also :* '''Numberphile - The Forgotten Number System''' :* '''dcode.fr - Online Cistercian numeral converter'''
# -*- coding: utf-8 -*- """ Some UTF-8 chars used: ‾ 8254 203E &oline; OVERLINE ┃ 9475 2503 BOX DRAWINGS HEAVY VERTICAL ╱ 9585 2571 BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT ╲ 9586 2572 BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT ◸ 9720 25F8 UPPER LEFT TRIANGLE ◹ 9721 25F9 UPPER RIGHT TRIANGLE ◺ 9722 25FA LOWER LEFT TRIANGLE ◻ 9723 25FB WHITE MEDIUM SQUARE ◿ 9727 25FF LOWER RIGHT TRIANGLE """ #%% digit sections def _init(): "digit sections for forming numbers" digi_bits = """ #0 1 2 3 4 5 6 7 8 9 # . ‾ _ ╲ ╱ ◸ .| ‾| _| ◻ # . ‾ _ ╱ ╲ ◹ |. |‾ |_ ◻ # . _ ‾ ╱ ╲ ◺ .| _| ‾| ◻ # . _ ‾ ╲ ╱ ◿ |. |_ |‾ ◻ """.strip() lines = [[d.replace('.', ' ') for d in ln.strip().split()] for ln in digi_bits.strip().split('\n') if '#' not in ln] formats = '<2 >2 <2 >2'.split() digits = [[f"{dig:{f}}" for dig in line] for f, line in zip(formats, lines)] return digits _digits = _init() #%% int to 3-line strings def _to_digits(n): assert 0 <= n < 10_000 and int(n) == n return [int(digit) for digit in f"{int(n):04}"][::-1] def num_to_lines(n): global _digits d = _to_digits(n) lines = [ ''.join((_digits[1][d[1]], '┃', _digits[0][d[0]])), ''.join((_digits[0][ 0], '┃', _digits[0][ 0])), ''.join((_digits[3][d[3]], '┃', _digits[2][d[2]])), ] return lines def cjoin(c1, c2, spaces=' '): return [spaces.join(by_row) for by_row in zip(c1, c2)] #%% main if __name__ == '__main__': #n = 6666 #print(f"Arabic {n} to Cistercian:\n") #print('\n'.join(num_to_lines(n))) for pow10 in range(4): step = 10 ** pow10 print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n') lines = num_to_lines(step) for n in range(step*2, step*10, step): lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines)) numbers = [0, 5555, 6789, 6666] print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n') lines = num_to_lines(numbers[0]) for n in numbers[1:]: lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines))
Closures/Value capture
Python
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. ;Goal: Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: [[Multiple distinct objects]]
funcs = [] for i in range(10): funcs.append((lambda i: lambda: i * i)(i)) print funcs[3]() # prints 9
Colorful numbers
Python
A '''colorful number''' is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique. ;E.G. 24753 is a colorful number. 2, 4, 7, 5, 3, (2x4)8, (4x7)28, (7x5)35, (5x3)15, (2x4x7)56, (4x7x5)140, (7x5x3)105, (2x4x7x5)280, (4x7x5x3)420, (2x4x7x5x3)840 Every product is unique. 2346 is '''not''' a colorful number. 2, 3, 4, '''6''', (2x3)'''6''', (3x4)12, (4x6)24, (2x3x4)48, (3x4x6)72, (2x3x4x6)144 The product '''6''' is repeated. Single digit numbers '''are''' considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits. ;Task * Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not. * Use that routine to find all of the colorful numbers less than 100. * Use that routine to find the largest possible colorful number. ;Stretch * Find and display the count of colorful numbers in each order of magnitude. * Find and show the total count of '''all''' colorful numbers. ''Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.''
from math import prod largest = [0] def iscolorful(n): if 0 <= n < 10: return True dig = [int(c) for c in str(n)] if 1 in dig or 0 in dig or len(dig) > len(set(dig)): return False products = list(set(dig)) for i in range(len(dig)): for j in range(i+2, len(dig)+1): p = prod(dig[i:j]) if p in products: return False products.append(p) largest[0] = max(n, largest[0]) return True print('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:') for i in range(1, 101, 25): for j in range(25): if iscolorful(i + j): print(f'{i + j: 5,}', end='') print() csum = 0 for i in range(8): j = 0 if i == 0 else 10**i k = 10**(i+1) - 1 n = sum(iscolorful(x) for x in range(j, k+1)) csum += n print(f'The count of colorful numbers between {j} and {k} is {n}.') print(f'The largest possible colorful number is {largest[0]}.') print(f'The total number of colorful numbers is {csum}.')
Colour bars/Display
Python
Display a series of vertical color bars across the width of the display. The color bars should either use: :::* the system palette, or :::* the sequence of colors: ::::::* black ::::::* red ::::::* green ::::::* blue ::::::* magenta ::::::* cyan ::::::* yellow ::::::* white
#!/usr/bin/env python #vertical coloured stripes in window in Python 2.7.1 from livewires import * horiz=640; vert=480 begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black) NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"] stepik=horiz/len(NameColors) for index,each in enumerate(NameColors): ExcStrng="set_colour(Colour."+each+")" exec ExcStrng box(index*stepik,0,(index+1)*stepik,vert,filled=1) while keys_pressed() != ['x']: # press x key to terminate program pass end_graphics()
Colour pinstripe/Printer
Python
The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white. After the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers). Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language. Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
from turtle import * from PIL import Image import time import subprocess """ Only works on Windows. Assumes that you have Ghostscript installed and in your path. https://www.ghostscript.com/download/gsdnld.html Hard coded to 100 pixels per inch. """ colors = ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"] screen = getscreen() # width and height in pixels # aspect ratio for 11 by 8.5 paper inch_width = 11.0 inch_height = 8.5 pixels_per_inch = 100 pix_width = int(inch_width*pixels_per_inch) pix_height = int(inch_height*pixels_per_inch) screen.setup (width=pix_width, height=pix_height, startx=0, starty=0) screen.screensize(pix_width,pix_height) # center is 0,0 # get coordinates of the edges left_edge = -screen.window_width()//2 right_edge = screen.window_width()//2 bottom_edge = -screen.window_height()//2 top_edge = screen.window_height()//2 # draw quickly screen.delay(0) screen.tracer(5) for inch in range(int(inch_width)-1): line_width = inch + 1 pensize(line_width) colornum = 0 min_x = left_edge + (inch * pixels_per_inch) max_x = left_edge + ((inch+1) * pixels_per_inch) for y in range(bottom_edge,top_edge,line_width): penup() pencolor(colors[colornum]) colornum = (colornum + 1) % len(colors) setposition(min_x,y) pendown() setposition(max_x,y) screen.getcanvas().postscript(file="striped.eps") # convert to jpeg # won't work without Ghostscript. im = Image.open("striped.eps") im.save("striped.jpg") # Got idea from http://rosettacode.org/wiki/Colour_pinstripe/Printer#Go subprocess.run(["mspaint", "/pt", "striped.jpg"])
Comma quibbling
Python
Comma quibbling is a task originally set by Eric Lippert in his blog. ;Task: Write a function to generate a string output which is the concatenation of input words from a list/sequence where: # An input of no words produces the output string of just the two brace characters "{}". # An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". # An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". # An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: * [] # (No input words). * ["ABC"] * ["ABC", "DEF"] * ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
>>> def strcat(sequence): return '{%s}' % ', '.join(sequence)[::-1].replace(',', 'dna ', 1)[::-1] >>> for seq in ([], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]): print('Input: %-24r -> Output: %r' % (seq, strcat(seq))) Input: [] -> Output: '{}' Input: ['ABC'] -> Output: '{ABC}' Input: ['ABC', 'DEF'] -> Output: '{ABC and DEF}' Input: ['ABC', 'DEF', 'G', 'H'] -> Output: '{ABC, DEF, G and H}' >>>
Command-line arguments
Python
{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]]. See also [[Program name]]. For parsing command line arguments intelligently, see [[Parsing command-line arguments]]. Example command line: myprogram -c "alpha beta" -h "gamma"
import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments)
Compare a list of strings
Python
Given a list of arbitrarily many strings, show how to: * test if they are all lexically '''equal''' * test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)'' Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. If the input list has less than two elements, the tests should always return true. There is ''no'' need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible. Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers. If you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature.
from operator import (eq, lt) xs = ["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu"] ys = ["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu"] az = sorted(xs) print ( all(map(eq, xs, ys)), all(map(lt, xs, xs[1:])), all(map(lt, az, az[1:])) )
Compiler/AST interpreter
Python
The C and Python versions can be considered reference implementations. ;Related Tasks * Lexical Analyzer task * Syntax Analyzer task * Code Generator task * Virtual Machine Interpreter task __TOC__
from __future__ import print_function import sys, shlex, operator nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \ nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \ nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25) all_syms = { "Identifier" : nd_Ident, "String" : nd_String, "Integer" : nd_Integer, "Sequence" : nd_Sequence, "If" : nd_If, "Prtc" : nd_Prtc, "Prts" : nd_Prts, "Prti" : nd_Prti, "While" : nd_While, "Assign" : nd_Assign, "Negate" : nd_Negate, "Not" : nd_Not, "Multiply" : nd_Mul, "Divide" : nd_Div, "Mod" : nd_Mod, "Add" : nd_Add, "Subtract" : nd_Sub, "Less" : nd_Lss, "LessEqual" : nd_Leq, "Greater" : nd_Gtr, "GreaterEqual": nd_Geq, "Equal" : nd_Eql, "NotEqual" : nd_Neq, "And" : nd_And, "Or" : nd_Or} input_file = None globals = {} #*** show error and exit def error(msg): print("%s" % (msg)) exit(1) class Node: def __init__(self, node_type, left = None, right = None, value = None): self.node_type = node_type self.left = left self.right = right self.value = value #*** def make_node(oper, left, right = None): return Node(oper, left, right) #*** def make_leaf(oper, n): return Node(oper, value = n) #*** def fetch_var(var_name): n = globals.get(var_name, None) if n == None: globals[var_name] = n = 0 return n #*** def interp(x): global globals if x == None: return None elif x.node_type == nd_Integer: return int(x.value) elif x.node_type == nd_Ident: return fetch_var(x.value) elif x.node_type == nd_String: return x.value elif x.node_type == nd_Assign: globals[x.left.value] = interp(x.right) return None elif x.node_type == nd_Add: return interp(x.left) + interp(x.right) elif x.node_type == nd_Sub: return interp(x.left) - interp(x.right) elif x.node_type == nd_Mul: return interp(x.left) * interp(x.right) # use C like division semantics # another way: abs(x) / abs(y) * cmp(x, 0) * cmp(y, 0) elif x.node_type == nd_Div: return int(float(interp(x.left)) / interp(x.right)) elif x.node_type == nd_Mod: return int(float(interp(x.left)) % interp(x.right)) elif x.node_type == nd_Lss: return interp(x.left) < interp(x.right) elif x.node_type == nd_Gtr: return interp(x.left) > interp(x.right) elif x.node_type == nd_Leq: return interp(x.left) <= interp(x.right) elif x.node_type == nd_Geq: return interp(x.left) >= interp(x.right) elif x.node_type == nd_Eql: return interp(x.left) == interp(x.right) elif x.node_type == nd_Neq: return interp(x.left) != interp(x.right) elif x.node_type == nd_And: return interp(x.left) and interp(x.right) elif x.node_type == nd_Or: return interp(x.left) or interp(x.right) elif x.node_type == nd_Negate: return -interp(x.left) elif x.node_type == nd_Not: return not interp(x.left) elif x.node_type == nd_If: if (interp(x.left)): interp(x.right.left) else: interp(x.right.right) return None elif x.node_type == nd_While: while (interp(x.left)): interp(x.right) return None elif x.node_type == nd_Prtc: print("%c" % (interp(x.left)), end='') return None elif x.node_type == nd_Prti: print("%d" % (interp(x.left)), end='') return None elif x.node_type == nd_Prts: print(interp(x.left), end='') return None elif x.node_type == nd_Sequence: interp(x.left) interp(x.right) return None else: error("error in code generator - found %d, expecting operator" % (x.node_type)) def str_trans(srce): dest = "" i = 0 srce = srce[1:-1] while i < len(srce): if srce[i] == '\\' and i + 1 < len(srce): if srce[i + 1] == 'n': dest += '\n' i += 2 elif srce[i + 1] == '\\': dest += '\\' i += 2 else: dest += srce[i] i += 1 return dest def load_ast(): line = input_file.readline() line_list = shlex.split(line, False, False) text = line_list[0] value = None if len(line_list) > 1: value = line_list[1] if value.isdigit(): value = int(value) if text == ";": return None node_type = all_syms[text] if value != None: if node_type == nd_String: value = str_trans(value) return make_leaf(node_type, value) left = load_ast() right = load_ast() return make_node(node_type, left, right) #*** main driver input_file = sys.stdin if len(sys.argv) > 1: try: input_file = open(sys.argv[1], "r", 4096) except IOError as e: error(0, 0, "Can't open %s" % sys.argv[1]) n = load_ast() interp(n)
Compiler/code generator
Python
The C and Python versions can be considered reference implementations. ;Related Tasks * Lexical Analyzer task * Syntax Analyzer task * Virtual Machine Interpreter task * AST Interpreter task __TOC__
from __future__ import print_function import sys, struct, shlex, operator nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \ nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \ nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25) all_syms = { "Identifier" : nd_Ident, "String" : nd_String, "Integer" : nd_Integer, "Sequence" : nd_Sequence, "If" : nd_If, "Prtc" : nd_Prtc, "Prts" : nd_Prts, "Prti" : nd_Prti, "While" : nd_While, "Assign" : nd_Assign, "Negate" : nd_Negate, "Not" : nd_Not, "Multiply" : nd_Mul, "Divide" : nd_Div, "Mod" : nd_Mod, "Add" : nd_Add, "Subtract" : nd_Sub, "Less" : nd_Lss, "LessEqual" : nd_Leq, "Greater" : nd_Gtr, "GreaterEqual": nd_Geq, "Equal" : nd_Eql, "NotEqual" : nd_Neq, "And" : nd_And, "Or" : nd_Or} FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, \ JMP, JZ, PRTC, PRTS, PRTI, HALT = range(24) operators = {nd_Lss: LT, nd_Gtr: GT, nd_Leq: LE, nd_Geq: GE, nd_Eql: EQ, nd_Neq: NE, nd_And: AND, nd_Or: OR, nd_Sub: SUB, nd_Add: ADD, nd_Div: DIV, nd_Mul: MUL, nd_Mod: MOD} unary_operators = {nd_Negate: NEG, nd_Not: NOT} input_file = None code = bytearray() string_pool = {} globals = {} string_n = 0 globals_n = 0 word_size = 4 #*** show error and exit def error(msg): print("%s" % (msg)) exit(1) def int_to_bytes(val): return struct.pack("<i", val) def bytes_to_int(bstr): return struct.unpack("<i", bstr) class Node: def __init__(self, node_type, left = None, right = None, value = None): self.node_type = node_type self.left = left self.right = right self.value = value #*** def make_node(oper, left, right = None): return Node(oper, left, right) #*** def make_leaf(oper, n): return Node(oper, value = n) #*** def emit_byte(x): code.append(x) #*** def emit_word(x): s = int_to_bytes(x) for x in s: code.append(x) def emit_word_at(at, n): code[at:at+word_size] = int_to_bytes(n) def hole(): t = len(code) emit_word(0) return t #*** def fetch_var_offset(name): global globals_n n = globals.get(name, None) if n == None: globals[name] = globals_n n = globals_n globals_n += 1 return n #*** def fetch_string_offset(the_string): global string_n n = string_pool.get(the_string, None) if n == None: string_pool[the_string] = string_n n = string_n string_n += 1 return n #*** def code_gen(x): if x == None: return elif x.node_type == nd_Ident: emit_byte(FETCH) n = fetch_var_offset(x.value) emit_word(n) elif x.node_type == nd_Integer: emit_byte(PUSH) emit_word(x.value) elif x.node_type == nd_String: emit_byte(PUSH) n = fetch_string_offset(x.value) emit_word(n) elif x.node_type == nd_Assign: n = fetch_var_offset(x.left.value) code_gen(x.right) emit_byte(STORE) emit_word(n) elif x.node_type == nd_If: code_gen(x.left) # expr emit_byte(JZ) # if false, jump p1 = hole() # make room for jump dest code_gen(x.right.left) # if true statements if (x.right.right != None): emit_byte(JMP) # jump over else statements p2 = hole() emit_word_at(p1, len(code) - p1) if (x.right.right != None): code_gen(x.right.right) # else statements emit_word_at(p2, len(code) - p2) elif x.node_type == nd_While: p1 = len(code) code_gen(x.left) emit_byte(JZ) p2 = hole() code_gen(x.right) emit_byte(JMP) # jump back to the top emit_word(p1 - len(code)) emit_word_at(p2, len(code) - p2) elif x.node_type == nd_Sequence: code_gen(x.left) code_gen(x.right) elif x.node_type == nd_Prtc: code_gen(x.left) emit_byte(PRTC) elif x.node_type == nd_Prti: code_gen(x.left) emit_byte(PRTI) elif x.node_type == nd_Prts: code_gen(x.left) emit_byte(PRTS) elif x.node_type in operators: code_gen(x.left) code_gen(x.right) emit_byte(operators[x.node_type]) elif x.node_type in unary_operators: code_gen(x.left) emit_byte(unary_operators[x.node_type]) else: error("error in code generator - found %d, expecting operator" % (x.node_type)) #*** def code_finish(): emit_byte(HALT) #*** def list_code(): print("Datasize: %d Strings: %d" % (len(globals), len(string_pool))) for k in sorted(string_pool, key=string_pool.get): print(k) pc = 0 while pc < len(code): print("%4d " % (pc), end='') op = code[pc] pc += 1 if op == FETCH: x = bytes_to_int(code[pc:pc+word_size])[0] print("fetch [%d]" % (x)); pc += word_size elif op == STORE: x = bytes_to_int(code[pc:pc+word_size])[0] print("store [%d]" % (x)); pc += word_size elif op == PUSH: x = bytes_to_int(code[pc:pc+word_size])[0] print("push %d" % (x)); pc += word_size elif op == ADD: print("add") elif op == SUB: print("sub") elif op == MUL: print("mul") elif op == DIV: print("div") elif op == MOD: print("mod") elif op == LT: print("lt") elif op == GT: print("gt") elif op == LE: print("le") elif op == GE: print("ge") elif op == EQ: print("eq") elif op == NE: print("ne") elif op == AND: print("and") elif op == OR: print("or") elif op == NEG: print("neg") elif op == NOT: print("not") elif op == JMP: x = bytes_to_int(code[pc:pc+word_size])[0] print("jmp (%d) %d" % (x, pc + x)); pc += word_size elif op == JZ: x = bytes_to_int(code[pc:pc+word_size])[0] print("jz (%d) %d" % (x, pc + x)); pc += word_size elif op == PRTC: print("prtc") elif op == PRTI: print("prti") elif op == PRTS: print("prts") elif op == HALT: print("halt") else: error("list_code: Unknown opcode %d", (op)); def load_ast(): line = input_file.readline() line_list = shlex.split(line, False, False) text = line_list[0] if text == ";": return None node_type = all_syms[text] if len(line_list) > 1: value = line_list[1] if value.isdigit(): value = int(value) return make_leaf(node_type, value) left = load_ast() right = load_ast() return make_node(node_type, left, right) #*** main driver input_file = sys.stdin if len(sys.argv) > 1: try: input_file = open(sys.argv[1], "r", 4096) except IOError as e: error("Can't open %s" % sys.argv[1]) n = load_ast() code_gen(n) code_finish() list_code()
Compiler/lexical analyzer
Python
The C and Python versions can be considered reference implementations. ;Related Tasks * Syntax Analyzer task * Code Generator task * Virtual Machine Interpreter task * AST Interpreter task
from __future__ import print_function import sys # following two must remain in the same order tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, \ tk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, \ tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident, \ tk_Integer, tk_String = range(31) all_syms = ["End_of_input", "Op_multiply", "Op_divide", "Op_mod", "Op_add", "Op_subtract", "Op_negate", "Op_not", "Op_less", "Op_lessequal", "Op_greater", "Op_greaterequal", "Op_equal", "Op_notequal", "Op_assign", "Op_and", "Op_or", "Keyword_if", "Keyword_else", "Keyword_while", "Keyword_print", "Keyword_putc", "LeftParen", "RightParen", "LeftBrace", "RightBrace", "Semicolon", "Comma", "Identifier", "Integer", "String"] # single character only symbols symbols = { '{': tk_Lbrace, '}': tk_Rbrace, '(': tk_Lparen, ')': tk_Rparen, '+': tk_Add, '-': tk_Sub, '*': tk_Mul, '%': tk_Mod, ';': tk_Semi, ',': tk_Comma } key_words = {'if': tk_If, 'else': tk_Else, 'print': tk_Print, 'putc': tk_Putc, 'while': tk_While} the_ch = " " # dummy first char - but it must be a space the_col = 0 the_line = 1 input_file = None #*** show error and exit def error(line, col, msg): print(line, col, msg) exit(1) #*** get the next character from the input def next_ch(): global the_ch, the_col, the_line the_ch = input_file.read(1) the_col += 1 if the_ch == '\n': the_line += 1 the_col = 0 return the_ch #*** 'x' - character constants def char_lit(err_line, err_col): n = ord(next_ch()) # skip opening quote if the_ch == '\'': error(err_line, err_col, "empty character constant") elif the_ch == '\\': next_ch() if the_ch == 'n': n = 10 elif the_ch == '\\': n = ord('\\') else: error(err_line, err_col, "unknown escape sequence \\%c" % (the_ch)) if next_ch() != '\'': error(err_line, err_col, "multi-character constant") next_ch() return tk_Integer, err_line, err_col, n #*** process divide or comments def div_or_cmt(err_line, err_col): if next_ch() != '*': return tk_Div, err_line, err_col # comment found next_ch() while True: if the_ch == '*': if next_ch() == '/': next_ch() return gettok() elif len(the_ch) == 0: error(err_line, err_col, "EOF in comment") else: next_ch() #*** "string" def string_lit(start, err_line, err_col): global the_ch text = "" while next_ch() != start: if len(the_ch) == 0: error(err_line, err_col, "EOF while scanning string literal") if the_ch == '\n': error(err_line, err_col, "EOL while scanning string literal") if the_ch == '\\': next_ch() if the_ch != 'n': error(err_line, err_col, "escape sequence unknown \\%c" % the_ch) the_ch = '\n' text += the_ch next_ch() return tk_String, err_line, err_col, text #*** handle identifiers and integers def ident_or_int(err_line, err_col): is_number = True text = "" while the_ch.isalnum() or the_ch == '_': text += the_ch if not the_ch.isdigit(): is_number = False next_ch() if len(text) == 0: error(err_line, err_col, "ident_or_int: unrecognized character: (%d) '%c'" % (ord(the_ch), the_ch)) if text[0].isdigit(): if not is_number: error(err_line, err_col, "invalid number: %s" % (text)) n = int(text) return tk_Integer, err_line, err_col, n if text in key_words: return key_words[text], err_line, err_col return tk_Ident, err_line, err_col, text #*** look ahead for '>=', etc. def follow(expect, ifyes, ifno, err_line, err_col): if next_ch() == expect: next_ch() return ifyes, err_line, err_col if ifno == tk_EOI: error(err_line, err_col, "follow: unrecognized character: (%d) '%c'" % (ord(the_ch), the_ch)) return ifno, err_line, err_col #*** return the next token type def gettok(): while the_ch.isspace(): next_ch() err_line = the_line err_col = the_col if len(the_ch) == 0: return tk_EOI, err_line, err_col elif the_ch == '/': return div_or_cmt(err_line, err_col) elif the_ch == '\'': return char_lit(err_line, err_col) elif the_ch == '<': return follow('=', tk_Leq, tk_Lss, err_line, err_col) elif the_ch == '>': return follow('=', tk_Geq, tk_Gtr, err_line, err_col) elif the_ch == '=': return follow('=', tk_Eq, tk_Assign, err_line, err_col) elif the_ch == '!': return follow('=', tk_Neq, tk_Not, err_line, err_col) elif the_ch == '&': return follow('&', tk_And, tk_EOI, err_line, err_col) elif the_ch == '|': return follow('|', tk_Or, tk_EOI, err_line, err_col) elif the_ch == '"': return string_lit(the_ch, err_line, err_col) elif the_ch in symbols: sym = symbols[the_ch] next_ch() return sym, err_line, err_col else: return ident_or_int(err_line, err_col) #*** main driver input_file = sys.stdin if len(sys.argv) > 1: try: input_file = open(sys.argv[1], "r", 4096) except IOError as e: error(0, 0, "Can't open %s" % sys.argv[1]) while True: t = gettok() tok = t[0] line = t[1] col = t[2] print("%5d %5d %-14s" % (line, col, all_syms[tok]), end='') if tok == tk_Integer: print(" %5d" % (t[3])) elif tok == tk_Ident: print(" %s" % (t[3])) elif tok == tk_String: print(' "%s"' % (t[3])) else: print("") if tok == tk_EOI: break
Compiler/syntax analyzer
Python
The C and Python versions can be considered reference implementations. ;Related Tasks * Lexical Analyzer task * Code Generator task * Virtual Machine Interpreter task * AST Interpreter task __TOC__
from __future__ import print_function import sys, shlex, operator tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, \ tk_Geq, tk_Eql, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, \ tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident, \ tk_Integer, tk_String = range(31) nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \ nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \ nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25) # must have same order as above Tokens = [ ["EOI" , False, False, False, -1, -1 ], ["*" , False, True, False, 13, nd_Mul ], ["/" , False, True, False, 13, nd_Div ], ["%" , False, True, False, 13, nd_Mod ], ["+" , False, True, False, 12, nd_Add ], ["-" , False, True, False, 12, nd_Sub ], ["-" , False, False, True, 14, nd_Negate ], ["!" , False, False, True, 14, nd_Not ], ["<" , False, True, False, 10, nd_Lss ], ["<=" , False, True, False, 10, nd_Leq ], [">" , False, True, False, 10, nd_Gtr ], [">=" , False, True, False, 10, nd_Geq ], ["==" , False, True, False, 9, nd_Eql ], ["!=" , False, True, False, 9, nd_Neq ], ["=" , False, False, False, -1, nd_Assign ], ["&&" , False, True, False, 5, nd_And ], ["||" , False, True, False, 4, nd_Or ], ["if" , False, False, False, -1, nd_If ], ["else" , False, False, False, -1, -1 ], ["while" , False, False, False, -1, nd_While ], ["print" , False, False, False, -1, -1 ], ["putc" , False, False, False, -1, -1 ], ["(" , False, False, False, -1, -1 ], [")" , False, False, False, -1, -1 ], ["{" , False, False, False, -1, -1 ], ["}" , False, False, False, -1, -1 ], [";" , False, False, False, -1, -1 ], ["," , False, False, False, -1, -1 ], ["Ident" , False, False, False, -1, nd_Ident ], ["Integer literal" , False, False, False, -1, nd_Integer], ["String literal" , False, False, False, -1, nd_String ] ] all_syms = {"End_of_input" : tk_EOI, "Op_multiply" : tk_Mul, "Op_divide" : tk_Div, "Op_mod" : tk_Mod, "Op_add" : tk_Add, "Op_subtract" : tk_Sub, "Op_negate" : tk_Negate, "Op_not" : tk_Not, "Op_less" : tk_Lss, "Op_lessequal" : tk_Leq, "Op_greater" : tk_Gtr, "Op_greaterequal": tk_Geq, "Op_equal" : tk_Eql, "Op_notequal" : tk_Neq, "Op_assign" : tk_Assign, "Op_and" : tk_And, "Op_or" : tk_Or, "Keyword_if" : tk_If, "Keyword_else" : tk_Else, "Keyword_while" : tk_While, "Keyword_print" : tk_Print, "Keyword_putc" : tk_Putc, "LeftParen" : tk_Lparen, "RightParen" : tk_Rparen, "LeftBrace" : tk_Lbrace, "RightBrace" : tk_Rbrace, "Semicolon" : tk_Semi, "Comma" : tk_Comma, "Identifier" : tk_Ident, "Integer" : tk_Integer, "String" : tk_String} Display_nodes = ["Identifier", "String", "Integer", "Sequence", "If", "Prtc", "Prts", "Prti", "While", "Assign", "Negate", "Not", "Multiply", "Divide", "Mod", "Add", "Subtract", "Less", "LessEqual", "Greater", "GreaterEqual", "Equal", "NotEqual", "And", "Or"] TK_NAME = 0 TK_RIGHT_ASSOC = 1 TK_IS_BINARY = 2 TK_IS_UNARY = 3 TK_PRECEDENCE = 4 TK_NODE = 5 input_file = None err_line = None err_col = None tok = None tok_text = None #*** show error and exit def error(msg): print("(%d, %d) %s" % (int(err_line), int(err_col), msg)) exit(1) #*** def gettok(): global err_line, err_col, tok, tok_text, tok_other line = input_file.readline() if len(line) == 0: error("empty line") line_list = shlex.split(line, False, False) # line col Ident var_name # 0 1 2 3 err_line = line_list[0] err_col = line_list[1] tok_text = line_list[2] tok = all_syms.get(tok_text) if tok == None: error("Unknown token %s" % (tok_text)) tok_other = None if tok in [tk_Integer, tk_Ident, tk_String]: tok_other = line_list[3] class Node: def __init__(self, node_type, left = None, right = None, value = None): self.node_type = node_type self.left = left self.right = right self.value = value #*** def make_node(oper, left, right = None): return Node(oper, left, right) #*** def make_leaf(oper, n): return Node(oper, value = n) #*** def expect(msg, s): if tok == s: gettok() return error("%s: Expecting '%s', found '%s'" % (msg, Tokens[s][TK_NAME], Tokens[tok][TK_NAME])) #*** def expr(p): x = None if tok == tk_Lparen: x = paren_expr() elif tok in [tk_Sub, tk_Add]: op = (tk_Negate if tok == tk_Sub else tk_Add) gettok() node = expr(Tokens[tk_Negate][TK_PRECEDENCE]) x = (make_node(nd_Negate, node) if op == tk_Negate else node) elif tok == tk_Not: gettok() x = make_node(nd_Not, expr(Tokens[tk_Not][TK_PRECEDENCE])) elif tok == tk_Ident: x = make_leaf(nd_Ident, tok_other) gettok() elif tok == tk_Integer: x = make_leaf(nd_Integer, tok_other) gettok() else: error("Expecting a primary, found: %s" % (Tokens[tok][TK_NAME])) while Tokens[tok][TK_IS_BINARY] and Tokens[tok][TK_PRECEDENCE] >= p: op = tok gettok() q = Tokens[op][TK_PRECEDENCE] if not Tokens[op][TK_RIGHT_ASSOC]: q += 1 node = expr(q) x = make_node(Tokens[op][TK_NODE], x, node) return x #*** def paren_expr(): expect("paren_expr", tk_Lparen) node = expr(0) expect("paren_expr", tk_Rparen) return node #*** def stmt(): t = None if tok == tk_If: gettok() e = paren_expr() s = stmt() s2 = None if tok == tk_Else: gettok() s2 = stmt() t = make_node(nd_If, e, make_node(nd_If, s, s2)) elif tok == tk_Putc: gettok() e = paren_expr() t = make_node(nd_Prtc, e) expect("Putc", tk_Semi) elif tok == tk_Print: gettok() expect("Print", tk_Lparen) while True: if tok == tk_String: e = make_node(nd_Prts, make_leaf(nd_String, tok_other)) gettok() else: e = make_node(nd_Prti, expr(0)) t = make_node(nd_Sequence, t, e) if tok != tk_Comma: break gettok() expect("Print", tk_Rparen) expect("Print", tk_Semi) elif tok == tk_Semi: gettok() elif tok == tk_Ident: v = make_leaf(nd_Ident, tok_other) gettok() expect("assign", tk_Assign) e = expr(0) t = make_node(nd_Assign, v, e) expect("assign", tk_Semi) elif tok == tk_While: gettok() e = paren_expr() s = stmt() t = make_node(nd_While, e, s) elif tok == tk_Lbrace: gettok() while tok != tk_Rbrace and tok != tk_EOI: t = make_node(nd_Sequence, t, stmt()) expect("Lbrace", tk_Rbrace) elif tok == tk_EOI: pass else: error("Expecting start of statement, found: %s" % (Tokens[tok][TK_NAME])) return t #*** def parse(): t = None gettok() while True: t = make_node(nd_Sequence, t, stmt()) if tok == tk_EOI or t == None: break return t def prt_ast(t): if t == None: print(";") else: print("%-14s" % (Display_nodes[t.node_type]), end='') if t.node_type in [nd_Ident, nd_Integer]: print("%s" % (t.value)) elif t.node_type == nd_String: print("%s" %(t.value)) else: print("") prt_ast(t.left) prt_ast(t.right) #*** main driver input_file = sys.stdin if len(sys.argv) > 1: try: input_file = open(sys.argv[1], "r", 4096) except IOError as e: error(0, 0, "Can't open %s" % sys.argv[1]) t = parse() prt_ast(t)
Compiler/virtual machine interpreter
Python
The C and Python versions can be considered reference implementations. ;Related Tasks * Lexical Analyzer task * Syntax Analyzer task * Code Generator task * AST Interpreter task __TOC__
from __future__ import print_function import sys, struct FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, \ JMP, JZ, PRTC, PRTS, PRTI, HALT = range(24) code_map = { "fetch": FETCH, "store": STORE, "push": PUSH, "add": ADD, "sub": SUB, "mul": MUL, "div": DIV, "mod": MOD, "lt": LT, "gt": GT, "le": LE, "ge": GE, "eq": EQ, "ne": NE, "and": AND, "or": OR, "not": NOT, "neg": NEG, "jmp": JMP, "jz": JZ, "prtc": PRTC, "prts": PRTS, "prti": PRTI, "halt": HALT } input_file = None code = bytearray() string_pool = [] word_size = 4 #*** show error and exit def error(msg): print("%s" % (msg)) exit(1) def int_to_bytes(val): return struct.pack("<i", val) def bytes_to_int(bstr): return struct.unpack("<i", bstr) #*** def emit_byte(x): code.append(x) #*** def emit_word(x): s = int_to_bytes(x) for x in s: code.append(x) #*** def run_vm(data_size): stack = [0 for i in range(data_size + 1)] pc = 0 while True: op = code[pc] pc += 1 if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() # use C like division semantics elif op == DIV: stack[-2] = int(float(stack[-2]) / stack[-1]); stack.pop() elif op == MOD: stack[-2] = int(float(stack[-2]) % stack[-1]); stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop(): pc += word_size else: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print("%c" % (stack[-1]), end=''); stack.pop() elif op == PRTS: print("%s" % (string_pool[stack[-1]]), end=''); stack.pop() elif op == PRTI: print("%d" % (stack[-1]), end=''); stack.pop() elif op == HALT: break def str_trans(srce): dest = "" i = 0 while i < len(srce): if srce[i] == '\\' and i + 1 < len(srce): if srce[i + 1] == 'n': dest += '\n' i += 2 elif srce[i + 1] == '\\': dest += '\\' i += 2 else: dest += srce[i] i += 1 return dest #*** def load_code(): global string_pool line = input_file.readline() if len(line) == 0: error("empty line") line_list = line.split() data_size = int(line_list[1]) n_strings = int(line_list[3]) for i in range(n_strings): string_pool.append(str_trans(input_file.readline().strip('"\n'))) while True: line = input_file.readline() if len(line) == 0: break line_list = line.split() offset = int(line_list[0]) instr = line_list[1] opcode = code_map.get(instr) if opcode == None: error("Unknown instruction %s at %d" % (instr, offset)) emit_byte(opcode) if opcode in [JMP, JZ]: p = int(line_list[3]) emit_word(p - (offset + 1)) elif opcode == PUSH: value = int(line_list[2]) emit_word(value) elif opcode in [FETCH, STORE]: value = int(line_list[2].strip('[]')) emit_word(value) return data_size #*** main driver input_file = sys.stdin if len(sys.argv) > 1: try: input_file = open(sys.argv[1], "r", 4096) except IOError as e: error(0, 0, "Can't open %s" % sys.argv[1]) data_size = load_code() run_vm(data_size)
Composite numbers k with no single digit factors whose factors are all substrings of k
Python
Find the composite numbers '''k''' in base 10, that have no single digit prime factors and whose prime factors are all a substring of '''k'''. ;Task * Find and show here, on this page, the first ten elements of the sequence. ;Stretch * Find and show the next ten elements.
from sympy import isprime, factorint def contains_its_prime_factors_all_over_7(n): if n < 10 or isprime(n): return False strn = str(n) pfacs = factorint(n).keys() return all(f > 9 and str(f) in strn for f in pfacs) found = 0 for n in range(1_000_000_000): if contains_its_prime_factors_all_over_7(n): found += 1 print(f'{n: 12,}', end = '\n' if found % 10 == 0 else '') if found == 20: break
Conjugate transpose
Python
Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M. ::: (M^H)_{ji} = \overline{M_{ij}} This means that row j, column i of the conjugate transpose equals the complex conjugate of row i, column j of the original matrix. In the next list, M must also be a square matrix. * A Hermitian matrix equals its own conjugate transpose: M^H = M. * A multiplication with its conjugate transpose: M^HM = MM^H. * A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix. ;Task: Given some matrix of complex numbers, find its conjugate transpose. Also determine if the matrix is a: ::* Hermitian matrix, ::* normal matrix, or ::* unitary matrix. ;See also: * MathWorld entry: conjugate transpose * MathWorld entry: Hermitian matrix * MathWorld entry: normal matrix * MathWorld entry: unitary matrix
def conjugate_transpose(m): return tuple(tuple(n.conjugate() for n in row) for row in zip(*m)) def mmul( ma, mb): return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma) def mi(size): 'Complex Identity matrix' sz = range(size) m = [[0 + 0j for i in sz] for j in sz] for i in range(size): m[i][i] = 1 + 0j return tuple(tuple(row) for row in m) def __allsame(vector): first, rest = vector[0], vector[1:] return all(i == first for i in rest) def __allnearsame(vector, eps=1e-14): first, rest = vector[0], vector[1:] return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps for i in rest) def isequal(matrices, eps=1e-14): 'Check any number of matrices for equality within eps' x = [len(m) for m in matrices] if not __allsame(x): return False y = [len(m[0]) for m in matrices] if not __allsame(y): return False for s in range(x[0]): for t in range(y[0]): if not __allnearsame([m[s][t] for m in matrices], eps): return False return True def ishermitian(m, ct): return isequal([m, ct]) def isnormal(m, ct): return isequal([mmul(m, ct), mmul(ct, m)]) def isunitary(m, ct): mct, ctm = mmul(m, ct), mmul(ct, m) mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0]) ident = mi(mctx) return isequal([mct, ctm, ident]) def printm(comment, m): print(comment) fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m] width = max(max(len(f) for f in row) for row in fields) lines = (', '.join('%*s' % (width, f) for f in row) for row in fields) print('\n'.join(lines)) if __name__ == '__main__': for matrix in [ ((( 3.000+0.000j), (+2.000+1.000j)), (( 2.000-1.000j), (+1.000+0.000j))), ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))), ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]: printm('\nMatrix:', matrix) ct = conjugate_transpose(matrix) printm('Its conjugate transpose:', ct) print('Hermitian? %s.' % ishermitian(matrix, ct)) print('Normal? %s.' % isnormal(matrix, ct)) print('Unitary? %s.' % isunitary(matrix, ct))
Continued fraction
Python 2.6+ and 3.x
A number may be represented as a continued fraction (see Mathworld for more information) as follows: :a_0 + \cfrac{b_1}{a_1 + \cfrac{b_2}{a_2 + \cfrac{b_3}{a_3 + \ddots}}} The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1. :\sqrt{2} = 1 + \cfrac{1}{2 + \cfrac{1}{2 + \cfrac{1}{2 + \ddots}}} For Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1. :e = 2 + \cfrac{1}{1 + \cfrac{1}{2 + \cfrac{2}{3 + \cfrac{3}{4 + \ddots}}}} For Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2. :\pi = 3 + \cfrac{1}{6 + \cfrac{9}{6 + \cfrac{25}{6 + \ddots}}} ;See also: :* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.
from fractions import Fraction import itertools try: zip = itertools.izip except: pass # The Continued Fraction def CF(a, b, t): terms = list(itertools.islice(zip(a, b), t)) z = Fraction(1,1) for a, b in reversed(terms): z = a + b / z return z # Approximates a fraction to a string def pRes(x, d): q, x = divmod(x, 1) res = str(q) res += "." for i in range(d): x *= 10 q, x = divmod(x, 1) res += str(q) return res # Test the Continued Fraction for sqrt2 def sqrt2_a(): yield 1 for x in itertools.repeat(2): yield x def sqrt2_b(): for x in itertools.repeat(1): yield x cf = CF(sqrt2_a(), sqrt2_b(), 950) print(pRes(cf, 200)) #1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147 # Test the Continued Fraction for Napier's Constant def Napier_a(): yield 2 for x in itertools.count(1): yield x def Napier_b(): yield 1 for x in itertools.count(1): yield x cf = CF(Napier_a(), Napier_b(), 950) print(pRes(cf, 200)) #2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901 # Test the Continued Fraction for Pi def Pi_a(): yield 3 for x in itertools.repeat(6): yield x def Pi_b(): for x in itertools.count(1,2): yield x*x cf = CF(Pi_a(), Pi_b(), 950) print(pRes(cf, 10)) #3.1415926532
Continued fraction
Python from D
A number may be represented as a continued fraction (see Mathworld for more information) as follows: :a_0 + \cfrac{b_1}{a_1 + \cfrac{b_2}{a_2 + \cfrac{b_3}{a_3 + \ddots}}} The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1. :\sqrt{2} = 1 + \cfrac{1}{2 + \cfrac{1}{2 + \cfrac{1}{2 + \ddots}}} For Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1. :e = 2 + \cfrac{1}{1 + \cfrac{1}{2 + \cfrac{2}{3 + \cfrac{3}{4 + \ddots}}}} For Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2. :\pi = 3 + \cfrac{1}{6 + \cfrac{9}{6 + \cfrac{25}{6 + \ddots}}} ;See also: :* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.
from decimal import Decimal, getcontext def calc(fun, n): temp = Decimal("0.0") for ni in xrange(n+1, 0, -1): (a, b) = fun(ni) temp = Decimal(b) / (a + temp) return fun(0)[0] + temp def fsqrt2(n): return (2 if n > 0 else 1, 1) def fnapier(n): return (n if n > 0 else 2, (n - 1) if n > 1 else 1) def fpi(n): return (6 if n > 0 else 3, (2 * n - 1) ** 2) getcontext().prec = 50 print calc(fsqrt2, 200) print calc(fnapier, 200) print calc(fpi, 200)
Continued fraction/Arithmetic/Construct from rational number
Python from Ruby
To understand this task in context please see [[Continued fraction arithmetic]] The purpose of this task is to write a function \mathit{r2cf}(\mathrm{int} N_1, \mathrm{int} N_2), or \mathit{r2cf}(\mathrm{Fraction} N), which will output a continued fraction assuming: :N_1 is the numerator :N_2 is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \mathrm{abs}(N_2) is zero. Demonstrate the function by outputing the continued fraction for: : 1/2 : 3 : 23/8 : 13/11 : 22/7 : -151/77 \sqrt 2 should approach [1; 2, 2, 2, 2, \ldots] try ever closer rational approximations until boredom gets the better of you: : 14142,10000 : 141421,100000 : 1414214,1000000 : 14142136,10000000 Try : : 31,10 : 314,100 : 3142,1000 : 31428,10000 : 314285,100000 : 3142857,1000000 : 31428571,10000000 : 314285714,100000000 Observe how this rational number behaves differently to \sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\infty] when an extra term is required.
def r2cf(n1,n2): while n2: n1, (t1, n2) = n2, divmod(n1, n2) yield t1 print(list(r2cf(1,2))) # => [0, 2] print(list(r2cf(3,1))) # => [3] print(list(r2cf(23,8))) # => [2, 1, 7] print(list(r2cf(13,11))) # => [1, 5, 2] print(list(r2cf(22,7))) # => [3, 7] print(list(r2cf(14142,10000))) # => [1, 2, 2, 2, 2, 2, 1, 1, 29] print(list(r2cf(141421,100000))) # => [1, 2, 2, 2, 2, 2, 2, 3, 1, 1, 3, 1, 7, 2] print(list(r2cf(1414214,1000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 3, 6, 1, 2, 1, 12] print(list(r2cf(14142136,10000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 1, 2, 4, 1, 1, 2]
Continued fraction/Arithmetic/G(matrix ng, continued fraction n)
Python from Ruby
This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG: : \begin{bmatrix} a_1 & a \\ b_1 & b \end{bmatrix} I may perform perform the following operations: :Input the next term of N1 :Output a term of the continued fraction resulting from the operation. I output a term if the integer parts of \frac{a}{b} and \frac{a_1}{b_1} are equal. Otherwise I input a term from N. If I need a term from N but N has no more terms I inject \infty. When I input a term t my internal state: \begin{bmatrix} a_1 & a \\ b_1 & b \end{bmatrix} is transposed thus \begin{bmatrix} a + a_1 * t & a_1 \\ b + b_1 * t & b_1 \end{bmatrix} When I output a term t my internal state: \begin{bmatrix} a_1 & a \\ b_1 & b \end{bmatrix} is transposed thus \begin{bmatrix} b_1 & b \\ a_1 - b_1 * t & a - b * t \end{bmatrix} When I need a term t but there are no more my internal state: \begin{bmatrix} a_1 & a \\ b_1 & b \end{bmatrix} is transposed thus \begin{bmatrix} a_1 & a_1 \\ b_1 & b_1 \end{bmatrix} I am done when b1 and b are zero. Demonstrate your solution by calculating: :[1;5,2] + 1/2 :[3;7] + 1/2 :[3;7] divided by 4 Using a generator for \sqrt{2} (e.g., from [[Continued fraction]]) calculate \frac{1}{\sqrt{2}}. You are now at the starting line for using Continued Fractions to implement [[Arithmetic-geometric mean]] without ulps and epsilons. The first step in implementing [[Arithmetic-geometric mean]] is to calculate \frac{1 + \frac{1}{\sqrt{2}}}{2} do this now to cross the starting line and begin the race.
class NG: def __init__(self, a1, a, b1, b): self.a1, self.a, self.b1, self.b = a1, a, b1, b def ingress(self, n): self.a, self.a1 = self.a1, self.a + self.a1 * n self.b, self.b1 = self.b1, self.b + self.b1 * n @property def needterm(self): return (self.b == 0 or self.b1 == 0) or not self.a//self.b == self.a1//self.b1 @property def egress(self): n = self.a // self.b self.a, self.b = self.b, self.a - self.b * n self.a1, self.b1 = self.b1, self.a1 - self.b1 * n return n @property def egress_done(self): if self.needterm: self.a, self.b = self.a1, self.b1 return self.egress @property def done(self): return self.b == 0 and self.b1 == 0
Convert decimal number to rational
Python 2.6+
The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: * 67 / 74 = 0.9(054) = 0.9054054... * 14 / 27 = 0.(518) = 0.518518... Acceptable output: * 0.9054054 - 4527027 / 5000000 * 0.518518 - 259259 / 500000 Finite decimals are of course no problem: * 0.75 - 3 / 4
>>> from fractions import Fraction >>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100)) 0.9054054 67/74 0.518518 14/27 0.75 3/4 >>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d)) 0.9054054 4527027/5000000 0.518518 259259/500000 0.75 3/4 >>>
Convert decimal number to rational
Python 3.7
The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: * 67 / 74 = 0.9(054) = 0.9054054... * 14 / 27 = 0.(518) = 0.518518... Acceptable output: * 0.9054054 - 4527027 / 5000000 * 0.518518 - 259259 / 500000 Finite decimals are of course no problem: * 0.75 - 3 / 4
'''Approximate rationals from decimals''' from math import (floor, gcd) import sys # approxRatio :: Float -> Float -> Ratio def approxRatio(epsilon): '''The simplest rational approximation to n within the margin given by epsilon. ''' def gcde(e, x, y): def _gcd(a, b): return a if b < e else _gcd(b, a % b) return _gcd(abs(x), abs(y)) return lambda n: (lambda c=( gcde(epsilon if 0 < epsilon else (0.0001), 1, n) ): ratio(floor(n / c))(floor(1 / c)))() # main :: IO () def main(): '''Conversions at different levels of precision.''' xs = [0.9054054, 0.518518, 0.75] print( fTable(__doc__ + ' (epsilon of 1/10000):\n')(str)( lambda r: showRatio(r) + ' -> ' + repr(fromRatio(r)) )( approxRatio(1 / 10000) )(xs) ) print('\n') e = minBound(float) print( fTable(__doc__ + ' (epsilon of ' + repr(e) + '):\n')(str)( lambda r: showRatio(r) + ' -> ' + repr(fromRatio(r)) )( approxRatio(e) )(xs) ) # GENERIC ------------------------------------------------- # fromRatio :: Ratio Int -> Float def fromRatio(r): '''A floating point value derived from a a rational value. ''' return r.get('numerator') / r.get('denominator') # minBound :: Bounded Type -> a def minBound(t): '''Minimum value for a bounded type.''' maxsize = sys.maxsize float_infomin = sys.float_info.min return { int: (-maxsize - 1), float: float_infomin, bool: False, str: chr(0) }[t] # ratio :: Int -> Int -> Ratio Int def ratio(n): '''Rational value constructed from a numerator and a denominator. ''' def go(n, d): g = gcd(n, d) return { 'type': 'Ratio', 'numerator': n // g, 'denominator': d // g } return lambda d: go(n * signum(d), abs(d)) # showRatio :: Ratio -> String def showRatio(r): '''String representation of the ratio r.''' d = r.get('denominator') return str(r.get('numerator')) + ( ' / ' + str(d) if 1 != d else '' ) # signum :: Num -> Num def signum(n): '''The sign of n.''' return -1 if 0 > n else (1 if 0 < n else 0) # 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 ) # MAIN --- if __name__ == '__main__': main()
Convert seconds to compound duration
Python
Write a function or program which: * takes a positive integer representing a duration in seconds as input (e.g., 100), and * returns a string which shows the same duration decomposed into: :::* weeks, :::* days, :::* hours, :::* minutes, and :::* seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrate that it passes the following three test-cases: '''''Test Cases''''' :::::{| class="wikitable" |- ! input number ! output string |- | 7259 | 2 hr, 59 sec |- | 86400 | 1 d |- | 6000000 | 9 wk, 6 d, 10 hr, 40 min |} '''''Details''''' The following five units should be used: :::::{| class="wikitable" |- ! unit ! suffix used in output ! conversion |- | week | wk | 1 week = 7 days |- | day | d | 1 day = 24 hours |- | hour | hr | 1 hour = 60 minutes |- | minute | min | 1 minute = 60 seconds |- | second | sec | |} However, '''only''' include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
'''Compound duration''' from functools import reduce from itertools import chain # compoundDurationFromUnits :: [Num] -> [String] -> Num -> [(Num, String)] def compoundDurationFromUnits(qs): '''A list of compound string representions of a number n of time units, in terms of the multiples given in qs, and the labels given in ks. ''' return lambda ks: lambda n: list( chain.from_iterable(map( lambda v, k: [(v, k)] if 0 < v else [], mapAccumR( lambda a, x: divmod(a, x) if 0 < x else (1, a) )(n)(qs)[1], ks )) ) # --------------------------TEST--------------------------- # main :: IO () def main(): '''Tests of various durations, with a particular set of units and labels. ''' print( fTable('Compound durations from numbers of seconds:\n')(str)( quoted("'") )( lambda n: ', '.join([ str(v) + ' ' + k for v, k in compoundDurationFromUnits([0, 7, 24, 60, 60])( ['wk', 'd', 'hr', 'min', 'sec'] )(n) ]) )([7259, 86400, 6000000]) ) # -------------------------GENERIC------------------------- # 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 ) # mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) def mapAccumR(f): '''A tuple of an accumulation and a list derived by a combined map and fold, with accumulation from right to left. ''' def go(a, x): acc, y = f(a[0], x) return (acc, [y] + a[1]) return lambda acc: lambda xs: ( reduce(go, reversed(xs), (acc, [])) ) # quoted :: Char -> String -> String def quoted(c): '''A string flanked on both sides by a specified quote character. ''' return lambda s: c + s + c # MAIN --- if __name__ == '__main__': main()
Copy stdin to stdout
Python
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
python -c 'import sys; sys.stdout.write(sys.stdin.read())'
Count the coins
Python from Go
There are four types of common coins in US currency: :::# quarters (25 cents) :::# dimes (10 cents) :::# nickels (5 cents), and :::# pennies (1 cent) There are six ways to make change for 15 cents: :::# A dime and a nickel :::# A dime and 5 pennies :::# 3 nickels :::# 2 nickels and 5 pennies :::# A nickel and 10 pennies :::# 15 pennies ;Task: How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents). ;Optional: Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? (Note: the answer is larger than 232). ;References: * an algorithm from the book ''Structure and Interpretation of Computer Programs''. * an article in the algorithmist. * Change-making problem on Wikipedia.
def changes(amount, coins): ways = [0] * (amount + 1) ways[0] = 1 for coin in coins: for j in xrange(coin, amount + 1): ways[j] += ways[j - coin] return ways[amount] print changes(100, [1, 5, 10, 25]) print changes(100000, [1, 5, 10, 25, 50, 100])
Count the coins
Python from C
There are four types of common coins in US currency: :::# quarters (25 cents) :::# dimes (10 cents) :::# nickels (5 cents), and :::# pennies (1 cent) There are six ways to make change for 15 cents: :::# A dime and a nickel :::# A dime and 5 pennies :::# 3 nickels :::# 2 nickels and 5 pennies :::# A nickel and 10 pennies :::# 15 pennies ;Task: How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents). ;Optional: Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? (Note: the answer is larger than 232). ;References: * an algorithm from the book ''Structure and Interpretation of Computer Programs''. * an article in the algorithmist. * Change-making problem on Wikipedia.
try: import psyco psyco.full() except ImportError: pass def count_changes(amount_cents, coins): n = len(coins) # max([]) instead of max() for Psyco cycle = max([c+1 for c in coins if c <= amount_cents]) * n table = [0] * cycle for i in xrange(n): table[i] = 1 pos = n for s in xrange(1, amount_cents + 1): for i in xrange(n): if i == 0 and pos >= cycle: pos = 0 if coins[i] <= s: q = pos - coins[i] * n table[pos]= table[q] if (q >= 0) else table[q + cycle] if i: table[pos] += table[pos - 1] pos += 1 return table[pos - 1] def main(): us_coins = [100, 50, 25, 10, 5, 1] eu_coins = [200, 100, 50, 20, 10, 5, 2, 1] for coins in (us_coins, eu_coins): print count_changes( 100, coins[2:]) print count_changes( 100000, coins) print count_changes( 1000000, coins) print count_changes(10000000, coins), "\n" main()
Create an HTML table
Python
Create an HTML table. * The table body should have at least three rows of three columns. * Each of these three columns should be labelled "X", "Y", and "Z". * An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. * The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. * The numbers should be aligned in the same fashion for all columns.
import random def rand9999(): return random.randint(1000, 9999) def tag(attr='', **kwargs): for tag, txt in kwargs.items(): return '<{tag}{attr}>{txt}</{tag}>'.format(**locals()) if __name__ == '__main__': header = tag(tr=''.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\n' rows = '\n'.join(tag(tr=tag(' style="font-weight: bold;"', td=i) + ''.join(tag(td=rand9999()) for j in range(3))) for i in range(1, 6)) table = tag(table='\n' + header + rows + '\n') print(table)
Create an HTML table
Python 3.6
Create an HTML table. * The table body should have at least three rows of three columns. * Each of these three columns should be labelled "X", "Y", and "Z". * An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. * The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. * The numbers should be aligned in the same fashion for all columns.
from functools import (reduce) import itertools import random # HTML RENDERING ---------------------------------------- # treeHTML :: tree # {tag :: String, text :: String, kvs :: Dict} # -> HTML String def treeHTML(tree): return foldTree( lambda x: lambda xs: ( f"<{x['tag'] + attribString(x)}>" + ( str(x['text']) if 'text' in x else '\n' ) + ''.join(xs) + f"</{x['tag']}>\n" ) )(tree) # attribString :: Dict -> String def attribString(dct): kvs = dct['kvs'] if 'kvs' in dct else None return ' ' + reduce( lambda a, k: a + k + '="' + kvs[k] + '" ', kvs.keys(), '' ).strip() if kvs else '' # HTML TABLE FROM GENERATED DATA ------------------------ def main(): # Number of columns and rows to generate. n = 3 # Table details ------------------------------------- strCaption = 'Table generated with Python' colNames = take(n)(enumFrom('A')) dataRows = map( lambda x: (x, map( lambda _: random.randint(100, 9999), colNames )), take(n)(enumFrom(1))) tableStyle = { 'style': "width:25%; border:2px solid silver;" } trStyle = { 'style': "border:1px solid silver;text-align:right;" } # TREE STRUCTURE OF TABLE --------------------------- tableTree = Node({'tag': 'table', 'kvs': tableStyle})([ Node({ 'tag': 'caption', 'text': strCaption })([]), # HEADER ROW -------------------------------- (Node({'tag': 'tr'})( Node({ 'tag': 'th', 'kvs': {'style': 'text-align:right;'}, 'text': k })([]) for k in ([''] + colNames) )) ] + # DATA ROWS --------------------------------- list(Node({'tag': 'tr', 'kvs': trStyle})( [Node({'tag': 'th', 'text': tpl[0]})([])] + list(Node( {'tag': 'td', 'text': str(v)})([]) for v in tpl[1] ) ) for tpl in dataRows) ) print( treeHTML(tableTree) # dataRows ) # GENERIC ----------------------------------------------- # Node :: a -> [Tree a] -> Tree a def Node(v): return lambda xs: {'type': 'Node', 'root': v, 'nest': xs} # enumFrom :: Enum a => a -> [a] def enumFrom(x): return itertools.count(x) if type(x) is int else ( map(chr, itertools.count(ord(x))) ) # foldTree :: (a -> [b] -> b) -> Tree a -> b def foldTree(f): def go(node): return f(node['root'])( list(map(go, node['nest'])) ) return lambda tree: go(tree) # take :: Int -> [a] -> [a] # take :: Int -> String -> String def take(n): return lambda xs: ( xs[0:n] if isinstance(xs, list) else list(itertools.islice(xs, n)) ) if __name__ == '__main__': main()
Cullen and Woodall numbers
Python
A Cullen number is a number of the form '''n x 2n + 1''' where '''n''' is a natural number. A Woodall number is very similar. It is a number of the form '''n x 2n - 1''' where '''n''' is a natural number. So for each '''n''' the associated Cullen number and Woodall number differ by 2. ''Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.'' '''Cullen primes''' are Cullen numbers that are prime. Similarly, '''Woodall primes''' are Woodall numbers that are prime. It is common to list the Cullen and Woodall primes by the value of '''n''' rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, '''n''' == 4713, has 1423 digits when evaluated. ;Task * Write procedures to find Cullen numbers and Woodall numbers. * Use those procedures to find and show here, on this page the first 20 of each. ;Stretch * Find and show the first '''5''' '''Cullen primes''' in terms of '''n'''. * Find and show the first '''12''' '''Woodall primes''' in terms of '''n'''. ;See also * OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1 * OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1 * OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime * OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
print("working...") print("First 20 Cullen numbers:") for n in range(1,21): num = n*pow(2,n)+1 print(str(num),end= " ") print() print("First 20 Woodall numbers:") for n in range(1,21): num = n*pow(2,n)-1 print(str(num),end=" ") print() print("done...")
Cullen and Woodall numbers
Python from Quackery
A Cullen number is a number of the form '''n x 2n + 1''' where '''n''' is a natural number. A Woodall number is very similar. It is a number of the form '''n x 2n - 1''' where '''n''' is a natural number. So for each '''n''' the associated Cullen number and Woodall number differ by 2. ''Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.'' '''Cullen primes''' are Cullen numbers that are prime. Similarly, '''Woodall primes''' are Woodall numbers that are prime. It is common to list the Cullen and Woodall primes by the value of '''n''' rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, '''n''' == 4713, has 1423 digits when evaluated. ;Task * Write procedures to find Cullen numbers and Woodall numbers. * Use those procedures to find and show here, on this page the first 20 of each. ;Stretch * Find and show the first '''5''' '''Cullen primes''' in terms of '''n'''. * Find and show the first '''12''' '''Woodall primes''' in terms of '''n'''. ;See also * OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1 * OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1 * OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime * OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
def cullen(n): return((n<<n)+1) def woodall(n): return((n<<n)-1) print("First 20 Cullen numbers:") for i in range(1,21): print(cullen(i),end=" ") print() print() print("First 20 Woodall numbers:") for i in range(1,21): print(woodall(i),end=" ") print()
Currency
Python
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents. ;Note: The '''IEEE 754''' binary floating point representations of numbers like '''2.86''' and '''.0765''' are not exact. For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate. Use the values: ::* 4000000000000000 hamburgers at $5.50 each (four quadrillion burgers) ::* 2 milkshakes at $2.86 each, and ::* a tax rate of 7.65%. (That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naive task solutions using 64 bit floating point types.) Compute and output (show results on this page): ::* the total price before tax ::* the tax ::* the total with tax The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax. The output must show dollars and cents with a decimal point. The three results displayed should be: ::* 22000000000000005.72 ::* 1683000000000000.44 ::* 23683000000000006.16 Dollar signs and thousands separators are optional.
from decimal import Decimal as D from collections import namedtuple Item = namedtuple('Item', 'price, quant') items = dict( hamburger=Item(D('5.50'), D('4000000000000000')), milkshake=Item(D('2.86'), D('2')) ) tax_rate = D('0.0765') fmt = "%-10s %8s %18s %22s" print(fmt % tuple('Item Price Quantity Extension'.upper().split())) total_before_tax = 0 for item, (price, quant) in sorted(items.items()): ext = price * quant print(fmt % (item, price, quant, ext)) total_before_tax += ext print(fmt % ('', '', '', '--------------------')) print(fmt % ('', '', 'subtotal', total_before_tax)) tax = (tax_rate * total_before_tax).quantize(D('0.00')) print(fmt % ('', '', 'Tax', tax)) total = total_before_tax + tax print(fmt % ('', '', '', '--------------------')) print(fmt % ('', '', 'Total', total))
Currying
Python
{{Wikipedia|Currying}} ;Task: Create a simple demonstrative example of Currying in a specific language. Add any historic details as to how the feature made its way into the language.
# AUTOMATIC CURRYING AND UNCURRYING OF EXISTING FUNCTIONS # curry :: ((a, b) -> c) -> a -> b -> c def curry(f): return lambda a: lambda b: f(a, b) # uncurry :: (a -> b -> c) -> ((a, b) -> c) def uncurry(f): return lambda x, y: f(x)(y) # EXAMPLES -------------------------------------- # A plain uncurried function with 2 arguments, # justifyLeft :: Int -> String -> String def justifyLeft(n, s): return (s + (n * ' '))[:n] # and a similar, but manually curried, function. # justifyRight :: Int -> String -> String def justifyRight(n): return lambda s: ( ((n * ' ') + s)[-n:] ) # CURRYING and UNCURRYING at run-time: def main(): for s in [ 'Manually curried using a lambda:', '\n'.join(map( justifyRight(5), ['1', '9', '10', '99', '100', '1000'] )), '\nAutomatically uncurried:', uncurry(justifyRight)(5, '10000'), '\nAutomatically curried', '\n'.join(map( curry(justifyLeft)(10), ['1', '9', '10', '99', '100', '1000'] )) ]: print (s) main()
Curzon numbers
Python
A '''Curzon number''' is defined to be a positive integer '''n''' for which '''2n + 1''' is evenly divisible by '''2 x n + 1'''. '''Generalized Curzon numbers''' are those where the positive integer '''n''', using a base integer '''k''', satisfy the condition that '''kn + 1''' is evenly divisible by '''k x n + 1'''. ''Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.'' Generalized Curzon numbers only exist for even base integers. ;Task * Find and show the first '''50 Generalized Curzon numbers''' for even base integers from '''2''' through '''10'''. ;Stretch * Find and show the '''one thousandth'''. ;See also ;* Numbers Aplenty - Curzon numbers ;* OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers) ''and even though it is not specifically mentioned that they are Curzon numbers:'' ;* OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
def is_Curzon(n, k): r = k * n return pow(k, n, r + 1) == r for k in [2, 4, 6, 8, 10]: n, curzons = 1, [] while len(curzons) < 1000: if is_Curzon(n, k): curzons.append(n) n += 1 print(f'Curzon numbers with k = {k}:') for i, c in enumerate(curzons[:50]): print(f'{c: 5,}', end='\n' if (i + 1) % 25 == 0 else '') print(f' Thousandth Curzon with k = {k}: {curzons[999]}.\n')
Cut a rectangle
Python from D
A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below. [[file:rect-cut.svg]] Write a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts. Possibly related task: [[Maze generation]] for depth-first search.
try: import psyco except ImportError: pass else: psyco.full() w, h = 0, 0 count = 0 vis = [] def cwalk(y, x, d): global vis, count, w, h if not y or y == h or not x or x == w: count += 1 return vis[y][x] = vis[h - y][w - x] = 1 if x and not vis[y][x - 1]: cwalk(y, x - 1, d | 1) if (d & 1) and x < w and not vis[y][x+1]: cwalk(y, x + 1, d|1) if y and not vis[y - 1][x]: cwalk(y - 1, x, d | 2) if (d & 2) and y < h and not vis[y + 1][x]: cwalk(y + 1, x, d | 2) vis[y][x] = vis[h - y][w - x] = 0 def count_only(x, y): global vis, count, w, h count = 0 w = x h = y if (h * w) & 1: return count if h & 1: w, h = h, w vis = [[0] * (w + 1) for _ in xrange(h + 1)] vis[h // 2][w // 2] = 1 if w & 1: vis[h // 2][w // 2 + 1] = 1 res = 0 if w > 1: cwalk(h // 2, w // 2 - 1, 1) res = 2 * count - 1 count = 0 if w != h: cwalk(h // 2 + 1, w // 2, 3 if (w & 1) else 2) res += 2 * count - (not (w & 1)) else: res = 1 if w == h: res = 2 * res + 2 return res def main(): for y in xrange(1, 10): for x in xrange(1, y + 1): if not (x & 1) or not (y & 1): print "%d x %d: %d" % (y, x, count_only(x, y)) main()
Cyclotomic polynomial
Python
The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n - 1, and is not a divisor of x^k - 1 for any k < n. ;Task: * Find and print the first 30 cyclotomic polynomials. * Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient. ;See also * Wikipedia article, Cyclotomic polynomial, showing ways to calculate them. * The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient.
from itertools import count, chain from collections import deque def primes(_cache=[2, 3]): yield from _cache for n in count(_cache[-1]+2, 2): if isprime(n): _cache.append(n) yield n def isprime(n): for p in primes(): if n%p == 0: return False if p*p > n: return True def factors(n): for p in primes(): # prime factoring is such a non-issue for small numbers that, for # this example, we might even just say # for p in count(2): if p*p > n: if n > 1: yield(n, 1, 1) break if n%p == 0: cnt = 0 while True: n, cnt = n//p, cnt+1 if n%p != 0: break yield p, cnt, n # ^^ not the most sophisticated prime number routines, because no need # Returns (list1, list2) representing the division between # two polinomials. A list p of integers means the product # (x^p[0] - 1) * (x^p[1] - 1) * ... def cyclotomic(n): def poly_div(num, den): return (num[0] + den[1], num[1] + den[0]) def elevate(poly, n): # replace poly p(x) with p(x**n) powerup = lambda p, n: [a*n for a in p] return poly if n == 1 else (powerup(poly[0], n), powerup(poly[1], n)) if n == 0: return ([], []) if n == 1: return ([1], []) p, m, r = next(factors(n)) poly = cyclotomic(r) return elevate(poly_div(elevate(poly, p), poly), p**(m-1)) def to_text(poly): def getx(c, e): if e == 0: return '1' elif e == 1: return 'x' return 'x' + (''.join('⁰¹²³⁴⁵⁶⁷⁸⁹'[i] for i in map(int, str(e)))) parts = [] for (c,e) in (poly): if c < 0: coef = ' - ' if c == -1 else f' - {-c} ' else: coef = (parts and ' + ' or '') if c == 1 else f' + {c}' parts.append(coef + getx(c,e)) return ''.join(parts) def terms(poly): # convert above representation of division to (coef, power) pairs def merge(a, b): # a, b should be deques. They may change during the course. while a or b: l = a[0] if a else (0, -1) # sentinel value r = b[0] if b else (0, -1) if l[1] > r[1]: a.popleft() elif l[1] < r[1]: b.popleft() l = r else: a.popleft() b.popleft() l = (l[0] + r[0], l[1]) yield l def mul(poly, p): # p means polynomial x^p - 1 poly = list(poly) return merge(deque((c, e+p) for c,e in poly), deque((-c, e) for c,e in poly)) def div(poly, p): # p means polynomial x^p - 1 q = deque() for c,e in merge(deque(poly), q): if c: q.append((c, e - p)) yield (c, e - p) if e == p: break p = [(1, 0)] # 1*x^0, i.e. 1 for x in poly[0]: # numerator p = mul(p, x) for x in sorted(poly[1], reverse=True): # denominator p = div(p, x) return p for n in chain(range(11), [2]): print(f'{n}: {to_text(terms(cyclotomic(n)))}') want = 1 for n in count(): c = [c for c,_ in terms(cyclotomic(n))] while want in c or -want in c: print(f'C[{want}]: {n}') want += 1
Damm algorithm
Python
The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. ;Task: Verify the checksum, stored as last digit of an input.
def damm(num: int) -> bool: row = 0 for digit in str(num): row = _matrix[row][int(digit)] return row == 0 _matrix = ( (0, 3, 1, 7, 5, 9, 8, 6, 4, 2), (7, 0, 9, 2, 1, 5, 4, 8, 6, 3), (4, 2, 0, 6, 8, 7, 1, 3, 5, 9), (1, 7, 5, 0, 9, 8, 3, 4, 2, 6), (6, 1, 2, 3, 0, 4, 5, 9, 7, 8), (3, 6, 7, 4, 2, 0, 9, 5, 8, 1), (5, 8, 6, 9, 7, 2, 0, 1, 3, 4), (8, 9, 4, 5, 3, 6, 2, 0, 1, 7), (9, 4, 3, 8, 6, 1, 7, 2, 0, 5), (2, 5, 8, 1, 4, 3, 6, 7, 9, 0) ) if __name__ == '__main__': for test in [5724, 5727, 112946]: print(f'{test}\t Validates as: {damm(test)}')
De Bruijn sequences
Python
{{DISPLAYTITLE:de Bruijn sequences}} The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn. A note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized unless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be capitalized. In combinatorial mathematics, a '''de Bruijn sequence''' of order ''n'' on a size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every possible length-''n'' string (computer science, formal theory) on ''A'' occurs exactly once as a contiguous substring. Such a sequence is denoted by ''B''(''k'', ''n'') and has length ''k''''n'', which is also the number of distinct substrings of length ''n'' on ''A''; de Bruijn sequences are therefore optimally short. There are: (k!)k(n-1) / kn distinct de Bruijn sequences ''B''(''k'', ''n''). ;Task: For this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on a PIN-like code lock that does not have an "enter" key and accepts the last ''n'' digits entered. Note: automated teller machines (ATMs) used to work like this, but their software has been updated to not allow a brute-force attack. ;Example: A digital door lock with a 4-digit code would have ''B'' (10, 4) solutions, with a length of '''10,000''' (digits). Therefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to open the lock. Trying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses. ;Task requirements: :* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code. :::* Show the length of the generated de Bruijn sequence. :::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page). :::* Show the first and last '''130''' digits of the de Bruijn sequence. :* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence. :::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros). :* Reverse the de Bruijn sequence. :* Again, perform the (above) verification test. :* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence. :::* Perform the verification test (again). There should be four PIN codes missing. (The last requirement is to ensure that the verification tests performs correctly. The verification processes should list any and all missing PIN codes.) Show all output here, on this page. ;References: :* Wikipedia entry: de Bruijn sequence. :* MathWorld entry: de Bruijn sequence. :* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.
# from https://en.wikipedia.org/wiki/De_Bruijn_sequence def de_bruijn(k, n): """ de Bruijn sequence for alphabet k and subsequences of length n. """ try: # let's see if k can be cast to an integer; # if so, make our alphabet a list _ = int(k) alphabet = list(map(str, range(k))) except (ValueError, TypeError): alphabet = k k = len(k) a = [0] * k * n sequence = [] def db(t, p): if t > n: if n % p == 0: sequence.extend(a[1:p + 1]) else: a[t] = a[t - p] db(t + 1, p) for j in range(a[t - p] + 1, k): a[t] = j db(t + 1, t) db(1, 1) return "".join(alphabet[i] for i in sequence) def validate(db): """ Check that all 10,000 combinations of 0-9 are present in De Bruijn string db. Validating the reversed deBruijn sequence: No errors found Validating the overlaid deBruijn sequence: 4 errors found: PIN number 1459 missing PIN number 4591 missing PIN number 5814 missing PIN number 8145 missing """ dbwithwrap = db+db[0:3] digits = '0123456789' errorstrings = [] for d1 in digits: for d2 in digits: for d3 in digits: for d4 in digits: teststring = d1+d2+d3+d4 if teststring not in dbwithwrap: errorstrings.append(teststring) if len(errorstrings) > 0: print(" "+str(len(errorstrings))+" errors found:") for e in errorstrings: print(" PIN number "+e+" missing") else: print(" No errors found") db = de_bruijn(10, 4) print(" ") print("The length of the de Bruijn sequence is ", str(len(db))) print(" ") print("The first 130 digits of the de Bruijn sequence are: "+db[0:130]) print(" ") print("The last 130 digits of the de Bruijn sequence are: "+db[-130:]) print(" ") print("Validating the deBruijn sequence:") validate(db) dbreversed = db[::-1] print(" ") print("Validating the reversed deBruijn sequence:") validate(dbreversed) dboverlaid = db[0:4443]+'.'+db[4444:] print(" ") print("Validating the overlaid deBruijn sequence:") validate(dboverlaid)
Deceptive numbers
Python
Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation '''Rn''' symbolizes the repunit made up of '''n''' ones. Every prime '''p''' larger than 5, evenly divides the repunit '''Rp-1'''. ;E.G. The repunit '''R6''' is evenly divisible by '''7'''. 111111 / 7 = 15873 The repunit '''R42''' is evenly divisible by '''43'''. 111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677 And so on. There are composite numbers that also have this same property. They are often referred to as ''deceptive non-primes'' or ''deceptive numbers''. The repunit '''R90''' is evenly divisible by the composite number '''91''' (=7*13). 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221 ;Task * Find and show at least the first '''10 deceptive numbers'''; composite numbers '''n''' that evenly divide the repunit '''Rn-1''' ;See also ;* Numbers Aplenty - Deceptive numbers ;* OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}
from itertools import count, islice from math import isqrt def is_deceptive(n): if n & 1 and n % 3 and n % 5 and pow(10, n - 1, n) == 1: for d in range(7, isqrt(n) + 1, 6): if not (n % d and n % (d + 4)): return True return False print(*islice(filter(is_deceptive, count()), 100))
Deming's funnel
Python from Racket
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target. * '''Rule 1''': The funnel remains directly above the target. * '''Rule 2''': Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position. * '''Rule 3''': As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target. * '''Rule 4''': The funnel is moved directly over the last place a marble landed. Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. '''Output''': calculate the mean and standard-deviations of the resulting x and y values for each rule. Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples. '''Stretch goal 1''': Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed. '''Stretch goal 2''': Show scatter plots of all four results. ;Further information: * Further explanation and interpretation * Video demonstration of the funnel experiment at the Mayo Clinic.
import math dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915, 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087] dys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032] def funnel(dxs, rule): x, rxs = 0, [] for dx in dxs: rxs.append(x + dx) x = rule(x, dx) return rxs def mean(xs): return sum(xs) / len(xs) def stddev(xs): m = mean(xs) return math.sqrt(sum((x-m)**2 for x in xs) / len(xs)) def experiment(label, rule): rxs, rys = funnel(dxs, rule), funnel(dys, rule) print label print 'Mean x, y : %.4f, %.4f' % (mean(rxs), mean(rys)) print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys)) print experiment('Rule 1:', lambda z, dz: 0) experiment('Rule 2:', lambda z, dz: -dz) experiment('Rule 3:', lambda z, dz: -(z+dz)) experiment('Rule 4:', lambda z, dz: z+dz)
Department numbers
Python
There is a highly organized city that has decided to assign a number to each of their departments: ::* police department ::* sanitation department ::* fire department Each department can have a number between '''1''' and '''7''' (inclusive). The three department numbers are to be unique (different from each other) and must add up to '''12'''. The Chief of the Police doesn't like odd numbers and wants to have an even number for his department. ;Task: Write a computer program which outputs all valid combinations. Possible output (for the 1st and 14th solutions): --police-- --sanitation-- --fire-- 2 3 7 6 5 1
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()
Department numbers
Python 3
There is a highly organized city that has decided to assign a number to each of their departments: ::* police department ::* sanitation department ::* fire department Each department can have a number between '''1''' and '''7''' (inclusive). The three department numbers are to be unique (different from each other) and must add up to '''12'''. The Chief of the Police doesn't like odd numbers and wants to have an even number for his department. ;Task: Write a computer program which outputs all valid combinations. Possible output (for the 1st and 14th solutions): --police-- --sanitation-- --fire-- 2 3 7 6 5 1
'''Department numbers''' from itertools import (chain) from operator import (ne) # options :: Int -> Int -> Int -> [(Int, Int, Int)] def options(lo, hi, total): '''Eligible integer triples.''' ds = enumFromTo(lo)(hi) return bind(filter(even, ds))( lambda x: bind(filter(curry(ne)(x), ds))( lambda y: bind([total - (x + y)])( lambda z: [(x, y, z)] if ( z != y and lo <= z <= hi ) else [] ) ) ) # TEST ---------------------------------------------------- # main :: IO () def main(): '''Test''' xs = options(1, 7, 12) print(('Police', 'Sanitation', 'Fire')) for tpl in xs: print(tpl) print('\nNo. of options: ' + str(len(xs))) # GENERIC ABSTRACTIONS ------------------------------------ # 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) ) ) # 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) # enumFromTo :: (Int, Int) -> [Int] def enumFromTo(m): '''Integer enumeration from m to n.''' return lambda n: list(range(m, 1 + n)) # even :: Int -> Bool def even(x): '''True if x is an integer multiple of two.''' return 0 == x % 2 if __name__ == '__main__': main()
Department numbers
Python 3.7
There is a highly organized city that has decided to assign a number to each of their departments: ::* police department ::* sanitation department ::* fire department Each department can have a number between '''1''' and '''7''' (inclusive). The three department numbers are to be unique (different from each other) and must add up to '''12'''. The Chief of the Police doesn't like odd numbers and wants to have an even number for his department. ;Task: Write a computer program which outputs all valid combinations. Possible output (for the 1st and 14th solutions): --police-- --sanitation-- --fire-- 2 3 7 6 5 1
'''Department numbers''' from operator import ne # options :: Int -> Int -> Int -> [(Int, Int, Int)] def options(lo, hi, total): '''Eligible triples.''' ds = enumFromTo(lo)(hi) return [ (x, y, z) for x in filter(even, ds) for y in filter(curry(ne)(x), ds) for z in [total - (x + y)] if y != z and lo <= z <= hi ] # Or with less tightly-constrained generation, # and more winnowing work downstream: # options2 :: Int -> Int -> Int -> [(Int, Int, Int)] def options2(lo, hi, total): '''Eligible triples.''' ds = enumFromTo(lo)(hi) return [ (x, y, z) for x in ds for y in ds for z in [total - (x + y)] if even(x) and y not in [x, z] and lo <= z <= hi ] # GENERIC ------------------------------------------------- # 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) # enumFromTo :: (Int, Int) -> [Int] def enumFromTo(m): '''Integer enumeration from m to n.''' return lambda n: list(range(m, 1 + n)) # even :: Int -> Bool def even(x): '''True if x is an integer multiple of two.''' return 0 == x % 2 # 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) # TEST ---------------------------------------------------- # main :: IO () def main(): '''Test''' xs = options(1, 7, 12) print(('Police', 'Sanitation', 'Fire')) print(unlines(map(str, xs))) print('\nNo. of options: ' + str(len(xs))) if __name__ == '__main__': main()
Descending primes
Python
Generate and show all primes with strictly descending decimal digits. ;See also ;* OEIS:A052014 - Primes with distinct digits in descending order ;Related: *[[Ascending primes]]
from sympy import isprime def descending(xs=range(10)): for x in xs: yield x yield from descending(x*10 + d for d in range(x%10)) for i, p in enumerate(sorted(filter(isprime, descending()))): print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n') print()
Detect division by zero
Python
Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.
def div_check(x, y): try: x / y except ZeroDivisionError: return True else: return False
Determinant and permanent
Python
permanent of the matrix. The determinant is given by :: \det(A) = \sum_\sigma\sgn(\sigma)\prod_{i=1}^n M_{i,\sigma_i} while the permanent is given by :: \operatorname{perm}(A)=\sum_\sigma\prod_{i=1}^n M_{i,\sigma_i} In both cases the sum is over the permutations \sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.) More efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known. ;Related task: * [[Permutations by swapping]]
from itertools import permutations from operator import mul from math import fsum from spermutations import spermutations def prod(lst): return reduce(mul, lst, 1) def perm(a): n = len(a) r = range(n) s = permutations(r) return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s) def det(a): n = len(a) r = range(n) s = spermutations(n) return fsum(sign * prod(a[i][sigma[i]] for i in r) for sigma, sign in s) if __name__ == '__main__': from pprint import pprint as pp for a in ( [ [1, 2], [3, 4]], [ [1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]], [ [ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]], ): print('') pp(a) print('Perm: %s Det: %s' % (perm(a), det(a)))
Determine if a string has all the same characters
Python
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are the same ::::* indicate if or which character is different from the previous character ::* display each string and its length (as the strings are being examined) ::* a zero-length (empty) string shall be considered as all the same character(s) ::* process the strings from left-to-right ::* if all the same character, display a message saying such ::* if not all the same character, then: ::::* display a message saying such ::::* display what character is different ::::* only the 1st different character need be displayed ::::* display where the different character is in the string ::::* the above messages can be part of a single message ::::* display the hexadecimal value of the different character Use (at least) these seven test values (strings): :::* a string of length 0 (an empty string) :::* a string of length 3 which contains three blanks :::* a string of length 1 which contains: '''2''' :::* a string of length 3 which contains: '''333''' :::* a string of length 3 which contains: '''.55''' :::* a string of length 6 which contains: '''tttTTT''' :::* a string of length 9 with a blank in the middle: '''4444 444k''' Show all output here on this page.
===Functional=== What we are testing here is the cardinality of the set of characters from which a string is drawn, so the first thought might well be to use '''set'''. On the other hand, '''itertools.groupby''' has the advantage of yielding richer information (the list of groups is ordered), for less work.
Determine if a string has all the same characters
Python 3.7
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are the same ::::* indicate if or which character is different from the previous character ::* display each string and its length (as the strings are being examined) ::* a zero-length (empty) string shall be considered as all the same character(s) ::* process the strings from left-to-right ::* if all the same character, display a message saying such ::* if not all the same character, then: ::::* display a message saying such ::::* display what character is different ::::* only the 1st different character need be displayed ::::* display where the different character is in the string ::::* the above messages can be part of a single message ::::* display the hexadecimal value of the different character Use (at least) these seven test values (strings): :::* a string of length 0 (an empty string) :::* a string of length 3 which contains three blanks :::* a string of length 1 which contains: '''2''' :::* a string of length 3 which contains: '''333''' :::* a string of length 3 which contains: '''.55''' :::* a string of length 6 which contains: '''tttTTT''' :::* a string of length 9 with a blank in the middle: '''4444 444k''' Show all output here on this page.
'''Determine if a string has all the same characters''' from itertools import groupby # firstDifferingCharLR :: String -> Either String Dict def firstDifferingCharLR(s): '''Either a message reporting that no character changes were seen, or a dictionary with details of the first character (if any) that differs from that at the head of the string. ''' def details(xs): c = xs[1][0] return { 'char': repr(c), 'hex': hex(ord(c)), 'index': s.index(c), 'total': len(s) } xs = list(groupby(s)) return Right(details(xs)) if 1 < len(xs) else ( Left('Total length ' + str(len(s)) + ' - No character changes.') ) # TEST ---------------------------------------------------- # main :: IO () def main(): '''Test of 7 strings''' print(fTable('First, if any, points of difference:\n')(repr)( either(identity)( lambda dct: dct['char'] + ' (' + dct['hex'] + ') at character ' + str(1 + dct['index']) + ' of ' + str(dct['total']) + '.' ) )(firstDifferingCharLR)([ '', ' ', '2', '333', '.55', 'tttTTT', '4444 444' ])) # GENERIC ------------------------------------------------- # either :: (a -> c) -> (b -> c) -> Either a b -> c def either(fl): '''The application of fl to e if e is a Left value, or the application of fr to e if e is a Right value. ''' return lambda fr: lambda e: fl(e['Left']) if ( None is e['Right'] ) else fr(e['Right']) # identity :: a -> a def identity(x): '''The identity function.''' return x # 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 ) # Left :: a -> Either a b def Left(x): '''Constructor for an empty Either (option type) value with an associated string. ''' return {'type': 'Either', 'Right': None, 'Left': x} # Right :: b -> Either a b def Right(x): '''Constructor for a populated Either (option type) value''' return {'type': 'Either', 'Left': None, 'Right': x} # MAIN --- if __name__ == '__main__': main()
Determine if a string has all unique characters
Python
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are unique ::::* indicate if or which character is duplicated and where ::* display each string and its length (as the strings are being examined) ::* a zero-length (empty) string shall be considered as unique ::* process the strings from left-to-right ::* if unique, display a message saying such ::* if not unique, then: ::::* display a message saying such ::::* display what character is duplicated ::::* only the 1st non-unique character need be displayed ::::* display where "both" duplicated characters are in the string ::::* the above messages can be part of a single message ::::* display the hexadecimal value of the duplicated character Use (at least) these five test values (strings): :::* a string of length 0 (an empty string) :::* a string of length 1 which is a single period ('''.''') :::* a string of length 6 which contains: '''abcABC''' :::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX''' :::* a string of length 36 which ''doesn't'' contain the letter "oh": :::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ''' Show all output here on this page.
'''Determine if a string has all unique characters''' from itertools import groupby # duplicatedCharIndices :: String -> Maybe (Char, [Int]) def duplicatedCharIndices(s): '''Just the first duplicated character, and the indices of its occurrence, or Nothing if there are no duplications. ''' def go(xs): if 1 < len(xs): duplicates = list(filter(lambda kv: 1 < len(kv[1]), [ (k, list(v)) for k, v in groupby( sorted(xs, key=swap), key=snd ) ])) return Just(second(fmap(fst))( sorted( duplicates, key=lambda kv: kv[1][0] )[0] )) if duplicates else Nothing() else: return Nothing() return go(list(enumerate(s))) # TEST ---------------------------------------------------- # main :: IO () def main(): '''Test over various strings.''' def showSample(s): return repr(s) + ' (' + str(len(s)) + ')' def showDuplicate(cix): c, ix = cix return repr(c) + ( ' (' + hex(ord(c)) + ') at ' + repr(ix) ) print( fTable('First duplicated character, if any:')( showSample )(maybe('None')(showDuplicate))(duplicatedCharIndices)([ '', '.', 'abcABC', 'XYZ ZYX', '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ' ]) ) # 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 ) # GENERIC ------------------------------------------------- # Just :: a -> Maybe a def Just(x): '''Constructor for an inhabited Maybe (option type) value. Wrapper containing the result of a computation. ''' return {'type': 'Maybe', 'Nothing': False, 'Just': x} # Nothing :: Maybe a def Nothing(): '''Constructor for an empty Maybe (option type) value. Empty wrapper returned where a computation is not possible. ''' return {'type': 'Maybe', 'Nothing': True} # fmap :: (a -> b) -> [a] -> [b] def fmap(f): '''fmap over a list. f lifted to a function over a list. ''' return lambda xs: [f(x) for x in xs] # fst :: (a, b) -> a def fst(tpl): '''First member of a pair.''' return tpl[0] # head :: [a] -> a def head(xs): '''The first element of a non-empty list.''' return xs[0] if isinstance(xs, list) else next(xs) # maybe :: b -> (a -> b) -> Maybe a -> b def maybe(v): '''Either the default value v, if m is Nothing, or the application of f to x, where m is Just(x). ''' return lambda f: lambda m: v if ( None is m or m.get('Nothing') ) else f(m.get('Just')) # second :: (a -> b) -> ((c, a) -> (c, b)) def second(f): '''A simple function lifted to a function over a tuple, with f applied only to the second of two values. ''' return lambda xy: (xy[0], f(xy[1])) # snd :: (a, b) -> b def snd(tpl): '''Second member of a pair.''' return tpl[1] # swap :: (a, b) -> (b, a) def swap(tpl): '''The swapped components of a pair.''' return (tpl[1], tpl[0]) # MAIN --- if __name__ == '__main__': main()
Determine if a string is collapsible
Python
Determine if a character string is ''collapsible''. And if so, collapse the string (by removing ''immediately repeated'' characters). If a character string has ''immediately repeated'' character(s), the repeated characters are to be deleted (removed), but not the primary (1st) character(s). An ''immediately repeated'' character is any character that is immediately followed by an identical character (or characters). Another word choice could've been ''duplicated character'', but that might have ruled out (to some readers) triplicated characters *** or more. {This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.} ;Examples: In the following character string: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated by underscores (above), even though they (those characters) appear elsewhere in the character string. So, after ''collapsing'' the string, the result would be: The beter the 4-whel drive, the further you'l be from help when ya get stuck! Another example: In the following character string: headmistressship The "collapsed" string would be: headmistreship ;Task: Write a subroutine/function/procedure/routine*** to locate ''repeated'' characters and ''collapse'' (delete) them from the character string. The character string can be processed from either direction. Show all output here, on this page: :* the original string and its length :* the resultant string and its length :* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks) ;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>> Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except the 1st string: string number ++ 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero) 2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln | 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | 5 | --- Harry S Truman | <###### has many repeated blanks +------------------------------------------------------------------------+
from itertools import groupby def collapser(txt): return ''.join(item for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "😍😀🙌💃😍😍😍🙌", ] for txt in strings: this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) this = "Collapsed" sqz = collapser(txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Determine if a string is squeezable
Python
Determine if a character string is ''squeezable''. And if so, squeeze the string (by removing any number of a ''specified'' ''immediately repeated'' character). This task is very similar to the task '''Determine if a character string is collapsible''' except that only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''. If a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be deleted (removed), but not the primary (1st) character(s). A specified ''immediately repeated'' character is any specified character that is immediately followed by an identical character (or characters). Another word choice could've been ''duplicated character'', but that might have ruled out (to some readers) triplicated characters *** or more. {This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''squeeze'''.} ;Examples: In the following character string with a specified ''immediately repeated'' character of '''e''': The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd '''e''' is an specified repeated character, indicated by an underscore (above), even though they (the characters) appear elsewhere in the character string. So, after ''squeezing'' the string, the result would be: The better the 4-whel drive, the further you'll be from help when ya get stuck! Another example: In the following character string, using a specified immediately repeated character '''s''': headmistressship The "squeezed" string would be: headmistreship ;Task: Write a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character and ''squeeze'' (delete) them from the character string. The character string can be processed from either direction. Show all output here, on this page: :* the specified repeated character (to be searched for and possibly ''squeezed''): :* the original string and its length :* the resultant string and its length :* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks) ;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>> Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except the 1st string: immediately string repeated number character ( | a blank, a minus, a seven, a period) ++ 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero) 2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln | '-' 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7' 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.' 5 | --- Harry S Truman | (below) <###### has many repeated blanks +------------------------------------------------------------------------+ | | | For the 5th string (Truman's signature line), use each of these specified immediately repeated characters: * a blank * a minus * a lowercase '''r''' Note: there should be seven results shown, one each for the 1st four strings, and three results for the 5th string.
from itertools import groupby def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt)) if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "😍😀🙌💃😍😍😍🙌", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Dice game probabilities
Python
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player? Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player? This task was adapted from the Project Euler Problem n.205: https://projecteuler.net/problem=205
from itertools import product def gen_dict(n_faces, n_dice): counts = [0] * ((n_faces + 1) * n_dice) for t in product(range(1, n_faces + 1), repeat=n_dice): counts[sum(t)] += 1 return counts, n_faces ** n_dice def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2): c1, p1 = gen_dict(n_sides1, n_dice1) c2, p2 = gen_dict(n_sides2, n_dice2) p12 = float(p1 * p2) return sum(p[1] * q[1] / p12 for p, q in product(enumerate(c1), enumerate(c2)) if p[0] > q[0]) print beating_probability(4, 9, 6, 6) print beating_probability(10, 5, 7, 6)
Digital root
Python
The digital root, X, of a number, n, is calculated: : find X as the sum of the digits of n : find a new X by summing the digits of X, repeating until X has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: :627615 has additive persistence 2 and digital root of 9; :39390 has additive persistence 2 and digital root of 6; :588225 has additive persistence 2 and digital root of 3; :393900588225 has additive persistence 2 and digital root of 9; The digital root may be calculated in bases other than 10. ;See: * [[Casting out nines]] for this wiki's use of this procedure. * [[Digital root/Multiplicative digital root]] * [[Sum digits of an integer]] * Digital root sequence on OEIS * Additive persistence sequence on OEIS * [[Iterated digits squaring]]
def digital_root (n): ap = 0 n = abs(int(n)) while n >= 10: n = sum(int(digit) for digit in str(n)) ap += 1 return ap, n if __name__ == '__main__': for n in [627615, 39390, 588225, 393900588225, 55]: persistance, root = digital_root(n) print("%12i has additive persistance %2i and digital root %i." % (n, persistance, root))
Disarium numbers
Python
A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. ;E.G. '''135''' is a '''Disarium number''': 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of '''Disarium numbers'''. ;Task * Find and display the first 18 '''Disarium numbers'''. ;Stretch * Find and display all 20 '''Disarium numbers'''. ;See also ;* Geeks for Geeks - Disarium numbers ;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) ;* Related task: Narcissistic decimal number ;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''
#!/usr/bin/python def isDisarium(n): digitos = len(str(n)) suma = 0 x = n while x != 0: suma += (x % 10) ** digitos digitos -= 1 x //= 10 if suma == n: return True else: return False if __name__ == '__main__': limite = 19 cont = 0 n = 0 print("The first",limite,"Disarium numbers are:") while cont < limite: if isDisarium(n): print(n, end = " ") cont += 1 n += 1
Display a linear combination
Python
Display a finite linear combination in an infinite vector basis (e_1, e_2,\ldots). Write a function that, when given a finite list of scalars (\alpha^1,\alpha^2,\ldots), creates a string representing the linear combination \sum_i\alpha^i e_i in an explicit format often used in mathematics, that is: :\alpha^{i_1}e_{i_1}\pm|\alpha^{i_2}|e_{i_2}\pm|\alpha^{i_3}|e_{i_3}\pm\ldots where \alpha^{i_k}\neq 0 The output must comply to the following rules: * don't show null terms, unless the whole combination is null. ::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong. * don't show scalars when they are equal to one or minus one. ::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong. * don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. ::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong. Show here output for the following lists of scalars: 1) 1, 2, 3 2) 0, 1, 2, 3 3) 1, 0, 3, 4 4) 1, 2, 0 5) 0, 0, 0 6) 0 7) 1, 1, 1 8) -1, -1, -1 9) -1, -2, 0, -3 10) -1
def linear(x): return ' + '.join(['{}e({})'.format('-' if v == -1 else '' if v == 1 else str(v) + '*', i + 1) for i, v in enumerate(x) if v] or ['0']).replace(' + -', ' - ') list(map(lambda x: print(linear(x)), [[1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0], [0, 0, 0], [0], [1, 1, 1], [-1, -1, -1], [-1, -2, 0, 3], [-1]]))
Display an outline as a nested table
Python
{| class="wikitable" style="text-align: center;" |- | style="background: #ffffe6; " colspan=7 | Display an outline as a nested table. |- | style="background: #ffebd2; " colspan=3 | Parse the outline to a tree, | style="background: #f0fff0; " colspan=2 | count the leaves descending from each node, | style="background: #e6ffff; " colspan=2 | and write out a table with 'colspan' values |- | style="background: #ffebd2; " | measuring the indent of each line, | style="background: #ffebd2; " | translating the indentation to a nested structure, | style="background: #ffebd2; " | and padding the tree to even depth. | style="background: #f0fff0; " | defining the width of a leaf as 1, | style="background: #f0fff0; " | and the width of a parent node as a sum. | style="background: #e6ffff; " | either as a wiki table, | style="background: #e6ffff; " | or as HTML. |- | | | | | | | | | style="background: #f0fff0; " | (The sum of the widths of its children) | | | | |} The graphic representation of outlines is a staple of mind-mapping and the planning of papers, reports, and speeches. ;Task: Given a outline with at least 3 levels of indentation, for example: Display an outline as a nested table. Parse the outline to a tree, measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even depth. count the leaves descending from each node, defining the width of a leaf as 1, and the width of a parent node as a sum. (The sum of the widths of its children) and write out a table with 'colspan' values either as a wiki table, or as HTML. write a program in your language which translates your outline into a nested table, with WikiTable or HTML colspan values attached (where needed) to parent nodes in the nested table. The WikiTable at the top of this page was generated from the indented outline shown above, producing the following markup string: {| class="wikitable" style="text-align: center;" |- | style="background: #ffffe6; " colspan=7 | Display an outline as a nested table. |- | style="background: #ffebd2; " colspan=3 | Parse the outline to a tree, | style="background: #f0fff0; " colspan=2 | count the leaves descending from each node, | style="background: #e6ffff; " colspan=2 | and write out a table with 'colspan' values |- | style="background: #ffebd2; " | measuring the indent of each line, | style="background: #ffebd2; " | translating the indentation to a nested structure, | style="background: #ffebd2; " | and padding the tree to even depth. | style="background: #f0fff0; " | defining the width of a leaf as 1, | style="background: #f0fff0; " | and the width of a parent node as a sum. | style="background: #e6ffff; " | either as a wiki table, | style="background: #e6ffff; " | or as HTML. |- | | | | | | | | | style="background: #f0fff0; " | (The sum of the widths of its children) | | | | |} ;Extra credit: Use background color to distinguish the main stages of your outline, so that the subtree of each node at level two is consistently colored, and the edges between adjacent subtrees are immediately revealed. ;Output: Display your nested table on this page.
"""Display an outline as a nested table. Requires Python >=3.6.""" import itertools import re import sys from collections import deque from typing import NamedTuple RE_OUTLINE = re.compile(r"^((?: |\t)*)(.+)$", re.M) COLORS = itertools.cycle( [ "#ffffe6", "#ffebd2", "#f0fff0", "#e6ffff", "#ffeeff", ] ) class Node: def __init__(self, indent, value, parent, children=None): self.indent = indent self.value = value self.parent = parent self.children = children or [] self.color = None def depth(self): if self.parent: return self.parent.depth() + 1 return -1 def height(self): """Height of the subtree rooted at this node.""" if not self.children: return 0 return max(child.height() for child in self.children) + 1 def colspan(self): if self.leaf: return 1 return sum(child.colspan() for child in self.children) @property def leaf(self): return not bool(self.children) def __iter__(self): # Level order tree traversal. q = deque() q.append(self) while q: node = q.popleft() yield node q.extend(node.children) class Token(NamedTuple): indent: int value: str def tokenize(outline): """Generate ``Token``s from the given outline.""" for match in RE_OUTLINE.finditer(outline): indent, value = match.groups() yield Token(len(indent), value) def parse(outline): """Return the given outline as a tree of ``Node``s.""" # Split the outline into lines and count the level of indentation. tokens = list(tokenize(outline)) # Parse the tokens into a tree of nodes. temp_root = Node(-1, "", None) _parse(tokens, 0, temp_root) # Pad the tree so that all branches have the same depth. root = temp_root.children[0] pad_tree(root, root.height()) return root def _parse(tokens, index, node): """Recursively build a tree of nodes. Args: tokens (list): A collection of ``Token``s. index (int): Index of the current token. node (Node): Potential parent or sibling node. """ # Base case. No more lines. if index >= len(tokens): return token = tokens[index] if token.indent == node.indent: # A sibling of node current = Node(token.indent, token.value, node.parent) node.parent.children.append(current) _parse(tokens, index + 1, current) elif token.indent > node.indent: # A child of node current = Node(token.indent, token.value, node) node.children.append(current) _parse(tokens, index + 1, current) elif token.indent < node.indent: # Try the node's parent until we find a sibling. _parse(tokens, index, node.parent) def pad_tree(node, height): """Pad the tree with blank nodes so all branches have the same depth.""" if node.leaf and node.depth() < height: pad_node = Node(node.indent + 1, "", node) node.children.append(pad_node) for child in node.children: pad_tree(child, height) def color_tree(node): """Walk the tree and color each node as we go.""" if not node.value: node.color = "#F9F9F9" elif node.depth() <= 1: node.color = next(COLORS) else: node.color = node.parent.color for child in node.children: color_tree(child) def table_data(node): """Return an HTML table data element for the given node.""" indent = " " if node.colspan() > 1: colspan = f'colspan="{node.colspan()}"' else: colspan = "" if node.color: style = f'style="background-color: {node.color};"' else: style = "" attrs = " ".join([colspan, style]) return f"{indent}<td{attrs}>{node.value}</td>" def html_table(tree): """Return the tree as an HTML table.""" # Number of columns in the table. table_cols = tree.colspan() # Running count of columns in the current row. row_cols = 0 # HTML buffer buf = ["<table style='text-align: center;'>"] # Breadth first iteration. for node in tree: if row_cols == 0: buf.append(" <tr>") buf.append(table_data(node)) row_cols += node.colspan() if row_cols == table_cols: buf.append(" </tr>") row_cols = 0 buf.append("</table>") return "\n".join(buf) def wiki_table_data(node): """Return an wiki table data string for the given node.""" if not node.value: return "| |" if node.colspan() > 1: colspan = f"colspan={node.colspan()}" else: colspan = "" if node.color: style = f'style="background: {node.color};"' else: style = "" attrs = " ".join([colspan, style]) return f"| {attrs} | {node.value}" def wiki_table(tree): """Return the tree as a wiki table.""" # Number of columns in the table. table_cols = tree.colspan() # Running count of columns in the current row. row_cols = 0 # HTML buffer buf = ['{| class="wikitable" style="text-align: center;"'] for node in tree: if row_cols == 0: buf.append("|-") buf.append(wiki_table_data(node)) row_cols += node.colspan() if row_cols == table_cols: row_cols = 0 buf.append("|}") return "\n".join(buf) def example(table_format="wiki"): """Write an example table to stdout in either HTML or Wiki format.""" outline = ( "Display an outline as a nested table.\n" " Parse the outline to a tree,\n" " measuring the indent of each line,\n" " translating the indentation to a nested structure,\n" " and padding the tree to even depth.\n" " count the leaves descending from each node,\n" " defining the width of a leaf as 1,\n" " and the width of a parent node as a sum.\n" " (The sum of the widths of its children)\n" " and write out a table with 'colspan' values\n" " either as a wiki table,\n" " or as HTML." ) tree = parse(outline) color_tree(tree) if table_format == "wiki": print(wiki_table(tree)) else: print(html_table(tree)) if __name__ == "__main__": args = sys.argv[1:] if len(args) == 1: table_format = args[0] else: table_format = "wiki" example(table_format)
Distance and Bearing
Python
It is very important in aviation to have knowledge of the nearby airports at any time in flight. ;Task: Determine the distance and bearing from an Airplane to the 20 nearest Airports whenever requested. Use the non-commercial data from openflights.org airports.dat as reference. A request comes from an airplane at position ( latitude, longitude ): ( '''51.514669, 2.198581''' ). Your report should contain the following information from table airports.dat (column shown in brackets): Name(2), Country(4), ICAO(6), Distance and Bearing calculated from Latitude(7) and Longitude(8). Distance is measured in nautical miles (NM). Resolution is 0.1 NM. Bearing is measured in degrees (deg). 0deg = 360deg = north then clockwise 90deg = east, 180deg = south, 270deg = west. Resolution is 1deg. ;See: :* openflights.org/data: Airport, airline and route data :* Movable Type Scripts: Calculate distance, bearing and more between Latitude/Longitude points
''' Rosetta Code task Distance_and_Bearing ''' from math import radians, degrees, sin, cos, asin, atan2, sqrt from pandas import read_csv EARTH_RADIUS_KM = 6372.8 TASK_CONVERT_NM = 0.0094174 AIRPORT_DATA_FILE = 'airports.dat.txt' QUERY_LATITUDE, QUERY_LONGITUDE = 51.514669, 2.198581 def haversine(lat1, lon1, lat2, lon2): ''' Given two latitude, longitude pairs in degrees for two points on the Earth, get distance (nautical miles) and initial direction of travel (degrees) for travel from lat1, lon1 to lat2, lon2 ''' rlat1, rlon1, rlat2, rlon2 = [radians(x) for x in [lat1, lon1, lat2, lon2]] dlat = rlat2 - rlat1 dlon = rlon2 - rlon1 arc = sin(dlat / 2) ** 2 + cos(rlat1) * cos(rlat2) * sin(dlon / 2) ** 2 clen = 2.0 * degrees(asin(sqrt(arc))) theta = atan2(sin(dlon) * cos(rlat2), cos(rlat1) * sin(rlat2) - sin(rlat1) * cos(rlat2) * cos(dlon)) theta = (degrees(theta) + 360) % 360 return EARTH_RADIUS_KM * clen * TASK_CONVERT_NM, theta def find_nearest_airports(latitude, longitude, wanted=20, csv=AIRPORT_DATA_FILE): ''' Given latitude and longitude, find `wanted` closest airports in database file csv. ''' airports = read_csv(csv, header=None, usecols=[1, 3, 5, 6, 7], names=[ 'Name', 'Country', 'ICAO', 'Latitude', 'Longitude']) airports['Distance'] = 0.0 airports['Bearing'] = 0 for (idx, row) in enumerate(airports.itertuples()): distance, bearing = haversine( latitude, longitude, row.Latitude, row.Longitude) airports.at[idx, 'Distance'] = round(distance, ndigits=1) airports.at[idx, 'Bearing'] = int(round(bearing)) airports.sort_values(by=['Distance'], ignore_index=True, inplace=True) return airports.loc[0:wanted-1, ['Name', 'Country', 'ICAO', 'Distance', 'Bearing']] print(find_nearest_airports(QUERY_LATITUDE, QUERY_LONGITUDE))
Diversity prediction theorem
Python 3.7
The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies. Scott E. Page introduced the diversity prediction theorem: : ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. Therefore, when the diversity in a group is large, the error of the crowd is small. ;Definitions: ::* Average Individual Error: Average of the individual squared errors ::* Collective Error: Squared error of the collective prediction ::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction ::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then :::::: Collective Error = Average Individual Error - Prediction Diversity ;Task: For a given true value and a number of number of estimates (from a crowd), show (here on this page): :::* the true value and the crowd estimates :::* the average error :::* the crowd error :::* the prediction diversity Use (at least) these two examples: :::* a true value of '''49''' with crowd estimates of: ''' 48 47 51''' :::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42''' ;Also see: :* Wikipedia entry: Wisdom of the crowd :* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').
'''Diversity prediction theorem''' from itertools import chain from functools import reduce # diversityValues :: Num a => a -> [a] -> # { mean-Error :: a, crowd-error :: a, diversity :: a } def diversityValues(x): '''The mean error, crowd error and diversity, for a given observation x and a non-empty list of predictions ps. ''' def go(ps): mp = mean(ps) return { 'mean-error': meanErrorSquared(x)(ps), 'crowd-error': pow(x - mp, 2), 'diversity': meanErrorSquared(mp)(ps) } return go # meanErrorSquared :: Num -> [Num] -> Num def meanErrorSquared(x): '''The mean of the squared differences between the observed value x and a non-empty list of predictions ps. ''' def go(ps): return mean([ pow(p - x, 2) for p in ps ]) return go # ------------------------- TEST ------------------------- # main :: IO () def main(): '''Observed value: 49, prediction lists: various. ''' print(unlines(map( showDiversityValues(49), [ [48, 47, 51], [48, 47, 51, 42], [50, '?', 50, {}, 50], # Non-numeric values. [] # Missing predictions. ] ))) print(unlines(map( showDiversityValues('49'), # String in place of number. [ [50, 50, 50], [40, 35, 40], ] ))) # ---------------------- FORMATTING ---------------------- # showDiversityValues :: Num -> [Num] -> Either String String def showDiversityValues(x): '''Formatted string representation of diversity values for a given observation x and a non-empty list of predictions p. ''' def go(ps): def showDict(dct): w = 4 + max(map(len, dct.keys())) def showKV(a, kv): k, v = kv return a + k.rjust(w, ' ') + ( ' : ' + showPrecision(3)(v) + '\n' ) return 'Predictions: ' + showList(ps) + ' ->\n' + ( reduce(showKV, dct.items(), '') ) def showProblem(e): return ( unlines(map(indented(1), e)) if ( isinstance(e, list) ) else indented(1)(repr(e)) ) + '\n' return 'Observation: ' + repr(x) + '\n' + ( either(showProblem)(showDict)( bindLR(numLR(x))( lambda n: bindLR(numsLR(ps))( compose(Right, diversityValues(n)) ) ) ) ) return go # ------------------ GENERIC FUNCTIONS ------------------- # Left :: a -> Either a b def Left(x): '''Constructor for an empty Either (option type) value with an associated string. ''' return {'type': 'Either', 'Right': None, 'Left': x} # Right :: b -> Either a b def Right(x): '''Constructor for a populated Either (option type) value''' return {'type': 'Either', 'Left': None, 'Right': x} # bindLR (>>=) :: Either a -> (a -> Either b) -> Either b def bindLR(m): '''Either monad injection operator. Two computations sequentially composed, with any value produced by the first passed as an argument to the second. ''' def go(mf): return ( mf(m.get('Right')) if None is m.get('Left') else m ) return go # compose :: ((a -> a), ...) -> (a -> a) def compose(*fs): '''Composition, from right to left, of a series of functions. ''' def go(f, g): def fg(x): return f(g(x)) return fg return reduce(go, fs, identity) # concatMap :: (a -> [b]) -> [a] -> [b] def concatMap(f): '''A concatenated list over which a function has been mapped. The list monad can be derived by using a function f which wraps its output in a list, (using an empty list to represent computational failure). ''' def go(xs): return chain.from_iterable(map(f, xs)) return go # either :: (a -> c) -> (b -> c) -> Either a b -> c def either(fl): '''The application of fl to e if e is a Left value, or the application of fr to e if e is a Right value. ''' return lambda fr: lambda e: fl(e['Left']) if ( None is e['Right'] ) else fr(e['Right']) # identity :: a -> a def identity(x): '''The identity function.''' return x # indented :: Int -> String -> String def indented(n): '''String indented by n multiples of four spaces. ''' return lambda s: (4 * ' ' * n) + s # mean :: [Num] -> Float def mean(xs): '''Arithmetic mean of a list of numeric values. ''' return sum(xs) / float(len(xs)) # numLR :: a -> Either String Num def numLR(x): '''Either Right x if x is a float or int, or a Left explanatory message.''' return Right(x) if ( isinstance(x, (float, int)) ) else Left( 'Expected number, saw: ' + ( str(type(x)) + ' ' + repr(x) ) ) # numsLR :: [a] -> Either String [Num] def numsLR(xs): '''Either Right xs if all xs are float or int, or a Left explanatory message.''' def go(ns): ls, rs = partitionEithers(map(numLR, ns)) return Left(ls) if ls else Right(rs) return bindLR( Right(xs) if ( bool(xs) and isinstance(xs, list) ) else Left( 'Expected a non-empty list, saw: ' + ( str(type(xs)) + ' ' + repr(xs) ) ) )(go) # partitionEithers :: [Either a b] -> ([a],[b]) def partitionEithers(lrs): '''A list of Either values partitioned into a tuple of two lists, with all Left elements extracted into the first list, and Right elements extracted into the second list. ''' def go(a, x): ls, rs = a r = x.get('Right') return (ls + [x.get('Left')], rs) if None is r else ( ls, rs + [r] ) return reduce(go, lrs, ([], [])) # showList :: [a] -> String def showList(xs): '''Compact string representation of a list''' return '[' + ','.join(str(x) for x in xs) + ']' # showPrecision :: Int -> Float -> String def showPrecision(n): '''A string showing a floating point number at a given degree of precision.''' def go(x): return str(round(x, n)) return go # 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) # MAIN --- if __name__ == '__main__': main()
Doomsday rule
Python
About the task John Conway (1937-2020), was a mathematician who also invented several mathematically oriented computer pastimes, such as the famous Game of Life cellular automaton program. Dr. Conway invented a simple algorithm for finding the day of the week, given any date. The algorithm was based on calculating the distance of a given date from certain "anchor days" which follow a pattern for the day of the week upon which they fall. ; Algorithm The formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7 which, for 2021, is 0 (Sunday). To calculate the day of the week, we then count days from a close doomsday, with these as charted here by month, then add the doomsday for the year, then get the remainder after dividing by 7. This should give us the number corresponding to the day of the week for that date. Month Doomsday Dates for Month -------------------------------------------- January (common years) 3, 10, 17, 24, 31 January (leap years) 4, 11, 18, 25 February (common years) 7, 14, 21, 28 February (leap years) 1, 8, 15, 22, 29 March 7, 14, 21, 28 April 4, 11, 18, 25 May 2, 9, 16, 23, 30 June 6, 13, 20, 27 July 4, 11, 18, 25 August 1, 8, 15, 22, 29 September 5, 12, 19, 26 October 3, 10, 17, 24, 31 November 7, 14, 21, 28 December 5, 12, 19, 26 ; Task Given the following dates: * 1800-01-06 (January 6, 1800) * 1875-03-29 (March 29, 1875) * 1915-12-07 (December 7, 1915) * 1970-12-23 (December 23, 1970) * 2043-05-14 (May 14, 2043) * 2077-02-12 (February 12, 2077) * 2101-04-02 (April 2, 2101) Use Conway's Doomsday rule to calculate the day of the week for each date. ; see also * Doomsday rule * Tomorrow is the Day After Doomsday (p.28)
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)))
Dot product
Python
Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors: :::: [1, 3, -5] and :::: [4, -2, -1] If implementing the dot product of two vectors directly: :::* each vector must be the same length :::* multiply corresponding terms from each vector :::* sum the products (to produce the answer) ;Related task: * [[Vector products]]
def dotp(a,b): assert len(a) == len(b), 'Vector sizes must match' return sum(aterm * bterm for aterm,bterm in zip(a, b)) if __name__ == '__main__': a, b = [1, 3, -5], [4, -2, -1] assert dotp(a,b) == 3
Dot product
Python 3.7
Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors: :::: [1, 3, -5] and :::: [4, -2, -1] If implementing the dot product of two vectors directly: :::* each vector must be the same length :::* multiply corresponding terms from each vector :::* sum the products (to produce the answer) ;Related task: * [[Vector products]]
'''Dot product''' from operator import (mul) # dotProduct :: Num a => [a] -> [a] -> Either String a def dotProduct(xs): '''Either the dot product of xs and ys, or a string reporting unmatched vector sizes. ''' return lambda ys: Left('vector sizes differ') if ( len(xs) != len(ys) ) else Right(sum(map(mul, xs, ys))) # TEST ---------------------------------------------------- # main :: IO () def main(): '''Dot product of other vectors with [1, 3, -5]''' print( fTable(main.__doc__ + ':\n')(str)(str)( compose( either(append('Undefined :: '))(str) )(dotProduct([1, 3, -5])) )([[4, -2, -1, 8], [4, -2], [4, 2, -1], [4, -2, -1]]) ) # GENERIC ------------------------------------------------- # Left :: a -> Either a b def Left(x): '''Constructor for an empty Either (option type) value with an associated string. ''' return {'type': 'Either', 'Right': None, 'Left': x} # Right :: b -> Either a b def Right(x): '''Constructor for a populated Either (option type) value''' return {'type': 'Either', 'Left': None, 'Right': x} # append (++) :: [a] -> [a] -> [a] # append (++) :: String -> String -> String def append(xs): '''Two lists or strings combined into one.''' return lambda ys: xs + ys # compose (<<<) :: (b -> c) -> (a -> b) -> a -> c def compose(g): '''Right to left function composition.''' return lambda f: lambda x: g(f(x)) # either :: (a -> c) -> (b -> c) -> Either a b -> c def either(fl): '''The application of fl to e if e is a Left value, or the application of fr to e if e is a Right value. ''' return lambda fr: lambda e: fl(e['Left']) if ( None is e['Right'] ) else fr(e['Right']) # 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()
Draw a clock
Python
Draw a clock. More specific: # Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. # The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. # A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. # A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. ;Key points * animate simple object * timed event * polling system resources * code clarity
[http://www.thinkgeek.com/gadgets/watches/6a17/ Think Geek Binary Clock]
Draw a clock
Python 2.6+, 3.0+
Draw a clock. More specific: # Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. # The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. # A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. # A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. ;Key points * animate simple object * timed event * polling system resources * code clarity
import time def chunks(l, n=5): return [l[i:i+n] for i in range(0, len(l), n)] def binary(n, digits=8): n=int(n) return '{0:0{1}b}'.format(n, digits) def secs(n): n=int(n) h='x' * n return "|".join(chunks(h)) def bin_bit(h): h=h.replace("1","x") h=h.replace("0"," ") return "|".join(list(h)) x=str(time.ctime()).split() y=x[3].split(":") s=y[-1] y=map(binary,y[:-1]) print bin_bit(y[0]) print print bin_bit(y[1]) print print secs(s)
Draw a rotating cube
Python 2.7.9
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. ;Related tasks * Draw a cuboid * write language name in 3D ASCII
from visual import * scene.title = "VPython: Draw a rotating cube" scene.range = 2 scene.autocenter = True print "Drag with right mousebutton to rotate view." print "Drag up+down with middle mousebutton to zoom." deg45 = math.radians(45.0) # 0.785398163397 cube = box() # using defaults, see http://www.vpython.org/contents/docs/defaults.html cube.rotate( angle=deg45, axis=(1,0,0) ) cube.rotate( angle=deg45, axis=(0,0,1) ) while True: # Animation-loop rate(50) cube.rotate( angle=0.005, axis=(0,1,0) )
Draw a sphere
Python from C
{{requires|Graphics}} ;Task: Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. ;Related tasks: * draw a cuboid * draw a rotating cube * write language name in 3D ASCII * draw a Deathstar
import math shades = ('.',':','!','*','o','e','&','#','%','@') def normalize(v): len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2) return (v[0]/len, v[1]/len, v[2]/len) def dot(x,y): d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2] return -d if d < 0 else 0 def draw_sphere(r, k, ambient, light): for i in range(int(math.floor(-r)),int(math.ceil(r)+1)): x = i + 0.5 line = '' for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)): y = j/2 + 0.5 if x*x + y*y <= r*r: vec = normalize((x,y,math.sqrt(r*r - x*x - y*y))) b = dot(light,vec)**k + ambient intensity = int((1-b)*(len(shades)-1)) line += shades[intensity] if 0 <= intensity < len(shades) else shades[0] else: line += ' ' print(line) light = normalize((30,30,-50)) draw_sphere(20,4,0.1, light) draw_sphere(10,2,0.4, light)
Draw a sphere
Python 2.7.5
{{requires|Graphics}} ;Task: Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. ;Related tasks: * draw a cuboid * draw a rotating cube * write language name in 3D ASCII * draw a Deathstar
from __future__ import print_function, division from visual import * title = "VPython: Draw a sphere" scene.title = title print( "%s\n" % title ) print( 'Drag with right mousebutton to rotate view' ) print( 'Drag up+down with middle mousebutton to zoom') scene.autocenter = True # uncomment any (or all) of those variants: S1 = sphere(pos=(0.0, 0.0, 0.0), radius=1.0, color=color.blue) #S2 = sphere(pos=(2.0, 0.0, 0.0), radius=1.0, material=materials.earth) #S3 = sphere(pos=(0.0, 2.0, 0.0), radius=1.0, material=materials.BlueMarble) #S4 = sphere(pos=(0.0, 0.0, 2.0), radius=1.0, # color=color.orange, material=materials.marble) while True: # Animation-loop rate(100) pass # no animation in this demo
Dutch national flag problem
Python
The Dutch national flag is composed of three coloured bands in the order: ::* red (top) ::* then white, and ::* lastly blue (at the bottom). The problem posed by Edsger Dijkstra is: :Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... ;Task # Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''. # Sort the balls in a way idiomatic to your language. # Check the sorted balls ''are'' in the order of the Dutch national flag. ;C.f.: * Dutch national flag problem * Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
import random colours_in_order = 'Red White Blue'.split() def dutch_flag_sort(items, order=colours_in_order): 'return sort of items using the given order' reverse_index = dict((x,i) for i,x in enumerate(order)) return sorted(items, key=lambda x: reverse_index[x]) def dutch_flag_check(items, order=colours_in_order): 'Return True if each item of items is in the given order' reverse_index = dict((x,i) for i,x in enumerate(order)) order_of_items = [reverse_index[item] for item in items] return all(x <= y for x, y in zip(order_of_items, order_of_items[1:])) def random_balls(mx=5): 'Select from 1 to mx balls of each colour, randomly' balls = sum([[colour] * random.randint(1, mx) for colour in colours_in_order], []) random.shuffle(balls) return balls def main(): # Ensure we start unsorted while True: balls = random_balls() if not dutch_flag_check(balls): break print("Original Ball order:", balls) sorted_balls = dutch_flag_sort(balls) print("Sorted Ball Order:", sorted_balls) assert dutch_flag_check(sorted_balls), 'Whoops. Not sorted!' if __name__ == '__main__': main()
EKG sequence convergence
Python
The sequence is from the natural numbers and is defined by: * a(1) = 1; * a(2) = Start = 2; * for n > 2, a(n) shares at least one prime factor with a(n-1) and is the ''smallest'' such natural number ''not already used''. The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed). Variants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call: * The sequence described above , starting 1, 2, ... the EKG(2) sequence; * the sequence starting 1, 3, ... the EKG(3) sequence; * ... the sequence starting 1, N, ... the EKG(N) sequence. ;Convergence If an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential '''state'''. Two EKG generators with differing starts can converge to produce the same sequence after initial differences. EKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)). ;Task: # Calculate and show here the first 10 members of EKG(2). # Calculate and show here the first 10 members of EKG(5). # Calculate and show here the first 10 members of EKG(7). # Calculate and show here the first 10 members of EKG(9). # Calculate and show here the first 10 members of EKG(10). # Calculate and show here at which term EKG(5) and EKG(7) converge ('''stretch goal'''). ;Related Tasks: # [[Greatest common divisor]] # [[Sieve of Eratosthenes]] ;Reference: * The EKG Sequence and the Tree of Numbers. (Video).
from itertools import count, islice, takewhile from math import gcd def EKG_gen(start=2): """\ Generate the next term of the EKG together with the minimum cache of numbers left in its production; (the "state" of the generator). Using math.gcd """ c = count(start + 1) last, so_far = start, list(range(2, start)) yield 1, [] yield last, [] while True: for index, sf in enumerate(so_far): if gcd(last, sf) > 1: last = so_far.pop(index) yield last, so_far[::] break else: so_far.append(next(c)) def find_convergence(ekgs=(5,7)): "Returns the convergence point or zero if not found within the limit" ekg = [EKG_gen(n) for n in ekgs] for e in ekg: next(e) # skip initial 1 in each sequence return 2 + len(list(takewhile(lambda state: not all(state[0] == s for s in state[1:]), zip(*ekg)))) if __name__ == '__main__': for start in 2, 5, 7, 9, 10: print(f"EKG({start}):", str([n[0] for n in islice(EKG_gen(start), 10)])[1: -1]) print(f"\nEKG(5) and EKG(7) converge at term {find_convergence(ekgs=(5,7))}!")
Earliest difference between prime gaps
Python from Julia, Wren
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer. {|class="wikitable" !gap!!minimalstartingprime!!endingprime |- |2||3||5 |- |4||7||11 |- |6||23||29 |- |8||89||97 |- |10||139||149 |- |12||199||211 |- |14||113||127 |- |16||1831||1847 |- |18||523||541 |- |20||887||907 |- |22||1129||1151 |- |24||1669||1693 |- |26||2477||2503 |- |28||2971||2999 |- |30||4297||4327 |} This task involves locating the minimal primes corresponding to those gaps. Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30: For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent. ;Task For each order of magnitude '''m''' from '''101''' through '''106''': * Find the first two sets of minimum adjacent prime gaps where the absolute value of the difference between the prime gap start values is greater than '''m'''. ;E.G. For an '''m''' of '''101'''; The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < '''101''' so keep going. The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > '''101''' so this the earliest adjacent gap difference > '''101'''. ;Stretch goal * Do the same for '''107''' and '''108''' (and higher?) orders of magnitude Note: the earliest value found for each order of magnitude may not be unique, in fact, ''is'' not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
""" https://rosettacode.org/wiki/Earliest_difference_between_prime_gaps """ from primesieve import primes LIMIT = 10**9 pri = primes(LIMIT * 5) gapstarts = {} for i in range(1, len(pri)): if pri[i] - pri[i - 1] not in gapstarts: gapstarts[pri[i] - pri[i - 1]] = pri[i - 1] PM, GAP1, = 10, 2 while True: while GAP1 not in gapstarts: GAP1 += 2 start1 = gapstarts[GAP1] GAP2 = GAP1 + 2 if GAP2 not in gapstarts: GAP1 = GAP2 + 2 continue start2 = gapstarts[GAP2] diff = abs(start2 - start1) if diff > PM: print(f"Earliest difference >{PM: ,} between adjacent prime gap starting primes:") print(f"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\n") if PM == LIMIT: break PM *= 10 else: GAP1 = GAP2
Eban numbers
Python
Definition: An '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English. Or more literally, spelled numbers that contain the letter '''e''' are banned. The American version of spelling numbers will be used here (as opposed to the British). '''2,000,000,000''' is two billion, ''not'' two milliard. Only numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task. This will allow optimizations to be used. ;Task: :::* show all eban numbers <= '''1,000''' (in a horizontal format), and a count :::* show all eban numbers between '''1,000''' and '''4,000''' (inclusive), and a count :::* show a count of all eban numbers up and including '''10,000''' :::* show a count of all eban numbers up and including '''100,000''' :::* show a count of all eban numbers up and including '''1,000,000''' :::* show a count of all eban numbers up and including '''10,000,000''' :::* show all output here. ;See also: :* The MathWorld entry: eban numbers. :* The OEIS entry: A6933, eban numbers. :* [[Number names]].
# Use inflect """ show all eban numbers <= 1,000 (in a horizontal format), and a count show all eban numbers between 1,000 and 4,000 (inclusive), and a count show a count of all eban numbers up and including 10,000 show a count of all eban numbers up and including 100,000 show a count of all eban numbers up and including 1,000,000 show a count of all eban numbers up and including 10,000,000 """ import inflect import time before = time.perf_counter() p = inflect.engine() # eban numbers <= 1000 print(' ') print('eban numbers up to and including 1000:') print(' ') count = 0 for i in range(1,1001): if not 'e' in p.number_to_words(i): print(str(i)+' ',end='') count += 1 print(' ') print(' ') print('count = '+str(count)) print(' ') # eban numbers 1000 to 4000 print(' ') print('eban numbers between 1000 and 4000 (inclusive):') print(' ') count = 0 for i in range(1000,4001): if not 'e' in p.number_to_words(i): print(str(i)+' ',end='') count += 1 print(' ') print(' ') print('count = '+str(count)) print(' ') # eban numbers up to 10000 print(' ') print('eban numbers up to and including 10000:') print(' ') count = 0 for i in range(1,10001): if not 'e' in p.number_to_words(i): count += 1 print(' ') print('count = '+str(count)) print(' ') # eban numbers up to 100000 print(' ') print('eban numbers up to and including 100000:') print(' ') count = 0 for i in range(1,100001): if not 'e' in p.number_to_words(i): count += 1 print(' ') print('count = '+str(count)) print(' ') # eban numbers up to 1000000 print(' ') print('eban numbers up to and including 1000000:') print(' ') count = 0 for i in range(1,1000001): if not 'e' in p.number_to_words(i): count += 1 print(' ') print('count = '+str(count)) print(' ') # eban numbers up to 10000000 print(' ') print('eban numbers up to and including 10000000:') print(' ') count = 0 for i in range(1,10000001): if not 'e' in p.number_to_words(i): count += 1 print(' ') print('count = '+str(count)) print(' ') after = time.perf_counter() print(" ") print("Run time in seconds: "+str(after - before))
Eertree
Python
An '''eertree''' is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both ''tries'' and ''suffix trees''. See links below. ;Task: Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. ;See also: * Wikipedia entry: trie. * Wikipedia entry: suffix tree * Cornell University Library, Computer Science, Data Structures and Algorithms ---> EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#!/bin/python from __future__ import print_function class Node(object): def __init__(self): self.edges = {} # edges (or forward links) self.link = None # suffix link (backward links) self.len = 0 # the length of the node class Eertree(object): def __init__(self): self.nodes = [] # two initial root nodes self.rto = Node() #odd length root node, or node -1 self.rte = Node() #even length root node, or node 0 # Initialize empty tree self.rto.link = self.rte.link = self.rto; self.rto.len = -1 self.rte.len = 0 self.S = [0] # accumulated input string, T=S[1..i] self.maxSufT = self.rte # maximum suffix of tree T def get_max_suffix_pal(self, startNode, a): # We traverse the suffix-palindromes of T in the order of decreasing length. # For each palindrome we read its length k and compare T[i-k] against a # until we get an equality or arrive at the -1 node. u = startNode i = len(self.S) k = u.len while id(u) != id(self.rto) and self.S[i - k - 1] != a: assert id(u) != id(u.link) #Prevent infinte loop u = u.link k = u.len return u def add(self, a): # We need to find the maximum suffix-palindrome P of Ta # Start by finding maximum suffix-palindrome Q of T. # To do this, we traverse the suffix-palindromes of T # in the order of decreasing length, starting with maxSuf(T) Q = self.get_max_suffix_pal(self.maxSufT, a) # We check Q to see whether it has an outgoing edge labeled by a. createANewNode = not a in Q.edges if createANewNode: # We create the node P of length Q+2 P = Node() self.nodes.append(P) P.len = Q.len + 2 if P.len == 1: # if P = a, create the suffix link (P,0) P.link = self.rte else: # It remains to create the suffix link from P if |P|>1. Just # continue traversing suffix-palindromes of T starting with the suffix # link of Q. P.link = self.get_max_suffix_pal(Q.link, a).edges[a] # create the edge (Q,P) Q.edges[a] = P #P becomes the new maxSufT self.maxSufT = Q.edges[a] #Store accumulated input string self.S.append(a) return createANewNode def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result): #Each node represents a palindrome, which can be reconstructed #by the path from the root node to each non-root node. #Traverse all edges, since they represent other palindromes for lnkName in nd.edges: nd2 = nd.edges[lnkName] #The lnkName is the character used for this edge self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result) #Reconstruct based on charsToHere characters. if id(nd) != id(self.rto) and id(nd) != id(self.rte): #Don't print for root nodes tmp = "".join(charsToHere) if id(nodesToHere[0]) == id(self.rte): #Even string assembled = tmp[::-1] + tmp else: #Odd string assembled = tmp[::-1] + tmp[1:] result.append(assembled) if __name__=="__main__": st = "eertree" print ("Processing string", st) eertree = Eertree() for ch in st: eertree.add(ch) print ("Number of sub-palindromes:", len(eertree.nodes)) #Traverse tree to find sub-palindromes result = [] eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) #Odd length words eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) #Even length words print ("Sub-palindromes:", result)
Egyptian division
Python
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of [[Ethiopian multiplication]] '''Algorithm:''' Given two numbers where the '''dividend''' is to be divided by the '''divisor''': # Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. # Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. # Continue with successive i'th rows of 2^i and 2^i * divisor. # Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. # We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator''' # Consider each row of the table, in the ''reverse'' order of its construction. # If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. # When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). '''Example: 580 / 34''' ''' Table creation: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings |- | 1 | 34 |- | 2 | 68 |- | 4 | 136 |- | 8 | 272 |- | 16 | 544 |} ''' Initialization of sums: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | 16 | 544 | | |- | | | 0 | 0 |} ''' Considering table rows, bottom-up: ''' When a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations. ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | 16 | 544 |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | 16 | 544 |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | 16 | 544 |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | 16 | 544 |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | '''1''' | '''34''' | 17 | 578 |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ;Answer: So 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''. ;Task: The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. * Functions should be clear interpretations of the algorithm. * Use the function to divide 580 by 34 and show the answer '''here, on this page'''. ;Related tasks: :* Egyptian fractions ;References: :* Egyptian Number System
from itertools import product def egyptian_divmod(dividend, divisor): assert divisor != 0 pwrs, dbls = [1], [divisor] while dbls[-1] <= dividend: pwrs.append(pwrs[-1] * 2) dbls.append(pwrs[-1] * divisor) ans, accum = 0, 0 for pwr, dbl in zip(pwrs[-2::-1], dbls[-2::-1]): if accum + dbl <= dividend: accum += dbl ans += pwr return ans, abs(accum - dividend) if __name__ == "__main__": # Test it gives the same results as the divmod built-in for i, j in product(range(13), range(1, 13)): assert egyptian_divmod(i, j) == divmod(i, j) # Mandated result i, j = 580, 34 print(f'{i} divided by {j} using the Egyption method is %i remainder %i' % egyptian_divmod(i, j))
Egyptian division
Python from Haskell
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of [[Ethiopian multiplication]] '''Algorithm:''' Given two numbers where the '''dividend''' is to be divided by the '''divisor''': # Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. # Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. # Continue with successive i'th rows of 2^i and 2^i * divisor. # Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. # We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator''' # Consider each row of the table, in the ''reverse'' order of its construction. # If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. # When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). '''Example: 580 / 34''' ''' Table creation: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings |- | 1 | 34 |- | 2 | 68 |- | 4 | 136 |- | 8 | 272 |- | 16 | 544 |} ''' Initialization of sums: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | 16 | 544 | | |- | | | 0 | 0 |} ''' Considering table rows, bottom-up: ''' When a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations. ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | 16 | 544 |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | 16 | 544 |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | 16 | 544 |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | 16 | 544 |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | '''1''' | '''34''' | 17 | 578 |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ;Answer: So 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''. ;Task: The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. * Functions should be clear interpretations of the algorithm. * Use the function to divide 580 by 34 and show the answer '''here, on this page'''. ;Related tasks: :* Egyptian fractions ;References: :* Egyptian Number System
'''Quotient and remainder of division by the Rhind papyrus method.''' from functools import reduce # eqyptianQuotRem :: Int -> Int -> (Int, Int) def eqyptianQuotRem(m): '''Quotient and remainder derived by the Eqyptian method.''' def expansion(xi): '''Doubled value, and next power of two - both by self addition.''' x, i = xi return Nothing() if x > m else Just( ((x + x, i + i), xi) ) def collapse(qr, ix): '''Addition of a power of two to the quotient, and subtraction of a paired value from the remainder.''' i, x = ix q, r = qr return (q + i, r - x) if x < r else qr return lambda n: reduce( collapse, unfoldl(expansion)( (1, n) ), (0, m) ) # ------------------------- TEST -------------------------- # main :: IO () def main(): '''Test''' print( eqyptianQuotRem(580)(34) ) # ------------------- GENERIC FUNCTIONS ------------------- # Just :: a -> Maybe a def Just(x): '''Constructor for an inhabited Maybe (option type) value.''' return {'type': 'Maybe', 'Nothing': False, 'Just': x} # Nothing :: Maybe a def Nothing(): '''Constructor for an empty Maybe (option type) value.''' return {'type': 'Maybe', 'Nothing': True} # unfoldl(lambda x: Just(((x - 1), x)) if 0 != x else Nothing())(10) # -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # unfoldl :: (b -> Maybe (b, a)) -> b -> [a] def unfoldl(f): '''Dual to reduce or foldl. Where these reduce a list to a summary value, unfoldl builds a list from a seed value. Where f returns Just(a, b), a is appended to the list, and the residual b is used as the argument for the next application of f. When f returns Nothing, the completed list is returned. ''' def go(v): x, r = v, v xs = [] while True: mb = f(x) if mb.get('Nothing'): return xs else: x, r = mb.get('Just') xs.insert(0, r) return xs return go # MAIN ---------------------------------------------------- if __name__ == '__main__': main()
Elementary cellular automaton
Python
An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. ;Task: Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of [[one-dimensional cellular automata]]. ;See also * Cellular automata (natureofcode.com)
def eca(cells, rule): lencells = len(cells) c = "0" + cells + "0" # Zero pad the ends rulebits = '{0:08b}'.format(rule) neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)} yield c[1:-1] while True: c = ''.join(['0', ''.join(neighbours2next[c[i-1:i+2]] for i in range(1,lencells+1)), '0']) yield c[1:-1] if __name__ == '__main__': lines, start, rules = 50, '0000000001000000000', (90, 30, 122) zipped = [range(lines)] + [eca(start, rule) for rule in rules] print('\n Rules: %r' % (rules,)) for data in zip(*zipped): i = data[0] cells = data[1:] print('%2i: %s' % (i, ' '.join(cells).replace('0', '.').replace('1', '#')))
Elementary cellular automaton/Infinite length
Python
The purpose of this task is to create a version of an [[Elementary cellular automaton]] whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells. Examples: 1 -> ..., 0, 0, 1, 0, 0, ... 0, 1 -> ..., 1, 1, 0, 1, 0, 0, ... 1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ... More complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.
def _notcell(c): return '0' if c == '1' else '1' def eca_infinite(cells, rule): lencells = len(cells) rulebits = '{0:08b}'.format(rule) neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)} c = cells while True: yield c c = _notcell(c[0])*2 + c + _notcell(c[-1])*2 # Extend and pad the ends c = ''.join(neighbours2next[c[i-1:i+2]] for i in range(1,len(c) - 1)) #yield c[1:-1] if __name__ == '__main__': lines = 25 for rule in (90, 30): print('\nRule: %i' % rule) for i, c in zip(range(lines), eca_infinite('1', rule)): print('%2i: %s%s' % (i, ' '*(lines - i), c.replace('0', '.').replace('1', '#')))
Elementary cellular automaton/Random number generator
Python
Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. ;Reference: * Cellular automata: Is Rule 30 random? (PDF).
from elementary_cellular_automaton import eca, eca_wrap def rule30bytes(lencells=100): cells = '1' + '0' * (lencells - 1) gen = eca(cells, 30) while True: yield int(''.join(next(gen)[0] for i in range(8)), 2) if __name__ == '__main__': print([b for i,b in zip(range(10), rule30bytes())])
Elliptic curve arithmetic
Python from C
digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol. In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the '''x''' and '''y''' coordinates of any point on the curve: :::: y^2 = x^3 + a x + b '''a''' and '''b''' are arbitrary parameters that define the specific curve which is used. For this particular task, we'll use the following parameters: :::: a=0, b=7 The most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it. To do so we define an internal composition rule with an additive notation '''+''', such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have: :::: P + Q + R = 0 Here '''0''' (zero) is the ''infinity point'', for which the '''x''' and '''y''' values are not defined. It's basically the same kind of point which defines the horizon in projective geometry. We'll also assume here that this infinity point is unique and defines the neutral element of the addition. This was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such: Given any three aligned points '''P''', '''Q''' and '''R''', we define the sum '''S = P + Q''' as the point (possibly the infinity point) such that '''S''', '''R''' and the infinity point are aligned. Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points '''S''' and '''R''' can be aligned with the infinity point if and only if '''S''' and '''R''' are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet). '''S''' is thus defined as the symmetric of '''R''' towards the '''x''' axis. The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. You will use the '''a''' and '''b''' parameters of secp256k1, i.e. respectively zero and seven. ''Hint'': You might need to define a "doubling" function, that returns '''P+P''' for any given point '''P'''. ''Extra credit'': define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns, for any point '''P''' and integer '''n''', the point '''P + P + ... + P''' ('''n''' times).
#!/usr/bin/env python3 class Point: b = 7 def __init__(self, x=float('inf'), y=float('inf')): self.x = x self.y = y def copy(self): return Point(self.x, self.y) def is_zero(self): return self.x > 1e20 or self.x < -1e20 def neg(self): return Point(self.x, -self.y) def dbl(self): if self.is_zero(): return self.copy() try: L = (3 * self.x * self.x) / (2 * self.y) except ZeroDivisionError: return Point() x = L * L - 2 * self.x return Point(x, L * (self.x - x) - self.y) def add(self, q): if self.x == q.x and self.y == q.y: return self.dbl() if self.is_zero(): return q.copy() if q.is_zero(): return self.copy() try: L = (q.y - self.y) / (q.x - self.x) except ZeroDivisionError: return Point() x = L * L - self.x - q.x return Point(x, L * (self.x - x) - self.y) def mul(self, n): p = self.copy() r = Point() i = 1 while i <= n: if i&n: r = r.add(p) p = p.dbl() i <<= 1 return r def __str__(self): return "({:.3f}, {:.3f})".format(self.x, self.y) def show(s, p): print(s, "Zero" if p.is_zero() else p) def from_y(y): n = y * y - Point.b x = n**(1./3) if n>=0 else -((-n)**(1./3)) return Point(x, y) # demonstrate a = from_y(1) b = from_y(2) show("a =", a) show("b =", b) c = a.add(b) show("c = a + b =", c) d = c.neg() show("d = -c =", d) show("c + d =", c.add(d)) show("a + b + d =", a.add(b.add(d))) show("a * 12345 =", a.mul(12345))
Empty directory
Python 2.x
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With [[Unix]] or [[Windows]] systems, every directory contains an entry for "." and almost every directory contains ".." (except for a root directory); an empty directory contains no other entries.
import os; if os.listdir(raw_input("directory")): print "not empty" else: print "empty"
Empty string
Python
Languages may have features for dealing specifically with empty strings (those containing no characters). ;Task: ::* Demonstrate how to assign an empty string to a variable. ::* Demonstrate how to check that a string is empty. ::* Demonstrate how to check that a string is not empty.
s = '' # or: s = str() if not s or s == '': print("String is empty") if len(s) == 0: print("String is empty") else: print("String not empty") # boolean test function for python2 and python3 # test for regular (non-unicode) strings # unicode strings # None def emptystring(s): if isinstance(s, (''.__class__ , u''.__class__) ): if len(s) == 0: return True else return False elif s is None: return True
Entropy/Narcissist
Python 3.4
Write a computer program that computes and shows its own [[entropy]]. ;Related Tasks: :* [[Fibonacci_word]] :* [[Entropy]]
import math from collections import Counter def entropy(s): p, lns = Counter(s), float(len(s)) return -sum( count/lns * math.log(count/lns, 2) for count in p.values()) with open(__file__) as f: b=f.read() print(entropy(b))
Equilibrium index
Python
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence A: ::::: A_0 = -7 ::::: A_1 = 1 ::::: A_2 = 5 ::::: A_3 = 2 ::::: A_4 = -4 ::::: A_5 = 3 ::::: A_6 = 0 3 is an equilibrium index, because: ::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6 6 is also an equilibrium index, because: ::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0 (sum of zero elements is zero) 7 is not an equilibrium index, because it is not a valid index of sequence A. ;Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
f = (eqindex2Pass, eqindexMultiPass, eqindex1Pass) d = ([-7, 1, 5, 2, -4, 3, 0], [2, 4, 6], [2, 9, 2], [1, -1, 1, -1, 1, -1, 1]) for data in d: print("d = %r" % data) for func in f: print(" %16s(d) -> %r" % (func.__name__, list(func(data))))
Esthetic numbers
Python 3.9.5
An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1. ;E.G. :* '''12''' is an esthetic number. One and two differ by 1. :* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour. :* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. ;Task :* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. :* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) :* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''. :* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''. ;Related task: * numbers with equal rises and falls ;See also: :;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 :;*Numbers Aplenty - Esthetic numbers :;*Geeks for Geeks - Stepping numbers
from collections import deque from itertools import dropwhile, islice, takewhile from textwrap import wrap from typing import Iterable, Iterator Digits = str # Alias for the return type of to_digits() def esthetic_nums(base: int) -> Iterator[int]: """Generate the esthetic number sequence for a given base >>> list(islice(esthetic_nums(base=10), 20)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65] """ queue: deque[tuple[int, int]] = deque() queue.extendleft((d, d) for d in range(1, base)) while True: num, lsd = queue.pop() yield num new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base) num *= base # Shift num left one digit queue.extendleft((num + d, d) for d in new_lsds) def to_digits(num: int, base: int) -> Digits: """Return a representation of an integer as digits in a given base >>> to_digits(0x3def84f0ce, base=16) '3def84f0ce' """ digits: list[str] = [] while num: num, d = divmod(num, base) digits.append("0123456789abcdef"[d]) return "".join(reversed(digits)) if digits else "0" def pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None: """Pretty print an iterable which returns strings >>> pprint_it(map(str, range(20)), indent=0, width=40) 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 <BLANKLINE> """ joined = ", ".join(it) lines = wrap(joined, width=width - indent) for line in lines: print(f"{indent*' '}{line}") print() def task_2() -> None: nums: Iterator[int] for base in range(2, 16 + 1): start, stop = 4 * base, 6 * base nums = esthetic_nums(base) nums = islice(nums, start - 1, stop) # start and stop are 1-based indices print( f"Base-{base} esthetic numbers from " f"index {start} through index {stop} inclusive:\n" ) pprint_it(to_digits(num, base) for num in nums) def task_3(lower: int, upper: int, base: int = 10) -> None: nums: Iterator[int] = esthetic_nums(base) nums = dropwhile(lambda num: num < lower, nums) nums = takewhile(lambda num: num <= upper, nums) print( f"Base-{base} esthetic numbers with " f"magnitude between {lower:,} and {upper:,}:\n" ) pprint_it(to_digits(num, base) for num in nums) if __name__ == "__main__": print("======\nTask 2\n======\n") task_2() print("======\nTask 3\n======\n") task_3(1_000, 9_999) print("======\nTask 4\n======\n") task_3(100_000_000, 130_000_000)
Esthetic numbers
Python from Haskell
An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1. ;E.G. :* '''12''' is an esthetic number. One and two differ by 1. :* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour. :* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. ;Task :* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. :* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) :* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''. :* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''. ;Related task: * numbers with equal rises and falls ;See also: :;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 :;*Numbers Aplenty - Esthetic numbers :;*Geeks for Geeks - Stepping numbers
'''Esthetic numbers''' from functools import reduce from itertools import ( accumulate, chain, count, dropwhile, islice, product, takewhile ) from operator import add from string import digits, ascii_lowercase from textwrap import wrap # estheticNumbersInBase :: Int -> [Int] def estheticNumbersInBase(b): '''Infinite stream of numbers which are esthetic in a given base. ''' return concatMap( compose( lambda deltas: concatMap( lambda headDigit: concatMap( compose( fromBaseDigits(b), scanl(add)(headDigit) ) )(deltas) )(range(1, b)), replicateList([-1, 1]) ) )(count(0)) # ------------------------ TESTS ------------------------- def main(): '''Specified tests''' def samples(b): i, j = b * 4, b * 6 return '\n'.join([ f'Esthetics [{i}..{j}] for base {b}:', unlines(wrap( unwords([ showInBase(b)(n) for n in compose( drop(i - 1), take(j) )( estheticNumbersInBase(b) ) ]), 60 )) ]) def takeInRange(a, b): return compose( dropWhile(lambda x: x < a), takeWhile(lambda x: x <= b) ) print( '\n\n'.join([ samples(b) for b in range(2, 1 + 16) ]) ) for (lo, hi) in [(1000, 9999), (100_000_000, 130_000_000)]: print(f'\nBase 10 Esthetics in range [{lo}..{hi}]:') print( unlines(wrap( unwords( str(x) for x in takeInRange(lo, hi)( estheticNumbersInBase(10) ) ), 60 )) ) # ------------------- BASES AND DIGITS ------------------- # fromBaseDigits :: Int -> [Int] -> [Int] def fromBaseDigits(b): '''An empty list if any digits are out of range for the base. Otherwise a list containing an integer. ''' def go(digitList): maybeNum = reduce( lambda r, d: None if r is None or ( 0 > d or d >= b ) else r * b + d, digitList, 0 ) return [] if None is maybeNum else [maybeNum] return go # toBaseDigits :: Int -> Int -> [Int] def toBaseDigits(b): '''A list of the digits of n in base b. ''' def f(x): return None if 0 == x else ( divmod(x, b)[::-1] ) return lambda n: list(reversed(unfoldr(f)(n))) # showInBase :: Int -> Int -> String def showInBase(b): '''String representation of n in base b. ''' charSet = digits + ascii_lowercase return lambda n: ''.join([ charSet[i] for i in toBaseDigits(b)(n) ]) # ----------------------- GENERIC ------------------------ # compose :: ((a -> a), ...) -> (a -> a) def compose(*fs): '''Composition, from right to left, of a series of functions. ''' def go(f, g): def fg(x): return f(g(x)) return fg return reduce(go, fs, lambda x: x) # concatMap :: (a -> [b]) -> [a] -> [b] def concatMap(f): '''A concatenated list over which a function has been mapped. The list monad can be derived by using a function f which wraps its output in a list, (using an empty list to represent computational failure). ''' def go(xs): return chain.from_iterable(map(f, xs)) return go # drop :: Int -> [a] -> [a] # drop :: Int -> String -> String def drop(n): '''The sublist of xs beginning at (zero-based) index n. ''' def go(xs): if isinstance(xs, (list, tuple, str)): return xs[n:] else: take(n)(xs) return xs return go # dropWhile :: (a -> Bool) -> [a] -> [a] # dropWhile :: (Char -> Bool) -> String -> String def dropWhile(p): '''The suffix remainining after takeWhile p xs. ''' return lambda xs: list( dropwhile(p, xs) ) # replicateList :: [a] -> Int -> [[a]] def replicateList(xs): '''All distinct lists of length n that consist of elements drawn from xs. ''' def rep(n): def go(x): return [[]] if 1 > x else [ ([a] + b) for (a, b) in product( xs, go(x - 1) ) ] return go(n) return rep # scanl :: (b -> a -> b) -> b -> [a] -> [b] def scanl(f): '''scanl is like reduce, but defines a succession of intermediate values, building from the left. ''' def go(a): def g(xs): return accumulate(chain([a], xs), f) return g return go # take :: Int -> [a] -> [a] # take :: Int -> String -> String def take(n): '''The prefix of xs of length n, or xs itself if n > length xs. ''' def go(xs): return list(islice(xs, n)) return go # takeWhile :: (a -> Bool) -> [a] -> [a] # takeWhile :: (Char -> Bool) -> String -> String def takeWhile(p): '''The longest (possibly empty) prefix of xs in which all elements satisfy p. ''' return lambda xs: list( takewhile(p, xs) ) # unfoldr :: (b -> Maybe (a, b)) -> b -> [a] def unfoldr(f): '''Dual to reduce or foldr. Where catamorphism reduces a list to a summary value, the anamorphic unfoldr builds a list from a seed value. As long as f returns (a, b) a is prepended to the list, and the residual b is used as the argument for the next application of f. When f returns None, the completed list is returned. ''' def go(v): xr = v, v xs = [] while True: xr = f(xr[1]) if None is not xr: xs.append(xr[0]) else: return xs return go # unlines :: [String] -> String def unlines(xs): '''A single string formed 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()
Euclid-Mullin sequence
Python
Definition The Euclid-Mullin sequence is an infinite sequence of distinct prime numbers, in which each element is the least prime factor of one plus the product of all earlier elements. The first element is usually assumed to be 2. So the second element is : (2) + 1 = 3 and the third element is : (2 x 3) + 1 = 7 as this is prime. Although intermingled with smaller elements, the sequence can produce very large elements quite quickly and only the first 51 have been computed at the time of writing. ;Task Compute and show here the first '''16''' elements of the sequence or, if your language does not support arbitrary precision arithmetic, as many as you can. ;Stretch goal Compute the next '''11''' elements of the sequence. ;Reference OEIS sequence A000945
""" Rosetta code task: Euclid-Mullin_sequence """ from primePy import primes def euclid_mullin(): """ generate Euclid-Mullin sequence """ total = 1 while True: next_iter = primes.factor(total + 1) total *= next_iter yield next_iter GEN = euclid_mullin() print('First 16 Euclid-Mullin numbers:', ', '.join(str(next(GEN)) for _ in range(16)))
Euler's identity
Python
{{Wikipedia|Euler's_identity}} In mathematics, ''Euler's identity'' is the equality: ei\pi + 1 = 0 where e is Euler's number, the base of natural logarithms, ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and \pi is pi, the ratio of the circumference of a circle to its diameter. Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants: The number 0. The number 1. The number \pi (\pi = 3.14159+), The number e (e = 2.71828+), which occurs widely in mathematical analysis. The number ''i'', the imaginary unit of the complex numbers. ;Task Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation. Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation. If that is the case, or there is some other limitation, show that ei\pi + 1 is ''approximately'' equal to zero and show the amount of error in the calculation. If your language is capable of symbolic calculations, show that ei\pi + 1 is ''exactly'' equal to zero for bonus kudos points.
>>> import math >>> math.e ** (math.pi * 1j) + 1 1.2246467991473532e-16j
Euler's sum of powers conjecture
Python
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. This conjecture is called Euler's sum of powers conjecture and can be stated as such: :At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk. In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250. The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here. Related tasks are: * [[Pythagorean quadruples]]. * [[Pythagorean triples]].
def eulers_sum_of_powers(): max_n = 250 pow_5 = [n**5 for n in range(max_n)] pow5_to_n = {n**5: n for n in range(max_n)} for x0 in range(1, max_n): for x1 in range(1, x0): for x2 in range(1, x1): for x3 in range(1, x2): pow_5_sum = sum(pow_5[i] for i in (x0, x1, x2, x3)) if pow_5_sum in pow5_to_n: y = pow5_to_n[pow_5_sum] return (x0, x1, x2, x3, y) print("%i**5 + %i**5 + %i**5 + %i**5 == %i**5" % eulers_sum_of_powers())
Euler's sum of powers conjecture
Python 2.6+
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. This conjecture is called Euler's sum of powers conjecture and can be stated as such: :At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk. In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250. The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here. Related tasks are: * [[Pythagorean quadruples]]. * [[Pythagorean triples]].
from itertools import combinations def eulers_sum_of_powers(): max_n = 250 pow_5 = [n**5 for n in range(max_n)] pow5_to_n = {n**5: n for n in range(max_n)} for x0, x1, x2, x3 in combinations(range(1, max_n), 4): pow_5_sum = sum(pow_5[i] for i in (x0, x1, x2, x3)) if pow_5_sum in pow5_to_n: y = pow5_to_n[pow_5_sum] return (x0, x1, x2, x3, y) print("%i**5 + %i**5 + %i**5 + %i**5 == %i**5" % eulers_sum_of_powers())
Euler's sum of powers conjecture
Python 3.7
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. This conjecture is called Euler's sum of powers conjecture and can be stated as such: :At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk. In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250. The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here. Related tasks are: * [[Pythagorean quadruples]]. * [[Pythagorean triples]].
'''Euler's sum of powers conjecture''' from itertools import (chain, takewhile) # main :: IO () def main(): '''Search for counter-example''' xs = enumFromTo(1)(249) powerMap = {x**5: x for x in xs} sumMap = { x**5 + y**5: (x, y) for x in xs[1:] for y in xs if x > y } # isExample :: (Int, Int) -> Bool def isExample(ps): p, s = ps return p - s in sumMap # display :: (Int, Int) -> String def display(ps): p, s = ps a, b = sumMap[p - s] c, d = sumMap[s] return '^5 + '.join([str(n) for n in [a, b, c, d]]) + ( '^5 = ' + str(powerMap[p]) + '^5' ) print(__doc__ + ' – counter-example:\n') print( maybe('No counter-example found.')(display)( find(isExample)( bind(powerMap.keys())( lambda p: bind( takewhile( lambda x: p > x, sumMap.keys() ) )(lambda s: [(p, s)]) ) ) ) ) # ----------------------- GENERIC ------------------------ # Just :: a -> Maybe a def Just(x): '''Constructor for an inhabited Maybe (option type) value. Wrapper containing the result of a computation. ''' return {'type': 'Maybe', 'Nothing': False, 'Just': x} # Nothing :: () -> Maybe a def Nothing(): '''Constructor for an empty Maybe (option type) value. Empty wrapper returned where a computation is not possible. ''' return {'type': 'Maybe', 'Nothing': True} # 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. ''' def go(f): return chain.from_iterable(map(f, xs)) return go # enumFromTo :: (Int, Int) -> [Int] def enumFromTo(m): '''Integer enumeration from m to n.''' return lambda n: range(m, 1 + n) # find :: (a -> Bool) -> [a] -> Maybe a def find(p): '''Just the first element in the list that matches p, or Nothing if no elements match. ''' def go(xs): try: return Just(next(x for x in xs if p(x))) except StopIteration: return Nothing() return go # maybe :: b -> (a -> b) -> Maybe a -> b def maybe(v): '''Either the default value v, if m is Nothing, or the application of f to x, where m is Just(x). ''' return lambda f: lambda m: v if ( None is m or m.get('Nothing') ) else f(m.get('Just')) # MAIN --- if __name__ == '__main__': main()
Even or odd
Python
Test whether an integer is even or odd. There is more than one way to solve this task: * Use the even and odd predicates, if the language provides them. * Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd. * Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd. * Use modular congruences: ** ''i'' 0 (mod 2) iff ''i'' is even. ** ''i'' 1 (mod 2) iff ''i'' is odd.
>>> def is_odd(i): return bool(i & 1) >>> def is_even(i): return not is_odd(i) >>> [(j, is_odd(j)) for j in range(10)] [(0, False), (1, True), (2, False), (3, True), (4, False), (5, True), (6, False), (7, True), (8, False), (9, True)] >>> [(j, is_even(j)) for j in range(10)] [(0, True), (1, False), (2, True), (3, False), (4, True), (5, False), (6, True), (7, False), (8, True), (9, False)] >>>
Evolutionary algorithm
Python
Starting with: * The target string: "METHINKS IT IS LIKE A WEASEL". * An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). * A fitness function that computes the 'closeness' of its argument to the target string. * A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. * While the parent is not yet the target: :* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. :* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. :* repeat until the parent converges, (hopefully), to the target. ;See also: * Wikipedia entry: Weasel algorithm. * Wikipedia entry: Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, * While the parent is not yet the target: :* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, '''changing randomly any characters which don't already match the target''': ''NOTE:'' this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
from string import letters from random import choice, random target = list("METHINKS IT IS LIKE A WEASEL") charset = letters + ' ' parent = [choice(charset) for _ in range(len(target))] minmutaterate = .09 C = range(100) perfectfitness = float(len(target)) def fitness(trial): 'Sum of matching chars by position' return sum(t==h for t,h in zip(trial, target)) def mutaterate(): 'Less mutation the closer the fit of the parent' return 1-((perfectfitness - fitness(parent)) / perfectfitness * (1 - minmutaterate)) def mutate(parent, rate): return [(ch if random() <= rate else choice(charset)) for ch in parent] def que(): '(from the favourite saying of Manuel in Fawlty Towers)' print ("#%-4i, fitness: %4.1f%%, '%s'" % (iterations, fitness(parent)*100./perfectfitness, ''.join(parent))) def mate(a, b): place = 0 if choice(xrange(10)) < 7: place = choice(xrange(len(target))) else: return a, b return a, b, a[:place] + b[place:], b[:place] + a[place:] iterations = 0 center = len(C)/2 while parent != target: rate = mutaterate() iterations += 1 if iterations % 100 == 0: que() copies = [ mutate(parent, rate) for _ in C ] + [parent] parent1 = max(copies[:center], key=fitness) parent2 = max(copies[center:], key=fitness) parent = max(mate(parent1, parent2), key=fitness) que()