_id
stringlengths 2
5
| title
stringlengths 2
76
| partition
stringclasses 3
values | text
stringlengths 8
6.97k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q472 | Continued fraction_Arithmetic_G(matrix ng, continued fraction n) | test | class NG:
def __init__(self, a1, a, b1, b):
self.a1, self.a, self.b1, self.b = a1, a, b1, b
def ingress(self, n):
self.a, self.a1 = self.a1, self.a + self.a1 * n
self.b, self.b1 = self.b1, self.b + self.b1 * n
@property
def needterm(self):
return (self.b == 0 or self.b1 == 0) or not self.a//self.b == self.a1//self.b1
@property
def egress(self):
n = self.a // self.b
self.a, self.b = self.b, self.a - self.b * n
self.a1, self.b1 = self.b1, self.a1 - self.b1 * n
return n
@property
def egress_done(self):
if self.needterm: self.a, self.b = self.a1, self.b1
return self.egress
@property
def done(self):
return self.b == 0 and self.b1 == 0
| Python | {
"resource": ""
} |
q473 | Calkin-Wilf sequence | test | from fractions import Fraction
from math import floor
from itertools import islice, groupby
def cw():
a = Fraction(1)
while True:
yield a
a = 1 / (2 * floor(a) + 1 - a)
def r2cf(rational):
num, den = rational.numerator, rational.denominator
while den:
num, (digit, den) = den, divmod(num, den)
yield digit
def get_term_num(rational):
ans, dig, pwr = 0, 1, 0
for n in r2cf(rational):
for _ in range(n):
ans |= dig << pwr
pwr += 1
dig ^= 1
return ans
if __name__ == '__main__':
print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))
x = Fraction(83116, 51639)
print(f"\n{x} is the {get_term_num(x):_}'th term.")
| Python | {
"resource": ""
} |
q474 | Distribution of 0 digits in factorial series | test | def facpropzeros(N, verbose = True):
proportions = [0.0] * N
fac, psum = 1, 0.0
for i in range(N):
fac *= i + 1
d = list(str(fac))
psum += sum(map(lambda x: x == '0', d)) / len(d)
proportions[i] = psum / (i + 1)
if verbose:
print("The mean proportion of 0 in factorials from 1 to {} is {}.".format(N, psum / N))
return proportions
for n in [100, 1000, 10000]:
facpropzeros(n)
props = facpropzeros(47500, False)
n = (next(i for i in reversed(range(len(props))) if props[i] > 0.16))
print("The mean proportion dips permanently below 0.16 at {}.".format(n + 2))
| Python | {
"resource": ""
} |
q475 | Abelian sandpile model_Identity | test | from itertools import product
from collections import defaultdict
class Sandpile():
def __init__(self, gridtext):
array = [int(x) for x in gridtext.strip().split()]
self.grid = defaultdict(int,
{(i //3, i % 3): x
for i, x in enumerate(array)})
_border = set((r, c)
for r, c in product(range(-1, 4), repeat=2)
if not 0 <= r <= 2 or not 0 <= c <= 2
)
_cell_coords = list(product(range(3), repeat=2))
def topple(self):
g = self.grid
for r, c in self._cell_coords:
if g[(r, c)] >= 4:
g[(r - 1, c)] += 1
g[(r + 1, c)] += 1
g[(r, c - 1)] += 1
g[(r, c + 1)] += 1
g[(r, c)] -= 4
return True
return False
def stabilise(self):
while self.topple():
pass
g = self.grid
for row_col in self._border.intersection(g.keys()):
del g[row_col]
return self
__pos__ = stabilise
def __eq__(self, other):
g = self.grid
return all(g[row_col] == other.grid[row_col]
for row_col in self._cell_coords)
def __add__(self, other):
g = self.grid
ans = Sandpile("")
for row_col in self._cell_coords:
ans.grid[row_col] = g[row_col] + other.grid[row_col]
return ans.stabilise()
def __str__(self):
g, txt = self.grid, []
for row in range(3):
txt.append(' '.join(str(g[(row, col)])
for col in range(3)))
return '\n'.join(txt)
def __repr__(self):
return f'{self.__class__.__name__}()'
unstable = Sandpile()
s1 = Sandpile()
s2 = Sandpile()
s3 = Sandpile("3 3 3 3 3 3 3 3 3")
s3_id = Sandpile("2 1 2 1 0 1 2 1 2")
| Python | {
"resource": ""
} |
q476 | Magic numbers | test | from itertools import groupby
def magic_numbers(base):
hist = []
n = l = i = 0
while True:
l += 1
hist.extend((n + digit, l) for digit in range(-n % l, base, l))
i += 1
if i == len(hist):
return hist
n, l = hist[i]
n *= base
mn = magic_numbers(10)
print("found", len(mn), "magic numbers")
print("the largest one is", mn[-1][0])
print("count by number of digits:")
print(*(f"{l}:{sum(1 for _ in g)}" for l, g in groupby(l for _, l in mn)))
print(end="minimally pandigital in 1..9: ")
print(*(m for m, l in mn if l == 9 == len(set(str(m)) - {"0"})))
print(end="minimally pandigital in 0..9: ")
print(*(m for m, l in mn if l == 10 == len(set(str(m)))))
| Python | {
"resource": ""
} |
q477 | Iterators | test |
from collections import deque
from typing import Iterable
from typing import Iterator
from typing import Reversible
days = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
]
colors = deque(
[
"red",
"yellow",
"pink",
"green",
"purple",
"orange",
"blue",
]
)
class MyIterable:
class MyIterator:
def __init__(self) -> None:
self._day = -1
def __iter__(self):
return self
def __next__(self):
if self._day >= 6:
raise StopIteration
self._day += 1
return days[self._day]
class MyReversedIterator:
def __init__(self) -> None:
self._day = 7
def __iter__(self):
return self
def __next__(self):
if self._day <= 0:
raise StopIteration
self._day -= 1
return days[self._day]
def __iter__(self):
return self.MyIterator()
def __reversed__(self):
return self.MyReversedIterator()
def print_elements(container: Iterable[object]) -> None:
for element in container:
print(element, end=" ")
print("")
def _drop(it: Iterator[object], n: int) -> None:
try:
for _ in range(n):
next(it)
except StopIteration:
pass
def print_first_fourth_fifth(container: Iterable[object]) -> None:
it = iter(container)
print(next(it), end=" ")
_drop(it, 2)
print(next(it), end=" ")
print(next(it))
def print_reversed_first_fourth_fifth(container: Reversible[object]) -> None:
it = reversed(container)
print(next(it), end=" ")
_drop(it, 2)
print(next(it), end=" ")
print(next(it))
def main() -> None:
my_iterable = MyIterable()
print("All elements:")
print_elements(days)
print_elements(colors)
print_elements(my_iterable)
print("\nFirst, fourth, fifth:")
print_first_fourth_fifth(days)
print_first_fourth_fifth(colors)
print_first_fourth_fifth(my_iterable)
print("\nLast, fourth to last, fifth to last:")
print_reversed_first_fourth_fifth(days)
print_reversed_first_fourth_fifth(colors)
print_reversed_first_fourth_fifth(my_iterable)
if __name__ == "__main__":
main()
| Python | {
"resource": ""
} |
q478 | Find words which contain the most consonants | test | print('\n'.join((f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in
(x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)
for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)]
if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)
| Python | {
"resource": ""
} |
q479 | Prime words | test | for i in range(65,123):
check = 1
for j in range(2,i):
if i%j == 0:
check = 0
if check==1:
print(chr(i),end='')
| Python | {
"resource": ""
} |
q480 | Riordan numbers | test | def Riordan(N):
a = [1, 0, 1]
for n in range(3, N):
a.append((n - 1) * (2 * a[n - 1] + 3 * a[n - 2]) // (n + 1))
return a
rios = Riordan(10_000)
for i in range(32):
print(f'{rios[i] : 18,}', end='\n' if (i + 1) % 4 == 0 else '')
print(f'The 1,000th Riordan has {len(str(rios[999]))} digits.')
print(f'The 10,000th Rirdan has {len(str(rios[9999]))} digits.')
| Python | {
"resource": ""
} |
q481 | Numbers which are the cube roots of the product of their proper divisors | test |
from functools import reduce
from sympy import divisors
FOUND = 0
for num in range(1, 1_000_000):
divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1
if num * num * num == divprod:
FOUND += 1
if FOUND <= 50:
print(f'{num:5}', end='\n' if FOUND % 10 == 0 else '')
if FOUND == 500:
print(f'\nFive hundreth: {num:,}')
if FOUND == 5000:
print(f'\nFive thousandth: {num:,}')
if FOUND == 50000:
print(f'\nFifty thousandth: {num:,}')
break
| Python | {
"resource": ""
} |
q482 | Ormiston triples | test | import textwrap
from itertools import pairwise
from typing import Iterator
from typing import List
import primesieve
def primes() -> Iterator[int]:
it = primesieve.Iterator()
while True:
yield it.next_prime()
def triplewise(iterable):
for (a, _), (b, c) in pairwise(pairwise(iterable)):
yield a, b, c
def is_anagram(a: int, b: int, c: int) -> bool:
return sorted(str(a)) == sorted(str(b)) == sorted(str(c))
def up_to_one_billion() -> int:
count = 0
for triple in triplewise(primes()):
if is_anagram(*triple):
count += 1
if triple[2] >= 1_000_000_000:
break
return count
def up_to_ten_billion() -> int:
count = 0
for triple in triplewise(primes()):
if is_anagram(*triple):
count += 1
if triple[2] >= 10_000_000_000:
break
return count
def first_25() -> List[int]:
rv: List[int] = []
for triple in triplewise(primes()):
if is_anagram(*triple):
rv.append(triple[0])
if len(rv) >= 25:
break
return rv
if __name__ == "__main__":
print("Smallest members of first 25 Ormiston triples:")
print(textwrap.fill(" ".join(str(i) for i in first_25())), "\n")
print(up_to_one_billion(), "Ormiston triples before 1,000,000,000")
print(up_to_ten_billion(), "Ormiston triples before 10,000,000,000")
| Python | {
"resource": ""
} |
q483 | Super-Poulet numbers | test | from sympy import isprime, divisors
def is_super_Poulet(n):
return not isprime(n) and 2**(n - 1) % n == 1 and all((2**d - 2) % d == 0 for d in divisors(n))
spoulets = [n for n in range(1, 1_100_000) if is_super_Poulet(n)]
print('The first 20 super-Poulet numbers are:', spoulets[:20])
idx1m, val1m = next((i, v) for i, v in enumerate(spoulets) if v > 1_000_000)
print(f'The first super-Poulet number over 1 million is the {idx1m}th one, which is {val1m}')
| Python | {
"resource": ""
} |
q484 | Minesweeper game | test |
gridsize = (6, 4)
minerange = (0.2, 0.6)
try:
raw_input
except:
raw_input = input
import random
from itertools import product
from pprint import pprint as pp
def gridandmines(gridsize=gridsize, minerange=minerange):
xgrid, ygrid = gridsize
minmines, maxmines = minerange
minecount = xgrid * ygrid
minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))
grid = set(product(range(xgrid), range(ygrid)))
mines = set(random.sample(grid, minecount))
show = {xy:'.' for xy in grid}
return grid, mines, show
def printgrid(show, gridsize=gridsize):
xgrid, ygrid = gridsize
grid = '\n'.join(''.join(show[(x,y)] for x in range(xgrid))
for y in range(ygrid))
print( grid )
def resign(showgrid, mines, markedmines):
for m in mines:
showgrid[m] = 'Y' if m in markedmines else 'N'
def clear(x,y, showgrid, grid, mines, markedmines):
if showgrid[(x, y)] == '.':
xychar = str(sum(1
for xx in (x-1, x, x+1)
for yy in (y-1, y, y+1)
if (xx, yy) in mines ))
if xychar == '0': xychar = '.'
showgrid[(x,y)] = xychar
for xx in (x-1, x, x+1):
for yy in (y-1, y, y+1):
xxyy = (xx, yy)
if ( xxyy != (x, y)
and xxyy in grid
and xxyy not in mines | markedmines ):
clear(xx, yy, showgrid, grid, mines, markedmines)
if __name__ == '__main__':
grid, mines, showgrid = gridandmines()
markedmines = set([])
print( __doc__ )
print( '\nThere are %i true mines of fixed position in the grid\n' % len(mines) )
printgrid(showgrid)
while markedmines != mines:
inp = raw_input('m x y/c x y/p/r: ').strip().split()
if inp:
if inp[0] == 'm':
x, y = [int(i)-1 for i in inp[1:3]]
if (x,y) in markedmines:
markedmines.remove((x,y))
showgrid[(x,y)] = '.'
else:
markedmines.add((x,y))
showgrid[(x,y)] = '?'
elif inp[0] == 'p':
printgrid(showgrid)
elif inp[0] == 'c':
x, y = [int(i)-1 for i in inp[1:3]]
if (x,y) in mines | markedmines:
print( '\nKLABOOM!! You hit a mine.\n' )
resign(showgrid, mines, markedmines)
printgrid(showgrid)
break
clear(x,y, showgrid, grid, mines, markedmines)
printgrid(showgrid)
elif inp[0] == 'r':
print( '\nResigning!\n' )
resign(showgrid, mines, markedmines)
printgrid(showgrid)
break
print( '\nYou got %i and missed %i of the %i mines'
% (len(mines.intersection(markedmines)),
len(markedmines.difference(mines)),
len(mines)) )
| Python | {
"resource": ""
} |
q485 | Elementary cellular automaton_Infinite length | test | def _notcell(c):
return '0' if c == '1' else '1'
def eca_infinite(cells, rule):
lencells = len(cells)
rulebits = '{0:08b}'.format(rule)
neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)}
c = cells
while True:
yield c
c = _notcell(c[0])*2 + c + _notcell(c[-1])*2
c = ''.join(neighbours2next[c[i-1:i+2]] for i in range(1,len(c) - 1))
if __name__ == '__main__':
lines = 25
for rule in (90, 30):
print('\nRule: %i' % rule)
for i, c in zip(range(lines), eca_infinite('1', rule)):
print('%2i: %s%s' % (i, ' '*(lines - i), c.replace('0', '.').replace('1', '
| Python | {
"resource": ""
} |
q486 | Even numbers which cannot be expressed as the sum of two twin primes | test |
from sympy import sieve
def nonpairsums(include1=False, limit=20_000):
tpri = [i in sieve and (i - 2 in sieve or i + 2 in sieve)
for i in range(limit+2)]
if include1:
tpri[1] = True
twinsums = [False] * (limit * 2)
for i in range(limit):
for j in range(limit-i+1):
if tpri[i] and tpri[j]:
twinsums[i + j] = True
return [i for i in range(2, limit+1, 2) if not twinsums[i]]
print('Non twin prime sums:')
for k, p in enumerate(nonpairsums()):
print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '')
print('\n\nNon twin prime sums (including 1):')
for k, p in enumerate(nonpairsums(include1=True)):
print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '')
| Python | {
"resource": ""
} |
q487 | Nested templated data | test | from pprint import pprint as pp
class Template():
def __init__(self, structure):
self.structure = structure
self.used_payloads, self.missed_payloads = [], []
def inject_payload(self, id2data):
def _inject_payload(substruct, i2d, used, missed):
used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d)
missed.extend(f'??
for x in substruct if type(x) is not tuple and x not in i2d)
return tuple(_inject_payload(x, i2d, used, missed)
if type(x) is tuple
else i2d.get(x, f'??
for x in substruct)
ans = _inject_payload(self.structure, id2data,
self.used_payloads, self.missed_payloads)
self.unused_payloads = sorted(set(id2data.values())
- set(self.used_payloads))
self.missed_payloads = sorted(set(self.missed_payloads))
return ans
if __name__ == '__main__':
index2data = {p: f'Payload
print("
print('\n '.join(list(index2data.values())))
for structure in [
(((1, 2),
(3, 4, 1),
5),),
(((1, 2),
(10, 4, 1),
5),)]:
print("\n\n
pp(structure, width=13)
print("\n TEMPLATE WITH PAYLOADS:")
t = Template(structure)
out = t.inject_payload(index2data)
pp(out)
print("\n UNUSED PAYLOADS:\n ", end='')
unused = t.unused_payloads
print('\n '.join(unused) if unused else '-')
print(" MISSING PAYLOADS:\n ", end='')
missed = t.missed_payloads
print('\n '.join(missed) if missed else '-')
| Python | {
"resource": ""
} |
q488 | Honaker primes | test |
from pyprimesieve import primes
def digitsum(num):
return sum(int(c) for c in str(num))
def generate_honaker(limit=5_000_000):
honaker = [(i + 1, p) for i, p in enumerate(primes(limit)) if digitsum(p) == digitsum(i + 1)]
for hcount, (ppi, pri) in enumerate(honaker):
yield hcount + 1, ppi, pri
print('First 50 Honaker primes:')
for p in generate_honaker():
if p[0] < 51:
print(f'{str(p):16}', end='\n' if p[0] % 5 == 0 else '')
elif p[0] == 10_000:
print(f'\nThe 10,000th Honaker prime is the {p[1]:,}th one, which is {p[2]:,}.')
break
| Python | {
"resource": ""
} |
q489 | De Polignac numbers | test |
from sympy import isprime
from math import log
from numpy import ndarray
max_value = 1_000_000
all_primes = [i for i in range(max_value + 1) if isprime(i)]
powers_of_2 = [2**i for i in range(int(log(max_value, 2)))]
allvalues = ndarray(max_value, dtype=bool)
allvalues[:] = True
for i in all_primes:
for j in powers_of_2:
if i + j < max_value:
allvalues[i + j] = False
dePolignac = [n for n in range(1, max_value) if n & 1 == 1 and allvalues[n]]
print('First fifty de Polignac numbers:')
for i, n in enumerate(dePolignac[:50]):
print(f'{n:5}', end='\n' if (i + 1) % 10 == 0 else '')
print(f'\nOne thousandth: {dePolignac[999]:,}')
print(f'\nTen thousandth: {dePolignac[9999]:,}')
| Python | {
"resource": ""
} |
q490 | Mastermind | test | import random
def encode(correct, guess):
output_arr = [''] * len(correct)
for i, (correct_char, guess_char) in enumerate(zip(correct, guess)):
output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-'
return ''.join(output_arr)
def safe_int_input(prompt, min_val, max_val):
while True:
user_input = input(prompt)
try:
user_input = int(user_input)
except ValueError:
continue
if min_val <= user_input <= max_val:
return user_input
def play_game():
print("Welcome to Mastermind.")
print("You will need to guess a random code.")
print("For each guess, you will receive a hint.")
print("In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.")
print()
number_of_letters = safe_int_input("Select a number of possible letters for the code (2-20): ", 2, 20)
code_length = safe_int_input("Select a length for the code (4-10): ", 4, 10)
letters = 'ABCDEFGHIJKLMNOPQRST'[:number_of_letters]
code = ''.join(random.choices(letters, k=code_length))
guesses = []
while True:
print()
guess = input(f"Enter a guess of length {code_length} ({letters}): ").upper().strip()
if len(guess) != code_length or any([char not in letters for char in guess]):
continue
elif guess == code:
print(f"\nYour guess {guess} was correct!")
break
else:
guesses.append(f"{len(guesses)+1}: {' '.join(guess)} => {' '.join(encode(code, guess))}")
for i_guess in guesses:
print("------------------------------------")
print(i_guess)
print("------------------------------------")
if __name__ == '__main__':
play_game()
| Python | {
"resource": ""
} |
q491 | Zsigmondy numbers | test |
from math import gcd
from sympy import divisors
def zsig(num, aint, bint):
assert aint > bint
dexpms = [aint**i - bint**i for i in range(1, num)]
dexpn = aint**num - bint**num
return max([d for d in divisors(dexpn) if all(gcd(k, d) == 1 for k in dexpms)])
tests = [(2, 1), (3, 1), (4, 1), (5, 1), (6, 1),
(7, 1), (3, 2), (5, 3), (7, 3), (7, 5)]
for (a, b) in tests:
print(f'\nZsigmondy(n, {a}, {b}):', ', '.join(
[str(zsig(n, a, b)) for n in range(1, 21)]))
| Python | {
"resource": ""
} |
q492 | Sorensen–Dice coefficient | test |
from multiset import Multiset
def tokenizetext(txt):
arr = []
for wrd in txt.lower().split(' '):
arr += ([wrd] if len(wrd) == 1 else [wrd[i:i+2]
for i in range(len(wrd)-1)])
return Multiset(arr)
def sorenson_dice(text1, text2):
bc1, bc2 = tokenizetext(text1), tokenizetext(text2)
return 2 * len(bc1 & bc2) / (len(bc1) + len(bc2))
with open('tasklist_sorenson.txt', 'r') as fd:
alltasks = fd.read().split('\n')
for testtext in ['Primordial primes', 'Sunkist-Giuliani formula',
'Sieve of Euripides', 'Chowder numbers']:
taskvalues = sorted([(sorenson_dice(testtext, t), t)
for t in alltasks], reverse=True)
print(f'\n{testtext}:')
for (val, task) in taskvalues[:5]:
print(f' {val:.6f} {task}')
| Python | {
"resource": ""
} |
q566 | Julia set | train | from __future__ import division
cX = -0.7
cY = 0.27015
maxIter = 300
def setup():
size(640, 480)
def draw():
for x in range(width):
for y in range(height):
zx = 1.5 * (x - width / 2) / (0.5 * width)
zy = (y - height / 2) / (0.5 * height)
i = maxIter
while zx * zx + zy * zy < 4 and i > 0:
tmp = zx * zx - zy * zy + cX
zy = 2.0 * zx * zy + cY
zx = tmp
i -= 1
colorMode(HSB)
c = color(i / maxIter * 255, 255, 255 if i > 1 else 0)
set(x, y, c)
| Python | {
"resource": ""
} |
q568 | Greatest subsequential sum | train | def maxsubseq(seq):
return max((seq[begin:end] for begin in xrange(len(seq)+1)
for end in xrange(begin, len(seq)+1)),
key=sum)
| Python | {
"resource": ""
} |
q569 | Flow-control structures | train |
for i in range(n):
if (n%2) == 0:
continue
if (n%i) == 0:
result = i
break
else:
result = None
print "No odd factors found"
| Python | {
"resource": ""
} |
q570 | Levenshtein distance | train | def setup():
println(distance("kitten", "sitting"))
def distance(a, b):
costs = []
for j in range(len(b) + 1):
costs.append(j)
for i in range(1, len(a) + 1):
costs[0] = i
nw = i - 1
for j in range(1, len(b) + 1):
cj = min(1 + min(costs[j], costs[j - 1]),
nw if a[i - 1] == b[j - 1] else nw + 1)
nw = costs[j]
costs[j] = cj
return costs[len(b)]
| Python | {
"resource": ""
} |
q571 | Probabilistic choice | train | import random, bisect
def probchoice(items, probs):
prob_accumulator = 0
accumulator = []
for p in probs:
prob_accumulator += p
accumulator.append(prob_accumulator)
while True:
r = random.random()
yield items[bisect.bisect(accumulator, r)]
def probchoice2(items, probs, bincount=10000):
bins = []
for item,prob in zip(items, probs):
bins += [item]*int(bincount*prob)
while True:
yield random.choice(bins)
def tester(func=probchoice, items='good bad ugly'.split(),
probs=[0.5, 0.3, 0.2],
trials = 100000
):
def problist2string(probs):
return ",".join('%8.6f' % (p,) for p in probs)
from collections import defaultdict
counter = defaultdict(int)
it = func(items, probs)
for dummy in xrange(trials):
counter[it.next()] += 1
print "\n
print "Trials: ", trials
print "Items: ", ' '.join(items)
print "Target probability: ", problist2string(probs)
print "Attained probability:", problist2string(
counter[x]/float(trials) for x in items)
if __name__ == '__main__':
items = 'aleph beth gimel daleth he waw zayin heth'.split()
probs = [1/(float(n)+5) for n in range(len(items))]
probs[-1] = 1-sum(probs[:-1])
tester(probchoice, items, probs, 1000000)
tester(probchoice2, items, probs, 1000000)
| Python | {
"resource": ""
} |
q572 | Coprimes | train |
from math import gcd
def coprime(a, b):
return 1 == gcd(a, b)
def main():
print([
xy for xy in [
(21, 15), (17, 23), (36, 12),
(18, 29), (60, 15)
]
if coprime(*xy)
])
if __name__ == '__main__':
main()
| Python | {
"resource": ""
} |
q573 | Arithmetic-geometric mean_Calculate Pi | train | from decimal import *
D = Decimal
getcontext().prec = 100
a = n = D(1)
g, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5)
for i in range(18):
x = [(a + g) * half, (a * g).sqrt()]
var = x[0] - a
z -= var * var * n
n += n
a, g = x
print(a * a / z)
| Python | {
"resource": ""
} |
q576 | Combinations | train | >>> from itertools import combinations
>>> list(combinations(range(5),3))
[(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
| Python | {
"resource": ""
} |
q577 | Window creation | train | import Tkinter
w = Tkinter.Tk()
w.mainloop()
| Python | {
"resource": ""
} |
q578 | Two identical strings | train | def bits(n):
r = 0
while n:
n >>= 1
r += 1
return r
def concat(n):
return n << bits(n) | n
n = 1
while concat(n) <= 1000:
print("{0}: {0:b}".format(concat(n)))
n += 1
| Python | {
"resource": ""
} |
q579 | Pig the dice game | train |
from random import randint
playercount = 2
maxscore = 100
safescore = [0] * playercount
player = 0
score=0
while max(safescore) < maxscore:
rolling = input("Player %i: (%i, %i) Rolling? (Y) "
% (player, safescore[player], score)).strip().lower() in {'yes', 'y', ''}
if rolling:
rolled = randint(1, 6)
print(' Rolled %i' % rolled)
if rolled == 1:
print(' Bust! you lose %i but still keep your previous %i'
% (score, safescore[player]))
score, player = 0, (player + 1) % playercount
else:
score += rolled
else:
safescore[player] += score
if safescore[player] >= maxscore:
break
print(' Sticking with %i' % safescore[player])
score, player = 0, (player + 1) % playercount
print('\nPlayer %i wins with a score of %i' %(player, safescore[player]))
| Python | {
"resource": ""
} |
q580 | Roman numerals_Encode | train | import roman
print(roman.toRoman(2022))
| Python | {
"resource": ""
} |
q581 | Frobenius numbers | train |
def isPrime(v):
if v <= 1:
return False
if v < 4:
return True
if v % 2 == 0:
return False
if v < 9:
return True
if v % 3 == 0:
return False
else:
r = round(pow(v,0.5))
f = 5
while f <= r:
if v % f == 0 or v % (f + 2) == 0:
return False
f += 6
return True
pn = 2
n = 0
for i in range(3, 9999, 2):
if isPrime(i):
n += 1
f = (pn * i) - pn - i
if f > 10000:
break
print (n, ' => ', f)
pn = i
| Python | {
"resource": ""
} |
q582 | Largest number divisible by its digits | train |
from itertools import (chain, permutations)
from functools import (reduce)
from math import (gcd)
def main():
digits = [1, 2, 3, 4, 6, 7, 8, 9]
lcmDigits = reduce(lcm, digits)
sevenDigits = ((delete)(digits)(x) for x in [1, 4, 7])
print(
max(
(
intFromDigits(x) for x
in concatMap(permutations)(sevenDigits)
),
key=lambda n: n if 0 == n % lcmDigits else 0
)
)
def intFromDigits(xs):
return reduce(lambda a, x: a * 10 + x, xs, 0)
def concatMap(f):
def go(xs):
return chain.from_iterable(map(f, xs))
return go
def delete(xs):
def go(x):
ys = xs.copy()
ys.remove(x)
return ys
return go
def lcm(x, y):
return 0 if (0 == x or 0 == y) else abs(
y * (x // gcd(x, y))
)
if __name__ == '__main__':
main()
| Python | {
"resource": ""
} |
q583 | 99 bottles of beer | train | fun bottles(n): match __args__:
(0) => "No more bottles"
(1) => "1 bottle"
(_) => "$n bottles"
for n in 99..-1..1:
print @format
| Python | {
"resource": ""
} |
q584 | Numbers in base-16 representation that cannot be written with decimal digits | train | [print(16*q + r,end=' ') for q in range(0,16) for r in range(10,16)]
| Python | {
"resource": ""
} |
q585 | Set puzzle | train |
from itertools import product, combinations
from random import sample
features = [ 'green purple red'.split(),
'one two three'.split(),
'oval diamond squiggle'.split(),
'open striped solid'.split() ]
deck = list(product(list(range(3)), repeat=4))
dealt = 9
def printcard(card):
print(' '.join('%8s' % f[i] for f,i in zip(features, card)))
def getdeal(dealt=dealt):
deal = sample(deck, dealt)
return deal
def getsets(deal):
good_feature_count = set([1, 3])
sets = [ comb for comb in combinations(deal, 3)
if all( [(len(set(feature)) in good_feature_count)
for feature in zip(*comb)]
) ]
return sets
def printit(deal, sets):
print('Dealt %i cards:' % len(deal))
for card in deal: printcard(card)
print('\nFound %i sets:' % len(sets))
for s in sets:
for card in s: printcard(card)
print('')
if __name__ == '__main__':
while True:
deal = getdeal()
sets = getsets(deal)
if len(sets) == dealt / 2:
break
printit(deal, sets)
| Python | {
"resource": ""
} |
q586 | Left factorials | train | from itertools import islice
def lfact():
yield 0
fact, summ, n = 1, 0, 1
while 1:
fact, summ, n = fact*n, summ + fact, n + 1
yield summ
print('first 11:\n %r' % [lf for i, lf in zip(range(11), lfact())])
print('20 through 110 (inclusive) by tens:')
for lf in islice(lfact(), 20, 111, 10):
print(lf)
print('Digits in 1,000 through 10,000 (inclusive) by thousands:\n %r'
% [len(str(lf)) for lf in islice(lfact(), 1000, 10001, 1000)] )
| Python | {
"resource": ""
} |
q587 | Yin and yang | train | import math
def yinyang(n=3):
radii = [i * n for i in (1, 3, 6)]
ranges = [list(range(-r, r+1)) for r in radii]
squares = [[ (x,y) for x in rnge for y in rnge]
for rnge in ranges]
circles = [[ (x,y) for x,y in sqrpoints
if math.hypot(x,y) <= radius ]
for sqrpoints, radius in zip(squares, radii)]
m = {(x,y):' ' for x,y in squares[-1]}
for x,y in circles[-1]:
m[x,y] = '*'
for x,y in circles[-1]:
if x>0: m[(x,y)] = '·'
for x,y in circles[-2]:
m[(x,y+3*n)] = '*'
m[(x,y-3*n)] = '·'
for x,y in circles[-3]:
m[(x,y+3*n)] = '·'
m[(x,y-3*n)] = '*'
return '\n'.join(''.join(m[(x,y)] for x in reversed(ranges[-1])) for y in ranges[-1])
| Python | {
"resource": ""
} |
q588 | Singly-linked list_Element definition | train | class LinkedList(object):
class Node(object):
def __init__(self, item):
self.value = item
self.next = None
def __init__(self, item=None):
if item is not None:
self.head = Node(item); self.tail = self.head
else:
self.head = None; self.tail = None
def append(self, item):
if not self.head:
self.head = Node(item)
self.tail = self.head
elif self.tail:
self.tail.next = Node(item)
self.tail = self.tail.next
else:
self.tail = Node(item)
def __iter__(self):
cursor = self.head
while cursor:
yield cursor.value
cursor = cursor.next
| Python | {
"resource": ""
} |
q591 | Diversity prediction theorem | train |
from itertools import chain
from functools import reduce
def diversityValues(x):
def go(ps):
mp = mean(ps)
return {
'mean-error': meanErrorSquared(x)(ps),
'crowd-error': pow(x - mp, 2),
'diversity': meanErrorSquared(mp)(ps)
}
return go
def meanErrorSquared(x):
def go(ps):
return mean([
pow(p - x, 2) for p in ps
])
return go
def main():
print(unlines(map(
showDiversityValues(49),
[
[48, 47, 51],
[48, 47, 51, 42],
[50, '?', 50, {}, 50],
[]
]
)))
print(unlines(map(
showDiversityValues('49'),
[
[50, 50, 50],
[40, 35, 40],
]
)))
def showDiversityValues(x):
def go(ps):
def showDict(dct):
w = 4 + max(map(len, dct.keys()))
def showKV(a, kv):
k, v = kv
return a + k.rjust(w, ' ') + (
' : ' + showPrecision(3)(v) + '\n'
)
return 'Predictions: ' + showList(ps) + ' ->\n' + (
reduce(showKV, dct.items(), '')
)
def showProblem(e):
return (
unlines(map(indented(1), e)) if (
isinstance(e, list)
) else indented(1)(repr(e))
) + '\n'
return 'Observation: ' + repr(x) + '\n' + (
either(showProblem)(showDict)(
bindLR(numLR(x))(
lambda n: bindLR(numsLR(ps))(
compose(Right, diversityValues(n))
)
)
)
)
return go
def Left(x):
return {'type': 'Either', 'Right': None, 'Left': x}
def Right(x):
return {'type': 'Either', 'Left': None, 'Right': x}
def bindLR(m):
def go(mf):
return (
mf(m.get('Right')) if None is m.get('Left') else m
)
return go
def compose(*fs):
def go(f, g):
def fg(x):
return f(g(x))
return fg
return reduce(go, fs, identity)
def concatMap(f):
def go(xs):
return chain.from_iterable(map(f, xs))
return go
def either(fl):
return lambda fr: lambda e: fl(e['Left']) if (
None is e['Right']
) else fr(e['Right'])
def identity(x):
return x
def indented(n):
return lambda s: (4 * ' ' * n) + s
def mean(xs):
return sum(xs) / float(len(xs))
def numLR(x):
return Right(x) if (
isinstance(x, (float, int))
) else Left(
'Expected number, saw: ' + (
str(type(x)) + ' ' + repr(x)
)
)
def numsLR(xs):
def go(ns):
ls, rs = partitionEithers(map(numLR, ns))
return Left(ls) if ls else Right(rs)
return bindLR(
Right(xs) if (
bool(xs) and isinstance(xs, list)
) else Left(
'Expected a non-empty list, saw: ' + (
str(type(xs)) + ' ' + repr(xs)
)
)
)(go)
def partitionEithers(lrs):
def go(a, x):
ls, rs = a
r = x.get('Right')
return (ls + [x.get('Left')], rs) if None is r else (
ls, rs + [r]
)
return reduce(go, lrs, ([], []))
def showList(xs):
return '[' + ','.join(str(x) for x in xs) + ']'
def showPrecision(n):
def go(x):
return str(round(x, n))
return go
def unlines(xs):
return '\n'.join(xs)
if __name__ == '__main__':
main()
| Python | {
"resource": ""
} |
q592 | Base64 decode data | train | import base64
data = 'VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g='
print(base64.b64decode(data).decode('utf-8'))
| Python | {
"resource": ""
} |
q593 | Largest difference between adjacent primes | train | print("working...")
limit = 1000000
res1 = 0
res2 = 0
maxOld = 0
newDiff = 0
oldDiff = 0
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
for n in range(limit):
newDiff = n - maxOld
if isprime(n):
if (newDiff > oldDiff):
res1 = n
res2 = maxOld
oldDiff = newDiff
maxOld = n
diff = res1 - res2
print(res1)
print(res2)
print("Largest difference is = ",end="")
print(diff)
print("done...")
| Python | {
"resource": ""
} |
q594 | Higher-order functions | train | def first(function):
return function()
def second():
return "second"
result = first(second)
| Python | {
"resource": ""
} |
q595 | Ackermann function | train | from __future__ import print_function
def setup():
for m in range(4):
for n in range(7):
print("{} ".format(ackermann(m, n)), end = "")
print()
def ackermann(m, n):
if m == 0:
return n + 1
elif m > 0 and n == 0:
return ackermann(m - 1, 1)
else:
return ackermann(m - 1, ackermann(m, n - 1))
| Python | {
"resource": ""
} |
q596 | Averages_Median | train | def median(aray):
srtd = sorted(aray)
alen = len(srtd)
return 0.5*( srtd[(alen-1)//2] + srtd[alen//2])
a = (4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)
print a, median(a)
a = (4.1, 7.2, 1.7, 9.3, 4.4, 3.2)
print a, median(a)
| Python | {
"resource": ""
} |
q597 | Cheryl's birthday | train |
from itertools import groupby
from re import split
def main():
month, day = 0, 1
print(
uniquePairing(month)(
uniquePairing(day)(
monthsWithUniqueDays(False)([
tuple(x.split()) for x in
split(
', ',
'May 15, May 16, May 19, ' +
'June 17, June 18, ' +
'July 14, July 16, ' +
'Aug 14, Aug 15, Aug 17'
)
])
)
)
)
def monthsWithUniqueDays(blnInclude):
def go(xs):
month, day = 0, 1
months = [fst(x) for x in uniquePairing(day)(xs)]
return [
md for md in xs
if blnInclude or not (md[month] in months)
]
return go
def uniquePairing(i):
def go(xs):
def inner(md):
dct = md[i]
uniques = [
k for k in dct.keys()
if 1 == len(dct[k])
]
return [tpl for tpl in xs if tpl[i] in uniques]
return inner
return ap(bindPairs)(go)
def bindPairs(xs):
return lambda f: f(
(
dictFromPairs(xs),
dictFromPairs(
[(b, a) for (a, b) in xs]
)
)
)
def dictFromPairs(xs):
return {
k: [snd(x) for x in m] for k, m in groupby(
sorted(xs, key=fst), key=fst
)
}
def ap(f):
def go(g):
def fxgx(x):
return f(x)(
g(x)
)
return fxgx
return go
def fst(tpl):
return tpl[0]
def snd(tpl):
return tpl[1]
if __name__ == '__main__':
main()
| Python | {
"resource": ""
} |
q598 | Jump anywhere | train |
from goto import goto, label
label .start
for i in range(1, 4):
print i
if i == 2:
try:
output = message
except NameError:
print "Oops - forgot to define 'message'! Start again."
message = "Hello world"
goto .start
print output, "\n"
| Python | {
"resource": ""
} |
q600 | Super-d numbers | train | from itertools import islice, count
def superd(d):
if d != int(d) or not 2 <= d <= 9:
raise ValueError("argument must be integer from 2 to 9 inclusive")
tofind = str(d) * d
for n in count(2):
if tofind in str(d * n ** d):
yield n
if __name__ == '__main__':
for d in range(2, 9):
print(f"{d}:", ', '.join(str(n) for n in islice(superd(d), 10)))
| Python | {
"resource": ""
} |
q602 | Montgomery reduction | train | class Montgomery:
BASE = 2
def __init__(self, m):
self.m = m
self.n = m.bit_length()
self.rrm = (1 << (self.n * 2)) % m
def reduce(self, t):
a = t
for i in xrange(self.n):
if (a & 1) == 1:
a = a + self.m
a = a >> 1
if a >= self.m:
a = a - self.m
return a
m = 750791094644726559640638407699
x1 = 540019781128412936473322405310
x2 = 515692107665463680305819378593
mont = Montgomery(m)
t1 = x1 * mont.rrm
t2 = x2 * mont.rrm
r1 = mont.reduce(t1)
r2 = mont.reduce(t2)
r = 1 << mont.n
print "b : ", Montgomery.BASE
print "n : ", mont.n
print "r : ", r
print "m : ", mont.m
print "t1: ", t1
print "t2: ", t2
print "r1: ", r1
print "r2: ", r2
print
print "Original x1 :", x1
print "Recovered from r1 :", mont.reduce(r1)
print "Original x2 :", x2
print "Recovered from r2 :", mont.reduce(r2)
print "\nMontgomery computation of x1 ^ x2 mod m:"
prod = mont.reduce(mont.rrm)
base = mont.reduce(x1 * mont.rrm)
exp = x2
while exp.bit_length() > 0:
if (exp & 1) == 1:
prod = mont.reduce(prod * base)
exp = exp >> 1
base = mont.reduce(base * base)
print mont.reduce(prod)
print "\nAlternate computation of x1 ^ x2 mod m :"
print pow(x1, x2, m)
| Python | {
"resource": ""
} |
q603 | Smallest power of 6 whose decimal expansion contains n | train | def smallest_six(n):
p = 1
while str(n) not in str(p): p *= 6
return p
for n in range(22):
print("{:2}: {}".format(n, smallest_six(n)))
| Python | {
"resource": ""
} |
q604 | Ludic numbers | train | def ludic(nmax=100000):
yield 1
lst = list(range(2, nmax + 1))
while lst:
yield lst[0]
del lst[::lst[0]]
ludics = [l for l in ludic()]
print('First 25 ludic primes:')
print(ludics[:25])
print("\nThere are %i ludic numbers <= 1000"
% sum(1 for l in ludics if l <= 1000))
print("\n2000'th..2005'th ludic primes:")
print(ludics[2000-1: 2005])
n = 250
triplets = [(x, x+2, x+6)
for x in ludics
if x+6 < n and x+2 in ludics and x+6 in ludics]
print('\nThere are %i triplets less than %i:\n %r'
% (len(triplets), n, triplets))
| Python | {
"resource": ""
} |
q605 | Undefined values | train |
try: name
except NameError: print "name is undefined at first check"
name = "Chocolate"
try: name
except NameError: print "name is undefined at second check"
del name
try: name
except NameError: print "name is undefined at third check"
name = 42
try: name
except NameError: print "name is undefined at fourth check"
print "Done"
| Python | {
"resource": ""
} |
q606 | Iterated digits squaring | train | >>> 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]
| Python | {
"resource": ""
} |
q607 | Longest substrings without repeating characters | train | def longest_substring(s = "xyzyab"):
substr = [s[x:y] for x in range(len(s)) for y in range(x+1, len(s) + 1)]
no_reps = []
for sub in substr:
if len(sub) == len(set(sub)) and sub not in no_reps:
no_reps.append(sub)
max_len = max(len(sub) for sub in no_reps) if no_reps else 0
max_subs = [sub for sub in no_reps if len(sub) == max_len]
return max_subs
if __name__ == '__main__':
for s in ["xyzyabcybdfd", "xyzyab", "zzzzz", "a", "α⊆϶α϶", "",
[1, 2, 3, 4, 1, 2, 5, 6, 1, 7, 8, 1, 0]]:
print(f"{s} => {longest_substring(s)}")
| Python | {
"resource": ""
} |
q608 | Pascal's triangle | train | def pascal(n):
row = [1]
k = [0]
for x in range(max(n,0)):
print row
row=[l+r for l,r in zip(row+k,k+row)]
return n>=1
| Python | {
"resource": ""
} |
q610 | Cumulative standard deviation | train | >>> from math import sqrt
>>> def sd(x):
sd.sum += x
sd.sum2 += x*x
sd.n += 1.0
sum, sum2, n = sd.sum, sd.sum2, sd.n
return sqrt(sum2/n - sum*sum/n/n)
>>> sd.sum = sd.sum2 = sd.n = 0
>>> for value in (2,4,4,4,5,5,7,9):
print (value, sd(value))
(2, 0.0)
(4, 1.0)
(4, 0.94280904158206258)
(4, 0.8660254037844386)
(5, 0.97979589711327075)
(5, 1.0)
(7, 1.3997084244475311)
(9, 2.0)
>>>
| Python | {
"resource": ""
} |
q611 | Atomic updates | train | from __future__ import with_statement
import threading
import random
import time
terminate = threading.Event()
class Buckets:
def __init__(self, nbuckets):
self.nbuckets = nbuckets
self.values = [random.randrange(10) for i in range(nbuckets)]
self.lock = threading.Lock()
def __getitem__(self, i):
return self.values[i]
def transfer(self, src, dst, amount):
with self.lock:
amount = min(amount, self.values[src])
self.values[src] -= amount
self.values[dst] += amount
def snapshot(self):
with self.lock:
return self.values[:]
def randomize(buckets):
nbuckets = buckets.nbuckets
while not terminate.isSet():
src = random.randrange(nbuckets)
dst = random.randrange(nbuckets)
if dst!=src:
amount = random.randrange(20)
buckets.transfer(src, dst, amount)
def equalize(buckets):
nbuckets = buckets.nbuckets
while not terminate.isSet():
src = random.randrange(nbuckets)
dst = random.randrange(nbuckets)
if dst!=src:
amount = (buckets[src] - buckets[dst]) // 2
if amount>=0: buckets.transfer(src, dst, amount)
else: buckets.transfer(dst, src, -amount)
def print_state(buckets):
snapshot = buckets.snapshot()
for value in snapshot:
print '%2d' % value,
print '=', sum(snapshot)
buckets = Buckets(15)
t1 = threading.Thread(target=randomize, args=[buckets])
t1.start()
t2 = threading.Thread(target=equalize, args=[buckets])
t2.start()
try:
while True:
print_state(buckets)
time.sleep(1)
except KeyboardInterrupt:
terminate.set()
t1.join()
t2.join()
| Python | {
"resource": ""
} |
q613 | Chinese zodiac | train |
from __future__ import print_function
from datetime import datetime
pinyin = {
'甲': 'jiă',
'乙': 'yĭ',
'丙': 'bĭng',
'丁': 'dīng',
'戊': 'wù',
'己': 'jĭ',
'庚': 'gēng',
'辛': 'xīn',
'壬': 'rén',
'癸': 'gŭi',
'子': 'zĭ',
'丑': 'chŏu',
'寅': 'yín',
'卯': 'măo',
'辰': 'chén',
'巳': 'sì',
'午': 'wŭ',
'未': 'wèi',
'申': 'shēn',
'酉': 'yŏu',
'戌': 'xū',
'亥': 'hài'
}
animals = ['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake',
'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig']
elements = ['Wood', 'Fire', 'Earth', 'Metal', 'Water']
celestial = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸']
terrestrial = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥']
aspects = ['yang', 'yin']
def calculate(year):
BASE = 4
year = int(year)
cycle_year = year - BASE
stem_number = cycle_year % 10
stem_han = celestial[stem_number]
stem_pinyin = pinyin[stem_han]
element_number = stem_number // 2
element = elements[element_number]
branch_number = cycle_year % 12
branch_han = terrestrial[branch_number]
branch_pinyin = pinyin[branch_han]
animal = animals[branch_number]
aspect_number = cycle_year % 2
aspect = aspects[aspect_number]
index = cycle_year % 60 + 1
print("{}: {}{} ({}-{}, {} {}; {} - year {} of the cycle)"
.format(year, stem_han, branch_han,
stem_pinyin, branch_pinyin, element, animal, aspect, index))
current_year = datetime.now().year
years = [1935, 1938, 1968, 1972, 1976, current_year]
for year in years:
calculate(year)
| Python | {
"resource": ""
} |
q614 | Hofstadter-Conway $10,000 sequence | train | from __future__ import division
def maxandmallows(nmaxpower2):
nmax = 2**nmaxpower2
mx = (0.5, 2)
mxpow2 = []
mallows = None
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)
| Python | {
"resource": ""
} |
q615 | Abundant, deficient and perfect number classifications | train | >>> from proper_divisors import proper_divs
>>> from collections import Counter
>>>
>>> rangemax = 20000
>>>
>>> def pdsum(n):
... return sum(proper_divs(n))
...
>>> def classify(n, p):
... return 'perfect' if n == p else 'abundant' if p > n else 'deficient'
...
>>> classes = Counter(classify(n, pdsum(n)) for n in range(1, 1 + rangemax))
>>> classes.most_common()
[('deficient', 15043), ('abundant', 4953), ('perfect', 4)]
>>>
| Python | {
"resource": ""
} |
q616 | Emirp primes | train | from __future__ import print_function
from prime_decomposition import primes, is_prime
from heapq import *
from itertools import islice
def emirp():
largest = set()
emirps = []
heapify(emirps)
for pr in primes():
while emirps and pr > emirps[0]:
yield heappop(emirps)
if pr in largest:
yield pr
else:
rp = int(str(pr)[::-1])
if rp > pr and is_prime(rp):
heappush(emirps, pr)
largest.add(rp)
print('First 20:\n ', list(islice(emirp(), 20)))
print('Between 7700 and 8000:\n [', end='')
for pr in emirp():
if pr >= 8000: break
if pr >= 7700: print(pr, end=', ')
print(']')
print('10000th:\n ', list(islice(emirp(), 10000-1, 10000)))
| Python | {
"resource": ""
} |
q617 | Run-length encoding | train | def encode(input_string):
count = 1
prev = None
lst = []
for character in input_string:
if character != prev:
if prev:
entry = (prev, count)
lst.append(entry)
count = 1
prev = character
else:
count += 1
else:
try:
entry = (character, count)
lst.append(entry)
return (lst, 0)
except Exception as e:
print("Exception encountered {e}".format(e=e))
return (e, 1)
def decode(lst):
q = []
for character, count in lst:
q.append(character * count)
return ''.join(q)
value = encode("aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa")
if value[1] == 0:
print("Encoded value is {}".format(value[0]))
decode(value[0])
| Python | {
"resource": ""
} |
q618 | Brownian tree | train | SIDESTICK = False
def setup() :
global is_taken
size(512, 512)
background(0)
is_taken = [[False] * height for _ in range(width)]
is_taken[width/2][height/2] = True
def draw() :
x = floor(random(width))
y = floor(random(height))
if is_taken[x][y]:
return
while True:
xp = x + floor(random(-1, 2))
yp = y + floor(random(-1, 2))
is_contained = 0 <= xp < width and 0 <= yp < height
if is_contained and not is_taken[xp][yp]:
x = xp
y = yp
continue
else:
if SIDESTICK or (is_contained and is_taken[xp][yp]):
is_taken[x][y] = True
set(x, y, color(255))
break
if frameCount > width * height:
noLoop()
| Python | {
"resource": ""
} |
q619 | Read a file character by character_UTF8 | train | def get_next_character(f):
c = f.read(1)
while c:
while True:
try:
yield c.decode('utf-8')
except UnicodeDecodeError:
c += f.read(1)
else:
c = f.read(1)
break
with open("input.txt","rb") as f:
for c in get_next_character(f):
print(c)
| Python | {
"resource": ""
} |
q620 | Multiplication tables | train | >>> size = 12
>>> width = len(str(size**2))
>>> for row in range(-1,size+1):
if row==0:
print("─"*width + "┼"+"─"*((width+1)*size-1))
else:
print("".join("%*s%1s" % ((width,) + (("x","│") if row==-1 and col==0
else (row,"│") if row>0 and col==0
else (col,"") if row==-1
else ("","") if row>col
else (row*col,"")))
for col in range(size+1)))
x│ 1 2 3 4 5 6 7 8 9 10 11 12
───┼───────────────────────────────────────────────
1│ 1 2 3 4 5 6 7 8 9 10 11 12
2│ 4 6 8 10 12 14 16 18 20 22 24
3│ 9 12 15 18 21 24 27 30 33 36
4│ 16 20 24 28 32 36 40 44 48
5│ 25 30 35 40 45 50 55 60
6│ 36 42 48 54 60 66 72
7│ 49 56 63 70 77 84
8│ 64 72 80 88 96
9│ 81 90 99 108
10│ 100 110 120
11│ 121 132
12│ 144
>>>
| Python | {
"resource": ""
} |
q621 | Find the intersection of two lines | train | from __future__ import division
def setup():
(a, b), (c, d) = (4, 0), (6, 10)
(e, f), (g, h) = (0, 3), (10, 7)
pt = line_instersect(a, b, c, d, e, f, g, h)
scale(9)
line(a, b, c, d)
line(e, f, g, h)
if pt:
x, y = pt
stroke(255)
point(x, y)
println(pt)
def line_instersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2):
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
| Python | {
"resource": ""
} |
q622 | Loops_Foreach | train | for i in collection:
print i
| Python | {
"resource": ""
} |
q623 | Determine if a string has all unique characters | train |
from itertools import groupby
def duplicatedCharIndices(s):
def go(xs):
if 1 < len(xs):
duplicates = list(filter(lambda kv: 1 < len(kv[1]), [
(k, list(v)) for k, v in groupby(
sorted(xs, key=swap),
key=snd
)
]))
return Just(second(fmap(fst))(
sorted(
duplicates,
key=lambda kv: kv[1][0]
)[0]
)) if duplicates else Nothing()
else:
return Nothing()
return go(list(enumerate(s)))
def main():
def showSample(s):
return repr(s) + ' (' + str(len(s)) + ')'
def showDuplicate(cix):
c, ix = cix
return repr(c) + (
' (' + hex(ord(c)) + ') at ' + repr(ix)
)
print(
fTable('First duplicated character, if any:')(
showSample
)(maybe('None')(showDuplicate))(duplicatedCharIndices)([
'', '.', 'abcABC', 'XYZ ZYX',
'1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'
])
)
def fTable(s):
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
)
def Just(x):
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
def Nothing():
return {'type': 'Maybe', 'Nothing': True}
def fmap(f):
return lambda xs: [f(x) for x in xs]
def fst(tpl):
return tpl[0]
def head(xs):
return xs[0] if isinstance(xs, list) else next(xs)
def maybe(v):
return lambda f: lambda m: v if (
None is m or m.get('Nothing')
) else f(m.get('Just'))
def second(f):
return lambda xy: (xy[0], f(xy[1]))
def snd(tpl):
return tpl[1]
def swap(tpl):
return (tpl[1], tpl[0])
if __name__ == '__main__':
main()
| Python | {
"resource": ""
} |
q624 | Averages_Root mean square | train | sqrt(mean(x²))
| Python | {
"resource": ""
} |
q625 | Range expansion | train | def rangeexpand(txt):
lst = []
for r in txt.split(','):
if '-' in r[1:]:
r0, r1 = r[1:].split('-', 1)
lst += range(int(r[0] + r0), int(r1) + 1)
else:
lst.append(int(r))
return lst
print(rangeexpand('-6,-3--1,3-5,7-11,14,15,17-20'))
| Python | {
"resource": ""
} |
q626 | Burrows–Wheeler transform | train | def bwt(s):
assert "\002" not in s and "\003" not in s, "Input string cannot contain STX and ETX characters"
s = "\002" + s + "\003"
table = sorted(s[i:] + s[:i] for i in range(len(s)))
last_column = [row[-1:] for row in table]
return "".join(last_column)
def ibwt(r):
table = [""] * len(r)
for i in range(len(r)):
table = sorted(r[i] + table[i] for i in range(len(r)))
s = [row for row in table if row.endswith("\003")][0]
return s.rstrip("\003").strip("\002")
| Python | {
"resource": ""
} |
q627 | Visualize a tree | train | Python 3.2.3 (default, May 3 2012, 15:54:42)
[GCC 4.6.3] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> help('pprint.pprint')
Help on function pprint in pprint:
pprint.pprint = pprint(object, stream=None, indent=1, width=80, depth=None)
Pretty-print a Python object to a stream [default is sys.stdout].
>>> from pprint import pprint
>>> for tree in [ (1, 2, 3, 4, 5, 6, 7, 8),
(1, (( 2, 3 ), (4, (5, ((6, 7), 8))))),
((((1, 2), 3), 4), 5, 6, 7, 8) ]:
print("\nTree %r can be pprint'd as:" % (tree, ))
pprint(tree, indent=1, width=1)
Tree (1, 2, 3, 4, 5, 6, 7, 8) can be pprint'd as:
(1,
2,
3,
4,
5,
6,
7,
8)
Tree (1, ((2, 3), (4, (5, ((6, 7), 8))))) can be pprint'd as:
(1,
((2,
3),
(4,
(5,
((6,
7),
8)))))
Tree ((((1, 2), 3), 4), 5, 6, 7, 8) can be pprint'd as:
((((1,
2),
3),
4),
5,
6,
7,
8)
>>>
| Python | {
"resource": ""
} |
q628 | Create an HTML table | train | import random
def rand9999():
return random.randint(1000, 9999)
def tag(attr='', **kwargs):
for tag, txt in kwargs.items():
return '<{tag}{attr}>{txt}</{tag}>'.format(**locals())
if __name__ == '__main__':
header = tag(tr=''.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\n'
rows = '\n'.join(tag(tr=tag(' style="font-weight: bold;"', td=i)
+ ''.join(tag(td=rand9999())
for j in range(3)))
for i in range(1, 6))
table = tag(table='\n' + header + rows + '\n')
print(table)
| Python | {
"resource": ""
} |
q629 | Rosetta Code_Rank languages by popularity | train | import requests
import re
response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3]
response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)
members = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response)
for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]):
if language in languages:
print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))
| Python | {
"resource": ""
} |
q630 | Eban numbers | train |
import inflect
import time
before = time.perf_counter()
p = inflect.engine()
print(' ')
print('eban numbers up to and including 1000:')
print(' ')
count = 0
for i in range(1,1001):
if not 'e' in p.number_to_words(i):
print(str(i)+' ',end='')
count += 1
print(' ')
print(' ')
print('count = '+str(count))
print(' ')
print(' ')
print('eban numbers between 1000 and 4000 (inclusive):')
print(' ')
count = 0
for i in range(1000,4001):
if not 'e' in p.number_to_words(i):
print(str(i)+' ',end='')
count += 1
print(' ')
print(' ')
print('count = '+str(count))
print(' ')
print(' ')
print('eban numbers up to and including 10000:')
print(' ')
count = 0
for i in range(1,10001):
if not 'e' in p.number_to_words(i):
count += 1
print(' ')
print('count = '+str(count))
print(' ')
print(' ')
print('eban numbers up to and including 100000:')
print(' ')
count = 0
for i in range(1,100001):
if not 'e' in p.number_to_words(i):
count += 1
print(' ')
print('count = '+str(count))
print(' ')
print(' ')
print('eban numbers up to and including 1000000:')
print(' ')
count = 0
for i in range(1,1000001):
if not 'e' in p.number_to_words(i):
count += 1
print(' ')
print('count = '+str(count))
print(' ')
print(' ')
print('eban numbers up to and including 10000000:')
print(' ')
count = 0
for i in range(1,10000001):
if not 'e' in p.number_to_words(i):
count += 1
print(' ')
print('count = '+str(count))
print(' ')
after = time.perf_counter()
print(" ")
print("Run time in seconds: "+str(after - before))
| Python | {
"resource": ""
} |
q631 | Exponentiation operator | train | MULTIPLY = lambda x, y: x*y
class num(float):
def __pow__(self, b):
return reduce(MULTIPLY, [self]*b, 1)
print num(2).__pow__(3)
print num(2) ** 3
print num(2.3).__pow__(8)
print num(2.3) ** 8
| Python | {
"resource": ""
} |
q632 | Priority queue | train | >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
| Python | {
"resource": ""
} |
q633 | Days between dates | train |
import sys
def days( y,m,d ):
m = (m + 9) % 12
y = y - m/10
result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
return result
def diff(one,two):
[y1,m1,d1] = one.split('-')
[y2,m2,d2] = two.split('-')
year2 = days( int(y2),int(m2),int(d2))
year1 = days( int(y1), int(m1), int(d1) )
return year2 - year1
if __name__ == "__main__":
one = sys.argv[1]
two = sys.argv[2]
print diff(one,two)
| Python | {
"resource": ""
} |
q634 | GUI enabling_disabling of controls | train |
import tkinter as tk
class MyForm(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.pack(expand=True, fill="both", padx=10, pady=10)
self.master.title("Controls")
self.setupUI()
def setupUI(self):
self.value_entry = tk.Entry(self, justify=tk.CENTER)
self.value_entry.grid(row=0, column=0, columnspan=2,
padx=5, pady=5, sticky="nesw")
self.value_entry.insert('end', '0')
self.value_entry.bind("<KeyPress-Return>", self.eventHandler)
self.decre_btn = tk.Button(self, text="Decrement", state=tk.DISABLED)
self.decre_btn.grid(row=1, column=0, padx=5, pady=5)
self.decre_btn.bind("<Button-1>", self.eventHandler)
self.incre_btn = tk.Button(self, text="Increment")
self.incre_btn.grid(row=1, column=1, padx=5, pady=5)
self.incre_btn.bind("<Button-1>", self.eventHandler)
def eventHandler(self, event):
value = int(self.value_entry.get())
if event.widget == self.value_entry:
if value > 10:
self.value_entry.delete("0", "end")
self.value_entry.insert("end", "0")
elif value == 10:
self.value_entry.config(state=tk.DISABLED)
self.incre_btn.config(state=tk.DISABLED)
self.decre_btn.config(state=tk.NORMAL)
elif value == 0:
self.value_entry.config(state=tk.NORMAL)
self.incre_btn.config(state=tk.NORMAL)
self.decre_btn.config(state=tk.DISABLED)
elif (value > 0) and (value < 10):
self.value_entry.config(state=tk.DISABLED)
self.incre_btn.config(state=tk.NORMAL)
self.decre_btn.config(state=tk.NORMAL)
else:
if event.widget == self.incre_btn:
if (value >= 0) and (value < 10):
value += 1
self.value_entry.config(state=tk.NORMAL)
self.value_entry.delete("0", "end")
self.value_entry.insert("end", str(value))
if value > 0:
self.decre_btn.config(state=tk.NORMAL)
self.value_entry.config(state=tk.DISABLED)
if value == 10:
self.incre_btn.config(state=tk.DISABLED)
elif event.widget == self.decre_btn:
if (value > 0) and (value <= 10):
value -= 1
self.value_entry.config(state=tk.NORMAL)
self.value_entry.delete("0", "end")
self.value_entry.insert("end", str(value))
self.value_entry.config(state=tk.DISABLED)
if (value) < 10:
self.incre_btn.config(state=tk.NORMAL)
if (value) == 0:
self.decre_btn.config(state=tk.DISABLED)
self.value_entry.config(state=tk.NORMAL)
def main():
app = MyForm()
app.mainloop()
if __name__ == "__main__":
main()
| Python | {
"resource": ""
} |
q636 | Mad Libs | train | import re
template =
def madlibs(template):
print('The story template is:\n' + template)
fields = sorted(set( re.findall('<[^>]+>', template) ))
values = input('\nInput a comma-separated list of words to replace the following items'
'\n %s: ' % ','.join(fields)).split(',')
story = template
for f,v in zip(fields, values):
story = story.replace(f, v)
print('\nThe story becomes:\n\n' + story)
madlibs(template)
| Python | {
"resource": ""
} |
q637 | Polymorphic copy | train | import copy
class T:
def classname(self):
return self.__class__.__name__
def __init__(self):
self.myValue = "I'm a T."
def speak(self):
print self.classname(), 'Hello', self.myValue
def clone(self):
return copy.copy(self)
class S1(T):
def speak(self):
print self.classname(),"Meow", self.myValue
class S2(T):
def speak(self):
print self.classname(),"Woof", self.myValue
print "creating initial objects of types S1, S2, and T"
a = S1()
a.myValue = 'Green'
a.speak()
b = S2()
b.myValue = 'Blue'
b.speak()
u = T()
u.myValue = 'Purple'
u.speak()
print "Making copy of a as u, colors and types should match"
u = a.clone()
u.speak()
a.speak()
print "Assigning new color to u, A's color should be unchanged."
u.myValue = "Orange"
u.speak()
a.speak()
print "Assigning u to reference same object as b, colors and types should match"
u = b
u.speak()
b.speak()
print "Assigning new color to u. Since u,b references same object b's color changes as well"
u.myValue = "Yellow"
u.speak()
b.speak()
| Python | {
"resource": ""
} |
q638 | Pangram checker | train | import string, sys
if sys.version_info[0] < 3:
input = raw_input
def ispangram(sentence, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
return alphaset <= set(sentence.lower())
print ( ispangram(input('Sentence: ')) )
| Python | {
"resource": ""
} |
q639 | Show ASCII table | train | for i in range(16):
for j in range(32+i, 127+1, 16):
if j == 32:
k = 'Spc'
elif j == 127:
k = 'Del'
else:
k = chr(j)
print("%3d : %-3s" % (j,k), end="")
print()
| Python | {
"resource": ""
} |
q641 | Fraction reduction | train | def indexOf(haystack, needle):
idx = 0
for straw in haystack:
if straw == needle:
return idx
else:
idx += 1
return -1
def getDigits(n, le, digits):
while n > 0:
r = n % 10
if r == 0 or indexOf(digits, r) >= 0:
return False
le -= 1
digits[le] = r
n = int(n / 10)
return True
def removeDigit(digits, le, idx):
pows = [1, 10, 100, 1000, 10000]
sum = 0
pow = pows[le - 2]
i = 0
while i < le:
if i == idx:
i += 1
continue
sum = sum + digits[i] * pow
pow = int(pow / 10)
i += 1
return sum
def main():
lims = [ [ 12, 97 ], [ 123, 986 ], [ 1234, 9875 ], [ 12345, 98764 ] ]
count = [0 for i in range(5)]
omitted = [[0 for i in range(10)] for j in range(5)]
i = 0
while i < len(lims):
n = lims[i][0]
while n < lims[i][1]:
nDigits = [0 for k in range(i + 2)]
nOk = getDigits(n, i + 2, nDigits)
if not nOk:
n += 1
continue
d = n + 1
while d <= lims[i][1] + 1:
dDigits = [0 for k in range(i + 2)]
dOk = getDigits(d, i + 2, dDigits)
if not dOk:
d += 1
continue
nix = 0
while nix < len(nDigits):
digit = nDigits[nix]
dix = indexOf(dDigits, digit)
if dix >= 0:
rn = removeDigit(nDigits, i + 2, nix)
rd = removeDigit(dDigits, i + 2, dix)
if (1.0 * n / d) == (1.0 * rn / rd):
count[i] += 1
omitted[i][digit] += 1
if count[i] <= 12:
print "%d/%d = %d/%d by omitting %d's" % (n, d, rn, rd, digit)
nix += 1
d += 1
n += 1
print
i += 1
i = 2
while i <= 5:
print "There are %d %d-digit fractions of which:" % (count[i - 2], i)
j = 1
while j <= 9:
if omitted[i - 2][j] == 0:
j += 1
continue
print "%6s have %d's omitted" % (omitted[i - 2][j], j)
j += 1
print
i += 1
return None
main()
| Python | {
"resource": ""
} |
q642 | Anagrams_Deranged anagrams | train | import urllib.request
from collections import defaultdict
from itertools import combinations
def getwords(url='http://www.puzzlers.org/pub/wordlists/unixdict.txt'):
return list(set(urllib.request.urlopen(url).read().decode().split()))
def find_anagrams(words):
anagram = defaultdict(list)
for word in words:
anagram[tuple(sorted(word))].append( word )
return dict((key, words) for key, words in anagram.items()
if len(words) > 1)
def is_deranged(words):
'returns pairs of words that have no character in the same position'
return [ (word1, word2)
for word1,word2 in combinations(words, 2)
if all(ch1 != ch2 for ch1, ch2 in zip(word1, word2)) ]
def largest_deranged_ana(anagrams):
ordered_anagrams = sorted(anagrams.items(),
key=lambda x:(-len(x[0]), x[0]))
for _, words in ordered_anagrams:
deranged_pairs = is_deranged(words)
if deranged_pairs:
return deranged_pairs
return []
if __name__ == '__main__':
words = getwords('http://www.puzzlers.org/pub/wordlists/unixdict.txt')
print("Word count:", len(words))
anagrams = find_anagrams(words)
print("Anagram count:", len(anagrams),"\n")
print("Longest anagrams with no characters in the same position:")
print(' ' + '\n '.join(', '.join(pairs)
for pairs in largest_deranged_ana(anagrams)))
| Python | {
"resource": ""
} |
q643 | Negative base numbers | train |
from __future__ import print_function
def EncodeNegBase(n, b):
if n == 0:
return "0"
out = []
while n != 0:
n, rem = divmod(n, b)
if rem < 0:
n += 1
rem -= b
out.append(rem)
return "".join(map(str, out[::-1]))
def DecodeNegBase(nstr, b):
if nstr == "0":
return 0
total = 0
for i, ch in enumerate(nstr[::-1]):
total += int(ch) * b**i
return total
if __name__=="__main__":
print ("Encode 10 as negabinary (expect 11110)")
result = EncodeNegBase(10, -2)
print (result)
if DecodeNegBase(result, -2) == 10: print ("Converted back to decimal")
else: print ("Error converting back to decimal")
print ("Encode 146 as negaternary (expect 21102)")
result = EncodeNegBase(146, -3)
print (result)
if DecodeNegBase(result, -3) == 146: print ("Converted back to decimal")
else: print ("Error converting back to decimal")
print ("Encode 15 as negadecimal (expect 195)")
result = EncodeNegBase(15, -10)
print (result)
if DecodeNegBase(result, -10) == 15: print ("Converted back to decimal")
else: print ("Error converting back to decimal")
| Python | {
"resource": ""
} |
q644 | Strange numbers | train |
def isStrange(n):
def test(a, b):
return abs(a - b) in [2, 3, 5, 7]
xs = digits(n)
return all(map(test, xs, xs[1:]))
def main():
xs = [
n for n in range(100, 1 + 500)
if isStrange(n)
]
print('\nStrange numbers in range [100..500]\n')
print('(Total: ' + str(len(xs)) + ')\n')
print(
'\n'.join(
' '.join(
str(x) for x in row
) for row in chunksOf(10)(xs)
)
)
def chunksOf(n):
def go(xs):
return (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
def digits(n):
return [int(c) for c in str(n)]
if __name__ == '__main__':
main()
| Python | {
"resource": ""
} |
q645 | Shortest common supersequence | train |
def shortest_common_supersequence(a, b):
lcs = longest_common_subsequence(a, b)
scs = ""
while len(lcs) > 0:
if a[0]==lcs[0] and b[0]==lcs[0]:
scs += lcs[0]
lcs = lcs[1:]
a = a[1:]
b = b[1:]
elif a[0]==lcs[0]:
scs += b[0]
b = b[1:]
else:
scs += a[0]
a = a[1:]
return scs + a + b
| Python | {
"resource": ""
} |
q646 | Queue_Usage | train | let my_queue = Queue()
my_queue.push!('foo')
my_queue.push!('bar')
my_queue.push!('baz')
print my_queue.pop!()
print my_queue.pop!()
print my_queue.pop!()
| Python | {
"resource": ""
} |
q647 | Random number generator (device) | train | import random
rand = random.SystemRandom()
rand.randint(1,10)
| Python | {
"resource": ""
} |
q648 | Anti-primes | train | from itertools import chain, count, cycle, islice, accumulate
def factors(n):
def prime_powers(n):
for c in accumulate(chain([2, 1, 2], cycle([2,4]))):
if c*c > n: break
if n%c: continue
d,p = (), c
while not n%c:
n,p,d = n//c, p*c, d+(p,)
yield d
if n > 1: yield n,
r = [1]
for e in prime_powers(n):
r += [a*b for a in r for b in e]
return r
def antiprimes():
mx = 0
yield 1
for c in count(2,2):
if c >= 58: break
ln = len(factors(c))
if ln > mx:
yield c
mx = ln
for c in count(60,30):
ln = len(factors(c))
if ln > mx:
yield c
mx = ln
if __name__ == '__main__':
print(*islice(antiprimes(), 40)))
| Python | {
"resource": ""
} |
q649 | Towers of Hanoi | train |
நிரல்பாகம் ஹோனாய்(வட்டுகள், முதல்அச்சு, இறுதிஅச்சு,வட்டு)
@(வட்டுகள் == 1 ) ஆனால்
பதிப்பி “வட்டு ” + str(வட்டு) + “ஐ \t (” + str(முதல்அச்சு) + “ —> ” + str(இறுதிஅச்சு)+ “) அச்சிற்கு நகர்த்துக.”
இல்லை
@( ["இ", "அ", "ஆ"] இல் அச்சு ) ஒவ்வொன்றாக
@( (முதல்அச்சு != அச்சு) && (இறுதிஅச்சு != அச்சு) ) ஆனால்
நடு = அச்சு
முடி
முடி
ஹோனாய்(வட்டுகள்-1, முதல்அச்சு,நடு,வட்டுகள்-1)
ஹோனாய்(1, முதல்அச்சு, இறுதிஅச்சு,வட்டுகள்)
ஹோனாய்(வட்டுகள்-1, நடு, இறுதிஅச்சு,வட்டுகள்-1)
முடி
முடி
ஹோனாய்(4,”அ”,”ஆ”,0)
| Python | {
"resource": ""
} |
q650 | Count in octal | train | import sys
for n in xrange(sys.maxint):
print oct(n)
| Python | {
"resource": ""
} |
q651 | Extract file extension | train | import re
def extractExt(url):
m = re.search(r'\.[A-Za-z0-9]+$', url)
return m.group(0) if m else ""
| Python | {
"resource": ""
} |
q652 | Orbital elements | train | import math
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
def __mul__(self, other):
return Vector(self.x * other, self.y * other, self.z * other)
def __div__(self, other):
return Vector(self.x / other, self.y / other, self.z / other)
def __str__(self):
return '({x}, {y}, {z})'.format(x=self.x, y=self.y, z=self.z)
def abs(self):
return math.sqrt(self.x*self.x + self.y*self.y + self.z*self.z)
def mulAdd(v1, x1, v2, x2):
return v1 * x1 + v2 * x2
def rotate(i, j, alpha):
return [mulAdd(i,math.cos(alpha),j,math.sin(alpha)), mulAdd(i,-math.sin(alpha),j,math.cos(alpha))]
def orbitalStateVectors(semimajorAxis, eccentricity, inclination, longitudeOfAscendingNode, argumentOfPeriapsis, trueAnomaly):
i = Vector(1, 0, 0)
j = Vector(0, 1, 0)
k = Vector(0, 0, 1)
p = rotate(i, j, longitudeOfAscendingNode)
i = p[0]
j = p[1]
p = rotate(j, k, inclination)
j = p[0]
p =rotate(i, j, argumentOfPeriapsis)
i = p[0]
j = p[1]
l = 2.0 if (eccentricity == 1.0) else 1.0 - eccentricity * eccentricity
l *= semimajorAxis
c = math.cos(trueAnomaly)
s = math.sin(trueAnomaly)
r = 1 / (1.0 + eccentricity * c)
rprime = s * r * r / l
position = mulAdd(i, c, j, s) * r
speed = mulAdd(i, rprime * c - r * s, j, rprime * s + r * c)
speed = speed / speed.abs()
speed = speed * math.sqrt(2.0 / r - 1.0 / semimajorAxis)
return [position, speed]
ps = orbitalStateVectors(1.0, 0.1, 0.0, 355.0 / (113.0 * 6.0), 0.0, 0.0)
print "Position :", ps[0]
print "Speed :", ps[1]
| Python | {
"resource": ""
} |
q653 | Floyd's triangle | train | >>> 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
>>>
| Python | {
"resource": ""
} |
q654 | Calendar | train | >>> import calendar
>>> help(calendar.prcal)
Help on method pryear in module calendar:
pryear(self, theyear, w=0, l=0, c=6, m=3) method of calendar.TextCalendar instance
Print a years calendar.
>>> calendar.prcal(1969)
1969
January February March
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 1 2 1 2
6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9
13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16
20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23
27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30
31
April May June
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 1 2 3 4 1
7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8
14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15
21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22
28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29
30
July August September
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7
7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14
14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21
21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28
28 29 30 31 25 26 27 28 29 30 31 29 30
October November December
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 1 2 1 2 3 4 5 6 7
6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14
13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21
20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28
27 28 29 30 31 24 25 26 27 28 29 30 29 30 31
| Python | {
"resource": ""
} |
q655 | Random Latin squares | train | from random import choice, shuffle
from copy import deepcopy
def rls(n):
if n <= 0:
return []
else:
symbols = list(range(n))
square = _rls(symbols)
return _shuffle_transpose_shuffle(square)
def _shuffle_transpose_shuffle(matrix):
square = deepcopy(matrix)
shuffle(square)
trans = list(zip(*square))
shuffle(trans)
return trans
def _rls(symbols):
n = len(symbols)
if n == 1:
return [symbols]
else:
sym = choice(symbols)
symbols.remove(sym)
square = _rls(symbols)
square.append(square[0].copy())
for i in range(n):
square[i].insert(i, sym)
return square
def _to_text(square):
if square:
width = max(len(str(sym)) for row in square for sym in row)
txt = '\n'.join(' '.join(f"{sym:>{width}}" for sym in row)
for row in square)
else:
txt = ''
return txt
def _check(square):
transpose = list(zip(*square))
assert _check_rows(square) and _check_rows(transpose), \
"Not a Latin square"
def _check_rows(square):
if not square:
return True
set_row0 = set(square[0])
return all(len(row) == len(set(row)) and set(row) == set_row0
for row in square)
if __name__ == '__main__':
for i in [3, 3, 5, 5, 12]:
square = rls(i)
print(_to_text(square))
_check(square)
print()
| Python | {
"resource": ""
} |