title
stringlengths 3
86
| language
stringlengths 1
35
| task
stringlengths 41
8.77k
| solution
stringlengths 60
47.6k
|
---|---|---|---|
Executable library | Python | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
'''Task detail'''
* Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the [[Hailstone sequence]] for that number.
* The library, when executed directly should satisfy the remaining requirements of the [[Hailstone sequence]] task:
:: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
:: 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
* Create a second executable to calculate the following:
** Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 <= n < 100,000.
* Explain any extra setup/run steps needed to complete the task.
'''Notes:'''
* It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed ''not'' to be present in the runtime environment.
* Interpreters are present in the runtime environment.
| from collections import Counter
def function_length_frequency(func, hrange):
return Counter(len(func(n)) for n in hrange).most_common()
if __name__ == '__main__':
from executable_hailstone_library import hailstone
upto = 100000
hlen, freq = function_length_frequency(hailstone, range(1, upto))[0]
print("The length of hailstone sequence that is most common for\n"
"hailstone(n) where 1<=n<%i, is %i. It occurs %i times."
% (upto, hlen, freq)) |
Execute Computer/Zero | Python | Computer/zero Assembly}}
;Task:
Create a [[Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7*8" found there.
:* The virtual machine "bytecode" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.
:* For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it.
;Bonus Points: Run all 5 sample programs at the aforementioned website and output their results.
| """Computer/zero Assembly emulator. Requires Python >= 3.7"""
import re
from typing import Dict
from typing import Iterable
from typing import List
from typing import NamedTuple
from typing import Optional
from typing import Tuple
NOP = 0b000
LDA = 0b001
STA = 0b010
ADD = 0b011
SUB = 0b100
BRZ = 0b101
JMP = 0b110
STP = 0b111
OPCODES = {
"NOP": NOP,
"LDA": LDA,
"STA": STA,
"ADD": ADD,
"SUB": SUB,
"BRZ": BRZ,
"JMP": JMP,
"STP": STP,
}
RE_INSTRUCTION = re.compile(
r"\s*"
r"(?:(?P<label>\w+):)?"
r"\s*"
rf"(?P<opcode>{'|'.join(OPCODES)})?"
r"\s*"
r"(?P<argument>\w+)?"
r"\s*"
r"(?:;(?P<comment>[\w\s]+))?"
)
class AssemblySyntaxError(Exception):
pass
class Instruction(NamedTuple):
label: Optional[str]
opcode: Optional[str]
argument: Optional[str]
comment: Optional[str]
def parse(assembly: str) -> Tuple[List[Instruction], Dict[str, int]]:
instructions: List[Instruction] = []
labels: Dict[str, int] = {}
linenum: int = 0
for line in assembly.split("\n"):
match = RE_INSTRUCTION.match(line)
if not match:
raise AssemblySyntaxError(f"{line}: {linenum}")
instructions.append(Instruction(**match.groupdict()))
label = match.group(1)
if label:
labels[label] = linenum
linenum += 1
return instructions, labels
def compile(instructions: List[Instruction], labels: Dict[str, int]) -> Iterable[int]:
for instruction in instructions:
if instruction.argument is None:
argument = 0
elif instruction.argument.isnumeric():
argument = int(instruction.argument)
else:
argument = labels[instruction.argument]
if instruction.opcode:
yield OPCODES[instruction.opcode] << 5 | argument
else:
yield argument
def run(bytecode: bytes) -> int:
accumulator = 0
program_counter = 0
memory = list(bytecode)[:32] + [0 for _ in range(32 - len(bytecode))]
while program_counter < 32:
operation = memory[program_counter] >> 5
argument = memory[program_counter] & 0b11111
program_counter += 1
if operation == NOP:
continue
elif operation == LDA:
accumulator = memory[argument]
elif operation == STA:
memory[argument] = accumulator
elif operation == ADD:
accumulator = (accumulator + memory[argument]) % 256
elif operation == SUB:
accumulator = (accumulator - memory[argument]) % 256
elif operation == BRZ:
if accumulator == 0:
program_counter = argument
elif operation == JMP:
program_counter = argument
elif operation == STP:
break
else:
raise Exception(f"error: {operation} {argument}")
return accumulator
SAMPLES = [
"""\
LDA x
ADD y ; accumulator = x + y
STP
x: 2
y: 2
""",
"""\
loop: LDA prodt
ADD x
STA prodt
LDA y
SUB one
STA y
BRZ done
JMP loop
done: LDA prodt ; to display it
STP
x: 8
y: 7
prodt: 0
one: 1
""",
"""\
loop: LDA n
STA temp
ADD m
STA n
LDA temp
STA m
LDA count
SUB one
BRZ done
STA count
JMP loop
done: LDA n ; to display it
STP
m: 1
n: 1
temp: 0
count: 8 ; valid range: 1-11
one: 1
""",
"""\
start: LDA load
ADD car ; head of list
STA ldcar
ADD one
STA ldcdr ; next CONS cell
ldcar: NOP
STA value
ldcdr: NOP
BRZ done ; 0 stands for NIL
STA car
JMP start
done: LDA value ; CAR of last CONS
STP
load: LDA 0
value: 0
car: 28
one: 1
; order of CONS cells
; in memory
; does not matter
6
0 ; 0 stands for NIL
2 ; (CADR ls)
26 ; (CDDR ls) -- etc.
5
20
3
30
1 ; value of (CAR ls)
22 ; points to (CDR ls)
4
24
""",
"""\
p: 0 ; NOP in first round
c: 0
start: STP ; wait for p's move
pmove: NOP
LDA pmove
SUB cmove
BRZ same
LDA pmove
STA cmove ; tit for tat
BRZ cdeft
LDA c ; p defected, c did not
ADD three
STA c
JMP start
cdeft: LDA p
ADD three
STA p
JMP start
same: LDA pmove
STA cmove ; tit for tat
LDA p
ADD one
ADD pmove
STA p
LDA c
ADD one
ADD pmove
STA c
JMP start
cmove: 0 ; co-operate initially
one: 1
three: 3
""",
"""\
LDA 3
SUB 4
STP 0
0
255
""",
"""\
LDA 3
SUB 4
STP 0
0
1
""",
"""\
LDA 3
ADD 4
STP 0
1
255
""",
]
def main() -> None:
for sample in SAMPLES:
instructions, labels = parse(sample)
bytecode = bytes(compile(instructions, labels))
result = run(bytecode)
print(result)
if __name__ == "__main__":
main()
|
Execute SNUSP | Python from Go | SNUSP}}'''RCSNUSP''' is a set of [[SNUSP compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCSNUSP.
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
| #!/usr/bin/env python3
HW = r'''
/++++!/===========?\>++.>+.+++++++..+++\
\+++\ | /+>+++++++>/ /++++++++++<<.++>./
$+++/ | \+++++++++>\ \+++++.>.+++.-----\
\==-<<<<+>+++/ /=.>.+>.--------.-/'''
def snusp(store, code):
ds = bytearray(store) # data store
dp = 0 # data pointer
cs = code.splitlines() # 2 dimensional code store
ipr, ipc = 0, 0 # instruction pointers in row and column
for r, row in enumerate(cs):
try:
ipc = row.index('$')
ipr = r
break
except ValueError:
pass
rt, dn, lt, up = range(4)
id = rt # instruction direction. starting direction is always rt
def step():
nonlocal ipr, ipc
if id&1:
ipr += 1 - (id&2)
else:
ipc += 1 - (id&2)
while ipr >= 0 and ipr < len(cs) and ipc >= 0 and ipc < len(cs[ipr]):
op = cs[ipr][ipc]
if op == '>':
dp += 1
elif op == '<':
dp -= 1
elif op == '+':
ds[dp] += 1
elif op == '-':
ds[dp] -= 1
elif op == '.':
print(chr(ds[dp]), end='')
elif op == ',':
ds[dp] = input()
elif op == '/':
id = ~id
elif op == '\\':
id ^= 1
elif op == '!':
step()
elif op == '?':
if not ds[dp]:
step()
step()
if __name__ == '__main__':
snusp(5, HW) |
Exponentiation order | Python | This task will demonstrate the order of exponentiation ('''xy''') when there are multiple exponents.
(Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.)
;Task requirements
Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):
::::* 5**3**2
::::* (5**3)**2
::::* 5**(3**2)
If there are other methods (or formats) of multiple exponentiations, show them as well.
;See also:
* MathWorld entry: exponentiation
;Related tasks:
* exponentiation operator
* arbitrary-precision integers (included)
* [[Exponentiation with infix operators in (or operating on) the base]]
| >>> 5**3**2
1953125
>>> (5**3)**2
15625
>>> 5**(3**2)
1953125
>>> # The following is not normally done
>>> try: from functools import reduce # Py3K
except: pass
>>> reduce(pow, (5, 3, 2))
15625
>>> |
Exponentiation with infix operators in (or operating on) the base | Python | (Many programming languages, especially those with extended-precision integer arithmetic, usually
support one of **, ^, | or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the '''POW''' or some other BIF
('''B'''uilt-'''I'''n '''F'''function), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an ''infix operator'' operating
in (or operating on) the base.
;Example:
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
;Task:
:* compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
:* Raise the following numbers (integer or real):
:::* -5 and
:::* +5
:* to the following powers:
:::* 2nd and
:::* 3rd
:* using the following expressions (if applicable in your language):
:::* -x**p
:::* -(x)**p
:::* (-x)**p
:::* -(x**p)
:* Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
;Related tasks:
* [[Exponentiation order]]
* [[Exponentiation operator]]
* [[Arbitrary-precision integers (included)]]
* [[Parsing/RPN to infix conversion]]
* [[Operator precedence]]
;References:
* Wikipedia: Order of operations in Programming languages
| from itertools import product
xx = '-5 +5'.split()
pp = '2 3'.split()
texts = '-x**p -(x)**p (-x)**p -(x**p)'.split()
print('Integer variable exponentiation')
for x, p in product(xx, pp):
print(f' x,p = {x:2},{p}; ', end=' ')
x, p = int(x), int(p)
print('; '.join(f"{t} =={eval(t):4}" for t in texts))
print('\nBonus integer literal exponentiation')
X, P = 'xp'
xx.insert(0, ' 5')
texts.insert(0, 'x**p')
for x, p in product(xx, pp):
texts2 = [t.replace(X, x).replace(P, p) for t in texts]
print(' ', '; '.join(f"{t2} =={eval(t2):4}" for t2 in texts2)) |
Extend your language | Python | {{Control Structures}}Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.
If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:
Occasionally, code must be written that depends on ''two'' conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:
if (condition1isTrue) {
if (condition2isTrue)
bothConditionsAreTrue();
else
firstConditionIsTrue();
}
else if (condition2isTrue)
secondConditionIsTrue();
else
noConditionIsTrue();
Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.
This can be improved by introducing a new keyword '''if2'''. It is similar to '''if''', but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:
if2 (condition1isTrue) (condition2isTrue)
bothConditionsAreTrue();
else1
firstConditionIsTrue();
else2
secondConditionIsTrue();
else
noConditionIsTrue();
Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
| a, b = 1, 0
if (c1 := a == 1) and (c2 := b == 3):
print('a = 1 and b = 3')
elif c1:
print('a = 1 and b <> 3')
elif c2:
print('a <> 1 and b = 3')
else:
print('a <> 1 and b <> 3') |
Extreme floating point values | Python | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
;See also:
* What Every Computer Scientist Should Know About Floating-Point Arithmetic
;Related tasks:
* [[Infinity]]
* [[Detect division by zero]]
* [[Literals/Floating point]]
| >>> # Extreme values from expressions
>>> inf = 1e234 * 1e234
>>> _inf = 1e234 * -1e234
>>> _zero = 1 / _inf
>>> nan = inf + _inf
>>> inf, _inf, _zero, nan
(inf, -inf, -0.0, nan)
>>> # Print
>>> for value in (inf, _inf, _zero, nan): print (value)
inf
-inf
-0.0
nan
>>> # Extreme values from other means
>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> -0.
-0.0
>>> # Some arithmetic
>>> nan == nan
False
>>> nan is nan
True
>>> 0. == -0.
True
>>> 0. is -0.
False
>>> inf + _inf
nan
>>> 0.0 * nan
nan
>>> nan * 0.0
nan
>>> 0.0 * inf
nan
>>> inf * 0.0
nan |
FASTA format | Python | In FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
;Task:
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
| import io
FASTA='''\
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED'''
infile = io.StringIO(FASTA)
def fasta_parse(infile):
key = ''
for line in infile:
if line.startswith('>'):
if key:
yield key, val
key, val = line[1:].rstrip().split()[0], ''
elif key:
val += line.rstrip()
if key:
yield key, val
print('\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile))) |
Faces from a mesh | Python | A mesh defining a surface has uniquely numbered vertices, and named,
simple-polygonal faces described usually by an ordered list of edge numbers
going around the face,
For example:
External image of two faces
Rough textual version without edges:
1
17
7 A
B
11
23
* A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or
any of all the rotations of those ordered vertices.
1
7 A
11
* B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any
of their rotations.
1
17
B
11
23
Let's call the above the '''perimeter format''' as it traces around the perimeter.
;A second format:
A separate algorithm returns polygonal faces consisting of a face name and an unordered
set of edge definitions for each face.
* A single edge is described by the vertex numbers at its two ends, always in
ascending order.
* All edges for the face are given, but in an undefined order.
For example face A could be described by the edges (1, 11), (7, 11), and (1, 7)
(The order of each vertex number in an edge is ascending, but the order in
which the edges are stated is arbitrary).
Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23),
and (1, 11) in arbitrary order of the edges.
Let's call this second format the '''edge format'''.
;Task:
'''1.''' Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same:
Q: (8, 1, 3)
R: (1, 3, 8)
U: (18, 8, 14, 10, 12, 17, 19)
V: (8, 14, 10, 12, 17, 19, 18)
'''2.''' Write a routine and use it to transform the following faces from edge to perimeter format.
E: {(1, 11), (7, 11), (1, 7)}
F: {(11, 23), (1, 17), (17, 23), (1, 11)}
G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)}
H: {(1, 3), (9, 11), (3, 11), (1, 11)}
Show your output here.
| def perim_equal(p1, p2):
# Cheap tests first
if len(p1) != len(p2) or set(p1) != set(p2):
return False
if any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1))):
return True
p2 = p2[::-1] # not inplace
return any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1)))
def edge_to_periphery(e):
edges = sorted(e)
p = list(edges.pop(0)) if edges else []
last = p[-1] if p else None
while edges:
for n, (i, j) in enumerate(edges):
if i == last:
p.append(j)
last = j
edges.pop(n)
break
elif j == last:
p.append(i)
last = i
edges.pop(n)
break
else:
#raise ValueError(f'Invalid edge format: {e}')
return ">>>Error! Invalid edge format<<<"
return p[:-1]
if __name__ == '__main__':
print('Perimeter format equality checks:')
for eq_check in [
{ 'Q': (8, 1, 3),
'R': (1, 3, 8)},
{ 'U': (18, 8, 14, 10, 12, 17, 19),
'V': (8, 14, 10, 12, 17, 19, 18)} ]:
(n1, p1), (n2, p2) = eq_check.items()
eq = '==' if perim_equal(p1, p2) else '!='
print(' ', n1, eq, n2)
print('\nEdge to perimeter format translations:')
edge_d = {
'E': {(1, 11), (7, 11), (1, 7)},
'F': {(11, 23), (1, 17), (17, 23), (1, 11)},
'G': {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)},
'H': {(1, 3), (9, 11), (3, 11), (1, 11)}
}
for name, edges in edge_d.items():
print(f" {name}: {edges}\n -> {edge_to_periphery(edges)}") |
Factorial base numbers indexing permutations of a collection | Python | You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.
I want to produce a 1 to 1 mapping between these numbers and permutations:-
0.0.0 -> 0123
0.0.1 -> 0132
0.1.0 -> 0213
0.1.1 -> 0231
0.2.0 -> 0312
0.2.1 -> 0321
1.0.0 -> 1023
1.0.1 -> 1032
1.1.0 -> 1203
1.1.1 -> 1230
1.2.0 -> 1302
1.2.1 -> 1320
2.0.0 -> 2013
2.0.1 -> 2031
2.1.0 -> 2103
2.1.1 -> 2130
2.2.0 -> 2301
2.2.1 -> 2310
3.0.0 -> 3012
3.0.1 -> 3021
3.1.0 -> 3102
3.1.1 -> 3120
3.2.0 -> 3201
3.2.1 -> 3210
The following psudo-code will do this:
Starting with m=0 and O, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.
If g is greater than zero, rotate the elements from m to m+g in O (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and O = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.
Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1
Let me work 2.0.1 and 0123
step 1 n=0 g=2 O=2013
step 2 n=1 g=0 so no action
step 3 n=2 g=1 O=2031
The task:
First use your function to recreate the above table.
Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
methods in rc's permutations task.
Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
use your function to crate the corresponding permutation of the following shoe of cards:
AKQJ1098765432AKQJ1098765432AKQJ1098765432AKQJ1098765432
Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
| """
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection
https://en.wikipedia.org/wiki/Factorial_number_system
"""
import math
def apply_perm(omega,fbn):
"""
omega contains a list which will be permuted (scrambled)
based on fbm.
fbm is a list which represents a factorial base number.
This function just translates the pseudo code in the
Rosetta Code task.
"""
for m in range(len(fbn)):
g = fbn[m]
if g > 0:
# do rotation
# save last number
new_first = omega[m+g]
# move numbers right
omega[m+1:m+g+1] = omega[m:m+g]
# put last number first
omega[m] = new_first
return omega
def int_to_fbn(i):
"""
convert integer i to factorial based number
"""
current = i
divisor = 2
new_fbn = []
while current > 0:
remainder = current % divisor
current = current // divisor
new_fbn.append(remainder)
divisor += 1
return list(reversed(new_fbn))
def leading_zeros(l,n):
"""
If list l has less than n elements returns l with enough 0 elements
in front of the list to make it length n.
"""
if len(l) < n:
return(([0] * (n - len(l))) + l)
else:
return l
def get_fbn(n):
"""
Return the n! + 1 first Factorial Based Numbers starting with zero.
"""
max = math.factorial(n)
for i in range(max):
# from Wikipedia article
current = i
divisor = 1
new_fbn = int_to_fbn(i)
yield leading_zeros(new_fbn,n-1)
def print_write(f, line):
"""
prints to console and
output file f
"""
print(line)
f.write(str(line)+'\n')
def dot_format(l):
"""
Take a list l that is a factorial based number
and returns it in dot format.
i.e. [0, 2, 1] becomes 0.2.1
"""
# empty list
if len(l) < 1:
return ""
# start with just first element no dot
dot_string = str(l[0])
# add rest if any with dots
for e in l[1:]:
dot_string += "."+str(e)
return dot_string
def str_format(l):
"""
Take a list l and returns a string
of those elements converted to strings.
"""
if len(l) < 1:
return ""
new_string = ""
for e in l:
new_string += str(e)
return new_string
with open("output.html", "w", encoding="utf-8") as f:
f.write("\n")
# first print list
omega=[0,1,2,3]
four_list = get_fbn(4)
for l in four_list:
print_write(f,dot_format(l)+' -> '+str_format(apply_perm(omega[:],l)))
print_write(f," ")
# now generate this output:
#
# Permutations generated = 39916800
# compared to 11! which = 39916800
num_permutations = 0
for p in get_fbn(11):
num_permutations += 1
if num_permutations % 1000000 == 0:
print_write(f,"permutations so far = "+str(num_permutations))
print_write(f," ")
print_write(f,"Permutations generated = "+str(num_permutations))
print_write(f,"compared to 11! which = "+str(math.factorial(11)))
print_write(f," ")
"""
u"\u2660" - spade
u"\u2665" - heart
u"\u2666" - diamond
u"\u2663" - club
"""
shoe = []
for suit in [u"\u2660",u"\u2665",u"\u2666",u"\u2663"]:
for value in ['A','K','Q','J','10','9','8','7','6','5','4','3','2']:
shoe.append(value+suit)
print_write(f,str_format(shoe))
p1 = [39,49,7,47,29,30,2,12,10,3,29,37,33,17,12,31,29,34,17,25,2,4,25,4,1,14,20,6,21,18,1,1,1,4,0,5,15,12,4,3,10,10,9,1,6,5,5,3,0,0,0]
p2 = [51,48,16,22,3,0,19,34,29,1,36,30,12,32,12,29,30,26,14,21,8,12,1,3,10,4,7,17,6,21,8,12,15,15,13,15,7,3,12,11,9,5,5,6,6,3,4,0,3,2,1]
print_write(f," ")
print_write(f,dot_format(p1))
print_write(f," ")
print_write(f,str_format(apply_perm(shoe[:],p1)))
print_write(f," ")
print_write(f,dot_format(p2))
print_write(f," ")
print_write(f,str_format(apply_perm(shoe[:],p2)))
# generate random 51 digit factorial based number
import random
max = math.factorial(52)
random_int = random.randint(0, max-1)
myperm = leading_zeros(int_to_fbn(random_int),51)
print(len(myperm))
print_write(f," ")
print_write(f,dot_format(myperm))
print_write(f," ")
print_write(f,str_format(apply_perm(shoe[:],myperm)))
f.write("\n")
|
Factorions | Python from C | Definition:
A factorion is a natural number that equals the sum of the factorials of its digits.
;Example:
'''145''' is a factorion in base '''10''' because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base '''10''' can exceed '''1,499,999'''.
;Task:
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
:* There are '''3''' factorions in base '''9'''
:* There are '''4''' factorions in base '''10'''
:* There are '''5''' factorions in base '''11'''
:* There are '''2''' factorions in base '''12''' (up to the same upper bound as for base '''10''')
;See also:
:* '''Wikipedia article'''
:* '''OEIS:A014080 - Factorions in base 10'''
:* '''OEIS:A193163 - Factorions in base n'''
| fact = [1] # cache factorials from 0 to 11
for n in range(1, 12):
fact.append(fact[n-1] * n)
for b in range(9, 12+1):
print(f"The factorions for base {b} are:")
for i in range(1, 1500000):
fact_sum = 0
j = i
while j > 0:
d = j % b
fact_sum += fact[d]
j = j//b
if fact_sum == i:
print(i, end=" ")
print("\n")
|
Fairshare between two and more | Python | The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)
The Thue-Morse sequence of ones-and-zeroes can be generated by:
:''"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"''
;Sharing fairly between two or more:
Use this method:
:''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.''
;Task
Counting from zero; using a function/method/routine to express an integer count in base '''b''',
sum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people.
Show the first 25 terms of the fairshare sequence:
:* For two people:
:* For three people
:* For five people
:* For eleven people
;Related tasks:
:* [[Non-decimal radices/Convert]]
:* [[Thue-Morse]]
;See also:
:* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))
| from itertools import count, islice
def _basechange_int(num, b):
"""
Return list of ints representing positive num in base b
>>> b = 3
>>> print(b, [_basechange_int(num, b) for num in range(11)])
3 [[0], [1], [2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2], [1, 0, 0], [1, 0, 1]]
>>>
"""
if num == 0:
return [0]
result = []
while num != 0:
num, d = divmod(num, b)
result.append(d)
return result[::-1]
def fairshare(b=2):
for i in count():
yield sum(_basechange_int(i, b)) % b
if __name__ == '__main__':
for b in (2, 3, 5, 11):
print(f"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}") |
Farey sequence | Python | The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size.
The ''Farey sequence'' is sometimes incorrectly called a ''Farey series''.
Each Farey sequence:
:::* starts with the value '''0''' (zero), denoted by the fraction \frac{0}{1}
:::* ends with the value '''1''' (unity), denoted by the fraction \frac{1}{1}.
The Farey sequences of orders '''1''' to '''5''' are:
:::: {\bf\it{F}}_1 = \frac{0}{1}, \frac{1}{1}
:
:::: {\bf\it{F}}_2 = \frac{0}{1}, \frac{1}{2}, \frac{1}{1}
:
:::: {\bf\it{F}}_3 = \frac{0}{1}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{1}{1}
:
:::: {\bf\it{F}}_4 = \frac{0}{1}, \frac{1}{4}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{3}{4}, \frac{1}{1}
:
:::: {\bf\it{F}}_5 = \frac{0}{1}, \frac{1}{5}, \frac{1}{4}, \frac{1}{3}, \frac{2}{5}, \frac{1}{2}, \frac{3}{5}, \frac{2}{3}, \frac{3}{4}, \frac{4}{5}, \frac{1}{1}
;Task
* Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive).
* Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds.
* Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator).
The length (the number of fractions) of a Farey sequence asymptotically approaches:
::::::::::: 3 x n2 / \pi2
;See also:
* OEIS sequence A006842 numerators of Farey series of order 1, 2, ***
* OEIS sequence A006843 denominators of Farey series of order 1, 2, ***
* OEIS sequence A005728 number of fractions in Farey series of order n
* MathWorld entry Farey sequence
* Wikipedia entry Farey sequence
| from fractions import Fraction
class Fr(Fraction):
def __repr__(self):
return '(%s/%s)' % (self.numerator, self.denominator)
def farey(n, length=False):
if not length:
return [Fr(0, 1)] + sorted({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})
else:
#return 1 + len({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})
return (n*(n+3))//2 - sum(farey(n//k, True) for k in range(2, n+1))
if __name__ == '__main__':
print('Farey sequence for order 1 through 11 (inclusive):')
for n in range(1, 12):
print(farey(n))
print('Number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds:')
print([farey(i, length=True) for i in range(100, 1001, 100)]) |
Farey sequence | Python 3.7 | The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size.
The ''Farey sequence'' is sometimes incorrectly called a ''Farey series''.
Each Farey sequence:
:::* starts with the value '''0''' (zero), denoted by the fraction \frac{0}{1}
:::* ends with the value '''1''' (unity), denoted by the fraction \frac{1}{1}.
The Farey sequences of orders '''1''' to '''5''' are:
:::: {\bf\it{F}}_1 = \frac{0}{1}, \frac{1}{1}
:
:::: {\bf\it{F}}_2 = \frac{0}{1}, \frac{1}{2}, \frac{1}{1}
:
:::: {\bf\it{F}}_3 = \frac{0}{1}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{1}{1}
:
:::: {\bf\it{F}}_4 = \frac{0}{1}, \frac{1}{4}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{3}{4}, \frac{1}{1}
:
:::: {\bf\it{F}}_5 = \frac{0}{1}, \frac{1}{5}, \frac{1}{4}, \frac{1}{3}, \frac{2}{5}, \frac{1}{2}, \frac{3}{5}, \frac{2}{3}, \frac{3}{4}, \frac{4}{5}, \frac{1}{1}
;Task
* Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive).
* Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds.
* Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator).
The length (the number of fractions) of a Farey sequence asymptotically approaches:
::::::::::: 3 x n2 / \pi2
;See also:
* OEIS sequence A006842 numerators of Farey series of order 1, 2, ***
* OEIS sequence A006843 denominators of Farey series of order 1, 2, ***
* OEIS sequence A005728 number of fractions in Farey series of order n
* MathWorld entry Farey sequence
* Wikipedia entry Farey sequence
| '''Farey sequence'''
from itertools import (chain, count, islice)
from math import gcd
# farey :: Int -> [Ratio Int]
def farey(n):
'''Farey sequence of order n.'''
return sorted(
nubBy(on(eq)(fromRatio))(
bind(enumFromTo(1)(n))(
lambda k: bind(enumFromTo(0)(k))(
lambda m: [ratio(m)(k)]
)
)
),
key=fromRatio
) + [ratio(1)(1)]
# fareyLength :: Int -> Int
def fareyLength(n):
'''Number of terms in a Farey sequence
of order n.'''
def go(x):
return (x * (x + 3)) // 2 - sum(
go(x // k) for k in enumFromTo(2)(x)
)
return go(n)
# showFarey :: [Ratio Int] -> String
def showFarey(xs):
'''Stringification of a Farey sequence.'''
return '(' + ', '.join(map(showRatio, xs)) + ')'
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Tests'''
print(
fTable(
'Farey sequence for orders 1-11 (inclusive):\n'
)(str)(showFarey)(
farey
)(enumFromTo(1)(11))
)
print(
fTable(
'\n\nNumber of fractions in the Farey sequence ' +
'for order 100 through 1,000 (inclusive) by hundreds:\n'
)(str)(str)(
fareyLength
)(enumFromThenTo(100)(200)(1000))
)
# GENERIC -------------------------------------------------
# bind(>>=) :: [a] -> (a -> [b]) -> [b]
def bind(xs):
'''List monad injection operator.
Two computations sequentially composed,
with any value produced by the first
passed as an argument to the second.'''
return lambda f: list(
chain.from_iterable(
map(f, xs)
)
)
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
# enumFromThenTo :: Int -> Int -> Int -> [Int]
def enumFromThenTo(m):
'''Integer values enumerated from m to n
with a step defined by nxt-m.
'''
def go(nxt, n):
d = nxt - m
return islice(count(0), m, d + n, d)
return lambda nxt: lambda n: (
list(go(nxt, n))
)
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
# eq (==) :: Eq a => a -> a -> Bool
def eq(a):
'''Simple equality of a and b.'''
return lambda b: a == b
# fromRatio :: Ratio Int -> Float
def fromRatio(r):
'''A floating point value derived from a
a rational value.
'''
return r.get('numerator') / r.get('denominator')
# nubBy :: (a -> a -> Bool) -> [a] -> [a]
def nubBy(p):
'''A sublist of xs from which all duplicates,
(as defined by the equality predicate p)
are excluded.
'''
def go(xs):
if not xs:
return []
x = xs[0]
return [x] + go(
list(filter(
lambda y: not p(x)(y),
xs[1:]
))
)
return lambda xs: go(xs)
# on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
def on(f):
'''A function returning the value of applying
the binary f to g(a) g(b)
'''
return lambda g: lambda a: lambda b: f(g(a))(g(b))
# ratio :: Int -> Int -> Ratio Int
def ratio(n):
'''Rational value constructed
from a numerator and a denominator.
'''
def go(n, d):
g = gcd(n, d)
return {
'type': 'Ratio',
'numerator': n // g, 'denominator': d // g
}
return lambda d: go(n * signum(d), abs(d))
# showRatio :: Ratio -> String
def showRatio(r):
'''String representation of the ratio r.'''
d = r.get('denominator')
return str(r.get('numerator')) + (
'/' + str(d) if 1 != d else ''
)
# signum :: Num -> Num
def signum(n):
'''The sign of n.'''
return -1 if 0 > n else (1 if 0 < n else 0)
# 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
)
# unlines :: [String] -> String
def unlines(xs):
'''A single string derived by the intercalation
of a list of strings with the newline character.
'''
return '\n'.join(xs)
if __name__ == '__main__':
main() |
Fast Fourier transform | Python | Calculate the FFT (Fast Fourier Transform) of an input sequence.
The most general case allows for complex numbers at the input
and results in a sequence of equal length, again of complex numbers.
If you need to restrict yourself to real numbers, the output should
be the magnitude (i.e.: sqrt(re2 + im2)) of the complex result.
The classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that.
Further optimizations are possible but not required.
| from cmath import exp, pi
def fft(x):
N = len(x)
if N <= 1: return x
even = fft(x[0::2])
odd = fft(x[1::2])
T= [exp(-2j*pi*k/N)*odd[k] for k in range(N//2)]
return [even[k] + T[k] for k in range(N//2)] + \
[even[k] - T[k] for k in range(N//2)]
print( ' '.join("%5.3f" % abs(f)
for f in fft([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0])) ) |
Feigenbaum constant calculation | Python from D | Calculate the Feigenbaum constant.
;See:
:* Details in the Wikipedia article: Feigenbaum constant.
| max_it = 13
max_it_j = 10
a1 = 1.0
a2 = 0.0
d1 = 3.2
a = 0.0
print " i d"
for i in range(2, max_it + 1):
a = a1 + (a1 - a2) / d1
for j in range(1, max_it_j + 1):
x = 0.0
y = 0.0
for k in range(1, (1 << i) + 1):
y = 1.0 - 2.0 * y * x
x = a - x * x
a = a - x / y
d = (a1 - a2) / (a - a1)
print("{0:2d} {1:.8f}".format(i, d))
d1 = d
a2 = a1
a1 = a |
Fibonacci n-step number sequences | Python | These number series are an expansion of the ordinary [[Fibonacci sequence]] where:
# For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2
# For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3
# For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4...
# For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}}
For small values of n, Greek numeric prefixes are sometimes used to individually name each series.
:::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2"
|+ Fibonacci n-step sequences
|- style="background-color: rgb(255, 204, 255);"
! n !! Series name !! Values
|-
| 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
|-
| 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
|-
| 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
|-
| 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
|-
| 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
|-
| 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
|-
| 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
|-
| 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
|-
| 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
|}
Allied sequences can be generated where the initial values are changed:
: '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values.
;Task:
# Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
# Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
;Related tasks:
* [[Fibonacci sequence]]
* Wolfram Mathworld
* [[Hofstadter Q sequence]]
* [[Leonardo numbers]]
;Also see:
* Lucas Numbers - Numberphile (Video)
* Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
* Wikipedia, Lucas number
* MathWorld, Fibonacci Number
* Some identities for r-Fibonacci numbers
* OEIS Fibonacci numbers
* OEIS Lucas numbers
| >>> class Fiblike():
def __init__(self, start):
self.addnum = len(start)
self.memo = start[:]
def __call__(self, n):
try:
return self.memo[n]
except IndexError:
ans = sum(self(i) for i in range(n-self.addnum, n))
self.memo.append(ans)
return ans
>>> fibo = Fiblike([1,1])
>>> [fibo(i) for i in range(10)]
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> lucas = Fiblike([2,1])
>>> [lucas(i) for i in range(10)]
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76]
>>> for n, name in zip(range(2,11), 'fibo tribo tetra penta hexa hepta octo nona deca'.split()) :
fibber = Fiblike([1] + [2**i for i in range(n-1)])
print('n=%2i, %5snacci -> %s ...' % (n, name, ' '.join(str(fibber(i)) for i in range(15))))
n= 2, fibonacci -> 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
n= 3, tribonacci -> 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
n= 4, tetranacci -> 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
n= 5, pentanacci -> 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
n= 6, hexanacci -> 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
n= 7, heptanacci -> 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
n= 8, octonacci -> 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
n= 9, nonanacci -> 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
n=10, decanacci -> 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
>>> |
Fibonacci n-step number sequences | Python 3.7 | These number series are an expansion of the ordinary [[Fibonacci sequence]] where:
# For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2
# For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3
# For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4...
# For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}}
For small values of n, Greek numeric prefixes are sometimes used to individually name each series.
:::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2"
|+ Fibonacci n-step sequences
|- style="background-color: rgb(255, 204, 255);"
! n !! Series name !! Values
|-
| 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
|-
| 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
|-
| 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
|-
| 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
|-
| 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
|-
| 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
|-
| 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
|-
| 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
|-
| 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
|}
Allied sequences can be generated where the initial values are changed:
: '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values.
;Task:
# Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
# Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
;Related tasks:
* [[Fibonacci sequence]]
* Wolfram Mathworld
* [[Hofstadter Q sequence]]
* [[Leonardo numbers]]
;Also see:
* Lucas Numbers - Numberphile (Video)
* Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
* Wikipedia, Lucas number
* MathWorld, Fibonacci Number
* Some identities for r-Fibonacci numbers
* OEIS Fibonacci numbers
* OEIS Lucas numbers
| '''Fibonacci n-step number sequences'''
from itertools import chain, count, islice
# A000032 :: () -> [Int]
def A000032():
'''Non finite sequence of Lucas numbers.
'''
return unfoldr(recurrence(2))([2, 1])
# nStepFibonacci :: Int -> [Int]
def nStepFibonacci(n):
'''Non-finite series of N-step Fibonacci numbers,
defined by a recurrence relation.
'''
return unfoldr(recurrence(n))(
take(n)(
chain(
[1],
(2 ** i for i in count(0))
)
)
)
# recurrence :: Int -> [Int] -> Int
def recurrence(n):
'''Recurrence relation in Fibonacci and related series.
'''
def go(xs):
h, *t = xs
return h, t + [sum(take(n)(xs))]
return go
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''First 15 terms each n-step Fibonacci(n) series
where n is drawn from [2..8]
'''
labels = "fibo tribo tetra penta hexa hepta octo nona deca"
table = list(
chain(
[['lucas:'] + [
str(x) for x in take(15)(A000032())]
],
map(
lambda k, n: list(
chain(
[k + 'nacci:'],
(
str(x) for x
in take(15)(nStepFibonacci(n))
)
)
),
labels.split(),
count(2)
)
)
)
print('Recurrence relation series:\n')
print(
spacedTable(table)
)
# ----------------------- GENERIC ------------------------
# 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
# unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
def unfoldr(f):
'''Generic anamorphism.
A lazy (generator) list unfolded from a seed value by
repeated application of f until no residue remains.
Dual to fold/reduce.
f returns either None, or just (value, residue).
For a strict output value, wrap in list().
'''
def go(x):
valueResidue = f(x)
while None is not valueResidue:
yield valueResidue[0]
valueResidue = f(valueResidue[1])
return go
# ---------------------- FORMATTING ----------------------
# spacedTable :: [[String]] -> String
def spacedTable(rows):
columnWidths = [
max([len(x) for x in col])
for col in zip(*rows)
]
return '\n'.join([
' '.join(
map(
lambda x, w: x.rjust(w, ' '),
row, columnWidths
)
)
for row in rows
])
# MAIN ---
if __name__ == '__main__':
main() |
Fibonacci word | Python | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as '''1'''
Define F_Word2 as '''0'''
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01'''
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
;Task:
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words '''1''' to '''37''' which shows:
::* The number of characters in the word
::* The word's [[Entropy]]
;Related tasks:
* Fibonacci word/fractal
* [[Entropy]]
* [[Entropy/Narcissist]]
| >>> import math
>>> from collections import Counter
>>>
>>> def entropy(s):
... p, lns = Counter(s), float(len(s))
... return -sum( count/lns * math.log(count/lns, 2) for count in p.values())
...
>>>
>>> def fibword(nmax=37):
... fwords = ['1', '0']
... print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))
... def pr(n, fwords):
... while len(fwords) < n:
... fwords += [''.join(fwords[-2:][::-1])]
... v = fwords[n-1]
... print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))
... for n in range(1, nmax+1): pr(n, fwords)
...
>>> fibword()
N Length Entropy Fibword
1 1 -0 1
2 1 -0 0
3 2 1 01
4 3 0.9182958 010
5 5 0.9709506 01001
6 8 0.954434 01001010
7 13 0.9612366 0100101001001
8 21 0.9587119 <too long>
9 34 0.9596869 <too long>
10 55 0.959316 <too long>
11 89 0.9594579 <too long>
12 144 0.9594038 <too long>
13 233 0.9594244 <too long>
14 377 0.9594165 <too long>
15 610 0.9594196 <too long>
16 987 0.9594184 <too long>
17 1597 0.9594188 <too long>
18 2584 0.9594187 <too long>
19 4181 0.9594187 <too long>
20 6765 0.9594187 <too long>
21 10946 0.9594187 <too long>
22 17711 0.9594187 <too long>
23 28657 0.9594187 <too long>
24 46368 0.9594187 <too long>
25 75025 0.9594187 <too long>
26 121393 0.9594187 <too long>
27 196418 0.9594187 <too long>
28 317811 0.9594187 <too long>
29 514229 0.9594187 <too long>
30 832040 0.9594187 <too long>
31 1346269 0.9594187 <too long>
32 2178309 0.9594187 <too long>
33 3524578 0.9594187 <too long>
34 5702887 0.9594187 <too long>
35 9227465 0.9594187 <too long>
36 14930352 0.9594187 <too long>
37 24157817 0.9594187 <too long>
>>> |
File extension is in extensions list | Python | Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''.
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the [[Extract file extension]] task.
;Related tasks:
* [[Extract file extension]]
* [[String matching]]
| '''Check for a specific set of file extensions'''
# extensionFound :: [Extension] -> FileName -> Maybe Extension
def extensionFound(xs):
'''Nothing if no matching extension is found,
or Just the extension (drawn from xs, and
a suffix of the filename, immediately following
a dot character).
'''
return lambda fn: find(fn.lower().endswith)(
['.' + x.lower() for x in xs]
)
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Check filenames for a particular set of extensions.'''
# checkExtension :: FileName -> Maybe Extension
def checkExtension(fn):
return extensionFound([
'zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'
])(fn)
print(
fTable(__doc__ + ':\n')(str)(str)(
compose(fromMaybe('n/a'))(checkExtension)
)([
'MyData.a##',
'MyData.tar.Gz',
'MyData.gzip',
'MyData.7z.backup',
'MyData...',
'MyData',
'MyData_v1.0.tar.bz2',
'MyData_v1.0.bz2'
])
)
# GENERIC -------------------------------------------------
# Just :: a -> Maybe a
def Just(x):
'''Constructor for an inhabited Maybe (option type) value.'''
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
# Nothing :: Maybe a
def Nothing():
'''Constructor for an empty Maybe (option type) value.'''
return {'type': 'Maybe', 'Nothing': True}
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
# find :: (a -> Bool) -> [a] -> Maybe a
def find(p):
'''Just the first element in the list that matches p,
or Nothing if no elements match.
'''
def go(xs):
for x in xs:
if p(x):
return Just(x)
return Nothing()
return lambda xs: go(xs)
# fromMaybe :: a -> Maybe a -> a
def fromMaybe(x):
'''The default value x if mb is Nothing,
or the value contained in mb.
'''
return lambda mb: x if (
mb.get('Nothing')
) else mb.get('Just')
# DISPLAY -------------------------------------------------
# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
'''Heading -> x display function -> fx display function ->
f -> xs -> tabular string.
'''
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
# MAIN ---
if __name__ == '__main__':
main() |
File size distribution | Python | Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant.
Don't forget that empty files may exist, to serve as a marker.
Is your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?
| import sys, os
from collections import Counter
def dodir(path):
global h
for name in os.listdir(path):
p = os.path.join(path, name)
if os.path.islink(p):
pass
elif os.path.isfile(p):
h[os.stat(p).st_size] += 1
elif os.path.isdir(p):
dodir(p)
else:
pass
def main(arg):
global h
h = Counter()
for dir in arg:
dodir(dir)
s = n = 0
for k, v in sorted(h.items()):
print("Size %d -> %d file(s)" % (k, v))
n += v
s += k * v
print("Total %d bytes for %d files" % (s, n))
main(sys.argv[1:]) |
Find Chess960 starting position identifier | Python 3.10.5 2022-06-28 | Starting Position Identifier number ("SP-ID"), and generate the corresponding position.
;Task:
This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array '''QNRBBNKR''' (or '''''' or ''''''), which we assume is given as seen from White's side of the board from left to right, your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.
You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.
;Algorithm:
The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example).
1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0='''NN---''', 1='''N-N--''', 2='''N--N-''', 3='''N---N''', 4='''-NN--''', etc; our pair is combination number 5. Call this number N. '''N=5'''
2. Still ignoring the Bishops, find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, '''Q=2'''.
3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 ('''D=1'''), and the light bishop is on square 2 ('''L=2''').
4. Then the position number is given by '''4(4(6N + Q)+D)+L''', which reduces to '''96N + 16Q + 4D + L'''. In our example, that's 96x5 + 16x2 + 4x1 + 2 = 480 + 32 + 4 + 2 = 518.
Note that an earlier iteration of this page contained an incorrect description of the algorithm which would give the same SP-ID for both of the following two positions.
RQNBBKRN = 601
RNQBBKRN = 617
| # optional, but task function depends on it as written
def validate_position(candidate: str):
assert (
len(candidate) == 8
), f"candidate position has invalide len = {len(candidate)}"
valid_pieces = {"R": 2, "N": 2, "B": 2, "Q": 1, "K": 1}
assert {
piece for piece in candidate
} == valid_pieces.keys(), f"candidate position contains invalid pieces"
for piece_type in valid_pieces.keys():
assert (
candidate.count(piece_type) == valid_pieces[piece_type]
), f"piece type '{piece_type}' has invalid count"
bishops_pos = [index for index,
value in enumerate(candidate) if value == "B"]
assert (
bishops_pos[0] % 2 != bishops_pos[1] % 2
), f"candidate position has both bishops in the same color"
assert [piece for piece in candidate if piece in "RK"] == [
"R",
"K",
"R",
], "candidate position has K outside of RR"
def calc_position(start_pos: str):
try:
validate_position(start_pos)
except AssertionError:
raise AssertionError
# step 1
subset_step1 = [piece for piece in start_pos if piece not in "QB"]
nights_positions = [
index for index, value in enumerate(subset_step1) if value == "N"
]
nights_table = {
(0, 1): 0,
(0, 2): 1,
(0, 3): 2,
(0, 4): 3,
(1, 2): 4,
(1, 3): 5,
(1, 4): 6,
(2, 3): 7,
(2, 4): 8,
(3, 4): 9,
}
N = nights_table.get(tuple(nights_positions))
# step 2
subset_step2 = [piece for piece in start_pos if piece != "B"]
Q = subset_step2.index("Q")
# step 3
dark_squares = [
piece for index, piece in enumerate(start_pos) if index in range(0, 9, 2)
]
light_squares = [
piece for index, piece in enumerate(start_pos) if index in range(1, 9, 2)
]
D = dark_squares.index("B")
L = light_squares.index("B")
return 4 * (4 * (6*N + Q) + D) + L
if __name__ == '__main__':
for example in ["QNRBBNKR", "RNBQKBNR", "RQNBBKRN", "RNQBBKRN"]:
print(f'Position: {example}; Chess960 PID= {calc_position(example)}') |
Find duplicate files | Python | In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
;Task:
Create a program which, given a minimum size and a folder/directory, will find all files of at least ''size'' bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
| from __future__ import print_function
import os
import hashlib
import datetime
def FindDuplicateFiles(pth, minSize = 0, hashName = "md5"):
knownFiles = {}
#Analyse files
for root, dirs, files in os.walk(pth):
for fina in files:
fullFina = os.path.join(root, fina)
isSymLink = os.path.islink(fullFina)
if isSymLink:
continue # Skip symlinks
si = os.path.getsize(fullFina)
if si < minSize:
continue
if si not in knownFiles:
knownFiles[si] = {}
h = hashlib.new(hashName)
h.update(open(fullFina, "rb").read())
hashed = h.digest()
if hashed in knownFiles[si]:
fileRec = knownFiles[si][hashed]
fileRec.append(fullFina)
else:
knownFiles[si][hashed] = [fullFina]
#Print result
sizeList = list(knownFiles.keys())
sizeList.sort(reverse=True)
for si in sizeList:
filesAtThisSize = knownFiles[si]
for hashVal in filesAtThisSize:
if len(filesAtThisSize[hashVal]) < 2:
continue
fullFinaLi = filesAtThisSize[hashVal]
print ("=======Duplicate=======")
for fullFina in fullFinaLi:
st = os.stat(fullFina)
isHardLink = st.st_nlink > 1
infoStr = []
if isHardLink:
infoStr.append("(Hard linked)")
fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ')
print (fmtModTime, si, os.path.relpath(fullFina, pth), " ".join(infoStr))
if __name__=="__main__":
FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)
|
Find if a point is within a triangle | Python | Find if a point is within a triangle.
;Task:
::* Assume points are on a plane defined by (x, y) real number coordinates.
::* Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
::* You may use any algorithm.
::* Bonus: explain why the algorithm you chose works.
;Related tasks:
* [[Determine_if_two_triangles_overlap]]
;Also see:
:* Discussion of several methods. [[http://totologic.blogspot.com/2014/01/accurate-point-in-triangle-test.html]]
:* Determine if a point is in a polygon [[https://en.wikipedia.org/wiki/Point_in_polygon]]
:* Triangle based coordinate systems [[https://en.wikipedia.org/wiki/Barycentric_coordinate_system]]
:* Wolfram entry [[https://mathworld.wolfram.com/TriangleInterior.html]]
| """ find if point is in a triangle """
from sympy.geometry import Point, Triangle
def sign(pt1, pt2, pt3):
""" which side of plane cut by line (pt2, pt3) is pt1 on? """
return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)
def iswithin(point, pt1, pt2, pt3):
"""
Determine if point is within triangle formed by points p1, p2, p3.
If so, the point will be on the same side of each of the half planes
defined by vectors p1p2, p2p3, and p3p1. zval is positive if outside,
negative if inside such a plane. All should be positive or all negative
if point is within the triangle.
"""
zval1 = sign(point, pt1, pt2)
zval2 = sign(point, pt2, pt3)
zval3 = sign(point, pt3, pt1)
notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0
notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0
return notanyneg or notanypos
if __name__ == "__main__":
POINTS = [Point(0, 0)]
TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))
for pnt in POINTS:
a, b, c = TRI.vertices
isornot = "is" if iswithin(pnt, a, b, c) else "is not"
print("Point", pnt, isornot, "within the triangle", TRI)
|
Find limit of recursion | Python | {{selection|Short Circuit|Console Program Basics}}
;Task:
Find the limit of recursion.
| def recurseDeeper(counter):
try:
print(counter)
recurseDeeper(counter + 1)
except RecursionError:
print("RecursionError at depth", counter)
recurseDeeper(counter + 1) |
Find palindromic numbers in both binary and ternary bases | Python | * Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in ''both'':
:::* base 2
:::* base 3
* Display '''0''' (zero) as the first number found, even though some other definitions ignore it.
* Optionally, show the decimal number found in its binary and ternary form.
* Show all output here.
It's permissible to assume the first two numbers and simply list them.
;See also
* Sequence A60792, numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.
| from itertools import islice
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
if num == 0: return "0"
result = ""
while num != 0:
num, d = divmod(num, b)
result += digits[d]
return result[::-1] # reverse
def pal2(num):
if num == 0 or num == 1: return True
based = bin(num)[2:]
return based == based[::-1]
def pal_23():
yield 0
yield 1
n = 1
while True:
n += 1
b = baseN(n, 3)
revb = b[::-1]
#if len(b) > 12: break
for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),
'{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):
t = int(trial, 3)
if pal2(t):
yield t
for pal23 in islice(pal_23(), 6):
print(pal23, baseN(pal23, 3), baseN(pal23, 2)) |
Find palindromic numbers in both binary and ternary bases | Python 3.7 | * Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in ''both'':
:::* base 2
:::* base 3
* Display '''0''' (zero) as the first number found, even though some other definitions ignore it.
* Optionally, show the decimal number found in its binary and ternary form.
* Show all output here.
It's permissible to assume the first two numbers and simply list them.
;See also
* Sequence A60792, numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.
| '''Numbers with palindromic digit strings in both binary and ternary'''
from itertools import (islice)
# palinBoth :: Generator [Int]
def palinBoth():
'''Non finite stream of dually palindromic integers.'''
yield 0, '0', '0'
ibt = 1, '1', '1'
yield ibt
while True:
ibt = until(isBoth)(psucc)(psucc(ibt))
yield int(ibt[2], 3), ibt[1], ibt[2]
# isBoth :: (Int, String, String) -> Bool
def isBoth(ibt):
'''True if the binary string is palindromic (as
the ternary string is already known to be).
'''
b = ibt[1]
return b == b[::-1]
# psucc :: (Int, String, String) -> (Int, String, String)
def psucc(ibt):
'''The next triple of index, binary
and (palindromic) ternary string
'''
d = 1 + ibt[0]
s = showBase3(d)
pal = s + '1' + s[::-1]
return d, bin(int(pal, 3))[2:], pal
# showBase3 :: Int -> String
def showBase3(n):
'''Ternary digit string for integer n.'''
return showIntAtBase(3)(
lambda i: '012'[i]
)(n)('')
# ------------------------- TEST -------------------------
def main():
'''Integers with palindromic digits in
both binary and ternary bases.
'''
xs = take(6)(palinBoth())
d, b, t = xs[-1]
bw = len(b)
tw = len(t)
print(
fTable(
label('rjust')(('Decimal', len(str(d)))) +
''.join(map(
label('center'),
[('Binary', bw), ('Ternary', tw)]
)) + '\n'
)(compose(str)(fst))(
lambda p: p[1].center(bw, ' ') +
' ' + p[2].center(tw, ' ')
)(identity)(xs)
)
# ----------------------- 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]
# identity :: a -> a
def identity(x):
'''The identity function.'''
return x
# showIntAtBase :: Int -> (Int -> String) -> Int -> String -> String
def showIntAtBase(base):
'''String representation of an integer in a given base,
using a supplied function for the string representation
of digits.
'''
def wrap(toChr, n, rs):
def go(nd, r):
n, d = nd
r_ = toChr(d) + r
return go(divmod(n, base), r_) if 0 != n else r_
return 'unsupported base' if 1 >= base else (
'negative number' if 0 > n else (
go(divmod(n, base), rs))
)
return lambda toChr: lambda n: lambda rs: (
wrap(toChr, n, rs)
)
# 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
# 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):
def g(x):
v = x
while not p(v):
v = f(v)
return v
return g
return go
# ---------------------- FORMATTING ----------------------
# label :: Method String -> (String, Int)
def label(k):
'''Stringification, using the named justification
method (ljust|centre|rjust) of the label,
and the specified amount of white space.
'''
def go(sw):
s, w = sw
return getattr(s, k)(w, ' ') + ' '
return go
# 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() |
Find the intersection of a line with a plane | Python | Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.
;Task:
Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].
| #!/bin/python
from __future__ import print_function
import numpy as np
def LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint, epsilon=1e-6):
ndotu = planeNormal.dot(rayDirection)
if abs(ndotu) < epsilon:
raise RuntimeError("no intersection or line is within plane")
w = rayPoint - planePoint
si = -planeNormal.dot(w) / ndotu
Psi = w + si * rayDirection + planePoint
return Psi
if __name__=="__main__":
#Define plane
planeNormal = np.array([0, 0, 1])
planePoint = np.array([0, 0, 5]) #Any point on the plane
#Define ray
rayDirection = np.array([0, -1, -1])
rayPoint = np.array([0, 0, 10]) #Any point along the ray
Psi = LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint)
print ("intersection at", Psi) |
Find the intersection of two lines | Python | Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html]
;Task:
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
| def line_intersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2):
""" returns a (x, y) tuple or None if there is no intersection """
d = (By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1)
if d:
uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d
uB = ((Ax2 - Ax1) * (Ay1 - By1) - (Ay2 - Ay1) * (Ax1 - Bx1)) / d
else:
return
if not(0 <= uA <= 1 and 0 <= uB <= 1):
return
x = Ax1 + uA * (Ax2 - Ax1)
y = Ay1 + uA * (Ay2 - Ay1)
return x, y
if __name__ == '__main__':
(a, b), (c, d) = (4, 0), (6, 10) # try (4, 0), (6, 4)
(e, f), (g, h) = (0, 3), (10, 7) # for non intersecting test
pt = line_intersect(a, b, c, d, e, f, g, h)
print(pt) |
Find the intersection of two lines | Python 3.7 | Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html]
;Task:
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
| '''The intersection of two lines.'''
from itertools import product
# intersection :: Line -> Line -> Either String Point
def intersection(ab):
'''Either the point at which the lines ab and pq
intersect, or a message string indicating that
they are parallel and have no intersection.'''
def delta(f):
return lambda x: f(fst(x)) - f(snd(x))
def prodDiff(abcd):
[a, b, c, d] = abcd
return (a * d) - (b * c)
def go(pq):
[abDX, pqDX, abDY, pqDY] = apList(
[delta(fst), delta(snd)]
)([ab, pq])
determinant = prodDiff([abDX, abDY, pqDX, pqDY])
def point():
[abD, pqD] = map(
lambda xy: prodDiff(
apList([fst, snd])([fst(xy), snd(xy)])
), [ab, pq]
)
return apList(
[lambda abpq: prodDiff(
[abD, fst(abpq), pqD, snd(abpq)]) / determinant]
)(
[(abDX, pqDX), (abDY, pqDY)]
)
return Right(point()) if 0 != determinant else Left(
'( Parallel lines - no intersection )'
)
return lambda pq: bindLR(go(pq))(
lambda xs: Right((fst(xs), snd(xs)))
)
# --------------------------TEST---------------------------
# main :: IO()
def main():
'''Test'''
# Left(message - no intersection) or Right(point)
# lrPoint :: Either String Point
lrPoint = intersection(
((4.0, 0.0), (6.0, 10.0))
)(
((0.0, 3.0), (10.0, 7.0))
)
print(
lrPoint['Left'] or lrPoint['Right']
)
# --------------------GENERIC FUNCTIONS--------------------
# Left :: a -> Either a b
def Left(x):
'''Constructor for an empty Either (option type) value
with an associated string.'''
return {'type': 'Either', 'Right': None, 'Left': x}
# Right :: b -> Either a b
def Right(x):
'''Constructor for a populated Either (option type) value'''
return {'type': 'Either', 'Left': None, 'Right': x}
# apList (<*>) :: [(a -> b)] -> [a] -> [b]
def apList(fs):
'''The application of each of a list of functions,
to each of a list of values.
'''
def go(fx):
f, x = fx
return f(x)
return lambda xs: [
go(x) for x
in product(fs, xs)
]
# bindLR (>>=) :: Either a -> (a -> Either b) -> Either b
def bindLR(m):
'''Either monad injection operator.
Two computations sequentially composed,
with any value produced by the first
passed as an argument to the second.'''
return lambda mf: (
mf(m.get('Right')) if None is m.get('Left') else m
)
# fst :: (a, b) -> a
def fst(tpl):
'''First member of a pair.'''
return tpl[0]
# snd :: (a, b) -> b
def snd(tpl):
'''Second member of a pair.'''
return tpl[1]
# MAIN ---
if __name__ == '__main__':
main() |
Find the last Sunday of each month | Python | Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
;Related tasks
* [[Day of the week]]
* [[Five weekends]]
* [[Last Friday of each month]]
| import sys
import calendar
year = 2013
if len(sys.argv) > 1:
try:
year = int(sys.argv[-1])
except ValueError:
pass
for month in range(1, 13):
last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month))
print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sunday))
|
Find the missing permutation | Python | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed.
;Task:
Find that missing permutation.
;Methods:
* Obvious method:
enumerate all permutations of '''A''', '''B''', '''C''', and '''D''',
and then look for the missing permutation.
* alternate method:
Hint: if all permutations were shown above, how many
times would '''A''' appear in each position?
What is the ''parity'' of this number?
* another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter '''A''', '''B''', '''C''', and '''D''' from each
column cause the total value for each column to be unique?
;Related task:
* [[Permutations]])
| ===Python: Calculate difference when compared to all permutations===
|
Find the missing permutation | Python 2.6+ | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed.
;Task:
Find that missing permutation.
;Methods:
* Obvious method:
enumerate all permutations of '''A''', '''B''', '''C''', and '''D''',
and then look for the missing permutation.
* alternate method:
Hint: if all permutations were shown above, how many
times would '''A''' appear in each position?
What is the ''parity'' of this number?
* another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter '''A''', '''B''', '''C''', and '''D''' from each
column cause the total value for each column to be unique?
;Related task:
* [[Permutations]])
| def missing_permutation(arr):
"Find the missing permutation in an array of N! - 1 permutations."
# We won't validate every precondition, but we do have some basic
# guards.
if len(arr) == 0: raise Exception("Need more data")
if len(arr) == 1:
return [arr[0][1] + arr[0][0]]
# Now we know that for each position in the string, elements should appear
# an even number of times (N-1 >= 2). We can use a set to detect the element appearing
# an odd number of times. Detect odd occurrences by toggling admission/expulsion
# to and from the set for each value encountered. At the end of each pass one element
# will remain in the set.
missing_permutation = ''
for pos in range(len(arr[0])):
s = set()
for permutation in arr:
c = permutation[pos]
if c in s:
s.remove(c)
else:
s.add(c)
missing_permutation += list(s)[0]
return missing_permutation
given = '''ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB'''.split()
print missing_permutation(given)
|
Find the missing permutation | Python from JavaScript | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed.
;Task:
Find that missing permutation.
;Methods:
* Obvious method:
enumerate all permutations of '''A''', '''B''', '''C''', and '''D''',
and then look for the missing permutation.
* alternate method:
Hint: if all permutations were shown above, how many
times would '''A''' appear in each position?
What is the ''parity'' of this number?
* another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter '''A''', '''B''', '''C''', and '''D''' from each
column cause the total value for each column to be unique?
;Related task:
* [[Permutations]])
| '''Find the missing permutation'''
from functools import reduce
from operator import xor
print(''.join([
chr(i) for i in reduce(
lambda a, s: map(
xor,
a,
[ord(c) for c in list(s)]
), [
'ABCD', 'CABD', 'ACDB', 'DACB',
'BCDA', 'ACBD', 'ADCB', 'CDAB',
'DABC', 'BCAD', 'CADB', 'CDBA',
'CBAD', 'ABDC', 'ADBC', 'BDCA',
'DCBA', 'BACD', 'BADC', 'BDAC',
'CBDA', 'DBCA', 'DCAB'
],
[0, 0, 0, 0]
)
])) |
First-class functions/Use numbers analogously | Python | In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
Create a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
new_function = multiplier(n1,n2)
# where new_function(m) returns the result of n1 * n2 * m
Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
'''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close.
To paraphrase the task description: Do what was done before, but with numbers rather than functions
| >>> # Some built in functions and their inverses
>>> from math import sin, cos, acos, asin
>>> # Add a user defined function and its inverse
>>> cube = lambda x: x * x * x
>>> croot = lambda x: x ** (1/3.0)
>>> # First class functions allow run-time creation of functions from functions
>>> # return function compose(f,g)(x) == f(g(x))
>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )
>>> # first class functions should be able to be members of collection types
>>> funclist = [sin, cos, cube]
>>> funclisti = [asin, acos, croot]
>>> # Apply functions from lists as easily as integers
>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]
[0.5, 0.4999999999999999, 0.5]
>>> |
First perfect square in base n with n unique digits | Python 3.7 | Find the first perfect square in a given base '''N''' that has at least '''N''' digits and
exactly '''N''' ''significant unique'' digits when expressed in base '''N'''.
E.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432''').
You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.
;Task
* Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated.
* (optional) Do the same for bases '''13''' through '''16'''.
* (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math)
;See also:
;* OEIS A260182: smallest square that is pandigital in base n.
;Related task
;* [[Casting out nines]]
| '''Perfect squares using every digit in a given base.'''
from itertools import count, dropwhile, repeat
from math import ceil, sqrt
from time import time
# allDigitSquare :: Int -> Int -> Int
def allDigitSquare(base, above):
'''The lowest perfect square which
requires all digits in the given base.
'''
bools = list(repeat(True, base))
return next(
dropwhile(
missingDigitsAtBase(base, bools),
count(
max(
above,
ceil(sqrt(int(
'10' + '0123456789abcdef'[2:base],
base
)))
)
)
)
)
# missingDigitsAtBase :: Int -> [Bool] -> Int -> Bool
def missingDigitsAtBase(base, bools):
'''Fusion of representing the square of integer N at a
given base with checking whether all digits of
that base contribute to N^2.
Clears the bool at a digit position to False when used.
True if any positions remain uncleared (unused).
'''
def go(x):
xs = bools.copy()
while x:
xs[x % base] = False
x //= base
return any(xs)
return lambda n: go(n * n)
# digit :: Int -> Char
def digit(n):
'''Digit character for given integer.'''
return '0123456789abcdef'[n]
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Smallest perfect squares using all digits in bases 2-16'''
start = time()
print(main.__doc__ + ':\n\nBase Root Square')
q = 0
for b in enumFromTo(2)(16):
q = allDigitSquare(b, q)
print(
str(b).rjust(2, ' ') + ' -> ' +
showIntAtBase(b)(digit)(q)('').rjust(8, ' ') +
' -> ' +
showIntAtBase(b)(digit)(q * q)('')
)
print(
'\nc. ' + str(ceil(time() - start)) + ' seconds.'
)
# ----------------------- GENERIC ------------------------
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
# showIntAtBase :: Int -> (Int -> String) -> Int ->
# String -> String
def showIntAtBase(base):
'''String representation of an integer in a given base,
using a supplied function for the string representation
of digits.
'''
def wrap(toChr, n, rs):
def go(nd, r):
n, d = nd
r_ = toChr(d) + r
return go(divmod(n, base), r_) if 0 != n else r_
return 'unsupported base' if 1 >= base else (
'negative number' if 0 > n else (
go(divmod(n, base), rs))
)
return lambda toChr: lambda n: lambda rs: (
wrap(toChr, n, rs)
)
# MAIN ---
if __name__ == '__main__':
main()
|
First power of 2 that has leading decimal digits of 12 | Python | (This task is taken from a ''Project Euler'' problem.)
(All numbers herein are expressed in base ten.)
'''27 = 128''' and '''7''' is
the first power of '''2''' whose leading decimal digits are '''12'''.
The next power of '''2''' whose leading decimal digits
are '''12''' is '''80''',
'''280 = 1208925819614629174706176'''.
Define ''' '' p''(''L,n'')''' to be the ''' ''n''th'''-smallest
value of ''' ''j'' ''' such that the base ten representation
of '''2''j''''' begins with the digits of ''' ''L'' '''.
So ''p''(12, 1) = 7 and
''p''(12, 2) = 80
You are also given that:
''p''(123, 45) = 12710
;Task:
::* find:
:::::* ''' ''p''(12, 1) '''
:::::* ''' ''p''(12, 2) '''
:::::* ''' ''p''(123, 45) '''
:::::* ''' ''p''(123, 12345) '''
:::::* ''' ''p''(123, 678910) '''
::* display the results here, on this page.
| from math import log, modf, floor
def p(l, n, pwr=2):
l = int(abs(l))
digitcount = floor(log(l, 10))
log10pwr = log(pwr, 10)
raised, found = -1, 0
while found < n:
raised += 1
firstdigits = floor(10**(modf(log10pwr * raised)[0] + digitcount))
if firstdigits == l:
found += 1
return raised
if __name__ == '__main__':
for l, n in [(12, 1), (12, 2), (123, 45), (123, 12345), (123, 678910)]:
print(f"p({l}, {n}) =", p(l, n)) |
Fivenum | Python from Perl | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the '''R''' programming language implements Tukey's five-number summary as the '''fivenum''' function.
;Task:
Given an array of numbers, compute the five-number summary.
;Note:
While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data.
Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
| from __future__ import division
import math
import sys
def fivenum(array):
n = len(array)
if n == 0:
print("you entered an empty array.")
sys.exit()
x = sorted(array)
n4 = math.floor((n+3.0)/2.0)/2.0
d = [1, n4, (n+1)/2, n+1-n4, n]
sum_array = []
for e in range(5):
floor = int(math.floor(d[e] - 1))
ceil = int(math.ceil(d[e] - 1))
sum_array.append(0.5 * (x[floor] + x[ceil]))
return sum_array
x = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970,
-0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163,
1.04312009, -0.10305385, 0.75775634, 0.32566578]
y = fivenum(x)
print(y) |
Fixed length records | Python | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encoded by punching holes in one or more rows of the card for each column.
These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).
;Task:
Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records.
Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.
'''Note:''' There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.
These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression ''logical record length''.
;Sample data:
To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of '''dd''' support blocking and unblocking records with a conversion byte size.
Line 1...1.........2.........3.........4.........5.........6.........7.........8
Line 2
Line 3
Line 4
Line 6
Line 7
Indented line 8............................................................
Line 9 RT MARGIN
prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block will create a fixed length record file of 80 bytes given newline delimited text input.
prompt$ dd if=infile.dat cbs=80 conv=unblock will display a file with 80 byte logical record lengths to standard out as standard text with newlines.
;Bonus round:
Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).
Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.
Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.
The COBOL example uses forth.txt and forth.blk filenames.
| infile = open('infile.dat', 'rb')
outfile = open('outfile.dat', 'wb')
while True:
onerecord = infile.read(80)
if len(onerecord) < 80:
break
onerecordreversed = bytes(reversed(onerecord))
outfile.write(onerecordreversed)
infile.close()
outfile.close()
|
Flatten a list | Python | Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
;Related task:
* [[Tree traversal]]
| >>> def flatten(itr):
>>> for x in itr:
>>> try:
>>> yield from flatten(x)
>>> except:
>>> yield x
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>> list(flatten(lst))
[1, 2, 3, 4, 5, 6, 7, 8]
>>> tuple(flatten(lst))
(1, 2, 3, 4, 5, 6, 7, 8)
>>>for i in flatten(lst):
>>> print(i)
1
2
3
4
5
6
7
8 |
Flatten a list | Python 3.7 | Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
;Related task:
* [[Tree traversal]]
| '''Flatten a list'''
from functools import (reduce)
from itertools import (chain)
def flatten(xs):
'''A flat list of atomic values derived
from a nested list.
'''
return reduce(
lambda a, x: a + list(until(every(notList))(
concatMap(pureList)
)([x])),
xs, []
)
# TEST ----------------------------------------------------
def main():
'''From nested list to flattened list'''
print(main.__doc__ + ':\n\n')
xs = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
print(
repr(xs) + ' -> ' + repr(flatten(xs))
)
# GENERIC -------------------------------------------------
# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
'''A concatenated list over which a function has been mapped.
The list monad can be derived by using a function f which
wraps its output in a list,
(using an empty list to represent computational failure).
'''
return lambda xs: list(
chain.from_iterable(map(f, xs))
)
# every :: (a -> Bool) -> [a] -> Bool
def every(p):
'''True if p(x) holds for every x in xs'''
def go(p, xs):
return all(map(p, xs))
return lambda xs: go(p, xs)
# notList :: a -> Bool
def notList(x):
'''True if the value x is not a list.'''
return not isinstance(x, list)
# pureList :: a -> [b]
def pureList(x):
'''x if x is a list, othewise [x]'''
return x if isinstance(x, list) else [x]
# until :: (a -> Bool) -> (a -> a) -> a -> a
def until(p):
'''The result of repeatedly applying f until p holds.
The initial seed value is x.'''
def go(f, x):
v = x
while not p(v):
v = f(v)
return v
return lambda f: lambda x: go(f, x)
if __name__ == '__main__':
main() |
Flipping bits game | Python | The game:
Given an '''NxN''' square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any '''1''' becomes '''0''', and any '''0''' becomes '''1''' for that whole row or column.
;Task:
Create a program to score for the Flipping bits game.
# The game should create an original random target configuration and a starting configuration.
# Ensure that the starting position is ''never'' the target position.
# The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).
# The number of moves taken so far should be shown.
Show an example of a short game here, on this page, for a '''3x3''' array of bits.
| """
Given a %i by %i sqare array of zeroes or ones in an initial
configuration, and a target configuration of zeroes and ones
The task is to transform one to the other in as few moves as
possible by inverting whole numbered rows or whole lettered
columns at once.
In an inversion any 1 becomes 0 and any 0 becomes 1 for that
whole row or column.
"""
from random import randrange
from copy import deepcopy
from string import ascii_lowercase
try: # 2to3 fix
input = raw_input
except:
pass
N = 3 # N x N Square arrray
board = [[0]* N for i in range(N)]
def setbits(board, count=1):
for i in range(count):
board[randrange(N)][randrange(N)] ^= 1
def shuffle(board, count=1):
for i in range(count):
if randrange(0, 2):
fliprow(randrange(N))
else:
flipcol(randrange(N))
def pr(board, comment=''):
print(str(comment))
print(' ' + ' '.join(ascii_lowercase[i] for i in range(N)))
print(' ' + '\n '.join(' '.join(['%2s' % j] + [str(i) for i in line])
for j, line in enumerate(board, 1)))
def init(board):
setbits(board, count=randrange(N)+1)
target = deepcopy(board)
while board == target:
shuffle(board, count=2 * N)
prompt = ' X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0],
ascii_lowercase[N-1])
return target, prompt
def fliprow(i):
board[i-1][:] = [x ^ 1 for x in board[i-1] ]
def flipcol(i):
for row in board:
row[i] ^= 1
if __name__ == '__main__':
print(__doc__ % (N, N))
target, prompt = init(board)
pr(target, 'Target configuration is:')
print('')
turns = 0
while board != target:
turns += 1
pr(board, '%i:' % turns)
ans = input(prompt).strip()
if (len(ans) == 1
and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):
flipcol(ascii_lowercase.index(ans))
elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:
fliprow(int(ans))
elif ans == 'T':
pr(target, 'Target configuration is:')
turns -= 1
elif ans == 'X':
break
else:
print(" I don't understand %r... Try again. "
"(X to exit or T to show target)\n" % ans[:9])
turns -= 1
else:
print('\nWell done!\nBye.') |
Floyd's triangle | Python | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
* the first row is '''1''' (unity)
* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
;Task:
:# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows).
:# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
| >>> def floyd(rowcount=5):
rows = [[1]]
while len(rows) < rowcount:
n = rows[-1][-1] + 1
rows.append(list(range(n, n + len(rows[-1]) + 1)))
return rows
>>> floyd()
[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14, 15]]
>>> def pfloyd(rows=[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]):
colspace = [len(str(n)) for n in rows[-1]]
for row in rows:
print( ' '.join('%*i' % space_n for space_n in zip(colspace, row)))
>>> pfloyd()
1
2 3
4 5 6
7 8 9 10
>>> pfloyd(floyd(5))
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
>>> pfloyd(floyd(14))
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63 64 65 66
67 68 69 70 71 72 73 74 75 76 77 78
79 80 81 82 83 84 85 86 87 88 89 90 91
92 93 94 95 96 97 98 99 100 101 102 103 104 105
>>> |
Floyd's triangle | Python 3 | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
* the first row is '''1''' (unity)
* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
;Task:
:# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows).
:# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
| '''Floyd triangle in terms of iterate(f)(x)'''
from itertools import islice
# floyd :: Int -> [[Int]]
def floyd(n):
'''n rows of a Floyd triangle.'''
return take(n)(iterate(nextFloyd)([1]))
# nextFloyd :: [Int] -> [Int]
def nextFloyd(xs):
'''A Floyd triangle row derived from
the preceding row.'''
n = succ(len(xs))
return [1] if n < 2 else (
enumFromTo(succ(n * pred(n) // 2))(
n * succ(n) // 2
)
)
# showFloyd :: [[Int]] -> String
def showFloyd(xs):
'''A stringification of Floyd triangle rows.'''
return unlines(str(x) for x in xs)
# main :: IO ()
def main():
'''Test'''
print(showFloyd(
floyd(5)
))
# GENERIC ABSTRACTIONS ------------------------------------
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
# iterate :: (a -> a) -> a -> Gen [a]
def iterate(f):
'''An infinite list of repeated applications of f to x.'''
def go(x):
v = x
while True:
yield v
v = f(v)
return lambda x: go(x)
# pred :: Enum a => a -> a
def pred(x):
'''The predecessor of a value. For numeric types, (- 1).'''
return x - 1 if isinstance(x, int) else (
chr(ord(x) - 1)
)
# succ :: Enum a => a -> a
def succ(x):
'''The successor of a value. For numeric types, (1 +).'''
return 1 + x if isinstance(x, int) else (
chr(1 + ord(x))
)
# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.'''
return lambda xs: (
xs[0:n]
if isinstance(xs, list)
else list(islice(xs, n))
)
# unlines :: [String] -> String
def unlines(xs):
'''A single string derived by the intercalation
of a list of strings with the newline character.'''
return '\n'.join(xs)
# MAIN ----------------------------------------------------
if __name__ == '__main__':
main() |
Four bit adder | Python | "''Simulate''" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two gate. ;
Finally a half adder can be made using an ''xor'' gate and an ''and'' gate.
The ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''.
'''Not''', '''or''' and '''and''', the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a ''bit type'' in your language, to be sure that the ''not'' does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra ''nand'' (''and'' then ''not'') with the constant '''1''' on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, ''connecting'' the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
{|
|+Schematics of the "constructive blocks"
!(Xor gate with ANDs, ORs and NOTs)
! (A half adder)
! (A full adder)
! (A 4-bit adder)
|-
|Xor gate done with ands, ors and nots
|A half adder
|A full adder
|A 4-bit adder
|}
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
| def xor(a, b): return (a and not b) or (b and not a)
def ha(a, b): return xor(a, b), a and b # sum, carry
def fa(a, b, ci):
s0, c0 = ha(ci, a)
s1, c1 = ha(s0, b)
return s1, c0 or c1 # sum, carry
def fa4(a, b):
width = 4
ci = [None] * width
co = [None] * width
s = [None] * width
for i in range(width):
s[i], co[i] = fa(a[i], b[i], co[i-1] if i else 0)
return s, co[-1]
def int2bus(n, width=4):
return [int(c) for c in "{0:0{1}b}".format(n, width)[::-1]]
def bus2int(b):
return sum(1 << i for i, bit in enumerate(b) if bit)
def test_fa4():
width = 4
tot = [None] * (width + 1)
for a in range(2**width):
for b in range(2**width):
tot[:width], tot[width] = fa4(int2bus(a), int2bus(b))
assert a + b == bus2int(tot), "totals don't match: %i + %i != %s" % (a, b, tot)
if __name__ == '__main__':
test_fa4() |
Four is magic | Python | Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.
Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word.
Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.
For instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.'''
'''Three is five, five is four, four is magic.'''
For reference, here are outputs for 0 through 9.
Zero is four, four is magic.
One is three, three is five, five is four, four is magic.
Two is three, three is five, five is four, four is magic.
Three is five, five is four, four is magic.
Four is magic.
Five is four, four is magic.
Six is three, three is five, five is four, four is magic.
Seven is five, five is four, four is magic.
Eight is five, five is four, four is magic.
Nine is four, four is magic.
;Some task guidelines:
:* You may assume the input will only contain integer numbers.
:* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.)
:* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)
:* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.)
:* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''.
:* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''.
:* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''.
:* The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.")
:* The output can either be the return value from the function, or be displayed from within the function.
:* You are encouraged, though not mandated to use proper sentence capitalization.
:* You may optionally support negative numbers. '''-7''' is '''negative seven'''.
:* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.
You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public.
If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)
Four is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code.
;Related tasks:
:* [[Four is the number of_letters in the ...]]
:* [[Look-and-say sequence]]
:* [[Number names]]
:* [[Self-describing numbers]]
:* [[Summarize and say sequence]]
:* [[Spelling of ordinal numbers]]
:* [[De Bruijn sequences]]
| import random
from collections import OrderedDict
numbers = { # taken from https://en.wikipedia.org/wiki/Names_of_large_numbers#cite_ref-a_14-3
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
30: 'thirty',
40: 'forty',
50: 'fifty',
60: 'sixty',
70: 'seventy',
80: 'eighty',
90: 'ninety',
100: 'hundred',
1000: 'thousand',
10 ** 6: 'million',
10 ** 9: 'billion',
10 ** 12: 'trillion',
10 ** 15: 'quadrillion',
10 ** 18: 'quintillion',
10 ** 21: 'sextillion',
10 ** 24: 'septillion',
10 ** 27: 'octillion',
10 ** 30: 'nonillion',
10 ** 33: 'decillion',
10 ** 36: 'undecillion',
10 ** 39: 'duodecillion',
10 ** 42: 'tredecillion',
10 ** 45: 'quattuordecillion',
10 ** 48: 'quinquadecillion',
10 ** 51: 'sedecillion',
10 ** 54: 'septendecillion',
10 ** 57: 'octodecillion',
10 ** 60: 'novendecillion',
10 ** 63: 'vigintillion',
10 ** 66: 'unvigintillion',
10 ** 69: 'duovigintillion',
10 ** 72: 'tresvigintillion',
10 ** 75: 'quattuorvigintillion',
10 ** 78: 'quinquavigintillion',
10 ** 81: 'sesvigintillion',
10 ** 84: 'septemvigintillion',
10 ** 87: 'octovigintillion',
10 ** 90: 'novemvigintillion',
10 ** 93: 'trigintillion',
10 ** 96: 'untrigintillion',
10 ** 99: 'duotrigintillion',
10 ** 102: 'trestrigintillion',
10 ** 105: 'quattuortrigintillion',
10 ** 108: 'quinquatrigintillion',
10 ** 111: 'sestrigintillion',
10 ** 114: 'septentrigintillion',
10 ** 117: 'octotrigintillion',
10 ** 120: 'noventrigintillion',
10 ** 123: 'quadragintillion',
10 ** 153: 'quinquagintillion',
10 ** 183: 'sexagintillion',
10 ** 213: 'septuagintillion',
10 ** 243: 'octogintillion',
10 ** 273: 'nonagintillion',
10 ** 303: 'centillion',
10 ** 306: 'uncentillion',
10 ** 309: 'duocentillion',
10 ** 312: 'trescentillion',
10 ** 333: 'decicentillion',
10 ** 336: 'undecicentillion',
10 ** 363: 'viginticentillion',
10 ** 366: 'unviginticentillion',
10 ** 393: 'trigintacentillion',
10 ** 423: 'quadragintacentillion',
10 ** 453: 'quinquagintacentillion',
10 ** 483: 'sexagintacentillion',
10 ** 513: 'septuagintacentillion',
10 ** 543: 'octogintacentillion',
10 ** 573: 'nonagintacentillion',
10 ** 603: 'ducentillion',
10 ** 903: 'trecentillion',
10 ** 1203: 'quadringentillion',
10 ** 1503: 'quingentillion',
10 ** 1803: 'sescentillion',
10 ** 2103: 'septingentillion',
10 ** 2403: 'octingentillion',
10 ** 2703: 'nongentillion',
10 ** 3003: 'millinillion'
}
numbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True))
def string_representation(i: int) -> str:
"""
Return the english string representation of an integer
"""
if i == 0:
return 'zero'
words = ['negative'] if i < 0 else []
working_copy = abs(i)
for key, value in numbers.items():
if key <= working_copy:
times = int(working_copy / key)
if key >= 100:
words.append(string_representation(times))
words.append(value)
working_copy -= times * key
if working_copy == 0:
break
return ' '.join(words)
def next_phrase(i: int):
"""
Generate all the phrases
"""
while not i == 4: # Generate phrases until four is reached
str_i = string_representation(i)
len_i = len(str_i)
yield str_i, 'is', string_representation(len_i)
i = len_i
# the last phrase
yield string_representation(i), 'is', 'magic'
def magic(i: int) -> str:
phrases = []
for phrase in next_phrase(i):
phrases.append(' '.join(phrase))
return f'{", ".join(phrases)}.'.capitalize()
if __name__ == '__main__':
for j in (random.randint(0, 10 ** 3) for i in range(5)):
print(j, ':\n', magic(j), '\n')
for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)):
print(j, ':\n', magic(j), '\n') |
Four is the number of letters in the ... | Python | The '''Four is ...''' sequence is based on the counting of the number of
letters in the words of the (never-ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ***
;Definitions and directives:
:* English is to be used in spelling numbers.
:* '''Letters''' are defined as the upper- and lowercase letters in the Latin alphabet ('''A-->Z''' and '''a-->z''').
:* Commas are not counted, nor are hyphens (dashes or minus signs).
:* '''twenty-three''' has eleven letters.
:* '''twenty-three''' is considered one word (which is hyphenated).
:* no ''' ''and'' ''' words are to be used when spelling a (English) word for a number.
:* The American version of numbers will be used here in this task (as opposed to the British version).
'''2,000,000,000''' is two billion, ''not'' two milliard.
;Task:
:* Write a driver (invoking routine) and a function (subroutine/routine***) that returns the sequence (for any positive integer) of the number of letters in the first '''N''' words in the never-ending sentence. For instance, the portion of the never-ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
'''4 2 3 6 2 7'''
:* Only construct as much as is needed for the never-ending sentence.
:* Write a driver (invoking routine) to show the number of letters in the Nth word, ''as well as'' showing the Nth word itself.
:* After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
:* Show all output here.
;Test cases:
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
;Related tasks:
:* [[Four is magic]]
:* [[Look-and-say sequence]]
:* [[Number names]]
:* [[Self-describing numbers]]
:* [[Self-referential sequence]]
:* [[Spelling of ordinal numbers]]
;Also see:
:* See the OEIS sequence A72425 "Four is the number of letters...".
:* See the OEIS sequence A72424 "Five's the number of letters..."
| # Python implementation of Rosetta Code Task
# http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
# Uses inflect
# https://pypi.org/project/inflect/
import inflect
def count_letters(word):
"""
count letters ignore , or -, or space
"""
count = 0
for letter in word:
if letter != ',' and letter !='-' and letter !=' ':
count += 1
return count
def split_with_spaces(sentence):
"""
Takes string with partial sentence and returns
list of words with spaces included.
Leading space is attached to first word.
Later spaces attached to prior word.
"""
sentence_list = []
curr_word = ""
for c in sentence:
if c == " " and curr_word != "":
# append space to end of non-empty words
# assumed no more than 1 consecutive space.
sentence_list.append(curr_word+" ")
curr_word = ""
else:
curr_word += c
# add trailing word that does not end with a space
if len(curr_word) > 0:
sentence_list.append(curr_word)
return sentence_list
def my_num_to_words(p, my_number):
"""
Front end to inflect's number_to_words
Get's rid of ands and commas in large numbers.
"""
number_string_list = p.number_to_words(my_number, wantlist=True, andword='')
number_string = number_string_list[0]
for i in range(1,len(number_string_list)):
number_string += " " + number_string_list[i]
return number_string
def build_sentence(p, max_words):
"""
Builds at most max_words of the task following the pattern:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth,
"""
# start with first part of sentence up first comma as a list
sentence_list = split_with_spaces("Four is the number of letters in the first word of this sentence,")
num_words = 13
# which word number we are doing next
# two/second is first one in loop
word_number = 2
# loop until sentance is at least as long as needs be
while num_words < max_words:
# Build something like
# ,two in the second
# get second or whatever we are on
ordinal_string = my_num_to_words(p, p.ordinal(word_number))
# get two or whatever the length is of the word_number word
word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))
# sentence addition
new_string = " "+word_number_string+" in the "+ordinal_string+","
new_list = split_with_spaces(new_string)
sentence_list += new_list
# add new word count
num_words += len(new_list)
# increment word number
word_number += 1
return sentence_list, num_words
def word_and_counts(word_num):
"""
Print's lines like this:
Word 1000 is "in", with 2 letters. Length of sentence so far: 6279
"""
sentence_list, num_words = build_sentence(p, word_num)
word_str = sentence_list[word_num - 1].strip(' ,')
num_letters = len(word_str)
num_characters = 0
for word in sentence_list:
num_characters += len(word)
print('Word {0:8d} is "{1}", with {2} letters. Length of the sentence so far: {3} '.format(word_num,word_str,num_letters,num_characters))
p = inflect.engine()
sentence_list, num_words = build_sentence(p, 201)
print(" ")
print("The lengths of the first 201 words are:")
print(" ")
print('{0:3d}: '.format(1),end='')
total_characters = 0
for word_index in range(201):
word_length = count_letters(sentence_list[word_index])
total_characters += len(sentence_list[word_index])
print('{0:2d}'.format(word_length),end='')
if (word_index+1) % 20 == 0:
# newline every 20
print(" ")
print('{0:3d}: '.format(word_index + 2),end='')
else:
print(" ",end='')
print(" ")
print(" ")
print("Length of the sentence so far: "+str(total_characters))
print(" ")
"""
Expected output this part:
Word 1000 is "in", with 2 letters. Length of the sentence so far: 6279
Word 10000 is "in", with 2 letters. Length of the sentence so far: 64140
Word 100000 is "one", with 3 letters. Length of the sentence so far: 659474
Word 1000000 is "the", with 3 letters. Length of the sentence so far: 7113621
Word 10000000 is "thousand", with 8 letters. Length of the sentence so far: 70995756
"""
word_and_counts(1000)
word_and_counts(10000)
word_and_counts(100000)
word_and_counts(1000000)
word_and_counts(10000000)
|
Functional coverage tree | Python | Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional ''requirements'' of the
system have been verified.
This task uses a sub-set of the calculations sometimes used in tracking
functional coverage but uses a more familiar(?) scenario.
;Task Description:
The head of the clean-up crews for "The Men in a very dark shade of grey when
viewed at night" has been tasked with managing the cleansing of two properties
after an incident involving aliens.
She arranges the task hierarchically with a manager for the crews working on
each house who return with a breakdown of how they will report on progress in
each house.
The overall hierarchy of (sub)tasks is as follows,
cleaning
house1
bedrooms
bathrooms
bathroom1
bathroom2
outside lavatory
attic
kitchen
living rooms
lounge
dining room
conservatory
playroom
basement
garage
garden
house2
upstairs
bedrooms
suite 1
suite 2
bedroom 3
bedroom 4
bathroom
toilet
attics
groundfloor
kitchen
living rooms
lounge
dining room
conservatory
playroom
wet room & toilet
garage
garden
hot tub suite
basement
cellars
wine cellar
cinema
The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.
Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.
NAME_HIERARCHY |WEIGHT |COVERAGE |
cleaning | | |
house1 |40 | |
bedrooms | |0.25 |
bathrooms | | |
bathroom1 | |0.5 |
bathroom2 | | |
outside_lavatory | |1 |
attic | |0.75 |
kitchen | |0.1 |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | |1 |
basement | | |
garage | | |
garden | |0.8 |
house2 |60 | |
upstairs | | |
bedrooms | | |
suite_1 | | |
suite_2 | | |
bedroom_3 | | |
bedroom_4 | | |
bathroom | | |
toilet | | |
attics | |0.6 |
groundfloor | | |
kitchen | | |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | | |
wet_room_&_toilet | | |
garage | | |
garden | |0.9 |
hot_tub_suite | |1 |
basement | | |
cellars | |1 |
wine_cellar | |1 |
cinema | |0.75 |
;Calculation:
The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.
'''The task is to''' calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.
;Extra Credit:
After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1-coverage for any node, by the product of the `powers` of its parent nodes from the top down to the node.
The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.
The pseudo code would be:
method delta_calculation(this, power):
sum_of_weights = sum(node.weight for node in children)
this.delta = (1 - this.coverage) * power
for node in self.children:
node.delta_calculation(power * node.weight / sum_of_weights)
return this.delta
Followed by a call to:
top.delta_calculation(power=1)
'''Note:''' to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
| from itertools import zip_longest
fc2 = '''\
cleaning,,
house1,40,
bedrooms,,.25
bathrooms,,
bathroom1,,.5
bathroom2,,
outside_lavatory,,1
attic,,.75
kitchen,,.1
living_rooms,,
lounge,,
dining_room,,
conservatory,,
playroom,,1
basement,,
garage,,
garden,,.8
house2,60,
upstairs,,
bedrooms,,
suite_1,,
suite_2,,
bedroom_3,,
bedroom_4,,
bathroom,,
toilet,,
attics,,.6
groundfloor,,
kitchen,,
living_rooms,,
lounge,,
dining_room,,
conservatory,,
playroom,,
wet_room_&_toilet,,
garage,,
garden,,.9
hot_tub_suite,,1
basement,,
cellars,,1
wine_cellar,,1
cinema,,.75
'''
NAME, WT, COV = 0, 1, 2
def right_type(txt):
try:
return float(txt)
except ValueError:
return txt
def commas_to_list(the_list, lines, start_indent=0):
'''
Output format is a nest of lists and tuples
lists are for coverage leaves without children items in the list are name, weight, coverage
tuples are 2-tuples for nodes with children. The first element is a list representing the
name, weight, coverage of the node (some to be calculated); the second element is a list of
child elements which may be 2-tuples or lists as above.
the_list is modified in-place
lines must be a generator of successive lines of input like fc2
'''
for n, line in lines:
indent = 0
while line.startswith(' ' * (4 * indent)):
indent += 1
indent -= 1
fields = [right_type(f) for f in line.strip().split(',')]
if indent == start_indent:
the_list.append(fields)
elif indent > start_indent:
lst = [fields]
sub = commas_to_list(lst, lines, indent)
the_list[-1] = (the_list[-1], lst)
if sub not in (None, ['']) :
the_list.append(sub)
else:
return fields if fields else None
return None
def pptreefields(lst, indent=0, widths=['%-32s', '%-8g', '%-10g']):
'''
Pretty prints the format described from function commas_to_list as a table with
names in the first column suitably indented and all columns having a fixed
minimum column width.
'''
lhs = ' ' * (4 * indent)
for item in lst:
if type(item) != tuple:
name, *rest = item
print(widths[0] % (lhs + name), end='|')
for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]):
if type(item) == str:
width = width[:-1] + 's'
print(width % item, end='|')
print()
else:
item, children = item
name, *rest = item
print(widths[0] % (lhs + name), end='|')
for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]):
if type(item) == str:
width = width[:-1] + 's'
print(width % item, end='|')
print()
pptreefields(children, indent+1)
def default_field(node_list):
node_list[WT] = node_list[WT] if node_list[WT] else 1.0
node_list[COV] = node_list[COV] if node_list[COV] else 0.0
def depth_first(tree, visitor=default_field):
for item in tree:
if type(item) == tuple:
item, children = item
depth_first(children, visitor)
visitor(item)
def covercalc(tree):
'''
Depth first weighted average of coverage
'''
sum_covwt, sum_wt = 0, 0
for item in tree:
if type(item) == tuple:
item, children = item
item[COV] = covercalc(children)
sum_wt += item[WT]
sum_covwt += item[COV] * item[WT]
cov = sum_covwt / sum_wt
return cov
if __name__ == '__main__':
lstc = []
commas_to_list(lstc, ((n, ln) for n, ln in enumerate(fc2.split('\n'))))
#pp(lstc, width=1, indent=4, compact=1)
#print('\n\nEXPANDED DEFAULTS\n')
depth_first(lstc)
#pptreefields(['NAME_HIERARCHY WEIGHT COVERAGE'.split()] + lstc)
print('\n\nTOP COVERAGE = %f\n' % covercalc(lstc))
depth_first(lstc)
pptreefields(['NAME_HIERARCHY WEIGHT COVERAGE'.split()] + lstc) |
Functional coverage tree | Python 3.7 | Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional ''requirements'' of the
system have been verified.
This task uses a sub-set of the calculations sometimes used in tracking
functional coverage but uses a more familiar(?) scenario.
;Task Description:
The head of the clean-up crews for "The Men in a very dark shade of grey when
viewed at night" has been tasked with managing the cleansing of two properties
after an incident involving aliens.
She arranges the task hierarchically with a manager for the crews working on
each house who return with a breakdown of how they will report on progress in
each house.
The overall hierarchy of (sub)tasks is as follows,
cleaning
house1
bedrooms
bathrooms
bathroom1
bathroom2
outside lavatory
attic
kitchen
living rooms
lounge
dining room
conservatory
playroom
basement
garage
garden
house2
upstairs
bedrooms
suite 1
suite 2
bedroom 3
bedroom 4
bathroom
toilet
attics
groundfloor
kitchen
living rooms
lounge
dining room
conservatory
playroom
wet room & toilet
garage
garden
hot tub suite
basement
cellars
wine cellar
cinema
The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.
Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.
NAME_HIERARCHY |WEIGHT |COVERAGE |
cleaning | | |
house1 |40 | |
bedrooms | |0.25 |
bathrooms | | |
bathroom1 | |0.5 |
bathroom2 | | |
outside_lavatory | |1 |
attic | |0.75 |
kitchen | |0.1 |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | |1 |
basement | | |
garage | | |
garden | |0.8 |
house2 |60 | |
upstairs | | |
bedrooms | | |
suite_1 | | |
suite_2 | | |
bedroom_3 | | |
bedroom_4 | | |
bathroom | | |
toilet | | |
attics | |0.6 |
groundfloor | | |
kitchen | | |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | | |
wet_room_&_toilet | | |
garage | | |
garden | |0.9 |
hot_tub_suite | |1 |
basement | | |
cellars | |1 |
wine_cellar | |1 |
cinema | |0.75 |
;Calculation:
The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.
'''The task is to''' calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.
;Extra Credit:
After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1-coverage for any node, by the product of the `powers` of its parent nodes from the top down to the node.
The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.
The pseudo code would be:
method delta_calculation(this, power):
sum_of_weights = sum(node.weight for node in children)
this.delta = (1 - this.coverage) * power
for node in self.children:
node.delta_calculation(power * node.weight / sum_of_weights)
return this.delta
Followed by a call to:
top.delta_calculation(power=1)
'''Note:''' to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
| '''Functional coverage tree'''
from itertools import chain, product
from functools import reduce
# main :: IO ()
def main():
'''Tabular outline serialisation of a parse tree
decorated with computations of:
1. Weighted coverage of each tree node.
2. Each node's share of the total project's
remaining work.
'''
columnWidths = [31, 9, 9, 9]
delimiter = '|'
reportLines = REPORT.splitlines()
columnTitles = init(columnNames(delimiter)(reportLines[0]))
# ------ SERIALISATION OF DECORATED PARSE TREE -------
print(titleLine(delimiter)(columnWidths)(
columnTitles + ['share of residue']
))
print(indentedLinesFromTree(' ', tabulation(columnWidths))(
# -------- TWO COMPUTATIONS BY TRAVERSAL ---------
withResidueShares(1.0)(
foldTree(weightedCoverage)(
# --- TREE FROM PARSE OF OUTLINE TEXT ----
fmapTree(
recordFromKeysDefaultsDelimiterAndLine(
columnTitles
)(
[str, float, float])([
'?', 1.0, 0.0
])(delimiter)
)(
forestFromIndentLevels(
indentLevelsFromLines(
reportLines[1:]
)
)[0]
)
)
)
))
# ---- WEIGHTED COVERAGE, AND SHARE OF TOTAL RESIDUE -----
# weightedCoverage :: Tree Dict ->
# [Tree Dict] -> Tree Dict
def weightedCoverage(x):
'''The weighted coverage of a tree node,
as a function of the weighted averages
of its children.
'''
def go(xs):
cws = [
(r['coverage'], r['weight']) for r
in [root(x) for x in xs]
]
totalWeight = reduce(lambda a, x: a + x[1], cws, 0)
return Node(dict(
x, **{
'coverage': round(reduce(
lambda a, cw: a + (cw[0] * cw[1]),
cws, x['coverage']
) / (totalWeight if 0 < totalWeight else 1), 5)
}
))(xs)
return go
# withResidueShares :: Float -> Tree Dict -> Tree Dict
def withResidueShares(shareOfTotal):
'''A Tree of dictionaries additionally decorated with each
node's proportion of the total project's outstanding work.
'''
def go(fraction, node):
[nodeRoot, nodeNest] = ap([root, nest])([node])
weights = [root(x)['weight'] for x in nodeNest]
siblingsTotal = sum(weights)
return Node(
insertDict('residual_share')(
round(fraction * (1 - nodeRoot['coverage']), 5)
)(nodeRoot)
)(
map(
go,
[fraction * (w / siblingsTotal) for w in weights],
nodeNest
)
)
return lambda tree: go(shareOfTotal, tree)
# ------------------ OUTLINE TABULATION ------------------
# tabulation :: [Int] -> String -> Dict -> String
def tabulation(columnWidths):
'''Indented string representation of a node
in a functional coverage tree.
'''
return lambda indent, dct: '| '.join(map(
lambda k, w: (
(indent if 10 < w else '') + str(dct.get(k, ''))
).ljust(w, ' '),
dct.keys(),
columnWidths
))
# titleLine :: String -> [Int] -> [String] -> String
def titleLine(delimiter):
'''A string consisting of a spaced and delimited
series of upper-case column titles.
'''
return lambda columnWidths: lambda ks: (
delimiter + ' '
).join(map(
lambda k, w: k.ljust(w, ' '),
[k.upper() for k in ks],
columnWidths
))
# ------------ GENERIC AND REUSABLE FUNCTIONS ------------
# Node :: a -> [Tree a] -> Tree a
def Node(v):
'''Constructor for a Tree node which connects a
value of some kind to a list of zero or
more child trees.
'''
return lambda xs: {'type': 'Tree', 'root': v, 'nest': xs}
# ap (<*>) :: [(a -> b)] -> [a] -> [b]
def ap(fs):
'''The application of each of a list of functions,
to each of a list of values.
'''
def go(xs):
return [
f(x) for (f, x)
in product(fs, xs)
]
return go
# columnNames :: String -> String -> [String]
def columnNames(delimiter):
'''A list of lower-case keys derived from
a header line and a delimiter character.
'''
return compose(
fmapList(compose(toLower, strip)),
splitOn(delimiter)
)
# compose :: ((a -> a), ...) -> (a -> a)
def compose(*fs):
'''Composition, from right to left,
of a series of functions.
'''
return lambda x: reduce(
lambda a, f: f(a),
fs[::-1], x
)
# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
'''A concatenated list over which a function has been mapped.
The list monad can be derived by using a function f which
wraps its output in a list,
(using an empty list to represent computational failure).
'''
def go(xs):
return chain.from_iterable(map(f, xs))
return go
# div :: Int -> Int -> Int
def div(x):
'''Integer division.'''
return lambda y: x // y
# first :: (a -> b) -> ((a, c) -> (b, c))
def first(f):
'''A simple function lifted to a function over a tuple,
with f applied only the first of two values.
'''
return lambda xy: (f(xy[0]), xy[1])
# flip :: (a -> b -> c) -> b -> a -> c
def flip(f):
'''The (curried or uncurried) function f with its
arguments reversed.
'''
return lambda a: lambda b: f(b)(a)
# fmapList :: (a -> b) -> [a] -> [b]
def fmapList(f):
'''fmap over a list.
f lifted to a function over a list.
'''
return lambda xs: [f(x) for x in xs]
# fmapTree :: (a -> b) -> Tree a -> Tree b
def fmapTree(f):
'''A new tree holding the results of
an application of f to each root in
the existing tree.
'''
def go(x):
return Node(
f(x['root'])
)([go(v) for v in x['nest']])
return go
# foldTree :: (a -> [b] -> b) -> Tree a -> b
def foldTree(f):
'''The catamorphism on trees. A summary
value defined by a depth-first fold.
'''
def go(node):
return f(root(node))([
go(x) for x in nest(node)
])
return go
# forestFromIndentLevels :: [(Int, a)] -> [Tree a]
def forestFromIndentLevels(tuples):
'''A list of trees derived from a list of values paired
with integers giving their levels of indentation.
'''
def go(xs):
if xs:
intIndent, v = xs[0]
firstTreeLines, rest = span(
lambda x: intIndent < x[0]
)(xs[1:])
return [Node(v)(go(firstTreeLines))] + go(rest)
else:
return []
return go(tuples)
# fst :: (a, b) -> a
def fst(tpl):
'''First member of a pair.'''
return tpl[0]
# indentLevelsFromLines :: [String] -> [(Int, String)]
def indentLevelsFromLines(xs):
'''Each input line stripped of leading
white space, and tupled with a preceding integer
giving its level of indentation from 0 upwards.
'''
indentTextPairs = list(map(
compose(first(len), span(isSpace)),
xs
))
indentUnit = min(concatMap(
lambda x: [x[0]] if x[0] else []
)(indentTextPairs))
return list(map(
first(flip(div)(indentUnit)),
indentTextPairs
))
# indentedLinesFromTree :: String -> (String -> a -> String) ->
# [Tree a] -> String
def indentedLinesFromTree(strTab, f):
'''An indented line rendering of a tree, in which
the function f stringifies a root value.
'''
def go(indent):
return lambda node: [f(indent, node['root'])] + list(
concatMap(
go(strTab + indent)
)(node['nest'])
)
return lambda tree: '\n'.join(go('')(tree))
# init :: [a] -> [a]
def init(xs):
'''A list containing all the elements
of xs except the last.
'''
return xs[:-1]
# insertDict :: String -> a -> Dict -> Dict
def insertDict(k):
'''A new dictionary updated with a (k, v) pair.'''
def go(v, dct):
return dict(dct, **{k: v})
return lambda v: lambda dct: go(v, dct)
# isSpace :: Char -> Bool
# isSpace :: String -> Bool
def isSpace(s):
'''True if s is not empty, and
contains only white space.
'''
return s.isspace()
# lt (<) :: Ord a => a -> a -> Bool
def lt(x):
'''True if x < y.'''
return lambda y: (x < y)
# nest :: Tree a -> [Tree a]
def nest(t):
'''Accessor function for children of tree node.'''
return t['nest'] if 'nest' in t else None
# recordFromKeysDefaultsAndLine :: String ->
# { name :: String, weight :: Float, completion :: Float }
def recordFromKeysDefaultsDelimiterAndLine(columnTitles):
'''A dictionary of key-value pairs, derived from a
delimited string, together with ordered lists of
key-names, types, default values, and a delimiter.
'''
return lambda ts: lambda vs: lambda delim: lambda s: dict(
map(
lambda k, t, v, x: (k, t(x) if x else v),
columnTitles, ts, vs,
map(strip, splitOn(delim)(s))
)
)
# root :: Tree a -> a
def root(t):
'''Accessor function for data of tree node.'''
return t['root'] if 'root' in t else None
# strip :: String -> String
def strip(s):
'''A copy of s without any leading or trailling
white space.
'''
return s.strip()
# span :: (a -> Bool) -> [a] -> ([a], [a])
def span(p):
'''The longest (possibly empty) prefix of xs
that contains only elements satisfying p,
tupled with the remainder of xs.
span p xs is equivalent to (takeWhile p xs, dropWhile p xs).
'''
def match(ab):
b = ab[1]
return not b or not p(b[0])
def f(ab):
a, b = ab
return a + [b[0]], b[1:]
def go(xs):
return until(match)(f)(([], xs))
return go
# splitOn :: String -> String -> [String]
def splitOn(pat):
'''A list of the strings delimited by
instances of a given pattern in s.
'''
return lambda xs: (
xs.split(pat) if isinstance(xs, str) else None
)
# toLower :: String -> String
def toLower(s):
'''String in lower case.'''
return s.lower()
# 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):
def g(x):
v = x
while not p(v):
v = f(v)
return v
return g
return go
# MAIN ----------------------------------------------------
if __name__ == '__main__':
REPORT = '''NAME_HIERARCHY |WEIGHT |COVERAGE |
cleaning | | |
house1 |40 | |
bedrooms | |0.25 |
bathrooms | | |
bathroom1 | |0.5 |
bathroom2 | | |
outside_lavatory | |1 |
attic | |0.75 |
kitchen | |0.1 |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | |1 |
basement | | |
garage | | |
garden | |0.8 |
house2 |60 | |
upstairs | | |
bedrooms | | |
suite_1 | | |
suite_2 | | |
bedroom_3 | | |
bedroom_4 | | |
bathroom | | |
toilet | | |
attics | |0.6 |
groundfloor | | |
kitchen | | |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | | |
wet_room_&_toilet | | |
garage | | |
garden | |0.9 |
hot_tub_suite | |1 |
basement | | |
cellars | |1 |
wine_cellar | |1 |
cinema | |0.75 |'''
main() |
Fusc sequence | Python | Definitions:
The '''fusc''' integer sequence is defined as:
::* fusc(0) = 0
::* fusc(1) = 1
::* for '''n'''>1, the '''n'''th term is defined as:
::::* if '''n''' is even; fusc(n) = fusc(n/2)
::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
;An observation:
:::::* fusc(A) = fusc(B)
where '''A''' is some non-negative integer expressed in binary, and
where '''B''' is the binary value of '''A''' reversed.
Fusc numbers are also known as:
::* fusc function (named by Dijkstra, 1982)
::* Stern's Diatomic series (although it starts with unity, not zero)
::* Stern-Brocot sequence (although it starts with unity, not zero)
;Task:
::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format.
::* show the fusc number (and its index) whose length is greater than any previous fusc number length.
::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.)
::* show all numbers with commas (if appropriate).
::* show all output here.
;Related task:
::* RosettaCode Stern-Brocot sequence
;Also see:
::* the MathWorld entry: Stern's Diatomic Series.
::* the OEIS entry: A2487.
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
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:
'''187''' is a '''gapful''' number because it is evenly divisible by the
number '''17''' which is formed by the first and last decimal digits
of '''187'''.
About 7.46% of positive integers are ''gapful''.
;Task:
:* Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
:* Show the first '''30''' gapful numbers
:* Show the first '''15''' gapful numbers >= '''1,000,000'''
:* Show the first '''10''' gapful numbers >= '''1,000,000,000'''
;Related tasks:
:* Harshad or Niven series.
:* palindromic gapful numbers.
:* largest number divisible by its digits.
;Also see:
:* The OEIS entry: A108343 gapful numbers.
:* numbersaplenty gapful numbers
| from itertools import islice, count
for start, n in [(100, 30), (1_000_000, 15), (1_000_000_000, 10)]:
print(f"\nFirst {n} gapful numbers from {start:_}")
print(list(islice(( x for x in count(start)
if (x % (int(str(x)[0]) * 10 + (x % 10)) == 0) )
, n))) |
Gauss-Jordan matrix inversion | Python | Invert matrix '''A''' using Gauss-Jordan method.
'''A''' being an '''n''' x '''n''' matrix.
| import numpy as np
from numpy.linalg import inv
a = np.array([[1., 2., 3.], [4., 1., 6.],[ 7., 8., 9.]])
ainv = inv(a)
print(a)
print(ainv)
|
Gaussian elimination | Python | Solve '''Ax=b''' using Gaussian elimination then backwards substitution.
'''A''' being an '''n''' by '''n''' matrix.
Also, '''x''' and '''b''' are '''n''' by '''1''' vectors.
To improve accuracy, please use partial pivoting and scaling.
;See also:
:* the Wikipedia entry: Gaussian elimination
| # The 'gauss' function takes two matrices, 'a' and 'b', with 'a' square, and it return the determinant of 'a' and a matrix 'x' such that a*x = b.
# If 'b' is the identity, then 'x' is the inverse of 'a'.
import copy
from fractions import Fraction
def gauss(a, b):
a = copy.deepcopy(a)
b = copy.deepcopy(b)
n = len(a)
p = len(b[0])
det = 1
for i in range(n - 1):
k = i
for j in range(i + 1, n):
if abs(a[j][i]) > abs(a[k][i]):
k = j
if k != i:
a[i], a[k] = a[k], a[i]
b[i], b[k] = b[k], b[i]
det = -det
for j in range(i + 1, n):
t = a[j][i]/a[i][i]
for k in range(i + 1, n):
a[j][k] -= t*a[i][k]
for k in range(p):
b[j][k] -= t*b[i][k]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
t = a[i][j]
for k in range(p):
b[i][k] -= t*b[j][k]
t = 1/a[i][i]
det *= a[i][i]
for j in range(p):
b[i][j] *= t
return det, b
def zeromat(p, q):
return [[0]*q for i in range(p)]
def matmul(a, b):
n, p = len(a), len(a[0])
p1, q = len(b), len(b[0])
if p != p1:
raise ValueError("Incompatible dimensions")
c = zeromat(n, q)
for i in range(n):
for j in range(q):
c[i][j] = sum(a[i][k]*b[k][j] for k in range(p))
return c
def mapmat(f, a):
return [list(map(f, v)) for v in a]
def ratmat(a):
return mapmat(Fraction, a)
# As an example, compute the determinant and inverse of 3x3 magic square
a = [[2, 9, 4], [7, 5, 3], [6, 1, 8]]
b = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
det, c = gauss(a, b)
det
-360.0
c
[[-0.10277777777777776, 0.18888888888888888, -0.019444444444444438],
[0.10555555555555554, 0.02222222222222223, -0.061111111111111116],
[0.0638888888888889, -0.14444444444444446, 0.14722222222222223]]
# Check product
matmul(a, c)
[[1.0, 0.0, 0.0], [5.551115123125783e-17, 1.0, 0.0],
[1.1102230246251565e-16, -2.220446049250313e-16, 1.0]]
# Same with fractions, so the result is exact
det, c = gauss(ratmat(a), ratmat(b))
det
Fraction(-360, 1)
c
[[Fraction(-37, 360), Fraction(17, 90), Fraction(-7, 360)],
[Fraction(19, 180), Fraction(1, 45), Fraction(-11, 180)],
[Fraction(23, 360), Fraction(-13, 90), Fraction(53, 360)]]
matmul(a, c)
[[Fraction(1, 1), Fraction(0, 1), Fraction(0, 1)],
[Fraction(0, 1), Fraction(1, 1), Fraction(0, 1)],
[Fraction(0, 1), Fraction(0, 1), Fraction(1, 1)]] |
Generate Chess960 starting position | Python | Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
* as in the standard chess game, all eight white pawns must be placed on the second rank.
* White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
** the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
** the King must be between two rooks (with any number of other pieces between them all)
* Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are '''960''' possible starting positions, thus the name of the variant.
;Task:
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.
| from random import choice
def random960():
start = ['R', 'K', 'R'] # Subsequent order unchanged by insertions.
#
for piece in ['Q', 'N', 'N']:
start.insert(choice(range(len(start)+1)), piece)
#
bishpos = choice(range(len(start)+1))
start.insert(bishpos, 'B')
start.insert(choice(range(bishpos + 1, len(start) + 1, 2)), 'B')
return start
return ''.join(start).upper()
print(random960()) |
Generate random chess position | Python | Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
:* there is one and only one king of each color (one black king and one white king);
:* the kings must not be placed on adjacent squares;
:* there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
:* including the kings, up to 32 pieces of either color can be placed.
:* There is no requirement for material balance between sides.
:* The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
:* it is white's turn.
:* It's assumed that both sides have lost castling rights and that there is no possibility for ''en passant'' (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
| import random
board = [[" " for x in range(8)] for y in range(8)]
piece_list = ["R", "N", "B", "Q", "P"]
def place_kings(brd):
while True:
rank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)
diff_list = [abs(rank_white - rank_black), abs(file_white - file_black)]
if sum(diff_list) > 2 or set(diff_list) == set([0, 2]):
brd[rank_white][file_white], brd[rank_black][file_black] = "K", "k"
break
def populate_board(brd, wp, bp):
for x in range(2):
if x == 0:
piece_amount = wp
pieces = piece_list
else:
piece_amount = bp
pieces = [s.lower() for s in piece_list]
while piece_amount != 0:
piece_rank, piece_file = random.randint(0, 7), random.randint(0, 7)
piece = random.choice(pieces)
if brd[piece_rank][piece_file] == " " and pawn_on_promotion_square(piece, piece_rank) == False:
brd[piece_rank][piece_file] = piece
piece_amount -= 1
def fen_from_board(brd):
fen = ""
for x in brd:
n = 0
for y in x:
if y == " ":
n += 1
else:
if n != 0:
fen += str(n)
fen += y
n = 0
if n != 0:
fen += str(n)
fen += "/" if fen.count("/") < 7 else ""
fen += " w - - 0 1\n"
return fen
def pawn_on_promotion_square(pc, pr):
if pc == "P" and pr == 0:
return True
elif pc == "p" and pr == 7:
return True
return False
def start():
piece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15)
place_kings(board)
populate_board(board, piece_amount_white, piece_amount_black)
print(fen_from_board(board))
for x in board:
print(x)
#entry point
start()
|
Generator/Exponential | Python | A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled "naturally".
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
;Task:
* Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
* Use it to create a generator of:
:::* Squares.
:::* Cubes.
* Create a new generator that filters all cubes from the generator of squares.
* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task ''requires'' the use of generators in the calculation of the result.
;Also see:
* Generator
| In Python, any function that contains a yield statement becomes a generator. The standard libraries itertools module provides the following functions used in the solution: [http://docs.python.org/library/itertools.html#itertools.count count], that will count up from zero; and [http://docs.python.org/library/itertools.html#itertools.islice islice], which will take a slice from an iterator/generator.
|
Generator/Exponential | Python 2.6+ and 3.x | A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled "naturally".
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
;Task:
* Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
* Use it to create a generator of:
:::* Squares.
:::* Cubes.
* Create a new generator that filters all cubes from the generator of squares.
* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task ''requires'' the use of generators in the calculation of the result.
;Also see:
* Generator
| from itertools import islice, count
def powers(m):
for n in count():
yield n ** m
def filtered(s1, s2):
v, f = next(s1), next(s2)
while True:
if v > f:
f = next(s2)
continue
elif v < f:
yield v
v = next(s1)
squares, cubes = powers(2), powers(3)
f = filtered(squares, cubes)
print(list(islice(f, 20, 30))) |
Generator/Exponential | Python 3.7 | A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled "naturally".
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
;Task:
* Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
* Use it to create a generator of:
:::* Squares.
:::* Cubes.
* Create a new generator that filters all cubes from the generator of squares.
* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task ''requires'' the use of generators in the calculation of the result.
;Also see:
* Generator
| '''Exponentials as generators'''
from itertools import count, islice
# powers :: Gen [Int]
def powers(n):
'''A non-finite succession of integers,
starting at zero,
raised to the nth power.'''
def f(x):
return pow(x, n)
return map(f, count(0))
# main :: IO ()
def main():
'''Taking the difference between two derived generators.'''
print(
take(10)(
drop(20)(
differenceGen(powers(2))(
powers(3)
)
)
)
)
# GENERIC -------------------------------------------------
# differenceGen :: Gen [a] -> Gen [a] -> Gen [a]
def differenceGen(ga):
'''All values of ga except any
already seen in gb.'''
def go(a, b):
stream = zip(a, b)
bs = set([])
while True:
xy = next(stream, None)
if None is not xy:
x, y = xy
bs.add(y)
if x not in bs:
yield x
else:
return
return lambda gb: go(ga, gb)
# drop :: Int -> [a] -> [a]
# drop :: Int -> String -> String
def drop(n):
'''The sublist of xs beginning at
(zero-based) index n.'''
def go(xs):
if isinstance(xs, list):
return xs[n:]
else:
take(n)(xs)
return xs
return lambda xs: go(xs)
# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.'''
return lambda xs: (
xs[0:n]
if isinstance(xs, list)
else list(islice(xs, n))
)
# MAIN ---
if __name__ == '__main__':
main() |
Get system command output | Python | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
;Related task
* Execute a system command
| >>> import subprocess
>>> returned_text = subprocess.check_output("dir", shell=True, universal_newlines=True)
>>> type(returned_text)
<class 'str'>
>>> print(returned_text)
Volume in drive C is Windows
Volume Serial Number is 44X7-73CE
Directory of C:\Python33
04/07/2013 06:40 <DIR> .
04/07/2013 06:40 <DIR> ..
27/05/2013 07:10 <DIR> DLLs
27/05/2013 07:10 <DIR> Doc
27/05/2013 07:10 <DIR> include
27/05/2013 07:10 <DIR> Lib
27/05/2013 07:10 <DIR> libs
16/05/2013 00:15 33,326 LICENSE.txt
15/05/2013 22:49 214,554 NEWS.txt
16/05/2013 00:03 26,624 python.exe
16/05/2013 00:03 27,136 pythonw.exe
15/05/2013 22:49 6,701 README.txt
27/05/2013 07:10 <DIR> tcl
27/05/2013 07:10 <DIR> Tools
16/05/2013 00:02 43,008 w9xpopen.exe
6 File(s) 351,349 bytes
9 Dir(s) 46,326,947,840 bytes free
>>> # Ref: https://docs.python.org/3/library/subprocess.html |
Giuga numbers | Python from FreeBASIC | Definition
A '''Giuga number''' is a composite number '''n''' which is such that each of its distinct prime factors
'''f''' divide (n/f - 1) exactly.
All known Giuga numbers are even though it is not known for certain that there are no odd examples.
;Example
30 is a Giuga number because its distinct prime factors are 2, 3 and 5 and:
* 30/2 - 1 = 14 is divisible by 2
* 30/3 - 1 = 9 is divisible by 3
* 30/5 - 1 = 5 is divisible by 5
;Task
Determine and show here the first four Giuga numbers.
;Stretch
Determine the fifth Giuga number and any more you have the patience for.
;References
* Wikipedia: Giuga number
* OEIS:A007850 - Giuga numbers
| #!/usr/bin/python
from math import sqrt
def isGiuga(m):
n = m
f = 2
l = sqrt(n)
while True:
if n % f == 0:
if ((m / f) - 1) % f != 0:
return False
n /= f
if f > n:
return True
else:
f += 1
if f > l:
return False
if __name__ == '__main__':
n = 3
c = 0
print("The first 4 Giuga numbers are: ")
while c < 4:
if isGiuga(n):
c += 1
print(n)
n += 1 |
Globally replace text in several files | Python | Replace every occurring instance of a piece of text in a group of text files with another one.
For this task we want to replace the text "'''Goodbye London!'''" with "'''Hello New York!'''" for a list of files.
| import fileinput
for line in fileinput.input(inplace=True):
print(line.replace('Goodbye London!', 'Hello New York!'), end='')
|
Graph colouring | Python | A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected. Only unconnected nodes ''need'' a separate
description.
For example,
0-1 1-2 2-0 3
Describes the following graph. Note that node 3 has no neighbours
;Example graph:
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
A useful internal datastructure for a graph and for later graph algorithms is
as a mapping between each node and the set/list of its neighbours.
In the above example:
0 maps-to 1 and 2
1 maps to 2 and 0
2 maps-to 1 and 0
3 maps-to
;Graph colouring task:
Colour the vertices of a given graph so that no edge is between verticies of
the same colour.
* Integers may be used to denote different colours.
* Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is '''not''' a requirement).
* Show for each edge, the colours assigned on each vertex.
* Show the total number of nodes, edges, and colours used for each graph.
;Use the following graphs:
;Ex1:
0-1 1-2 2-0 3
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
;Ex2:
The wp articles left-side graph
1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7
+----------------------------------+
| |
| +---+ |
| +-----------------| 3 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 6 | --- | 4 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 7 | --- | 2 | --- | 5 | -+
| +---+ +---+ +---+
| |
+-------------------+
;Ex3:
The wp articles right-side graph which is the same graph as Ex2, but with
different node orderings and namings.
1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6
+----------------------------------+
| |
| +---+ |
| +-----------------| 5 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 4 | --- | 7 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 6 | --- | 3 | --- | 2 | -+
| +---+ +---+ +---+
| |
+-------------------+
;Ex4:
This is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x.
This might alter the node order used in the greedy algorithm leading to differing numbers of colours.
1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7
+-------------------------------------------------+
| |
| |
+-------------------+---------+ |
| | | |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| | | | | |
+---------+-----------------------------+---------+ | |
| | | |
| | | |
+-----------------------------+-------------------+ |
| |
| |
+-----------------------------+
;References:
* Greedy coloring Wikipedia.
* Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm by Priyank Jain.
| import re
from collections import defaultdict
from itertools import count
connection_re = r"""
(?: (?P<N1>\d+) - (?P<N2>\d+) | (?P<N>\d+) (?!\s*-))
"""
class Graph:
def __init__(self, name, connections):
self.name = name
self.connections = connections
g = self.graph = defaultdict(list) # maps vertex to direct connections
matches = re.finditer(connection_re, connections,
re.MULTILINE | re.VERBOSE)
for match in matches:
n1, n2, n = match.groups()
if n:
g[n] += []
else:
g[n1].append(n2) # Each the neighbour of the other
g[n2].append(n1)
def greedy_colour(self, order=None):
"Greedy colourisation algo."
if order is None:
order = self.graph # Choose something
colour = self.colour = {}
neighbours = self.graph
for node in order:
used_neighbour_colours = (colour[nbr] for nbr in neighbours[node]
if nbr in colour)
colour[node] = first_avail_int(used_neighbour_colours)
self.pp_colours()
return colour
def pp_colours(self):
print(f"\n{self.name}")
c = self.colour
e = canonical_edges = set()
for n1, neighbours in sorted(self.graph.items()):
if neighbours:
for n2 in neighbours:
edge = tuple(sorted([n1, n2]))
if edge not in canonical_edges:
print(f" {n1}-{n2}: Colour: {c[n1]}, {c[n2]}")
canonical_edges.add(edge)
else:
print(f" {n1}: Colour: {c[n1]}")
lc = len(set(c.values()))
print(f" #Nodes: {len(c)}\n #Edges: {len(e)}\n #Colours: {lc}")
def first_avail_int(data):
"return lowest int 0... not in data"
d = set(data)
for i in count():
if i not in d:
return i
if __name__ == '__main__':
for name, connections in [
('Ex1', "0-1 1-2 2-0 3"),
('Ex2', "1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7"),
('Ex3', "1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6"),
('Ex4', "1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7"),
]:
g = Graph(name, connections)
g.greedy_colour() |
Gray code | Python | Karnaugh maps in order from left to right or top to bottom.
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
;Reference
* Converting Between Gray and Binary Codes. It includes step-by-step animations.
| def gray_encode(n):
return n ^ n >> 1
def gray_decode(n):
m = n >> 1
while m:
n ^= m
m >>= 1
return n
if __name__ == '__main__':
print("DEC, BIN => GRAY => DEC")
for i in range(32):
gray = gray_encode(i)
dec = gray_decode(gray)
print(f" {i:>2d}, {i:>05b} => {gray:>05b} => {dec:>2d}") |
Greatest subsequential sum | Python | Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.
| f = maxsumit
assert f([]) == []
assert f([-1]) == []
assert f([0]) == []
assert f([1]) == [1]
assert f([1, 0]) == [1]
assert f([0, 1]) == [0, 1]
assert f([0, 1, 0]) == [0, 1]
assert f([2]) == [2]
assert f([2, -1]) == [2]
assert f([-1, 2]) == [2]
assert f([-1, 2, -1]) == [2]
assert f([2, -1, 3]) == [2, -1, 3]
assert f([2, -1, 3, -1]) == [2, -1, 3]
assert f([-1, 2, -1, 3]) == [2, -1, 3]
assert f([-1, 2, -1, 3, -1]) == [2, -1, 3]
assert f([-1, 1, 2, -5, -6]) == [1,2] |
Greatest subsequential sum | Python 3.7 | Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.
| '''Greatest subsequential sum'''
from functools import (reduce)
# maxSubseq :: [Int] -> [Int] -> (Int, [Int])
def maxSubseq(xs):
'''Subsequence of xs with the maximum sum'''
def go(ab, x):
(m1, m2) = ab[0]
hi = max((0, []), (m1 + x, m2 + [x]))
return (hi, max(ab[1], hi))
return reduce(go, xs, ((0, []), (0, [])))[1]
# TEST -----------------------------------------------------------
print(
maxSubseq(
[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
)
) |
Greedy algorithm for Egyptian fractions | Python | An Egyptian fraction is the sum of distinct unit fractions such as:
:::: \tfrac{1}{2} + \tfrac{1}{3} + \tfrac{1}{16} \,(= \tfrac{43}{48})
Each fraction in the expression has a numerator equal to '''1''' (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions).
Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction \tfrac{x}{y} to be represented by repeatedly performing the replacement
:::: \frac{x}{y} = \frac{1}{\lceil y/x\rceil} + \frac{(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil}
(simplifying the 2nd term in this replacement as necessary, and where \lceil x \rceil is the ''ceiling'' function).
For this task, Proper and improper fractions must be able to be expressed.
Proper fractions are of the form \tfrac{a}{b} where a and b are positive integers, such that a < b, and
improper fractions are of the form \tfrac{a}{b} where a and b are positive integers, such that ''a'' >= ''b''.
(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)
For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [''n''].
;Task requirements:
* show the Egyptian fractions for: \tfrac{43}{48} and \tfrac{5}{121} and \tfrac{2014}{59}
* for all proper fractions, \tfrac{a}{b} where a and b are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:
::* the largest number of terms,
::* the largest denominator.
* for all one-, two-, and three-digit integers, find and show (as above). {extra credit}
;Also see:
* Wolfram MathWorld(tm) entry: Egyptian fraction
| from fractions import Fraction
from math import ceil
class Fr(Fraction):
def __repr__(self):
return '%s/%s' % (self.numerator, self.denominator)
def ef(fr):
ans = []
if fr >= 1:
if fr.denominator == 1:
return [[int(fr)], Fr(0, 1)]
intfr = int(fr)
ans, fr = [[intfr]], fr - intfr
x, y = fr.numerator, fr.denominator
while x != 1:
ans.append(Fr(1, ceil(1/fr)))
fr = Fr(-y % x, y* ceil(1/fr))
x, y = fr.numerator, fr.denominator
ans.append(fr)
return ans
if __name__ == '__main__':
for fr in [Fr(43, 48), Fr(5, 121), Fr(2014, 59)]:
print('%r ─► %s' % (fr, ' '.join(str(x) for x in ef(fr))))
lenmax = denommax = (0, None)
for fr in set(Fr(a, b) for a in range(1,100) for b in range(1, 100)):
e = ef(fr)
#assert sum((f[0] if type(f) is list else f) for f in e) == fr, 'Whoops!'
elen, edenom = len(e), e[-1].denominator
if elen > lenmax[0]:
lenmax = (elen, fr, e)
if edenom > denommax[0]:
denommax = (edenom, fr, e)
print('Term max is %r with %i terms' % (lenmax[1], lenmax[0]))
dstr = str(denommax[0])
print('Denominator max is %r with %i digits %s...%s' %
(denommax[1], len(dstr), dstr[:5], dstr[-5:])) |
Greedy algorithm for Egyptian fractions | Python 3.7 | An Egyptian fraction is the sum of distinct unit fractions such as:
:::: \tfrac{1}{2} + \tfrac{1}{3} + \tfrac{1}{16} \,(= \tfrac{43}{48})
Each fraction in the expression has a numerator equal to '''1''' (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions).
Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction \tfrac{x}{y} to be represented by repeatedly performing the replacement
:::: \frac{x}{y} = \frac{1}{\lceil y/x\rceil} + \frac{(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil}
(simplifying the 2nd term in this replacement as necessary, and where \lceil x \rceil is the ''ceiling'' function).
For this task, Proper and improper fractions must be able to be expressed.
Proper fractions are of the form \tfrac{a}{b} where a and b are positive integers, such that a < b, and
improper fractions are of the form \tfrac{a}{b} where a and b are positive integers, such that ''a'' >= ''b''.
(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)
For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [''n''].
;Task requirements:
* show the Egyptian fractions for: \tfrac{43}{48} and \tfrac{5}{121} and \tfrac{2014}{59}
* for all proper fractions, \tfrac{a}{b} where a and b are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:
::* the largest number of terms,
::* the largest denominator.
* for all one-, two-, and three-digit integers, find and show (as above). {extra credit}
;Also see:
* Wolfram MathWorld(tm) entry: Egyptian fraction
| '''Egyptian fractions'''
from fractions import Fraction
from functools import reduce
from operator import neg
# eqyptianFraction :: Ratio Int -> Ratio Int
def eqyptianFraction(nd):
'''The rational number nd as a sum
of the series of unit fractions
obtained by application of the
greedy algorithm.'''
def go(x):
n, d = x.numerator, x.denominator
r = 1 + d // n if n else None
return Just((0, x) if 1 == n else (
(fr(n % d, d), fr(n // d, 1)) if n > d else (
fr(-d % n, d * r), fr(1, r)
)
)) if n else Nothing()
fr = Fraction
f = unfoldr(go)
return list(map(neg, f(-nd))) if 0 > nd else f(nd)
# TESTS ---------------------------------------------------
# maxEqyptianFraction :: Int -> (Ratio Int -> a)
# -> (Ratio Int, a)
def maxEqyptianFraction(nDigits):
'''An Egyptian Fraction, representing a
proper fraction with numerators and
denominators of up to n digits each,
which returns a maximal value for the
supplied function f.'''
# maxVals :: ([Ratio Int], a) -> (Ratio Int, a)
# -> ([Ratio Int], a)
def maxima(xsv, ndfx):
xs, v = xsv
nd, fx = ndfx
return ([nd], fx) if fx > v else (
xs + [nd], v
) if fx == v and nd not in xs else xsv
# go :: (Ratio Int -> a) -> ([Ratio Int], a)
def go(f):
iLast = int(nDigits * '9')
fs, mx = reduce(
maxima, [
(nd, f(eqyptianFraction(nd))) for nd in [
Fraction(n, d)
for n in enumFromTo(1)(iLast)
for d in enumFromTo(1 + n)(iLast)
]
],
([], 0)
)
return f.__name__ + ' -> [' + ', '.join(
map(str, fs)
) + '] -> ' + str(mx)
return lambda f: go(f)
# main :: IO ()
def main():
'''Tests'''
ef = eqyptianFraction
fr = Fraction
print('Three values as Eqyptian fractions:')
print('\n'.join([
str(fr(*nd)) + ' -> ' + ' + '.join(map(str, ef(fr(*nd))))
for nd in [(43, 48), (5, 121), (2014, 59)]
]))
# maxDenominator :: [Ratio Int] -> Int
def maxDenominator(ef):
return max(map(lambda nd: nd.denominator, ef))
# maxTermCount :: [Ratio Int] -> Int
def maxTermCount(ef):
return len(ef)
for i in [1, 2, 3]:
print(
'\nMaxima for proper fractions with up to ' + (
str(i) + ' digit(s):'
)
)
for f in [maxTermCount, maxDenominator]:
print(maxEqyptianFraction(i)(f))
# GENERIC -------------------------------------------------
# Just :: a -> Maybe a
def Just(x):
'''Constructor for an inhabited Maybe (option type) value.'''
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
# Nothing :: Maybe a
def Nothing():
'''Constructor for an empty Maybe (option type) value.'''
return {'type': 'Maybe', 'Nothing': True}
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
# unfoldr :: (b -> Maybe (b, a)) -> 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(xr):
mb = f(xr[0])
if mb.get('Nothing'):
return []
else:
y, r = mb.get('Just')
return [r] + go((y, r))
return lambda x: go((x, x))
# MAIN ---
if __name__ == '__main__':
main() |
Hailstone sequence | Python | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
* If n is '''1''' then the sequence ends.
* If n is '''even''' then the next n of the sequence = n/2
* If n is '''odd''' then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
:::* hailstone sequence, hailstone numbers
:::* 3x + 2 mapping, 3n + 1 problem
:::* Collatz sequence
:::* Hasse's algorithm
:::* Kakutani's problem
:::* Syracuse algorithm, Syracuse problem
:::* Thwaites conjecture
:::* Ulam's problem
The hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
;Task:
# Create a routine to generate the hailstone sequence for a number.
# Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
# Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!)
;See also:
* xkcd (humourous).
* The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
* The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
| def hailstone(n):
seq = [n]
while n > 1:
n = 3 * n + 1 if n & 1 else n // 2
seq.append(n)
return seq
if __name__ == '__main__':
h = hailstone(27)
assert (len(h) == 112
and h[:4] == [27, 82, 41, 124]
and h[-4:] == [8, 4, 2, 1])
max_length, n = max((len(hailstone(i)), i) for i in range(1, 100_000))
print(f"Maximum length {max_length} was found for hailstone({n}) "
f"for numbers <100,000") |
Hailstone sequence | Python 3.7 | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
* If n is '''1''' then the sequence ends.
* If n is '''even''' then the next n of the sequence = n/2
* If n is '''odd''' then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
:::* hailstone sequence, hailstone numbers
:::* 3x + 2 mapping, 3n + 1 problem
:::* Collatz sequence
:::* Hasse's algorithm
:::* Kakutani's problem
:::* Syracuse algorithm, Syracuse problem
:::* Thwaites conjecture
:::* Ulam's problem
The hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
;Task:
# Create a routine to generate the hailstone sequence for a number.
# Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
# Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!)
;See also:
* xkcd (humourous).
* The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
* The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
| '''Hailstone sequences'''
from itertools import (islice, takewhile)
# hailstone :: Int -> [Int]
def hailstone(x):
'''Hailstone sequence starting with x.'''
def p(n):
return 1 != n
return list(takewhile(p, iterate(collatz)(x))) + [1]
# collatz :: Int -> Int
def collatz(n):
'''Next integer in the hailstone sequence.'''
return 3 * n + 1 if 1 & n else n // 2
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Tests.'''
n = 27
xs = hailstone(n)
print(unlines([
f'The hailstone sequence for {n} has {len(xs)} elements,',
f'starting with {take(4)(xs)},',
f'and ending with {drop(len(xs) - 4)(xs)}.\n'
]))
(a, b) = (1, 99999)
(i, x) = max(
enumerate(
map(compose(len)(hailstone), enumFromTo(a)(b))
),
key=snd
)
print(unlines([
f'The number in the range {a}..{b} '
f'which produces the longest sequence is {1 + i},',
f'generating a hailstone sequence of {x} integers.'
]))
# ----------------------- GENERIC ------------------------
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Function composition.'''
return lambda f: lambda x: g(f(x))
# drop :: Int -> [a] -> [a]
# drop :: Int -> String -> String
def drop(n):
'''The sublist of xs beginning at
(zero-based) index n.
'''
def go(xs):
if isinstance(xs, (list, tuple, str)):
return xs[n:]
else:
take(n)(xs)
return xs
return go
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: range(m, 1 + n)
# 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
# snd :: (a, b) -> b
def snd(tpl):
'''Second component of a tuple.'''
return tpl[1]
# 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
# unlines :: [String] -> String
def unlines(xs):
'''A single newline-delimited string derived
from a list of strings.'''
return '\n'.join(xs)
if __name__ == '__main__':
main() |
Harmonic series | Python | {{Wikipedia|Harmonic number}}
In mathematics, the '''n-th''' harmonic number is the sum of the reciprocals of the first '''n''' natural numbers:
'''H''n'' = 1 + 1/2 + 1/3 + ... + 1/n'''
The series of harmonic numbers thus obtained is often loosely referred to as the harmonic series.
Harmonic numbers are closely related to the Euler-Mascheroni constant.
The harmonic series is divergent, albeit quite slowly, and grows toward infinity.
;Task
* Write a function (routine, procedure, whatever it may be called in your language) to generate harmonic numbers.
* Use that procedure to show the values of the first 20 harmonic numbers.
* Find and show the position in the series of the first value greater than the integers 1 through 5
;Stretch
* Find and show the position in the series of the first value greater than the integers 6 through 10
;Related
* [[Egyptian fractions]]
| from fractions import Fraction
def harmonic_series():
n, h = Fraction(1), Fraction(1)
while True:
yield h
h += 1 / (n + 1)
n += 1
if __name__ == '__main__':
from itertools import islice
for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)):
print(n, '/', d) |
Harshad or Niven series | Python | The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits.
For example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder.
Assume that the series is defined as the numbers in increasing order.
;Task:
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.
Use it to:
::* list the first '''20''' members of the sequence, and
::* list the first Harshad number greater than '''1000'''.
Show your output here.
;Related task
:* Increasing gaps between consecutive Niven numbers
;See also
* OEIS: A005349
| >>> import itertools
>>> def harshad():
for n in itertools.count(1):
if n % sum(int(ch) for ch in str(n)) == 0:
yield n
>>> list(itertools.islice(harshad(), 0, 20))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42]
>>> for n in harshad():
if n > 1000:
print(n)
break
1002
>>> |
Harshad or Niven series | Python 3.7 | The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits.
For example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder.
Assume that the series is defined as the numbers in increasing order.
;Task:
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.
Use it to:
::* list the first '''20''' members of the sequence, and
::* list the first Harshad number greater than '''1000'''.
Show your output here.
;Related task
:* Increasing gaps between consecutive Niven numbers
;See also
* OEIS: A005349
| '''Harshad or Niven series'''
from itertools import count, dropwhile, islice
# harshads :: () -> [Int]
def harshads():
'''Harshad series'''
return (
x for x in count(1)
if 0 == x % digitSum(x)
)
# digitSum :: Int -> Int
def digitSum(n):
'''Sum of the decimal digits of n.'''
def go(x):
return None if 0 == x else divmod(x, 10)
return sum(unfoldl(go)(n))
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''First 20, and first above 1000.'''
def firstTwenty(xs):
return take(20)(xs)
def firstAbove1000(xs):
return take(1)(
dropwhile(lambda x: 1000 >= x, xs)
)
print(
fTable(__doc__ + ':\n')(
lambda x: x.__name__
)(showList)(lambda f: f(harshads()))([
firstTwenty,
firstAbove1000
])
)
# ----------------------- GENERIC ------------------------
# 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))
)
# unfoldl :: (b -> Maybe (b, a)) -> b -> [a]
def unfoldl(f):
'''A lazy (generator) list unfolded from a seed value
by repeated application of f until no residue remains.
Dual to fold/reduce.
f returns either None or just (residue, value).
For a strict output list, wrap the result with list()
'''
def go(v):
residueValue = f(v)
while residueValue:
yield residueValue[1]
residueValue = f(residueValue[0])
return go
# ----------------------- DISPLAY ------------------------
# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
'''Heading -> x display function ->
fx display function -> f -> xs -> tabular string.
'''
def gox(xShow):
def gofx(fxShow):
def gof(f):
def goxs(xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
def arrowed(x, y):
return y.rjust(w, ' ') + ' -> ' + (
fxShow(f(x))
)
return s + '\n' + '\n'.join(
map(arrowed, xs, ys)
)
return goxs
return gof
return gofx
return gox
# showList :: [a] -> String
def showList(xs):
'''Stringification of a list.'''
return '[' + ','.join(repr(x) for x in xs) + ']'
# MAIN ---
if __name__ == '__main__':
main() |
Hash join | Python | {| class="wikitable"
|-
! Input
! Output
|-
|
{| style="border:none; border-collapse:collapse;"
|-
| style="border:none" | ''A'' =
| style="border:none" |
{| class="wikitable"
|-
! Age !! Name
|-
| 27 || Jonah
|-
| 18 || Alan
|-
| 28 || Glory
|-
| 18 || Popeye
|-
| 28 || Alan
|}
| style="border:none; padding-left:1.5em;" rowspan="2" |
| style="border:none" | ''B'' =
| style="border:none" |
{| class="wikitable"
|-
! Character !! Nemesis
|-
| Jonah || Whales
|-
| Jonah || Spiders
|-
| Alan || Ghosts
|-
| Alan || Zombies
|-
| Glory || Buffy
|}
|-
| style="border:none" | ''jA'' =
| style="border:none" | Name (i.e. column 1)
| style="border:none" | ''jB'' =
| style="border:none" | Character (i.e. column 0)
|}
|
{| class="wikitable" style="margin-left:1em"
|-
! A.Age !! A.Name !! B.Character !! B.Nemesis
|-
| 27 || Jonah || Jonah || Whales
|-
| 27 || Jonah || Jonah || Spiders
|-
| 18 || Alan || Alan || Ghosts
|-
| 18 || Alan || Alan || Zombies
|-
| 28 || Glory || Glory || Buffy
|-
| 28 || Alan || Alan || Ghosts
|-
| 28 || Alan || Alan || Zombies
|}
|}
The order of the rows in the output table is not significant.
If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
| from collections import defaultdict
def hashJoin(table1, index1, table2, index2):
h = defaultdict(list)
# hash phase
for s in table1:
h[s[index1]].append(s)
# join phase
return [(s, r) for r in table2 for s in h[r[index2]]]
table1 = [(27, "Jonah"),
(18, "Alan"),
(28, "Glory"),
(18, "Popeye"),
(28, "Alan")]
table2 = [("Jonah", "Whales"),
("Jonah", "Spiders"),
("Alan", "Ghosts"),
("Alan", "Zombies"),
("Glory", "Buffy")]
for row in hashJoin(table1, 1, table2, 0):
print(row) |
Haversine formula | Python | {{Wikipedia}}
The '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical "triangles".
;Task:
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
* Nashville International Airport (BNA) in Nashville, TN, USA, which is:
'''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and-
* Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
'''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' 1.0621333 km and .001" .00177 km,
practical precision required is certainly no greater than about
.0000001----i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
| from math import radians, sin, cos, sqrt, asin
def haversine(lat1, lon1, lat2, lon2):
R = 6372.8 # Earth radius in kilometers
dLat = radians(lat2 - lat1)
dLon = radians(lon2 - lon1)
lat1 = radians(lat1)
lat2 = radians(lat2)
a = sin(dLat / 2)**2 + cos(lat1) * cos(lat2) * sin(dLon / 2)**2
c = 2 * asin(sqrt(a))
return R * c
>>> haversine(36.12, -86.67, 33.94, -118.40)
2887.2599506071106
>>> |
Hello world/Line printer | Python | Cause a line printer attached to the computer to print a line containing the message: Hello World!
;Note:
A line printer is not the same as standard output.
A line printer was an older-style printer which prints one line at a time to a continuous ream of paper.
With some systems, a line printer can be any device attached to an appropriate port (such as a parallel port).
| lp = open("/dev/lp0","w")
lp.write("Hello World!\n")
lp.close() |
Here document | Python | A ''here document'' (or "heredoc") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text.
Depending on the language being used, a ''here document'' is constructed using a command followed by "<<" (or some other symbol) followed by a token string.
The text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the text block.
;Task:
Demonstrate the use of ''here documents'' within the language.
;Related task:
* [[Documentation]]
| print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""") |
Heronian triangles | Python | Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by:
:::: A = \sqrt{s(s-a)(s-b)(s-c)},
where ''s'' is half the perimeter of the triangle; that is,
:::: s=\frac{a+b+c}{2}.
'''Heronian triangles'''
are triangles whose sides ''and area'' are all integers.
: An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12''').
Note that any triangle whose sides are all an integer multiple of '''3, 4, 5'''; such as '''6, 8, 10,''' will also be a Heronian triangle.
Define a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor
of all three sides is '''1''' (unity).
This will exclude, for example, triangle '''6, 8, 10.'''
;Task:
# Create a named function/method/procedure/... that implements Hero's formula.
# Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200.
# Show the count of how many triangles are found.
# Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths
# Show the first ten ordered triangles in a table of sides, perimeter, and area.
# Show a similar ordered table for those triangles with area = 210
Show all output here.
'''Note''': when generating triangles it may help to restrict a <= b <= c
| from __future__ import division, print_function
from math import gcd, sqrt
def hero(a, b, c):
s = (a + b + c) / 2
a2 = s * (s - a) * (s - b) * (s - c)
return sqrt(a2) if a2 > 0 else 0
def is_heronian(a, b, c):
a = hero(a, b, c)
return a > 0 and a.is_integer()
def gcd3(x, y, z):
return gcd(gcd(x, y), z)
if __name__ == '__main__':
MAXSIDE = 200
N = 1 + MAXSIDE
h = [(x, y, z)
for x in range(1, N)
for y in range(x, N)
for z in range(y, N) if (x + y > z) and
1 == gcd3(x, y, z) and
is_heronian(x, y, z)]
# By increasing area, perimeter, then sides
h.sort(key=lambda x: (hero(*x), sum(x), x[::-1]))
print(
'Primitive Heronian triangles with sides up to %i:' % MAXSIDE, len(h)
)
print('\nFirst ten when ordered by increasing area, then perimeter,',
'then maximum sides:')
print('\n'.join(' %14r perim: %3i area: %i'
% (sides, sum(sides), hero(*sides)) for sides in h[:10]))
print('\nAll with area 210 subject to the previous ordering:')
print('\n'.join(' %14r perim: %3i area: %i'
% (sides, sum(sides), hero(*sides)) for sides in h
if hero(*sides) == 210))
|
Hex words | Python | Definition
For the purposes of this task a '''hex word''' means a word which (in lower case form) consists entirely of the letters '''a, b, c, d, e''' and '''f'''.
;Task
Using unixdict.txt, find all hex words with '''4''' letters or more.
Convert each such word to its decimal equivalent and compute its base 10 digital root.
Display all three in increasing order of digital root and show the total count of such words.
Keeping only words which contain at least '''4''' distinct letters, display the same statistics but in decreasing order of decimal equivalent together with their total count.
| def digroot(n):
while n > 9:
n = sum([int(d) for d in str(n)])
return n
with open('unixdict.txt') as f:
lines = [w.strip() for w in f.readlines()]
words = [w for w in lines if len(w) >= 4 and all(c in 'abcdef' for c in w)]
results = [[w, int(w, 16)] for w in words]
for a in results:
a.append(digroot(a[1]))
print(f"Hex words in unixdict.txt:\nRoot Word Base 10\n", "-"*22)
for a in sorted(results, key=lambda x:x[2]):
print(f"{a[2]} {a[0]:6}{a[1]:10}")
print("Total count of these words:", len(results))
print("\nHex words with > 3 distinct letters:\nRoot Word Base 10\n", "-"*22)
results = [a for a in results if len(set(str(a[0]))) > 3]
for a in sorted(results, key=lambda x:x[2]):
print(f"{a[2]} {a[0]:6}{a[1]:10}")
print("Total count of those words:", len(results))
|
Hickerson series of almost integers | Python | The following function, due to D. Hickerson, is said to generate "Almost integers" by the
"Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered '''51'''.)
The function is: h(n) = {\operatorname{n}!\over2(\ln{2})^{n+1}}
It is said to produce "almost integers" for '''n''' between '''1''' and '''17'''.
The purpose of the task is to verify this assertion.
Assume that an "almost integer" has '''either a nine or a zero as its first digit after the decimal point''' of its decimal string representation
;Task:
Calculate all values of the function checking and stating which are "almost integers".
Note: Use extended/arbitrary precision numbers in your calculation if necessary to ensure you have adequate precision of results as for example:
h(18) = 3385534663256845326.39...
| from decimal import Decimal
import math
def h(n):
'Simple, reduced precision calculation'
return math.factorial(n) / (2 * math.log(2) ** (n + 1))
def h2(n):
'Extended precision Hickerson function'
return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))
for n in range(18):
x = h2(n)
norm = str(x.normalize())
almostinteger = (' Nearly integer'
if 'E' not in norm and ('.0' in norm or '.9' in norm)
else ' NOT nearly integer!')
print('n:%2i h:%s%s' % (n, norm, almostinteger)) |
History variables | Python | ''Storing the history of objects in a program is a common task.
Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.''
''History variables are variables in a programming language which store not only their current value, but also the values they have contained in the past. Some existing languages do provide support for history variables. However these languages typically have many limits and restrictions on use of history variables.
''
"History Variables:
The Semantics, Formal Correctness, and Implementation of History Variables
in an Imperative Programming Language" by Mallon and Takaoka
Concept also discussed on LtU and Patents.com.
;Task:
Demonstrate History variable support:
* enable history variable support (if needed)
* define a history variable
* assign three values
* non-destructively display the history
* recall the three values.
For extra points, if the language of choice does not support history variables,
demonstrate how this might be implemented.
| import sys
HIST = {}
def trace(frame, event, arg):
for name,val in frame.f_locals.items():
if name not in HIST:
HIST[name] = []
else:
if HIST[name][-1] is val:
continue
HIST[name].append(val)
return trace
def undo(name):
HIST[name].pop(-1)
return HIST[name][-1]
def main():
a = 10
a = 20
for i in range(5):
c = i
print "c:", c, "-> undo x3 ->",
c = undo('c')
c = undo('c')
c = undo('c')
print c
print 'HIST:', HIST
sys.settrace(trace)
main() |
Hofstadter-Conway $10,000 sequence | Python | The definition of the sequence is colloquially described as:
* Starting with the list [1,1],
* Take the last number in the list so far: 1, I'll call it x.
* Count forward x places from the beginning of the list to find the first number to add (1)
* Count backward x places from the end of the list to find the second number to add (1)
* Add the two indexed numbers from the list and the result becomes the next number in the list (1+1)
* This would then produce [1,1,2] where 2 is the third element of the sequence.
Note that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''.
A less wordy description of the sequence is:
a(1)=a(2)=1
a(n)=a(a(n-1))+a(n-a(n-1))
The sequence begins:
1, 1, 2, 2, 3, 4, 4, 4, 5, ...
Interesting features of the sequence are that:
* a(n)/n tends to 0.5 as n grows towards infinity.
* a(n)/n where n is a power of 2 is 0.5
* For n>4 the maximal value of a(n)/n between successive powers of 2 decreases.
a(n) / n for n in 1..256
The sequence is so named because John Conway offered a prize of $10,000 to the first person who could
find the first position, p in the sequence where
|a(n)/n| < 0.55 for all n > p
It was later found that Hofstadter had also done prior work on the sequence.
The 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of n (which is much smaller than the 3,173,375,556 quoted in the NYT article).
;Task:
# Create a routine to generate members of the Hofstadter-Conway $10,000 sequence.
# Use it to show the maxima of a(n)/n between successive powers of two up to 2**20
# As a stretch goal: compute the value of n that would have won the prize and confirm it is true for n up to 2**20
;Also see:
* Conways Challenge Sequence, Mallows' own account.
* Mathworld Article.
| from __future__ import division
def maxandmallows(nmaxpower2):
nmax = 2**nmaxpower2
mx = (0.5, 2)
mxpow2 = []
mallows = None
# Hofstadter-Conway sequence starts at hc[1],
# hc[0] is not part of the series.
hc = [None, 1, 1]
for n in range(2, nmax + 1):
ratio = hc[n] / n
if ratio > mx[0]:
mx = (ratio, n)
if ratio >= 0.55:
mallows = n
if ratio == 0.5:
print("In the region %7i < n <= %7i: max a(n)/n = %6.4f at n = %i" %
(n//2, n, mx[0], mx[1]))
mxpow2.append(mx[0])
mx = (ratio, n)
hc.append(hc[hc[n]] + hc[-hc[n]])
return hc, mallows if mxpow2 and mxpow2[-1] < 0.55 and n > 4 else None
if __name__ == '__main__':
hc, mallows = maxandmallows(20)
if mallows:
print("\nYou too might have won $1000 with the mallows number of %i" % mallows)
|
Hofstadter Figure-Figure sequences | Python | These two sequences of positive integers are defined as:
:::: \begin{align}
R(1)&=1\ ;\ S(1)=2 \\
R(n)&=R(n-1)+S(n-1), \quad n>1.
\end{align}
The sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n).
Sequence R starts:
1, 3, 7, 12, 18, ...
Sequence S starts:
2, 4, 5, 6, 8, ...
;Task:
# Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).
# No maximum value for '''n''' should be assumed.
# Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69
# Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once.
;References:
* Sloane's A005228 and A030124.
* Wolfram MathWorld
* Wikipedia: Hofstadter Figure-Figure sequences.
| def ffr(n):
if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
try:
return ffr.r[n]
except IndexError:
r, s = ffr.r, ffs.s
ffr_n_1 = ffr(n-1)
lastr = r[-1]
# extend s up to, and one past, last r
s += list(range(s[-1] + 1, lastr))
if s[-1] < lastr: s += [lastr + 1]
# access s[n-1] temporarily extending s if necessary
len_s = len(s)
ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]
ans = ffr_n_1 + ffs_n_1
r.append(ans)
return ans
ffr.r = [None, 1]
def ffs(n):
if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
try:
return ffs.s[n]
except IndexError:
r, s = ffr.r, ffs.s
for i in range(len(r), n+2):
ffr(i)
if len(s) > n:
return s[n]
raise Exception("Whoops!")
ffs.s = [None, 2]
if __name__ == '__main__':
first10 = [ffr(i) for i in range(1,11)]
assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)"
print("ffr(n) for n = [1..10] is", first10)
#
bin = [None] + [0]*1000
for i in range(40, 0, -1):
bin[ffr(i)] += 1
for i in range(960, 0, -1):
bin[ffs(i)] += 1
if all(b == 1 for b in bin[1:1000]):
print("All Integers 1..1000 found OK")
else:
print("All Integers 1..1000 NOT found only once: ERROR") |
Hofstadter Figure-Figure sequences | Python from Haskell | These two sequences of positive integers are defined as:
:::: \begin{align}
R(1)&=1\ ;\ S(1)=2 \\
R(n)&=R(n-1)+S(n-1), \quad n>1.
\end{align}
The sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n).
Sequence R starts:
1, 3, 7, 12, 18, ...
Sequence S starts:
2, 4, 5, 6, 8, ...
;Task:
# Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).
# No maximum value for '''n''' should be assumed.
# Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69
# Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once.
;References:
* Sloane's A005228 and A030124.
* Wolfram MathWorld
* Wikipedia: Hofstadter Figure-Figure sequences.
| from itertools import islice
def R():
n = 1
yield n
for s in S():
n += s
yield n;
def S():
yield 2
yield 4
u = 5
for r in R():
if r <= u: continue;
for x in range(u, r): yield x
u = r + 1
def lst(s, n): return list(islice(s(), n))
print "R:", lst(R, 10)
print "S:", lst(S, 10)
print sorted(lst(R, 40) + lst(S, 960)) == list(range(1,1001))
# perf test case
# print sum(lst(R, 10000000)) |
Hofstadter Q sequence | Python | The Hofstadter Q sequence is defined as:
:: \begin{align}
Q(1)&=Q(2)=1, \\
Q(n)&=Q\big(n-Q(n-1)\big)+Q\big(n-Q(n-2)\big), \quad n>2.
\end{align}
It is defined like the [[Fibonacci sequence]], but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence.
;Task:
* Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6
* Confirm and display that the 1000th term is: 502
;Optional extra credit
* Count and display how many times a member of the sequence is less than its preceding term for terms up to and including the 100,000th term.
* Ensure that the extra credit solution ''safely'' handles being initially asked for an '''n'''th term where '''n''' is large.
(This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).
| from sys import getrecursionlimit
def q1(n):
if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
try:
return q.seq[n]
except IndexError:
len_q, rlimit = len(q.seq), getrecursionlimit()
if (n - len_q) > (rlimit // 5):
for i in range(len_q, n, rlimit // 5):
q(i)
ans = q(n - q(n - 1)) + q(n - q(n - 2))
q.seq.append(ans)
return ans
if __name__ == '__main__':
tmp = q1(100000)
print("Q(i+1) < Q(i) for i [1..100000] is true %i times." %
sum(k1 < k0 for k0, k1 in zip(q.seq[1:], q.seq[2:]))) |
Horner's rule for polynomial evaluation | Python | A fast scheme for evaluating a polynomial such as:
: -19+7x-4x^2+6x^3\,
when
: x=3\;.
is to arrange the computation as follows:
: ((((0) x + 6) x + (-4)) x + 7) x + (-19)\;
And compute the result from the innermost brackets outwards as in this pseudocode:
coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order''
x ''':=''' 3
accumulator ''':=''' 0
'''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do'''
''# Assumes 1-based indexing for arrays''
accumulator ''':=''' ( accumulator * x ) + coefficients[i]
'''done'''
''# accumulator now has the answer''
'''Task Description'''
:Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using Horner's rule.
Cf. [[Formal power series]]
| >>> try: from functools import reduce
except: pass
>>> def horner(coeffs, x):
return reduce(lambda acc, c: acc * x + c, reversed(coeffs), 0)
>>> horner( (-19, 7, -4, 6), 3)
128 |
ISBN13 check digit | Python | Validate the check digit of an ISBN-13 code:
::* Multiply every other digit by '''3'''.
::* Add these numbers and the other digits.
::* Take the remainder of this number after division by '''10'''.
::* If it is '''0''', the ISBN-13 check digit is correct.
You might use the following codes for testing:
::::* 978-0596528126 (good)
::::* 978-0596528120 (bad)
::::* 978-1788399081 (good)
::::* 978-1788399083 (bad)
Show output here, on this page
;See also:
:* for details: 13-digit ISBN method of validation. (installs cookies.)
| def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = '''
978-1734314502
978-1734314509
978-1788399081
978-1788399083'''.strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}") |
I before E except after C | Python | The phrase "I before E, except after C" is a
widely known mnemonic which is supposed to help when spelling English words.
;Task:
Using the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
check if the two sub-clauses of the phrase are plausible individually:
:::# ''"I before E when not preceded by C"''
:::# ''"E before I when preceded by C"''
If both sub-phrases are plausible then the original phrase can be said to be plausible.
Something is plausible if the number of words having the feature is more than two times the number of words having the opposite feature (where feature is 'ie' or 'ei' preceded or not by 'c' as appropriate).
;Stretch goal:
As a stretch goal use the entries from the table of Word Frequencies in Written and Spoken English: based on the British National Corpus, (selecting those rows with three space or tab separated words only), to see if the phrase is plausible when word frequencies are taken into account.
''Show your output here as well as your program.''
;cf.:
* Schools to rethink 'i before e' - BBC news, 20 June 2009
* I Before E Except After C - QI Series 8 Ep 14, (humorous)
* Companion website for the book: "Word Frequencies in Written and Spoken English: based on the British National Corpus".
| import urllib.request
import re
PLAUSIBILITY_RATIO = 2
def plausibility_check(comment, x, y):
print('\n Checking plausibility of: %s' % comment)
if x > PLAUSIBILITY_RATIO * y:
print(' PLAUSIBLE. As we have counts of %i vs %i, a ratio of %4.1f times'
% (x, y, x / y))
else:
if x > y:
print(' IMPLAUSIBLE. As although we have counts of %i vs %i, a ratio of %4.1f times does not make it plausible'
% (x, y, x / y))
else:
print(' IMPLAUSIBLE, probably contra-indicated. As we have counts of %i vs %i, a ratio of %4.1f times'
% (x, y, x / y))
return x > PLAUSIBILITY_RATIO * y
def simple_stats(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):
words = urllib.request.urlopen(url).read().decode().lower().split()
cie = len({word for word in words if 'cie' in word})
cei = len({word for word in words if 'cei' in word})
not_c_ie = len({word for word in words if re.search(r'(^ie|[^c]ie)', word)})
not_c_ei = len({word for word in words if re.search(r'(^ei|[^c]ei)', word)})
return cei, cie, not_c_ie, not_c_ei
def print_result(cei, cie, not_c_ie, not_c_ei):
if ( plausibility_check('I before E when not preceded by C', not_c_ie, not_c_ei)
& plausibility_check('E before I when preceded by C', cei, cie) ):
print('\nOVERALL IT IS PLAUSIBLE!')
else:
print('\nOVERALL IT IS IMPLAUSIBLE!')
print('(To be plausible, one count must exceed another by %i times)' % PLAUSIBILITY_RATIO)
print('Checking plausibility of "I before E except after C":')
print_result(*simple_stats()) |
Identity matrix | Python | Build an identity matrix of a size known at run-time.
An ''identity matrix'' is a square matrix of size '''''n'' x ''n''''',
where the diagonal elements are all '''1'''s (ones),
and all the other elements are all '''0'''s (zeroes).
I_n = \begin{bmatrix}
1 & 0 & 0 & \cdots & 0 \\
0 & 1 & 0 & \cdots & 0 \\
0 & 0 & 1 & \cdots & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
0 & 0 & 0 & \cdots & 1 \\
\end{bmatrix}
;Related tasks:
* [[Spiral matrix]]
* [[Zig-zag matrix]]
* [[Ulam_spiral_(for_primes)]]
| def identity(size):
matrix = [[0]*size for i in range(size)]
#matrix = [[0] * size] * size #Has a flaw. See http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of-lists
for i in range(size):
matrix[i][i] = 1
for rows in matrix:
for elements in rows:
print elements,
print "" |
Identity matrix | Python 3.7 | Build an identity matrix of a size known at run-time.
An ''identity matrix'' is a square matrix of size '''''n'' x ''n''''',
where the diagonal elements are all '''1'''s (ones),
and all the other elements are all '''0'''s (zeroes).
I_n = \begin{bmatrix}
1 & 0 & 0 & \cdots & 0 \\
0 & 1 & 0 & \cdots & 0 \\
0 & 0 & 1 & \cdots & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
0 & 0 & 0 & \cdots & 1 \\
\end{bmatrix}
;Related tasks:
* [[Spiral matrix]]
* [[Zig-zag matrix]]
* [[Ulam_spiral_(for_primes)]]
| '''Identity matrices by maps and equivalent list comprehensions'''
import operator
# idMatrix :: Int -> [[Int]]
def idMatrix(n):
'''Identity matrix of order n,
expressed as a nested map.
'''
eq = curry(operator.eq)
xs = range(0, n)
return list(map(
lambda x: list(map(
compose(int)(eq(x)),
xs
)),
xs
))
# idMatrix3 :: Int -> [[Int]]
def idMatrix2(n):
'''Identity matrix of order n,
expressed as a nested comprehension.
'''
xs = range(0, n)
return ([int(x == y) for x in xs] for y in xs)
# TEST ----------------------------------------------------
def main():
'''
Identity matrix of dimension five,
by two different routes.
'''
for f in [idMatrix, idMatrix2]:
print(
'\n' + f.__name__ + ':',
'\n\n' + '\n'.join(map(str, f(5))),
)
# GENERIC -------------------------------------------------
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
# curry :: ((a, b) -> c) -> a -> b -> c
def curry(f):
'''A curried function derived
from an uncurried function.'''
return lambda a: lambda b: f(a, b)
# MAIN ---
if __name__ == '__main__':
main() |
Idiomatically determine all the characters that can be used for symbols | Python | Idiomatically determine all the characters that can be used for ''symbols''.
The word ''symbols'' is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to ''name'', but not being restricted to this list. ''Identifiers'' might be another name for ''symbols''.
The method should find the characters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
;Task requirements
Display the set of all the characters that can be used for symbols which can be used (allowed) by the computer program.
You may want to mention what hardware architecture is being used, and if applicable, the operating system.
Note that most languages have additional restrictions on what characters can't be used for the first character of a variable or statement label, for instance. These type of restrictions needn't be addressed here (but can be mentioned).
;See also
* Idiomatically determine all the lowercase and uppercase letters.
| See [[Idiomatically_determine_all_the_lowercase_and_uppercase_letters#Python|String class isidentifier]].
|
Idiomatically determine all the lowercase and uppercase letters | Python | Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
;Task requirements
Display the set of all:
::::::* lowercase letters
::::::* uppercase letters
that can be used (allowed) by the computer program,
where ''letter'' is a member of the Latin (English) alphabet: '''a''' --> '''z''' and '''A''' --> '''Z'''.
You may want to mention what hardware architecture is being used, and if applicable, the operating system.
;See also
* Idiomatically determine all the characters that can be used for symbols.
| classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal,
str.isdigit, str.isidentifier, str.isnumeric, str.isprintable,
str.isspace, str.istitle)
for stringclass in classes:
chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i)))
print('\nString class %s has %i characters the first of which are:\n %r'
% (stringclass.__name__, len(chars), chars[:100])) |
Imaginary base numbers | Python from C++ | Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i.
''The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.]''
Other imaginary bases are possible too but are not as widely discussed and aren't specifically named.
'''Task:''' Write a set of procedures (functions, subroutines, however they are referred to in your language) to convert base 10 numbers to an imaginary base and back.
At a minimum, support quater-imaginary (base 2i).
For extra kudos, support positive or negative bases 2i through 6i (or higher).
As a stretch goal, support converting non-integer numbers ( E.G. 227.65625+10.859375i ) to an imaginary base.
See Wikipedia: Quater-imaginary_base for more details.
For reference, here are some some decimal and complex numbers converted to quater-imaginary.
Base 10
Base 2i
1
1
2
2
3
3
4
10300
5
10301
6
10302
7
10303
8
10200
9
10201
10
10202
11
10203
12
10100
13
10101
14
10102
15
10103
16
10000
Base 10
Base 2i
-1
103
-2
102
-3
101
-4
100
-5
203
-6
202
-7
201
-8
200
-9
303
-10
302
-11
301
-12
300
-13
1030003
-14
1030002
-15
1030001
-16
1030000
Base 10
Base 2i
1i
10.2
2i
10.0
3i
20.2
4i
20.0
5i
30.2
6i
30.0
7i
103000.2
8i
103000.0
9i
103010.2
10i
103010.0
11i
103020.2
12i
103020.0
13i
103030.2
14i
103030.0
15i
102000.2
16i
102000.0
Base 10
Base 2i
-1i
0.2
-2i
1030.0
-3i
1030.2
-4i
1020.0
-5i
1020.2
-6i
1010.0
-7i
1010.2
-8i
1000.0
-9i
1000.2
-10i
2030.0
-11i
2030.2
-12i
2020.0
-13i
2020.2
-14i
2010.0
-15i
2010.2
-16i
2000.0
| import math
import re
def inv(c):
denom = c.real * c.real + c.imag * c.imag
return complex(c.real / denom, -c.imag / denom)
class QuaterImaginary:
twoI = complex(0, 2)
invTwoI = inv(twoI)
def __init__(self, str):
if not re.match("^[0123.]+$", str) or str.count('.') > 1:
raise Exception('Invalid base 2i number')
self.b2i = str
def toComplex(self):
pointPos = self.b2i.find('.')
posLen = len(self.b2i) if (pointPos < 0) else pointPos
sum = complex(0, 0)
prod = complex(1, 0)
for j in xrange(0, posLen):
k = int(self.b2i[posLen - 1 - j])
if k > 0:
sum += prod * k
prod *= QuaterImaginary.twoI
if pointPos != -1:
prod = QuaterImaginary.invTwoI
for j in xrange(posLen + 1, len(self.b2i)):
k = int(self.b2i[j])
if k > 0:
sum += prod * k
prod *= QuaterImaginary.invTwoI
return sum
def __str__(self):
return str(self.b2i)
def toQuaterImaginary(c):
if c.real == 0.0 and c.imag == 0.0:
return QuaterImaginary("0")
re = int(c.real)
im = int(c.imag)
fi = -1
ss = ""
while re != 0:
re, rem = divmod(re, -4)
if rem < 0:
rem += 4
re += 1
ss += str(rem) + '0'
if im != 0:
f = c.imag / 2
im = int(math.ceil(f))
f = -4 * (f - im)
index = 1
while im != 0:
im, rem = divmod(im, -4)
if rem < 0:
rem += 4
im += 1
if index < len(ss):
ss[index] = str(rem)
else:
ss += '0' + str(rem)
index = index + 2
fi = int(f)
ss = ss[::-1]
if fi != -1:
ss += '.' + str(fi)
ss = ss.lstrip('0')
if ss[0] == '.':
ss = '0' + ss
return QuaterImaginary(ss)
for i in xrange(1,17):
c1 = complex(i, 0)
qi = toQuaterImaginary(c1)
c2 = qi.toComplex()
print "{0:8} -> {1:>8} -> {2:8} ".format(c1, qi, c2),
c1 = -c1
qi = toQuaterImaginary(c1)
c2 = qi.toComplex()
print "{0:8} -> {1:>8} -> {2:8}".format(c1, qi, c2)
print
for i in xrange(1,17):
c1 = complex(0, i)
qi = toQuaterImaginary(c1)
c2 = qi.toComplex()
print "{0:8} -> {1:>8} -> {2:8} ".format(c1, qi, c2),
c1 = -c1
qi = toQuaterImaginary(c1)
c2 = qi.toComplex()
print "{0:8} -> {1:>8} -> {2:8}".format(c1, qi, c2)
print "done"
|
Increasing gaps between consecutive Niven numbers | Python | Note: '''Niven''' numbers are also called '''Harshad''' numbers.
:::: They are also called '''multidigital''' numbers.
'''Niven''' numbers are positive integers which are evenly divisible by the sum of its
digits (expressed in base ten).
''Evenly divisible'' means ''divisible with no remainder''.
;Task:
:* find the gap (difference) of a Niven number from the previous Niven number
:* if the gap is ''larger'' than the (highest) previous gap, then:
:::* show the index (occurrence) of the gap (the 1st gap is '''1''')
:::* show the index of the Niven number that starts the gap (1st Niven number is '''1''', 33rd Niven number is '''100''')
:::* show the Niven number that starts the gap
:::* show all numbers with comma separators where appropriate (optional)
:::* I.E.: the gap size of '''60''' starts at the 33,494th Niven number which is Niven number '''297,864'''
:* show all increasing gaps up to the ten millionth ('''10,000,000th''') Niven number
:* (optional) show all gaps up to whatever limit is feasible/practical/realistic/reasonable/sensible/viable on your computer
:* show all output here, on this page
;Related task:
:* Harshad or Niven series.
;Also see:
:* Journal of Integer Sequences, Vol. 6 (2004), Article 03.2.5, Large and Small Gaps Between Consecutive Niven Numbers.
:* (PDF) version of the (above) article by Doyon.
| """
Python implementation of
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers
"""
# based on C example
# Returns the sum of the digits of n given the
# sum of the digits of n - 1
def digit_sum(n, sum):
sum += 1
while n > 0 and n % 10 == 0:
sum -= 9
n /= 10
return sum
previous = 1
gap = 0
sum = 0
niven_index = 0
gap_index = 1
print("Gap index Gap Niven index Niven number")
niven = 1
while gap_index <= 22:
sum = digit_sum(niven, sum)
if niven % sum == 0:
if niven > previous + gap:
gap = niven - previous;
print('{0:9d} {1:4d} {2:13d} {3:11d}'.format(gap_index, gap, niven_index, previous))
gap_index += 1
previous = niven
niven_index += 1
niven += 1
|
Index finite lists of positive integers | Python | It is known that the set of finite lists of positive integers is countable.
This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers.
;Task:
Implement such a mapping:
:* write a function ''rank'' which assigns an integer to any finite, arbitrarily long list of arbitrary large positive integers.
:* write a function ''unrank'' which is the ''rank'' inverse function.
Demonstrate your solution by:
:* picking a random-length list of random positive integers
:* turn it into an integer, and
:* get the list back.
There are many ways to do this. Feel free to choose any one you like.
;Extra credit:
Make the ''rank'' function as a bijection and show ''unrank(n)'' for '''n''' varying from '''0''' to '''10'''.
| def rank(x): return int('a'.join(map(str, [1] + x)), 11)
def unrank(n):
s = ''
while n: s,n = "0123456789a"[n%11] + s, n//11
return map(int, s.split('a'))[1:]
l = [1, 2, 3, 10, 100, 987654321]
print l
n = rank(l)
print n
l = unrank(n)
print l |
Integer overflow | Python | Some languages support one or more integer types of the underlying processor.
This integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit.
The integers supported by such a type can be ''signed'' or ''unsigned''.
Arithmetic for machine level integers can often be done by single CPU instructions.
This allows high performance and is the main reason to support machine level integers.
;Definition:
An integer overflow happens when the result of a computation does not fit into the fixed size integer.
The result can be too small or too big to be representable in the fixed size integer.
;Task:
When a language has fixed size integer types, create a program that
does arithmetic computations for the fixed size integers of the language.
These computations must be done such that the result would overflow.
The program should demonstrate what the following expressions do.
For 32-bit signed integers:
::::: {|class="wikitable"
!Expression
!Result that does not fit into a 32-bit signed integer
|-
| -(-2147483647-1)
| 2147483648
|-
| 2000000000 + 2000000000
| 4000000000
|-
| -2147483647 - 2147483647
| -4294967294
|-
| 46341 * 46341
| 2147488281
|-
| (-2147483647-1) / -1
| 2147483648
|}
For 64-bit signed integers:
::: {|class="wikitable"
!Expression
!Result that does not fit into a 64-bit signed integer
|-
| -(-9223372036854775807-1)
| 9223372036854775808
|-
| 5000000000000000000+5000000000000000000
| 10000000000000000000
|-
| -9223372036854775807 - 9223372036854775807
| -18446744073709551614
|-
| 3037000500 * 3037000500
| 9223372037000250000
|-
| (-9223372036854775807-1) / -1
| 9223372036854775808
|}
For 32-bit unsigned integers:
::::: {|class="wikitable"
!Expression
!Result that does not fit into a 32-bit unsigned integer
|-
| -4294967295
| -4294967295
|-
| 3000000000 + 3000000000
| 6000000000
|-
| 2147483647 - 4294967295
| -2147483648
|-
| 65537 * 65537
| 4295098369
|}
For 64-bit unsigned integers:
::: {|class="wikitable"
!Expression
!Result that does not fit into a 64-bit unsigned integer
|-
| -18446744073709551615
| -18446744073709551615
|-
| 10000000000000000000 + 10000000000000000000
| 20000000000000000000
|-
| 9223372036854775807 - 18446744073709551615
| -9223372036854775808
|-
| 4294967296 * 4294967296
| 18446744073709551616
|}
;Notes:
:* When the integer overflow does trigger an exception show how the exception is caught.
:* When the integer overflow produces some value, print it.
:* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results.
:* This should be done for signed and unsigned integers of various sizes supported by the computer programming language.
:* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted.
:* It is okay to mention, when a language supports unlimited precision integers, but this task is NOT the place to demonstrate the capabilities of unlimited precision integers.
| Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> for calc in ''' -(-2147483647-1)
2000000000 + 2000000000
-2147483647 - 2147483647
46341 * 46341
(-2147483647-1) / -1'''.split('\n'):
ans = eval(calc)
print('Expression: %r evaluates to %s of type %s'
% (calc.strip(), ans, type(ans)))
Expression: '-(-2147483647-1)' evaluates to 2147483648 of type <class 'int'>
Expression: '2000000000 + 2000000000' evaluates to 4000000000 of type <class 'int'>
Expression: '-2147483647 - 2147483647' evaluates to -4294967294 of type <class 'int'>
Expression: '46341 * 46341' evaluates to 2147488281 of type <class 'int'>
Expression: '(-2147483647-1) / -1' evaluates to 2147483648.0 of type <class 'float'>
>>> |
Integer sequence | Python | Create a program that, when run, would display all integers from '''1''' to ''' ''' (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295. Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library.
If appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations--or lack thereof.
| from itertools import count
for i in count():
print(i) |
Intersecting number wheels | Python | A number wheel has:
* A ''name'' which is an uppercase letter.
* A set of ordered ''values'' which are either ''numbers'' or ''names''.
A ''number'' is generated/yielded from a named wheel by:
:1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel":
::1.a If the value is a number, yield it.
::1.b If the value is a name, yield the next value from the named wheel
::1.c Advance the position of this wheel.
Given the wheel
: A: 1 2 3
the number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ...
'''Note:''' When more than one wheel is defined as a set of intersecting wheels then the
first named wheel is assumed to be the one that values are generated from.
;Examples:
Given the wheels:
A: 1 B 2
B: 3 4
The series of numbers generated starts:
1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2...
The intersections of number wheels can be more complex, (and might loop forever),
and wheels may be multiply connected.
'''Note:''' If a named wheel is referenced more than
once by one or many other wheels, then there is only one position of the wheel
that is advanced by each and all references to it.
E.g.
A: 1 D D
D: 6 7 8
Generates:
1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ...
;Task:
Generate and show the first twenty terms of the sequence of numbers generated
from these groups:
Intersecting Number Wheel group:
A: 1 2 3
Intersecting Number Wheel group:
A: 1 B 2
B: 3 4
Intersecting Number Wheel group:
A: 1 D D
D: 6 7 8
Intersecting Number Wheel group:
A: 1 B C
B: 3 4
C: 5 B
Show your output here, on this page.
| from itertools import islice
class INW():
"""
Intersecting Number Wheels
represented as a dict mapping
name to tuple of values.
"""
def __init__(self, **wheels):
self._wheels = wheels
self.isect = {name: self._wstate(name, wheel)
for name, wheel in wheels.items()}
def _wstate(self, name, wheel):
"Wheel state holder"
assert all(val in self._wheels for val in wheel if type(val) == str), \
f"ERROR: Interconnected wheel not found in {name}: {wheel}"
pos = 0
ln = len(wheel)
while True:
nxt, pos = wheel[pos % ln], pos + 1
yield next(self.isect[nxt]) if type(nxt) == str else nxt
def __iter__(self):
base_wheel_name = next(self.isect.__iter__())
yield from self.isect[base_wheel_name]
def __repr__(self):
return f"{self.__class__.__name__}({self._wheels})"
def __str__(self):
txt = "Intersecting Number Wheel group:"
for name, wheel in self._wheels.items():
txt += f"\n {name+':':4}" + ' '.join(str(v) for v in wheel)
return txt
def first(iter, n):
"Pretty print first few terms"
return ' '.join(f"{nxt}" for nxt in islice(iter, n))
if __name__ == '__main__':
for group in[
{'A': (1, 2, 3)},
{'A': (1, 'B', 2),
'B': (3, 4)},
{'A': (1, 'D', 'D'),
'D': (6, 7, 8)},
{'A': (1, 'B', 'C'),
'B': (3, 4),
'C': (5, 'B')}, # 135143145...
]:
w = INW(**group)
print(f"{w}\n Generates:\n {first(w, 20)} ...\n") |
Intersecting number wheels | Python 3.7 | A number wheel has:
* A ''name'' which is an uppercase letter.
* A set of ordered ''values'' which are either ''numbers'' or ''names''.
A ''number'' is generated/yielded from a named wheel by:
:1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel":
::1.a If the value is a number, yield it.
::1.b If the value is a name, yield the next value from the named wheel
::1.c Advance the position of this wheel.
Given the wheel
: A: 1 2 3
the number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ...
'''Note:''' When more than one wheel is defined as a set of intersecting wheels then the
first named wheel is assumed to be the one that values are generated from.
;Examples:
Given the wheels:
A: 1 B 2
B: 3 4
The series of numbers generated starts:
1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2...
The intersections of number wheels can be more complex, (and might loop forever),
and wheels may be multiply connected.
'''Note:''' If a named wheel is referenced more than
once by one or many other wheels, then there is only one position of the wheel
that is advanced by each and all references to it.
E.g.
A: 1 D D
D: 6 7 8
Generates:
1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ...
;Task:
Generate and show the first twenty terms of the sequence of numbers generated
from these groups:
Intersecting Number Wheel group:
A: 1 2 3
Intersecting Number Wheel group:
A: 1 B 2
B: 3 4
Intersecting Number Wheel group:
A: 1 D D
D: 6 7 8
Intersecting Number Wheel group:
A: 1 B C
B: 3 4
C: 5 B
Show your output here, on this page.
| '''Intersecting number wheels'''
from itertools import cycle, islice
from functools import reduce
# clockWorkTick :: Dict -> (Dict, Char)
def clockWorkTick(wheelMap):
'''The new state of the wheels, tupled with a
digit found by recursive descent from a single
click of the first wheel.'''
def click(wheels):
def go(wheelName):
wheel = wheels.get(wheelName, ['?'])
v = wheel[0]
return (Tuple if v.isdigit() or '?' == v else click)(
insertDict(wheelName)(leftRotate(wheel))(wheels)
)(v)
return go
return click(wheelMap)('A')
# leftRotate :: [a] -> String
def leftRotate(xs):
''' A string shifted cyclically towards
the left by one position.
'''
return ''.join(islice(cycle(xs), 1, 1 + len(xs)))
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''First twenty values from each set of test wheels.'''
wheelMaps = [dict(kvs) for kvs in [
[('A', "123")],
[('A', "1B2"), ('B', "34")],
[('A', "1DD"), ('D', "678")],
[('A', "1BC"), ('B', "34"), ('C', "5B")]
]]
print('New state of wheel sets, after 20 clicks of each:\n')
for wheels, series in [
mapAccumL(compose(const)(clockWorkTick))(
dct
)(' ' * 20) for dct in wheelMaps
]:
print((wheels, ''.join(series)))
print('\nInital states:')
for x in wheelMaps:
print(x)
# ----------------------- GENERIC ------------------------
# Tuple (,) :: a -> b -> (a, b)
def Tuple(x):
'''Constructor for a pair of values,
possibly of two different types.
'''
return lambda y: (
x + (y,)
) if isinstance(x, tuple) else (x, y)
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
# const :: a -> b -> a
def const(k):
'''The latter of two arguments,
with the first discarded.
'''
return lambda _: k
# insertDict :: String -> a -> Dict -> Dict
def insertDict(k):
'''A new dictionary updated with a (k, v) pair.'''
def go(v, dct):
return dict(dct, **{k: v})
return lambda v: lambda dct: go(v, dct)
# mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
def mapAccumL(f):
'''A tuple of an accumulation and a map
with accumulation from left to right.
'''
def nxt(a, x):
tpl = f(a[0])(x)
return tpl[0], a[1] + [tpl[1]]
def go(acc):
def g(xs):
return reduce(nxt, xs, (acc, []))
return g
return go
# MAIN ---
if __name__ == '__main__':
main() |
Isqrt (integer square root) of X | Python 2.7 | Sometimes a function is needed to find the integer square root of '''X''', where '''X''' can be a
real non-negative number.
Often '''X''' is actually a non-negative integer.
For the purposes of this task, '''X''' can be an integer or a real number, but if it
simplifies things in your computer programming language, assume it's an integer.
One of the most common uses of '''Isqrt''' is in the division of an integer by all factors (or
primes) up to the
X of that
integer, either to find the factors of that integer, or to determine primality.
An alternative method for finding the '''Isqrt''' of a number is to
calculate: floor( sqrt(X) )
::* where '''sqrt''' is the square root function for non-negative real numbers, and
::* where '''floor''' is the floor function for real numbers.
If the hardware supports the computation of (real) square roots, the above method might be a faster method for
small numbers that don't have very many significant (decimal) digits.
However, floating point arithmetic is limited in the number of (binary or decimal) digits that it can support.
;Pseudo-code using quadratic residue:
For this task, the integer square root of a non-negative number will be computed using a version
of ''quadratic residue'', which has the advantage that no ''floating point'' calculations are
used, only integer arithmetic.
Furthermore, the two divisions can be performed by bit shifting, and the one multiplication can also be be performed by bit shifting or additions.
The disadvantage is the limitation of the size of the largest integer that a particular computer programming language can support.
Pseudo-code of a procedure for finding the integer square root of '''X''' (all variables are integers):
q <-- 1 /*initialize Q to unity. */
/*find a power of 4 that's greater than X.*/
perform while q <= x /*perform while Q <= X. */
q <-- q * 4 /*multiply Q by four. */
end /*perform*/
/*Q is now greater than X.*/
z <-- x /*set Z to the value of X.*/
r <-- 0 /*initialize R to zero. */
perform while q > 1 /*perform while Q > unity. */
q <-- q / 4 /*integer divide by four. */
t <-- z - r - q /*compute value of T. */
r <-- r / 2 /*integer divide by two. */
if t >= 0 then do
z <-- t /*set Z to value of T. */
r <-- r + q /*compute new value of R. */
end
end /*perform*/
/*R is now the Isqrt(X). */
/* Sidenote: Also, Z is now the remainder after square root (i.e. */
/* R^2 + Z = X, so if Z = 0 then X is a perfect square). */
Another version for the (above) 1st '''perform''' is:
perform until q > X /*perform until Q > X. */
q <-- q * 4 /*multiply Q by four. */
end /*perform*/
Integer square roots of some values:
Isqrt( 0) is 0 Isqrt(60) is 7 Isqrt( 99) is 9
Isqrt( 1) is 1 Isqrt(61) is 7 Isqrt(100) is 10
Isqrt( 2) is 1 Isqrt(62) is 7 Isqrt(102) is 10
Isqrt( 3) is 1 Isqrt(63) is 7
Isqrt( 4) is 2 Isqrt(64) is 8 Isqet(120) is 10
Isqrt( 5) is 2 Isqrt(65) is 8 Isqrt(121) is 11
Isqrt( 6) is 2 Isqrt(66) is 8 Isqrt(122) is 11
Isqrt( 7) is 2 Isqrt(67) is 8
Isqrt( 8) is 2 Isqrt(68) is 8 Isqrt(143) is 11
Isqrt( 9) is 3 Isqrt(69) is 8 Isqrt(144) is 12
Isqrt(10) is 3 Isqrt(70) is 8 Isqrt(145) is 12
;Task:
Compute and show all output here (on this page) for:
::* the Isqrt of the integers from '''0''' ---> '''65''' (inclusive), shown in a horizontal format.
::* the Isqrt of the odd powers from '''71''' ---> '''773''' (inclusive), shown in a vertical format.
::* use commas in the displaying of larger numbers.
You can show more numbers for the 2nd requirement if the displays fits on one screen on Rosetta Code.
If your computer programming language only supports smaller integers, show what you can.
;Related tasks:
:* sequence of non-squares
:* integer roots
:* square root by hand
| def isqrt ( x ):
q = 1
while q <= x :
q *= 4
z,r = x,0
while q > 1 :
q /= 4
t,r = z-r-q,r/2
if t >= 0 :
z,r = t,r+q
return r
print ' '.join( '%d'%isqrt( n ) for n in xrange( 66 ))
print '\n'.join( '{0:114,} = isqrt( 7^{1:3} )'.format( isqrt( 7**n ),n ) for n in range( 1,204,2 )) |
Iterated digits squaring | Python from D | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else iterate(step(x))
>>> [iterate(x) for x in xrange(1, 20)]
[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1]
;Task:
: Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89.
Or, for much less credit - (showing that your algorithm and/or language is slow):
: Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89.
This problem derives from the Project Euler problem 92.
For a quick algorithm for this task see the talk page
;Related tasks:
* [[Combinations with repetitions]]
* [[Digital root]]
* [[Digital root/Multiplicative digital root]]
| from math import ceil, log10, factorial
def next_step(x):
result = 0
while x > 0:
result += (x % 10) ** 2
x /= 10
return result
def check(number):
candidate = 0
for n in number:
candidate = candidate * 10 + n
while candidate != 89 and candidate != 1:
candidate = next_step(candidate)
if candidate == 89:
digits_count = [0] * 10
for d in number:
digits_count[d] += 1
result = factorial(len(number))
for c in digits_count:
result /= factorial(c)
return result
return 0
def main():
limit = 100000000
cache_size = int(ceil(log10(limit)))
assert 10 ** cache_size == limit
number = [0] * cache_size
result = 0
i = cache_size - 1
while True:
if i == 0 and number[i] == 9:
break
if i == cache_size - 1 and number[i] < 9:
number[i] += 1
result += check(number)
elif number[i] == 9:
i -= 1
else:
number[i] += 1
for j in xrange(i + 1, cache_size):
number[j] = number[i]
i = cache_size - 1
result += check(number)
print result
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.