title
stringlengths 3
86
| language
stringlengths 1
35
| task
stringlengths 41
8.77k
| solution
stringlengths 60
47.6k
|
---|---|---|---|
Iterated digits squaring | Python from Ruby | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else iterate(step(x))
>>> [iterate(x) for x in xrange(1, 20)]
[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1]
;Task:
: Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89.
Or, for much less credit - (showing that your algorithm and/or language is slow):
: Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89.
This problem derives from the Project Euler problem 92.
For a quick algorithm for this task see the talk page
;Related tasks:
* [[Combinations with repetitions]]
* [[Digital root]]
* [[Digital root/Multiplicative digital root]]
| from itertools import combinations_with_replacement
from array import array
from time import clock
D = 8
F = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000, 355687428096000]
def b(n):
yield 1
for g in range(1,n+1):
gn = g
res = 0
while gn > 0:
gn,rem = divmod(gn,10)
res += rem**2
if res==89:
yield 0
else:
yield res
N = array('I',b(81*D))
for n in range(2,len(N)):
q = N[n]
while q>1:
q = N[q]
N[n] = q
es = clock()
z = 0
for n in combinations_with_replacement(range(10),D):
t = 0
for g in n:
t += g*g
if N[t] == 0:
continue
t = [0,0,0,0,0,0,0,0,0,0]
for g in n:
t[g] += 1
t1 = F[D]
for g in t:
t1 /= F[g]
z += t1
ee = clock() - es
print "\nD==" + str(D) + "\n " + str(z) + " numbers produce 1 and " + str(10**D-z) + " numbers produce 89"
print "Time ~= " + str(ee) + " secs"
|
JSON | Python 2.6+ | Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.
Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).
| >>> import json
>>> data = json.loads('{ "foo": 1, "bar": [10, "apples"] }')
>>> sample = { "blue": [1,2], "ocean": "water" }
>>> json_string = json.dumps(sample)
>>> json_string
'{"blue": [1, 2], "ocean": "water"}'
>>> sample
{'blue': [1, 2], 'ocean': 'water'}
>>> data
{'foo': 1, 'bar': [10, 'apples']} |
Jacobi symbol | Python | The '''Jacobi symbol''' is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p)
* (a | p) 1 if a is a square (mod p)
* (a | p) -1 if a is not a square (mod p)
* (a | p) 0 if a 0
If n is prime, then the Jacobi symbol (a | n) equals the Legendre symbol (a | n).
;Task:
Calculate the Jacobi symbol (a | n).
;Reference:
* Wikipedia article on Jacobi symbol.
| def jacobi(a, n):
if n <= 0:
raise ValueError("'n' must be a positive integer.")
if n % 2 == 0:
raise ValueError("'n' must be odd.")
a %= n
result = 1
while a != 0:
while a % 2 == 0:
a /= 2
n_mod_8 = n % 8
if n_mod_8 in (3, 5):
result = -result
a, n = n, a
if a % 4 == 3 and n % 4 == 3:
result = -result
a %= n
if n == 1:
return result
else:
return 0 |
Jacobsthal numbers | Python from Phix | '''Jacobsthal numbers''' are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.
J0 = 0
J1 = 1
Jn = Jn-1 + 2 x Jn-2
Terms may be calculated directly using one of several possible formulas:
Jn = ( 2n - (-1)n ) / 3
'''Jacobsthal-Lucas numbers''' are very similar. They have the same recurrence relationship, the only difference is an initial starting value '''J0 = 2''' rather than '''J0 = 0'''.
Terms may be calculated directly using one of several possible formulas:
JLn = 2n + (-1)n
'''Jacobsthal oblong numbers''' is the sequence obtained from multiplying each '''Jacobsthal number''' '''Jn''' by its direct successor '''Jn+1'''.
'''Jacobsthal primes''' are '''Jacobsthal numbers''' that are prime.
;Task
* Find and display the first 30 '''Jacobsthal numbers'''
* Find and display the first 30 '''Jacobsthal-Lucas numbers'''
* Find and display the first 20 '''Jacobsthal oblong numbers'''
* Find and display at least the first 10 '''Jacobsthal primes'''
;See also
;* Wikipedia: Jacobsthal number
;* Numbers Aplenty - Jacobsthal number
;* OEIS:A001045 - Jacobsthal sequence (or Jacobsthal numbers)
;* OEIS:A014551 - Jacobsthal-Lucas numbers.
;* OEIS:A084175 - Jacobsthal oblong numbers
;* OEIS:A049883 - Primes in the Jacobsthal sequence
;* Related task: Fibonacci sequence
;* Related task: Leonardo numbers
| #!/usr/bin/python
from math import floor, pow
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def odd(n):
return n and 1 != 0
def jacobsthal(n):
return floor((pow(2,n)+odd(n))/3)
def jacobsthal_lucas(n):
return int(pow(2,n)+pow(-1,n))
def jacobsthal_oblong(n):
return jacobsthal(n)*jacobsthal(n+1)
if __name__ == '__main__':
print("First 30 Jacobsthal numbers:")
for j in range(0, 30):
print(jacobsthal(j), end=" ")
print("\n\nFirst 30 Jacobsthal-Lucas numbers: ")
for j in range(0, 30):
print(jacobsthal_lucas(j), end = '\t')
print("\n\nFirst 20 Jacobsthal oblong numbers: ")
for j in range(0, 20):
print(jacobsthal_oblong(j), end=" ")
print("\n\nFirst 10 Jacobsthal primes: ")
for j in range(3, 33):
if isPrime(jacobsthal(j)):
print(jacobsthal(j)) |
Jaro similarity | Python 3 | The Jaro distance is a measure of edit distance between two strings; its inverse, called the ''Jaro similarity'', is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that '''0''' equates to no similarities and '''1''' is an exact match.
;;Definition
The Jaro similarity d_j of two given strings s_1 and s_2 is
: d_j = \left\{
\begin{array}{l l}
0 & \text{if }m = 0\\
\frac{1}{3}\left(\frac{m}{|s_1|} + \frac{m}{|s_2|} + \frac{m-t}{m}\right) & \text{otherwise} \end{array} \right.
Where:
* m is the number of ''matching characters'';
* t is half the number of ''transpositions''.
Two characters from s_1 and s_2 respectively, are considered ''matching'' only if they are the same and not farther apart than \left\lfloor\frac{\max(|s_1|,|s_2|)}{2}\right\rfloor-1 characters.
Each character of s_1 is compared with all its matching characters in s_2. Each difference in position is half a ''transposition''; that is, the number of transpositions is half the number of characters which are common to the two strings but occupy different positions in each one.
;;Example
Given the strings s_1 ''DWAYNE'' and s_2 ''DUANE'' we find:
* m = 4
* |s_1| = 6
* |s_2| = 5
* t = 0
We find a Jaro score of:
: d_j = \frac{1}{3}\left(\frac{4}{6} + \frac{4}{5} + \frac{4-0}{4}\right) = 0.822
;Task
Implement the Jaro algorithm and show the similarity scores for each of the following pairs:
* ("MARTHA", "MARHTA")
* ("DIXON", "DICKSONX")
* ("JELLYFISH", "SMELLYFISH")
; See also
* Jaro-Winkler distance on Wikipedia.
| '''Jaro distance between two strings'''
from functools import reduce
import itertools
# --------------------- JARO FUNCTION ----------------------
# jaro :: String -> String -> Float
def jaro(x):
'''The Jaro distance between two strings.'''
def go(s1, s2):
m, t = ap(compose(Tuple, len))(
transpositionSum
)(matches(s1, s2))
return 0 if 0 == m else (
(1 / 3) * ((m / len(s1)) + (
m / len(s2)
) + ((m - t) / m))
)
return lambda y: go(x, y)
# -------------------------- TEST --------------------------
# main :: IO ()
def main():
'''Sample word pairs'''
print(
fTable('Jaro distances:\n')(str)(
showPrecision(3)
)(
uncurry(jaro)
)([
("DWAYNE", "DUANE"),
("MARTHA", "MARHTA"),
("DIXON", "DICKSONX"),
("JELLYFISH", "SMELLYFISH")
])
)
# ----------------- JARO HELPER FUNCTIONS ------------------
# transpositionSum :: [(Int, Char)] -> Int
def transpositionSum(xs):
'''A count of the transpositions in xs.'''
def f(a, xy):
x, y = xy
return 1 + a if fst(x) > fst(y) else a
return reduce(f, zip(xs, xs[1:]), 0)
# matches :: String -> String -> [(Int, Char)]
def matches(s1, s2):
'''A list of (Index, Char) correspondences
between the two strings s1 and s2.'''
[(_, xs), (l2, ys)] = sorted(map(
ap(compose(Tuple, len))(list), [s1, s2]
))
r = l2 // 2 - 1
# match :: (Int, (Char, Int)) -> (Int, Char)
def match(a, nc):
n, c = nc
offset = max(0, n - (1 + r))
def indexChar(x):
return a + [(offset + x, c)]
return maybe(a)(indexChar)(
elemIndex(c)(
drop(offset)(take(n + r)(ys))
)
)
return reduce(match, enumerate(xs), [])
# ------------------- GENERIC FUNCTIONS --------------------
# 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}
# Tuple (,) :: a -> b -> (a, b)
def Tuple(x):
'''Constructor for a pair of values,
possibly of two different types.
'''
def go(y):
return (
x + (y,)
) if isinstance(x, tuple) else (x, y)
return go
# 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
# 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)
# 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
# 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 go
# fst :: (a, b) -> a
def fst(tpl):
'''First member of a pair.'''
return tpl[0]
# 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'))
# showPrecision Int -> Float -> String
def showPrecision(n):
'''A string showing a floating point number
at a given degree of precision.'''
return lambda x: str(round(x, n))
# 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 gox(xShow):
def gofx(fxShow):
def gof(f):
def goxs(xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
def arrowed(x, y):
return y.rjust(w, ' ') + (
' -> ' + fxShow(f(x))
)
return s + '\n' + '\n'.join(
map(arrowed, xs, ys)
)
return goxs
return gof
return gofx
return gox
# 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.
'''
islice = itertools.islice
def go(xs):
return (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
return go
# 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]
)
# MAIN ---
if __name__ == '__main__':
main() |
Jewels and stones | Python | Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct.
The function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.
Note that:
:# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered.
:# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'.
:# The parameters do not need to have exactly the same names.
:# Validating the arguments is unnecessary.
So, for example, if passed "aAAbbbb" for 'stones' and "aA" for 'jewels', the function should return 3.
This task was inspired by this problem.
| def countJewels(s, j):
return sum(x in j for x in s)
print countJewels("aAAbbbb", "aA")
print countJewels("ZZ", "z") |
Juggler sequence | Python | Background of the '''juggler sequence''':
Juggler sequences were publicized by an American mathematician and author Clifford A. Pickover. The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences, much like balls in the hands of a juggler.
;Description
A juggler sequence is an integer sequence that starts with a positive integer a[0], with each subsequent term in the sequence being defined by the recurrence relation:
a[k + 1] = floor(a[k] ^ 0.5) if a[k] is even ''' ''or'' '''
a[k + 1] = floor(a[k] ^ 1.5) if a[k] is odd
If a juggler sequence reaches 1, then all subsequent terms are equal to 1. This is known to be the case for initial terms up to 1,000,000 but it is not known whether all juggler sequences after that will eventually reach 1.
;Task:
Compute and show here the following statistics for juggler sequences with an initial term of a[n] where n is between '''20''' and '''39''' inclusive:
* l[n] - the number of terms needed to reach 1.
* h[n] - the maximum value reached in that sequence.
* i[n] - the index of the term (starting from 0) at which the maximum is (first) reached.
If your language supports ''big integers'' with an integer square root function, also compute and show here the same statistics for as many as you reasonably can of the following values for n:
113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915, 5812827
Those with fast languages and fast machines may also like to try their luck at n = 7110201.
However, as h[n] for most of these numbers is thousands or millions of digits long, show instead of h[n]:
* d[n] - the number of digits in h[n]
The results can be (partially) verified against the table here.
;Related tasks:
* [[Hailstone sequence]]
* [[Yellowstone sequence]]
* [[Isqrt_(integer_square_root)_of_X]]
;See also:
* [[oeis:A007320]] Number of steps needed for Juggler sequence started at n to reach 1
* [[oeis:A094716]] Largest value in the Juggler sequence started at n
| from math import isqrt
def juggler(k, countdig=True, maxiters=1000):
m, maxj, maxjpos = k, k, 0
for i in range(1, maxiters):
m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m)
if m >= maxj:
maxj, maxjpos = m, i
if m == 1:
print(f"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}")
return i
print("ERROR: Juggler series starting with $k did not converge in $maxiters iterations")
print(" n l(n) i(n) h(n) or d(n)\n-------------------------------------------")
for k in range(20, 40):
juggler(k, False)
for k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:
juggler(k)
|
Julia set | Python from zkl | Task
Generate and draw a Julia set.
;Related tasks
* Mandelbrot Set
| """
Solution from:
https://codereview.stackexchange.com/questions/210271/generating-julia-set
"""
from functools import partial
from numbers import Complex
from typing import Callable
import matplotlib.pyplot as plt
import numpy as np
def douady_hubbard_polynomial(z: Complex,
c: Complex) -> Complex:
"""
Monic and centered quadratic complex polynomial
https://en.wikipedia.org/wiki/Complex_quadratic_polynomial#Map
"""
return z ** 2 + c
def julia_set(mapping: Callable[[Complex], Complex],
*,
min_coordinate: Complex,
max_coordinate: Complex,
width: int,
height: int,
iterations_count: int = 256,
threshold: float = 2.) -> np.ndarray:
"""
As described in https://en.wikipedia.org/wiki/Julia_set
:param mapping: function defining Julia set
:param min_coordinate: bottom-left complex plane coordinate
:param max_coordinate: upper-right complex plane coordinate
:param height: pixels in vertical axis
:param width: pixels in horizontal axis
:param iterations_count: number of iterations
:param threshold: if the magnitude of z becomes greater
than the threshold we assume that it will diverge to infinity
:return: 2D pixels array of intensities
"""
im, re = np.ogrid[min_coordinate.imag: max_coordinate.imag: height * 1j,
min_coordinate.real: max_coordinate.real: width * 1j]
z = (re + 1j * im).flatten()
live, = np.indices(z.shape) # indexes of pixels that have not escaped
iterations = np.empty_like(z, dtype=int)
for i in range(iterations_count):
z_live = z[live] = mapping(z[live])
escaped = abs(z_live) > threshold
iterations[live[escaped]] = i
live = live[~escaped]
if live.size == 0:
break
else:
iterations[live] = iterations_count
return iterations.reshape((height, width))
if __name__ == '__main__':
mapping = partial(douady_hubbard_polynomial,
c=-0.7 + 0.27015j) # type: Callable[[Complex], Complex]
image = julia_set(mapping,
min_coordinate=-1.5 - 1j,
max_coordinate=1.5 + 1j,
width=800,
height=600)
plt.axis('off')
plt.imshow(image,
cmap='nipy_spectral_r',
origin='lower')
plt.show()
|
Jump anywhere | Python | Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their [[conditional structures]] and [[loops]] to ''local jumps'' within a function. Some assembly languages limit certain jumps or branches to a small range.
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes.
You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].
This task provides a "grab bag" for several types of jumps. There are ''non-local jumps'' across function calls, or ''long jumps'' to anywhere within a program. Anywhere means not only to the tops of functions!
* Some languages can ''go to'' any global label in a program.
* Some languages can break multiple function calls, also known as ''unwinding the call stack''.
* Some languages can save a ''continuation''. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation).
These jumps are not all alike.
A simple ''goto'' never touches the call stack.
A continuation saves the call stack, so you can continue a function call after it ends.
;Task:
Use your language to demonstrate the various types of jumps that it supports.
Because the possibilities vary by language, this task is not specific.
You have the freedom to use these jumps for different purposes.
You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].
| # Example 2: Restarting a loop:
from goto import goto, label
label .start
for i in range(1, 4):
print i
if i == 2:
try:
output = message
except NameError:
print "Oops - forgot to define 'message'! Start again."
message = "Hello world"
goto .start
print output, "\n"
|
K-d tree | Python from D | {{wikipedia|K-d tree}}
A k-d tree (short for ''k''-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space. k-d trees are a useful data structure for several applications, such as searches involving a multidimensional search key (e.g. range searches and nearest neighbor searches).
k-d trees are a special case of binary space partitioning trees.
k-d trees are not suitable, however, for efficiently finding the nearest neighbor in high dimensional spaces. As a general rule, if the dimensionality is ''k'', the number of points in the data, ''N'', should be ''N'' 2''k''.
Otherwise, when k-d trees are used with high-dimensional data, most of the points in the tree will be evaluated and the efficiency is no better than exhaustive search, and other methods such as approximate nearest-neighbor are used instead.
'''Task:''' Construct a k-d tree and perform a nearest neighbor search for two example data sets:
# The Wikipedia example data of [(2,3), (5,4), (9,6), (4,7), (8,1), (7,2)].
# 1000 3-d points uniformly distributed in a 3-d cube.
For the Wikipedia example, find the nearest neighbor to point (9, 2)
For the random data, pick a random location and find the nearest neighbor.
In addition, instrument your code to count the number of nodes visited in the nearest neighbor search. Count a node as visited if any field of it is accessed.
Output should show the point searched for, the point found,
the distance to the point, and the number of nodes visited.
There are variant algorithms for constructing the tree.
You can use a simple median strategy or implement something more efficient.
Variants of the nearest neighbor search include nearest N neighbors, approximate nearest neighbor, and range searches.
You do not have to implement these.
The requirement for this task is specifically the nearest single neighbor.
Also there are algorithms for inserting, deleting, and balancing k-d trees.
These are also not required for the task.
| from random import seed, random
from time import time
from operator import itemgetter
from collections import namedtuple
from math import sqrt
from copy import deepcopy
def sqd(p1, p2):
return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))
class KdNode(object):
__slots__ = ("dom_elt", "split", "left", "right")
def __init__(self, dom_elt, split, left, right):
self.dom_elt = dom_elt
self.split = split
self.left = left
self.right = right
class Orthotope(object):
__slots__ = ("min", "max")
def __init__(self, mi, ma):
self.min, self.max = mi, ma
class KdTree(object):
__slots__ = ("n", "bounds")
def __init__(self, pts, bounds):
def nk2(split, exset):
if not exset:
return None
exset.sort(key=itemgetter(split))
m = len(exset) // 2
d = exset[m]
while m + 1 < len(exset) and exset[m + 1][split] == d[split]:
m += 1
d = exset[m]
s2 = (split + 1) % len(d) # cycle coordinates
return KdNode(d, split, nk2(s2, exset[:m]),
nk2(s2, exset[m + 1:]))
self.n = nk2(0, pts)
self.bounds = bounds
T3 = namedtuple("T3", "nearest dist_sqd nodes_visited")
def find_nearest(k, t, p):
def nn(kd, target, hr, max_dist_sqd):
if kd is None:
return T3([0.0] * k, float("inf"), 0)
nodes_visited = 1
s = kd.split
pivot = kd.dom_elt
left_hr = deepcopy(hr)
right_hr = deepcopy(hr)
left_hr.max[s] = pivot[s]
right_hr.min[s] = pivot[s]
if target[s] <= pivot[s]:
nearer_kd, nearer_hr = kd.left, left_hr
further_kd, further_hr = kd.right, right_hr
else:
nearer_kd, nearer_hr = kd.right, right_hr
further_kd, further_hr = kd.left, left_hr
n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd)
nearest = n1.nearest
dist_sqd = n1.dist_sqd
nodes_visited += n1.nodes_visited
if dist_sqd < max_dist_sqd:
max_dist_sqd = dist_sqd
d = (pivot[s] - target[s]) ** 2
if d > max_dist_sqd:
return T3(nearest, dist_sqd, nodes_visited)
d = sqd(pivot, target)
if d < dist_sqd:
nearest = pivot
dist_sqd = d
max_dist_sqd = dist_sqd
n2 = nn(further_kd, target, further_hr, max_dist_sqd)
nodes_visited += n2.nodes_visited
if n2.dist_sqd < dist_sqd:
nearest = n2.nearest
dist_sqd = n2.dist_sqd
return T3(nearest, dist_sqd, nodes_visited)
return nn(t.n, p, t.bounds, float("inf"))
def show_nearest(k, heading, kd, p):
print(heading + ":")
print("Point: ", p)
n = find_nearest(k, kd, p)
print("Nearest neighbor:", n.nearest)
print("Distance: ", sqrt(n.dist_sqd))
print("Nodes visited: ", n.nodes_visited, "\n")
def random_point(k):
return [random() for _ in range(k)]
def random_points(k, n):
return [random_point(k) for _ in range(n)]
if __name__ == "__main__":
seed(1)
P = lambda *coords: list(coords)
kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)],
Orthotope(P(0, 0), P(10, 10)))
show_nearest(2, "Wikipedia example data", kd1, P(9, 2))
N = 400000
t0 = time()
kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1)))
t1 = time()
text = lambda *parts: "".join(map(str, parts))
show_nearest(2, text("k-d tree with ", N,
" random 3D points (generation time: ",
t1-t0, "s)"),
kd2, random_point(3)) |
Kaprekar numbers | Python | A positive integer is a Kaprekar number if:
* It is '''1''' (unity)
* The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
Note that a split resulting in a part consisting purely of 0s is not valid,
as 0 is not considered positive.
;Example Kaprekar numbers:
* 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223.
* The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, ....
;Example process:
10000 (1002) splitting from left to right:
* The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive.
* Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid.
;Task:
Generate and show all Kaprekar numbers less than 10,000.
;Extra credit:
Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.
;Extra extra credit:
The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers);
if you can, show that Kaprekar numbers exist in other bases too.
For this purpose, do the following:
* Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million);
* Display each of them in base 10 representation;
* Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square.
For example, 225(10) is "d4" in base 17, its square "a52g", and a5(17) + 2g(17) = d4(17), so the display would be something like:225 d4 a52g a5 + 2g
;Reference:
* The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version
;Related task:
* [[Casting out nines]]
| def encode(n, base):
result = ""
while n:
n, d = divmod(n, base)
if d < 10:
result += str(d)
else:
result += chr(d - 10 + ord("a"))
return result[::-1]
def Kaprekar(n, base):
if n == '1':
return True
sq = encode((int(n, base)**2), base)
for i in range(1,len(sq)):
if (int(sq[:i], base) + int(sq[i:], base) == int(n, base)) and (int(sq[:i], base) > 0) and (int(sq[i:], base)>0):
return True
return False
def Find(m, n, base):
return [encode(i, base) for i in range(m,n+1) if Kaprekar(encode(i, base), base)]
m = int(raw_input('Where to start?\n'))
n = int(raw_input('Where to stop?\n'))
base = int(raw_input('Enter base:'))
KNumbers = Find(m, n, base)
for i in KNumbers:
print i
print 'The number of Kaprekar Numbers found are',
print len(KNumbers)
raw_input() |
Kernighans large earthquake problem | Python | Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based.
;Problem:
You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event.
Example lines from the file would be lines like:
8/27/1883 Krakatoa 8.8
5/18/1980 MountStHelens 7.6
3/13/2009 CostaRica 5.1
;Task:
* Create a program or script invocation to find all the events with magnitude greater than 6
* Assuming an appropriate name e.g. "data.txt" for the file:
:# Either: Show how your program is invoked to process a data file of that name.
:# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).
| from os.path import expanduser
from functools import (reduce)
from itertools import (chain)
# largeQuakes :: Int -> [String] -> [(String, String, String)]
def largeQuakes(n):
def quake(threshold):
def go(x):
ws = x.split()
return [tuple(ws)] if threshold < float(ws[2]) else []
return lambda x: go(x)
return concatMap(quake(n))
# main :: IO ()
def main():
print (
largeQuakes(6)(
open(expanduser('~/data.txt')).read().splitlines()
)
)
# GENERIC ABSTRACTION -------------------------------------
# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
return lambda xs: list(
chain.from_iterable(
map(f, xs)
)
)
# MAIN ---
if __name__ == '__main__':
main() |
Keyboard input/Obtain a Y or N response | Python | Obtain a valid '''Y''' or '''N''' response from the [[input device::keyboard]].
The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing '''Y''' or '''N''' key-press from being evaluated.
The response should be obtained as soon as '''Y''' or '''N''' are pressed, and there should be no need to press an enter key.
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from curses import wrapper
#
#
def main(stdscr):
# const
#y = ord("y")
#n = ord("n")
while True:
# keyboard input interceptor|listener
#window.nodelay(yes)
# - If yes is 1, getch() will be non-blocking.
# return char code
#kb_Inpt = stdscr.getch()
# return string
kb_Inpt = stdscr.getkey()
#if kb_Inpt == (y or n):
if kb_Inpt.lower() == ('y' or 'n'):
break
return None
#
return None
#
#*** unit test ***#
if __name__ == "__main__":
#
wrapper(main) |
Knight's tour | Python | Task
Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position.
Input and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard.
Input: starting square
Output: move sequence
;Related tasks
* [[A* search algorithm]]
* [[N-queens problem]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]
| import copy
boardsize=6
_kmoves = ((2,1), (1,2), (-1,2), (-2,1), (-2,-1), (-1,-2), (1,-2), (2,-1))
def chess2index(chess, boardsize=boardsize):
'Convert Algebraic chess notation to internal index format'
chess = chess.strip().lower()
x = ord(chess[0]) - ord('a')
y = boardsize - int(chess[1:])
return (x, y)
def boardstring(board, boardsize=boardsize):
r = range(boardsize)
lines = ''
for y in r:
lines += '\n' + ','.join('%2i' % board[(x,y)] if board[(x,y)] else ' '
for x in r)
return lines
def knightmoves(board, P, boardsize=boardsize):
Px, Py = P
kmoves = set((Px+x, Py+y) for x,y in _kmoves)
kmoves = set( (x,y)
for x,y in kmoves
if 0 <= x < boardsize
and 0 <= y < boardsize
and not board[(x,y)] )
return kmoves
def accessibility(board, P, boardsize=boardsize):
access = []
brd = copy.deepcopy(board)
for pos in knightmoves(board, P, boardsize=boardsize):
brd[pos] = -1
access.append( (len(knightmoves(brd, pos, boardsize=boardsize)), pos) )
brd[pos] = 0
return access
def knights_tour(start, boardsize=boardsize, _debug=False):
board = {(x,y):0 for x in range(boardsize) for y in range(boardsize)}
move = 1
P = chess2index(start, boardsize)
board[P] = move
move += 1
if _debug:
print(boardstring(board, boardsize=boardsize))
while move <= len(board):
P = min(accessibility(board, P, boardsize))[1]
board[P] = move
move += 1
if _debug:
print(boardstring(board, boardsize=boardsize))
input('\n%2i next: ' % move)
return board
if __name__ == '__main__':
while 1:
boardsize = int(input('\nboardsize: '))
if boardsize < 5:
continue
start = input('Start position: ')
board = knights_tour(start, boardsize)
print(boardstring(board, boardsize=boardsize)) |
Knuth's algorithm S | Python 3.x | This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive samples can change).
;The algorithm:
:* Select the first n items as the sample as they become available;
:* For the i-th item where i > n, have a random chance of n/i of keeping it. If failing this chance, the sample remains the same. If not, have it randomly (1/n) replace one of the previously selected n items of the sample.
:* Repeat 2nd step for any subsequent items.
;The Task:
:* Create a function s_of_n_creator that given n the maximum sample size, returns a function s_of_n that takes one parameter, item.
:* Function s_of_n when called with successive items returns an equi-weighted random sample of up to n of its items so far, each time it is called, calculated using Knuths Algorithm S.
:* Test your functions by printing and showing the frequency of occurrences of the selected digits from 100,000 repetitions of:
:::# Use the s_of_n_creator with n == 3 to generate an s_of_n.
:::# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9.
Note: A class taking n and generating a callable instance/function might also be used.
;Reference:
* The Art of Computer Programming, Vol 2, 3.4.2 p.142
;Related tasks:
* [[One of n lines in a file]]
* [[Accumulator factory]]
| from random import randrange
def s_of_n_creator(n):
sample, i = [], 0
def s_of_n(item):
nonlocal i
i += 1
if i <= n:
# Keep first n items
sample.append(item)
elif randrange(i) < n:
# Keep item
sample[randrange(n)] = item
return sample
return s_of_n
if __name__ == '__main__':
bin = [0]* 10
items = range(10)
print("Single run samples for n = 3:")
s_of_n = s_of_n_creator(3)
for item in items:
sample = s_of_n(item)
print(" Item: %i -> sample: %s" % (item, sample))
#
for trial in range(100000):
s_of_n = s_of_n_creator(3)
for item in items:
sample = s_of_n(item)
for s in sample:
bin[s] += 1
print("\nTest item frequencies for 100000 runs:\n ",
'\n '.join("%i:%i" % x for x in enumerate(bin))) |
Koch curve | Python | Draw a Koch curve. See details: Koch curve
| ===Functional===
Generates SVG for a Koch snowflake. To view, save as a text file with the extension .svg, and open in a browser.
|
Koch curve | Python from Haskell | Draw a Koch curve. See details: Koch curve
| '''Koch curve'''
from math import cos, pi, sin
from operator import add, sub
from itertools import chain
# kochSnowflake :: Int -> (Float, Float) -> (Float, Float) -> [(Float, Float)]
def kochSnowflake(n, a, b):
'''List of points on a Koch snowflake of order n, derived
from an equilateral triangle with base a b.
'''
points = [a, equilateralApex(a, b), b]
return chain.from_iterable(map(
kochCurve(n),
points,
points[1:] + [points[0]]
))
# kochCurve :: Int -> (Float, Float) -> (Float, Float)
# -> [(Float, Float)]
def kochCurve(n):
'''List of points on a Koch curve of order n,
starting at point ab, and ending at point xy.
'''
def koch(n):
def goTuple(abxy):
ab, xy = abxy
if 0 == n:
return [xy]
else:
mp, mq = midThirdOfLine(ab, xy)
points = [
ab,
mp,
equilateralApex(mp, mq),
mq,
xy
]
return list(
chain.from_iterable(map(
koch(n - 1),
zip(points, points[1:])
))
)
return goTuple
def go(ab, xy):
return [ab] + koch(n)((ab, xy))
return go
# equilateralApex :: (Float, Float) -> (Float, Float) -> (Float, Float)
def equilateralApex(p, q):
'''Apex of triangle with base p q.
'''
return rotatedPoint(pi / 3)(p, q)
# rotatedPoint :: Float -> (Float, Float) ->
# (Float, Float) -> (Float, Float)
def rotatedPoint(theta):
'''The point ab rotated theta radians
around the origin xy.
'''
def go(xy, ab):
ox, oy = xy
a, b = ab
dx, dy = rotatedVector(theta, (a - ox, oy - b))
return ox + dx, oy - dy
return go
# rotatedVector :: Float -> (Float, Float) -> (Float, Float)
def rotatedVector(theta, xy):
'''The vector xy rotated by theta radians.
'''
x, y = xy
return (
x * cos(theta) - y * sin(theta),
x * sin(theta) + y * cos(theta)
)
# midThirdOfLine :: (Float, Float) -> (Float, Float)
# -> ((Float, Float), (Float, Float))
def midThirdOfLine(ab, xy):
'''Second of three equal segments of
the line between ab and xy.
'''
vector = [x / 3 for x in map(sub, xy, ab)]
def f(p):
return tuple(map(add, vector, p))
p = f(ab)
return (p, f(p))
# -------------------------- TEST --------------------------
# main :: IO ()
def main():
'''SVG for Koch snowflake of order 4.
'''
print(
svgFromPoints(1024)(
kochSnowflake(
4, (200, 600), (800, 600)
)
)
)
# -------------------------- SVG ---------------------------
# svgFromPoints :: Int -> [(Float, Float)] -> SVG String
def svgFromPoints(w):
'''Width of square canvas -> Point list -> SVG string.
'''
def go(xys):
xs = ' '.join(map(
lambda xy: str(round(xy[0], 2)) + ' ' + str(round(xy[1], 2)),
xys
))
return '\n'.join([
'<svg xmlns="http://www.w3.org/2000/svg"',
f'width="512" height="512" viewBox="5 5 {w} {w}">',
f'<path d="M{xs}" ',
'stroke-width="2" stroke="red" fill="transparent"/>',
'</svg>'
])
return go
# MAIN ---
if __name__ == '__main__':
main() |
Kolakoski sequence | Python | The natural numbers, (excluding zero); with the property that:
: ''if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence''.
;Example:
This is ''not'' a Kolakoski sequence:
1,1,2,2,2,1,2,2,1,2,...
Its sequence of run counts, (sometimes called a run length encoding, (RLE); but a true RLE also gives the character that each run encodes), is calculated like this:
: Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ...
The above gives the RLE of:
2, 3, 1, 2, 1, ...
The original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''.
;Creating a Kolakoski sequence:
Lets start with the two numbers (1, 2) that we will cycle through; i.e. they will be used in this order: 1,2,1,2,1,2,....
# We start the sequence s with the first item from the cycle c: 1
# An index, k, into the, (expanding), sequence will step, or index through each item of the sequence s from the first, at its own rate.
We will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s.
We started s with 1 and therefore s[k] states that it should appear only the 1 time.
Increment k
Get the next item from c and append it to the end of sequence s. s will then become: 1, 2
k was moved to the second item in the list and s[k] states that it should appear two times, so append another of the last item to the sequence s: 1, 2,2
Increment k
Append the next item from the cycle to the list: 1, 2,2, 1
k is now at the third item in the list that states that the last item should appear twice so add another copy of the last item to the sequence s: 1, 2,2, 1,1
increment k
...
'''Note''' that the RLE of 1, 2, 2, 1, 1, ... begins 1, 2, 2 which is the beginning of the original sequence. The generation algorithm ensures that this will always be the case.
;Task:
# Create a routine/proceedure/function/... that given an initial ordered list/array/tuple etc of the natural numbers (1, 2), returns the next number from the list when accessed in a cycle.
# Create another routine that when given the initial ordered list (1, 2) and the minimum length of the sequence to generate; uses the first routine and the algorithm above, to generate at least the requested first members of the kolakoski sequence.
# Create a routine that when given a sequence, creates the run length encoding of that sequence (as defined above) and returns the result of checking if sequence starts with the exact members of its RLE. (But ''note'', due to sampling, do not compare the last member of the RLE).
# Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2)
# Check the sequence againt its RLE.
# Show, on this page, the first 20 members of the sequence generated from (2, 1)
# Check the sequence againt its RLE.
# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2)
# Check the sequence againt its RLE.
# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1)
# Check the sequence againt its RLE.
(There are rules on generating Kolakoski sequences from this method that are broken by the last example)
| import itertools
def cycler(start_items):
return itertools.cycle(start_items).__next__
def _kolakoski_gen(start_items):
s, k = [], 0
c = cycler(start_items)
while True:
c_next = c()
s.append(c_next)
sk = s[k]
yield sk
if sk > 1:
s += [c_next] * (sk - 1)
k += 1
def kolakoski(start_items=(1, 2), length=20):
return list(itertools.islice(_kolakoski_gen(start_items), length))
def _run_len_encoding(truncated_series):
return [len(list(group)) for grouper, group in itertools.groupby(truncated_series)][:-1]
def is_series_eq_its_rle(series):
rle = _run_len_encoding(series)
return (series[:len(rle)] == rle) if rle else not series
if __name__ == '__main__':
for start_items, length in [((1, 2), 20), ((2, 1), 20),
((1, 3, 1, 2), 30), ((1, 3, 2, 1), 30)]:
print(f'\n## {length} members of the series generated from {start_items} is:')
s = kolakoski(start_items, length)
print(f' {s}')
ans = 'YES' if is_series_eq_its_rle(s) else 'NO'
print(f' Does it look like a Kolakoski sequence: {ans}') |
Kosaraju | Python | {{wikipedia|Graph}}
Kosaraju's algorithm (also known as the Kosaraju-Sharir algorithm) is a linear time algorithm to find the strongly connected components of a directed graph. Aho, Hopcroft and Ullman credit it to an unpublished paper from 1978 by S. Rao Kosaraju. The same algorithm was independently discovered by Micha Sharir and published by him in 1981. It makes use of the fact that the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph.
For this task consider the directed graph with these connections:
0 -> 1
1 -> 2
2 -> 0
3 -> 1, 3 -> 2, 3 -> 4
4 -> 3, 4 -> 5
5 -> 2, 5 -> 6
6 -> 5
7 -> 4, 7 -> 6, 7 -> 7
And report the kosaraju strongly connected component for each node.
;References:
* The article on Wikipedia.
| def kosaraju(g):
class nonlocal: pass
# 1. For each vertex u of the graph, mark u as unvisited. Let l be empty.
size = len(g)
vis = [False]*size # vertexes that have been visited
l = [0]*size
nonlocal.x = size
t = [[]]*size # transpose graph
def visit(u):
if not vis[u]:
vis[u] = True
for v in g[u]:
visit(v)
t[v] = t[v] + [u]
nonlocal.x = nonlocal.x - 1
l[nonlocal.x] = u
# 2. For each vertex u of the graph do visit(u)
for u in range(len(g)):
visit(u)
c = [0]*size
def assign(u, root):
if vis[u]:
vis[u] = False
c[u] = root
for v in t[u]:
assign(v, root)
# 3: For each element u of l in order, do assign(u, u)
for u in l:
assign(u, u)
return c
g = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]
print kosaraju(g) |
Lah numbers | Python | Lah numbers, sometimes referred to as ''Stirling numbers of the third kind'', are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.
Unsigned Lah numbers count the number of ways a set of '''n''' elements can be partitioned into '''k''' non-empty linearly ordered subsets.
Lah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them.
Lah numbers obey the identities and relations:
L(n, 0), L(0, k) = 0 # for n, k > 0
L(n, n) = 1
L(n, 1) = n!
L(n, k) = ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For unsigned Lah numbers
''or''
L(n, k) = (-1)**n * ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For signed Lah numbers
;Task:
:* Write a routine (function, procedure, whatever) to find '''unsigned Lah numbers'''. There are several methods to generate unsigned Lah numbers. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
:* Using the routine, generate and show here, on this page, a table (or triangle) showing the unsigned Lah numbers, '''L(n, k)''', up to '''L(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where L(n, k) == 0 (when k > n).
:* If your language supports large integers, find and show here, on this page, the maximum value of '''L(n, k)''' where '''n == 100'''.
;See also:
:* '''Wikipedia - Lah number'''
:* '''OEIS:A105278 - Unsigned Lah numbers'''
:* '''OEIS:A008297 - Signed Lah numbers'''
;Related Tasks:
:* '''Stirling numbers of the first kind'''
:* '''Stirling numbers of the second kind'''
:* '''Bell numbers'''
| from math import (comb,
factorial)
def lah(n, k):
if k == 1:
return factorial(n)
if k == n:
return 1
if k > n:
return 0
if k < 1 or n < 1:
return 0
return comb(n, k) * factorial(n - 1) // factorial(k - 1)
def main():
print("Unsigned Lah numbers: L(n, k):")
print("n/k ", end='\t')
for i in range(13):
print("%11d" % i, end='\t')
print()
for row in range(13):
print("%-4d" % row, end='\t')
for i in range(row + 1):
l = lah(row, i)
print("%11d" % l, end='\t')
print()
print("\nMaximum value from the L(100, *) row:")
max_val = max(lah(100, a) for a in range(100))
print(max_val)
if __name__ == '__main__':
main() |
Largest int from concatenated ints | Python | Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
:::::* {1, 34, 3, 98, 9, 76, 45, 4}
:::::* {54, 546, 548, 60}
;Possible algorithms:
# A solution could be found by trying all combinations and return the best.
# Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X.
# Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key.
;See also:
* Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?
* Constructing the largest number possible by rearranging a list
| try:
cmp # Python 2 OK or NameError in Python 3
def maxnum(x):
return ''.join(sorted((str(n) for n in x),
cmp=lambda x,y:cmp(y+x, x+y)))
except NameError:
# Python 3
from functools import cmp_to_key
def cmp(x, y):
return -1 if x<y else ( 0 if x==y else 1)
def maxnum(x):
return ''.join(sorted((str(n) for n in x),
key=cmp_to_key(lambda x,y:cmp(y+x, x+y))))
for numbers in [(1, 34, 3, 98, 9, 76, 45, 4), (54, 546, 548, 60)]:
print('Numbers: %r\n Largest integer: %15s' % (numbers, maxnum(numbers))) |
Largest int from concatenated ints | Python 2.6+ | Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
:::::* {1, 34, 3, 98, 9, 76, 45, 4}
:::::* {54, 546, 548, 60}
;Possible algorithms:
# A solution could be found by trying all combinations and return the best.
# Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X.
# Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key.
;See also:
* Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?
* Constructing the largest number possible by rearranging a list
| from fractions import Fraction
from math import log10
def maxnum(x):
return ''.join(str(n) for n in sorted(x, reverse=True,
key=lambda i: Fraction(i, 10**(int(log10(i))+1)-1)))
for numbers in [(1, 34, 3, 98, 9, 76, 45, 4), (54, 546, 548, 60)]:
print('Numbers: %r\n Largest integer: %15s' % (numbers, maxnum(numbers))) |
Largest number divisible by its digits | Python | Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the
(base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits.
;Example:
'''135''' is evenly divisible by '''1''', '''3''', and '''5'''.
Note that the digit zero (0) can not be in the number as integer division by zero is undefined.
The digits must all be unique so a base ten number will have at most '''9''' digits.
Feel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.)
;Stretch goal:
Do the same thing for hexadecimal.
;Related tasks:
:* gapful numbers.
:* palindromic gapful numbers.
;Also see:
:* The OEIS sequence: A115569: Lynch-Bell numbers.
| ===base 10===
Using the insights presented in the preamble to the Raku (base 10) example:
|
Largest number divisible by its digits | Python 3.7 | Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the
(base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits.
;Example:
'''135''' is evenly divisible by '''1''', '''3''', and '''5'''.
Note that the digit zero (0) can not be in the number as integer division by zero is undefined.
The digits must all be unique so a base ten number will have at most '''9''' digits.
Feel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.)
;Stretch goal:
Do the same thing for hexadecimal.
;Related tasks:
:* gapful numbers.
:* palindromic gapful numbers.
;Also see:
:* The OEIS sequence: A115569: Lynch-Bell numbers.
| '''Largest number divisible by its hex digits'''
from functools import (reduce)
from math import (gcd)
# main :: IO ()
def main():
'''First integer evenly divisible by each of its
hex digits, none of which appear more than once.
'''
# Least common multiple of digits [1..15]
# ( -> 360360 )
lcmDigits = foldl1(lcm)(
enumFromTo(1)(15)
)
allDigits = 0xfedcba987654321
# ( -> 1147797409030632360 )
upperLimit = allDigits - (allDigits % lcmDigits)
# Possible numbers
xs = enumFromThenToNext(upperLimit)(
upperLimit - lcmDigits
)(1)
print(
hex(
until(lambda x: 15 == len(set(showHex(x))))(
lambda _: next(xs)
)(next(xs))
)
) # --> 0xfedcb59726a1348
# ------------------ GENERIC FUNCTIONS -------------------
# enumFromThenToNext :: Int -> Int -> Int -> Gen [Int]
def enumFromThenToNext(m):
'''Non-finite series of integer values enumerated
from m to n with a step size defined by nxt-m.
'''
def go(m, nxt):
d = nxt - m
v = m
while True:
yield v
v = d + v
return lambda nxt: lambda n: go(m, nxt)
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: range(m, 1 + n)
# foldl1 :: (a -> a -> a) -> [a] -> a
def foldl1(f):
'''Left to right reduction of the
non-empty list xs, using the binary
operator f, with the head of xs
as the initial acccumulator value.
'''
return lambda xs: reduce(
lambda a, x: f(a)(x), xs[1:], xs[0]
) if xs else None
# lcm :: Int -> Int -> Int
def lcm(x):
'''The smallest positive integer divisible
without remainder by both x and y.
'''
return lambda y: (
0 if (0 == x or 0 == y) else abs(
y * (x // gcd(x, y))
)
)
# until :: (a -> Bool) -> (a -> a) -> a -> a
def until(p):
'''The result of repeatedly applying f until p holds.
The initial seed value is x.
'''
def go(f, x):
v = x
while not p(v):
v = f(v)
return v
return lambda f: lambda x: go(f, x)
# showHex :: Int -> String
def showHex(n):
'''Hexadecimal string representation
of an integer value.
'''
return hex(n)[2:]
# MAIN --
if __name__ == '__main__':
main() |
Largest proper divisor of n | Python | a(1) = 1; for n > 1, a(n) = '''largest''' proper divisor of n, where '''n < 101 '''.
| def lpd(n):
for i in range(n-1,0,-1):
if n%i==0: return i
return 1
for i in range(1,101):
print("{:3}".format(lpd(i)), end=i%10==0 and '\n' or '') |
Last Friday of each month | Python | Write a program or a script that returns the date of the last Fridays of each month of a given year.
The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
2012-06-29
2012-07-27
2012-08-31
2012-09-28
2012-10-26
2012-11-30
2012-12-28
;Related tasks
* [[Five weekends]]
* [[Day of the week]]
* [[Find the last Sunday of each month]]
| import calendar
def last_fridays(year):
for month in range(1, 13):
last_friday = max(week[calendar.FRIDAY]
for week in calendar.monthcalendar(year, month))
print('{:4d}-{:02d}-{:02d}'.format(year, month, last_friday)) |
Last letter-first letter | Python | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game.
For example, with "animals" as the category,
Child 1: dog
Child 2: goldfish
Child 1: hippopotamus
Child 2: snake
...
;Task:
Take the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name.
No Pokemon name is to be repeated.
audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine
nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking
sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko
tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask
Extra brownie points for dealing with the full list of 646 names.
| import psyco
nsolutions = 0
def search(sequences, ord_minc, curr_word, current_path,
current_path_len, longest_path):
global nsolutions
current_path[current_path_len] = curr_word
current_path_len += 1
if current_path_len == len(longest_path):
nsolutions += 1
elif current_path_len > len(longest_path):
nsolutions = 1
longest_path[:] = current_path[:current_path_len]
# recursive search
last_char_index = ord(curr_word[-1]) - ord_minc
if last_char_index >= 0 and last_char_index < len(sequences):
for pair in sequences[last_char_index]:
if not pair[1]:
pair[1] = True
search(sequences, ord_minc, pair[0], current_path,
current_path_len, longest_path)
pair[1] = False
def find_longest_chain(words):
ord_minc = ord(min(word[0] for word in words))
ord_maxc = ord(max(word[0] for word in words))
sequences = [[] for _ in xrange(ord_maxc - ord_minc + 1)]
for word in words:
sequences[ord(word[0]) - ord_minc].append([word, False])
current_path = [None] * len(words)
longest_path = []
# try each item as possible start
for seq in sequences:
for pair in seq:
pair[1] = True
search(sequences, ord_minc, pair[0],
current_path, 0, longest_path)
pair[1] = False
return longest_path
def main():
global nsolutions
pokemon = """audino bagon baltoy banette bidoof braviary
bronzor carracosta charmeleon cresselia croagunk darmanitan deino
emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor
heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus
ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass
petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede
scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly
tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle
whismur wingull yamask""".lower().split()
# remove duplicates
pokemon = sorted(set(pokemon))
sol = find_longest_chain(pokemon)
print "Maximum path length:", len(sol)
print "Paths of that length:", nsolutions
print "Example path of that length:"
for i in xrange(0, len(sol), 7):
print " ", " ".join(sol[i : i+7])
psyco.full()
main() |
Latin Squares in reduced form | Python from D | A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin Squares of order n. The objective of this task is to construct the set of all Latin Squares of a given order and to provide a means which given suitable values for g any element within the set may be obtained.
For a reduced Latin Square the first row is always 1 to n. The second row is all [[Permutations/Derangements]] of 1 to n starting with 2. The third row is all [[Permutations/Derangements]] of 1 to n starting with 3 which do not clash (do not have the same item in any column) with row 2. The fourth row is all [[Permutations/Derangements]] of 1 to n starting with 4 which do not clash with rows 2 or 3. Likewise continuing to the nth row.
Demonstrate by:
* displaying the four reduced Latin Squares of order 4.
* for n = 1 to 6 (or more) produce the set of reduced Latin Squares; produce a table which shows the size of the set of reduced Latin Squares and compares this value times n! times (n-1)! with the values in OEIS A002860.
| def dList(n, start):
start -= 1 # use 0 basing
a = range(n)
a[start] = a[0]
a[0] = start
a[1:] = sorted(a[1:])
first = a[1]
# rescursive closure permutes a[1:]
r = []
def recurse(last):
if (last == first):
# bottom of recursion. you get here once for each permutation.
# test if permutation is deranged.
# yes, save a copy with 1 based indexing
for j,v in enumerate(a[1:]):
if j + 1 == v:
return # no, ignore it
b = [x + 1 for x in a]
r.append(b)
return
for i in xrange(last, 0, -1):
a[i], a[last] = a[last], a[i]
recurse(last - 1)
a[i], a[last] = a[last], a[i]
recurse(n - 1)
return r
def printSquare(latin,n):
for row in latin:
print row
print
def reducedLatinSquares(n,echo):
if n <= 0:
if echo:
print []
return 0
elif n == 1:
if echo:
print [1]
return 1
rlatin = [None] * n
for i in xrange(n):
rlatin[i] = [None] * n
# first row
for j in xrange(0, n):
rlatin[0][j] = j + 1
class OuterScope:
count = 0
def recurse(i):
rows = dList(n, i)
for r in xrange(len(rows)):
rlatin[i - 1] = rows[r]
justContinue = False
k = 0
while not justContinue and k < i - 1:
for j in xrange(1, n):
if rlatin[k][j] == rlatin[i - 1][j]:
if r < len(rows) - 1:
justContinue = True
break
if i > 2:
return
k += 1
if not justContinue:
if i < n:
recurse(i + 1)
else:
OuterScope.count += 1
if echo:
printSquare(rlatin, n)
# remaining rows
recurse(2)
return OuterScope.count
def factorial(n):
if n == 0:
return 1
prod = 1
for i in xrange(2, n + 1):
prod *= i
return prod
print "The four reduced latin squares of order 4 are:\n"
reducedLatinSquares(4,True)
print "The size of the set of reduced latin squares for the following orders"
print "and hence the total number of latin squares of these orders are:\n"
for n in xrange(1, 7):
size = reducedLatinSquares(n, False)
f = factorial(n - 1)
f *= f * n * size
print "Order %d: Size %-4d x %d! x %d! => Total %d" % (n, size, n, n - 1, f) |
Law of cosines - triples | Python | The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(g) = C2
;Specific angles:
For an angle of of '''90o''' this becomes the more familiar "Pythagoras equation":
A2 + B2 = C2
For an angle of '''60o''' this becomes the less familiar equation:
A2 + B2 - AB = C2
And finally for an angle of '''120o''' this becomes the equation:
A2 + B2 + AB = C2
;Task:
* Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.
* Restrain all sides to the integers '''1..13''' inclusive.
* Show how many results there are for each of the three angles mentioned above.
* Display results on this page.
Note: Triangles with the same length sides but different order are to be treated as the same.
;Optional Extra credit:
* How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''.
;Related Task
* [[Pythagorean triples]]
;See also:
* Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video
| N = 13
def method1(N=N):
squares = [x**2 for x in range(0, N+1)]
sqrset = set(squares)
tri90, tri60, tri120 = (set() for _ in range(3))
for a in range(1, N+1):
a2 = squares[a]
for b in range(1, a + 1):
b2 = squares[b]
c2 = a2 + b2
if c2 in sqrset:
tri90.add(tuple(sorted((a, b, int(c2**0.5)))))
ab = a * b
c2 -= ab
if c2 in sqrset:
tri60.add(tuple(sorted((a, b, int(c2**0.5)))))
c2 += 2 * ab
if c2 in sqrset:
tri120.add(tuple(sorted((a, b, int(c2**0.5)))))
return sorted(tri90), sorted(tri60), sorted(tri120)
#%%
if __name__ == '__main__':
print(f'Integer triangular triples for sides 1..{N}:')
for angle, triples in zip([90, 60, 120], method1(N)):
print(f' {angle:3}° has {len(triples)} solutions:\n {triples}')
_, t60, _ = method1(10_000)
notsame = sum(1 for a, b, c in t60 if a != b or b != c)
print('Extra credit:', notsame) |
Least common multiple | Python | Compute the least common multiple (LCM) of two integers.
Given ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors.
;Example:
The least common multiple of '''12''' and '''18''' is '''36''', because:
:* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and
:* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and
:* there is no positive integer less than '''36''' that has both factors.
As a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero.
One way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''.
If you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''.
:::: \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)}
One can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''.
;Related task
:* greatest common divisor.
;See also:
* MathWorld entry: Least Common Multiple.
* Wikipedia entry: Least common multiple.
| '''Least common multiple'''
from inspect import signature
# lcm :: Int -> Int -> Int
def lcm(x):
'''The smallest positive integer divisible
without remainder by both x and y.
'''
return lambda y: 0 if 0 in (x, y) else abs(
y * (x // gcd_(x)(y))
)
# gcd_ :: Int -> Int -> Int
def gcd_(x):
'''The greatest common divisor in terms of
the divisibility preordering.
'''
def go(a, b):
return go(b, a % b) if 0 != b else a
return lambda y: go(abs(x), abs(y))
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Tests'''
print(
fTable(
__doc__ + 's of 60 and [12..20]:'
)(repr)(repr)(
lcm(60)
)(enumFromTo(12)(20))
)
pairs = [(0, 2), (2, 0), (-6, 14), (12, 18)]
print(
fTable(
'\n\n' + __doc__ + 's of ' + repr(pairs) + ':'
)(repr)(repr)(
uncurry(lcm)
)(pairs)
)
# GENERIC -------------------------------------------------
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
# uncurry :: (a -> b -> c) -> ((a, b) -> c)
def uncurry(f):
'''A function over a tuple, derived from
a vanilla or curried function.
'''
if 1 < len(signature(f).parameters):
return lambda xy: f(*xy)
else:
return lambda xy: f(xy[0])(xy[1])
# unlines :: [String] -> String
def unlines(xs):
'''A single string derived by the intercalation
of a list of strings with the newline character.
'''
return '\n'.join(xs)
# 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() |
Least common multiple | Python from Tcl | Compute the least common multiple (LCM) of two integers.
Given ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors.
;Example:
The least common multiple of '''12''' and '''18''' is '''36''', because:
:* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and
:* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and
:* there is no positive integer less than '''36''' that has both factors.
As a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero.
One way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''.
If you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''.
:::: \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)}
One can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''.
;Related task
:* greatest common divisor.
;See also:
* MathWorld entry: Least Common Multiple.
* Wikipedia entry: Least common multiple.
| >>> def lcm(p,q):
p, q = abs(p), abs(q)
m = p * q
if not m: return 0
while True:
p %= q
if not p: return m // q
q %= p
if not q: return m // p
>>> lcm(-6, 14)
42
>>> lcm(12, 18)
36
>>> lcm(2, 0)
0
>>> |
Left factorials | Python | '''Left factorials''', !n, may refer to either ''subfactorials'' or to ''factorial sums'';
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, ''subfactorials'' (also known as ''derangements'') may use any of the notations:
:::::::* !''n''`
:::::::* !''n''
:::::::* ''n''!
(It may not be visually obvious, but the last example uses an upside-down exclamation mark.)
This Rosetta Code task will be using this formula (''factorial sums'') for '''left factorial''':
::::: !n = \sum_{k=0}^{n-1} k!
:::: where
::::: !0 = 0
;Task
Display the left factorials for:
* zero through ten (inclusive)
* 20 through 110 (inclusive) by tens
Display the length (in decimal digits) of the left factorials for:
* 1,000 through 10,000 (inclusive), by thousands.
;Also see:
* The OEIS entry: A003422 left factorials
* The MathWorld entry: left factorial
* The MathWorld entry: factorial sums
* The MathWorld entry: subfactorial
;Related task:
* permutations/derangements (subfactorials)
| from itertools import islice
def lfact():
yield 0
fact, summ, n = 1, 0, 1
while 1:
fact, summ, n = fact*n, summ + fact, n + 1
yield summ
print('first 11:\n %r' % [lf for i, lf in zip(range(11), lfact())])
print('20 through 110 (inclusive) by tens:')
for lf in islice(lfact(), 20, 111, 10):
print(lf)
print('Digits in 1,000 through 10,000 (inclusive) by thousands:\n %r'
% [len(str(lf)) for lf in islice(lfact(), 1000, 10001, 1000)] ) |
Left factorials | Python from Haskell | '''Left factorials''', !n, may refer to either ''subfactorials'' or to ''factorial sums'';
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, ''subfactorials'' (also known as ''derangements'') may use any of the notations:
:::::::* !''n''`
:::::::* !''n''
:::::::* ''n''!
(It may not be visually obvious, but the last example uses an upside-down exclamation mark.)
This Rosetta Code task will be using this formula (''factorial sums'') for '''left factorial''':
::::: !n = \sum_{k=0}^{n-1} k!
:::: where
::::: !0 = 0
;Task
Display the left factorials for:
* zero through ten (inclusive)
* 20 through 110 (inclusive) by tens
Display the length (in decimal digits) of the left factorials for:
* 1,000 through 10,000 (inclusive), by thousands.
;Also see:
* The OEIS entry: A003422 left factorials
* The MathWorld entry: left factorial
* The MathWorld entry: factorial sums
* The MathWorld entry: subfactorial
;Related task:
* permutations/derangements (subfactorials)
| '''Left factorials'''
from itertools import (accumulate, chain, count, islice)
from operator import (mul, add)
# leftFact :: [Integer]
def leftFact():
'''Left factorial series defined in terms
of the factorial series.
'''
return accumulate(
chain([0], fact()), add
)
# fact :: [Integer]
def fact():
'''The factorial series.
'''
return accumulate(
chain([1], count(1)), mul
)
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Tests'''
print(
'Terms 0 thru 10 inclusive:\n %r'
% take(11)(leftFact())
)
print('\nTerms 20 thru 110 (inclusive) by tens:')
for x in takeFromThenTo(20)(30)(110)(leftFact()):
print(x)
print(
'\n\nDigit counts for terms 1k through 10k (inclusive) by k:\n %r'
% list(map(
compose(len)(str),
takeFromThenTo(1000)(2000)(10000)(
leftFact()
)
))
)
# ----------------------- GENERIC ------------------------
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Function composition.'''
return lambda f: lambda x: g(f(x))
# 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'''
return lambda xs: (
xs[0:n]
if isinstance(xs, list)
else list(islice(xs, n))
)
# takeFromThenTo :: Int -> Int -> Int -> [a] -> [a]
def takeFromThenTo(a):
'''Values drawn from a series betweens positions a and b
at intervals of size z'''
return lambda b: lambda z: lambda xs: islice(
xs, a, 1 + z, b - a
)
if __name__ == '__main__':
main() |
Levenshtein distance | Python | {{Wikipedia}}
In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character.
;Example:
The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:
::# '''k'''itten '''s'''itten (substitution of 'k' with 's')
::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i')
::# sittin sittin'''g''' (insert 'g' at the end).
''The Levenshtein distance between "'''rosettacode'''", "'''raisethysword'''" is '''8'''.
''The distance between two strings is same as that when both strings are reversed.''
;Task:
Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between "kitten" and "sitting".
;Related task:
* [[Longest common subsequence]]
| def levenshteinDistance(str1, str2):
m = len(str1)
n = len(str2)
d = [[i] for i in range(1, m + 1)] # d matrix rows
d.insert(0, list(range(0, n + 1))) # d matrix columns
for j in range(1, n + 1):
for i in range(1, m + 1):
if str1[i - 1] == str2[j - 1]: # Python (string) is 0-based
substitutionCost = 0
else:
substitutionCost = 1
d[i].insert(j, min(d[i - 1][j] + 1,
d[i][j - 1] + 1,
d[i - 1][j - 1] + substitutionCost))
return d[-1][-1]
print(levenshteinDistance("kitten","sitting"))
print(levenshteinDistance("rosettacode","raisethysword")) |
Levenshtein distance | Python 3.7 | {{Wikipedia}}
In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character.
;Example:
The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:
::# '''k'''itten '''s'''itten (substitution of 'k' with 's')
::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i')
::# sittin sittin'''g''' (insert 'g' at the end).
''The Levenshtein distance between "'''rosettacode'''", "'''raisethysword'''" is '''8'''.
''The distance between two strings is same as that when both strings are reversed.''
;Task:
Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between "kitten" and "sitting".
;Related task:
* [[Longest common subsequence]]
| '''Levenshtein distance'''
from itertools import (accumulate, chain, islice)
from functools import reduce
# levenshtein :: String -> String -> Int
def levenshtein(sa):
'''Levenshtein distance between
two strings.'''
s1 = list(sa)
# go :: [Int] -> Char -> [Int]
def go(ns, c):
n, ns1 = ns[0], ns[1:]
# gap :: Int -> (Char, Int, Int) -> Int
def gap(z, c1xy):
c1, x, y = c1xy
return min(
succ(y),
succ(z),
succ(x) if c != c1 else x
)
return scanl(gap)(succ(n))(
zip(s1, ns, ns1)
)
return lambda sb: reduce(
go, list(sb), enumFromTo(0)(len(s1))
)[-1]
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Tests'''
pairs = [
('rosettacode', 'raisethysword'),
('kitten', 'sitting'),
('saturday', 'sunday')
]
print(
tabulated(
'Levenshtein minimum edit distances:\n'
)(str)(str)(
uncurry(levenshtein)
)(concat(map(
list,
zip(pairs, map(swap, pairs))
)))
)
# GENERIC -------------------------------------------------
# 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(xxs):
'''The concatenation of all the elements in a list.'''
xs = list(chain.from_iterable(xxs))
unit = '' if isinstance(xs, str) else []
return unit if not xs else (
''.join(xs) if isinstance(xs[0], str) else xs
)
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
# scanl :: (b -> a -> b) -> b -> [a] -> [b]
def scanl(f):
'''scanl is like reduce, but returns a succession of
intermediate values, building from the left.'''
return lambda a: lambda xs: (
list(accumulate(chain([a], xs), f))
)
# swap :: (a, b) -> (b, a)
def swap(tpl):
'''The swapped components of a pair.'''
return (tpl[1], tpl[0])
# succ :: Int => Int -> Int
def succ(x):
'''The successor of a value.
For numeric types, (1 +).'''
return 1 + x
# tabulated :: String -> (a -> String) ->
# (b -> String) ->
# (a -> b) -> [a] -> String
def tabulated(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
)
)
# 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)
else list(islice(xs, n))
)
# 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]
)
# MAIN ---
if __name__ == '__main__':
main() |
Levenshtein distance/Alignment | Python | The [[Levenshtein distance]] algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used to turn a string into an other. At some point in the strings, the minus character ('-') is placed in order to signify that a character must be added at this very place. For instance, an alignment between the words 'place' and 'palace' is:
P-LACE
PALACE
;Task:
Write a function that shows the alignment of two strings for the corresponding levenshtein distance.
As an example, use the words "rosettacode" and "raisethysword".
You can either implement an algorithm, or use a dedicated library (thus showing us how it is named in your language).
| from difflib import ndiff
def levenshtein(str1, str2):
result = ""
pos, removed = 0, 0
for x in ndiff(str1, str2):
if pos<len(str1) and str1[pos] == x[2]:
pos += 1
result += x[2]
if x[0] == "-":
removed += 1
continue
else:
if removed > 0:
removed -=1
else:
result += "-"
print(result)
levenshtein("place","palace")
levenshtein("rosettacode","raisethysword") |
List rooted trees | Python | You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.
If we use a matching pair of parentheses to represent a bag, the ways are:
For 1 bag, there's one way:
() <- a bag
for 2 bags, there's one way:
(()) <- one bag in another
for 3 bags, there are two:
((())) <- 3 bags nested Russian doll style
(()()) <- 2 bags side by side, inside the third
for 4 bags, four:
(()()())
((())())
((()()))
(((())))
Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.
It's easy to see that each configuration for ''n'' bags represents a ''n''-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given ''n'' is given by OEIS A81.
;Task:
Write a program that, when given ''n'', enumerates all ways of nesting ''n'' bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.
This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.
As an example output, run 5 bags. There should be 9 ways.
| def bags(n,cache={}):
if not n: return [(0, "")]
upto = sum([bags(x) for x in range(n-1, 0, -1)], [])
return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)]
def bagchain(x, n, bb, start=0):
if not n: return [x]
out = []
for i in range(start, len(bb)):
c,s = bb[i]
if c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)
return out
# Maybe this lessens eye strain. Maybe not.
def replace_brackets(s):
depth,out = 0,[]
for c in s:
if c == '(':
out.append("([{"[depth%3])
depth += 1
else:
depth -= 1
out.append(")]}"[depth%3])
return "".join(out)
for x in bags(5): print(replace_brackets(x[1])) |
Long literals, with continuations | Python | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
''hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...''
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
''ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium''
To make computer programming languages comparable, the statement widths should be
restricted to less than '''81''' bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if ''not''
in column one.
The list ''may'' have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program ''will'' be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the ''clause length'' of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
;Task:
:* Write a computer program (by whatever name) to contain a list of the known elements.
:* The program should eventually contain a long literal of words (the elements).
:* The literal should show how one could create a long list of blank-delineated words.
:* The "final" (stored) list should only have a single blank between elements.
:* Try to use the most idiomatic approach(es) in creating the final list.
:* Use continuation if possible, and/or show alternatives (possibly using concatenation).
:* Use a program comment to explain what the continuation character is if it isn't obvious.
:* The program should contain a variable that has the date of the last update/revision.
:* The program, when run, should display with verbiage:
:::* The last update/revision date (and should be unambiguous).
:::* The number of chemical elements in the list.
:::* The name of the highest (last) element name.
Show all output here, on this page.
| """Long string literal. Requires Python 3.6+ for f-strings."""
revision = "October 13th 2020"
# String literal continuation. Notice the trailing space at the end of each
# line but the last, and the lack of commas. There is exactly one "blank"
# between each item in the list.
elements = (
"hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine "
"neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon "
"potassium calcium scandium titanium vanadium chromium manganese iron "
"cobalt nickel copper zinc gallium germanium arsenic selenium bromine "
"krypton rubidium strontium yttrium zirconium niobium molybdenum "
"technetium ruthenium rhodium palladium silver cadmium indium tin "
"antimony tellurium iodine xenon cesium barium lanthanum cerium "
"praseodymium neodymium promethium samarium europium gadolinium terbium "
"dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum "
"tungsten rhenium osmium iridium platinum gold mercury thallium lead "
"bismuth polonium astatine radon francium radium actinium thorium "
"protactinium uranium neptunium plutonium americium curium berkelium "
"californium einsteinium fermium mendelevium nobelium lawrencium "
"rutherfordium dubnium seaborgium bohrium hassium meitnerium darmstadtium "
"roentgenium copernicium nihonium flerovium moscovium livermorium "
"tennessine oganesson"
)
def report():
"""Write a summary report to stdout."""
items = elements.split()
print(f"Last revision date: {revision}")
print(f"Number of elements: {len(items)}")
print(f"Last element : {items[-1]}")
if __name__ == "__main__":
report()
|
Long year | Python 3.7 | Most years have 52 weeks, some have 53, according to ISO8601.
;Task:
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
| '''Long Year ?'''
from datetime import date
# longYear :: Year Int -> Bool
def longYear(y):
'''True if the ISO year y has 53 weeks.'''
return 52 < date(y, 12, 28).isocalendar()[1]
# --------------------------TEST---------------------------
# main :: IO ()
def main():
'''Longer (53 week) years in the range 2000-2100'''
for year in [
x for x in range(2000, 1 + 2100)
if longYear(x)
]:
print(year)
# MAIN ---
if __name__ == '__main__':
main() |
Longest common subsequence | Python | '''Introduction'''
Define a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.
The '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings.
Let ''A'' ''A''[0]... ''A''[m - 1] and ''B'' ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B.
An ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n.
The set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''.
Define a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly.
We say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''.
Define the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly.
A chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable.
A chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j].
Every Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''.
According to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.
'''Background'''
Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.
The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n''). However, this approach requires O(''m*n'') time even in the best case.
This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.
In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(''n'') growth.
A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m''). Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n'').
'''Note'''
[Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)'').
'''Legend'''
A, B are input strings of lengths m, n respectively
p is the length of the LCS
M is the set of matches (i, j) such that A[i] = B[j]
r is the magnitude of M
s is the magnitude of the alphabet S of distinct symbols in A + B
'''References'''
[Dilworth 1950] "A decomposition theorem for partially ordered sets"
by Robert P. Dilworth, published January 1950,
Annals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166]
[Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common
Subsequence Problem" by Heiko Goeman and Michael Clausen,
published 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66]
[Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences"
by Daniel S. Hirschberg, published June 1975
Communications of the ACM [Volume 18, Number 6, ''pp.'' 341-343]
[Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison"
by James W. Hunt and M. Douglas McIlroy, June 1976
Computing Science Technical Report, Bell Laboratories 41
[Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences"
by James W. Hunt and Thomas G. Szymanski, published May 1977
Communications of the ACM [Volume 20, Number 5, ''pp.'' 350-353]
[Rick 2000] "Simple and fast linear space computation of longest common subsequences"
by Claus Rick, received 17 March 2000, Information Processing Letters,
Elsevier Science [Volume 75, ''pp.'' 275-281]
'''Examples'''
The sequences "1234" and "1224533324" have an LCS of "1234":
'''1234'''
'''12'''245'''3'''332'''4'''
For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest":
'''t'''hi'''si'''sa'''test'''
'''t'''e'''s'''t'''i'''ng123'''test'''ing
In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.
For more information on this problem please see Wikipedia.
| def lcs(a, b):
# generate matrix of length of longest common subsequence for substrings of both words
lengths = [[0] * (len(b)+1) for _ in range(len(a)+1)]
for i, x in enumerate(a):
for j, y in enumerate(b):
if x == y:
lengths[i+1][j+1] = lengths[i][j] + 1
else:
lengths[i+1][j+1] = max(lengths[i+1][j], lengths[i][j+1])
# read a substring from the matrix
result = ''
j = len(b)
for i in range(1, len(a)+1):
if lengths[i][j] != lengths[i-1][j]:
result += a[i-1]
return result |
Longest common substring | Python | Write a function that returns the longest common substring of two strings.
Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing".
Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them.
Hence, the [[longest common subsequence]] between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common sub''string'' is just "test".
;References:
*Generalize Suffix Tree
*[[Ukkonen's Suffix Tree Construction]]
| s1 = "thisisatest"
s2 = "testing123testing"
len1, len2 = len(s1), len(s2)
ir, jr = 0, -1
for i1 in range(len1):
i2 = s2.find(s1[i1])
while i2 >= 0:
j1, j2 = i1, i2
while j1 < len1 and j2 < len2 and s2[j2] == s1[j1]:
if j1-i1 >= jr-ir:
ir, jr = i1, j1
j1 += 1; j2 += 1
i2 = s2.find(s1[i1], i2+1)
print (s1[ir:jr+1]) |
Longest common substring | Python from JavaScript | Write a function that returns the longest common substring of two strings.
Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing".
Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them.
Hence, the [[longest common subsequence]] between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common sub''string'' is just "test".
;References:
*Generalize Suffix Tree
*[[Ukkonen's Suffix Tree Construction]]
| '''Longest common substring'''
from itertools import accumulate, chain
from functools import reduce
# longestCommon :: String -> String -> String
def longestCommon(s1):
'''The longest common substring of
two given strings.
'''
def go(s2):
return max(intersect(
*map(lambda s: map(
concat,
concatMap(tails)(
compose(tail, list, inits)(s)
)
), [s1, s2])
), key=len)
return go
# ------------------------- TEST -------------------------
def main():
'''Test'''
print(
longestCommon(
"testing123testing"
)(
"thisisatest"
)
)
# ----------------------- 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)
# concat :: [String] -> String
def concat(xs):
'''The concatenation of all the elements
in a list or iterable.
'''
return ''.join(xs)
# 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
# inits :: [a] -> [[a]]
def inits(xs):
'''all initial segments of xs, shortest first.'''
return accumulate(chain([[]], xs), lambda a, x: a + [x])
# intersect :: [a] -> [a] -> [a]
def intersect(xs, ys):
'''The ordered intersection of xs and ys.
intersect([1,2,2,3,4])([6,4,4,2]) -> [2,2,4]
'''
s = set(ys)
return (x for x in xs if x in s)
# 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
# tail :: [a] -> [a]
# tail :: Gen [a] -> [a]
def tail(xs):
'''The elements following the head of a
(non-empty) list.
'''
return xs[1:]
# tails :: [a] -> [[a]]
def tails(xs):
'''All final segments of xs,
longest first.
'''
return [
xs[i:] for i in
range(0, 1 + len(xs))
]
# MAIN ---
main()
|
Longest increasing subsequence | Python | Calculate and show here a longest increasing subsequence of the list:
:\{3, 2, 6, 4, 5, 1\}
And of the list:
:\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\}
Note that a list may have more than one subsequence that is of the maximum length.
;Ref:
# Dynamic Programming #1: Longest Increasing Subsequence on YouTube
# An efficient solution can be based on Patience sorting.
| def longest_increasing_subsequence(X):
"""Returns the Longest Increasing Subsequence in the Given List/Array"""
N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo+hi)//2
if (X[M[mid]] < X[i]):
lo = mid+1
else:
hi = mid-1
newL = lo
P[i] = M[newL-1]
M[newL] = i
if (newL > L):
L = newL
S = []
k = M[L]
for i in range(L-1, -1, -1):
S.append(X[k])
k = P[k]
return S[::-1]
if __name__ == '__main__':
for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:
print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d))) |
Lucky and even lucky numbers | Python | Note that in the following explanation list indices are assumed to start at ''one''.
;Definition of lucky numbers
''Lucky numbers'' are positive integers that are formed by:
# Form a list of all the positive odd integers > 01, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ...
# Return the first number from the list (which is '''1''').
# (Loop begins here)
#* Note then return the second number from the list (which is '''3''').
#* Discard every third, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 57 ...
# (Expanding the loop a few more times...)
#* Note then return the third number from the list (which is '''7''').
#* Discard every 7th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 27, 31, 33, 37, 43, 45, 49, 51, 55, 57, 63, 67 ...
#* Note then return the 4th number from the list (which is '''9''').
#* Discard every 9th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 45, 49, 51, 55, 63, 67, 69, 73 ...
#* Take the 5th, i.e. '''13'''. Remove every 13th.
#* Take the 6th, i.e. '''15'''. Remove every 15th.
#* Take the 7th, i.e. '''21'''. Remove every 21th.
#* Take the 8th, i.e. '''25'''. Remove every 25th.
# (Rule for the loop)
#* Note the nth, which is m.
#* Remove every mth.
#* Increment n.
;Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above ''except for the very first step'':
# Form a list of all the positive '''even''' integers > 02, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ...
# Return the first number from the list (which is '''2''').
# (Loop begins here)
#* Note then return the second number from the list (which is '''4''').
#* Discard every 4th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52 ...
# (Expanding the loop a few more times...)
#* Note then return the third number from the list (which is '''6''').
#* Discard every 6th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 18, 20, 22, 26, 28, 34, 36, 38, 42, 44, 50, 52, 54, 58, 60 ...
#* Take the 4th, i.e. '''10'''. Remove every 10th.
#* Take the 5th, i.e. '''12'''. Remove every 12th.
# (Rule for the loop)
#* Note the nth, which is m.
#* Remove every mth.
#* Increment n.
;Task requirements
* Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers''
* Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
** missing arguments
** too many arguments
** number (or numbers) aren't legal
** misspelled argument ('''lucky''' or '''evenLucky''')
* The command line handling should:
** support mixed case handling of the (non-numeric) arguments
** support printing a particular number
** support printing a range of numbers by their index
** support printing a range of numbers by their values
* The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
+-------------------+----------------------------------------------------+
| j | Jth lucky number |
| j , lucky | Jth lucky number |
| j , evenLucky | Jth even lucky number |
| | |
| j k | Jth through Kth (inclusive) lucky numbers |
| j k lucky | Jth through Kth (inclusive) lucky numbers |
| j k evenLucky | Jth through Kth (inclusive) even lucky numbers |
| | |
| j -k | all lucky numbers in the range j --> |k| |
| j -k lucky | all lucky numbers in the range j --> |k| |
| j -k evenLucky | all even lucky numbers in the range j --> |k| |
+-------------------+----------------------------------------------------+
where |k| is the absolute value of k
Demonstrate the program by:
* showing the first twenty ''lucky'' numbers
* showing the first twenty ''even lucky'' numbers
* showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive)
* showing all ''even lucky'' numbers in the same range as above
* showing the 10,000th ''lucky'' number (extra credit)
* showing the 10,000th ''even lucky'' number (extra credit)
;See also:
* This task is related to the [[Sieve of Eratosthenes]] task.
* OEIS Wiki Lucky numbers.
* Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
* Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
* Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| from itertools import islice
import sys, re
class ArgumentError(Exception):
pass
def arghandler(argstring):
match_obj = re.match( r"""(?mx)
(?:
(?P<SINGLE>
(?: ^ (?P<SINGLEL> \d+ ) (?: | \s , \s lucky ) \s* $ )
|(?: ^ (?P<SINGLEE> \d+ ) (?: | \s , \s evenLucky ) \s* $ )
)
|(?P<KTH>
(?: ^ (?P<KTHL> \d+ \s \d+ ) (?: | \s lucky ) \s* $ )
|(?: ^ (?P<KTHE> \d+ \s \d+ ) (?: | \s evenLucky ) \s* $ )
)
|(?P<RANGE>
(?: ^ (?P<RANGEL> \d+ \s -\d+ ) (?: | \s lucky ) \s* $ )
|(?: ^ (?P<RANGEE> \d+ \s -\d+ ) (?: | \s evenLucky ) \s* $ )
)
)""", argstring)
if match_obj:
# Retrieve group(s) by name
SINGLEL = match_obj.group('SINGLEL')
SINGLEE = match_obj.group('SINGLEE')
KTHL = match_obj.group('KTHL')
KTHE = match_obj.group('KTHE')
RANGEL = match_obj.group('RANGEL')
RANGEE = match_obj.group('RANGEE')
if SINGLEL:
j = int(SINGLEL)
assert 0 < j < 10001, "Argument out of range"
print("Single %i'th lucky number:" % j, end=' ')
print( list(islice(lgen(), j-1, j))[0] )
elif SINGLEE:
j = int(SINGLEE)
assert 0 < j < 10001, "Argument out of range"
print("Single %i'th even lucky number:" % j, end=' ')
print( list(islice(lgen(even=True), j-1, j))[0] )
elif KTHL:
j, k = [int(num) for num in KTHL.split()]
assert 0 < j < 10001, "first argument out of range"
assert 0 < k < 10001 and k > j, "second argument out of range"
print("List of %i ... %i lucky numbers:" % (j, k), end=' ')
for n, luck in enumerate(lgen(), 1):
if n > k: break
if n >=j: print(luck, end = ', ')
print('')
elif KTHE:
j, k = [int(num) for num in KTHE.split()]
assert 0 < j < 10001, "first argument out of range"
assert 0 < k < 10001 and k > j, "second argument out of range"
print("List of %i ... %i even lucky numbers:" % (j, k), end=' ')
for n, luck in enumerate(lgen(even=True), 1):
if n > k: break
if n >=j: print(luck, end = ', ')
print('')
elif RANGEL:
j, k = [int(num) for num in RANGEL.split()]
assert 0 < j < 10001, "first argument out of range"
assert 0 < -k < 10001 and -k > j, "second argument out of range"
k = -k
print("List of lucky numbers in the range %i ... %i :" % (j, k), end=' ')
for n in lgen():
if n > k: break
if n >=j: print(n, end = ', ')
print('')
elif RANGEE:
j, k = [int(num) for num in RANGEE.split()]
assert 0 < j < 10001, "first argument out of range"
assert 0 < -k < 10001 and -k > j, "second argument out of range"
k = -k
print("List of even lucky numbers in the range %i ... %i :" % (j, k), end=' ')
for n in lgen(even=True):
if n > k: break
if n >=j: print(n, end = ', ')
print('')
else:
raise ArgumentError('''
Error Parsing Arguments!
Expected Arguments of the form (where j and k are integers):
j # Jth lucky number
j , lucky # Jth lucky number
j , evenLucky # Jth even lucky number
#
j k # Jth through Kth (inclusive) lucky numbers
j k lucky # Jth through Kth (inclusive) lucky numbers
j k evenLucky # Jth through Kth (inclusive) even lucky numbers
#
j -k # all lucky numbers in the range j --? |k|
j -k lucky # all lucky numbers in the range j --? |k|
j -k evenLucky # all even lucky numbers in the range j --? |k|
''')
if __name__ == '__main__':
arghandler(' '.join(sys.argv[1:])) |
Lychrel numbers | Python | ::# Take an integer n, greater than zero.
::# Form the next n of its series by reversing the digits of the current n and adding the result to the current n.
::# Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.
The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.
;Example:
If n0 = 12 we get
12
12 + 21 = 33, a palindrome!
And if n0 = 55 we get
55
55 + 55 = 110
110 + 011 = 121, a palindrome!
Notice that the check for a palindrome happens ''after'' an addition.
Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome.
These numbers that do not end in a palindrome are called '''Lychrel numbers'''.
For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.
;Seed and related Lychrel numbers:
Any integer produced in the sequence of a Lychrel number is also a Lychrel number.
In general, any sequence from one Lychrel number ''might'' converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:
196
196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
...
689
689 + 986 = 1675
1675 + 5761 = 7436
...
So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196.
Because of this we can further split the Lychrel numbers into true '''Seed''' Lychrel number candidates, and '''Related''' numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.
;Task:
* Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).
* Print the number of seed Lychrels found; the actual seed Lychrels; and just the ''number'' of relateds found.
* Print any seed Lychrel or related number that is itself a palindrome.
Show all output here.
;References:
* What's special about 196? Numberphile video.
* A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).
* Status of the 196 conjecture? Mathoverflow.
| from __future__ import print_function
def add_reverse(num, max_iter=1000):
i, nums = 0, {num}
while True:
i, num = i+1, num + reverse_int(num)
nums.add(num)
if reverse_int(num) == num or i >= max_iter:
break
return nums
#@functools.lru_cache(maxsize=2**20)
def reverse_int(num):
return int(str(num)[::-1])
def split_roots_from_relateds(roots_and_relateds):
roots = roots_and_relateds[::]
i = 1
while i < len(roots):
this = roots[i]
if any(this.intersection(prev) for prev in roots[:i]):
del roots[i]
else:
i += 1
root = [min(each_set) for each_set in roots]
related = [min(each_set) for each_set in roots_and_relateds]
related = [n for n in related if n not in root]
return root, related
def find_lychrel(maxn, max_reversions):
'Lychrel number generator'
series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]
roots_and_relateds = [s for s in series if len(s) > max_reversions]
return split_roots_from_relateds(roots_and_relateds)
if __name__ == '__main__':
maxn, reversion_limit = 10000, 500
print("Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds"
% (maxn, reversion_limit))
lychrel, l_related = find_lychrel(maxn, reversion_limit)
print(' Number of Lychrel numbers:', len(lychrel))
print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel))
print(' Number of Lychrel related:', len(l_related))
#print(' Lychrel related:', ', '.join(str(n) for n in l_related))
pals = [x for x in lychrel + l_related if x == reverse_int(x)]
print(' Number of Lychrel palindromes:', len(pals))
print(' Lychrel palindromes:', ', '.join(str(n) for n in pals)) |
Mad Libs | Python | {{wikipedia}}
Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
;Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
went for a walk in the park.
found a . decided to take it home.
Given this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).
| import re
# Optional Python 2.x compatibility
#try: input = raw_input
#except: pass
template = '''<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.'''
def madlibs(template):
print('The story template is:\n' + template)
fields = sorted(set( re.findall('<[^>]+>', template) ))
values = input('\nInput a comma-separated list of words to replace the following items'
'\n %s: ' % ','.join(fields)).split(',')
story = template
for f,v in zip(fields, values):
story = story.replace(f, v)
print('\nThe story becomes:\n\n' + story)
madlibs(template) |
Magic 8-ball | Python | Create Magic 8-Ball.
See details at: Magic 8-Ball.
| import random
s = ('It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely',
'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good',
'Signs point to yes', 'Yes', 'Reply hazy, try again', 'Ask again later',
'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again',
"Don't bet on it", 'My reply is no', 'My sources say no', 'Outlook not so good',
'Very doubtful')
q_and_a = {}
while True:
question = input('Ask your question:')
if len(question) == 0: break
if question in q_and_a:
print('Your question has already been answered')
else:
answer = random.choice(s)
q_and_a[question] = answer
print(answer) |
Magic constant | Python | A magic square is a square grid containing consecutive integers from 1 to N2, arranged so that every row, column and diagonal adds up to the same number. That number is a constant. There is no way to create a valid N x N magic square that does not sum to the associated constant.
;EG
A 3 x 3 magic square ''always'' sums to 15.
+---+---+---+
| 2 | 7 | 6 |
+---+---+---+
| 9 | 5 | 1 |
+---+---+---+
| 4 | 3 | 8 |
+---+---+---+
A 4 x 4 magic square ''always'' sums to 34.
Traditionally, the sequence leaves off terms for n = 0 and n = 1 as the magic squares of order 0 and 1 are trivial; and a term for n = 2 because it is impossible to form a magic square of order 2.
;Task
* Starting at order 3, show the first 20 magic constants.
* Show the 1000th magic constant. (Order 1003)
* Find and show the order of the smallest N x N magic square whose constant is greater than 101 through 1010.
;Stretch
* Find and show the order of the smallest N x N magic square whose constant is greater than 1011 through 1020.
;See also
* Wikipedia: Magic constant
* OEIS: A006003 (Similar sequence, though it includes terms for 0, 1 & 2.)
* [[Magic squares of odd order]]
* [[Magic squares of singly even order]]
* [[Magic squares of doubly even order]]
| #!/usr/bin/python
def a(n):
n += 2
return n*(n**2 + 1)/2
def inv_a(x):
k = 0
while k*(k**2+1)/2+2 < x:
k+=1
return k
if __name__ == '__main__':
print("The first 20 magic constants are:");
for n in range(1, 20):
print(int(a(n)), end = " ");
print("\nThe 1,000th magic constant is:",int(a(1000)));
for e in range(1, 20):
print(f'10^{e}: {inv_a(10**e)}'); |
Magic squares of doubly even order | Python | A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant'').
A magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12''').
This means that the subsquares also have an even size, which plays a role in the construction.
{| class="wikitable" style="float:right;border: 2px solid black; background:lightblue; color:black; margin-left:auto;margin-right:auto;text-align:center;width:22em;height:15em;table-layout:fixed;font-size:100%"
|-
|'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8'''
|-
|'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16'''
|-
|'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41'''
|-
|'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33'''
|-
|'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25'''
|-
|'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17'''
|-
|'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56'''
|-
|'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64'''
|}
;Task
Create a magic square of '''8 x 8'''.
;Related tasks
* [[Magic squares of odd order]]
* [[Magic squares of singly even order]]
;See also:
* Doubly Even Magic Squares (1728.org)
| def MagicSquareDoublyEven(order):
sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]
n1 = order/4
for r in range(n1):
r1 = sq[r][n1:-n1]
r2 = sq[order -r - 1][n1:-n1]
r1.reverse()
r2.reverse()
sq[r][n1:-n1] = r2
sq[order -r - 1][n1:-n1] = r1
for r in range(n1, order-n1):
r1 = sq[r][:n1]
r2 = sq[order -r - 1][order-n1:]
r1.reverse()
r2.reverse()
sq[r][:n1] = r2
sq[order -r - 1][order-n1:] = r1
return sq
def printsq(s):
n = len(s)
bl = len(str(n**2))+1
for i in range(n):
print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] )
print "\nMagic constant = %d"%sum(s[0])
printsq(MagicSquareDoublyEven(8))
|
Magic squares of doubly even order | Python 3.7 | A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant'').
A magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12''').
This means that the subsquares also have an even size, which plays a role in the construction.
{| class="wikitable" style="float:right;border: 2px solid black; background:lightblue; color:black; margin-left:auto;margin-right:auto;text-align:center;width:22em;height:15em;table-layout:fixed;font-size:100%"
|-
|'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8'''
|-
|'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16'''
|-
|'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41'''
|-
|'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33'''
|-
|'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25'''
|-
|'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17'''
|-
|'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56'''
|-
|'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64'''
|}
;Task
Create a magic square of '''8 x 8'''.
;Related tasks
* [[Magic squares of odd order]]
* [[Magic squares of singly even order]]
;See also:
* Doubly Even Magic Squares (1728.org)
| '''Magic squares of doubly even order'''
from itertools import chain, repeat
from functools import reduce
from math import log
# doublyEvenMagicSquare :: Int -> [[Int]]
def doublyEvenMagicSquare(n):
'''Magic square of order n'''
# magic :: Int -> [Bool]
def magic(n):
'''Truth-table series'''
if 0 < n:
xs = magic(n - 1)
return xs + [not x for x in xs]
else:
return [True]
sqr = n * n
power = log(sqr, 2)
scale = replicate(n / 4)
return chunksOf(n)([
succ(i) if bln else sqr - i for i, bln in
enumerate(magic(power) if isInteger(power) else (
flatten(scale(
map(scale, chunksOf(4)(magic(4)))
))
))
])
# TEST ----------------------------------------------------
# main :: IO()
def main():
'''Tests'''
order = 8
magicSquare = doublyEvenMagicSquare(order)
print(
'Row sums: ',
[sum(xs) for xs in magicSquare],
'\nCol sums:',
[sum(xs) for xs in transpose(magicSquare)],
'\n1st diagonal sum:',
sum(magicSquare[i][i] for i in range(0, order)),
'\n2nd diagonal sum:',
sum(magicSquare[i][(order - 1) - i] for i in range(0, order)),
'\n'
)
print(wikiTable({
'class': 'wikitable',
'style': cssFromDict({
'text-align': 'center',
'color': '#605B4B',
'border': '2px solid silver'
}),
'colwidth': '3em'
})(magicSquare))
# GENERIC -------------------------------------------------
# chunksOf :: Int -> [a] -> [[a]]
def chunksOf(n):
'''A series of lists of length n,
subdividing the contents of xs.
Where the length of xs is not evenly divible
the final list will be shorter than n.'''
return lambda xs: reduce(
lambda a, i: a + [xs[i:n + i]],
range(0, len(xs), n), []
) if 0 < n else []
# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
'''Concatenated list over which a function has been mapped.
The list monad can be derived by using a function f which
wraps its output a in list
(using an empty list to represent computational failure).'''
return lambda xs: list(
chain.from_iterable(
map(f, xs)
)
)
# cssFromDict :: Dict -> String
def cssFromDict(dct):
'''CSS string serialized from key values in a Dictionary.'''
return reduce(
lambda a, k: a + k + ':' + dct[k] + '; ', dct.keys(), ''
)
# flatten :: NestedList a -> [a]
def flatten(x):
'''A list of atoms resulting from fully flattening
an arbitrarily nested list.'''
return concatMap(flatten)(x) if isinstance(x, list) else [x]
# isInteger :: Num -> Bool
def isInteger(n):
'''Divisible by one without remainder ?'''
return 0 == (n - int(n))
# replicate :: Int -> a -> [a]
def replicate(n):
'''A list of length n in which every element
has the value x.'''
return lambda x: list(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))
)
# 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
# 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'
if __name__ == '__main__':
main() |
Magic squares of odd order | Python | A magic square is an '''NxN''' square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both long (main) diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant'').
The numbers are usually (but not always) the first '''N'''2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''.
{| class="wikitable" style="float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%"
|-
| '''8''' || '''1''' || '''6'''
|-
| '''3''' || '''5''' || '''7'''
|-
| '''4''' || '''9''' || '''2'''
|}
;Task
For any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here.
Optionally, show the ''magic number''.
You should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''.
; Related tasks
* [[Magic squares of singly even order]]
* [[Magic squares of doubly even order]]
; See also:
* MathWorld(tm) entry: Magic_square
* Odd Magic Squares (1728.org)
| >>> def magic(n):
for row in range(1, n + 1):
print(' '.join('%*i' % (len(str(n**2)), cell) for cell in
(n * ((row + col - 1 + n // 2) % n) +
((row + 2 * col - 2) % n) + 1
for col in range(1, n + 1))))
print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2))
>>> for n in (5, 3, 7):
print('\nOrder %i\n=======' % n)
magic(n)
Order 5
=======
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
All sum to magic number 65
Order 3
=======
8 1 6
3 5 7
4 9 2
All sum to magic number 15
Order 7
=======
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
All sum to magic number 175
>>> |
Magic squares of odd order | Python 3.7 | A magic square is an '''NxN''' square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both long (main) diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant'').
The numbers are usually (but not always) the first '''N'''2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''.
{| class="wikitable" style="float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%"
|-
| '''8''' || '''1''' || '''6'''
|-
| '''3''' || '''5''' || '''7'''
|-
| '''4''' || '''9''' || '''2'''
|}
;Task
For any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here.
Optionally, show the ''magic number''.
You should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''.
; Related tasks
* [[Magic squares of singly even order]]
* [[Magic squares of doubly even order]]
; See also:
* MathWorld(tm) entry: Magic_square
* Odd Magic Squares (1728.org)
| '''Magic squares of odd order N'''
from itertools import cycle, islice, repeat
from functools import reduce
# magicSquare :: Int -> [[Int]]
def magicSquare(n):
'''Magic square of odd order n.'''
return applyN(2)(
compose(transposed)(cycled)
)(plainSquare(n)) if 1 == n % 2 else []
# plainSquare :: Int -> [[Int]]
def plainSquare(n):
'''The sequence of integers from 1 to N^2,
subdivided into N sub-lists of equal length,
forming N rows, each of N integers.
'''
return chunksOf(n)(
enumFromTo(1)(n ** 2)
)
# cycled :: [[Int]] -> [[Int]]
def cycled(rows):
'''A table in which the rows are
rotated by descending deltas.
'''
n = len(rows)
d = n // 2
return list(map(
lambda d, xs: take(n)(
drop(n - d)(cycle(xs))
),
enumFromThenTo(d)(d - 1)(-d),
rows
))
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Magic squares of order 3, 5, 7'''
print(
fTable(__doc__ + ':')(lambda x: '\n' + repr(x))(
showSquare
)(magicSquare)([3, 5, 7])
)
# GENERIC -------------------------------------------------
# applyN :: Int -> (a -> a) -> a -> a
def applyN(n):
'''n applications of f.
(Church numeral n).
'''
def go(f):
return lambda x: reduce(
lambda a, g: g(a), repeat(f, n), x
)
return lambda f: go(f)
# chunksOf :: Int -> [a] -> [[a]]
def chunksOf(n):
'''A series of lists of length n,
subdividing the contents of xs.
Where the length of xs is not evenly divible,
the final list will be shorter than n.'''
return lambda xs: reduce(
lambda a, i: a + [xs[i:n + i]],
range(0, len(xs), n), []
) if 0 < n else []
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
# 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)
# enumFromThenTo :: Int -> Int -> Int -> [Int]
def enumFromThenTo(m):
'''Integer values enumerated from m to n
with a step defined by nxt-m.
'''
def go(nxt, n):
d = nxt - m
return range(m, n - 1 if d < 0 else 1 + n, d)
return lambda nxt: lambda n: list(go(nxt, n))
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + 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))
)
# transposed :: Matrix a -> Matrix a
def transposed(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
# 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
)
# indented :: Int -> String -> String
def indented(n):
'''String indented by n multiples
of four spaces
'''
return lambda s: (n * 4 * ' ') + s
# showSquare :: [[Int]] -> String
def showSquare(rows):
'''Lines representing rows of lists.'''
w = 1 + len(str(reduce(max, map(max, rows), 0)))
return '\n' + '\n'.join(
map(
lambda row: indented(1)(''.join(
map(lambda x: str(x).rjust(w, ' '), row)
)),
rows
)
)
# MAIN ---
if __name__ == '__main__':
main() |
Magic squares of singly even order | Python from Lua | A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant'').
A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.
;Task
Create a magic square of 6 x 6.
; Related tasks
* [[Magic squares of odd order]]
* [[Magic squares of doubly even order]]
; See also
* Singly Even Magic Squares (1728.org)
| import math
from sys import stdout
LOG_10 = 2.302585092994
# build odd magic square
def build_oms(s):
if s % 2 == 0:
s += 1
q = [[0 for j in range(s)] for i in range(s)]
p = 1
i = s // 2
j = 0
while p <= (s * s):
q[i][j] = p
ti = i + 1
if ti >= s: ti = 0
tj = j - 1
if tj < 0: tj = s - 1
if q[ti][tj] != 0:
ti = i
tj = j + 1
i = ti
j = tj
p = p + 1
return q, s
# build singly even magic square
def build_sems(s):
if s % 2 == 1:
s += 1
while s % 4 == 0:
s += 2
q = [[0 for j in range(s)] for i in range(s)]
z = s // 2
b = z * z
c = 2 * b
d = 3 * b
o = build_oms(z)
for j in range(0, z):
for i in range(0, z):
a = o[0][i][j]
q[i][j] = a
q[i + z][j + z] = a + b
q[i + z][j] = a + c
q[i][j + z] = a + d
lc = z // 2
rc = lc
for j in range(0, z):
for i in range(0, s):
if i < lc or i > s - rc or (i == lc and j == lc):
if not (i == 0 and j == lc):
t = q[i][j]
q[i][j] = q[i][j + z]
q[i][j + z] = t
return q, s
def format_sqr(s, l):
for i in range(0, l - len(s)):
s = "0" + s
return s + " "
def display(q):
s = q[1]
print(" - {0} x {1}\n".format(s, s))
k = 1 + math.floor(math.log(s * s) / LOG_10)
for j in range(0, s):
for i in range(0, s):
stdout.write(format_sqr("{0}".format(q[0][i][j]), k))
print()
print("Magic sum: {0}\n".format(s * ((s * s) + 1) // 2))
stdout.write("Singly Even Magic Square")
display(build_sems(6))
|
Map range | Python | Given two ranges:
:::* [a_1,a_2] and
:::* [b_1,b_2];
:::* then a value s in range [a_1,a_2]
:::* is linearly mapped to a value t in range [b_1,b_2]
where:
:::* t = b_1 + {(s - a_1)(b_2 - b_1) \over (a_2 - a_1)}
;Task:
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
;Extra credit:
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| >>> def maprange( a, b, s):
(a1, a2), (b1, b2) = a, b
return b1 + ((s - a1) * (b2 - b1) / (a2 - a1))
>>> for s in range(11):
print("%2g maps to %g" % (s, maprange( (0, 10), (-1, 0), s)))
0 maps to -1
1 maps to -0.9
2 maps to -0.8
3 maps to -0.7
4 maps to -0.6
5 maps to -0.5
6 maps to -0.4
7 maps to -0.3
8 maps to -0.2
9 maps to -0.1
10 maps to 0 |
Matrix digital rain | Python | Implement the Matrix Digital Rain visual effect from the movie "The Matrix" as described in Wikipedia.
Provided is a reference implementation in Common Lisp to be run in a terminal.
| import curses
import random
import time
"""
Based on C ncurses version
http://rosettacode.org/wiki/Matrix_Digital_Rain#NCURSES_version
"""
"""
Time between row updates in seconds
Controls the speed of the digital rain effect.
"""
ROW_DELAY=.0001
def get_rand_in_range(min, max):
return random.randrange(min,max+1)
try:
# Characters to randomly appear in the rain sequence.
chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
total_chars = len(chars)
stdscr = curses.initscr()
curses.noecho()
curses.curs_set(False)
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
stdscr.attron(curses.color_pair(1))
max_x = curses.COLS - 1
max_y = curses.LINES - 1
# Create arrays of columns based on screen width.
# Array containing the current row of each column.
columns_row = []
# Array containing the active status of each column.
# A column draws characters on a row when active.
columns_active = []
for i in range(max_x+1):
columns_row.append(-1)
columns_active.append(0)
while(True):
for i in range(max_x):
if columns_row[i] == -1:
# If a column is at the top row, pick a
# random starting row and active status.
columns_row[i] = get_rand_in_range(0, max_y)
columns_active[i] = get_rand_in_range(0, 1)
# Loop through columns and draw characters on rows
for i in range(max_x):
if columns_active[i] == 1:
# Draw a random character at this column's current row.
char_index = get_rand_in_range(0, total_chars-1)
#mvprintw(columns_row[i], i, "%c", chars[char_index])
stdscr.addstr(columns_row[i], i, chars[char_index])
else:
# Draw an empty character if the column is inactive.
#mvprintw(columns_row[i], i, " ");
stdscr.addstr(columns_row[i], i, " ");
columns_row[i]+=1
# When a column reaches the bottom row, reset to top.
if columns_row[i] >= max_y:
columns_row[i] = -1
# Randomly alternate the column's active status.
if get_rand_in_range(0, 1000) == 0:
if columns_active[i] == 0:
columns_active[i] = 1
else:
columns_active[i] = 0
time.sleep(ROW_DELAY)
stdscr.refresh()
except KeyboardInterrupt as err:
curses.endwin()
|
Maximum triangle path sum | Python | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You can compute the total of the numbers you have seen in such walk,
in this case it's 205.
Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.
;Task:
Find the maximum total in the triangle below:
55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93
Such numbers can be included in the solution code, or read from a "triangle.txt" file.
This task is derived from the Euler Problem #18.
| '''Maximum triangle path sum'''
from functools import (reduce)
# maxPathSum :: [[Int]] -> Int
def maxPathSum(rows):
'''The maximum total among all possible
paths from the top to the bottom row.
'''
return reduce(
lambda xs, ys: [
a + max(b, c) for (a, b, c)
in zip(ys, xs, xs[1:])
],
reversed(rows[:-1]), rows[-1]
)[0]
# ------------------------- TEST -------------------------
print(
maxPathSum([
[55],
[94, 48],
[95, 30, 96],
[77, 71, 26, 67],
[97, 13, 76, 38, 45],
[7, 36, 79, 16, 37, 68],
[48, 7, 9, 18, 70, 26, 6],
[18, 72, 79, 46, 59, 79, 29, 90],
[20, 76, 87, 11, 32, 7, 7, 49, 18],
[27, 83, 58, 35, 71, 11, 25, 57, 29, 85],
[14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],
[2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23],
[92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42],
[56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72],
[44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],
[85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52],
[6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15],
[27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]
])
) |
Mayan calendar | Python 3.6 | The ancient Maya people had two somewhat distinct calendar systems.
In somewhat simplified terms, one is a cyclical calendar known as '''The Calendar Round''',
that meshes several sacred and civil cycles; the other is an offset calendar
known as '''The Long Count''', similar in many ways to the Gregorian calendar.
'''The Calendar Round'''
'''The Calendar Round''' has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle.
'''The Tzolk'in'''
The sacred cycle in the Mayan calendar round was called the '''Tzolk'in'''. The '''Tzolk'in''' has a cycle of 20 day names:
Imix'
Ik'
Ak'bal
K'an
Chikchan
Kimi
Manik'
Lamat
Muluk
Ok
Chuwen
Eb
Ben
Hix
Men
K'ib'
Kaban
Etz'nab'
Kawak
Ajaw
Intermeshed with the named days, the '''Tzolk'in''' has a cycle of 13 numbered days; 1
through 13. Every day has both a number and a name that repeat in a 260 day cycle.
For example:
1 Imix'
2 Ik'
3 Ak'bal
...
11 Chuwen
12 Eb
13 Ben
1 Hix
2 Men
3 K'ib'
... and so on.
'''The Haab''''
The Mayan civil calendar is called the '''Haab''''. This calendar has 365 days per
year, and is sometimes called the 'vague year.' It is substantially the same as
our year, but does not make leap year adjustments, so over long periods of time,
gets out of synchronization with the seasons. It consists of 18 months with 20 days each,
and the end of the year, a special month of only 5 days, giving a total of 365.
The 5 days of the month of '''Wayeb'''' (the last month), are usually considered to be
a time of bad luck.
Each month in the '''Haab'''' has a name. The Mayan names for the civil months are:
Pop
Wo'
Sip
Sotz'
Sek
Xul
Yaxk'in
Mol
Ch'en
Yax
Sak'
Keh
Mak
K'ank'in
Muwan
Pax
K'ayab
Kumk'u
Wayeb' (Short, "unlucky" month)
The months function very much like ours do. That is, for any given month we
count through all the days of that month, and then move on to the next month.
Normally, the day '''1 Pop''' is considered the first day of the civil year, just as '''1 January'''
is the first day of our year. In 2019, '''1 Pop''' falls on '''April 2nd'''. But,
because of the leap year in 2020, '''1 Pop''' falls on '''April 1st''' in the years 2020-2023.
The only really unusual aspect of the '''Haab'''' calendar is that, although there are
20 (or 5) days in each month, the last day of the month is not called
the 20th (5th). Instead, the last day of the month is referred to as the
'seating,' or 'putting in place,' of the next month. (Much like how in our
culture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In
the language of the ancient Maya, the word for seating was '''chum''', So you might
have:
...
18 Pop (18th day of the first month)
19 Pop (19th day of the first month)
Chum Wo' (20th day of the first month)
1 Wo' (1st day of the second month)
... and so on.
Dates for any particular day are a combination of the '''Tzolk'in''' sacred date,
and '''Haab'''' civil date. When put together we get the '''"Calendar Round."'''
'''Calendar Round''' dates always have two numbers and two names, and they are
always written in the same order:
(1) the day number in the '''Tzolk'in'''
(2) the day name in the '''Tzolk'in'''
(3) the day of the month in the '''Haab''''
(4) the month name in the '''Haab''''
A calendar round is a repeating cycle with a period of just short of 52
Gregorian calendar years. To be precise: it is 52 x 365 days. (No leap days)
'''Lords of the Night'''
A third cycle of nine days honored the nine '''Lords of the Night'''; nine deities
that were associated with each day in turn. The names of the nine deities are
lost; they are now commonly referred to as '''G1''' through '''G9'''. The Lord of the Night
may or may not be included in a Mayan date, if it is, it is typically
just the appropriate '''G(''x'')''' at the end.
'''The Long Count'''
Mayans had a separate independent way of measuring time that did not run in
cycles. (At least, not on normal human scales.) Instead, much like our yearly
calendar, each day just gets a little further from the starting point. For the
ancient Maya, the starting point was the 'creation date' of the current world.
This date corresponds to our date of August 11, 3114 B.C. Dates are calculated
by measuring how many days have transpired since this starting date; This is
called '''"The Long Count."''' Rather than just an absolute count of days, the long
count is broken up into unit blocks, much like our calendar has months, years,
decades and centuries.
The basic unit is a '''k'in''' - one day.
A 20 day month is a '''winal'''.
18 '''winal''' (360 days) is a '''tun''' - sometimes referred to as a short year.
20 short years ('''tun''') is a '''k'atun'''
20 '''k'atun''' is a '''bak'tun'''
There are longer units too:
'''Piktun''' == 20 '''Bak'tun''' (8,000 short years)
'''Kalabtun''' == 20 '''Piktun''' (160,000 short years)
'''Kinchiltun''' == 20 '''Kalabtun''' (3,200,000 short years)
For the most part, the Maya only used the blocks of time up to the '''bak'tun'''. One
'''bak'tun''' is around 394 years, much more than a human life span, so that was all
they usually needed to describe dates in this era, or this world. It is worth
noting, the two calendars working together allow much more accurate and reliable
notation for dates than is available in many other calendar systems; mostly due
to the pragmatic choice to make the calendar simply track days, rather than
trying to make it align with seasons and/or try to conflate it with the notion
of time.
'''Mayan Date correlations'''
There is some controversy over finding a correlation point between the Gregorian
and Mayan calendars. The Gregorian calendar is full of jumps and skips to keep
the calendar aligned with the seasons so is much more difficult to work with.
The most commonly used correlation
factor is The '''GMT: 584283'''. Julian 584283 is a day count corresponding '''Mon, Aug 11, 3114 BCE'''
in the Gregorian calendar, and the final day in the last Mayan long count
cycle: 13.0.0.0.0 which is referred to as "the day of creation" in the Mayan
calendar. There is nothing in known Mayan writing or history that suggests that
a long count "cycle" resets ''every'' 13 '''bak'tun'''. Judging by their other practices,
it would make much more sense for it to reset at 20, if at all.
The reason there was much interest at all, outside historical scholars, in
the Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri,
Dec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy
theorists to predict a cataclysmic "end-of-the-world" scenario.
'''Excerpts taken from, and recommended reading:'''
*''From the website of the Foundation for the Advancement of Meso-America Studies, Inc.'' Pitts, Mark. The complete Writing in Maya Glyphs Book 2 - Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19. http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf
*wikipedia: Maya calendar
*wikipedia: Mesoamerican Long Count calendar
'''The Task:'''
Write a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. ''If desired, support other correlations.''
Using the GMT correlation, the following Gregorian and Mayan dates are equivalent:
'''Dec 21, 2012''' (Gregorian)
'''4 Ajaw 3 K'ank'in G9''' (Calendar round)
'''13.0.0.0.0''' (Long count)
Support looking up dates for at least 50 years before and after the Mayan Long Count '''13 bak'tun''' rollover: ''Dec 21, 2012''. ''(Will require taking into account Gregorian leap days.)''
Show the output here, on this page, for ''at least'' the following dates:
''(Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.)''
2004-06-19
2012-12-18
2012-12-21
2019-01-19
2019-03-27
2020-02-29
2020-03-01
| import datetime
def g2m(date, gtm_correlation=True):
"""
Translates Gregorian date into Mayan date, see
https://rosettacode.org/wiki/Mayan_calendar
Input arguments:
date: string date in ISO-8601 format: YYYY-MM-DD
gtm_correlation: GTM correlation to apply if True, Astronomical correlation otherwise (optional, True by default)
Output arguments:
long_date: Mayan date in Long Count system as string
round_date: Mayan date in Calendar Round system as string
"""
# define some parameters and names
correlation = 584283 if gtm_correlation else 584285
long_count_days = [144000, 7200, 360, 20, 1]
tzolkin_months = ['Imix’', 'Ik’', 'Ak’bal', 'K’an', 'Chikchan', 'Kimi', 'Manik’', 'Lamat', 'Muluk', 'Ok', 'Chuwen',
'Eb', 'Ben', 'Hix', 'Men', 'K’ib’', 'Kaban', 'Etz’nab’', 'Kawak', 'Ajaw'] # tzolk'in
haad_months = ['Pop', 'Wo’', 'Sip', 'Sotz’', 'Sek', 'Xul', 'Yaxk’in', 'Mol', 'Ch’en', 'Yax', 'Sak’', 'Keh', 'Mak',
'K’ank’in', 'Muwan', 'Pax', 'K’ayab', 'Kumk’u', 'Wayeb’'] # haab'
gregorian_days = datetime.datetime.strptime(date, '%Y-%m-%d').toordinal()
julian_days = gregorian_days + 1721425
# 1. calculate long count date
long_date = list()
remainder = julian_days - correlation
for days in long_count_days:
result, remainder = divmod(remainder, days)
long_date.append(int(result))
long_date = '.'.join(['{:02d}'.format(d) for d in long_date])
# 2. calculate round calendar date
tzolkin_month = (julian_days + 16) % 20
tzolkin_day = ((julian_days + 5) % 13) + 1
haab_month = int(((julian_days + 65) % 365) / 20)
haab_day = ((julian_days + 65) % 365) % 20
haab_day = haab_day if haab_day else 'Chum'
lord_number = (julian_days - correlation) % 9
lord_number = lord_number if lord_number else 9
round_date = f'{tzolkin_day} {tzolkin_months[tzolkin_month]} {haab_day} {haad_months[haab_month]} G{lord_number}'
return long_date, round_date
if __name__ == '__main__':
dates = ['2004-06-19', '2012-12-18', '2012-12-21', '2019-01-19', '2019-03-27', '2020-02-29', '2020-03-01']
for date in dates:
long, round = g2m(date)
print(date, long, round)
|
McNuggets problem | Python | From Wikipedia:
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number of McDonald's Chicken McNuggets in any number of boxes.
In the United Kingdom, the original boxes (prior to the introduction of
the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.
;Task:
Calculate (from 0 up to a limit of 100) the largest non-McNuggets
number (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n''
where ''x'', ''y'' and ''z'' are natural numbers).
| >>> from itertools import product
>>> nuggets = set(range(101))
>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):
nuggets.discard(6*s + 9*n + 20*t)
>>> max(nuggets)
43
>>> |
McNuggets problem | Python from FSharp | From Wikipedia:
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number of McDonald's Chicken McNuggets in any number of boxes.
In the United Kingdom, the original boxes (prior to the introduction of
the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.
;Task:
Calculate (from 0 up to a limit of 100) the largest non-McNuggets
number (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n''
where ''x'', ''y'' and ''z'' are natural numbers).
| #Wherein I observe that Set Comprehension is not intrinsically dysfunctional. Nigel Galloway: October 28th., 2018
n = {n for x in range(0,101,20) for y in range(x,101,9) for n in range(y,101,6)}
g = {n for n in range(101)}
print(max(g.difference(n)))
|
McNuggets problem | Python 3.7 | From Wikipedia:
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number of McDonald's Chicken McNuggets in any number of boxes.
In the United Kingdom, the original boxes (prior to the introduction of
the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.
;Task:
Calculate (from 0 up to a limit of 100) the largest non-McNuggets
number (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n''
where ''x'', ''y'' and ''z'' are natural numbers).
| '''mcNuggets list monad'''
from itertools import (chain, dropwhile)
# mcNuggetsByListMonad :: Int -> Set Int
def mcNuggetsByListMonad(limit):
'''McNugget numbers up to limit.'''
box = size(limit)
return set(
bind(
box(6)
)(lambda x: bind(
box(9)
)(lambda y: bind(
box(20)
)(lambda z: (
lambda v=sum([x, y, z]): (
[] if v > limit else [v]
)
)())))
)
# Which, for comparison, is equivalent to:
# mcNuggetsByComprehension :: Int -> Set Int
def mcNuggetsByComprehension(limit):
'''McNuggets numbers up to limit'''
box = size(limit)
return {
v for v in (
sum([x, y, z])
for x in box(6)
for y in box(9)
for z in box(20)
) if v <= limit
}
# size :: Int -> Int -> [Int]
def size(limit):
'''Multiples of n up to limit.'''
return lambda n: enumFromThenTo(0)(n)(limit)
# -------------------------- TEST --------------------------
def main():
'''List monad and set comprehension - parallel routes'''
def test(limit):
def go(nuggets):
ys = list(dropwhile(
lambda x: x in nuggets,
enumFromThenTo(limit)(limit - 1)(1)
))
return str(ys[0]) if ys else (
'No unreachable targets in this range.'
)
return lambda nuggets: go(nuggets)
def fName(f):
return f.__name__
limit = 100
print(
fTable(main.__doc__ + ':\n')(fName)(test(limit))(
lambda f: f(limit)
)([mcNuggetsByListMonad, mcNuggetsByComprehension])
)
# ------------------------ GENERIC -------------------------
# bind (>>=) :: [a] -> (a -> [b]) -> [b]
def bind(xs):
'''List monad injection operator.
Two computations sequentially composed,
with any value produced by the first
passed as an argument to the second.
'''
return lambda f: chain.from_iterable(
map(f, xs)
)
# enumFromThenTo :: Int -> Int -> Int -> [Int]
def enumFromThenTo(m):
'''Integer values enumerated from m to n
with a step defined by nxt-m.
'''
def go(nxt, n):
d = nxt - m
return range(m, n - 1 if d < 0 else 1 + n, d)
return lambda nxt: lambda n: go(nxt, n)
# ------------------------ 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 gox(xShow):
def gofx(fxShow):
def gof(f):
def goxs(xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
def arrowed(x, y):
return y.rjust(w, ' ') + ' -> ' + fxShow(f(x))
return s + '\n' + '\n'.join(
map(arrowed, xs, ys)
)
return goxs
return gof
return gofx
return gox
# MAIN ---
if __name__ == '__main__':
main() |
Meissel–Mertens constant | Python from FreeBASIC | Calculate Meissel-Mertens constant up to a precision your language can handle.
;Motivation:
Analogous to Euler's constant, which is important in determining the sum of reciprocal natural numbers, Meissel-Mertens' constant is important in calculating the sum of reciprocal primes.
;Example:
We consider the finite sum of reciprocal natural numbers:
''1 + 1/2 + 1/3 + 1/4 + 1/5 ... 1/n''
this sum can be well approximated with:
''log(n) + E''
where ''E'' denotes Euler's constant: 0.57721...
''log(n)'' denotes the natural logarithm of ''n''.
Now consider the finite sum of reciprocal primes:
''1/2 + 1/3 + 1/5 + 1/7 + 1/11 ... 1/p''
this sum can be well approximated with:
''log( log(p) ) + M''
where ''M'' denotes Meissel-Mertens constant: 0.26149...
;See:
:* Details in the Wikipedia article: Meissel-Mertens constant
| #!/usr/bin/python
from math import log
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
Euler = 0.57721566490153286
m = 0
for x in range(2, 10_000_000):
if isPrime(x):
m += log(1-(1/x)) + (1/x)
print("MM =", Euler + m) |
Memory layout of a data structure | Python | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
__________________________________________
1 2 3 4 5 6 7 8 9 10 11 12 13
14 15 16 17 18 19 20 21 22 23 24 25
_________________
1 2 3 4 5
6 7 8 9
25 pin 9 pin
1 - PG Protective ground
2 - TD Transmitted data 3
3 - RD Received data 2
4 - RTS Request to send 7
5 - CTS Clear to send 8
6 - DSR Data set ready 6
7 - SG Signal ground 5
8 - CD Carrier detect 1
9 - + voltage (testing)
10 - - voltage (testing)
11 -
12 - SCD Secondary CD
13 - SCS Secondary CTS
14 - STD Secondary TD
15 - TC Transmit clock
16 - SRD Secondary RD
17 - RC Receiver clock
18 -
19 - SRS Secondary RTS
20 - DTR Data terminal ready 4
21 - SQD Signal quality detector
22 - RI Ring indicator 9
23 - DRS Data rate select
24 - XTC External clock
25 -
| from ctypes import Structure, c_int
rs232_9pin = "_0 CD RD TD DTR SG DSR RTS CTS RI".split()
rs232_25pin = ( "_0 PG TD RD RTS CTS DSR SG CD pos neg"
"_11 SCD SCS STD TC SRD RC"
"_18 SRS DTR SQD RI DRS XTC" ).split()
class RS232_9pin(Structure):
_fields_ = [(__, c_int, 1) for __ in rs232_9pin]
class RS232_25pin(Structure):
_fields_ = [(__, c_int, 1) for __ in rs232_25pin] |
Metallic ratios | Python | Many people have heard of the '''Golden ratio''', phi ('''ph'''). Phi is just one of a series
of related ratios that are referred to as the "'''Metallic ratios'''".
The '''Golden ratio''' was discovered and named by ancient civilizations as it was
thought to be the most pure and beautiful (like Gold). The '''Silver ratio''' was was
also known to the early Greeks, though was not named so until later as a nod to
the '''Golden ratio''' to which it is closely related. The series has been extended to
encompass all of the related ratios and was given the general name '''Metallic ratios''' (or ''Metallic means'').
''Somewhat incongruously as the original Golden ratio referred to the adjective "golden" rather than the metal "gold".''
'''Metallic ratios''' are the real roots of the general form equation:
x2 - bx - 1 = 0
where the integer '''b''' determines which specific one it is.
Using the quadratic equation:
( -b +- (b2 - 4ac) ) / 2a = x
Substitute in (from the top equation) '''1''' for '''a''', '''-1''' for '''c''', and recognising that -b is negated we get:
( b +- (b2 + 4) ) ) / 2 = x
We only want the real root:
( b + (b2 + 4) ) ) / 2 = x
When we set '''b''' to '''1''', we get an irrational number: the '''Golden ratio'''.
( 1 + (12 + 4) ) / 2 = (1 + 5) / 2 = ~1.618033989...
With '''b''' set to '''2''', we get a different irrational number: the '''Silver ratio'''.
( 2 + (22 + 4) ) / 2 = (2 + 8) / 2 = ~2.414213562...
When the ratio '''b''' is '''3''', it is commonly referred to as the '''Bronze''' ratio, '''4''' and '''5'''
are sometimes called the '''Copper''' and '''Nickel''' ratios, though they aren't as
standard. After that there isn't really any attempt at standardized names. They
are given names here on this page, but consider the names fanciful rather than
canonical.
Note that technically, '''b''' can be '''0''' for a "smaller" ratio than the '''Golden ratio'''.
We will refer to it here as the '''Platinum ratio''', though it is kind-of a
degenerate case.
'''Metallic ratios''' where '''b''' > '''0''' are also defined by the irrational continued fractions:
[b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...]
So, The first ten '''Metallic ratios''' are:
:::::: {| class="wikitable" style="text-align: center;"
|+ Metallic ratios
!Name!!'''b'''!!Equation!!Value!!Continued fraction!!OEIS link
|-
|Platinum||0||(0 + 4) / 2|| 1||-||-
|-
|Golden||1||(1 + 5) / 2|| 1.618033988749895...||[1;1,1,1,1,1,1,1,1,1,1...]||[[OEIS:A001622]]
|-
|Silver||2||(2 + 8) / 2|| 2.414213562373095...||[2;2,2,2,2,2,2,2,2,2,2...]||[[OEIS:A014176]]
|-
|Bronze||3||(3 + 13) / 2|| 3.302775637731995...||[3;3,3,3,3,3,3,3,3,3,3...]||[[OEIS:A098316]]
|-
|Copper||4||(4 + 20) / 2|| 4.23606797749979...||[4;4,4,4,4,4,4,4,4,4,4...]||[[OEIS:A098317]]
|-
|Nickel||5||(5 + 29) / 2|| 5.192582403567252...||[5;5,5,5,5,5,5,5,5,5,5...]||[[OEIS:A098318]]
|-
|Aluminum||6||(6 + 40) / 2|| 6.16227766016838...||[6;6,6,6,6,6,6,6,6,6,6...]||[[OEIS:A176398]]
|-
|Iron||7||(7 + 53) / 2|| 7.140054944640259...||[7;7,7,7,7,7,7,7,7,7,7...]||[[OEIS:A176439]]
|-
|Tin||8||(8 + 68) / 2|| 8.123105625617661...||[8;8,8,8,8,8,8,8,8,8,8...]||[[OEIS:A176458]]
|-
|Lead||9||(9 + 85) / 2|| 9.109772228646444...||[9;9,9,9,9,9,9,9,9,9,9...]||[[OEIS:A176522]]
|}
There are other ways to find the '''Metallic ratios'''; one, (the focus of this task)
is through '''successive approximations of Lucas sequences'''.
A traditional '''Lucas sequence''' is of the form:
x''n'' = P * x''n-1'' - Q * x''n-2''
and starts with the first 2 values '''0, 1'''.
For our purposes in this task, to find the metallic ratios we'll use the form:
x''n'' = b * x''n-1'' + x''n-2''
( '''P''' is set to '''b''' and '''Q''' is set to '''-1'''. ) To avoid "divide by zero" issues we'll start the sequence with the first two terms '''1, 1'''. The initial starting value has very little effect on the final ratio or convergence rate. ''Perhaps it would be more accurate to call it a Lucas-like sequence.''
At any rate, when '''b = 1''' we get:
x''n'' = x''n-1'' + x''n-2''
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...
more commonly known as the Fibonacci sequence.
When '''b = 2''':
x''n'' = 2 * x''n-1'' + x''n-2''
1, 1, 3, 7, 17, 41, 99, 239, 577, 1393...
And so on.
To find the ratio by successive approximations, divide the ('''n+1''')th term by the
'''n'''th. As '''n''' grows larger, the ratio will approach the '''b''' metallic ratio.
For '''b = 1''' (Fibonacci sequence):
1/1 = 1
2/1 = 2
3/2 = 1.5
5/3 = 1.666667
8/5 = 1.6
13/8 = 1.625
21/13 = 1.615385
34/21 = 1.619048
55/34 = 1.617647
89/55 = 1.618182
etc.
It converges, but pretty slowly. In fact, the '''Golden ratio''' has the slowest
possible convergence for any irrational number.
;Task
For each of the first '''10 Metallic ratios'''; '''b''' = '''0''' through '''9''':
* Generate the corresponding "Lucas" sequence.
* Show here, on this page, at least the first '''15''' elements of the "Lucas" sequence.
* Using successive approximations, calculate the value of the ratio accurate to '''32''' decimal places.
* Show the '''value''' of the '''approximation''' at the required accuracy.
* Show the '''value''' of '''n''' when the approximation reaches the required accuracy (How many iterations did it take?).
Optional, stretch goal - Show the '''value''' and number of iterations '''n''', to approximate the '''Golden ratio''' to '''256''' decimal places.
You may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change.
;See also
* Wikipedia: Metallic mean
* Wikipedia: Lucas sequence
| from itertools import count, islice
from _pydecimal import getcontext, Decimal
def metallic_ratio(b):
m, n = 1, 1
while True:
yield m, n
m, n = m*b + n, m
def stable(b, prec):
def to_decimal(b):
for m,n in metallic_ratio(b):
yield Decimal(m)/Decimal(n)
getcontext().prec = prec
last = 0
for i,x in zip(count(), to_decimal(b)):
if x == last:
print(f'after {i} iterations:\n\t{x}')
break
last = x
for b in range(4):
coefs = [n for _,n in islice(metallic_ratio(b), 15)]
print(f'\nb = {b}: {coefs}')
stable(b, 32)
print(f'\nb = 1 with 256 digits:')
stable(1, 256) |
Metaprogramming | Python | {{omit from|BBC BASIC}}
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation.
For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
| Metaprogramming is frowned on in Python and considered un-pythonic. The only widely known example of metaprogramming in Python was an implementation of a goto (and comefrom) keyword done as an [http://entrian.com/goto/ April-fools joke].
Another more recent library that shows it can be done in Python is [https://github.com/lihaoyi/macropy MacroPy].
|
Metronome | Python | The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used.
However, the playing of the sounds should not interfere with the timing of the metronome.
The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities.
If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
| #lang Python
import time
def main(bpm = 72, bpb = 4):
sleep = 60.0 / bpm
counter = 0
while True:
counter += 1
if counter % bpb:
print 'tick'
else:
print 'TICK'
time.sleep(sleep)
main()
|
Mian-Chowla sequence | Python | The Mian-Chowla sequence is an integer sequence defined recursively.
Mian-Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B2 sequences.
The sequence starts with:
::a1 = 1
then for n > 1, an is the smallest positive integer such that every pairwise sum
::ai + aj
is distinct, for all i and j less than or equal to n.
;The Task:
:* Find and display, here, on this page the first 30 terms of the Mian-Chowla sequence.
:* Find and display, here, on this page the 91st through 100th terms of the Mian-Chowla sequence.
Demonstrating working through the first few terms longhand:
::a1 = 1
::1 + 1 = 2
Speculatively try a2 = 2
::1 + 1 = 2
::1 + 2 = 3
::2 + 2 = 4
There are no repeated sums so '''2''' is the next number in the sequence.
Speculatively try a3 = 3
::1 + 1 = 2
::1 + 2 = 3
::1 + 3 = 4
::2 + 2 = 4
::2 + 3 = 5
::3 + 3 = 6
Sum of '''4''' is repeated so '''3''' is rejected.
Speculatively try a3 = 4
::1 + 1 = 2
::1 + 2 = 3
::1 + 4 = 5
::2 + 2 = 4
::2 + 4 = 6
::4 + 4 = 8
There are no repeated sums so '''4''' is the next number in the sequence.
And so on...
;See also:
:* OEIS:A005282 Mian-Chowla sequence
| from itertools import count, islice, chain
import time
def mian_chowla():
mc = [1]
yield mc[-1]
psums = set([2])
newsums = set([])
for trial in count(2):
for n in chain(mc, [trial]):
sum = n + trial
if sum in psums:
newsums.clear()
break
newsums.add(sum)
else:
psums |= newsums
newsums.clear()
mc.append(trial)
yield trial
def pretty(p, t, s, f):
print(p, t, " ".join(str(n) for n in (islice(mian_chowla(), s, f))))
if __name__ == '__main__':
st = time.time()
ts = "of the Mian-Chowla sequence are:\n"
pretty("The first 30 terms", ts, 0, 30)
pretty("\nTerms 91 to 100", ts, 90, 100)
print("\nComputation time was", (time.time()-st) * 1000, "ms") |
Mian-Chowla sequence | Python 3.7 | The Mian-Chowla sequence is an integer sequence defined recursively.
Mian-Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B2 sequences.
The sequence starts with:
::a1 = 1
then for n > 1, an is the smallest positive integer such that every pairwise sum
::ai + aj
is distinct, for all i and j less than or equal to n.
;The Task:
:* Find and display, here, on this page the first 30 terms of the Mian-Chowla sequence.
:* Find and display, here, on this page the 91st through 100th terms of the Mian-Chowla sequence.
Demonstrating working through the first few terms longhand:
::a1 = 1
::1 + 1 = 2
Speculatively try a2 = 2
::1 + 1 = 2
::1 + 2 = 3
::2 + 2 = 4
There are no repeated sums so '''2''' is the next number in the sequence.
Speculatively try a3 = 3
::1 + 1 = 2
::1 + 2 = 3
::1 + 3 = 4
::2 + 2 = 4
::2 + 3 = 5
::3 + 3 = 6
Sum of '''4''' is repeated so '''3''' is rejected.
Speculatively try a3 = 4
::1 + 1 = 2
::1 + 2 = 3
::1 + 4 = 5
::2 + 2 = 4
::2 + 4 = 6
::4 + 4 = 8
There are no repeated sums so '''4''' is the next number in the sequence.
And so on...
;See also:
:* OEIS:A005282 Mian-Chowla sequence
| '''Mian-Chowla series'''
from itertools import (islice)
from time import time
# mianChowlas :: Gen [Int]
def mianChowlas():
'''Mian-Chowla series - Generator constructor
'''
mcs = [1]
sumSet = set([2])
x = 1
while True:
yield x
(sumSet, mcs, x) = nextMC(sumSet, mcs, x)
# nextMC :: (Set Int, [Int], Int) -> (Set Int, [Int], Int)
def nextMC(setSums, mcs, n):
'''(Set of sums, series so far, current term) ->
(updated sum set, updated series, next term)
'''
def valid(x):
for m in mcs:
if x + m in setSums:
return False
return True
x = until(valid)(succ)(n)
setSums.update(
[x + y for y in mcs] + [2 * x]
)
return (setSums, mcs + [x], x)
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Tests'''
start = time()
genMianChowlas = mianChowlas()
print(
'First 30 terms of the Mian-Chowla series:\n',
take(30)(genMianChowlas)
)
drop(60)(genMianChowlas)
print(
'\n\nTerms 91 to 100 of the Mian-Chowla series:\n',
take(10)(genMianChowlas),
'\n'
)
print(
'(Computation time c. ' + str(round(
1000 * (time() - start)
)) + ' ms)'
)
# GENERIC -------------------------------------------------
# drop :: Int -> [a] -> [a]
# drop :: Int -> String -> String
def drop(n):
'''The suffix of xs after the
first n elements, or [] if n > length xs'''
def go(xs):
if isinstance(xs, list):
return xs[n:]
else:
take(n)(xs)
return xs
return lambda xs: go(xs)
# succ :: Int -> Int
def succ(x):
'''The successor of a numeric value (1 +)'''
return 1 + x
# 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)
else list(islice(xs, n))
)
# until :: (a -> Bool) -> (a -> a) -> a -> a
def until(p):
'''The result of applying f until p holds.
The initial seed value is x.'''
def go(f, x):
v = x
while not p(v):
v = f(v)
return v
return lambda f: lambda x: go(f, x)
if __name__ == '__main__':
main() |
Middle three digits | Python | Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| >>> def middle_three_digits(i):
s = str(abs(i))
length = len(s)
assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits"
mid = length // 2
return s[mid-1:mid+2]
>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
>>> failing = [1, 2, -1, -10, 2002, -2002, 0]
>>> for x in passing + failing:
try:
answer = middle_three_digits(x)
except AssertionError as error:
answer = error
print("middle_three_digits(%s) returned: %r" % (x, answer))
middle_three_digits(123) returned: '123'
middle_three_digits(12345) returned: '234'
middle_three_digits(1234567) returned: '345'
middle_three_digits(987654321) returned: '654'
middle_three_digits(10001) returned: '000'
middle_three_digits(-10001) returned: '000'
middle_three_digits(-123) returned: '123'
middle_three_digits(-100) returned: '100'
middle_three_digits(100) returned: '100'
middle_three_digits(-12345) returned: '234'
middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)
>>> |
Middle three digits | Python from Haskell | Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| '''Middle 3 digits'''
# mid3digits :: Int -> Either String String
def mid3digits(n):
'''Either the middle three digits,
or an explanatory string.'''
m = abs(n)
s = str(m)
return Left('Less than 3 digits') if (100 > m) else (
Left('Even digit count') if even(len(s)) else Right(
s[(len(s) - 3) // 2:][0:3]
)
)
# TEST ----------------------------------------------------
def main():
'''Test'''
def bracketed(x):
return '(' + str(x) + ')'
print(
tabulated('Middle three digits, where defined:\n')(str)(
either(bracketed)(str)
)(mid3digits)([
123, 12345, 1234567, 987654321, 10001, -10001, -123,
-100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0
])
)
# 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}
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''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'])
# even :: Int -> Bool
def even(x):
'''Is x even ?'''
return 0 == x % 2
# tabulated :: String -> (b -> String) -> (a -> b) -> [a] -> String
def tabulated(s):
'''Heading -> x display function -> fx display function ->
f -> value list -> tabular string.'''
def go(xShow, fxShow, f, xs):
w = max(map(compose(len)(str), 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
)
if __name__ == '__main__':
main() |
Mind boggling card trick | Python | Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics the steps shown in the video.
; 1. Cards.
# Create a common deck of cards of 52 cards (which are half red, half black).
# Give the pack a good shuffle.
; 2. Deal from the shuffled deck, you'll be creating three piles.
# Assemble the cards face down.
## Turn up the ''top card'' and hold it in your hand.
### if the card is black, then add the ''next'' card (unseen) to the "black" pile.
### If the card is red, then add the ''next'' card (unseen) to the "red" pile.
## Add the ''top card'' that you're holding to the '''discard''' pile. (You might optionally show these discarded cards to get an idea of the randomness).
# Repeat the above for the rest of the shuffled deck.
; 3. Choose a random number (call it '''X''') that will be used to swap cards from the "red" and "black" piles.
# Randomly choose '''X''' cards from the "red" pile (unseen), let's call this the "red" bunch.
# Randomly choose '''X''' cards from the "black" pile (unseen), let's call this the "black" bunch.
# Put the "red" bunch into the "black" pile.
# Put the "black" bunch into the "red" pile.
# (The above two steps complete the swap of '''X''' cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows).
; 4. Order from randomness?
# Verify (or not) the mathematician's assertion that:
'''The number of black cards in the "black" pile equals the number of red cards in the "red" pile.'''
(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)
Show output on this page.
| import random
## 1. Cards
n = 52
Black, Red = 'Black', 'Red'
blacks = [Black] * (n // 2)
reds = [Red] * (n // 2)
pack = blacks + reds
# Give the pack a good shuffle.
random.shuffle(pack)
## 2. Deal from the randomised pack into three stacks
black_stack, red_stack, discard = [], [], []
while pack:
top = pack.pop()
if top == Black:
black_stack.append(pack.pop())
else:
red_stack.append(pack.pop())
discard.append(top)
print('(Discards:', ' '.join(d[0] for d in discard), ')\n')
## 3. Swap the same, random, number of cards between the two stacks.
# We can't swap more than the number of cards in a stack.
max_swaps = min(len(black_stack), len(red_stack))
# Randomly choose the number of cards to swap.
swap_count = random.randint(0, max_swaps)
print('Swapping', swap_count)
# Randomly choose that number of cards out of each stack to swap.
def random_partition(stack, count):
"Partition the stack into 'count' randomly selected members and the rest"
sample = random.sample(stack, count)
rest = stack[::]
for card in sample:
rest.remove(card)
return rest, sample
black_stack, black_swap = random_partition(black_stack, swap_count)
red_stack, red_swap = random_partition(red_stack, swap_count)
# Perform the swap.
black_stack += red_swap
red_stack += black_swap
## 4. Order from randomness?
if black_stack.count(Black) == red_stack.count(Red):
print('Yeha! The mathematicians assertion is correct.')
else:
print('Whoops - The mathematicians (or my card manipulations) are flakey') |
Minimal steps down to 1 | Python | Given:
* A starting, positive integer (greater than one), N.
* A selection of possible integer perfect divisors, D.
* And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
* Divided by any member of D if it is perfectly divided by D, (remainder zero).
* OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
* Find the ''minimum'' number of ''steps'' to reach 1.
* Show '''one''' way of getting fron N to 1 in those minimum steps.
;Examples:
No divisors, D. a single subtractor of 1.
:Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
:N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
:N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
:N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
;Task:
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
:1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
:2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
:3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
:4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
;Optional stretch goal:
:2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
;Reference:
* Learn Dynamic Programming (Memoization & Tabulation) Video of similar task.
| from functools import lru_cache
#%%
DIVS = {2, 3}
SUBS = {1}
class Minrec():
"Recursive, memoised minimised steps to 1"
def __init__(self, divs=DIVS, subs=SUBS):
self.divs, self.subs = divs, subs
@lru_cache(maxsize=None)
def _minrec(self, n):
"Recursive, memoised"
if n == 1:
return 0, ['=1']
possibles = {}
for d in self.divs:
if n % d == 0:
possibles[f'/{d}=>{n // d:2}'] = self._minrec(n // d)
for s in self.subs:
if n > s:
possibles[f'-{s}=>{n - s:2}'] = self._minrec(n - s)
thiskind, (count, otherkinds) = min(possibles.items(), key=lambda x: x[1])
ret = 1 + count, [thiskind] + otherkinds
return ret
def __call__(self, n):
"Recursive, memoised"
ans = self._minrec(n)[1][:-1]
return len(ans), ans
if __name__ == '__main__':
for DIVS, SUBS in [({2, 3}, {1}), ({2, 3}, {2})]:
minrec = Minrec(DIVS, SUBS)
print('\nMINIMUM STEPS TO 1: Recursive algorithm')
print(' Possible divisors: ', DIVS)
print(' Possible decrements:', SUBS)
for n in range(1, 11):
steps, how = minrec(n)
print(f' minrec({n:2}) in {steps:2} by: ', ', '.join(how))
upto = 2000
print(f'\n Those numbers up to {upto} that take the maximum, "minimal steps down to 1":')
stepn = sorted((minrec(n)[0], n) for n in range(upto, 0, -1))
mx = stepn[-1][0]
ans = [x[1] for x in stepn if x[0] == mx]
print(' Taking', mx, f'steps is/are the {len(ans)} numbers:',
', '.join(str(n) for n in sorted(ans)))
#print(minrec._minrec.cache_info())
print() |
Minimum multiple of m where digital sum equals m | Python | Generate the sequence '''a(n)''' when each element is the minimum integer multiple '''m''' such that the digit sum of '''n''' times '''m''' is equal to '''n'''.
;Task
* Find the first 40 elements of the sequence.
;Stretch
* Find the next 30 elements of the sequence.
;See also
;* OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| '''A131382'''
from itertools import count, islice
# a131382 :: [Int]
def a131382():
'''An infinite series of the terms of A131382'''
return (
elemIndex(x)(
productDigitSums(x)
) for x in count(1)
)
# productDigitSums :: Int -> [Int]
def productDigitSums(n):
'''The sum of the decimal digits of n'''
return (digitSum(n * x) for x in count(0))
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''First 40 terms of A131382'''
print(
table(10)([
str(x) for x in islice(
a131382(),
40
)
])
)
# ----------------------- GENERIC ------------------------
# chunksOf :: Int -> [a] -> [[a]]
def chunksOf(n):
'''A series of lists of length n, subdividing the
contents of xs. Where the length of xs is not evenly
divisible, the final list will be shorter than n.
'''
def go(xs):
return (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
# digitSum :: Int -> Int
def digitSum(n):
'''The sum of the digital digits of n.
'''
return sum(int(x) for x in list(str(n)))
# elemIndex :: a -> [a] -> (None | Int)
def elemIndex(x):
'''Just the first index of x in xs,
or None if no elements match.
'''
def go(xs):
try:
return next(
i for i, v in enumerate(xs) if x == v
)
except StopIteration:
return None
return go
# table :: Int -> [String] -> String
def table(n):
'''A list of strings formatted as
right-justified rows of n columns.
'''
def go(xs):
w = len(xs[-1])
return '\n'.join(
' '.join(row) for row in chunksOf(n)([
s.rjust(w, ' ') for s in xs
])
)
return go
# MAIN ---
if __name__ == '__main__':
main() |
Minimum positive multiple in base 10 using only 0 and 1 | Python from Kotlin | Every positive integer has infinitely many base-10 multiples that only use the digits '''0''' and '''1'''. The goal of this task is to find and display the '''minimum''' multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "'''B10'''".
;Task:
Write a routine to find the B10 of a given integer.
E.G.
'''n''' '''B10''' '''n''' x '''multiplier'''
1 1 ( 1 x 1 )
2 10 ( 2 x 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the '''B10''' value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find '''B10''' for:
1998, 2079, 2251, 2277
Stretch goal; find '''B10''' for:
2439, 2997, 4878
There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you ''do'' use magic numbers, explain briefly why and what they do for your implementation.
;See also:
:* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
:* How to find Minimum Positive Multiple in base 10 using only 0 and 1
| def getA004290(n):
if n < 2:
return 1
arr = [[0 for _ in range(n)] for _ in range(n)]
arr[0][0] = 1
arr[0][1] = 1
m = 0
while True:
m += 1
if arr[m - 1][-10 ** m % n] == 1:
break
arr[m][0] = 1
for k in range(1, n):
arr[m][k] = max([arr[m - 1][k], arr[m - 1][k - 10 ** m % n]])
r = 10 ** m
k = -r % n
for j in range((m - 1), 0, -1):
if arr[j - 1][k] == 0:
r = r + 10 ** j
k = (k - 10 ** j) % n
if k == 1:
r += 1
return r
for n in [i for i in range(1, 11)] + \
[i for i in range(95, 106)] + \
[297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878]:
result = getA004290(n)
print(f"A004290({n}) = {result} = {n} * {result // n})")
|
Minkowski question-mark function | Python from Go | The '''Minkowski question-mark function''' converts the continued fraction representation {{math|[a0; a1, a2, a3, ...]}} of a number into a binary decimal representation in which the integer part {{math|a0}} is unchanged and the {{math|a1, a2, ...}} become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place of the first zero.
Thus, {{math|?}}(31/7) = 71/16 because 31/7 has the continued fraction representation {{math|[4;2,3]}} giving the binary expansion {{math|4 + 0.01112}}.
Among its interesting properties is that it maps roots of quadratic equations, which have repeating continued fractions, to rational numbers, which have repeating binary digits.
The question-mark function is continuous and monotonically increasing, so it has an inverse.
* Produce a function for {{math|?(x)}}. Be careful: rational numbers have two possible continued fraction representations:
:::* {{math|[a0;a1,... an-1,an]}} and
:::* {{math|[a0;a1,... an-1,an-1,1]}}
* Choose one of the above that will give a binary expansion ending with a '''1'''.
* Produce the inverse function {{math|?-1(x)}}
* Verify that {{math|?(ph)}} = 5/3, where {{math|ph}} is the Greek golden ratio.
* Verify that {{math|?-1(-5/9)}} = (13 - 7)/6
* Verify that the two functions are inverses of each other by showing that {{math|?-1(?(x))}}={{math|x}} and {{math|?(?-1(y))}}={{math|y}} for {{math|x, y}} of your choice
Don't worry about precision error in the last few digits.
;See also:
* Wikipedia entry: Minkowski's question-mark function
| import math
MAXITER = 151
def minkowski(x):
if x > 1 or x < 0:
return math.floor(x) + minkowski(x - math.floor(x))
p = int(x)
q = 1
r = p + 1
s = 1
d = 1.0
y = float(p)
while True:
d /= 2
if y + d == y:
break
m = p + r
if m < 0 or p < 0:
break
n = q + s
if n < 0:
break
if x < m / n:
r = m
s = n
else:
y += d
p = m
q = n
return y + d
def minkowski_inv(x):
if x > 1 or x < 0:
return math.floor(x) + minkowski_inv(x - math.floor(x))
if x == 1 or x == 0:
return x
cont_frac = [0]
current = 0
count = 1
i = 0
while True:
x *= 2
if current == 0:
if x < 1:
count += 1
else:
cont_frac.append(0)
cont_frac[i] = count
i += 1
count = 1
current = 1
x -= 1
else:
if x > 1:
count += 1
x -= 1
else:
cont_frac.append(0)
cont_frac[i] = count
i += 1
count = 1
current = 0
if x == math.floor(x):
cont_frac[i] = count
break
if i == MAXITER:
break
ret = 1.0 / cont_frac[i]
for j in range(i - 1, -1, -1):
ret = cont_frac[j] + 1.0 / ret
return 1.0 / ret
if __name__ == "__main__":
print(
"{:19.16f} {:19.16f}".format(
minkowski(0.5 * (1 + math.sqrt(5))),
5.0 / 3.0,
)
)
print(
"{:19.16f} {:19.16f}".format(
minkowski_inv(-5.0 / 9.0),
(math.sqrt(13) - 7) / 6,
)
)
print(
"{:19.16f} {:19.16f}".format(
minkowski(minkowski_inv(0.718281828)),
minkowski_inv(minkowski(0.1213141516171819)),
)
)
|
Modified random distribution | Python | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating random numbers to the probability given by function modifier:
while True:
random1 = rgen()
random2 = rgen()
if random2 < modifier(random1):
answer = random1
break
endif
endwhile
;Task:
* Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:
modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5)
* Create a generator of random numbers with probabilities modified by the above function.
* Generate >= 10,000 random numbers subject to the probability modification.
* Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.
Show your output here, on this page.
| import random
from typing import List, Callable, Optional
def modifier(x: float) -> float:
"""
V-shaped, modifier(x) goes from 1 at 0 to 0 at 0.5 then back to 1 at 1.0 .
Parameters
----------
x : float
Number, 0.0 .. 1.0 .
Returns
-------
float
Target probability for generating x; between 0 and 1.
"""
return 2*(.5 - x) if x < 0.5 else 2*(x - .5)
def modified_random_distribution(modifier: Callable[[float], float],
n: int) -> List[float]:
"""
Generate n random numbers between 0 and 1 subject to modifier.
Parameters
----------
modifier : Callable[[float], float]
Target random number gen. 0 <= modifier(x) < 1.0 for 0 <= x < 1.0 .
n : int
number of random numbers generated.
Returns
-------
List[float]
n random numbers generated with given probability.
"""
d: List[float] = []
while len(d) < n:
r1 = prob = random.random()
if random.random() < modifier(prob):
d.append(r1)
return d
if __name__ == '__main__':
from collections import Counter
data = modified_random_distribution(modifier, 50_000)
bins = 15
counts = Counter(d // (1 / bins) for d in data)
#
mx = max(counts.values())
print(" BIN, COUNTS, DELTA: HISTOGRAM\n")
last: Optional[float] = None
for b, count in sorted(counts.items()):
delta = 'N/A' if last is None else str(count - last)
print(f" {b / bins:5.2f}, {count:4}, {delta:>4}: "
f"{'#' * int(40 * count / mx)}")
last = count |
Modular arithmetic | Python 3.x | equivalence relation called ''congruence''.
For any positive integer p called the ''congruence modulus'',
two numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that:
:a = b + k\,p
The corresponding set of multiplicative inverse for this task.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
:f(x) = x^{100} + x + 1
You will use 13 as the congruence modulus and you will compute f(10).
It is important that the function f is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| import operator
import functools
@functools.total_ordering
class Mod:
__slots__ = ['val','mod']
def __init__(self, val, mod):
if not isinstance(val, int):
raise ValueError('Value must be integer')
if not isinstance(mod, int) or mod<=0:
raise ValueError('Modulo must be positive integer')
self.val = val % mod
self.mod = mod
def __repr__(self):
return 'Mod({}, {})'.format(self.val, self.mod)
def __int__(self):
return self.val
def __eq__(self, other):
if isinstance(other, Mod):
if self.mod == other.mod:
return self.val==other.val
else:
return NotImplemented
elif isinstance(other, int):
return self.val == other
else:
return NotImplemented
def __lt__(self, other):
if isinstance(other, Mod):
if self.mod == other.mod:
return self.val<other.val
else:
return NotImplemented
elif isinstance(other, int):
return self.val < other
else:
return NotImplemented
def _check_operand(self, other):
if not isinstance(other, (int, Mod)):
raise TypeError('Only integer and Mod operands are supported')
if isinstance(other, Mod) and self.mod != other.mod:
raise ValueError('Inconsistent modulus: {} vs. {}'.format(self.mod, other.mod))
def __pow__(self, other):
self._check_operand(other)
# We use the built-in modular exponentiation function, this way we can avoid working with huge numbers.
return Mod(pow(self.val, int(other), self.mod), self.mod)
def __neg__(self):
return Mod(self.mod - self.val, self.mod)
def __pos__(self):
return self # The unary plus operator does nothing.
def __abs__(self):
return self # The value is always kept non-negative, so the abs function should do nothing.
# Helper functions to build common operands based on a template.
# They need to be implemented as functions for the closures to work properly.
def _make_op(opname):
op_fun = getattr(operator, opname) # Fetch the operator by name from the operator module
def op(self, other):
self._check_operand(other)
return Mod(op_fun(self.val, int(other)) % self.mod, self.mod)
return op
def _make_reflected_op(opname):
op_fun = getattr(operator, opname)
def op(self, other):
self._check_operand(other)
return Mod(op_fun(int(other), self.val) % self.mod, self.mod)
return op
# Build the actual operator overload methods based on the template.
for opname, reflected_opname in [('__add__', '__radd__'), ('__sub__', '__rsub__'), ('__mul__', '__rmul__')]:
setattr(Mod, opname, _make_op(opname))
setattr(Mod, reflected_opname, _make_reflected_op(opname))
def f(x):
return x**100+x+1
print(f(Mod(10,13)))
# Output: Mod(1, 13) |
Modular exponentiation | Python | Find the last '''40''' decimal digits of a^b, where
::* a = 2988348162058574136915891421498819466320163312926952423791023078876139
::* b = 2351399303373464486466122544523690094744975233415544072992656881240319
A computer is too slow to find the entire value of a^b.
Instead, the program must use a fast algorithm for modular exponentiation: a^b \mod m.
The algorithm must work for any integers a, b, m, where b \ge 0 and m > 0.
| a = 2988348162058574136915891421498819466320163312926952423791023078876139
b = 2351399303373464486466122544523690094744975233415544072992656881240319
m = 10 ** 40
print(pow(a, b, m)) |
Modular inverse | Python | From Wikipedia:
In modulo ''m'' is an integer ''x'' such that
::a\,x \equiv 1 \pmod{m}.
Or in other words, such that:
::\exists k \in\Z,\qquad a\, x = 1 + k\,m
It can be shown that such an inverse exists if and only if ''a'' and ''m'' are coprime, but we will ignore this for this task.
;Task:
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| from functools import (reduce)
from itertools import (chain)
# modInv :: Int -> Int -> Maybe Int
def modInv(a):
return lambda m: (
lambda ig=gcdExt(a)(m): (
lambda i=ig[0]: (
Just(i + m if 0 > i else i) if 1 == ig[2] else (
Nothing()
)
)
)()
)()
# gcdExt :: Int -> Int -> (Int, Int, Int)
def gcdExt(x):
def go(a, b):
if 0 == b:
return (1, 0, a)
else:
(q, r) = divmod(a, b)
(s, t, g) = go(b, r)
return (t, s - q * t, g)
return lambda y: go(x, y)
# TEST ---------------------------------------------------
# Numbers between 2010 and 2015 which do yield modular inverses for 42:
# main :: IO ()
def main():
print (
mapMaybe(
lambda y: bindMay(modInv(42)(y))(
lambda mInv: Just((y, mInv))
)
)(
enumFromTo(2010)(2025)
)
)
# -> [(2011, 814), (2015, 48), (2017, 1969), (2021, 1203)]
# GENERIC ABSTRACTIONS ------------------------------------
# enumFromTo :: Int -> Int -> [Int]
def enumFromTo(m):
return lambda n: list(range(m, 1 + n))
# bindMay (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
def bindMay(m):
return lambda mf: (
m if m.get('Nothing') else mf(m.get('Just'))
)
# Just :: a -> Maybe a
def Just(x):
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
# mapMaybe :: (a -> Maybe b) -> [a] -> [b]
def mapMaybe(mf):
return lambda xs: reduce(
lambda a, x: maybe(a)(lambda j: a + [j])(mf(x)),
xs,
[]
)
# maybe :: b -> (a -> b) -> Maybe a -> b
def maybe(v):
return lambda f: lambda m: v if m.get('Nothing') else (
f(m.get('Just'))
)
# Nothing :: Maybe a
def Nothing():
return {'type': 'Maybe', 'Nothing': True}
# MAIN ---
main() |
Monads/List monad | Python | A Monad is a combination of a data-type with two helper functions written for that type.
The data-type can be of any kind which can contain values of some other type - common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as '''eta''' and '''mu''', but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.
The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.
A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product.
The natural implementation of bind for the List monad is a composition of '''concat''' and '''map''', which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.
Demonstrate in your programming language the following:
#Construct a List Monad by writing the 'bind' function and the 'pure' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
#Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String
#Compose the two functions with bind
| """A List Monad. Requires Python >= 3.7 for type hints."""
from __future__ import annotations
from itertools import chain
from typing import Any
from typing import Callable
from typing import Iterable
from typing import List
from typing import TypeVar
T = TypeVar("T")
class MList(List[T]):
@classmethod
def unit(cls, value: Iterable[T]) -> MList[T]:
return cls(value)
def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
return MList(chain.from_iterable(map(func, self)))
def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
return self.bind(func)
if __name__ == "__main__":
# Chained int and string functions
print(
MList([1, 99, 4])
.bind(lambda val: MList([val + 1]))
.bind(lambda val: MList([f"${val}.00"]))
)
# Same, but using `>>` as the bind operator.
print(
MList([1, 99, 4])
>> (lambda val: MList([val + 1]))
>> (lambda val: MList([f"${val}.00"]))
)
# Cartesian product of [1..5] and [6..10]
print(
MList(range(1, 6)).bind(
lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)]))
)
)
# Pythagorean triples with elements between 1 and 25
print(
MList(range(1, 26)).bind(
lambda x: MList(range(x + 1, 26)).bind(
lambda y: MList(range(y + 1, 26)).bind(
lambda z: MList([(x, y, z)])
if x * x + y * y == z * z
else MList([])
)
)
)
)
|
Monads/Maybe monad | Python | Demonstrate in your programming language the following:
#Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
#Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String
#Compose the two functions with bind
A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.
A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
| """A Maybe Monad. Requires Python >= 3.7 for type hints."""
from __future__ import annotations
from typing import Any
from typing import Callable
from typing import Generic
from typing import Optional
from typing import TypeVar
from typing import Union
T = TypeVar("T")
class Maybe(Generic[T]):
def __init__(self, value: Union[Optional[T], Maybe[T]] = None):
if isinstance(value, Maybe):
self.value: Optional[T] = value.value
else:
self.value = value
def __rshift__(self, func: Callable[[Optional[T]], Maybe[Any]]):
return self.bind(func)
def bind(self, func: Callable[[Optional[T]], Maybe[Any]]) -> Maybe[Any]:
return func(self.value)
def __str__(self):
return f"{self.__class__.__name__}({self.value!r})"
def plus_one(value: Optional[int]) -> Maybe[int]:
if value is not None:
return Maybe[int](value + 1)
return Maybe[int](None)
def currency(value: Optional[int]) -> Maybe[str]:
if value is not None:
return Maybe[str](f"${value}.00")
return Maybe[str](None)
if __name__ == "__main__":
test_cases = [1, 99, None, 4]
for case in test_cases:
m_int = Maybe[int](case)
result = m_int >> plus_one >> currency
# or..
# result = m_int.bind(plus_one).bind(currency)
print(f"{str(case):<4} -> {result}")
|
Monads/Writer monad | Python | The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application.
Demonstrate in your programming language the following:
# Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)
# Write three simple functions: root, addOne, and half
# Derive Writer monad versions of each of these functions
# Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio ph, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
| """A Writer Monad. Requires Python >= 3.7 for type hints."""
from __future__ import annotations
import functools
import math
import os
from typing import Any
from typing import Callable
from typing import Generic
from typing import List
from typing import TypeVar
from typing import Union
T = TypeVar("T")
class Writer(Generic[T]):
def __init__(self, value: Union[T, Writer[T]], *msgs: str):
if isinstance(value, Writer):
self.value: T = value.value
self.msgs: List[str] = value.msgs + list(msgs)
else:
self.value = value
self.msgs = list(f"{msg}: {self.value}" for msg in msgs)
def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
writer = func(self.value)
return Writer(writer, *self.msgs)
def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
return self.bind(func)
def __str__(self):
return f"{self.value}\n{os.linesep.join(reversed(self.msgs))}"
def __repr__(self):
return f"Writer({self.value}, \"{', '.join(reversed(self.msgs))}\")"
def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:
"""Return a writer monad version of the simple function `func`."""
@functools.wraps(func)
def wrapped(value):
return Writer(func(value), msg)
return wrapped
if __name__ == "__main__":
square_root = lift(math.sqrt, "square root")
add_one = lift(lambda x: x + 1, "add one")
half = lift(lambda x: x / 2, "div two")
print(Writer(5, "initial") >> square_root >> add_one >> half)
|
Move-to-front algorithm | Python | Given a symbol table of a ''zero-indexed'' array of all possible input symbols
this algorithm reversibly transforms a sequence
of input symbols into an array of output numbers (indices).
The transform in many cases acts to give frequently repeated input symbols
lower indices which is useful in some compression algorithms.
;Encoding algorithm:
for each symbol of the input sequence:
output the index of the symbol in the symbol table
move that symbol to the front of the symbol table
;Decoding algorithm:
# Using the same starting symbol table
for each index of the input sequence:
output the symbol at that index of the symbol table
move that symbol to the front of the symbol table
;Example:
Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters '''a'''-to-'''z'''
:::::{| class="wikitable" border="1"
|-
! Input
! Output
! SymbolTable
|-
| '''b'''roood
| 1
| 'abcdefghijklmnopqrstuvwxyz'
|-
| b'''r'''oood
| 1 17
| 'bacdefghijklmnopqrstuvwxyz'
|-
| br'''o'''ood
| 1 17 15
| 'rbacdefghijklmnopqstuvwxyz'
|-
| bro'''o'''od
| 1 17 15 0
| 'orbacdefghijklmnpqstuvwxyz'
|-
| broo'''o'''d
| 1 17 15 0 0
| 'orbacdefghijklmnpqstuvwxyz'
|-
| brooo'''d'''
| 1 17 15 0 0 5
| 'orbacdefghijklmnpqstuvwxyz'
|}
Decoding the indices back to the original symbol order:
:::::{| class="wikitable" border="1"
|-
! Input
! Output
! SymbolTable
|-
| '''1''' 17 15 0 0 5
| b
| 'abcdefghijklmnopqrstuvwxyz'
|-
| 1 '''17''' 15 0 0 5
| br
| 'bacdefghijklmnopqrstuvwxyz'
|-
| 1 17 '''15''' 0 0 5
| bro
| 'rbacdefghijklmnopqstuvwxyz'
|-
| 1 17 15 '''0''' 0 5
| broo
| 'orbacdefghijklmnpqstuvwxyz'
|-
| 1 17 15 0 '''0''' 5
| brooo
| 'orbacdefghijklmnpqstuvwxyz'
|-
| 1 17 15 0 0 '''5'''
| broood
| 'orbacdefghijklmnpqstuvwxyz'
|}
;Task:
:* Encode and decode the following three strings of characters using the symbol table of the lowercase characters '''a'''-to-'''z''' as above.
:* Show the strings and their encoding here.
:* Add a check to ensure that the decoded string is the same as the original.
The strings are:
broood
bananaaa
hiphophiphop
(Note the misspellings in the above strings.)
| from __future__ import print_function
from string import ascii_lowercase
SYMBOLTABLE = list(ascii_lowercase)
def move2front_encode(strng, symboltable):
sequence, pad = [], symboltable[::]
for char in strng:
indx = pad.index(char)
sequence.append(indx)
pad = [pad.pop(indx)] + pad
return sequence
def move2front_decode(sequence, symboltable):
chars, pad = [], symboltable[::]
for indx in sequence:
char = pad[indx]
chars.append(char)
pad = [pad.pop(indx)] + pad
return ''.join(chars)
if __name__ == '__main__':
for s in ['broood', 'bananaaa', 'hiphophiphop']:
encode = move2front_encode(s, SYMBOLTABLE)
print('%14r encodes to %r' % (s, encode), end=', ')
decode = move2front_decode(encode, SYMBOLTABLE)
print('which decodes back to %r' % decode)
assert s == decode, 'Whoops!' |
Multi-dimensional array | Python | For the purposes of this task, the actual memory layout or access method of this data structure is not mandated.
It is enough to:
# State the number and extent of each index to the array.
# Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value.
# Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.
;Task:
* State if the language supports multi-dimensional arrays in its syntax and usual implementation.
* State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage.
* Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred.
:* The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, ''if'' indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).
* State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.
* If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.
Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
| >>> from numpy import *
>>>
>>> mdarray = zeros((2, 3, 4, 5), dtype=int8, order='F')
>>> mdarray
array([[[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]],
[[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]]], dtype=int8)
>>> mdarray[0, 1, 2, 3]
0
>>> mdarray[0, 1, 2, 3] = 123
>>> mdarray[0, 1, 2, 3]
123
>>> mdarray[0, 1, 2, 3] = 666
>>> mdarray[0, 1, 2, 3]
-102
>>> mdarray[0, 1, 2, 3] = 255
>>> mdarray[0, 1, 2, 3]
-1
>>> mdarray[0, 1, 2, 3] = -128
>>> mdarray[0, 1, 2, 3]
-128
>>> mdarray
array([[[[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0]],
[[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, -128, 0],
[ 0, 0, 0, 0, 0]],
[[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0]]],
[[[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0]],
[[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0]],
[[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0]]]], dtype=int8)
>>> |
Multifactorial | Python | The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1).
Multifactorials generalize factorials as follows:
: n! = n(n-1)(n-2)...(2)(1)
: n!! = n(n-2)(n-4)...
: n!! ! = n(n-3)(n-6)...
: n!! !! = n(n-4)(n-8)...
: n!! !! ! = n(n-5)(n-10)...
In all cases, the terms in the products are positive integers.
If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
# Write a function that given n and the degree, calculates the multifactorial.
# Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.
'''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
| >>> from functools import reduce
>>> from operator import mul
>>> def mfac(n, m): return reduce(mul, range(n, 0, -m))
>>> for m in range(1, 11): print("%2i: %r" % (m, [mfac(n, m) for n in range(1, 11)]))
1: [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
2: [1, 2, 3, 8, 15, 48, 105, 384, 945, 3840]
3: [1, 2, 3, 4, 10, 18, 28, 80, 162, 280]
4: [1, 2, 3, 4, 5, 12, 21, 32, 45, 120]
5: [1, 2, 3, 4, 5, 6, 14, 24, 36, 50]
6: [1, 2, 3, 4, 5, 6, 7, 16, 27, 40]
7: [1, 2, 3, 4, 5, 6, 7, 8, 18, 30]
8: [1, 2, 3, 4, 5, 6, 7, 8, 9, 20]
9: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
10: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> |
Multiple distinct objects | Python | Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.
By ''distinct'' we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By ''initialized'' we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the ''same'' mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: [[Closures/Value capture]]
| [Foo()] * n # here Foo() can be any expression that returns a new object |
Multisplit | Python | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string "a!===b=!=c" and the separators "==", "!=" and "=".
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.
'''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| def min_pos(List):
return List.index(min(List))
def find_all(S, Sub, Start = 0, End = -1, IsOverlapped = 0):
Res = []
if End == -1:
End = len(S)
if IsOverlapped:
DeltaPos = 1
else:
DeltaPos = len(Sub)
Pos = Start
while True:
Pos = S.find(Sub, Pos, End)
if Pos == -1:
break
Res.append(Pos)
Pos += DeltaPos
return Res
def multisplit(S, SepList):
SepPosListList = []
SLen = len(S)
SepNumList = []
ListCount = 0
for i, Sep in enumerate(SepList):
SepPosList = find_all(S, Sep, 0, SLen, IsOverlapped = 1)
if SepPosList != []:
SepNumList.append(i)
SepPosListList.append(SepPosList)
ListCount += 1
if ListCount == 0:
return [S]
MinPosList = []
for i in range(ListCount):
MinPosList.append(SepPosListList[i][0])
SepEnd = 0
MinPosPos = min_pos(MinPosList)
Res = []
while True:
Res.append( S[SepEnd : MinPosList[MinPosPos]] )
Res.append([SepNumList[MinPosPos], MinPosList[MinPosPos]])
SepEnd = MinPosList[MinPosPos] + len(SepList[SepNumList[MinPosPos]])
while True:
MinPosPos = min_pos(MinPosList)
if MinPosList[MinPosPos] < SepEnd:
del SepPosListList[MinPosPos][0]
if len(SepPosListList[MinPosPos]) == 0:
del SepPosListList[MinPosPos]
del MinPosList[MinPosPos]
del SepNumList[MinPosPos]
ListCount -= 1
if ListCount == 0:
break
else:
MinPosList[MinPosPos] = SepPosListList[MinPosPos][0]
else:
break
if ListCount == 0:
break
Res.append(S[SepEnd:])
return Res
S = "a!===b=!=c"
multisplit(S, ["==", "!=", "="]) # output: ['a', [1, 1], '', [0, 3], 'b', [2, 6], '', [1, 7], 'c']
multisplit(S, ["=", "!=", "=="]) # output: ['a', [1, 1], '', [0, 3], '', [0, 4], 'b', [0, 6], '', [1, 7], 'c'] |
Multisplit | Python 3.7 | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string "a!===b=!=c" and the separators "==", "!=" and "=".
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.
'''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| '''Multisplit'''
from functools import reduce
# multiSplit :: [String] -> String -> [(String, String, Int)]
def multiSplit(separators):
'''List of triples:
[(token, separator, start index of separator].
'''
def go(s):
def f(tokensPartsOffset, ic):
tokens, parts, offset = tokensPartsOffset
i, c = ic
inDelim = offset > i
return maybe(
(
tokens if inDelim
else c + tokens, parts, offset
)
)(
lambda x: (
'',
[(tokens, x, i)] + parts,
i + len(x)
)
)(
None if inDelim else find(
s[i:].startswith
)(separators)
)
ts, ps, _ = reduce(f, enumerate(s), ('', [], 0))
return list(reversed(ps)) + [(ts, '', len(s))]
return go
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''String split on three successive separators.'''
print(
multiSplit(['==', '!=', '='])(
'a!===b=!=c'
)
)
# ------------------ GENERIC FUNCTIONS -------------------
# find :: (a -> Bool) -> [a] -> (a | None)
def find(p):
'''Just the first element in the list that matches p,
or None if no elements match.
'''
def go(xs):
try:
return next(x for x in xs if p(x))
except StopIteration:
return None
return go
# maybe :: b -> (a -> b) -> (a | None) -> b
def maybe(v):
'''Either the default value v, if m is None,
or the application of f to x.
'''
return lambda f: lambda m: v if (
None is m
) else f(m)
# MAIN ---
if __name__ == '__main__':
main() |
Munchausen numbers | Python | A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''.
('''Munchausen''' is also spelled: '''Munchhausen'''.)
For instance: 3435 = 33 + 44 + 33 + 55
;Task
Find all Munchausen numbers between '''1''' and '''5000'''.
;Also see:
:* The OEIS entry: A046253
:* The Wikipedia entry: Perfect digit-to-digit invariant, redirected from ''Munchausen Number''
| for i in range(5000):
if i == sum(int(x) ** int(x) for x in str(i)):
print(i) |
Munchausen numbers | Python 3 | A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''.
('''Munchausen''' is also spelled: '''Munchhausen'''.)
For instance: 3435 = 33 + 44 + 33 + 55
;Task
Find all Munchausen numbers between '''1''' and '''5000'''.
;Also see:
:* The OEIS entry: A046253
:* The Wikipedia entry: Perfect digit-to-digit invariant, redirected from ''Munchausen Number''
| '''Munchausen numbers'''
from functools import (reduce)
# isMunchausen :: Int -> Bool
def isMunchausen(n):
'''True if n equals the sum of
each of its digits raised to
the power of itself.'''
def powerOfSelf(d):
i = digitToInt(d)
return i**i
return n == reduce(
lambda n, c: n + powerOfSelf(c),
str(n), 0
)
# main :: IO ()
def main():
'''Test'''
print(list(filter(
isMunchausen,
enumFromTo(1)(5000)
)))
# GENERIC -------------------------------------------------
# digitToInt :: Char -> Int
def digitToInt(c):
'''The integer value of any digit character
drawn from the 0-9, A-F or a-f ranges.'''
oc = ord(c)
if 48 > oc or 102 < oc:
return None
else:
dec = oc - 48 # ord('0')
hexu = oc - 65 # ord('A')
hexl = oc - 97 # ord('a')
return dec if 9 >= dec else (
10 + hexu if 0 <= hexu <= 5 else (
10 + hexl if 0 <= hexl <= 5 else None
)
)
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
if __name__ == '__main__':
main() |
Musical scale | Python | Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.
These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfege.
For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.
For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
| >>> import winsound
>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:
winsound.Beep(int(note+.5), 500)
>>> |
Mutex | Python | {{requires|Concurrency}}
A '''mutex''' (''abbreviated'' '''Mut'''ually '''Ex'''clusive access) is a synchronization object, a variant of [[semaphore]] with ''k''=1.
A mutex is said to be seized by a [[task]] decreasing ''k''.
It is released when the task restores ''k''. Mutexes are typically used to protect a shared resource from concurrent access.
A [[task]] seizes (or acquires) the mutex, then accesses the resource, and after that releases the mutex.
A mutex is a low-level synchronization primitive exposed to deadlocking. A deadlock can occur with just two tasks and two mutexes (if each task attempts to acquire both mutexes, but in the opposite order).
Entering the deadlock is usually aggravated by a [[race condition]] state, which leads to sporadic hangups, which are very difficult to track down.
=Variants of mutexes=
==Global and local mutexes==
Usually the [[OS]] provides various implementations of mutexes corresponding to the variants of [[task]]s available in the OS. For example, system-wide mutexes can be used by [[process]]es. Local mutexes can be used only by [[threads]] etc. This distinction is maintained because, depending on the hardware, seizing a global mutex might be a thousand times slower than seizing a local one.
==Reentrant mutex==
A reentrant mutex can be seized by the same [[task]] multiple times. Each seizing of the mutex is matched by releasing it, in order to allow another task to seize it.
==Read write mutex==
A read write mutex can be seized at two levels for ''read'' and for ''write''. The mutex can be seized for ''read'' by any number of tasks. Only one task may seize it for '''write''. Read write mutexes are usually used to protect resources which can be accessed in mutable and immutable ways. Immutable (read) access is granted concurrently for many tasks because they do not change the resource state. Read write mutexes can be reentrant, global or local. Further, promotion operations may be provided. That's when a [[task]] that has seized the mutex for ''write'' releases it while keeping seized for ''read''. Note that the reverse operation is potentially deadlocking and requires some additional access policy control.
=Deadlock prevention=
There exists a simple technique of deadlock prevention when mutexes are seized in some fixed order. This is discussed in depth in the [[Dining philosophers]] problem.
=Sample implementations / APIs=
| import threading
from time import sleep
# res: max number of resources. If changed to 1, it functions
# identically to a mutex/lock object
res = 2
sema = threading.Semaphore(res)
class res_thread(threading.Thread):
def run(self):
global res
n = self.getName()
for i in range(1, 4):
# acquire a resource if available and work hard
# for 2 seconds. if all res are occupied, block
# and wait
sema.acquire()
res = res - 1
print n, "+ res count", res
sleep(2)
# after done with resource, return it to pool and flag so
res = res + 1
print n, "- res count", res
sema.release()
# create 4 threads, each acquire resorce and work
for i in range(1, 5):
t = res_thread()
t.start() |
N-queens problem | Python | right
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''.
For the number of solutions for small values of '''N''', see OEIS: A000170.
;Related tasks:
* [[A* search algorithm]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Knight's tour]]
* [[Peaceful chess queen armies]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]
| from itertools import permutations
n = 8
cols = range(n)
for vec in permutations(cols):
if n == len(set(vec[i]+i for i in cols)) \
== len(set(vec[i]-i for i in cols)):
print ( vec ) |
N-queens problem | Python 2.6, 3.x | right
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''.
For the number of solutions for small values of '''N''', see OEIS: A000170.
;Related tasks:
* [[A* search algorithm]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Knight's tour]]
* [[Peaceful chess queen armies]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]
| def queens_lex(n):
a = list(range(n))
up = [True]*(2*n - 1)
down = [True]*(2*n - 1)
def sub(i):
if i == n:
yield tuple(a)
else:
for k in range(i, n):
a[i], a[k] = a[k], a[i]
j = a[i]
p = i + j
q = i - j + n - 1
if up[p] and down[q]:
up[p] = down[q] = False
yield from sub(i + 1)
up[p] = down[q] = True
x = a[i]
for k in range(i + 1, n):
a[k - 1] = a[k]
a[n - 1] = x
yield from sub(0)
next(queens(31))
(0, 2, 4, 1, 3, 8, 10, 12, 14, 6, 17, 21, 26, 28, 25, 27, 24, 30, 7, 5, 29, 15, 13, 11, 9, 18, 22, 19, 23, 16, 20)
next(queens_lex(31))
(0, 2, 4, 1, 3, 8, 10, 12, 14, 5, 17, 22, 25, 27, 30, 24, 26, 29, 6, 16, 28, 13, 9, 7, 19, 11, 15, 18, 21, 23, 20)
#Compare to A065188
#1, 3, 5, 2, 4, 9, 11, 13, 15, 6, 8, 19, 7, 22, 10, 25, 27, 29, 31, 12, 14, 35, 37, ... |
N-queens problem | Python 3.7 | right
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''.
For the number of solutions for small values of '''N''', see OEIS: A000170.
;Related tasks:
* [[A* search algorithm]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Knight's tour]]
* [[Peaceful chess queen armies]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]
| '''N Queens problem'''
from functools import reduce
from itertools import chain
# queenPuzzle :: Int -> Int -> [[Int]]
def queenPuzzle(nCols):
'''All board patterns of this dimension
in which no two Queens share a row,
column, or diagonal.
'''
def go(nRows):
lessRows = nRows - 1
return reduce(
lambda a, xys: a + reduce(
lambda b, iCol: b + [xys + [iCol]] if (
safe(lessRows, iCol, xys)
) else b,
enumFromTo(1)(nCols),
[]
),
go(lessRows),
[]
) if 0 < nRows else [[]]
return go
# safe :: Int -> Int -> [Int] -> Bool
def safe(iRow, iCol, pattern):
'''True if no two queens in the pattern
share a row, column or diagonal.
'''
def p(sc, sr):
return (iCol == sc) or (
sc + sr == (iCol + iRow)
) or (sc - sr == (iCol - iRow))
return not any(map(p, pattern, range(0, iRow)))
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Number of solutions for boards of various sizes'''
n = 5
xs = queenPuzzle(n)(n)
print(
str(len(xs)) + ' solutions for a {n} * {n} board:\n'.format(n=n)
)
print(showBoards(10)(xs))
print(
fTable(
'\n\n' + main.__doc__ + ':\n'
)(str)(lambda n: str(n).rjust(3, ' '))(
lambda n: len(queenPuzzle(n)(n))
)(enumFromTo(1)(10))
)
# ---------------------- FORMATTING ----------------------
# showBoards :: Int -> [[Int]] -> String
def showBoards(nCols):
'''String representation, with N columns
of a set of board patterns.
'''
def showBlock(b):
return '\n'.join(map(intercalate(' '), zip(*b)))
def go(bs):
return '\n\n'.join(map(
showBlock,
chunksOf(nCols)([
showBoard(b) for b in bs
])
))
return go
# showBoard :: [Int] -> String
def showBoard(xs):
'''String representation of a Queens board.'''
lng = len(xs)
def showLine(n):
return ('.' * (n - 1)) + '♛' + ('.' * (lng - n))
return map(showLine, xs)
# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
'''Heading -> x display function -> fx display function ->
f -> xs -> tabular string.
'''
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
# ----------------------- GENERIC ------------------------
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: range(m, 1 + n)
# chunksOf :: Int -> [a] -> [[a]]
def chunksOf(n):
'''A series of lists of length n, subdividing the
contents of xs. Where the length of xs is not evenly
divible, the final list will be shorter than n.
'''
return lambda xs: reduce(
lambda a, i: a + [xs[i:n + i]],
range(0, len(xs), n), []
) if 0 < n else []
# intercalate :: [a] -> [[a]] -> [a]
# intercalate :: String -> [String] -> String
def intercalate(x):
'''The concatenation of xs
interspersed with copies of x.
'''
return lambda xs: x.join(xs) if isinstance(x, str) else list(
chain.from_iterable(
reduce(lambda a, v: a + [x, v], xs[1:], [xs[0]])
)
) if xs else []
# MAIN ---
if __name__ == '__main__':
main() |
Narcissist | Python 2 | Quoting from the Esolangs wiki page:
A '''narcissist''' (or '''Narcissus program''') is the decision-problem version of a [[quine]].
A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not.
For concreteness, in this task we shall assume that symbol = character.
The narcissist should be able to cope with any finite input, whatever its length.
Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
| import sys
with open(sys.argv[0]) as quine:
code = raw_input("Enter source code: ")
if code == quine.read():
print("Accept")
else:
print("Reject")
|
Narcissistic decimal number | Python | A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n.
Narcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong.
They are also known as '''Plus Perfect''' numbers.
;An example:
::::* if n is '''153'''
::::* then m, (the number of decimal digits) is '''3'''
::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153'''
::::* and so '''153''' is a narcissistic decimal number
;Task:
Generate and show here the first '''25''' narcissistic decimal numbers.
Note: 0^1 = 0, the first in the series.
;See also:
* the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
* MathWorld entry: Narcissistic Number.
* Wikipedia entry: Narcissistic number.
| from __future__ import print_function
from itertools import count, islice
def narcissists():
for digits in count(0):
digitpowers = [i**digits for i in range(10)]
for n in range(int(10**(digits-1)), 10**digits):
div, digitpsum = n, 0
while div:
div, mod = divmod(div, 10)
digitpsum += digitpowers[mod]
if n == digitpsum:
yield n
for i, n in enumerate(islice(narcissists(), 25), 1):
print(n, end=' ')
if i % 5 == 0: print()
print() |
Narcissistic decimal number | Python from D | A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n.
Narcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong.
They are also known as '''Plus Perfect''' numbers.
;An example:
::::* if n is '''153'''
::::* then m, (the number of decimal digits) is '''3'''
::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153'''
::::* and so '''153''' is a narcissistic decimal number
;Task:
Generate and show here the first '''25''' narcissistic decimal numbers.
Note: 0^1 = 0, the first in the series.
;See also:
* the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
* MathWorld entry: Narcissistic Number.
* Wikipedia entry: Narcissistic number.
| try:
import psyco
psyco.full()
except:
pass
class Narcissistics:
def __init__(self, max_len):
self.max_len = max_len
self.power = [0] * 10
self.dsum = [0] * (max_len + 1)
self.count = [0] * 10
self.len = 0
self.ord0 = ord('0')
def check_perm(self, out = [0] * 10):
for i in xrange(10):
out[i] = 0
s = str(self.dsum[0])
for d in s:
c = ord(d) - self.ord0
out[c] += 1
if out[c] > self.count[c]:
return
if len(s) == self.len:
print self.dsum[0],
def narc2(self, pos, d):
if not pos:
self.check_perm()
return
while True:
self.dsum[pos - 1] = self.dsum[pos] + self.power[d]
self.count[d] += 1
self.narc2(pos - 1, d)
self.count[d] -= 1
if d == 0:
break
d -= 1
def show(self, n):
self.len = n
for i in xrange(len(self.power)):
self.power[i] = i ** n
self.dsum[n] = 0
print "length %d:" % n,
self.narc2(n, 9)
print
def main():
narc = Narcissistics(14)
for i in xrange(1, narc.max_len + 1):
narc.show(i)
main() |
Narcissistic decimal number | Python 3.7 | A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n.
Narcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong.
They are also known as '''Plus Perfect''' numbers.
;An example:
::::* if n is '''153'''
::::* then m, (the number of decimal digits) is '''3'''
::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153'''
::::* and so '''153''' is a narcissistic decimal number
;Task:
Generate and show here the first '''25''' narcissistic decimal numbers.
Note: 0^1 = 0, the first in the series.
;See also:
* the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
* MathWorld entry: Narcissistic Number.
* Wikipedia entry: Narcissistic number.
| '''Narcissistic decimal numbers'''
from itertools import chain
from functools import reduce
# main :: IO ()
def main():
'''Narcissistic numbers of digit lengths 1 to 7'''
print(
fTable(main.__doc__ + ':\n')(str)(str)(
narcissiOfLength
)(enumFromTo(1)(7))
)
# narcissiOfLength :: Int -> [Int]
def narcissiOfLength(n):
'''List of Narcissistic numbers of
(base 10) digit length n.
'''
return [
x for x in digitPowerSums(n)
if isDaffodil(n)(x)
]
# digitPowerSums :: Int -> [Int]
def digitPowerSums(e):
'''The subset of integers of e digits that are potential narcissi.
(Flattened leaves of a tree of unique digit combinations, in which
order is not significant. The sum is independent of the sequence.)
'''
powers = [(x, x ** e) for x in enumFromTo(0)(9)]
def go(n, parents):
return go(
n - 1,
chain.from_iterable(map(
lambda pDigitSum: (
map(
lambda lDigitSum: (
lDigitSum[0],
lDigitSum[1] + pDigitSum[1]
),
powers[0: 1 + pDigitSum[0]]
)
),
parents
)) if parents else powers
) if 0 < n else parents
return [xs for (_, xs) in go(e, [])]
# isDaffodil :: Int -> Int -> Bool
def isDaffodil(e):
'''True if n is a narcissistic number
of decimal digit length e.
'''
def go(n):
ds = digitList(n)
return e == len(ds) and n == powerSum(e)(ds)
return lambda n: go(n)
# powerSum :: Int -> [Int] -> Int
def powerSum(e):
'''The sum of a list obtained by raising
each element of xs to the power of e.
'''
return lambda xs: reduce(
lambda a, x: a + x ** e,
xs, 0
)
# -----------------------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 -------------------------------------------------
# digitList :: Int -> [Int]
def digitList(n):
'''A decomposition of n into a
list of single-digit integers.
'''
def go(x):
return go(x // 10) + [x % 10] if x else []
return go(n) if n else [0]
# enumFromTo :: Int -> Int -> [Int]
def enumFromTo(m):
'''Enumeration of integer values [m..n]'''
def go(n):
return list(range(m, 1 + n))
return lambda n: go(n)
# MAIN ---
if __name__ == '__main__':
main() |
Nautical bell | Python | Task
Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day.
The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise.
It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type.
;Related task:
* [[Sleep]]
| import time, calendar, sched, winsound
duration = 750 # Bell duration in ms
freq = 1280 # Bell frequency in hertz
bellchar = "\u2407"
watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')
def gap(n=1):
time.sleep(n * duration / 1000)
off = gap
def on(n=1):
winsound.Beep(freq, n * duration)
def bong():
on(); off(0.5)
def bongs(m):
for i in range(m):
print(bellchar, end=' ')
bong()
if i % 2:
print(' ', end='')
off(0.5)
print('')
scheds = sched.scheduler(time.time, time.sleep)
def ships_bell(now=None):
def adjust_to_half_hour(atime):
atime[4] = (atime[4] // 30) * 30
atime[5] = 0
return atime
debug = now is not None
rightnow = time.gmtime()
if not debug:
now = adjust_to_half_hour( list(rightnow) )
then = now[::]
then[4] += 30
hr, mn = now[3:5]
watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)
b += 1
bells = '%i bell%s' % (b, 's' if b > 1 else ' ')
if debug:
print("%02i:%02i, %-20s %s" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')
else:
print("%02i:%02i, %-20s %s" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')
bongs(b)
if not debug:
scheds.enterabs(calendar.timegm(then), 0, ships_bell)
#print(time.struct_time(then))
scheds.run()
def dbg_tester():
for h in range(24):
for m in (0, 30):
if (h,m) == (24,30): break
ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )
if __name__ == '__main__':
ships_bell() |
Negative base numbers | Python | Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).Negabinary on Wolfram MathworldNegative base on Wikipedia
;Task:
*Encode the decimal number 10 as negabinary (expect 11110)
*Encode the decimal number 146 as negaternary (expect 21102)
*Encode the decimal number 15 as negadecimal (expect 195)
*In each of the above cases, convert the encoded number back to decimal.
;extra credit:
* supply an integer, that when encoded to base -62 (or something "higher"), expresses the name of the language being used (with correct capitalization). If the computer language has non-alphanumeric characters, try to encode them into the negatory numerals, or use other characters instead.
| #!/bin/python
from __future__ import print_function
def EncodeNegBase(n, b): #Converts from decimal
if n == 0:
return "0"
out = []
while n != 0:
n, rem = divmod(n, b)
if rem < 0:
n += 1
rem -= b
out.append(rem)
return "".join(map(str, out[::-1]))
def DecodeNegBase(nstr, b): #Converts to decimal
if nstr == "0":
return 0
total = 0
for i, ch in enumerate(nstr[::-1]):
total += int(ch) * b**i
return total
if __name__=="__main__":
print ("Encode 10 as negabinary (expect 11110)")
result = EncodeNegBase(10, -2)
print (result)
if DecodeNegBase(result, -2) == 10: print ("Converted back to decimal")
else: print ("Error converting back to decimal")
print ("Encode 146 as negaternary (expect 21102)")
result = EncodeNegBase(146, -3)
print (result)
if DecodeNegBase(result, -3) == 146: print ("Converted back to decimal")
else: print ("Error converting back to decimal")
print ("Encode 15 as negadecimal (expect 195)")
result = EncodeNegBase(15, -10)
print (result)
if DecodeNegBase(result, -10) == 15: print ("Converted back to decimal")
else: print ("Error converting back to decimal") |
Subsets and Splits