title
stringlengths 3
86
| language
stringlengths 1
35
| task
stringlengths 41
8.77k
| solution
stringlengths 60
47.6k
|
---|---|---|---|
Nested function | Python 3+ | In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
;Task:
Write a program consisting of two nested functions that prints the following text.
1. first
2. second
3. third
The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.
The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.
;References:
:* Nested function
| def makeList(separator):
counter = 1
def makeItem(item):
nonlocal counter
result = str(counter) + separator + item + "\n"
counter += 1
return result
return makeItem("first") + makeItem("second") + makeItem("third")
print(makeList(". ")) |
Nested templated data | Python | A template for data is an arbitrarily nested tree of integer indices.
Data payloads are given as a separate mapping, array or other simpler, flat,
association of indices to individual items of data, and are strings.
The idea is to create a data structure with the templates' nesting, and the
payload corresponding to each index appearing at the position of each index.
Answers using simple string replacement or regexp are to be avoided. The idea is
to use the native, or usual implementation of lists/tuples etc of the language
and to hierarchically traverse the template to generate the output.
;Task Detail:
Given the following input template t and list of payloads p:
# Square brackets are used here to denote nesting but may be changed for other,
# clear, visual representations of nested data appropriate to ones programming
# language.
t = [
[[1, 2],
[3, 4, 1],
5]]
p = 'Payload#0' ... 'Payload#6'
The correct output should have the following structure, (although spacing and
linefeeds may differ, the nesting and order should follow):
[[['Payload#1', 'Payload#2'],
['Payload#3', 'Payload#4', 'Payload#1'],
'Payload#5']]
1. Generate the output for the above template, t.
;Optional Extended tasks:
2. Show which payloads remain unused.
3. Give some indication/handling of indices without a payload.
''Show output on this page.''
| from pprint import pprint as pp
class Template():
def __init__(self, structure):
self.structure = structure
self.used_payloads, self.missed_payloads = [], []
def inject_payload(self, id2data):
def _inject_payload(substruct, i2d, used, missed):
used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d)
missed.extend(f'??#{x}'
for x in substruct if type(x) is not tuple and x not in i2d)
return tuple(_inject_payload(x, i2d, used, missed)
if type(x) is tuple
else i2d.get(x, f'??#{x}')
for x in substruct)
ans = _inject_payload(self.structure, id2data,
self.used_payloads, self.missed_payloads)
self.unused_payloads = sorted(set(id2data.values())
- set(self.used_payloads))
self.missed_payloads = sorted(set(self.missed_payloads))
return ans
if __name__ == '__main__':
index2data = {p: f'Payload#{p}' for p in range(7)}
print("##PAYLOADS:\n ", end='')
print('\n '.join(list(index2data.values())))
for structure in [
(((1, 2),
(3, 4, 1),
5),),
(((1, 2),
(10, 4, 1),
5),)]:
print("\n\n# TEMPLATE:")
pp(structure, width=13)
print("\n TEMPLATE WITH PAYLOADS:")
t = Template(structure)
out = t.inject_payload(index2data)
pp(out)
print("\n UNUSED PAYLOADS:\n ", end='')
unused = t.unused_payloads
print('\n '.join(unused) if unused else '-')
print(" MISSING PAYLOADS:\n ", end='')
missed = t.missed_payloads
print('\n '.join(missed) if missed else '-') |
Next highest int from digits | Python | Given a zero or positive integer, the task is to generate the next largest
integer using only the given digits*1.
* Numbers will not be padded to the left with zeroes.
* Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).
* If there is no next highest integer return zero.
:*1 Alternatively phrased as: "Find the smallest integer larger than the (positive or zero) integer '''N'''
:: which can be obtained by reordering the (base ten) digits of '''N'''".
;Algorithm 1:
# Generate all the permutations of the digits and sort into numeric order.
# Find the number in the list.
# Return the next highest number from the list.
The above could prove slow and memory hungry for numbers with large numbers of
digits, but should be easy to reason about its correctness.
;Algorithm 2:
# Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.
# Exchange that digit with the digit on the right that is ''both'' more than it, and closest to it.
# Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation)
'''E.g.:'''
n = 12453
12_4_53
12_5_43
12_5_34
return: 12534
This second algorithm is faster and more memory efficient, but implementations
may be harder to test.
One method of testing, (as used in developing the task), is to compare results from both
algorithms for random numbers generated from a range that the first algorithm can handle.
;Task requirements:
Calculate the next highest int from the digits of the following numbers:
:* 0
:* 9
:* 12
:* 21
:* 12453
:* 738440
:* 45072010
:* 95322020
;Optional stretch goal:
:* 9589776899767587796600
| def closest_more_than(n, lst):
"(index of) closest int from lst, to n that is also > n"
large = max(lst) + 1
return lst.index(min(lst, key=lambda x: (large if x <= n else x)))
def nexthigh(n):
"Return nxt highest number from n's digits using scan & re-order"
assert n == int(abs(n)), "n >= 0"
this = list(int(digit) for digit in str(int(n)))[::-1]
mx = this[0]
for i, digit in enumerate(this[1:], 1):
if digit < mx:
mx_index = closest_more_than(digit, this[:i + 1])
this[mx_index], this[i] = this[i], this[mx_index]
this[:i] = sorted(this[:i], reverse=True)
return int(''.join(str(d) for d in this[::-1]))
elif digit > mx:
mx, mx_index = digit, i
return 0
if __name__ == '__main__':
for x in [0, 9, 12, 21, 12453, 738440, 45072010, 95322020,
9589776899767587796600]:
print(f"{x:>12_d} -> {nexthigh(x):>12_d}") |
Nim game | Python | Nim is a simple game where the second player-if they know the trick-will always win.
The game has only 3 rules:
::* start with '''12''' tokens
::* each player takes '''1, 2, or 3''' tokens in turn
::* the player who takes the last token wins.
To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3; if the first player takes 2, the second should take 2; and if the first player takes 3, the second player will take 1.
;Task:
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| print("Py Nim\n")
def getTokens(curTokens):
global tokens
print("How many tokens would you like to take? ", end='')
take = int(input())
if (take < 1 or take > 3):
print("Number must be between 1 and 3.\n")
getTokens(curTokens)
return
tokens = curTokens - take
print(f'You take {take} tokens.')
print(f'{tokens} tokens remaining.\n')
def compTurn(curTokens):
global tokens
take = curTokens % 4
tokens = curTokens - take
print (f'Computer takes {take} tokens.')
print (f'{tokens} tokens remaining.\n')
tokens = 12
while (tokens > 0):
getTokens(tokens)
compTurn(tokens)
print("Computer wins!")
|
Non-transitive dice | Python | Let our dice select numbers on their faces with equal probability, i.e. fair dice.
Dice may have more or less than six faces. (The possibility of there being a
3D physical shape that has that many "faces" that allow them to be fair dice,
is ignored for this task - a die with 3 or 33 defined sides is defined by the
number of faces and the numbers on each face).
Throwing dice will randomly select a face on each die with equal probability.
To show which die of dice thrown multiple times is more likely to win over the
others:
# calculate all possible combinations of different faces from each die
# Count how many times each die wins a combination
# Each ''combination'' is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice.
'''If two dice X and Y are thrown against each other then X likely to: win, lose, or break-even against Y can be shown as: X > Y, X < Y, or X = Y respectively.
'''
;Example 1:
If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its
faces then the equal possibility outcomes from throwing both, and the winners
is:
X Y Winner
= = ======
1 2 Y
1 3 Y
1 4 Y
3 2 X
3 3 -
3 4 Y
6 2 X
6 3 X
6 4 X
TOTAL WINS: X=4, Y=4
Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y
;Transitivity:
In mathematics transitivity are rules like:
if a op b and b op c then a op c
If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers
we get the familiar if a < b and b < c then a < c
;Non-transitive dice
These are an ordered list of dice where the '>' operation between successive
dice pairs applies but a comparison between the first and last of the list
yields the opposite result, '<'.
''(Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive).''
Three dice S, T, U with appropriate face values could satisfy
S < T, T < U and yet S > U
To be non-transitive.
;Notes:
* The order of numbers on the faces of a die is not relevant. For example, three faced die described with face numbers of 1, 2, 3 or 2, 1, 3 or any other permutation are equivalent. For the purposes of the task '''show only the permutation in lowest-first sorted order i.e. 1, 2, 3''' (and remove any of its perms).
* A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4
* '''Rotations''': Any rotation of non-transitive dice from an answer is also an answer. You may ''optionally'' compute and show only one of each such rotation sets, ideally the first when sorted in a natural way. If this option is used then prominently state in the output that rotations of results are also solutions.
;Task:
;====
Find all the ordered lists of ''three'' non-transitive dice S, T, U of the form
S < T, T < U and yet S > U; where the dice are selected from all ''four-faced die''
, (unique w.r.t the notes), possible by having selections from the integers
''one to four'' on any dies face.
Solution can be found by generating all possble individual die then testing all
possible permutations, (permutations are ordered), of three dice for
non-transitivity.
;Optional stretch goal:
Find lists of '''four''' non-transitive dice selected from the same possible dice from the non-stretch goal.
Show the results here, on this page.
;References:
* The Most Powerful Dice - Numberphile Video.
* Nontransitive dice - Wikipedia.
| from itertools import combinations_with_replacement as cmbr
from time import time
def dice_gen(n, faces, m):
dice = list(cmbr(faces, n))
succ = [set(j for j, b in enumerate(dice)
if sum((x>y) - (x<y) for x in a for y in b) > 0)
for a in dice]
def loops(seq):
s = succ[seq[-1]]
if len(seq) == m:
if seq[0] in s: yield seq
return
for d in (x for x in s if x > seq[0] and not x in seq):
yield from loops(seq + (d,))
yield from (tuple(''.join(dice[s]) for s in x)
for i, v in enumerate(succ)
for x in loops((i,)))
t = time()
for n, faces, loop_len in [(4, '1234', 3), (4, '1234', 4), (6, '123456', 3), (6, '1234567', 3)]:
for i, x in enumerate(dice_gen(n, faces, loop_len)): pass
print(f'{n}-sided, markings {faces}, loop length {loop_len}:')
print(f'\t{i + 1}*{loop_len} solutions, e.g. {" > ".join(x)} > [loop]')
t, t0 = time(), t
print(f'\ttime: {t - t0:.4f} seconds\n') |
Nonoblock | Python | Nonogram puzzle.
;Given:
* The number of cells in a row.
* The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.
;Task:
* show all possible positions.
* show the number of positions of the blocks for the following cases within the row.
* show all output on this page.
* use a "neat" diagram of the block positions.
;Enumerate the following configurations:
# '''5''' cells and '''[2, 1]''' blocks
# '''5''' cells and '''[]''' blocks (no blocks)
# '''10''' cells and '''[8]''' blocks
# '''15''' cells and '''[2, 3, 2, 3]''' blocks
# '''5''' cells and '''[2, 3]''' blocks (should give some indication of this not being possible)
;Example:
Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as:
|_|_|_|_|_| # 5 cells and [2, 1] blocks
And would expand to the following 3 possible rows of block positions:
|A|A|_|B|_|
|A|A|_|_|B|
|_|A|A|_|B|
Note how the sets of blocks are always separated by a space.
Note also that it is not necessary for each block to have a separate letter.
Output approximating
This:
|#|#|_|#|_|
|#|#|_|_|#|
|_|#|#|_|#|
This would also work:
##.#.
##..#
.##.#
;An algorithm:
* Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember).
* The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks.
* for each position of the LH block recursively compute the position of the rest of the blocks in the ''remaining'' space to the right of the current placement of the LH block.
(This is the algorithm used in the [[Nonoblock#Python]] solution).
;Reference:
* The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.
| def nonoblocks(blocks, cells):
if not blocks or blocks[0] == 0:
yield [(0, 0)]
else:
assert sum(blocks) + len(blocks)-1 <= cells, \
'Those blocks will not fit in those cells'
blength, brest = blocks[0], blocks[1:] # Deal with the first block of length
minspace4rest = sum(1+b for b in brest) # The other blocks need space
# Slide the start position from left to max RH index allowing for other blocks.
for bpos in range(0, cells - minspace4rest - blength + 1):
if not brest:
# No other blocks to the right so just yield this one.
yield [(bpos, blength)]
else:
# More blocks to the right so create a *sub-problem* of placing
# the brest blocks in the cells one space to the right of the RHS of
# this block.
offset = bpos + blength +1
nonoargs = (brest, cells - offset) # Pre-compute arguments to nonoargs
# recursive call to nonoblocks yields multiple sub-positions
for subpos in nonoblocks(*nonoargs):
# Remove the offset from sub block positions
rest = [(offset + bp, bl) for bp, bl in subpos]
# Yield this block plus sub blocks positions
vec = [(bpos, blength)] + rest
yield vec
def pblock(vec, cells):
'Prettyprints each run of blocks with a different letter A.. for each block of filled cells'
vector = ['_'] * cells
for ch, (bp, bl) in enumerate(vec, ord('A')):
for i in range(bp, bp + bl):
vector[i] = chr(ch) if vector[i] == '_' else'?'
return '|' + '|'.join(vector) + '|'
if __name__ == '__main__':
for blocks, cells in (
([2, 1], 5),
([], 5),
([8], 10),
([2, 3, 2, 3], 15),
# ([4, 3], 10),
# ([2, 1], 5),
# ([3, 1], 10),
([2, 3], 5),
):
print('\nConfiguration:\n %s # %i cells and %r blocks' % (pblock([], cells), cells, blocks))
print(' Possibilities:')
for i, vector in enumerate(nonoblocks(blocks, cells)):
print(' ', pblock(vector, cells))
print(' A total of %i Possible configurations.' % (i+1)) |
Nonogram solver | Python | nonogram is a puzzle that provides
numeric clues used to fill in a grid of cells,
establishing for each cell whether it is filled or not.
The puzzle solution is typically a picture of some kind.
Each row and column of a rectangular grid is annotated with the lengths
of its distinct runs of occupied cells.
Using only these lengths you should find one valid configuration
of empty and occupied cells, or show a failure message.
;Example
Problem: Solution:
. . . . . . . . 3 . # # # . . . . 3
. . . . . . . . 2 1 # # . # . . . . 2 1
. . . . . . . . 3 2 . # # # . . # # 3 2
. . . . . . . . 2 2 . . # # . . # # 2 2
. . . . . . . . 6 . . # # # # # # 6
. . . . . . . . 1 5 # . # # # # # . 1 5
. . . . . . . . 6 # # # # # # . . 6
. . . . . . . . 1 . . . . # . . . 1
. . . . . . . . 2 . . . # # . . . 2
1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3
2 1 5 1 2 1 5 1
The problem above could be represented by two lists of lists:
x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]]
y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]]
A more compact representation of the same problem uses strings,
where the letters represent the numbers, A=1, B=2, etc:
x = "C BA CB BB F AE F A B"
y = "AB CA AE GA E C D C"
;Task
For this task, try to solve the 4 problems below, read from a "nonogram_problems.txt" file that has this content
(the blank lines are separators):
C BA CB BB F AE F A B
AB CA AE GA E C D C
F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC
D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA
CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC
BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC
E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G
E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM
'''Extra credit''': generate nonograms with unique solutions, of desired height and width.
This task is the problem n.98 of the "99 Prolog Problems" by Werner Hett (also thanks to Paul Singleton for the idea and the examples).
; Related tasks
* [[Nonoblock]].
;See also
* Arc Consistency Algorithm
* http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell)
* http://twanvl.nl/blog/haskell/Nonograms (Haskell)
* http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
| from itertools import izip
def gen_row(w, s):
"""Create all patterns of a row or col that match given runs."""
def gen_seg(o, sp):
if not o:
return [[2] * sp]
return [[2] * x + o[0] + tail
for x in xrange(1, sp - len(o) + 2)
for tail in gen_seg(o[1:], sp - x)]
return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]
def deduce(hr, vr):
"""Fix inevitable value of cells, and propagate."""
def allowable(row):
return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)
def fits(a, b):
return all(x & y for x, y in izip(a, b))
def fix_col(n):
"""See if any value in a given column is fixed;
if so, mark its corresponding row for future fixup."""
c = [x[n] for x in can_do]
cols[n] = [x for x in cols[n] if fits(x, c)]
for i, x in enumerate(allowable(cols[n])):
if x != can_do[i][n]:
mod_rows.add(i)
can_do[i][n] &= x
def fix_row(n):
"""Ditto, for rows."""
c = can_do[n]
rows[n] = [x for x in rows[n] if fits(x, c)]
for i, x in enumerate(allowable(rows[n])):
if x != can_do[n][i]:
mod_cols.add(i)
can_do[n][i] &= x
def show_gram(m):
# If there's 'x', something is wrong.
# If there's '?', needs more work.
for x in m:
print " ".join("x#.?"[i] for i in x)
print
w, h = len(vr), len(hr)
rows = [gen_row(w, x) for x in hr]
cols = [gen_row(h, x) for x in vr]
can_do = map(allowable, rows)
# Initially mark all columns for update.
mod_rows, mod_cols = set(), set(xrange(w))
while mod_cols:
for i in mod_cols:
fix_col(i)
mod_cols = set()
for i in mod_rows:
fix_row(i)
mod_rows = set()
if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):
print "Solution would be unique" # but could be incorrect!
else:
print "Solution may not be unique, doing exhaustive search:"
# We actually do exhaustive search anyway. Unique solution takes
# no time in this phase anyway, but just in case there's no
# solution (could happen?).
out = [0] * h
def try_all(n = 0):
if n >= h:
for j in xrange(w):
if [x[j] for x in out] not in cols[j]:
return 0
show_gram(out)
return 1
sol = 0
for x in rows[n]:
out[n] = x
sol += try_all(n + 1)
return sol
n = try_all()
if not n:
print "No solution."
elif n == 1:
print "Unique solution."
else:
print n, "solutions."
print
def solve(p, show_runs=True):
s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]
for l in p.splitlines()]
if show_runs:
print "Horizontal runs:", s[0]
print "Vertical runs:", s[1]
deduce(s[0], s[1])
def main():
# Read problems from file.
fn = "nonogram_problems.txt"
for p in (x for x in open(fn).read().split("\n\n") if x):
solve(p)
print "Extra example not solvable by deduction alone:"
solve("B B A A\nB B A A")
print "Extra example where there is no solution:"
solve("B A A\nA A A")
main() |
Numbers which are the cube roots of the product of their proper divisors | Python | Example
Consider the number 24. Its proper divisors are: 1, 2, 3, 4, 6, 8 and 12. Their product is 13,824 and the cube root of this is 24. So 24 satisfies the definition in the task title.
;Task
Compute and show here the first '''50''' positive integers which are the cube roots of the product of their proper divisors.
Also show the '''500th''' and '''5,000th''' such numbers.
;Stretch
Compute and show the '''50,000th''' such number.
;Reference
* OEIS:A111398 - Numbers which are the cube roots of the product of their proper divisors.
;Note
OEIS considers 1 to be the first number in this sequence even though, strictly speaking, it has no proper divisors. Please therefore do likewise.
| ''' Rosetta code rosettacode.org/wiki/Numbers_which_are_the_cube_roots_of_the_product_of_their_proper_divisors '''
from functools import reduce
from sympy import divisors
FOUND = 0
for num in range(1, 1_000_000):
divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1
if num * num * num == divprod:
FOUND += 1
if FOUND <= 50:
print(f'{num:5}', end='\n' if FOUND % 10 == 0 else '')
if FOUND == 500:
print(f'\nFive hundreth: {num:,}')
if FOUND == 5000:
print(f'\nFive thousandth: {num:,}')
if FOUND == 50000:
print(f'\nFifty thousandth: {num:,}')
break
|
Numbers with equal rises and falls | Python | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
;Definition:
Given the decimal digits of the number are written as a series d:
:* A ''rise'' is an index i such that d(i) < d(i+1)
:* A ''fall'' is an index i such that d(i) > d(i+1)
;Examples:
:* The number '''726,169''' has '''3''' rises and '''2''' falls, so it isn't in the sequence.
:* The number '''83,548''' has '''2''' rises and '''2''' falls, so it is in the sequence.
;Task:
:* Print the first '''200''' numbers in the sequence
:* Show that the '''10 millionth''' (10,000,000th) number in the sequence is '''41,909,002'''
;See also:
* OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
;Related tasks:
* Esthetic numbers
| import itertools
def riseEqFall(num):
"""Check whether a number belongs to sequence A296712."""
height = 0
d1 = num % 10
num //= 10
while num:
d2 = num % 10
height += (d1<d2) - (d1>d2)
d1 = d2
num //= 10
return height == 0
def sequence(start, fn):
"""Generate a sequence defined by a function"""
num=start-1
while True:
num += 1
while not fn(num): num += 1
yield num
a296712 = sequence(1, riseEqFall)
# Generate the first 200 numbers
print("The first 200 numbers are:")
print(*itertools.islice(a296712, 200))
# Generate the 10,000,000th number
print("The 10,000,000th number is:")
print(*itertools.islice(a296712, 10000000-200-1, 10000000-200))
# It is necessary to subtract 200 from the index, because 200 numbers
# have already been consumed.
|
Numeric error propagation | Python | If '''f''', '''a''', and '''b''' are values with uncertainties sf, sa, and sb, and '''c''' is a constant;
then if '''f''' is derived from '''a''', '''b''', and '''c''' in the following ways,
then sf can be calculated as follows:
:;Addition/Subtraction
:* If f = a +- c, or f = c +- a then '''sf = sa'''
:* If f = a +- b then '''sf2 = sa2 + sb2'''
:;Multiplication/Division
:* If f = ca or f = ac then '''sf = |csa|'''
:* If f = ab or f = a / b then '''sf2 = f2( (sa / a)2 + (sb / b)2)'''
:;Exponentiation
:* If f = ac then '''sf = |fc(sa / a)|'''
Caution:
::This implementation of error propagation does not address issues of dependent and independent values. It is assumed that '''a''' and '''b''' are independent and so the formula for multiplication should not be applied to '''a*a''' for example. See the talk page for some of the implications of this issue.
;Task details:
# Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations.
# Given coordinates and their errors:x1 = 100 +- 1.1y1 = 50 +- 1.2x2 = 200 +- 2.2y2 = 100 +- 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula: d = (x1 - x2)2 + (y1 - y2)2
# Print and display both '''d''' and its error.
;References:
* A Guide to Error Propagation B. Keeney, 2005.
* Propagation of uncertainty Wikipedia.
;Related task:
* [[Quaternion type]]
| from collections import namedtuple
import math
class I(namedtuple('Imprecise', 'value, delta')):
'Imprecise type: I(value=0.0, delta=0.0)'
__slots__ = ()
def __new__(_cls, value=0.0, delta=0.0):
'Defaults to 0.0 ± delta'
return super().__new__(_cls, float(value), abs(float(delta)))
def reciprocal(self):
return I(1. / self.value, self.delta / (self.value**2))
def __str__(self):
'Shorter form of Imprecise as string'
return 'I(%g, %g)' % self
def __neg__(self):
return I(-self.value, self.delta)
def __add__(self, other):
if type(other) == I:
return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 )
try:
c = float(other)
except:
return NotImplemented
return I(self.value + c, self.delta)
def __sub__(self, other):
return self + (-other)
def __radd__(self, other):
return I.__add__(self, other)
def __mul__(self, other):
if type(other) == I:
#if id(self) == id(other):
# return self ** 2
a1,b1 = self
a2,b2 = other
f = a1 * a2
return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 )
try:
c = float(other)
except:
return NotImplemented
return I(self.value * c, self.delta * c)
def __pow__(self, other):
if type(other) == I:
return NotImplemented
try:
c = float(other)
except:
return NotImplemented
f = self.value ** c
return I(f, f * c * (self.delta / self.value))
def __rmul__(self, other):
return I.__mul__(self, other)
def __truediv__(self, other):
if type(other) == I:
return self.__mul__(other.reciprocal())
try:
c = float(other)
except:
return NotImplemented
return I(self.value / c, self.delta / c)
def __rtruediv__(self, other):
return other * self.reciprocal()
__div__, __rdiv__ = __truediv__, __rtruediv__
Imprecise = I
def distance(p1, p2):
x1, y1 = p1
x2, y2 = p2
return ((x1 - x2)**2 + (y1 - y2)**2)**0.5
x1 = I(100, 1.1)
x2 = I(200, 2.2)
y1 = I( 50, 1.2)
y2 = I(100, 2.3)
p1, p2 = (x1, y1), (x2, y2)
print("Distance between points\n p1: %s\n and p2: %s\n = %r" % (
p1, p2, distance(p1, p2))) |
Odd word problem | Python | Write a program that solves the odd word problem with the restrictions given below.
;Description:
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
* the words (sequence of consecutive letters) are delimited by one and only one punctuation,
* the stream will begin with a word,
* the words will be at least one letter long, and
* a full stop (a period, [.]) appears after, and only after, the last word.
;Example:
A stream with six words:
:: what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
:: what,si,the;gninaem,of:efil.
while observing the following restrictions:
# Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
# You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
# You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
;Test cases:
Work on both the "life" example given above, and also the text:
:: we,are;not,in,kansas;any,more.
| from sys import stdin, stdout
def char_in(): return stdin.read(1)
def char_out(c): stdout.write(c)
def odd(prev = lambda: None):
a = char_in()
if not a.isalpha():
prev()
char_out(a)
return a != '.'
# delay action until later, in the shape of a closure
def clos():
char_out(a)
prev()
return odd(clos)
def even():
while True:
c = char_in()
char_out(c)
if not c.isalpha(): return c != '.'
e = False
while odd() if e else even():
e = not e |
Odd word problem | Python from Scheme | Write a program that solves the odd word problem with the restrictions given below.
;Description:
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
* the words (sequence of consecutive letters) are delimited by one and only one punctuation,
* the stream will begin with a word,
* the words will be at least one letter long, and
* a full stop (a period, [.]) appears after, and only after, the last word.
;Example:
A stream with six words:
:: what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
:: what,si,the;gninaem,of:efil.
while observing the following restrictions:
# Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
# You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
# You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
;Test cases:
Work on both the "life" example given above, and also the text:
:: we,are;not,in,kansas;any,more.
| from sys import stdin, stdout
def char_in(): return stdin.read(1)
def char_out(c): stdout.write(c)
def odd():
a = char_in()
if a.isalpha():
r = odd()
char_out(a)
return r
# delay printing terminator until later, in the shape of a closure
def clos():
char_out(a)
return a != '.'
return clos
def even():
while True:
c = char_in()
char_out(c)
if not c.isalpha(): return c != '.'
e = False
while odd()() if e else even():
e = not e |
Odd word problem | Python 3.3+ | Write a program that solves the odd word problem with the restrictions given below.
;Description:
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
* the words (sequence of consecutive letters) are delimited by one and only one punctuation,
* the stream will begin with a word,
* the words will be at least one letter long, and
* a full stop (a period, [.]) appears after, and only after, the last word.
;Example:
A stream with six words:
:: what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
:: what,si,the;gninaem,of:efil.
while observing the following restrictions:
# Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
# You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
# You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
;Test cases:
Work on both the "life" example given above, and also the text:
:: we,are;not,in,kansas;any,more.
| from sys import stdin, stdout
def fwd(c):
if c.isalpha():
return [stdout.write(c), (yield from fwd((yield f)))][1]
else:
return c
def rev(c):
if c.isalpha():
return [(yield from rev((yield r))), stdout.write(c)][0]
else:
return c
def fw():
while True:
stdout.write((yield from fwd((yield r))))
def re():
while True:
stdout.write((yield from rev((yield f))))
f = fw()
r = re()
next(f)
next(r)
coro = f
while True:
c = stdin.read(1)
if not c:
break
coro = coro.send(c) |
Old Russian measure of length | Python | Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
''vershoks'', ''arshins'', ''sazhens'', ''versts'', ''meters'', ''centimeters'' and ''kilometers''.
;Also see:
:* Old Russian measure of length
| from sys import argv
unit2mult = {"arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254,
"fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254,
"meter": 1.0, "milia": 7467.6, "piad": 0.1778,
"sazhen": 2.1336, "tochka": 0.000254, "vershok": 0.04445,
"versta": 1066.8}
if __name__ == '__main__':
assert len(argv) == 3, 'ERROR. Need two arguments - number then units'
try:
value = float(argv[1])
except:
print('ERROR. First argument must be a (float) number')
raise
unit = argv[2]
assert unit in unit2mult, ( 'ERROR. Only know the following units: '
+ ' '.join(unit2mult.keys()) )
print("%g %s to:" % (value, unit))
for unt, mlt in sorted(unit2mult.items()):
print(' %10s: %g' % (unt, value * unit2mult[unit] / mlt)) |
Old lady swallowed a fly | Python | Present a program which emits the lyrics to the song ''I Knew an Old Lady Who Swallowed a Fly'', taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
| animals = [
("fly", "I don't know why she swallowed a fly, perhaps she'll die."),
("spider", "It wiggled and jiggled and tickled inside her."),
("bird", "How absurd, to swallow a bird."),
("cat", "Imagine that, she swallowed a cat."),
("dog", "What a hog, to swallow a dog."),
("goat", "She just opened her throat and swallowed a goat."),
("cow", "I don't know how she swallowed a cow."),
("horse", "She's dead, of course.")]
for i, (animal, lyric) in enumerate(animals):
print("There was an old lady who swallowed a {}.\n{}".format(animal, lyric))
if animal == "horse": break
for (predator, _), (prey, _) in zip(animals[i:0:-1], animals[i-1::-1]):
print("\tShe swallowed the {} to catch the {}".format(predator, prey))
if animal != "fly": print(animals[0][1]) # fly lyric
print() # new line |
One-time pad | Python | One-time pad, for encrypting and decrypting messages.
To keep it simple, we will be using letters only.
;Sub-Tasks:
* '''Generate''' the data for a One-time pad (user needs to specify a filename and length)
: The important part is to get "true random" numbers, e.g. from /dev/random
* '''encryption / decryption''' ( basically the same operation, much like [[Rot-13]] )
: For this step, much of [[Vigenere cipher]] could be reused,with the key to be read from the file containing the One-time pad.
* optional: '''management''' of One-time pads: list, mark as used, delete, etc.
: Somehow, the users needs to keep track which pad to use for which partner.
To support the management of pad-files:
* Such files have a file-extension ".1tp"
* Lines starting with "#" may contain arbitary meta-data (i.e. comments)
* Lines starting with "-" count as "used"
* Whitespace within the otp-data is ignored
For example, here is the data from Wikipedia:
# Example data - Wikipedia - 2014-11-13
-ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ
-HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK
YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK
CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX
QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR
CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE
EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE
;See also
* one time pad encryption in Python
* snapfractalpop - One-Time-Pad Command-Line-Utility (C).
* Crypt-OTP-2.00 on CPAN (Perl)
| """One-time pad using an XOR cipher. Requires Python >=3.6."""
import argparse
import itertools
import pathlib
import re
import secrets
import sys
# One-time pad file signature.
MAGIC = "#one-time pad"
def make_keys(n, size):
"""Generate ``n`` secure, random keys of ``size`` bytes."""
# We're generating and storing keys in their hexadecimal form to make
# one-time pad files a little more human readable and to ensure a key
# can not start with a hyphen.
return (secrets.token_hex(size) for _ in range(n))
def make_pad(name, pad_size, key_size):
"""Create a new one-time pad identified by the given name.
Args:
name (str): Unique one-time pad identifier.
pad_size (int): The number of keys (or pages) in the pad.
key_size (int): The number of bytes per key.
Returns:
The new one-time pad as a string.
"""
pad = [
MAGIC,
f"#name={name}",
f"#size={pad_size}",
*make_keys(pad_size, key_size),
]
return "\n".join(pad)
def xor(message, key):
"""Return ``message`` XOR-ed with ``key``.
Args:
message (bytes): Plaintext or cyphertext to be encrypted or decrypted.
key (bytes): Encryption and decryption key.
Returns:
Plaintext or cyphertext as a byte string.
"""
return bytes(mc ^ kc for mc, kc in zip(message, itertools.cycle(key)))
def use_key(pad):
"""Use the next available key from the given one-time pad.
Args:
pad (str): A one-time pad.
Returns:
(str, str) A two-tuple of updated pad and key.
"""
match = re.search(r"^[a-f0-9]+$", pad, re.MULTILINE)
if not match:
error("pad is all used up")
key = match.group()
pos = match.start()
return (f"{pad[:pos]}-{pad[pos:]}", key)
def log(msg):
"""Log a message."""
sys.stderr.write(msg)
sys.stderr.write("\n")
def error(msg):
"""Exit with an error message."""
sys.stderr.write(msg)
sys.stderr.write("\n")
sys.exit(1)
def write_pad(path, pad_size, key_size):
"""Write a new one-time pad to the given path.
Args:
path (pathlib.Path): Path to write one-time pad to.
length (int): Number of keys in the pad.
"""
if path.exists():
error(f"pad '{path}' already exists")
with path.open("w") as fd:
fd.write(make_pad(path.name, pad_size, key_size))
log(f"New one-time pad written to {path}")
def main(pad, message, outfile):
"""Encrypt or decrypt ``message`` using the given pad.
Args:
pad (pathlib.Path): Path to one-time pad.
message (bytes): Plaintext or ciphertext message to encrypt or decrypt.
outfile: File-like object to write to.
"""
if not pad.exists():
error(f"no such pad '{pad}'")
with pad.open("r") as fd:
if fd.readline().strip() != MAGIC:
error(f"file '{pad}' does not look like a one-time pad")
# Rewrites the entire one-time pad every time
with pad.open("r+") as fd:
updated, key = use_key(fd.read())
fd.seek(0)
fd.write(updated)
outfile.write(xor(message, bytes.fromhex(key)))
if __name__ == "__main__":
# Command line interface
parser = argparse.ArgumentParser(description="One-time pad.")
parser.add_argument(
"pad",
help=(
"Path to one-time pad. If neither --encrypt or --decrypt "
"are given, will create a new pad."
),
)
parser.add_argument(
"--length",
type=int,
default=10,
help="Pad size. Ignored if --encrypt or --decrypt are given. Defaults to 10.",
)
parser.add_argument(
"--key-size",
type=int,
default=64,
help="Key size in bytes. Ignored if --encrypt or --decrypt are given. Defaults to 64.",
)
parser.add_argument(
"-o",
"--outfile",
type=argparse.FileType("wb"),
default=sys.stdout.buffer,
help=(
"Write encoded/decoded message to a file. Ignored if --encrypt or "
"--decrypt is not given. Defaults to stdout."
),
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--encrypt",
metavar="FILE",
type=argparse.FileType("rb"),
help="Encrypt FILE using the next available key from pad.",
)
group.add_argument(
"--decrypt",
metavar="FILE",
type=argparse.FileType("rb"),
help="Decrypt FILE using the next available key from pad.",
)
args = parser.parse_args()
if args.encrypt:
message = args.encrypt.read()
elif args.decrypt:
message = args.decrypt.read()
else:
message = None
# Sometimes necessary if message came from stdin
if isinstance(message, str):
message = message.encode()
pad = pathlib.Path(args.pad).with_suffix(".1tp")
if message:
main(pad, message, args.outfile)
else:
write_pad(pad, args.length, args.key_size)
|
One of n lines in a file | Python | A method of choosing a line randomly from a file:
::* Without reading the file more than once
::* When substantial parts of the file cannot be held in memory
::* Without knowing how many lines are in the file
Is to:
::* keep the first line of the file as a possible choice, then
::* Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
::* Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
::* ...
::* Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
::* Return the computed possible choice when no further lines exist in the file.
;Task:
# Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run.
# Use one_of_n in a ''simulation'' to find what would be the chosen line of a 10-line file simulated 1,000,000 times.
# Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| from random import randrange
try:
range = xrange
except: pass
def one_of_n(lines): # lines is any iterable
choice = None
for i, line in enumerate(lines):
if randrange(i+1) == 0:
choice = line
return choice
def one_of_n_test(n=10, trials=1000000):
bins = [0] * n
if n:
for i in range(trials):
bins[one_of_n(range(n))] += 1
return bins
print(one_of_n_test()) |
OpenWebNet password | Python | Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist
'''Note:''' Factory default password is '12345'. Changing it is highly recommended !
conversation goes as follows
- *#*1##
- *99*0##
- *#603356072##
at which point a password should be sent back, calculated from the "password open" that is set in the gateway, and the nonce that was just sent
- *#25280520##
- *#*1##
| def ownCalcPass (password, nonce, test=False) :
start = True
num1 = 0
num2 = 0
password = int(password)
if test:
print("password: %08x" % (password))
for c in nonce :
if c != "0":
if start:
num2 = password
start = False
if test:
print("c: %s num1: %08x num2: %08x" % (c, num1, num2))
if c == '1':
num1 = (num2 & 0xFFFFFF80) >> 7
num2 = num2 << 25
elif c == '2':
num1 = (num2 & 0xFFFFFFF0) >> 4
num2 = num2 << 28
elif c == '3':
num1 = (num2 & 0xFFFFFFF8) >> 3
num2 = num2 << 29
elif c == '4':
num1 = num2 << 1
num2 = num2 >> 31
elif c == '5':
num1 = num2 << 5
num2 = num2 >> 27
elif c == '6':
num1 = num2 << 12
num2 = num2 >> 20
elif c == '7':
num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 )
num2 = ( num2 & 0xFF000000 ) >> 8
elif c == '8':
num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 )
num2 = (num2 & 0x00FF0000) >> 8
elif c == '9':
num1 = ~num2
else :
num1 = num2
num1 &= 0xFFFFFFFF
num2 &= 0xFFFFFFFF
if (c not in "09"):
num1 |= num2
if test:
print(" num1: %08x num2: %08x" % (num1, num2))
num2 = num1
return num1
def test_passwd_calc(passwd, nonce, expected):
res = ownCalcPass(passwd, nonce, False)
m = passwd+' '+nonce+' '+str(res)+' '+str(expected)
if res == int(expected) :
print('PASS '+m)
else :
print('FAIL '+m)
if __name__ == '__main__':
test_passwd_calc('12345','603356072','25280520')
test_passwd_calc('12345','410501656','119537670')
test_passwd_calc('12345','630292165','4269684735')
|
Operator precedence | Python | Operators in C and C++}}
;Task:
Provide a list of [[wp:order of operations|precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| See [http://docs.python.org/py3k/reference/expressions.html?highlight=precedence#summary this table] and the whole page for details on Python version 3.x
An excerpt of which is this table:
{| class="wikitable"
|-
! Precedence
! Operator
! Description
|-
! lowest
| '''lambda'''
| Lambda expression
|-
!
| '''if – else'''
| Conditional expression
|-
!
| '''or'''
| <nowiki>Boolean OR</nowiki>
|-
!
| '''<nowiki>and</nowiki>'''
| Boolean AND
|-
!
| '''not x'''
| Boolean NOT
|-
!
| '''in, not in, is, is not, <, <=, >, >=, !=, =='''
| Comparisons, including membership tests and identity tests,
|-
!
| '''<nowiki>|</nowiki>'''
| Bitwise OR
|-
!
| '''^'''
| Bitwise XOR
|-
!
| '''<nowiki>&</nowiki>'''
| <nowiki>Bitwise AND</nowiki>
|-
!
| '''<nowiki><<, >></nowiki>'''
| <nowiki>Shifts</nowiki>
|-
!
| '''<nowiki>+, -</nowiki>'''
| Addition and subtraction
|-
!
| '''<nowiki>*, /, //, %</nowiki>'''
| <nowiki>Multiplication, division, remainder [1]</nowiki>
|-
!
| '''+x, -x, ~x'''
| Positive, negative, bitwise NOT
|-
!
| '''**'''
| Exponentiation [2]
|-
!
| '''x[index], x[index:index], x(arguments...), x.attribute'''
| <nowiki>Subscription, slicing, call, attribute reference</nowiki>
|-
! highest
| '''<nowiki>(expressions...), [expressions...], {key:datum...}, {expressions...}</nowiki>'''
| Binding or tuple display, list display, dictionary display, set display
|}
;Footnotes:
# The <code>%</code> operator is also used for string formatting; the same precedence applies.
# The power operator <code>**</code> binds less tightly than an arithmetic or bitwise unary operator on its right, that is, <code>2**-1</code> is <code>0.5</code>.
|
Palindrome dates | Python 3.7 | Today ('''2020-02-02''', at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the '''yyyy-mm-dd''' format but, unusually, also for countries which use the '''dd-mm-yyyy''' format.
;Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the '''yyyy-mm-dd''' format.
| '''Palindrome dates'''
from functools import reduce
from itertools import chain
from datetime import date
# palinDay :: Integer -> [ISO Date]
def palinDay(y):
'''A possibly empty list containing the palindromic
date for the given year, if such a date exists.
'''
[m, d] = [undigits(pair) for pair in chunksOf(2)(
reversedDecimalDigits(y)
)]
return [] if (
1 > m or m > 12 or 31 < d
) else validISODate((y, m, d))
# --------------------------TEST---------------------------
# main :: IO ()
def main():
'''Count and samples of palindromic dates [2021..9999]
'''
palinDates = list(chain.from_iterable(
map(palinDay, range(2021, 10000))
))
for x in [
'Count of palindromic dates [2021..9999]:',
len(palinDates),
'\nFirst 15:',
'\n'.join(palinDates[0:15]),
'\nLast 15:',
'\n'.join(palinDates[-15:])
]:
print(x)
# -------------------------GENERIC-------------------------
# Just :: a -> Maybe a
def Just(x):
'''Constructor for an inhabited Maybe (option type) value.
Wrapper containing the result of a computation.
'''
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
# Nothing :: Maybe a
def Nothing():
'''Constructor for an empty Maybe (option type) value.
Empty wrapper returned where a computation is not possible.
'''
return {'type': 'Maybe', 'Nothing': True}
# 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 []
# reversedDecimalDigits :: Int -> [Int]
def reversedDecimalDigits(n):
'''A list of the decimal digits of n,
in reversed sequence.
'''
return unfoldr(
lambda x: Nothing() if (
0 == x
) else Just(divmod(x, 10))
)(n)
# unDigits :: [Int] -> Int
def undigits(xs):
'''An integer derived from a list of decimal digits
'''
return reduce(lambda a, x: a * 10 + x, xs, 0)
# unfoldr(lambda x: Just((x, x - 1)) if 0 != x else Nothing())(10)
# -> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
# unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
def unfoldr(f):
'''Dual to reduce or foldr.
Where catamorphism reduces a list to a summary value,
the anamorphic unfoldr builds a list from a seed value.
As long as f returns Just(a, b), a is prepended to the list,
and the residual b is used as the argument for the next
application of f.
When f returns Nothing, the completed list is returned.
'''
def go(v):
xr = v, v
xs = []
while True:
mb = f(xr[0])
if mb.get('Nothing'):
return xs
else:
xr = mb.get('Just')
xs.append(xr[1])
return xs
return go
# validISODate :: (Int, Int, Int) -> [Date]
def validISODate(ymd):
'''A possibly empty list containing the
ISO8601 string for a date, if that date exists.
'''
try:
return [date(*ymd).isoformat()]
except ValueError:
return []
# MAIN ---
if __name__ == '__main__':
main() |
Palindromic gapful numbers | Python | Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as '''gapful numbers'''.
''Evenly divisible'' means divisible with no remainder.
All one- and two-digit numbers have this property and are trivially excluded. Only
numbers >= '''100''' will be considered for this Rosetta Code task.
;Example:
'''1037''' is a '''gapful''' number because it is evenly divisible by the
number '''17''' which is formed by the first and last decimal digits
of '''1037'''.
A palindromic number is (for this task, a positive integer expressed in base ten), when the number is
reversed, is the same as the original number.
;Task:
:* Show (nine sets) the first '''20''' palindromic gapful numbers that ''end'' with:
:::* the digit '''1'''
:::* the digit '''2'''
:::* the digit '''3'''
:::* the digit '''4'''
:::* the digit '''5'''
:::* the digit '''6'''
:::* the digit '''7'''
:::* the digit '''8'''
:::* the digit '''9'''
:* Show (nine sets, like above) of palindromic gapful numbers:
:::* the last '''15''' palindromic gapful numbers (out of '''100''')
:::* the last '''10''' palindromic gapful numbers (out of '''1,000''') {optional}
For other ways of expressing the (above) requirements, see the ''discussion'' page.
;Note:
All palindromic gapful numbers are divisible by eleven.
;Related tasks:
:* palindrome detection.
:* gapful numbers.
;Also see:
:* The OEIS entry: A108343 gapful numbers.
| from itertools import count
from pprint import pformat
import re
import heapq
def pal_part_gen(odd=True):
for i in count(1):
fwd = str(i)
rev = fwd[::-1][1:] if odd else fwd[::-1]
yield int(fwd + rev)
def pal_ordered_gen():
yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False))
def is_gapful(x):
return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0)
if __name__ == '__main__':
start = 100
for mx, last in [(20, 20), (100, 15), (1_000, 10)]:
print(f"\nLast {last} of the first {mx} binned-by-last digit "
f"gapful numbers >= {start}")
bin = {i: [] for i in range(1, 10)}
gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i))
while any(len(val) < mx for val in bin.values()):
g = next(gen)
val = bin[g % 10]
if len(val) < mx:
val.append(g)
b = {k:v[-last:] for k, v in bin.items()}
txt = pformat(b, width=220)
print('', re.sub(r"[{},\[\]]", '', txt)) |
Pancake numbers | Python 3.7 | Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers.
The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.
[[Sorting_algorithms/Pancake_sort]] actually performs the sort some giving the number of flips used. How do these compare with p(n)?
Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16).
;References
# Bill Gates and the pancake problem
# A058986
| """Pancake numbers. Requires Python>=3.7."""
import time
from collections import deque
from operator import itemgetter
from typing import Tuple
Pancakes = Tuple[int, ...]
def flip(pancakes: Pancakes, position: int) -> Pancakes:
"""Flip the stack of pancakes at the given position."""
return tuple([*reversed(pancakes[:position]), *pancakes[position:]])
def pancake(n: int) -> Tuple[Pancakes, int]:
"""Return the nth pancake number."""
init_stack = tuple(range(1, n + 1))
stack_flips = {init_stack: 0}
queue = deque([init_stack])
while queue:
stack = queue.popleft()
flips = stack_flips[stack] + 1
for i in range(2, n + 1):
flipped = flip(stack, i)
if flipped not in stack_flips:
stack_flips[flipped] = flips
queue.append(flipped)
return max(stack_flips.items(), key=itemgetter(1))
if __name__ == "__main__":
start = time.time()
for n in range(1, 10):
pancakes, p = pancake(n)
print(f"pancake({n}) = {p:>2}. Example: {list(pancakes)}")
print(f"\nTook {time.time() - start:.3} seconds.")
|
Pangram checker | Python | A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: ''The quick brown fox jumps over the lazy dog''.
;Task:
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
;Related tasks:
:* determine if a string has all the same characters
:* determine if a string has all unique characters
| import string, sys
if sys.version_info[0] < 3:
input = raw_input
def ispangram(sentence, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
return alphaset <= set(sentence.lower())
print ( ispangram(input('Sentence: ')) ) |
Paraffins | Python | This organic chemistry task is essentially to implement a tree enumeration algorithm.
;Task:
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds.
In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with '''n''' carbon atoms share the empirical formula CnH2n+2
But for all '''n''' >= 4 there are several distinct molecules ("isomers") with the same formula but different structures.
The number of isomers rises rather rapidly when '''n''' increases.
In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.
;Example:
With '''n''' = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with '''n''' = 4 there are two configurations:
:::* a straight chain: (CH3)(CH2)(CH2)(CH3)
:::* a branched chain: (CH3)(CH(CH3))(CH3)
Due to bond rotations, it doesn't matter which direction the branch points in.
The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.
The input is the number '''n''' of carbon atoms of a molecule (for instance '''17''').
The output is how many different different paraffins there are with '''n''' carbon atoms (for instance 24,894 if '''n''' = 17).
The sequence of those results is visible in the OEIS entry:
::: A00602: number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers.
The sequence is (the index starts from zero, and represents the number of carbon atoms):
1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,
24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,
36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,
10660307791, 27711253769, ...
;Extra credit:
Show the paraffins in some way.
A flat 1D representation, with arrays or lists is enough, for instance:
*Main> all_paraffins 1
[CCP H H H H]
*Main> all_paraffins 2
[BCP (C H H H) (C H H H)]
*Main> all_paraffins 3
[CCP H H (C H H H) (C H H H)]
*Main> all_paraffins 4
[BCP (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 5
[CCP H H (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 6
[BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),
BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),
BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),
CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]
Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):
methane ethane propane isobutane
H H H H H H H H H
| | | | | | | | |
H - C - H H - C - C - H H - C - C - C - H H - C - C - C - H
| | | | | | | | |
H H H H H H H | H
|
H - C - H
|
H
;Links:
* A paper that explains the problem and its solution in a functional language:
http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf
* A Haskell implementation:
https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs
* A Scheme implementation:
http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm
* A Fortress implementation: (this site has been closed)
http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
| This version only counts different paraffins. The multi-precision integers of Python avoid overflows.
|
Paraffins | Python from C | This organic chemistry task is essentially to implement a tree enumeration algorithm.
;Task:
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds.
In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with '''n''' carbon atoms share the empirical formula CnH2n+2
But for all '''n''' >= 4 there are several distinct molecules ("isomers") with the same formula but different structures.
The number of isomers rises rather rapidly when '''n''' increases.
In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.
;Example:
With '''n''' = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with '''n''' = 4 there are two configurations:
:::* a straight chain: (CH3)(CH2)(CH2)(CH3)
:::* a branched chain: (CH3)(CH(CH3))(CH3)
Due to bond rotations, it doesn't matter which direction the branch points in.
The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.
The input is the number '''n''' of carbon atoms of a molecule (for instance '''17''').
The output is how many different different paraffins there are with '''n''' carbon atoms (for instance 24,894 if '''n''' = 17).
The sequence of those results is visible in the OEIS entry:
::: A00602: number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers.
The sequence is (the index starts from zero, and represents the number of carbon atoms):
1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,
24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,
36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,
10660307791, 27711253769, ...
;Extra credit:
Show the paraffins in some way.
A flat 1D representation, with arrays or lists is enough, for instance:
*Main> all_paraffins 1
[CCP H H H H]
*Main> all_paraffins 2
[BCP (C H H H) (C H H H)]
*Main> all_paraffins 3
[CCP H H (C H H H) (C H H H)]
*Main> all_paraffins 4
[BCP (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 5
[CCP H H (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 6
[BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),
BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),
BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),
CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]
Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):
methane ethane propane isobutane
H H H H H H H H H
| | | | | | | | |
H - C - H H - C - C - H H - C - C - C - H H - C - C - C - H
| | | | | | | | |
H H H H H H H | H
|
H - C - H
|
H
;Links:
* A paper that explains the problem and its solution in a functional language:
http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf
* A Haskell implementation:
https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs
* A Scheme implementation:
http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm
* A Fortress implementation: (this site has been closed)
http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
| from itertools import count, chain, tee, islice, cycle
from fractions import Fraction
from sys import setrecursionlimit
setrecursionlimit(5000)
def frac(a,b): return a//b if a%b == 0 else Fraction(a,b)
# infinite polynomial class
class Poly:
def __init__(self, gen = None):
self.gen, self.source = (None, gen) if type(gen) is Poly \
else (gen, None)
def __iter__(self):
# We're essentially tee'ing it everytime the iterator
# is, well, iterated. This may be excessive.
return Poly(self)
def getsource(self):
if self.gen == None:
s = self.source
s.getsource()
s.gen, self.gen = tee(s.gen, 2)
def next(self):
self.getsource()
return next(self.gen)
__next__ = next
# Overload "<<" as stream input operator. Hey, C++ does it.
def __lshift__(self, a): self.gen = a
# The other operators are pretty much what one would expect
def __neg__(self): return Poly(-x for x in self)
def __sub__(a, b): return a + (-b)
def __rsub__(a, n):
a = Poly(a)
def gen():
yield(n - next(a))
for x in a: yield(-x)
return Poly(gen())
def __add__(a, b):
if type(b) is Poly:
return Poly(x + y for (x,y) in zip(a,b))
a = Poly(a)
def gen():
yield(next(a) + b)
for x in a: yield(x)
return Poly(gen())
def __radd__(a,b):
return a + b
def __mul__(a,b):
if not type(b) is Poly:
return Poly(x*b for x in a)
def gen():
s = Poly(cycle([0]))
for y in b:
s += y*a
yield(next(s))
return Poly(gen())
def __rmul__(a,b): return a*b
def __truediv__(a,b):
if not type(b) is Poly:
return Poly(frac(x, b) for x in a)
a, b = Poly(a), Poly(b)
def gen():
r, bb = a,next(b)
while True:
aa = next(r)
q = frac(aa, bb)
yield(q)
r -= q*b
return Poly(gen())
def repl(self, n):
def gen():
for x in self:
yield(x)
for i in range(n-1): yield(0)
return Poly(gen())
def __pow__(self, n):
return Poly(self) if n == 1 else self * self**(n-1)
def S2(a,b): return (a*a + b)/2
def S4(a,b,c,d): return a**4/24 + a**2*b/4 + a*c/3 + b**2/8 + d/4
x1 = Poly()
x2 = x1.repl(2)
x3 = x1.repl(3)
x4 = x1.repl(4)
x1 << chain([1], (x1**3 + 3*x1*x2 + 2*x3)/6)
a598 = x1
a678 = Poly(chain([0], S4(x1, x2, x3, x4)))
a599 = S2(x1 - 1, x2 - 1)
a602 = a678 - a599 + x2
for n,x in zip(count(0), islice(a602, 500)): print(n,x) |
Parse an IP Address | Python 3.5 | The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6.
Taking the following as inputs:
::: {| border="5" cellspacing="0" cellpadding=2
|-
|127.0.0.1
|The "localhost" IPv4 address
|-
|127.0.0.1:80
|The "localhost" IPv4 address, with a specified port (80)
|-
|::1
|The "localhost" IPv6 address
|-
|[::1]:80
|The "localhost" IPv6 address, with a specified port (80)
|-
|2605:2700:0:3::4713:93e3
|Rosetta Code's primary server's public IPv6 address
|-
|[2605:2700:0:3::4713:93e3]:80
|Rosetta Code's primary server's public IPv6 address, with a specified port (80)
|}
;Task:
Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any.
In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified.
;Example:
'''127.0.0.1''' has the address number '''7F000001''' (2130706433 decimal)
in the ipv4 address space.
'''::ffff:127.0.0.1''' represents the same address in the ipv6 address space where it has the
address number '''FFFF7F000001''' (281472812449793 decimal).
'''::1''' has address number '''1''' and serves the same purpose in the ipv6 address
space that '''127.0.0.1''' serves in the ipv4 address space.
| from ipaddress import ip_address
from urllib.parse import urlparse
tests = [
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:80",
"::192.168.0.1",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80" ]
def parse_ip_port(netloc):
try:
ip = ip_address(netloc)
port = None
except ValueError:
parsed = urlparse('//{}'.format(netloc))
ip = ip_address(parsed.hostname)
port = parsed.port
return ip, port
for address in tests:
ip, port = parse_ip_port(address)
hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))
print("{:39s} {:>32s} IPv{} port={}".format(
str(ip), hex_ip, ip.version, port )) |
Parsing/RPN calculator algorithm | Python | Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed ''as a table''.
* Assume an input of a correct, space separated, string of tokens of an RPN expression
* Test with the RPN expression generated from the [[Parsing/Shunting-yard algorithm]] task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
* Print or display the output here
;Notes:
* '''^''' means exponentiation in the expression above.
* '''/''' means division.
;See also:
* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.
* Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).
* [[Parsing/RPN to infix conversion]].
* [[Arithmetic evaluation]].
| def op_pow(stack):
b = stack.pop(); a = stack.pop()
stack.append( a ** b )
def op_mul(stack):
b = stack.pop(); a = stack.pop()
stack.append( a * b )
def op_div(stack):
b = stack.pop(); a = stack.pop()
stack.append( a / b )
def op_add(stack):
b = stack.pop(); a = stack.pop()
stack.append( a + b )
def op_sub(stack):
b = stack.pop(); a = stack.pop()
stack.append( a - b )
def op_num(stack, num):
stack.append( num )
ops = {
'^': op_pow,
'*': op_mul,
'/': op_div,
'+': op_add,
'-': op_sub,
}
def get_input(inp = None):
'Inputs an expression and returns list of tokens'
if inp is None:
inp = input('expression: ')
tokens = inp.strip().split()
return tokens
def rpn_calc(tokens):
stack = []
table = ['TOKEN,ACTION,STACK'.split(',')]
for token in tokens:
if token in ops:
action = 'Apply op to top of stack'
ops[token](stack)
table.append( (token, action, ' '.join(str(s) for s in stack)) )
else:
action = 'Push num onto top of stack'
op_num(stack, eval(token))
table.append( (token, action, ' '.join(str(s) for s in stack)) )
return table
if __name__ == '__main__':
rpn = '3 4 2 * 1 5 - 2 3 ^ ^ / +'
print( 'For RPN expression: %r\n' % rpn )
rp = rpn_calc(get_input(rpn))
maxcolwidths = [max(len(y) for y in x) for x in zip(*rp)]
row = rp[0]
print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
for row in rp[1:]:
print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
print('\n The final output value is: %r' % rp[-1][2]) |
Parsing/RPN to infix conversion | Python | Create a program that takes an infix notation.
* Assume an input of a correct, space separated, string of tokens
* Generate a space separated output string representing the same expression in infix notation
* Show how the major datastructure of your algorithm changes with each new token parsed.
* Test with the following input RPN strings then print and display the output here.
:::::{| class="wikitable"
! RPN input !! sample output
|- || align="center"
| 3 4 2 * 1 5 - 2 3 ^ ^ / +|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
|- || align="center"
| 1 2 + 3 4 + ^ 5 6 + ^|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
|}
* Operator precedence and operator associativity is given in this table:
::::::::{| class="wikitable"
! operator !! associativity !! operation
|- || align="center"
| ^ || 4 || right || exponentiation
|- || align="center"
| * || 3 || left || multiplication
|- || align="center"
| / || 3 || left || division
|- || align="center"
| + || 2 || left || addition
|- || align="center"
| - || 2 || left || subtraction
|}
;See also:
* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.
* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.
* Postfix to infix from the RubyQuiz site.
| """
>>> # EXAMPLE USAGE
>>> result = rpn_to_infix('3 4 2 * 1 5 - 2 3 ^ ^ / +', VERBOSE=True)
TOKEN STACK
3 ['3']
4 ['3', '4']
2 ['3', '4', '2']
* ['3', Node('2','*','4')]
1 ['3', Node('2','*','4'), '1']
5 ['3', Node('2','*','4'), '1', '5']
- ['3', Node('2','*','4'), Node('5','-','1')]
2 ['3', Node('2','*','4'), Node('5','-','1'), '2']
3 ['3', Node('2','*','4'), Node('5','-','1'), '2', '3']
^ ['3', Node('2','*','4'), Node('5','-','1'), Node('3','^','2')]
^ ['3', Node('2','*','4'), Node(Node('3','^','2'),'^',Node('5','-','1'))]
/ ['3', Node(Node(Node('3','^','2'),'^',Node('5','-','1')),'/',Node('2','*','4'))]
+ [Node(Node(Node(Node('3','^','2'),'^',Node('5','-','1')),'/',Node('2','*','4')),'+','3')]
"""
prec_dict = {'^':4, '*':3, '/':3, '+':2, '-':2}
assoc_dict = {'^':1, '*':0, '/':0, '+':0, '-':0}
class Node:
def __init__(self,x,op,y=None):
self.precedence = prec_dict[op]
self.assocright = assoc_dict[op]
self.op = op
self.x,self.y = x,y
def __str__(self):
"""
Building an infix string that evaluates correctly is easy.
Building an infix string that looks pretty and evaluates
correctly requires more effort.
"""
# easy case, Node is unary
if self.y == None:
return '%s(%s)'%(self.op,str(self.x))
# determine left side string
str_y = str(self.y)
if self.y < self or \
(self.y == self and self.assocright) or \
(str_y[0] is '-' and self.assocright):
str_y = '(%s)'%str_y
# determine right side string and operator
str_x = str(self.x)
str_op = self.op
if self.op is '+' and not isinstance(self.x, Node) and str_x[0] is '-':
str_x = str_x[1:]
str_op = '-'
elif self.op is '-' and not isinstance(self.x, Node) and str_x[0] is '-':
str_x = str_x[1:]
str_op = '+'
elif self.x < self or \
(self.x == self and not self.assocright and \
getattr(self.x, 'op', 1) != getattr(self, 'op', 2)):
str_x = '(%s)'%str_x
return ' '.join([str_y, str_op, str_x])
def __repr__(self):
"""
>>> repr(Node('3','+','4')) == repr(eval(repr(Node('3','+','4'))))
True
"""
return 'Node(%s,%s,%s)'%(repr(self.x), repr(self.op), repr(self.y))
def __lt__(self, other):
if isinstance(other, Node):
return self.precedence < other.precedence
return self.precedence < prec_dict.get(other,9)
def __gt__(self, other):
if isinstance(other, Node):
return self.precedence > other.precedence
return self.precedence > prec_dict.get(other,9)
def __eq__(self, other):
if isinstance(other, Node):
return self.precedence == other.precedence
return self.precedence > prec_dict.get(other,9)
def rpn_to_infix(s, VERBOSE=False):
"""
converts rpn notation to infix notation for string s
"""
if VERBOSE : print('TOKEN STACK')
stack=[]
for token in s.replace('^','^').split():
if token in prec_dict:
stack.append(Node(stack.pop(),token,stack.pop()))
else:
stack.append(token)
# can't use \t in order to make global docstring pass doctest
if VERBOSE : print(token+' '*(7-len(token))+repr(stack))
return str(stack[0])
strTest = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
strResult = rpn_to_infix(strTest, VERBOSE=False)
print ("Input: ",strTest)
print ("Output:",strResult)
print()
strTest = "1 2 + 3 4 + ^ 5 6 + ^"
strResult = rpn_to_infix(strTest, VERBOSE=False)
print ("Input: ",strTest)
print ("Output:",strResult)
|
Parsing/Shunting-yard algorithm | Python | Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
* Assume an input of a correct, space separated, string of tokens representing an infix expression
* Generate a space separated output string representing the RPN
* Test with the input string:
:::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
* print and display the output here.
* Operator precedence is given in this table:
:{| class="wikitable"
! operator !! associativity !! operation
|- || align="center"
| ^ || 4 || right || exponentiation
|- || align="center"
| * || 3 || left || multiplication
|- || align="center"
| / || 3 || left || division
|- || align="center"
| + || 2 || left || addition
|- || align="center"
| - || 2 || left || subtraction
|}
;Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
;Note
The handling of functions and arguments is not required.
;See also:
* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.
* [[Parsing/RPN to infix conversion]].
| from collections import namedtuple
from pprint import pprint as pp
OpInfo = namedtuple('OpInfo', 'prec assoc')
L, R = 'Left Right'.split()
ops = {
'^': OpInfo(prec=4, assoc=R),
'*': OpInfo(prec=3, assoc=L),
'/': OpInfo(prec=3, assoc=L),
'+': OpInfo(prec=2, assoc=L),
'-': OpInfo(prec=2, assoc=L),
'(': OpInfo(prec=9, assoc=L),
')': OpInfo(prec=0, assoc=L),
}
NUM, LPAREN, RPAREN = 'NUMBER ( )'.split()
def get_input(inp = None):
'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'
if inp is None:
inp = input('expression: ')
tokens = inp.strip().split()
tokenvals = []
for token in tokens:
if token in ops:
tokenvals.append((token, ops[token]))
#elif token in (LPAREN, RPAREN):
# tokenvals.append((token, token))
else:
tokenvals.append((NUM, token))
return tokenvals
def shunting(tokenvals):
outq, stack = [], []
table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]
for token, val in tokenvals:
note = action = ''
if token is NUM:
action = 'Add number to output'
outq.append(val)
table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
elif token in ops:
t1, (p1, a1) = token, val
v = t1
note = 'Pop ops from stack to output'
while stack:
t2, (p2, a2) = stack[-1]
if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):
if t1 != RPAREN:
if t2 != LPAREN:
stack.pop()
action = '(Pop op)'
outq.append(t2)
else:
break
else:
if t2 != LPAREN:
stack.pop()
action = '(Pop op)'
outq.append(t2)
else:
stack.pop()
action = '(Pop & discard "(")'
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
break
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
v = note = ''
else:
note = ''
break
note = ''
note = ''
if t1 != RPAREN:
stack.append((token, val))
action = 'Push op token to stack'
else:
action = 'Discard ")"'
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
note = 'Drain stack to output'
while stack:
v = ''
t2, (p2, a2) = stack[-1]
action = '(Pop op)'
stack.pop()
outq.append(t2)
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
v = note = ''
return table
if __name__ == '__main__':
infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'
print( 'For infix expression: %r\n' % infix )
rp = shunting(get_input(infix))
maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]
row = rp[0]
print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
for row in rp[1:]:
print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
print('\n The final output RPN is: %r' % rp[-1][2]) |
Pascal's triangle/Puzzle | Python 2.4+ | This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the middle one is the sum of the other two (that is, Y = X + Z).
;Task:
Write a program to find a solution to this puzzle.
| # Pyramid solver
# [151]
# [ ] [ ]
# [ 40] [ ] [ ]
# [ ] [ ] [ ] [ ]
#[ X ] [ 11] [ Y ] [ 4 ] [ Z ]
# X -Y + Z = 0
def combine( snl, snr ):
cl = {}
if isinstance(snl, int):
cl['1'] = snl
elif isinstance(snl, string):
cl[snl] = 1
else:
cl.update( snl)
if isinstance(snr, int):
n = cl.get('1', 0)
cl['1'] = n + snr
elif isinstance(snr, string):
n = cl.get(snr, 0)
cl[snr] = n + 1
else:
for k,v in snr.items():
n = cl.get(k, 0)
cl[k] = n+v
return cl
def constrain(nsum, vn ):
nn = {}
nn.update(vn)
n = nn.get('1', 0)
nn['1'] = n - nsum
return nn
def makeMatrix( constraints ):
vmap = set()
for c in constraints:
vmap.update( c.keys())
vmap.remove('1')
nvars = len(vmap)
vmap = sorted(vmap) # sort here so output is in sorted order
mtx = []
for c in constraints:
row = []
for vv in vmap:
row.append(float(c.get(vv, 0)))
row.append(-float(c.get('1',0)))
mtx.append(row)
if len(constraints) == nvars:
print 'System appears solvable'
elif len(constraints) < nvars:
print 'System is not solvable - needs more constraints.'
return mtx, vmap
def SolvePyramid( vl, cnstr ):
vl.reverse()
constraints = [cnstr]
lvls = len(vl)
for lvln in range(1,lvls):
lvd = vl[lvln]
for k in range(lvls - lvln):
sn = lvd[k]
ll = vl[lvln-1]
vn = combine(ll[k], ll[k+1])
if sn is None:
lvd[k] = vn
else:
constraints.append(constrain( sn, vn ))
print 'Constraint Equations:'
for cstr in constraints:
fset = ('%d*%s'%(v,k) for k,v in cstr.items() )
print ' + '.join(fset), ' = 0'
mtx,vmap = makeMatrix(constraints)
MtxSolve(mtx)
d = len(vmap)
for j in range(d):
print vmap[j],'=', mtx[j][d]
def MtxSolve(mtx):
# Simple Matrix solver...
mDim = len(mtx) # dimension---
for j in range(mDim):
rw0= mtx[j]
f = 1.0/rw0[j]
for k in range(j, mDim+1):
rw0[k] *= f
for l in range(1+j,mDim):
rwl = mtx[l]
f = -rwl[j]
for k in range(j, mDim+1):
rwl[k] += f * rw0[k]
# backsolve part ---
for j1 in range(1,mDim):
j = mDim - j1
rw0= mtx[j]
for l in range(0, j):
rwl = mtx[l]
f = -rwl[j]
rwl[j] += f * rw0[j]
rwl[mDim] += f * rw0[mDim]
return mtx
p = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]
addlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }
SolvePyramid( p, addlConstraint) |
Pascal matrix generation | Python | A pascal matrix is a two-dimensional square matrix holding numbers from binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
;Task:
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).
;Note:
The [[Cholesky decomposition]] of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| from pprint import pprint as pp
def pascal_upp(n):
s = [[0] * n for _ in range(n)]
s[0] = [1] * n
for i in range(1, n):
for j in range(i, n):
s[i][j] = s[i-1][j-1] + s[i][j-1]
return s
def pascal_low(n):
# transpose of pascal_upp(n)
return [list(x) for x in zip(*pascal_upp(n))]
def pascal_sym(n):
s = [[1] * n for _ in range(n)]
for i in range(1, n):
for j in range(1, n):
s[i][j] = s[i-1][j] + s[i][j-1]
return s
if __name__ == "__main__":
n = 5
print("\nUpper:")
pp(pascal_upp(n))
print("\nLower:")
pp(pascal_low(n))
print("\nSymmetric:")
pp(pascal_sym(n)) |
Password generator | Python | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a --> z
upper-case letters: A --> Z
digits: 0 --> 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above character list excludes white-space, backslash and grave)
The generated password(s) must include ''at least one'' (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
::::* capital eye, lowercase ell, the digit one
::::* capital oh, the digit zero
::::* the digit five, capital ess
::::* the digit two, capital zee
| import random
lowercase = 'abcdefghijklmnopqrstuvwxyz' # same as string.ascii_lowercase
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # same as string.ascii_uppercase
digits = '0123456789' # same as string.digits
punctuation = '!"#$%&\'()*+,-./:;<=>?@[]^_{|}~' # like string.punctuation but without backslash \ nor grave `
allowed = lowercase + uppercase + digits + punctuation
visually_similar = 'Il1O05S2Z'
def new_password(length:int, readable=True) -> str:
if length < 4:
print("password length={} is too short,".format(length),
"minimum length=4")
return ''
choice = random.SystemRandom().choice
while True:
password_chars = [
choice(lowercase),
choice(uppercase),
choice(digits),
choice(punctuation)
] + random.sample(allowed, length-4)
if (not readable or
all(c not in visually_similar for c in password_chars)):
random.SystemRandom().shuffle(password_chars)
return ''.join(password_chars)
def password_generator(length, qty=1, readable=True):
for i in range(qty):
print(new_password(length, readable))
|
Pathological floating point problems | Python | Most programmers are familiar with the inexactness of floating point calculations in a binary processor.
The classic example being:
0.1 + 0.2 = 0.30000000000000004
In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding.
There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision.
This task's purpose is to show how your language deals with such classes of problems.
'''A sequence that seems to converge to a wrong limit.'''
Consider the sequence:
:::::: v1 = 2
:::::: v2 = -4
:::::: vn = 111 - 1130 / vn-1 + 3000 / (vn-1 * vn-2)
As '''n''' grows larger, the series should converge to '''6''' but small amounts of error will cause it to approach '''100'''.
;Task 1:
Display the values of the sequence where n = 3, 4, 5, 6, 7, 8, 20, 30, 50 & 100 to at least '''16''' decimal places.
n = 3 18.5
n = 4 9.378378
n = 5 7.801153
n = 6 7.154414
n = 7 6.806785
n = 8 6.5926328
n = 20 6.0435521101892689
n = 30 6.006786093031205758530554
n = 50 6.0001758466271871889456140207471954695237
n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266
;Task 2:
'''The Chaotic Bank Society''' is offering a new investment account to their customers.
You first deposit $e - 1 where e is 2.7182818... the base of natural logarithms.
After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed.
So ...
::* after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges.
::* after 2 years your balance will be doubled and $1 removed.
::* after 3 years your balance will be tripled and $1 removed.
::* ...
::* after 10 years, multiplied by 10 and $1 removed, and so on.
What will your balance be after 25 years?
Starting balance: $e-1
Balance = (Balance * year) - 1 for 25 years
Balance after 25 years: $0.0399387296732302
;Task 3, extra credit:
'''Siegfried Rump's example.''' Consider the following function, designed by Siegfried Rump in 1988.
:::::: f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b)
:::::: compute f(a,b) where a=77617.0 and b=33096.0
:::::: f(77617.0, 33096.0) = -0.827396059946821
Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty.
;See also;
* Floating-Point Arithmetic Section 1.3.2 Difficult problems.
| from fractions import Fraction
def muller_seq(n:int) -> float:
seq = [Fraction(0), Fraction(2), Fraction(-4)]
for i in range(3, n+1):
next_value = (111 - 1130/seq[i-1]
+ 3000/(seq[i-1]*seq[i-2]))
seq.append(next_value)
return float(seq[n])
for n in [3, 4, 5, 6, 7, 8, 20, 30, 50, 100]:
print("{:4d} -> {}".format(n, muller_seq(n))) |
Peaceful chess queen armies | Python | In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces ''not'' of its own colour.
\
|
/
=
=
=
=
/
|
\
/
|
\
|
The goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that ''no queen attacks another of a different colour''.
;Task:
# Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion).
# Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board.
# Display here results for the m=4, n=5 case.
;References:
* Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62.
* A250000 OEIS
| from itertools import combinations, product, count
from functools import lru_cache, reduce
_bbullet, _wbullet = '\u2022\u25E6'
_or = set.__or__
def place(m, n):
"Place m black and white queens, peacefully, on an n-by-n board"
board = set(product(range(n), repeat=2)) # (x, y) tuples
placements = {frozenset(c) for c in combinations(board, m)}
for blacks in placements:
black_attacks = reduce(_or,
(queen_attacks_from(pos, n) for pos in blacks),
set())
for whites in {frozenset(c) # Never on blsck attacking squares
for c in combinations(board - black_attacks, m)}:
if not black_attacks & whites:
return blacks, whites
return set(), set()
@lru_cache(maxsize=None)
def queen_attacks_from(pos, n):
x0, y0 = pos
a = set([pos]) # Its position
a.update((x, y0) for x in range(n)) # Its row
a.update((x0, y) for y in range(n)) # Its column
# Diagonals
for x1 in range(n):
# l-to-r diag
y1 = y0 -x0 +x1
if 0 <= y1 < n:
a.add((x1, y1))
# r-to-l diag
y1 = y0 +x0 -x1
if 0 <= y1 < n:
a.add((x1, y1))
return a
def pboard(black_white, n):
"Print board"
if black_white is None:
blk, wht = set(), set()
else:
blk, wht = black_white
print(f"## {len(blk)} black and {len(wht)} white queens "
f"on a {n}-by-{n} board:", end='')
for x, y in product(range(n), repeat=2):
if y == 0:
print()
xy = (x, y)
ch = ('?' if xy in blk and xy in wht
else 'B' if xy in blk
else 'W' if xy in wht
else _bbullet if (x + y)%2 else _wbullet)
print('%s' % ch, end='')
print()
if __name__ == '__main__':
n=2
for n in range(2, 7):
print()
for m in count(1):
ans = place(m, n)
if ans[0]:
pboard(ans, n)
else:
print (f"# Can't place {m} queens on a {n}-by-{n} board")
break
#
print('\n')
m, n = 5, 7
ans = place(m, n)
pboard(ans, n) |
Pentagram | Python 3.4.1 | A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
;Task:
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.
;See also
* Angle sum of a pentagram
| import turtle
turtle.bgcolor("green")
t = turtle.Turtle()
t.color("red", "blue")
t.begin_fill()
for i in range(0, 5):
t.forward(200)
t.right(144)
t.end_fill() |
Pentomino tiling | Python | A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes,
if you don't count rotations and reflections. Most pentominoes can form their own mirror image through
rotation, but some of them have to be flipped over.
I
I L N Y
FF I L NN PP TTT V W X YY ZZ
FF I L N PP T U U V WW XXX Y Z
F I LL N P T UUU VVV WW X Y ZZ
A Pentomino tiling is an example of an exact cover problem and can take on many forms.
A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered
by the 12 pentomino shapes, without overlaps, with every shape only used once.
The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable.
;Task
Create an 8 by 8 tiling and print the result.
;Example
F I I I I I L N
F F F L L L L N
W F - X Z Z N N
W W X X X Z N V
T W W X - Z Z V
T T T P P V V V
T Y - P P U U U
Y Y Y Y P U - U
;Related tasks
* Free polyominoes enumeration
| from itertools import product
minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),
((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),
((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),
((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)),
((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)),
((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)),
((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)),
((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)),
((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)),
((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)),
((4311810305, 8, 4), (31, 4, 8)),
((132866, 6, 6),))
boxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋'
boxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)]
# choose drawing alphabet based on terminal font
patterns = boxchar_single_width
tiles = []
for row in reversed(minos):
tiles.append([])
for n, x, y in row:
for shift in (b*8 + a for a, b in product(range(x), range(y))):
tiles[-1].append(n << shift)
def img(seq):
b = [[0]*10 for _ in range(10)]
for i, s in enumerate(seq):
for j, k in product(range(8), range(8)):
if s & (1<<(j*8 + k)):
b[j + 1][k + 1] = i + 1
idices = [[0]*9 for _ in range(9)]
for i, j in product(range(9), range(9)):
n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1])
idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:])))
return '\n'.join(''.join(patterns[i] for i in row) for row in idices)
def tile(board=0, seq=tuple(), tiles=tiles):
if not tiles:
yield img(seq)
return
for c in tiles[0]:
b = board | c
tnext = [] # not using list comprehension ...
for t in tiles[1:]:
tnext.append(tuple(n for n in t if not n&b))
if not tnext[-1]: break # because early break is faster
else:
yield from tile(b, seq + (c,), tnext)
for x in tile():
print(x) |
Perfect shuffle | Python | A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:
::: 7 8 9 J Q K-7 8 9 J Q K-7 J 8 Q 9 K
When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:
::::: {| style="border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right"
|-
| ''original:'' ||
1
2
3
4
5
6
7
8
|-
| ''after 1st shuffle:'' ||
1
5
2
6
3
7
4
8
|-
| ''after 2nd shuffle:'' ||
1
3
5
7
2
4
6
8
|-
| ''after 3rd shuffle:'' ||
1
2
3
4
5
6
7
8
|}
'''''The Task'''''
# Write a function that can perform a perfect shuffle on an even-sized list of values.
# Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
#* You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
#* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
'''''Test Cases'''''
::::: {| class="wikitable"
|-
! input ''(deck size)'' !! output ''(number of shuffles required)''
|-
| 8 || 3
|-
| 24 || 11
|-
| 52 || 8
|-
| 100 || 30
|-
| 1020 || 1018
|-
| 1024 || 10
|-
| 10000 || 300
|}
| """
Brute force solution for the Perfect Shuffle problem.
See http://oeis.org/A002326 for possible improvements
"""
from functools import partial
from itertools import chain
from operator import eq
from typing import (Callable,
Iterable,
Iterator,
List,
TypeVar)
T = TypeVar('T')
def main():
print("Deck length | Shuffles ")
for length in (8, 24, 52, 100, 1020, 1024, 10000):
deck = list(range(length))
shuffles_needed = spin_number(deck, shuffle)
print(f"{length:<11} | {shuffles_needed}")
def shuffle(deck: List[T]) -> List[T]:
"""[1, 2, 3, 4] -> [1, 3, 2, 4]"""
half = len(deck) // 2
return list(chain.from_iterable(zip(deck[:half], deck[half:])))
def spin_number(source: T,
function: Callable[[T], T]) -> int:
"""
Applies given function to the source
until the result becomes equal to it,
returns the number of calls
"""
is_equal_source = partial(eq, source)
spins = repeat_call(function, source)
return next_index(is_equal_source,
spins,
start=1)
def repeat_call(function: Callable[[T], T],
value: T) -> Iterator[T]:
"""(f, x) -> f(x), f(f(x)), f(f(f(x))), ..."""
while True:
value = function(value)
yield value
def next_index(predicate: Callable[[T], bool],
iterable: Iterable[T],
start: int = 0) -> int:
"""
Returns index of the first element of the iterable
satisfying given condition
"""
for index, item in enumerate(iterable, start=start):
if predicate(item):
return index
if __name__ == "__main__":
main()
|
Perfect totient numbers | Python | Generate and show here, the first twenty Perfect totient numbers.
;Related task:
::* [[Totient function]]
;Also see:
::* the OEIS entry for perfect totient numbers.
::* mrob list of the first 54
| from math import gcd
from functools import lru_cache
from itertools import islice, count
@lru_cache(maxsize=None)
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
def perfect_totient():
for n0 in count(1):
parts, n = 0, n0
while n != 1:
n = φ(n)
parts += n
if parts == n0:
yield n0
if __name__ == '__main__':
print(list(islice(perfect_totient(), 20))) |
Periodic table | Python | Display the row and column in the periodic table of the given atomic number.
;The periodic table:
Let us consider the following periodic table representation.
__________________________________________________________________________
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
| |
|1 H He |
| |
|2 Li Be B C N O F Ne |
| |
|3 Na Mg Al Si P S Cl Ar |
| |
|4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |
| |
|5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |
| |
|6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |
| |
|7 Fr Ra deg Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |
|__________________________________________________________________________|
| |
| |
|8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |
| |
|9 Aktinoidideg Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |
|__________________________________________________________________________|
;Example test cases;
* 1 -> 1 1
* 2 -> 1 18
* 29 -> 4 11
* 42 -> 5 6
* 57 -> 8 4
* 58 -> 8 5
* 72 -> 6 4
* 89 -> 9 4
;Details;
The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.
You may take a look at the atomic number repartitions here.
The atomic number is at least 1, at most 118.
;See also:
* the periodic table
* This task was an idea from CompSciFact
* The periodic table in ascii that was used as template
| def perta(atomic) -> (int, int):
NOBLES = 2, 10, 18, 36, 54, 86, 118
INTERTWINED = 0, 0, 0, 0, 0, 57, 89
INTERTWINING_SIZE = 14
LINE_WIDTH = 18
prev_noble = 0
for row, noble in enumerate(NOBLES):
if atomic <= noble: # we are at the good row. We now need to determine the column
nb_elem = noble - prev_noble # number of elements on that row
rank = atomic - prev_noble # rank of the input element among elements
if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE: # lantanides or actinides
row += 2
col = rank + 1
else: # not a lantanide nor actinide
# handle empty spaces between 1-2, 4-5 and 12-13.
nb_empty = LINE_WIDTH - nb_elem # spaces count as columns
inside_left_element_rank = 2 if noble > 2 else 1
col = rank + (nb_empty if rank > inside_left_element_rank else 0)
break
prev_noble = noble
return row+1, col
# small test suite
TESTS = {
1: (1, 1),
2: (1, 18),
29: (4,11),
42: (5, 6),
58: (8, 5),
59: (8, 6),
57: (8, 4),
71: (8, 18),
72: (6, 4),
89: (9, 4),
90: (9, 5),
103: (9, 18),
}
for input, out in TESTS.items():
found = perta(input)
print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))
|
Perlin noise | Python from Java | The '''computer graphics, most notably to procedurally generate textures or heightmaps.
The Perlin noise is basically a pseudo-random mapping of \R^d into \R with an integer d which can be arbitrarily large but which is usually 2, 3, or 4.
Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012.
''Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.''
| import math
def perlin_noise(x, y, z):
X = math.floor(x) & 255 # FIND UNIT CUBE THAT
Y = math.floor(y) & 255 # CONTAINS POINT.
Z = math.floor(z) & 255
x -= math.floor(x) # FIND RELATIVE X,Y,Z
y -= math.floor(y) # OF POINT IN CUBE.
z -= math.floor(z)
u = fade(x) # COMPUTE FADE CURVES
v = fade(y) # FOR EACH OF X,Y,Z.
w = fade(z)
A = p[X ]+Y; AA = p[A]+Z; AB = p[A+1]+Z # HASH COORDINATES OF
B = p[X+1]+Y; BA = p[B]+Z; BB = p[B+1]+Z # THE 8 CUBE CORNERS,
return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), # AND ADD
grad(p[BA ], x-1, y , z )), # BLENDED
lerp(u, grad(p[AB ], x , y-1, z ), # RESULTS
grad(p[BB ], x-1, y-1, z ))),# FROM 8
lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), # CORNERS
grad(p[BA+1], x-1, y , z-1 )), # OF CUBE
lerp(u, grad(p[AB+1], x , y-1, z-1 ),
grad(p[BB+1], x-1, y-1, z-1 ))))
def fade(t):
return t ** 3 * (t * (t * 6 - 15) + 10)
def lerp(t, a, b):
return a + t * (b - a)
def grad(hash, x, y, z):
h = hash & 15 # CONVERT LO 4 BITS OF HASH CODE
u = x if h<8 else y # INTO 12 GRADIENT DIRECTIONS.
v = y if h<4 else (x if h in (12, 14) else z)
return (u if (h&1) == 0 else -u) + (v if (h&2) == 0 else -v)
p = [None] * 512
permutation = [151,160,137,91,90,15,
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]
for i in range(256):
p[256+i] = p[i] = permutation[i]
if __name__ == '__main__':
print("%1.17f" % perlin_noise(3.14, 42, 7)) |
Permutations/Derangements | Python | A derangement is a permutation of the order of distinct items in which ''no item appears in its original place''.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of ''n'' distinct items is known as the subfactorial of ''n'', sometimes written as !''n''.
There are various ways to calculate !''n''.
;Task:
# Create a named function/method/subroutine/... to generate derangements of the integers ''0..n-1'', (or ''1..n'' if you prefer).
# Generate ''and show'' all the derangements of 4 integers using the above routine.
# Create a function that calculates the subfactorial of ''n'', !''n''.
# Print and show a table of the ''counted'' number of derangements of ''n'' vs. the calculated !''n'' for n from 0..9 inclusive.
;Optional stretch goal:
* Calculate !''20''
;Related tasks:
* [[Anagrams/Deranged anagrams]]
* [[Best shuffle]]
* [[Left_factorials]]
| from itertools import permutations
import math
def derangements(n):
'All deranged permutations of the integers 0..n-1 inclusive'
return ( perm for perm in permutations(range(n))
if all(indx != p for indx, p in enumerate(perm)) )
def subfact(n):
if n == 2 or n == 0:
return 1
elif n == 1:
return 0
elif 1 <= n <=18:
return round(math.factorial(n) / math.e)
elif n.imag == 0 and n.real == int(n.real) and n > 0:
return (n-1) * ( subfact(n - 1) + subfact(n - 2) )
else:
raise ValueError()
def _iterlen(iter):
'length of an iterator without taking much memory'
l = 0
for x in iter:
l += 1
return l
if __name__ == '__main__':
n = 4
print("Derangements of %s" % (tuple(range(n)),))
for d in derangements(n):
print(" %s" % (d,))
print("\nTable of n vs counted vs calculated derangements")
for n in range(10):
print("%2i %-5i %-5i" %
(n, _iterlen(derangements(n)), subfact(n)))
n = 20
print("\n!%i = %i" % (n, subfact(n))) |
Permutations/Rank of a permutation | Python | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers 0 .. (n! - 1) to an ordering of all the permutations of the integers 0 .. (n - 1).
For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:
PERMUTATION RANK
(0, 1, 2, 3) -> 0
(0, 1, 3, 2) -> 1
(0, 2, 1, 3) -> 2
(0, 2, 3, 1) -> 3
(0, 3, 1, 2) -> 4
(0, 3, 2, 1) -> 5
(1, 0, 2, 3) -> 6
(1, 0, 3, 2) -> 7
(1, 2, 0, 3) -> 8
(1, 2, 3, 0) -> 9
(1, 3, 0, 2) -> 10
(1, 3, 2, 0) -> 11
(2, 0, 1, 3) -> 12
(2, 0, 3, 1) -> 13
(2, 1, 0, 3) -> 14
(2, 1, 3, 0) -> 15
(2, 3, 0, 1) -> 16
(2, 3, 1, 0) -> 17
(3, 0, 1, 2) -> 18
(3, 0, 2, 1) -> 19
(3, 1, 0, 2) -> 20
(3, 1, 2, 0) -> 21
(3, 2, 0, 1) -> 22
(3, 2, 1, 0) -> 23
Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).
One use of such algorithms could be in generating a small, random, sample of permutations of n items without duplicates when the total number of permutations is large. Remember that the total number of permutations of n items is given by n! which grows large very quickly: A 32 bit integer can only hold 12!, a 64 bit integer only 20!. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.
A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.
;Task:
# Create a function to generate a permutation from a rank.
# Create the inverse function that given the permutation generates its rank.
# Show that for n=3 the two functions are indeed inverses of each other.
# Compute and show here 4 random, individual, samples of permutations of 12 objects.
;Stretch goal:
* State how reasonable it would be to use your program to address the limits of the Stack Overflow question.
;References:
# Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
# Ranks on the DevData site.
# Another answer on Stack Overflow to a different question that explains its algorithm in detail.
;Related tasks:
#[[Factorial_base_numbers_indexing_permutations_of_a_collection]]
| from math import factorial as fact
from random import randrange
from textwrap import wrap
def identity_perm(n):
return list(range(n))
def unranker1(n, r, pi):
while n > 0:
n1, (rdivn, rmodn) = n-1, divmod(r, n)
pi[n1], pi[rmodn] = pi[rmodn], pi[n1]
n = n1
r = rdivn
return pi
def init_pi1(n, pi):
pi1 = [-1] * n
for i in range(n):
pi1[pi[i]] = i
return pi1
def ranker1(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s + n * ranker1(n1, pi, pi1)
def unranker2(n, r, pi):
while n > 0:
n1 = n-1
s, rmodf = divmod(r, fact(n1))
pi[n1], pi[s] = pi[s], pi[n1]
n = n1
r = rmodf
return pi
def ranker2(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s * fact(n1) + ranker2(n1, pi, pi1)
def get_random_ranks(permsize, samplesize):
perms = fact(permsize)
ranks = set()
while len(ranks) < samplesize:
ranks |= set( randrange(perms)
for r in range(samplesize - len(ranks)) )
return ranks
def test1(comment, unranker, ranker):
n, samplesize, n2 = 3, 4, 12
print(comment)
perms = []
for r in range(fact(n)):
pi = identity_perm(n)
perm = unranker(n, r, pi)
perms.append((r, perm))
for r, pi in perms:
pi1 = init_pi1(n, pi)
print(' From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))
print('\n %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))
print('')
def test2(comment, unranker):
samplesize, n2 = 4, 144
print(comment)
print(' %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + '\n '.join(wrap(repr(unranker(n2, r, pi)))))
print('')
if __name__ == '__main__':
test1('First ordering:', unranker1, ranker1)
test1('Second ordering:', unranker2, ranker2)
test2('First ordering, large number of perms:', unranker1) |
Permutations by swapping | Python | Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation ''here''.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus-Johnson-Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement.
;References:
* Steinhaus-Johnson-Trotter algorithm
* Johnson-Trotter Algorithm Listing All Permutations
* Heap's algorithm
* Tintinnalogia
;Related tasks:
* [[Matrix arithmetic]
* [[Gray code]]
| from operator import itemgetter
DEBUG = False # like the built-in __debug__
def spermutations(n):
"""permutations by swapping. Yields: perm, sign"""
sign = 1
p = [[i, 0 if i == 0 else -1] # [num, direction]
for i in range(n)]
if DEBUG: print ' #', p
yield tuple(pp[0] for pp in p), sign
while any(pp[1] for pp in p): # moving
i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),
key=itemgetter(1))
sign *= -1
if d1 == -1:
# Swap down
i2 = i1 - 1
p[i1], p[i2] = p[i2], p[i1]
# If this causes the chosen element to reach the First or last
# position within the permutation, or if the next element in the
# same direction is larger than the chosen element:
if i2 == 0 or p[i2 - 1][0] > n1:
# The direction of the chosen element is set to zero
p[i2][1] = 0
elif d1 == 1:
# Swap up
i2 = i1 + 1
p[i1], p[i2] = p[i2], p[i1]
# If this causes the chosen element to reach the first or Last
# position within the permutation, or if the next element in the
# same direction is larger than the chosen element:
if i2 == n - 1 or p[i2 + 1][0] > n1:
# The direction of the chosen element is set to zero
p[i2][1] = 0
if DEBUG: print ' #', p
yield tuple(pp[0] for pp in p), sign
for i3, pp in enumerate(p):
n3, d3 = pp
if n3 > n1:
pp[1] = 1 if i3 < i2 else -1
if DEBUG: print ' # Set Moving'
if __name__ == '__main__':
from itertools import permutations
for n in (3, 4):
print '\nPermutations and sign of %i items' % n
sp = set()
for i in spermutations(n):
sp.add(i[0])
print('Perm: %r Sign: %2i' % i)
#if DEBUG: raw_input('?')
# Test
p = set(permutations(range(n)))
assert sp == p, 'Two methods of generating permutations do not agree' |
Phrase reversals | Python | Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
:# Reverse the characters of the string.
:# Reverse the characters of each individual word in the string, maintaining original word order within the string.
:# Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
| '''String reversals at different levels.'''
# reversedCharacters :: String -> String
def reversedCharacters(s):
'''All characters in reversed sequence.'''
return reverse(s)
# wordsWithReversedCharacters :: String -> String
def wordsWithReversedCharacters(s):
'''Characters within each word in reversed sequence.'''
return unwords(map(reverse, words(s)))
# reversedWordOrder :: String -> String
def reversedWordOrder(s):
'''Sequence of words reversed.'''
return unwords(reverse(words(s)))
# TESTS -------------------------------------------------
# main :: IO()
def main():
'''Tests'''
s = 'rosetta code phrase reversal'
print(
tabulated(s + ':\n')(
lambda f: f.__name__
)(lambda s: "'" + s + "'")(
lambda f: f(s)
)([
reversedCharacters,
wordsWithReversedCharacters,
reversedWordOrder
])
)
# GENERIC -------------------------------------------------
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Function composition.'''
return lambda f: lambda x: g(f(x))
# reverse :: [a] -> [a]
# reverse :: String -> String
def reverse(xs):
'''The elements of xs in reverse order.'''
return xs[::-1] if isinstance(xs, str) else (
list(reversed(xs))
)
# 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
)
# unwords :: [String] -> String
def unwords(xs):
'''A space-separated string derived from a list of words.'''
return ' '.join(xs)
# words :: String -> [String]
def words(s):
'''A list of words delimited by characters
representing white space.'''
return s.split()
if __name__ == '__main__':
main() |
Pig the dice game | Python | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach '''100''' points or more.
Play is taken in turns. On each person's turn that person has the option of either:
:# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of '''1''' loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player.
:# '''Holding''': the player's score for that round is added to their total and becomes safe from the effects of throwing a '''1''' (one). The player's turn finishes with play passing to the next player.
;Task:
Create a program to score for, and simulate dice throws for, a two-person game.
;Related task:
* [[Pig the dice game/Player]]
| #!/usr/bin/python3
'''
See: http://en.wikipedia.org/wiki/Pig_(dice)
This program scores and throws the dice for a two player game of Pig
'''
from random import randint
playercount = 2
maxscore = 100
safescore = [0] * playercount
player = 0
score=0
while max(safescore) < maxscore:
rolling = input("Player %i: (%i, %i) Rolling? (Y) "
% (player, safescore[player], score)).strip().lower() in {'yes', 'y', ''}
if rolling:
rolled = randint(1, 6)
print(' Rolled %i' % rolled)
if rolled == 1:
print(' Bust! you lose %i but still keep your previous %i'
% (score, safescore[player]))
score, player = 0, (player + 1) % playercount
else:
score += rolled
else:
safescore[player] += score
if safescore[player] >= maxscore:
break
print(' Sticking with %i' % safescore[player])
score, player = 0, (player + 1) % playercount
print('\nPlayer %i wins with a score of %i' %(player, safescore[player])) |
Pig the dice game/Player | Python | Create a dice simulator and scorer of [[Pig the dice game]] and add to it the ability to play the game to at least one strategy.
* State here the play strategies involved.
* Show play during a game here.
As a stretch goal:
* Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.
;Game Rules:
The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either
# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player.
# '''Holding''': The player's score for that round is added to their total and becomes safe from the effects of throwing a one. The player's turn finishes with play passing to the next player.
;References
* Pig (dice)
* The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.
| #!/usr/bin/python3
'''
See: http://en.wikipedia.org/wiki/Pig_(dice)
This program scores, throws the dice, and plays for an N player game of Pig.
'''
from random import randint
from collections import namedtuple
import random
from pprint import pprint as pp
from collections import Counter
playercount = 2
maxscore = 100
maxgames = 100000
Game = namedtuple('Game', 'players, maxscore, rounds')
Round = namedtuple('Round', 'who, start, scores, safe')
class Player():
def __init__(self, player_index):
self.player_index = player_index
def __repr__(self):
return '%s(%i)' % (self.__class__.__name__, self.player_index)
def __call__(self, safescore, scores, game):
'Returns boolean True to roll again'
pass
class RandPlay(Player):
def __call__(self, safe, scores, game):
'Returns random boolean choice of whether to roll again'
return bool(random.randint(0, 1))
class RollTo20(Player):
def __call__(self, safe, scores, game):
'Roll again if this rounds score < 20'
return (((sum(scores) + safe[self.player_index]) < maxscore) # Haven't won yet
and(sum(scores) < 20)) # Not at 20 this round
class Desparat(Player):
def __call__(self, safe, scores, game):
'Roll again if this rounds score < 20 or someone is within 20 of winning'
return (((sum(scores) + safe[self.player_index]) < maxscore) # Haven't won yet
and( (sum(scores) < 20) # Not at 20 this round
or max(safe) >= (maxscore - 20))) # Someone's close
def game__str__(self):
'Pretty printer for Game class'
return ("Game(players=%r, maxscore=%i,\n rounds=[\n %s\n ])"
% (self.players, self.maxscore,
',\n '.join(repr(round) for round in self.rounds)))
Game.__str__ = game__str__
def winningorder(players, safescores):
'Return (players in winning order, their scores)'
return tuple(zip(*sorted(zip(players, safescores),
key=lambda x: x[1], reverse=True)))
def playpig(game):
'''
Plays the game of pig returning the players in winning order
and their scores whilst updating argument game with the details of play.
'''
players, maxscore, rounds = game
playercount = len(players)
safescore = [0] * playercount # Safe scores for each player
player = 0 # Who plays this round
scores=[] # Individual scores this round
while max(safescore) < maxscore:
startscore = safescore[player]
rolling = players[player](safescore, scores, game)
if rolling:
rolled = randint(1, 6)
scores.append(rolled)
if rolled == 1:
# Bust!
round = Round(who=players[player],
start=startscore,
scores=scores,
safe=safescore[player])
rounds.append(round)
scores, player = [], (player + 1) % playercount
else:
# Stick
safescore[player] += sum(scores)
round = Round(who=players[player],
start=startscore,
scores=scores,
safe=safescore[player])
rounds.append(round)
if safescore[player] >= maxscore:
break
scores, player = [], (player + 1) % playercount
# return players in winning order and all scores
return winningorder(players, safescore)
if __name__ == '__main__':
game = Game(players=tuple(RandPlay(i) for i in range(playercount)),
maxscore=20,
rounds=[])
print('ONE GAME')
print('Winning order: %r; Respective scores: %r\n' % playpig(game))
print(game)
game = Game(players=tuple(RandPlay(i) for i in range(playercount)),
maxscore=maxscore,
rounds=[])
algos = (RollTo20, RandPlay, Desparat)
print('\n\nMULTIPLE STATISTICS using %r\n for %i GAMES'
% (', '.join(p.__name__ for p in algos), maxgames,))
winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)
for i in range(playercount)),
rounds=[]))[0])
for i in range(maxgames))
print(' Players(position) winning on left; occurrences on right:\n %s'
% ',\n '.join(str(w) for w in winners.most_common())) |
Plasma effect | Python from Raku | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
;Task
Create a plasma effect.
;See also
* Computer Graphics Tutorial (lodev.org)
* Plasma (bidouille.org)
| import math
import colorsys
from PIL import Image
def plasma (w, h):
out = Image.new("RGB", (w, h))
pix = out.load()
for x in range (w):
for y in range(h):
hue = 4.0 + math.sin(x / 19.0) + math.sin(y / 9.0) \
+ math.sin((x + y) / 25.0) + math.sin(math.sqrt(x**2.0 + y**2.0) / 8.0)
hsv = colorsys.hsv_to_rgb(hue/8.0, 1, 1)
pix[x, y] = tuple([int(round(c * 255.0)) for c in hsv])
return out
if __name__=="__main__":
im = plasma(400, 400)
im.show() |
Playfair cipher | Python from Raku | Implement a Playfair cipher for encryption and decryption.
The user must be able to choose '''J''' = '''I''' or no '''Q''' in the alphabet.
The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.
;Output example:
HI DE TH EG OL DI NT HE TR EX ES TU MP
| from string import ascii_uppercase
from itertools import product
from re import findall
def uniq(seq):
seen = {}
return [seen.setdefault(x, x) for x in seq if x not in seen]
def partition(seq, n):
return [seq[i : i + n] for i in xrange(0, len(seq), n)]
"""Instantiate a specific encoder/decoder."""
def playfair(key, from_ = 'J', to = None):
if to is None:
to = 'I' if from_ == 'J' else ''
def canonicalize(s):
return filter(str.isupper, s.upper()).replace(from_, to)
# Build 5x5 matrix.
m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)
# Pregenerate all forward translations.
enc = {}
# Map pairs in same row.
for row in m:
for i, j in product(xrange(5), repeat=2):
if i != j:
enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]
# Map pairs in same column.
for c in zip(*m):
for i, j in product(xrange(5), repeat=2):
if i != j:
enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]
# Map pairs with cross-connections.
for i1, j1, i2, j2 in product(xrange(5), repeat=4):
if i1 != i2 and j1 != j2:
enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]
# Generate reverse translations.
dec = dict((v, k) for k, v in enc.iteritems())
def sub_enc(txt):
lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt))
return " ".join(enc[a + (b if b else 'X')] for a, b in lst)
def sub_dec(encoded):
return " ".join(dec[p] for p in partition(canonicalize(encoded), 2))
return sub_enc, sub_dec
(encode, decode) = playfair("Playfair example")
orig = "Hide the gold in...the TREESTUMP!!!"
print "Original:", orig
enc = encode(orig)
print "Encoded:", enc
print "Decoded:", decode(enc) |
Plot coordinate pairs | Python | Plot a function represented as x, y numerical arrays.
Post the resulting image for the following input arrays (taken from Python's Example section on ''Time a function''):
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};
This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
| from visual import *
from visual.graph import *
plot1 = gdisplay( title='VPython Plot-Demo',
xtitle='x',
ytitle='y (click and drag mouse to see coordinates)',
foreground=color.black,
background=color.white,
x=0, y=0,
width=400, height=400,
xmin=0, xmax=10,
ymin=0, ymax=200 )
f1 = gdots(color=color.red) # create plot-object
f1.plot(pos= (0, 2.7), color=color.blue ) # add a single point
f1.plot(pos=[(1, 2.8), # add a list of points
(2, 31.4),
(3, 38.1),
(4, 58.0),
(5, 76.2),
(6, 100.5),
(7, 130.0),
(8, 149.3),
(9, 180.0) ]
)
label(display=plot1.display, text="Look here",
pos=(6,100.5), xoffset=30,yoffset=-20 )
|
Poker hand analyser | Python | Create a program to parse a single five card poker hand and rank it according to this list of poker hands.
A poker hand is specified as a space separated list of five playing cards.
Each input card has two characters indicating face and suit.
;Example:
::::'''2d''' (two of diamonds).
Faces are: '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k'''
Suits are: '''h''' (hearts), '''d''' (diamonds), '''c''' (clubs), and '''s''' (spades), or
alternatively, the unicode card-suit characters:
Duplicate cards are illegal.
The program should analyze a single hand and produce one of the following outputs:
straight-flush
four-of-a-kind
full-house
flush
straight
three-of-a-kind
two-pair
one-pair
high-card
invalid
;Examples:
2 2 2 k q: three-of-a-kind
2 5 7 8 9: high-card
a 2 3 4 5: straight
2 3 2 3 3: full-house
2 7 2 3 3: two-pair
2 7 7 7 7: four-of-a-kind
10 j q k a: straight-flush
4 4 k 5 10: one-pair
q 10 7 6 q: invalid
The programs output for the above examples should be displayed here on this page.
;Extra credit:
# use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).
# allow two jokers
::* use the symbol '''joker'''
::* duplicates would be allowed (for jokers only)
::* five-of-a-kind would then be the highest hand
;More extra credit examples:
joker 2 2 k q: three-of-a-kind
joker 5 7 8 9: straight
joker 2 3 4 5: straight
joker 3 2 3 3: four-of-a-kind
joker 7 2 3 3: three-of-a-kind
joker 7 7 7 7: five-of-a-kind
joker j q k A: straight-flush
joker 4 k 5 10: one-pair
joker k 7 6 4: flush
joker 2 joker 4 5: straight
joker Q joker A 10: straight
joker Q joker A 10: straight-flush
joker 2 2 joker q: four-of-a-kind
;Related tasks:
* [[Playing cards]]
* [[Card shuffles]]
* [[Deal cards_for_FreeCell]]
* [[War Card_Game]]
* [[Go Fish]]
| from collections import namedtuple
class Card(namedtuple('Card', 'face, suit')):
def __repr__(self):
return ''.join(self)
suit = '♥ ♦ ♣ ♠'.split()
# ordered strings of faces
faces = '2 3 4 5 6 7 8 9 10 j q k a'
lowaces = 'a 2 3 4 5 6 7 8 9 10 j q k'
# faces as lists
face = faces.split()
lowace = lowaces.split()
def straightflush(hand):
f,fs = ( (lowace, lowaces) if any(card.face == '2' for card in hand)
else (face, faces) )
ordered = sorted(hand, key=lambda card: (f.index(card.face), card.suit))
first, rest = ordered[0], ordered[1:]
if ( all(card.suit == first.suit for card in rest) and
' '.join(card.face for card in ordered) in fs ):
return 'straight-flush', ordered[-1].face
return False
def fourofakind(hand):
allfaces = [f for f,s in hand]
allftypes = set(allfaces)
if len(allftypes) != 2:
return False
for f in allftypes:
if allfaces.count(f) == 4:
allftypes.remove(f)
return 'four-of-a-kind', [f, allftypes.pop()]
else:
return False
def fullhouse(hand):
allfaces = [f for f,s in hand]
allftypes = set(allfaces)
if len(allftypes) != 2:
return False
for f in allftypes:
if allfaces.count(f) == 3:
allftypes.remove(f)
return 'full-house', [f, allftypes.pop()]
else:
return False
def flush(hand):
allstypes = {s for f, s in hand}
if len(allstypes) == 1:
allfaces = [f for f,s in hand]
return 'flush', sorted(allfaces,
key=lambda f: face.index(f),
reverse=True)
return False
def straight(hand):
f,fs = ( (lowace, lowaces) if any(card.face == '2' for card in hand)
else (face, faces) )
ordered = sorted(hand, key=lambda card: (f.index(card.face), card.suit))
first, rest = ordered[0], ordered[1:]
if ' '.join(card.face for card in ordered) in fs:
return 'straight', ordered[-1].face
return False
def threeofakind(hand):
allfaces = [f for f,s in hand]
allftypes = set(allfaces)
if len(allftypes) <= 2:
return False
for f in allftypes:
if allfaces.count(f) == 3:
allftypes.remove(f)
return ('three-of-a-kind', [f] +
sorted(allftypes,
key=lambda f: face.index(f),
reverse=True))
else:
return False
def twopair(hand):
allfaces = [f for f,s in hand]
allftypes = set(allfaces)
pairs = [f for f in allftypes if allfaces.count(f) == 2]
if len(pairs) != 2:
return False
p0, p1 = pairs
other = [(allftypes - set(pairs)).pop()]
return 'two-pair', pairs + other if face.index(p0) > face.index(p1) else pairs[::-1] + other
def onepair(hand):
allfaces = [f for f,s in hand]
allftypes = set(allfaces)
pairs = [f for f in allftypes if allfaces.count(f) == 2]
if len(pairs) != 1:
return False
allftypes.remove(pairs[0])
return 'one-pair', pairs + sorted(allftypes,
key=lambda f: face.index(f),
reverse=True)
def highcard(hand):
allfaces = [f for f,s in hand]
return 'high-card', sorted(allfaces,
key=lambda f: face.index(f),
reverse=True)
handrankorder = (straightflush, fourofakind, fullhouse,
flush, straight, threeofakind,
twopair, onepair, highcard)
def rank(cards):
hand = handy(cards)
for ranker in handrankorder:
rank = ranker(hand)
if rank:
break
assert rank, "Invalid: Failed to rank cards: %r" % cards
return rank
def handy(cards='2♥ 2♦ 2♣ k♣ q♦'):
hand = []
for card in cards.split():
f, s = card[:-1], card[-1]
assert f in face, "Invalid: Don't understand card face %r" % f
assert s in suit, "Invalid: Don't understand card suit %r" % s
hand.append(Card(f, s))
assert len(hand) == 5, "Invalid: Must be 5 cards in a hand, not %i" % len(hand)
assert len(set(hand)) == 5, "Invalid: All cards in the hand must be unique %r" % cards
return hand
if __name__ == '__main__':
hands = ["2♥ 2♦ 2♣ k♣ q♦",
"2♥ 5♥ 7♦ 8♣ 9♠",
"a♥ 2♦ 3♣ 4♣ 5♦",
"2♥ 3♥ 2♦ 3♣ 3♦",
"2♥ 7♥ 2♦ 3♣ 3♦",
"2♥ 7♥ 7♦ 7♣ 7♠",
"10♥ j♥ q♥ k♥ a♥"] + [
"4♥ 4♠ k♠ 5♦ 10♠",
"q♣ 10♣ 7♣ 6♣ 4♣",
]
print("%-18s %-15s %s" % ("HAND", "CATEGORY", "TIE-BREAKER"))
for cards in hands:
r = rank(cards)
print("%-18r %-15s %r" % (cards, r[0], r[1])) |
Population count | Python | The ''population count'' is the number of '''1'''s (ones) in the binary representation of a non-negative integer.
''Population count'' is also known as:
::::* ''pop count''
::::* ''popcount''
::::* ''sideways sum''
::::* ''bit summation''
::::* ''Hamming weight''
For example, '''5''' (which is '''101''' in binary) has a population count of '''2'''.
''Evil numbers'' are non-negative integers that have an ''even'' population count.
''Odious numbers'' are positive integers that have an ''odd'' population count.
;Task:
* write a function (or routine) to return the population count of a non-negative integer.
* all computation of the lists below should start with '''0''' (zero indexed).
:* display the ''pop count'' of the 1st thirty powers of '''3''' ('''30''', '''31''', '''32''', '''33''', '''34''', '''329''').
:* display the 1st thirty ''evil'' numbers.
:* display the 1st thirty ''odious'' numbers.
* display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
;See also
* The On-Line Encyclopedia of Integer Sequences: A000120 population count.
* The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
* The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| >>> def popcount(n): return bin(n).count("1")
...
>>> [popcount(3**i) for i in range(30)]
[1, 2, 2, 4, 3, 6, 6, 5, 6, 8, 9, 13, 10, 11, 14, 15, 11, 14, 14, 17, 17, 20, 19, 22, 16, 18, 24, 30, 25, 25]
>>> evil, odious, i = [], [], 0
>>> while len(evil) < 30 or len(odious) < 30:
... p = popcount(i)
... if p % 2: odious.append(i)
... else: evil.append(i)
... i += 1
...
>>> evil[:30]
[0, 3, 5, 6, 9, 10, 12, 15, 17, 18, 20, 23, 24, 27, 29, 30, 33, 34, 36, 39, 40, 43, 45, 46, 48, 51, 53, 54, 57, 58]
>>> odious[:30]
[1, 2, 4, 7, 8, 11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44, 47, 49, 50, 52, 55, 56, 59]
>>> |
Population count | Python 3 | The ''population count'' is the number of '''1'''s (ones) in the binary representation of a non-negative integer.
''Population count'' is also known as:
::::* ''pop count''
::::* ''popcount''
::::* ''sideways sum''
::::* ''bit summation''
::::* ''Hamming weight''
For example, '''5''' (which is '''101''' in binary) has a population count of '''2'''.
''Evil numbers'' are non-negative integers that have an ''even'' population count.
''Odious numbers'' are positive integers that have an ''odd'' population count.
;Task:
* write a function (or routine) to return the population count of a non-negative integer.
* all computation of the lists below should start with '''0''' (zero indexed).
:* display the ''pop count'' of the 1st thirty powers of '''3''' ('''30''', '''31''', '''32''', '''33''', '''34''', '''329''').
:* display the 1st thirty ''evil'' numbers.
:* display the 1st thirty ''odious'' numbers.
* display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
;See also
* The On-Line Encyclopedia of Integer Sequences: A000120 population count.
* The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
* The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| '''Population count'''
from functools import reduce
# popCount :: Int -> Int
def popCount(n):
'''The count of non-zero digits in the binary
representation of the positive integer n.'''
def go(x):
return Just(divmod(x, 2)) if 0 < x else Nothing()
return sum(unfoldl(go)(n))
# -------------------------- TEST --------------------------
def main():
'''Tests'''
print('Population count of first 30 powers of 3:')
print(' ' + showList(
[popCount(pow(3, x)) for x in enumFromTo(0)(29)]
))
evilNums, odiousNums = partition(
compose(even, popCount)
)(enumFromTo(0)(59))
print("\nFirst thirty 'evil' numbers:")
print(' ' + showList(evilNums))
print("\nFirst thirty 'odious' numbers:")
print(' ' + showList(odiousNums))
# ------------------------ GENERIC -------------------------
# Just :: a -> Maybe a
def Just(x):
'''Constructor for an inhabited Maybe (option type) value.
Wrapper containing the result of a computation.
'''
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
# Nothing :: Maybe a
def Nothing():
'''Constructor for an empty Maybe (option type) value.
Empty wrapper returned where a computation is not possible.
'''
return {'type': 'Maybe', 'Nothing': True}
# compose :: ((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)
# enumFromTo :: Int -> Int -> [Int]
def enumFromTo(m):
'''Enumeration of integer values [m..n]'''
return lambda n: range(m, 1 + n)
# even :: Int -> Bool
def even(x):
'''True if x is an integer
multiple of two.
'''
return 0 == x % 2
# partition :: (a -> Bool) -> [a] -> ([a], [a])
def partition(p):
'''The pair of lists of those elements in xs
which respectively do, and don't
satisfy the predicate p.
'''
def go(a, x):
ts, fs = a
return (ts + [x], fs) if p(x) else (ts, fs + [x])
return lambda xs: reduce(go, xs, ([], []))
# showList :: [a] -> String
def showList(xs):
'''Stringification of a list.'''
return '[' + ','.join(repr(x) for x in xs) + ']'
# unfoldl(lambda x: Just(((x - 1), x)) if 0 != x else Nothing())(10)
# -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# unfoldl :: (b -> Maybe (b, a)) -> b -> [a]
def unfoldl(f):
'''Dual to reduce or foldl.
Where these reduce a list to a summary value, unfoldl
builds a list from a seed value.
Where f returns Just(a, b), a is appended to the list,
and the residual b is used as the argument for the next
application of f.
When f returns Nothing, the completed list is returned.
'''
def go(v):
x, r = v, v
xs = []
while True:
mb = f(x)
if mb.get('Nothing'):
return xs
else:
x, r = mb.get('Just')
xs.insert(0, r)
return xs
return go
# MAIN ---
if __name__ == '__main__':
main() |
Pragmatic directives | Python | Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).
;Task:
List any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
| Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import __future__
>>> __future__.all_feature_names
['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'barry_as_FLUFL']
>>> |
Prime triangle | Python | You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangements of 1 to S meeting these requirements.
;See also
:* OEIS:A036440
| from numpy import array
# for Rosetta Code by MG - 20230312
def is_prime(n: int) -> bool:
assert n < 64
return ((1 << n) & 0x28208a20a08a28ac) != 0
def prime_triangle_row(a: array, start: int, length: int) -> bool:
if length == 2:
return is_prime(a[0] + a[1])
for i in range(1, length - 1, 1):
if is_prime(a[start] + a[start + i]):
a[start + i], a[start + 1] = a[start + 1], a[start + i]
if prime_triangle_row(a, start + 1, length - 1):
return True
a[start + i], a[start + 1] = a[start + 1], a[start + i]
return False
def prime_triangle_count(a: array, start: int, length: int) -> int:
count: int = 0
if length == 2:
if is_prime(a[start] + a[start + 1]):
count += 1
else:
for i in range(1, length - 1, 1):
if is_prime(a[start] + a[start + i]):
a[start + i], a[start + 1] = a[start + 1], a[start + i]
count += prime_triangle_count(a, start + 1, length - 1)
a[start + i], a[start + 1] = a[start + 1], a[start + i]
return count
def print_row(a: array):
if a == []:
return
print("%2d"% a[0], end=" ")
for x in a[1:]:
print("%2d"% x, end=" ")
print()
for n in range(2, 21):
tr: array = [_ for _ in range(1, n + 1)]
if prime_triangle_row(tr, 0, n):
print_row(tr)
print()
for n in range(2, 21):
tr: array = [_ for _ in range(1, n + 1)]
if n > 2:
print(" ", end="")
print(prime_triangle_count(tr, 0, n), end="")
print()
|
Priority queue | Python | A queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
;Task:
Create a priority queue. The queue must support at least two operations:
:# Insertion. An element is added to the queue with a priority (a numeric value).
:# Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
'''Priority''' '''Task'''
---------- ----------------
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has '''O(log n)''' insertion and extraction time, where '''n''' is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
| >>> import queue
>>> help(queue.PriorityQueue)
Help on class PriorityQueue in module queue:
class PriorityQueue(Queue)
| Variant of Queue that retrieves open entries in priority order (lowest first).
|
| Entries are typically tuples of the form: (priority number, data).
|
| Method resolution order:
| PriorityQueue
| Queue
| builtins.object
|
| Methods inherited from Queue:
|
| __init__(self, maxsize=0)
|
| empty(self)
| Return True if the queue is empty, False otherwise (not reliable!).
|
| This method is likely to be removed at some point. Use qsize() == 0
| as a direct substitute, but be aware that either approach risks a race
| condition where a queue can grow before the result of empty() or
| qsize() can be used.
|
| To create code that needs to wait for all queued tasks to be
| completed, the preferred technique is to use the join() method.
|
| full(self)
| Return True if the queue is full, False otherwise (not reliable!).
|
| This method is likely to be removed at some point. Use qsize() >= n
| as a direct substitute, but be aware that either approach risks a race
| condition where a queue can shrink before the result of full() or
| qsize() can be used.
|
| get(self, block=True, timeout=None)
| Remove and return an item from the queue.
|
| If optional args 'block' is true and 'timeout' is None (the default),
| block if necessary until an item is available. If 'timeout' is
| a positive number, it blocks at most 'timeout' seconds and raises
| the Empty exception if no item was available within that time.
| Otherwise ('block' is false), return an item if one is immediately
| available, else raise the Empty exception ('timeout' is ignored
| in that case).
|
| get_nowait(self)
| Remove and return an item from the queue without blocking.
|
| Only get an item if one is immediately available. Otherwise
| raise the Empty exception.
|
| join(self)
| Blocks until all items in the Queue have been gotten and processed.
|
| The count of unfinished tasks goes up whenever an item is added to the
| queue. The count goes down whenever a consumer thread calls task_done()
| to indicate the item was retrieved and all work on it is complete.
|
| When the count of unfinished tasks drops to zero, join() unblocks.
|
| put(self, item, block=True, timeout=None)
| Put an item into the queue.
|
| If optional args 'block' is true and 'timeout' is None (the default),
| block if necessary until a free slot is available. If 'timeout' is
| a positive number, it blocks at most 'timeout' seconds and raises
| the Full exception if no free slot was available within that time.
| Otherwise ('block' is false), put an item on the queue if a free slot
| is immediately available, else raise the Full exception ('timeout'
| is ignored in that case).
|
| put_nowait(self, item)
| Put an item into the queue without blocking.
|
| Only enqueue the item if a free slot is immediately available.
| Otherwise raise the Full exception.
|
| qsize(self)
| Return the approximate size of the queue (not reliable!).
|
| task_done(self)
| Indicate that a formerly enqueued task is complete.
|
| Used by Queue consumer threads. For each get() used to fetch a task,
| a subsequent call to task_done() tells the queue that the processing
| on the task is complete.
|
| If a join() is currently blocking, it will resume when all items
| have been processed (meaning that a task_done() call was received
| for every item that had been put() into the queue).
|
| Raises a ValueError if called more times than there were items
| placed in the queue.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Queue:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
>>> |
Pseudo-random numbers/Combined recursive generator MRG32k3a | Python | MRG32k3a Combined recursive generator (pseudo-code):
/* Constants */
/* First generator */
a1 = [0, 1403580, -810728]
m1 = 2**32 - 209
/* Second Generator */
a2 = [527612, 0, -1370589]
m2 = 2**32 - 22853
d = m1 + 1
class MRG32k3a
x1 = [0, 0, 0] /* list of three last values of gen #1 */
x2 = [0, 0, 0] /* list of three last values of gen #2 */
method seed(u64 seed_state)
assert seed_state in range >0 and < d
x1 = [seed_state, 0, 0]
x2 = [seed_state, 0, 0]
end method
method next_int()
x1i = (a1[0]*x1[0] + a1[1]*x1[1] + a1[2]*x1[2]) mod m1
x2i = (a2[0]*x2[0] + a2[1]*x2[1] + a2[2]*x2[2]) mod m2
x1 = [x1i, x1[0], x1[1]] /* Keep last three */
x2 = [x2i, x2[0], x2[1]] /* Keep last three */
z = (x1i - x2i) % m1
answer = (z + 1)
return answer
end method
method next_float():
return float next_int() / d
end method
end class
:MRG32k3a Use:
random_gen = instance MRG32k3a
random_gen.seed(1234567)
print(random_gen.next_int()) /* 1459213977 */
print(random_gen.next_int()) /* 2827710106 */
print(random_gen.next_int()) /* 4245671317 */
print(random_gen.next_int()) /* 3877608661 */
print(random_gen.next_int()) /* 2595287583 */
;Task
* Generate a class/set of functions that generates pseudo-random
numbers as shown above.
* Show that the first five integers generated with the seed `1234567`
are as shown above
* Show that for an initial seed of '987654321' the counts of 100_000
repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20002, 1: 20060, 2: 19948, 3: 20059, 4: 19931
* Show your output here, on this page.
| # Constants
a1 = [0, 1403580, -810728]
m1 = 2**32 - 209
#
a2 = [527612, 0, -1370589]
m2 = 2**32 - 22853
#
d = m1 + 1
class MRG32k3a():
def __init__(self, seed_state=123):
self.seed(seed_state)
def seed(self, seed_state):
assert 0 <seed_state < d, f"Out of Range 0 x < {d}"
self.x1 = [seed_state, 0, 0]
self.x2 = [seed_state, 0, 0]
def next_int(self):
"return random int in range 0..d"
x1i = sum(aa * xx for aa, xx in zip(a1, self.x1)) % m1
x2i = sum(aa * xx for aa, xx in zip(a2, self.x2)) % m2
self.x1 = [x1i] + self.x1[:2]
self.x2 = [x2i] + self.x2[:2]
z = (x1i - x2i) % m1
answer = (z + 1)
return answer
def next_float(self):
"return random float between 0 and 1"
return self.next_int() / d
if __name__ == '__main__':
random_gen = MRG32k3a()
random_gen.seed(1234567)
for i in range(5):
print(random_gen.next_int())
random_gen.seed(987654321)
hist = {i:0 for i in range(5)}
for i in range(100_000):
hist[int(random_gen.next_float() *5)] += 1
print(hist) |
Pseudo-random numbers/Middle-square method | Python | {{Wikipedia|Middle-square method|en}}
; The Method:
To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers.
; Pseudo code:
var seed = 675248
function random()
var s = str(seed * seed) 'str: turn a number into string
do while not len(s) = 12
s = "0" + s 'add zeroes before the string
end do
seed = val(mid(s, 4, 6)) 'mid: string variable, start, length
'val: turn a string into number
return seed
end function
; Middle-square method use:
for i = 1 to 5
print random()
end for
;Task:
* Generate a class/set of functions that generates pseudo-random
numbers (6 digits) as shown above.
* Show the first five integers generated with the seed 675248 as shown above.
* Show your output here, on this page.
| seed = 675248
def random():
global seed
seed = int(str(seed ** 2).zfill(12)[3:9])
return seed
for _ in range(5):
print(random())
|
Pseudo-random numbers/PCG32 | Python | Some definitions to help in the explanation:
:Floor operation
::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
::Greatest integer less than or equal to a real number.
:Bitwise Logical shift operators (c-inspired)
::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
::Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
::Examples are shown for 8 bit binary numbers; most significant bit to the left.
:: '''<<''' Logical shift left by given number of bits.
:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100
:: '''>>''' Logical shift right by given number of bits.
:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101
:'''^''' Bitwise exclusive-or operator
::https://en.wikipedia.org/wiki/Exclusive_or
::Bitwise comparison for if bits differ
:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110
:'''|''' Bitwise or operator
::https://en.wikipedia.org/wiki/Bitwise_operation#OR
::Bitwise comparison gives 1 if any of corresponding bits are 1
:::E.g Binary 00110101 '''|''' Binary 00110011 == Binary 00110111
;PCG32 Generator (pseudo-code):
PCG32 has two unsigned 64-bit integers of internal state:
# '''state''': All 2**64 values may be attained.
# '''sequence''': Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime).
Values of sequence allow 2**63 ''different'' sequences of random numbers from the same state.
The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-
const N<-U64 6364136223846793005
const inc<-U64 (seed_sequence << 1) | 1
state<-U64 ((inc+seed_state)*N+inc
do forever
xs<-U32 (((state>>18)^state)>>27)
rot<-INT (state>>59)
OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))
state<-state*N+inc
end do
Note that this an anamorphism - dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.
;Task:
* Generate a class/set of functions that generates pseudo-random
numbers using the above.
* Show that the first five integers generated with the seed 42, 54
are: 2707161783 2068313097 3122475824 2211639955 3215226955
* Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
:Is as follows:
0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005
* Show your output here, on this page.
| mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
CONST = 6364136223846793005
class PCG32():
def __init__(self, seed_state=None, seed_sequence=None):
if all(type(x) == int for x in (seed_state, seed_sequence)):
self.seed(seed_state, seed_sequence)
else:
self.state = self.inc = 0
def seed(self, seed_state, seed_sequence):
self.state = 0
self.inc = ((seed_sequence << 1) | 1) & mask64
self.next_int()
self.state = (self.state + seed_state)
self.next_int()
def next_int(self):
"return random 32 bit unsigned int"
old = self.state
self.state = ((old * CONST) + self.inc) & mask64
xorshifted = (((old >> 18) ^ old) >> 27) & mask32
rot = (old >> 59) & mask32
answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))
answer = answer &mask32
return answer
def next_float(self):
"return random float between 0 and 1"
return self.next_int() / (1 << 32)
if __name__ == '__main__':
random_gen = PCG32()
random_gen.seed(42, 54)
for i in range(5):
print(random_gen.next_int())
random_gen.seed(987654321, 1)
hist = {i:0 for i in range(5)}
for i in range(100_000):
hist[int(random_gen.next_float() *5)] += 1
print(hist) |
Pseudo-random numbers/Xorshift star | Python | Some definitions to help in the explanation:
:Floor operation
::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
::Greatest integer less than or equal to a real number.
:Bitwise Logical shift operators (c-inspired)
::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
::Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
::Examples are shown for 8 bit binary numbers; most significant bit to the left.
:: '''<<''' Logical shift left by given number of bits.
:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100
:: '''>>''' Logical shift right by given number of bits.
:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101
:'''^''' Bitwise exclusive-or operator
::https://en.wikipedia.org/wiki/Exclusive_or
::Bitwise comparison for if bits differ
:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110
;Xorshift_star Generator (pseudo-code):
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
:;Xorshift use:
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
;Task:
* Generate a class/set of functions that generates pseudo-random
numbers as shown above.
* Show that the first five integers genrated with the seed 1234567
are as shown above
* Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
:Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
* Show your output here, on this page.
| mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
const = 0x2545F4914F6CDD1D
class Xorshift_star():
def __init__(self, seed=0):
self.state = seed & mask64
def seed(self, num):
self.state = num & mask64
def next_int(self):
"return random int between 0 and 2**32"
x = self.state
x = (x ^ (x >> 12)) & mask64
x = (x ^ (x << 25)) & mask64
x = (x ^ (x >> 27)) & mask64
self.state = x
answer = (((x * const) & mask64) >> 32) & mask32
return answer
def next_float(self):
"return random float between 0 and 1"
return self.next_int() / (1 << 32)
if __name__ == '__main__':
random_gen = Xorshift_star()
random_gen.seed(1234567)
for i in range(5):
print(random_gen.next_int())
random_gen.seed(987654321)
hist = {i:0 for i in range(5)}
for i in range(100_000):
hist[int(random_gen.next_float() *5)] += 1
print(hist) |
Pythagoras tree | Python | The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem.
;Task
Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions).
;Related tasks
* Fractal tree
| from turtle import goto, pu, pd, color, done
def level(ax, ay, bx, by, depth=0):
if depth > 0:
dx,dy = bx-ax, ay-by
x3,y3 = bx-dy, by-dx
x4,y4 = ax-dy, ay-dx
x5,y5 = x4 + (dx - dy)/2, y4 - (dx + dy)/2
goto(ax, ay), pd()
for x, y in ((bx, by), (x3, y3), (x4, y4), (ax, ay)):
goto(x, y)
pu()
level(x4,y4, x5,y5, depth - 1)
level(x5,y5, x3,y3, depth - 1)
if __name__ == '__main__':
color('red', 'yellow')
pu()
level(-100, 500, 100, 500, depth=8)
done() |
Pythagorean quadruples | Python from Julia | One form of '''Pythagorean quadruples''' is (for positive integers '''a''', '''b''', '''c''', and '''d'''):
:::::::: a2 + b2 + c2 = d2
An example:
:::::::: 22 + 32 + 62 = 72
::::: which is:
:::::::: 4 + 9 + 36 = 49
;Task:
For positive integers up '''2,200''' (inclusive), for all values of '''a''',
'''b''', '''c''', and '''d''',
find (and show here) those values of '''d''' that ''can't'' be represented.
Show the values of '''d''' on one line of output (optionally with a title).
;Related tasks:
* [[Euler's sum of powers conjecture]].
* [[Pythagorean triples]].
;Reference:
:* the Wikipedia article: Pythagorean quadruple.
| def quad(top=2200):
r = [False] * top
ab = [False] * (top * 2)**2
for a in range(1, top):
for b in range(a, top):
ab[a * a + b * b] = True
s = 3
for c in range(1, top):
s1, s, s2 = s, s + 2, s + 2
for d in range(c + 1, top):
if ab[s1]:
r[d] = True
s1 += s2
s2 += 2
return [i for i, val in enumerate(r) if not val and i]
if __name__ == '__main__':
n = 2200
print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}") |
Pythagorean quadruples | Python from AppleScript | One form of '''Pythagorean quadruples''' is (for positive integers '''a''', '''b''', '''c''', and '''d'''):
:::::::: a2 + b2 + c2 = d2
An example:
:::::::: 22 + 32 + 62 = 72
::::: which is:
:::::::: 4 + 9 + 36 = 49
;Task:
For positive integers up '''2,200''' (inclusive), for all values of '''a''',
'''b''', '''c''', and '''d''',
find (and show here) those values of '''d''' that ''can't'' be represented.
Show the values of '''d''' on one line of output (optionally with a title).
;Related tasks:
* [[Euler's sum of powers conjecture]].
* [[Pythagorean triples]].
;Reference:
:* the Wikipedia article: Pythagorean quadruple.
| '''Pythagorean Quadruples'''
from itertools import islice, takewhile
# unrepresentables :: () -> [Int]
def unrepresentables():
'''A non-finite stream of powers of two which can
not be represented as a Pythagorean quadruple.
'''
return merge(
powersOfTwo()
)(
5 * x for x in powersOfTwo()
)
# powersOfTwo :: Gen [Int]
def powersOfTwo():
'''A non-finite stream of successive powers of two.
'''
def double(x):
return 2 * x
return iterate(double)(1)
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''For positive integers up to 2,200 (inclusive)
'''
def p(x):
return 2200 >= x
print(
list(
takewhile(p, unrepresentables())
)
)
# ----------------------- GENERIC ------------------------
# iterate :: (a -> a) -> a -> Gen [a]
def iterate(f):
'''An infinite list of repeated
applications of f to x.
'''
def go(x):
v = x
while True:
yield v
v = f(v)
return go
# merge :: Gen [Int] -> Gen [Int] -> Gen [Int]
def merge(ga):
'''An ordered stream of values drawn from two
other ordered streams.
'''
def go(gb):
def f(ma, mb):
a, b = ma, mb
while a and b:
ta, tb = a, b
if ta[0] < tb[0]:
yield ta[0]
a = uncons(ta[1])
else:
yield tb[0]
b = uncons(tb[1])
return f(uncons(ga), uncons(gb))
return go
# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.
'''
def go(xs):
return (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
return go
# uncons :: [a] -> Maybe (a, [a])
def uncons(xs):
'''The deconstruction of a non-empty list
(or generator stream) into two parts:
a head value, and the remaining values.
'''
if isinstance(xs, list):
return (xs[0], xs[1:]) if xs else None
else:
nxt = take(1)(xs)
return (nxt[0], xs) if nxt else None
# MAIN ---
if __name__ == '__main__':
main() |
Pythagorean triples | Python | A Pythagorean triple is defined as three positive integers (a, b, c) where a < b < c, and a^2+b^2=c^2.
They are called primitive triples if a, b, c are co-prime, that is, if their pairwise greatest common divisors {\rm gcd}(a, b) = {\rm gcd}(a, c) = {\rm gcd}(b, c) = 1.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ({\rm gcd}(a, b) = 1).
Each triple forms the length of the sides of a right triangle, whose perimeter is P=a+b+c.
;Task:
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
;Extra credit:
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
;Related tasks:
* [[Euler's sum of powers conjecture]]
* [[List comprehensions]]
* [[Pythagorean quadruples]]
| from fractions import gcd
def pt1(maxperimeter=100):
'''
# Naive method
'''
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
#
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
'''
# Parent/child relationship method:
# http://en.wikipedia.org/wiki/Formulas_for_generating_Pythagorean_triples#XI.
'''
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
|
Quaternion type | Python | complex numbers.
A complex number has a real and complex part, sometimes written as a + bi,
where a and b stand for real numbers, and i stands for the square root of minus 1.
An example of a complex number might be -3 + 2i,
where the real part, a is '''-3.0''' and the complex part, b is '''+2.0'''.
A quaternion has one real part and ''three'' imaginary parts, i, j, and k.
A quaternion might be written as a + bi + cj + dk.
In the quaternion numbering system:
:::* ii = jj = kk = ijk = -1, or more simply,
:::* ii = jj = kk = ijk = -1.
The order of multiplication is important, as, in general, for two quaternions:
:::: q1 and q2: q1q2 q2q1.
An example of a quaternion might be 1 +2i +3j +4k
There is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position.
So the example above would be written as (1, 2, 3, 4)
;Task:
Given the three quaternions and their components:
q = (1, 2, 3, 4) = (a, b, c, d)
q1 = (2, 3, 4, 5) = (a1, b1, c1, d1)
q2 = (3, 4, 5, 6) = (a2, b2, c2, d2)
And a wholly real number r = 7.
Create functions (or classes) to perform simple maths with quaternions including computing:
# The norm of a quaternion: = \sqrt{a^2 + b^2 + c^2 + d^2}
# The negative of a quaternion: = (-a, -b, -c, -d)
# The conjugate of a quaternion: = ( a, -b, -c, -d)
# Addition of a real number r and a quaternion q: r + q = q + r = (a+r, b, c, d)
# Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2)
# Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr)
# Multiplication of two quaternions q1 and q2 is given by: ( a1a2 - b1b2 - c1c2 - d1d2, a1b2 + b1a2 + c1d2 - d1c2, a1c2 - b1d2 + c1a2 + d1b2, a1d2 + b1c2 - c1b2 + d1a2 )
# Show that, for the two quaternions q1 and q2: q1q2 q2q1
If a language has built-in support for quaternions, then use it.
;C.f.:
* [[Vector products]]
* On Quaternions; or on a new System of Imaginaries in Algebra. By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
| from collections import namedtuple
import math
class Q(namedtuple('Quaternion', 'real, i, j, k')):
'Quaternion type: Q(real=0.0, i=0.0, j=0.0, k=0.0)'
__slots__ = ()
def __new__(_cls, real=0.0, i=0.0, j=0.0, k=0.0):
'Defaults all parts of quaternion to zero'
return super().__new__(_cls, float(real), float(i), float(j), float(k))
def conjugate(self):
return Q(self.real, -self.i, -self.j, -self.k)
def _norm2(self):
return sum( x*x for x in self)
def norm(self):
return math.sqrt(self._norm2())
def reciprocal(self):
n2 = self._norm2()
return Q(*(x / n2 for x in self.conjugate()))
def __str__(self):
'Shorter form of Quaternion as string'
return 'Q(%g, %g, %g, %g)' % self
def __neg__(self):
return Q(-self.real, -self.i, -self.j, -self.k)
def __add__(self, other):
if type(other) == Q:
return Q( *(s+o for s,o in zip(self, other)) )
try:
f = float(other)
except:
return NotImplemented
return Q(self.real + f, self.i, self.j, self.k)
def __radd__(self, other):
return Q.__add__(self, other)
def __mul__(self, other):
if type(other) == Q:
a1,b1,c1,d1 = self
a2,b2,c2,d2 = other
return Q(
a1*a2 - b1*b2 - c1*c2 - d1*d2,
a1*b2 + b1*a2 + c1*d2 - d1*c2,
a1*c2 - b1*d2 + c1*a2 + d1*b2,
a1*d2 + b1*c2 - c1*b2 + d1*a2 )
try:
f = float(other)
except:
return NotImplemented
return Q(self.real * f, self.i * f, self.j * f, self.k * f)
def __rmul__(self, other):
return Q.__mul__(self, other)
def __truediv__(self, other):
if type(other) == Q:
return self.__mul__(other.reciprocal())
try:
f = float(other)
except:
return NotImplemented
return Q(self.real / f, self.i / f, self.j / f, self.k / f)
def __rtruediv__(self, other):
return other * self.reciprocal()
__div__, __rdiv__ = __truediv__, __rtruediv__
Quaternion = Q
q = Q(1, 2, 3, 4)
q1 = Q(2, 3, 4, 5)
q2 = Q(3, 4, 5, 6)
r = 7 |
Quine | Python 2.x and 3.x | A quine is a self-referential program that can,
without any external access, output its own source.
A '''quine''' (named after Willard Van Orman Quine) is also known as:
::* ''self-reproducing automata'' (1972)
::* ''self-replicating program'' or ''self-replicating computer program''
::* ''self-reproducing program'' or ''self-reproducing computer program''
::* ''self-copying program'' or ''self-copying computer program''
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once ''quoted'' in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
;Task:
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
* Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
** Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
** Another solution is to construct the quote character from its [[character code]], without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
* Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
** If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
** Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
** Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
'''Next to the Quines presented here, many other versions can be found on the Quine page.'''
;Related task:
:* print itself.
| import sys,inspect;sys.stdout.write(inspect.getsource(inspect.currentframe())) |
Quine | Python 3.8+ | A quine is a self-referential program that can,
without any external access, output its own source.
A '''quine''' (named after Willard Van Orman Quine) is also known as:
::* ''self-reproducing automata'' (1972)
::* ''self-replicating program'' or ''self-replicating computer program''
::* ''self-reproducing program'' or ''self-reproducing computer program''
::* ''self-copying program'' or ''self-copying computer program''
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once ''quoted'' in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
;Task:
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
* Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
** Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
** Another solution is to construct the quote character from its [[character code]], without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
* Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
** If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
** Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
** Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
'''Next to the Quines presented here, many other versions can be found on the Quine page.'''
;Related task:
:* print itself.
| data = (
'ZGF0YSA9ICgKCSc=',
'JywKCSc=',
'JwopCnByZWZpeCwgc2VwYXJhdG9yLCBzdWZmaXggPSAoZC5kZWNvZGUoJ2Jhc2U2NCcpIGZvciBkIGluIGRhdGEpCnByaW50IHByZWZpeCArIGRhdGFbMF0gKyBzZXBhcmF0b3IgKyBkYXRhWzFdICsgc2VwYXJhdG9yICsgZGF0YVsyXSArIHN1ZmZpeA=='
)
prefix, separator, suffix = (d.decode('base64') for d in data)
print prefix + data[0] + separator + data[1] + separator + data[2] + suffix |
RIPEMD-160 | Python | '''RIPEMD-160''' is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like [[MD4]] (RFC 1320).
Find the RIPEMD-160 message digest of a string of [[octet]]s.
Use the ASCII encoded string "Rosetta Code".
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
| Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import hashlib
>>> h = hashlib.new('ripemd160')
>>> h.update(b"Rosetta Code")
>>> h.hexdigest()
'b3be159860842cebaa7174c8fff0aa9e50a5199f'
>>> |
RPG attributes generator | Python | '''RPG''' = Role Playing Game.
You're running a tabletop RPG, and your players are creating characters.
Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.
One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.
Some players like to assign values to their attributes in the order they're rolled.
To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:
* The total of all character attributes must be at least 75.
* At least two of the attributes must be at least 15.
However, this can require a lot of manual dice rolling. A programatic solution would be much faster.
;Task:
Write a program that:
# Generates 4 random, whole values between 1 and 6.
# Saves the sum of the 3 largest values.
# Generates a total of 6 values this way.
# Displays the total, and all 6 values once finished.
* The order in which each value was generated must be preserved.
* The total of all 6 values must be at least 75.
* At least 2 of the values must be 15 or more.
| import random
random.seed()
attributes_total = 0
count = 0
while attributes_total < 75 or count < 2:
attributes = []
for attribute in range(0, 6):
rolls = []
for roll in range(0, 4):
result = random.randint(1, 6)
rolls.append(result)
sorted_rolls = sorted(rolls)
largest_3 = sorted_rolls[1:]
rolls_total = sum(largest_3)
if rolls_total >= 15:
count += 1
attributes.append(rolls_total)
attributes_total = sum(attributes)
print(attributes_total, attributes) |
RPG attributes generator | Python 3.7 | '''RPG''' = Role Playing Game.
You're running a tabletop RPG, and your players are creating characters.
Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.
One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.
Some players like to assign values to their attributes in the order they're rolled.
To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:
* The total of all character attributes must be at least 75.
* At least two of the attributes must be at least 15.
However, this can require a lot of manual dice rolling. A programatic solution would be much faster.
;Task:
Write a program that:
# Generates 4 random, whole values between 1 and 6.
# Saves the sum of the 3 largest values.
# Generates a total of 6 values this way.
# Displays the total, and all 6 values once finished.
* The order in which each value was generated must be preserved.
* The total of all 6 values must be at least 75.
* At least 2 of the values must be 15 or more.
| '''RPG Attributes Generator'''
from itertools import islice
from random import randint
from operator import eq
# heroes :: Gen IO [(Int, Int, Int, Int, Int, Int)]
def heroes(p):
'''Non-finite list of heroes matching
the requirements of predicate p.
'''
while True:
yield tuple(
until(p)(character)([])
)
# character :: () -> IO [Int]
def character(_):
'''A random character with six
integral attributes.
'''
return [
sum(sorted(map(
randomRInt(1)(6),
enumFromTo(1)(4)
))[1:])
for _ in enumFromTo(1)(6)
]
# ------------------------- TEST --------------------------
# main :: IO ()
def main():
'''Test :: Sample of 10'''
# seventyFivePlusWithTwo15s :: [Int] -> Bool
def seventyFivePlusIncTwo15s(xs):
'''Sums to 75 or more,
and includes at least two 15s.
'''
return 75 <= sum(xs) and (
1 < len(list(filter(curry(eq)(15), xs)))
)
print('A sample of 10:\n')
print(unlines(
str(sum(x)) + ' -> ' + str(x) for x
in take(10)(heroes(
seventyFivePlusIncTwo15s
))
))
# ------------------------- GENERIC -------------------------
# curry :: ((a, b) -> c) -> a -> b -> c
def curry(f):
'''A curried function derived
from an uncurried function.
'''
return lambda x: lambda y: f(x, y)
# enumFromTo :: Int -> Int -> [Int]
def enumFromTo(m):
'''Enumeration of integer values [m..n]'''
return lambda n: range(m, 1 + n)
# randomRInt :: Int -> Int -> IO () -> Int
def randomRInt(m):
'''The return value of randomRInt is itself
a function. The returned function, whenever
called, yields a a new pseudo-random integer
in the range [m..n].
'''
return lambda n: lambda _: randint(m, 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))
)
# unlines :: [String] -> String
def unlines(xs):
'''A single string formed by the intercalation
of a list of strings with the newline character.
'''
return '\n'.join(xs)
# until :: (a -> Bool) -> (a -> a) -> a -> a
def until(p):
'''The result of repeatedly applying f until p holds.
The initial seed value is x.
'''
def go(f, x):
v = x
while not p(v):
v = f(v)
return v
return lambda f: lambda x: go(f, x)
if __name__ == '__main__':
main() |
Random Latin squares | Python | A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once.
For the purposes of this task, a random Latin square of size n is a Latin square constructed or generated by a probabilistic procedure such that the probability of any particular Latin square of size n being produced is non-zero.
;Example n=4 randomised Latin square:
0 2 3 1
2 1 0 3
3 0 1 2
1 3 2 0
;Task:
# Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.
# Use the function to generate ''and show here'', two randomly generated squares of size 5.
;Note:
Strict ''uniformity'' in the random generation is a hard problem and '''not''' a requirement of the task.
;Related tasks:
* [[Latin Squares in reduced form/Randomizing using Jacobson and Matthews' Technique]]
* [[Latin Squares in reduced form]]
;Reference:
* Wikipedia: Latin square
* OEIS: A002860
| from random import choice, shuffle
from copy import deepcopy
def rls(n):
if n <= 0:
return []
else:
symbols = list(range(n))
square = _rls(symbols)
return _shuffle_transpose_shuffle(square)
def _shuffle_transpose_shuffle(matrix):
square = deepcopy(matrix)
shuffle(square)
trans = list(zip(*square))
shuffle(trans)
return trans
def _rls(symbols):
n = len(symbols)
if n == 1:
return [symbols]
else:
sym = choice(symbols)
symbols.remove(sym)
square = _rls(symbols)
square.append(square[0].copy())
for i in range(n):
square[i].insert(i, sym)
return square
def _to_text(square):
if square:
width = max(len(str(sym)) for row in square for sym in row)
txt = '\n'.join(' '.join(f"{sym:>{width}}" for sym in row)
for row in square)
else:
txt = ''
return txt
def _check(square):
transpose = list(zip(*square))
assert _check_rows(square) and _check_rows(transpose), \
"Not a Latin square"
def _check_rows(square):
if not square:
return True
set_row0 = set(square[0])
return all(len(row) == len(set(row)) and set(row) == set_row0
for row in square)
if __name__ == '__main__':
for i in [3, 3, 5, 5, 12]:
square = rls(i)
print(_to_text(square))
_check(square)
print() |
Random number generator (device) | Python | If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:
show how to obtain a random 32-bit number from that mechanism.
;Related task
* [[Random_number_generator_(included)]]
| import random
rand = random.SystemRandom()
rand.randint(1,10) |
Random number generator (included) | Python | The task is to:
: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
: If possible, give a link to a wider explanation of the algorithm used.
Note: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
| Python uses the [[wp:Mersenne twister|Mersenne twister]] algorithm accessed via the built-in [http://docs.python.org/library/random.html random module].
|
Random sentence from book | Python | * Read in the book "The War of the Worlds", by H. G. Wells.
* Skip to the start of the book, proper.
* Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ?
* Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too).
* Keep account of what words follow ''two'' words and how many times it is seen, (again treating sentence terminators as words too).
* Assume that a sentence starts with a not to be shown full-stop character then ''use a weighted random choice'' of the possible words that may follow a full-stop to add to the sentence.
* Then repeatedly add words to the sentence based on weighted random choices of what words my follow the last two words to extend the sentence.
* Stop after adding a sentence ending punctuation character.
* Tidy and then print the sentence.
Show examples of random sentences generated.
;Related task
* [[Markov_chain_text_generator]]
| from urllib.request import urlopen
import re
from string import punctuation
from collections import Counter, defaultdict
import random
# The War of the Worlds, by H. G. Wells
text_url = 'http://www.gutenberg.org/files/36/36-0.txt'
text_start = 'No one would have believed'
sentence_ending = '.!?'
sentence_pausing = ',;:'
def read_book(text_url, text_start) -> str:
with urlopen(text_url) as book:
text = book.read().decode('utf-8')
return text[text.index(text_start):]
def remove_punctuation(text: str, keep=sentence_ending+sentence_pausing)-> str:
"Remove punctuation, keeping some"
to_remove = ''.join(set(punctuation) - set(keep))
text = text.translate(str.maketrans(to_remove, ' ' * len(to_remove))).strip()
text = re.sub(fr"[^a-zA-Z0-9{keep}\n ]+", ' ', text)
# Remove duplicates and put space around remaining punctuation
if keep:
text = re.sub(f"([{keep}])+", r" \1 ", text).strip()
if text[-1] not in sentence_ending:
text += ' .'
return text.lower()
def word_follows_words(txt_with_pauses_and_endings):
"return dict of freq of words following one/two words"
words = ['.'] + txt_with_pauses_and_endings.strip().split()
# count of what word follows this
word2next = defaultdict(lambda :defaultdict(int))
word2next2 = defaultdict(lambda :defaultdict(int))
for lh, rh in zip(words, words[1:]):
word2next[lh][rh] += 1
for lh, mid, rh in zip(words, words[1:], words[2:]):
word2next2[(lh, mid)][rh] += 1
return dict(word2next), dict(word2next2)
def gen_sentence(word2next, word2next2) -> str:
s = ['.']
s += random.choices(*zip(*word2next[s[-1]].items()))
while True:
s += random.choices(*zip(*word2next2[(s[-2], s[-1])].items()))
if s[-1] in sentence_ending:
break
s = ' '.join(s[1:]).capitalize()
s = re.sub(fr" ([{sentence_ending+sentence_pausing}])", r'\1', s)
s = re.sub(r" re\b", "'re", s)
s = re.sub(r" s\b", "'s", s)
s = re.sub(r"\bi\b", "I", s)
return s
if __name__ == "__main__":
txt_with_pauses_and_endings = remove_punctuation(read_book(text_url, text_start))
word2next, word2next2 = word_follows_words(txt_with_pauses_and_endings)
#%%
sentence = gen_sentence(word2next, word2next2)
print(sentence) |
Range consolidation | Python | Define a range of numbers '''R''', with bounds '''b0''' and '''b1''' covering all numbers ''between and including both bounds''.
That range can be shown as:
::::::::: '''[b0, b1]'''
:::::::: or equally as:
::::::::: '''[b1, b0]'''
Given two ranges, the act of consolidation between them compares the two ranges:
* If one range covers all of the other then the result is that encompassing range.
* If the ranges touch or intersect then the result is ''one'' new single range covering the overlapping ranges.
* Otherwise the act of consolidation is to return the two non-touching ranges.
Given '''N''' ranges where '''N > 2''' then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible.
If '''N < 2''' then range consolidation has no strict meaning and the input can be returned.
;Example 1:
: Given the two ranges '''[1, 2.5]''' and '''[3, 4.2]''' then
: there is no common region between the ranges and the result is the same as the input.
;Example 2:
: Given the two ranges '''[1, 2.5]''' and '''[1.8, 4.7]''' then
: there is : an overlap '''[2.5, 1.8]''' between the ranges and
: the result is the single range '''[1, 4.7]'''.
: Note that order of bounds in a range is not (yet) stated.
;Example 3:
: Given the two ranges '''[6.1, 7.2]''' and '''[7.2, 8.3]''' then
: they touch at '''7.2''' and
: the result is the single range '''[6.1, 8.3]'''.
;Example 4:
: Given the three ranges '''[1, 2]''' and '''[4, 8]''' and '''[2, 5]'''
: then there is no intersection of the ranges '''[1, 2]''' and '''[4, 8]'''
: but the ranges '''[1, 2]''' and '''[2, 5]''' overlap and
: consolidate to produce the range '''[1, 5]'''.
: This range, in turn, overlaps the other range '''[4, 8]''', and
: so consolidates to the final output of the single range '''[1, 8]'''.
;Task:
Let a normalized range display show the smaller bound to the left; and show the
range with the smaller lower bound to the left of other ranges when showing multiple ranges.
Output the ''normalized'' result of applying consolidation to these five sets of ranges:
[1.1, 2.2]
[6.1, 7.2], [7.2, 8.3]
[4, 3], [2, 1]
[4, 3], [2, 1], [-1, -2], [3.9, 10]
[1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]
Show all output here.
;See also:
* [[Set consolidation]]
* [[Set of real numbers]]
| def normalize(s):
return sorted(sorted(bounds) for bounds in s if bounds)
def consolidate(ranges):
norm = normalize(ranges)
for i, r1 in enumerate(norm):
if r1:
for r2 in norm[i+1:]:
if r2 and r1[-1] >= r2[0]: # intersect?
r1[:] = [r1[0], max(r1[-1], r2[-1])]
r2.clear()
return [rnge for rnge in norm if rnge]
if __name__ == '__main__':
for s in [
[[1.1, 2.2]],
[[6.1, 7.2], [7.2, 8.3]],
[[4, 3], [2, 1]],
[[4, 3], [2, 1], [-1, -2], [3.9, 10]],
[[1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]],
]:
print(f"{str(s)[1:-1]} => {str(consolidate(s))[1:-1]}")
|
Range consolidation | Python 3.7 | Define a range of numbers '''R''', with bounds '''b0''' and '''b1''' covering all numbers ''between and including both bounds''.
That range can be shown as:
::::::::: '''[b0, b1]'''
:::::::: or equally as:
::::::::: '''[b1, b0]'''
Given two ranges, the act of consolidation between them compares the two ranges:
* If one range covers all of the other then the result is that encompassing range.
* If the ranges touch or intersect then the result is ''one'' new single range covering the overlapping ranges.
* Otherwise the act of consolidation is to return the two non-touching ranges.
Given '''N''' ranges where '''N > 2''' then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible.
If '''N < 2''' then range consolidation has no strict meaning and the input can be returned.
;Example 1:
: Given the two ranges '''[1, 2.5]''' and '''[3, 4.2]''' then
: there is no common region between the ranges and the result is the same as the input.
;Example 2:
: Given the two ranges '''[1, 2.5]''' and '''[1.8, 4.7]''' then
: there is : an overlap '''[2.5, 1.8]''' between the ranges and
: the result is the single range '''[1, 4.7]'''.
: Note that order of bounds in a range is not (yet) stated.
;Example 3:
: Given the two ranges '''[6.1, 7.2]''' and '''[7.2, 8.3]''' then
: they touch at '''7.2''' and
: the result is the single range '''[6.1, 8.3]'''.
;Example 4:
: Given the three ranges '''[1, 2]''' and '''[4, 8]''' and '''[2, 5]'''
: then there is no intersection of the ranges '''[1, 2]''' and '''[4, 8]'''
: but the ranges '''[1, 2]''' and '''[2, 5]''' overlap and
: consolidate to produce the range '''[1, 5]'''.
: This range, in turn, overlaps the other range '''[4, 8]''', and
: so consolidates to the final output of the single range '''[1, 8]'''.
;Task:
Let a normalized range display show the smaller bound to the left; and show the
range with the smaller lower bound to the left of other ranges when showing multiple ranges.
Output the ''normalized'' result of applying consolidation to these five sets of ranges:
[1.1, 2.2]
[6.1, 7.2], [7.2, 8.3]
[4, 3], [2, 1]
[4, 3], [2, 1], [-1, -2], [3.9, 10]
[1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]
Show all output here.
;See also:
* [[Set consolidation]]
* [[Set of real numbers]]
| '''Range consolidation'''
from functools import reduce
# consolidated :: [(Float, Float)] -> [(Float, Float)]
def consolidated(xs):
'''A consolidated list of
[(Float, Float)] ranges.'''
def go(abetc, xy):
'''A copy of the accumulator abetc,
with its head range ab either:
1. replaced by or
2. merged with
the next range xy, or
with xy simply prepended.'''
if abetc:
a, b = abetc[0]
etc = abetc[1:]
x, y = xy
return [xy] + etc if y >= b else ( # ab replaced.
[(x, b)] + etc if y >= a else ( # xy + ab merged.
[xy] + abetc # xy simply prepended.
)
)
else:
return [xy]
def tupleSort(ab):
a, b = ab
return ab if a <= b else (b, a)
return reduce(
go,
sorted(map(tupleSort, xs), reverse=True),
[]
)
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Tests'''
print(
tabulated('Consolidation of numeric ranges:')(str)(str)(
consolidated
)([
[(1.1, 2.2)],
[(6.1, 7.2), (7.2, 8.3)],
[(4, 3), (2, 1)],
[(4, 3), (2, 1), (-1, -2), (3.9, 10)],
[(1, 3), (-6, -1), (-4, -5), (8, 2), (-6, -6)]
])
)
# GENERIC FUNCTIONS FOR DISPLAY ---------------------------
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(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
)
)
# MAIN ---
if __name__ == '__main__':
main() |
Range expansion | Python | {{:Range extraction/Format}}
;Task:
Expand the range description:
-6,-3--1,3-5,7-11,14,15,17-20
Note that the second element above,
is the '''range from minus 3 to ''minus'' 1'''.
;Related task:
* [[Range extraction]]
| def rangeexpand(txt):
lst = []
for r in txt.split(','):
if '-' in r[1:]:
r0, r1 = r[1:].split('-', 1)
lst += range(int(r[0] + r0), int(r1) + 1)
else:
lst.append(int(r))
return lst
print(rangeexpand('-6,-3--1,3-5,7-11,14,15,17-20')) |
Range expansion | Python 3.7 | {{:Range extraction/Format}}
;Task:
Expand the range description:
-6,-3--1,3-5,7-11,14,15,17-20
Note that the second element above,
is the '''range from minus 3 to ''minus'' 1'''.
;Related task:
* [[Range extraction]]
| '''Range expansion'''
from functools import (reduce)
# ------------------- EXPANSION FUNCTION -------------------
# rangeExpansion :: String -> [Int]
def rangeExpansion(s):
'''List of integers expanded from a
comma-delimited string of individual
numbers and hyphenated ranges.
'''
def go(a, x):
tpl = breakOn('-')(x[1:])
r = tpl[1]
return a + (
[int(x)] if not r
else enumFromTo(int(x[0] + tpl[0]))(
int(r[1:])
)
)
return reduce(go, s.split(','), [])
# -------------------------- TEST --------------------------
def main():
'''Expansion test'''
print(
fTable(__doc__ + ':')(
lambda x: "\n'" + str(x) + "'"
)(lambda x: '\n\n\t' + showList(x))(
rangeExpansion
)([
'-6,-3--1,3-5,7-11,14,15,17-20'
])
)
# ------------------- GENERIC FUNCTIONS --------------------
# breakOn :: String -> String -> (String, String)
def breakOn(needle):
'''A tuple of:
1. the prefix of haystack before needle,
2. the remainder of haystack, starting
with needle.
'''
def go(haystack):
xs = haystack.split(needle)
return (xs[0], haystack[len(xs[0]):]) if (
1 < len(xs)
) else (haystack, '')
return lambda haystack: go(haystack) if (
needle
) else None
# enumFromTo :: Int -> Int -> [Int]
def enumFromTo(m):
'''Enumeration of integer values [m..n]
'''
return lambda n: list(range(m, 1 + 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
# showList :: [a] -> String
def showList(xs):
'''Stringification of a list.
'''
return '[' + ','.join(str(x) for x in xs) + ']'
# MAIN ---
if __name__ == '__main__':
main() |
Range extraction | Python | {{:Range extraction/Format}}
;Task:
* Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
* Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
* Show the output of your program.
;Related task:
* [[Range expansion]]
| def range_extract(lst):
'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'
lenlst = len(lst)
i = 0
while i< lenlst:
low = lst[i]
while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
hi = lst[i]
if hi - low >= 2:
yield (low, hi)
elif hi - low == 1:
yield (low,)
yield (hi,)
else:
yield (low,)
i += 1
def printr(ranges):
print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)
for r in ranges ) )
if __name__ == '__main__':
for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,
8, 9, 10, 11, 14, 15, 17, 18, 19, 20],
[0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:
#print(list(range_extract(lst)))
printr(range_extract(lst)) |
Range extraction | Python 3.7 | {{:Range extraction/Format}}
;Task:
* Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
* Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
* Show the output of your program.
;Related task:
* [[Range expansion]]
| '''Range extraction'''
from functools import reduce
# rangeFormat :: [Int] -> String
def rangeFormat(xs):
'''Range-formatted display string for
a list of integers.
'''
return ','.join([
rangeString(x) for x
in splitBy(lambda a, b: 1 < b - a)(xs)
])
# rangeString :: [Int] -> String
def rangeString(xs):
'''Start and end of xs delimited by hyphens
if there are more than two integers.
Otherwise, comma-delimited xs.
'''
ys = [str(x) for x in xs]
return '-'.join([ys[0], ys[-1]]) if 2 < len(ys) else (
','.join(ys)
)
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Test'''
xs = [
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
]
print(
__doc__ + ':\n[' + '\n'.join(map(
lambda x: ' ' + repr(x)[1:-1],
chunksOf(11)(xs)
)) + " ]\n\n -> '" + rangeFormat(xs) + "'\n"
)
# 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 []
# splitBy :: (a -> a -> Bool) -> [a] -> [[a]]
def splitBy(p):
'''A list split wherever two consecutive
items match the binary predicate p.
'''
# step :: ([[a]], [a], a) -> a -> ([[a]], [a], a)
def step(acp, x):
acc, active, prev = acp
return (acc + [active], [x], x) if p(prev, x) else (
(acc, active + [x], x)
)
# go :: [a] -> [[a]]
def go(xs):
if 2 > len(xs):
return xs
else:
h = xs[0]
ys = reduce(step, xs[1:], ([], [h], h))
# The accumulated sublists, and the current group.
return ys[0] + [ys[1]]
return lambda xs: go(xs)
# MAIN ---
if __name__ == '__main__':
main() |
Rate counter | Python | Counting the frequency at which something occurs is a common activity in measuring performance and managing resources. In this task, we assume that there is some job which we want to perform repeatedly, and we want to know how quickly these jobs are being performed.
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
* Run N seconds worth of jobs and/or Y jobs.
* Report at least three distinct times.
Be aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can.
'''See also:''' [[System time]], [[Time a function]]
| import subprocess
import time
class Tlogger(object):
def __init__(self):
self.counts = 0
self.tottime = 0.0
self.laststart = 0.0
self.lastreport = time.time()
def logstart(self):
self.laststart = time.time()
def logend(self):
self.counts +=1
self.tottime += (time.time()-self.laststart)
if (time.time()-self.lastreport)>5.0: # report once every 5 seconds
self.report()
def report(self):
if ( self.counts > 4*self.tottime):
print "Subtask execution rate: %f times/second"% (self.counts/self.tottime);
else:
print "Average execution time: %f seconds"%(self.tottime/self.counts);
self.lastreport = time.time()
def taskTimer( n, subproc_args ):
logger = Tlogger()
for x in range(n):
logger.logstart()
p = subprocess.Popen(subproc_args)
p.wait()
logger.logend()
logger.report()
import timeit
import sys
def main( ):
# for accurate timing of code segments
s = """j = [4*n for n in range(50)]"""
timer = timeit.Timer(s)
rzlts = timer.repeat(5, 5000)
for t in rzlts:
print "Time for 5000 executions of statement = ",t
# subprocess execution timing
print "#times:",sys.argv[1]
print "Command:",sys.argv[2:]
print ""
for k in range(3):
taskTimer( int(sys.argv[1]), sys.argv[2:])
main() |
Read a specific line from a file | Python | Some languages have special semantics for obtaining a known line number from a file.
;Task:
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded).
If the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message.
If no special semantics are available for obtaining the required line, it is permissible to read line by line.
Note that empty lines are considered and should still be counted.
Also note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.
| from itertools import islice
with open('xxx.txt') as f:
try:
line = next(islice(f, 6, 7))
except StopIteration:
print('Not 7 lines in file') |
Recaman's sequence | Python | The '''Recaman's sequence''' generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated.
If the conditions ''don't'' hold then a(n) = a(n-1) + n.
;Task:
# Generate and show here the first 15 members of the sequence.
# Find and show here, the first duplicated number in the sequence.
# '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.
;References:
* A005132, The On-Line Encyclopedia of Integer Sequences.
* The Slightly Spooky Recaman Sequence, Numberphile video.
* Recaman's sequence, on Wikipedia.
| from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None # Set of results so far
self.n = None # n'th term (counting from zero)
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
yield nxt
while True:
an1, n = nxt, n + 1
nxt = an1 - n
if nxt < 0 or nxt in a:
nxt = an1 + n
a.add(nxt)
self.n = n
yield nxt
if __name__ == '__main__':
recamans = Recamans()
print("First fifteen members of Recamans sequence:",
list(islice(recamans(), 15)))
so_far = set()
for term in recamans():
if term in so_far:
print(f"First duplicate number in series is: a({recamans.n}) = {term}")
break
so_far.add(term)
n = 1_000
setn = set(range(n + 1)) # The target set of numbers to be covered
for _ in recamans():
if setn.issubset(recamans.a):
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
break |
Remove lines from a file | Python | Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2
Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed.
An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.
| #!/usr/bin/env python
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close() |
Rep-string | Python | Given a series of ones and zeroes in a string, define a repeated string or ''rep-string'' as a string which is created by repeating a substring of the ''first'' N characters of the string ''truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original''.
For example, the string '''10011001100''' is a rep-string as the leftmost four characters of '''1001''' are repeated three times and truncated on the right to give the original string.
Note that the requirement for having the repeat occur two or more times means that the repeating unit is ''never'' longer than half the length of the input string.
;Task:
* Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice).
* There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice.
* Use the function to indicate the repeating substring if any, in the following:
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
* Show your output on this page.
| def is_repeated(text):
'check if the first part of the string is repeated throughout the string'
for x in range(len(text)//2, 0, -1):
if text.startswith(text[x:]): return x
return 0
matchstr = """\
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
"""
for line in matchstr.split():
ln = is_repeated(line)
print('%r has a repetition length of %i i.e. %s'
% (line, ln, repr(line[:ln]) if ln else '*not* a rep-string')) |
Rep-string | Python 3.7 | Given a series of ones and zeroes in a string, define a repeated string or ''rep-string'' as a string which is created by repeating a substring of the ''first'' N characters of the string ''truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original''.
For example, the string '''10011001100''' is a rep-string as the leftmost four characters of '''1001''' are repeated three times and truncated on the right to give the original string.
Note that the requirement for having the repeat occur two or more times means that the repeating unit is ''never'' longer than half the length of the input string.
;Task:
* Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice).
* There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice.
* Use the function to indicate the repeating substring if any, in the following:
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
* Show your output on this page.
| '''Rep-strings'''
from itertools import (accumulate, chain, cycle, islice)
# repCycles :: String -> [String]
def repCycles(s):
'''Repeated sequences of characters in s.'''
n = len(s)
cs = list(s)
return [
x for x in
tail(inits(take(n // 2)(s)))
if cs == take(n)(cycle(x))
]
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Tests - longest cycle (if any) in each string.'''
print(
fTable('Longest cycles:\n')(repr)(
lambda xs: ''.join(xs[-1]) if xs else '(none)'
)(repCycles)([
'1001110011',
'1110111011',
'0010010010',
'1010101010',
'1111111111',
'0100101101',
'0100100',
'101',
'11',
'00',
'1',
])
)
# GENERIC -------------------------------------------------
# inits :: [a] -> [[a]]
def inits(xs):
'''all initial segments of xs, shortest first.'''
return accumulate(chain([[]], xs), lambda a, x: a + [x])
# tail :: [a] -> [a]
# tail :: Gen [a] -> [a]
def tail(xs):
'''The elements following the head of a
(non-empty) list or generator stream.'''
if isinstance(xs, list):
return xs[1:]
else:
list(islice(xs, 1)) # First item dropped.
return 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, tuple))
else list(islice(xs, n))
)
# OUTPUT FORMATTING ---------------------------------------
# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
'''Heading -> x display function ->
fx display function ->
f -> value list -> tabular string.
'''
def go(xShow, fxShow, f, xs):
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() |
Repeat | Python | Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| #!/usr/bin/python
def repeat(f,n):
for i in range(n):
f();
def procedure():
print("Example");
repeat(procedure,3); #prints "Example" (without quotes) three times, separated by newlines. |
Repeat | Python 3.7 | Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| '''Application of a given function, repeated N times'''
from itertools import repeat
from functools import reduce
from inspect import getsource
# applyN :: Int -> (a -> a) -> a -> a
def applyN(n):
'''n compounding applications of the supplied
function f. Equivalent to Church numeral n.
'''
def go(f):
return lambda x: reduce(
lambda a, g: g(a), repeat(f, n), x
)
return lambda f: go(f)
# MAIN ----------------------------------------------------
def main():
'''Tests - compounding repetition
of function application.
'''
def f(x):
return x + 'Example\n'
def g(x):
return 2 * x
def h(x):
return 1.05 * x
print(
fTable(__doc__ + ':')(
lambda fx: '\nRepeated * 3:\n (' + (
getsource(fst(fx)).strip() + ')(' +
repr(snd(fx)) + ')'
)
)(str)(
liftA2(applyN(3))(fst)(snd)
)([(f, '\n'), (g, 1), (h, 100)])
)
# GENERIC -------------------------------------------------
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
# fst :: (a, b) -> a
def fst(tpl):
'''First member of a pair.'''
return tpl[0]
# liftA2 :: (a0 -> b -> c) -> (a -> a0) -> (a -> b) -> a -> c
def liftA2(op):
'''Lift a binary function to a composition
over two other functions.
liftA2 (*) (+ 2) (+ 3) 7 == 90
'''
def go(f, g):
return lambda x: op(
f(x)
)(g(x))
return lambda f: lambda g: go(f, g)
# snd :: (a, b) -> b
def snd(tpl):
'''Second member of a pair.'''
return tpl[1]
# 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() |
Repunit primes | Python | portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, '''1'''. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.)
In base three: 111, 1111111, 1111111111111, etc.
''Repunit primes, by definition, are also [[circular primes]].''
Any repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits ''might'' be prime.
Rather than expanding the repunit out as a giant list of '''1'''s or converting to base 10, it is common to just list the ''number'' of '''1'''s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc.
Many of these sequences exist on OEIS, though they aren't specifically listed as "repunit prime digits" sequences.
Some bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already.
;Task
* For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000.
;Stretch
* Increase the limit to 2700 (or as high as you have patience for.)
;See also
;* Wikipedia: Repunit primes
;* OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2)
;* OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3)
;* OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5)
;* OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6)
;* OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7)
;* OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10)
;* OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11)
;* OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12)
;* OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13)
;* OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14)
;* OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15)
;* Related task: Circular primes
| from sympy import isprime
for b in range(2, 17):
print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))]) |
Resistor mesh | Python from D | Given 10x10 grid nodes (as shown in the image) interconnected by 1O resistors as shown,
find the resistance between points '''A''' and '''B'''.
;See also:
* (humor, nerd sniping) xkcd.com cartoon (you can solve that for extra credits)
* An article on how to calculate this and an implementation in Mathematica
| DIFF_THRESHOLD = 1e-40
class Fixed:
FREE = 0
A = 1
B = 2
class Node:
__slots__ = ["voltage", "fixed"]
def __init__(self, v=0.0, f=Fixed.FREE):
self.voltage = v
self.fixed = f
def set_boundary(m):
m[1][1] = Node( 1.0, Fixed.A)
m[6][7] = Node(-1.0, Fixed.B)
def calc_difference(m, d):
h = len(m)
w = len(m[0])
total = 0.0
for i in xrange(h):
for j in xrange(w):
v = 0.0
n = 0
if i != 0: v += m[i-1][j].voltage; n += 1
if j != 0: v += m[i][j-1].voltage; n += 1
if i < h-1: v += m[i+1][j].voltage; n += 1
if j < w-1: v += m[i][j+1].voltage; n += 1
v = m[i][j].voltage - v / n
d[i][j].voltage = v
if m[i][j].fixed == Fixed.FREE:
total += v ** 2
return total
def iter(m):
h = len(m)
w = len(m[0])
difference = [[Node() for j in xrange(w)] for i in xrange(h)]
while True:
set_boundary(m) # Enforce boundary conditions.
if calc_difference(m, difference) < DIFF_THRESHOLD:
break
for i, di in enumerate(difference):
for j, dij in enumerate(di):
m[i][j].voltage -= dij.voltage
cur = [0.0] * 3
for i, di in enumerate(difference):
for j, dij in enumerate(di):
cur[m[i][j].fixed] += (dij.voltage *
(bool(i) + bool(j) + (i < h-1) + (j < w-1)))
return (cur[Fixed.A] - cur[Fixed.B]) / 2.0
def main():
w = h = 10
mesh = [[Node() for j in xrange(w)] for i in xrange(h)]
print "R = %.16f" % (2 / iter(mesh))
main() |
Resistor mesh | Python from Maxima | Given 10x10 grid nodes (as shown in the image) interconnected by 1O resistors as shown,
find the resistance between points '''A''' and '''B'''.
;See also:
* (humor, nerd sniping) xkcd.com cartoon (you can solve that for extra credits)
* An article on how to calculate this and an implementation in Mathematica
| import sys, copy
from fractions import Fraction
def gauss(a, b):
n, p = len(a), len(a[0])
for i in range(n):
t = abs(a[i][i])
k = i
for j in range(i + 1, n):
if abs(a[j][i]) > t:
t = abs(a[j][i])
k = j
if k != i:
for j in range(i, n):
a[i][j], a[k][j] = a[k][j], a[i][j]
b[i], b[k] = b[k], b[i]
t = 1/a[i][i]
for j in range(i + 1, n):
a[i][j] *= t
b[i] *= t
for j in range(i + 1, n):
t = a[j][i]
for k in range(i + 1, n):
a[j][k] -= t*a[i][k]
b[j] -= t * b[i]
for i in range(n - 1, -1, -1):
for j in range(i):
b[j] -= a[j][i]*b[i]
return b
def resistor_grid(p, q, ai, aj, bi, bj):
n = p*q
I = Fraction(1, 1)
v = [0*I]*n
a = [copy.copy(v) for i in range(n)]
for i in range(p):
for j in range(q):
k = i*q + j
if i == ai and j == aj:
a[k][k] = I
else:
c = 0
if i + 1 < p:
c += 1
a[k][k + q] = -1
if i >= 1:
c += 1
a[k][k - q] = -1
if j + 1 < q:
c += 1
a[k][k + 1] = -1
if j >= 1:
c += 1
a[k][k - 1] = -1
a[k][k] = c*I
b = [0*I]*n
k = bi*q + bj
b[k] = 1
return gauss(a, b)[k]
def main(arg):
r = resistor_grid(int(arg[0]), int(arg[1]), int(arg[2]), int(arg[3]), int(arg[4]), int(arg[5]))
print(r)
print(float(r))
main(sys.argv[1:])
# Output:
# python grid.py 10 10 1 1 7 6
# 455859137025721/283319837425200
# 1.6089912417307297 |
Reverse words in a string | Python | Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
;Example:
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
'''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
;Input data
(ten lines within the box)
line
+----------------------------------------+
1 | ---------- Ice and Fire ------------ |
2 | | <--- a blank line here.
3 | fire, in end will world the say Some |
4 | ice. in say Some |
5 | desire of tasted I've what From |
6 | fire. favor who those with hold I |
7 | | <--- a blank line here.
8 | ... elided paragraph last ... |
9 | | <--- a blank line here.
10 | Frost Robert ----------------------- |
+----------------------------------------+
;Cf.
* [[Phrase reversals]]
| text = '''\
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------'''
for line in text.split('\n'): print(' '.join(line.split()[::-1])) |
Roman numerals/Decode | Python | Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any '''0'''s (zeroes).
'''1990''' is rendered as '''MCMXC''' (1000 = M, 900 = CM, 90 = XC) and
'''2008''' is rendered as '''MMVIII''' (2000 = MM, 8 = VIII).
The Roman numeral for '''1666''', '''MDCLXVI''', uses each letter in descending order.
| _rdecode = dict(zip('MDCLXVI', (1000, 500, 100, 50, 10, 5, 1)))
def decode( roman ):
result = 0
for r, r1 in zip(roman, roman[1:]):
rd, rd1 = _rdecode[r], _rdecode[r1]
result += -rd if rd < rd1 else rd
return result + _rdecode[roman[-1]]
if __name__ == '__main__':
for r in 'MCMXC MMVIII MDCLXVI'.split():
print( r, decode(r) ) |
Roman numerals/Decode | Python 3 | Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any '''0'''s (zeroes).
'''1990''' is rendered as '''MCMXC''' (1000 = M, 900 = CM, 90 = XC) and
'''2008''' is rendered as '''MMVIII''' (2000 = MM, 8 = VIII).
The Roman numeral for '''1666''', '''MDCLXVI''', uses each letter in descending order.
| '''Roman numerals decoded'''
from operator import mul
from functools import reduce
from collections import defaultdict
from itertools import accumulate, chain, cycle
# intFromRoman :: String -> Maybe Int
def intFromRoman(s):
'''Just the integer represented by a Roman
numeral string, or Nothing if any
characters are unrecognised.
'''
dct = defaultdict(
lambda: None,
zip(
'IVXLCDM',
accumulate(chain([1], cycle([5, 2])), mul)
)
)
def go(mb, x):
'''Just a letter value added to or
subtracted from a total, or Nothing
if no letter value is defined.
'''
if None in (mb, x):
return None
else:
r, total = mb
return x, total + (-x if x < r else x)
return bindMay(reduce(
go,
[dct[k.upper()] for k in reversed(list(s))],
(0, 0)
))(snd)
# ------------------------- TEST -------------------------
def main():
'''Testing a sample of dates.'''
print(
fTable(__doc__ + ':\n')(str)(
maybe('(Contains unknown character)')(str)
)(
intFromRoman
)([
"MDCLXVI", "MCMXC", "MMVIII",
"MMXVI", "MMXVIII", "MMZZIII"
])
)
# ----------------------- GENERIC ------------------------
# bindMay (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
def bindMay(m):
'''Injection operator for the Maybe monad.
If m is Nothing, it is passed straight through.
If m is Just(x), the result is an application
of the (a -> Maybe b) function (mf) to x.'''
return lambda mf: (
m if None is m else mf(m)
)
# 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 else (
f(m)
)
# snd :: (a, b) -> b
def snd(ab):
'''Second member of a pair.'''
return ab[1]
# ---------------------- 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: (
f'{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() |
Roman numerals/Encode | Python | Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numerals:
* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
* 2008 is written as 2000=MM, 8=VIII; or MMVIII
* 1666 uses each Roman symbol in descending order: MDCLXVI
| def toRoman(n):
res='' #converts int to str(Roman numeral)
reg=n #using the numerals (M,D,C,L,X,V,I)
if reg<4000:#no more than three repetitions
while reg>=1000: #thousands up to MMM
res+='M' #MAX is MMMCMXCIX
reg-=1000
if reg>=900: #nine hundreds in 900-999
res+='CM'
reg-=900
if reg>=500: #five hudreds in 500-899
res+='D'
reg-=500
if reg>=400: #four hundreds in 400-499
res+='CD'
reg-=400
while reg>=100: #hundreds in 100-399
res+='C'
reg-=100
if reg>=90: #nine tens in 90-99
res+='XC'
reg-=90
if reg>=50: #five Tens in 50-89
res+='L'
reg-=50
if reg>=40:
res+='XL' #four Tens
reg-=40
while reg>=10:
res+="X" #tens
reg-=10
if reg>=9:
res+='IX' #nine Units
reg-=9
if reg>=5:
res+='V' #five Units
reg-=5
if reg>=4:
res+='IV' #four Units
reg-=4
while reg>0: #three or less Units
res+='I'
reg-=1
return res |
Roman numerals/Encode | Python from Haskell | Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numerals:
* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
* 2008 is written as 2000=MM, 8=VIII; or MMVIII
* 1666 uses each Roman symbol in descending order: MDCLXVI
| '''Encoding Roman Numerals'''
from functools import reduce
from itertools import chain
# romanFromInt :: Int -> String
def romanFromInt(n):
'''A string of Roman numerals encoding an integer.'''
def go(a, ms):
m, s = ms
q, r = divmod(a, m)
return (r, s * q)
return concat(snd(mapAccumL(go)(n)(
zip([
1000, 900, 500, 400, 100, 90, 50,
40, 10, 9, 5, 4, 1
], [
'M', 'CM', 'D', 'CD', 'C', 'XC', 'L',
'XL', 'X', 'IX', 'V', 'IV', 'I'
])
)))
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Sample of years'''
for s in [
romanFromInt(x) for x in [
1666, 1990, 2008, 2016, 2018, 2020
]
]:
print(s)
# ------------------ GENERIC FUNCTIONS -------------------
# 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
)
# mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
def mapAccumL(f):
'''A tuple of an accumulation and a list derived by a
combined map and fold,
with accumulation from left to right.'''
def go(a, x):
tpl = f(a[0], x)
return (tpl[0], a[1] + [tpl[1]])
return lambda acc: lambda xs: (
reduce(go, xs, (acc, []))
)
# snd :: (a, b) -> b
def snd(tpl):
'''Second component of a tuple.'''
return tpl[1]
# MAIN ---
if __name__ == '__main__':
main() |
Runge-Kutta method | Python | Given the example Differential equation:
:y'(t) = t \times \sqrt {y(t)}
With initial condition:
:t_0 = 0 and y_0 = y(t_0) = y(0) = 1
This equation has an exact solution:
:y(t) = \tfrac{1}{16}(t^2 +4)^2
;Task
Demonstrate the commonly used explicit fourth-order Runge-Kutta method to solve the above differential equation.
* Solve the given differential equation over the range t = 0 \ldots 10 with a step value of \delta t=0.1 (101 total points, the first being given)
* Print the calculated values of y at whole numbered t's (0.0, 1.0, \ldots 10.0) along with error as compared to the exact solution.
;Method summary
Starting with a given y_n and t_n calculate:
:\delta y_1 = \delta t\times y'(t_n, y_n)\quad
:\delta y_2 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_1)
:\delta y_3 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_2)
:\delta y_4 = \delta t\times y'(t_n + \delta t , y_n + \delta y_3)\quad
then:
:y_{n+1} = y_n + \tfrac{1}{6} (\delta y_1 + 2\delta y_2 + 2\delta y_3 + \delta y_4)
:t_{n+1} = t_n + \delta t\quad
| from math import sqrt
def rk4(f, x0, y0, x1, n):
vx = [0] * (n + 1)
vy = [0] * (n + 1)
h = (x1 - x0) / float(n)
vx[0] = x = x0
vy[0] = y = y0
for i in range(1, n + 1):
k1 = h * f(x, y)
k2 = h * f(x + 0.5 * h, y + 0.5 * k1)
k3 = h * f(x + 0.5 * h, y + 0.5 * k2)
k4 = h * f(x + h, y + k3)
vx[i] = x = x0 + i * h
vy[i] = y = y + (k1 + k2 + k2 + k3 + k3 + k4) / 6
return vx, vy
def f(x, y):
return x * sqrt(y)
vx, vy = rk4(f, 0, 1, 10, 100)
for x, y in list(zip(vx, vy))[::10]:
print("%4.1f %10.5f %+12.4e" % (x, y, y - (4 + x * x)**2 / 16))
0.0 1.00000 +0.0000e+00
1.0 1.56250 -1.4572e-07
2.0 4.00000 -9.1948e-07
3.0 10.56250 -2.9096e-06
4.0 24.99999 -6.2349e-06
5.0 52.56249 -1.0820e-05
6.0 99.99998 -1.6595e-05
7.0 175.56248 -2.3518e-05
8.0 288.99997 -3.1565e-05
9.0 451.56246 -4.0723e-05
10.0 675.99995 -5.0983e-05 |
Runtime evaluation/In an environment | Python | Given a program in the language (as a string or AST) with a free variable named x (or another name if that is not valid syntax), evaluate it with x bound to a provided value, then evaluate it again with x bound to another provided value, then subtract the result of the first from the second and return or print it.
Do so in a way which:
* does not involve string manipulation of the input source code
* is plausibly extensible to a runtime-chosen set of bindings rather than just x
* does not make x a ''global'' variable
or note that these are impossible.
;See also:
* For more general examples and language-specific details, see [[Eval]].
* [[Dynamic variable names]] is a similar task.
| >>> def eval_with_args(code, **kwordargs):
return eval(code, kwordargs)
>>> code = '2 ** x'
>>> eval_with_args(code, x=5) - eval_with_args(code, x=3)
24
>>> code = '3 * x + y'
>>> eval_with_args(code, x=5, y=2) - eval_with_args(code, x=3, y=1)
7 |
SHA-1 | Python | '''SHA-1''' or '''SHA1''' is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of [[octet]]s. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
{{alertbox|lightgray|'''Warning:''' SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.}}
| import hashlib
h = hashlib.sha1()
h.update(bytes("Ars longa, vita brevis", encoding="ASCII"))
h.hexdigest()
# "e640d285242886eb96ab80cbf858389b3df52f43" |
Sailors, coconuts and a monkey problem | Python | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.
To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.
In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
;The task:
# Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
# Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.)
# Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
# Show your answers here.
;Extra credit (optional):
* Give some indication of the number of coconuts each sailor hides during the night.
;Note:
* Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
* The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale!
;C.f:
* Monkeys and Coconuts - Numberphile (Video) Analytical solution.
* A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
| def monkey_coconuts(sailors=5):
"Parameterised the number of sailors using an inner loop including the last mornings case"
nuts = sailors
while True:
n0, wakes = nuts, []
for sailor in range(sailors + 1):
portion, remainder = divmod(n0, sailors)
wakes.append((n0, portion, remainder))
if portion <= 0 or remainder != (1 if sailor != sailors else 0):
nuts += 1
break
n0 = n0 - portion - remainder
else:
break
return nuts, wakes
if __name__ == "__main__":
for sailors in [5, 6]:
nuts, wake_stats = monkey_coconuts(sailors)
print("\nFor %i sailors the initial nut count is %i" % (sailors, nuts))
print("On each waking, the nut count, portion taken, and monkeys share are:\n ",
',\n '.join(repr(ws) for ws in wake_stats)) |
Same fringe | Python | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.
Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
| try:
from itertools import zip_longest as izip_longest # Python 3.x
except:
from itertools import izip_longest # Python 2.6+
def fringe(tree):
"""Yield tree members L-to-R depth first,
as if stored in a binary tree"""
for node1 in tree:
if isinstance(node1, tuple):
for node2 in fringe(node1):
yield node2
else:
yield node1
def same_fringe(tree1, tree2):
return all(node1 == node2 for node1, node2 in
izip_longest(fringe(tree1), fringe(tree2)))
if __name__ == '__main__':
a = 1, 2, 3, 4, 5, 6, 7, 8
b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))
c = (((1, 2), 3), 4), 5, 6, 7, 8
x = 1, 2, 3, 4, 5, 6, 7, 8, 9
y = 0, 2, 3, 4, 5, 6, 7, 8
z = 1, 2, (4, 3), 5, 6, 7, 8
assert same_fringe(a, a)
assert same_fringe(a, b)
assert same_fringe(a, c)
assert not same_fringe(a, x)
assert not same_fringe(a, y)
assert not same_fringe(a, z) |
Subsets and Splits