Dataset Viewer
Auto-converted to Parquet Duplicate
_id
stringlengths
2
5
title
stringlengths
2
76
partition
stringclasses
3 values
text
stringlengths
8
6.97k
language
stringclasses
1 value
meta_information
dict
q47
Stack
test
from collections import deque stack = deque() stack.append(value) value = stack.pop() not stack
Python
{ "resource": "" }
q91
Carmichael 3 strong pseudoprimes
test
class Isprime(): multiples = {2} primes = [2] nmax = 2 def __init__(self, nmax): if nmax > self.nmax: self.check(nmax) def check(self, n): if type(n) == float: if not n.is_integer(): return False n = int(n) multiples = self.multi...
Python
{ "resource": "" }
q92
Image noise
test
black = color(0) white = color(255) def setup(): size(320, 240) def draw(): loadPixels() for i in range(len(pixels)): if random(1) < 0.5: pixels[i] = black else: pixels[i] = white updatePixels() fill(0, 128) rect(0, 0, 60, 20) fill(255) te...
Python
{ "resource": "" }
q93
Keyboard input_Obtain a Y or N response
test
try: from msvcrt import getch except ImportError: def getch(): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr...
Python
{ "resource": "" }
q94
Perfect numbers
test
def perf1(n): sum = 0 for i in range(1, n): if n % i == 0: sum += i return sum == n
Python
{ "resource": "" }
q95
Conjugate transpose
test
def conjugate_transpose(m): return tuple(tuple(n.conjugate() for n in row) for row in zip(*m)) def mmul( ma, mb): return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma) def mi(size): 'Complex Identity matrix' sz = range(size) m = [[0 + 0j for i in sz] for j in sz] ...
Python
{ "resource": "" }
q96
Jacobsthal numbers
test
from math import floor, pow def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def odd(n): return n and 1 != 0 def jacobsthal(n): return floor((pow(2,n)+odd(n))/3) def jacobsthal_lucas(n): return int(pow(2,n)+pow(-1,n)) d...
Python
{ "resource": "" }
q97
Sorting algorithms_Bead sort
test
from itertools import zip_longest def beadsort(l): return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0))) print(beadsort([5,3,1,7,4,1,1]))
Python
{ "resource": "" }
q98
Cistercian numerals
test
def _init(): "digit sections for forming numbers" digi_bits = .strip() lines = [[d.replace('.', ' ') for d in ln.strip().split()] for ln in digi_bits.strip().split('\n') if ' formats = '<2 >2 <2 >2'.split() digits = [[f"{dig:{f}}" for dig in line] for f,...
Python
{ "resource": "" }
q99
Arbitrary-precision integers (included)
test
>>> y = str( 5**4**3**2 ) >>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y))) 5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
Python
{ "resource": "" }
q100
Draw a sphere
test
import math shades = ('.',':','!','*','o','e','&',' def normalize(v): len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2) return (v[0]/len, v[1]/len, v[2]/len) def dot(x,y): d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2] return -d if d < 0 else 0 def draw_sphere(r, k, ambient, light): for i in range(int(math.floor(-r)),int(ma...
Python
{ "resource": "" }
q101
Inverted index
test
from pprint import pprint as pp from glob import glob try: reduce except: from functools import reduce try: raw_input except: raw_input = input def parsetexts(fileglob='InvertedIndex/T*.txt'): texts, words = {}, set() for txtfile in glob(fileglob): with open(txtfile, 'r') as f: txt = ...
Python
{ "resource": "" }
q102
Least common multiple
test
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Python
{ "resource": "" }
q103
Fermat numbers
test
def factors(x): factors = [] i = 2 s = int(x ** 0.5) while i < s: if x % i == 0: factors.append(i) x = int(x / i) s = int(x ** 0.5) i += 1 factors.append(x) return factors print("First 10 Fermat numbers:") for i in range(10): fermat = 2 **...
Python
{ "resource": "" }
q104
Loops_Break
test
from random import randrange while True: a = randrange(20) print(a) if a == 10: break b = randrange(20) print(b)
Python
{ "resource": "" }
q105
Hello world_Line printer
test
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
Python
{ "resource": "" }
q106
Water collected between towers
test
def water_collected(tower): N = len(tower) highest_left = [0] + [max(tower[:n]) for n in range(1,N)] highest_right = [max(tower[n:N]) for n in range(1,N)] + [0] water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0) for n in range(N)] print("highest_left: ", highest_left) ...
Python
{ "resource": "" }
q107
Descending primes
test
from sympy import isprime def descending(xs=range(10)): for x in xs: yield x yield from descending(x*10 + d for d in range(x%10)) for i, p in enumerate(sorted(filter(isprime, descending()))): print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n') print()
Python
{ "resource": "" }
q108
Square-free integers
test
import math def SquareFree ( _number ) : max = (int) (math.sqrt ( _number )) for root in range ( 2, max+1 ): if 0 == _number % ( root * root ): return False return True def ListSquareFrees( _start, _end ): count = 0 for i in range ( _start, _end+1 ): if True == SquareFree( i ): print ( "{}\t".fo...
Python
{ "resource": "" }
q109
Jaro similarity
test
from __future__ import division def jaro(s, t): s_len = len(s) t_len = len(t) if s_len == 0 and t_len == 0: return 1 match_distance = (max(s_len, t_len) // 2) - 1 s_matches = [False] * s_len t_matches = [False] * t_len matches = 0 transpositions = 0 for i in ran...
Python
{ "resource": "" }
q110
Sum and product puzzle
test
from collections import Counter def decompose_sum(s): return [(a,s-a) for a in range(2,int(s/2+1))] all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100) product_counts = Counter(c*d for c,d in all_pairs) unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1) s_...
Python
{ "resource": "" }
q111
Fairshare between two and more
test
from itertools import count, islice def _basechange_int(num, b): 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 __na...
Python
{ "resource": "" }
q112
Two bullet roulette
test
import numpy as np class Revolver: def __init__(self): self.cylinder = np.array([False] * 6) def unload(self): self.cylinder[:] = False def load(self): while self.cylinder[1]: self.cylinder[:] = np.roll(self.cylinder, 1) self.c...
Python
{ "resource": "" }
q113
Parsing_Shunting-yard algorithm
test
from collections import namedtuple from pprint import pprint as pp OpInfo = namedtuple('OpInfo', 'prec assoc') L, R = 'Left Right'.split() ops = { '^': OpInfo(prec=4, assoc=R), '*': OpInfo(prec=3, assoc=L), '/': OpInfo(prec=3, assoc=L), '+': OpInfo(prec=2, assoc=L), '-': OpInfo(prec=2, assoc=L), '(': OpInfo(pre...
Python
{ "resource": "" }
q114
Trabb Pardoโ€“Knuth algorithm
test
Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def f(x): return abs(x) ** 0.5 + 5 * x**3 >>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!") for x,v in ((y, f(float(y))) for y in input('\nn...
Python
{ "resource": "" }
q115
Middle three digits
test
>>> def middle_three_digits(i): s = str(abs(i)) length = len(s) assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits" mid = length // 2 return s[mid-1:mid+2] >>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] >>> failing = [1, 2, -1, -10, 2002, -2002, 0] >>> for x ...
Python
{ "resource": "" }
q116
Sequence_ nth number with exactly n divisors
test
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def is_prime(n): return len(divisors(n)) == 2 def primes(): ii = 1 while True: ii += 1...
Python
{ "resource": "" }
q117
Sequence_ smallest number with exactly n divisors
test
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def sequence(max_n=None): n = 0 while True: n += 1 ii = 0 if max_n is not No...
Python
{ "resource": "" }
q118
Pancake numbers
test
import time from collections import deque from operator import itemgetter from typing import Tuple Pancakes = Tuple[int, ...] def flip(pancakes: Pancakes, position: int) -> Pancakes: return tuple([*reversed(pancakes[:position]), *pancakes[position:]]) def pancake(n: int) -> Tuple[Pancakes, int]: ...
Python
{ "resource": "" }
q119
Generate random chess position
test
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)...
Python
{ "resource": "" }
q120
Esthetic numbers
test
from collections import deque from itertools import dropwhile, islice, takewhile from textwrap import wrap from typing import Iterable, Iterator Digits = str def esthetic_nums(base: int) -> Iterator[int]: queue: deque[tuple[int, int]] = deque() queue.extendleft((d, d) for d in range(1, base)) whi...
Python
{ "resource": "" }
q121
Topswops
test
>>> from itertools import permutations >>> def f1(p): i = 0 while True: p0 = p[0] if p0 == 1: break p[:p0] = p[:p0][::-1] i += 1 return i >>> def fannkuch(n): return max(f1(list(p)) for p in permutations(range(1, n+1))) >>> for n in range(1, 11): print(n,fannkuch(n)) 1 0 2 1 3 2 4 4 5 7 6 10 7 16 8 22 ...
Python
{ "resource": "" }
q122
Old Russian measure of length
test
from sys import argv unit2mult = {"arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254, "fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254, "meter": 1.0, "milia": 7467.6, "piad": 0.1778, "sazhen": 2.1336, "tochka": 0.000254, "vershok": 0.04445,...
Python
{ "resource": "" }
q123
Rate counter
test
import subprocess import time class Tlogger(object): def __init__(self): self.counts = 0 self.tottime = 0.0 self.laststart = 0.0 self.lastreport = time.time() def logstart(self): self.laststart = time.time() def logend(self): self.counts +=1 self.to...
Python
{ "resource": "" }
q124
Sequence_ smallest number greater than previous term with exactly n divisors
test
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def sequence(max_n=None): previous = 0 n = 0 while True: n += 1 ii = previous ...
Python
{ "resource": "" }
q125
Padovan sequence
test
from math import floor from collections import deque from typing import Dict, Generator def padovan_r() -> Generator[int, None, None]: last = deque([1, 1, 1], 4) while True: last.append(last[-2] + last[-3]) yield last.popleft() _p, _s = 1.324717957244746025960908854, 1.0453567932525329623 de...
Python
{ "resource": "" }
q126
Pythagoras tree
test
def setup(): size(800, 400) background(255) stroke(0, 255, 0) tree(width / 2.3, height, width / 1.8, height, 10) def tree(x1, y1, x2, y2, depth): if depth <= 0: return dx = (x2 - x1) dy = (y1 - y2) x3 = (x2 - dy) y3 = (y2 - dx) x4 = (x1 - dy) y4 = (y1 - dx) x5 = (x4 + ...
Python
{ "resource": "" }
q127
Odd word problem
test
from sys import stdin, stdout def char_in(): return stdin.read(1) def char_out(c): stdout.write(c) def odd(prev = lambda: None): a = char_in() if not a.isalpha(): prev() char_out(a) return a != '.' def clos(): char_out(a) prev() return odd(clos) def even(): while True: c = char_in() char_out(c...
Python
{ "resource": "" }
q128
Pseudo-random numbers_Combined recursive generator MRG32k3a
test
a1 = [0, 1403580, -810728] m1 = 2**32 - 209 a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a(): def __init__(self, seed_state=123): self.seed(seed_state) def seed(self, seed_state): assert 0 <seed_state < d, f"Out of Range 0 x < {d}" self.x1 = [seed_s...
Python
{ "resource": "" }
q129
Stern-Brocot sequence
test
def stern_brocot(predicate=lambda series: len(series) < 20): sb, i = [1, 1], 0 while predicate(sb): sb += [sum(sb[i:i + 2]), sb[i + 1]] i += 1 return sb if __name__ == '__main__': from fractions import gcd n_first = 15 print('The first %i values:\n ' % n_first, ...
Python
{ "resource": "" }
q130
Numeric error propagation
test
from collections import namedtuple import math class I(namedtuple('Imprecise', 'value, delta')): 'Imprecise type: I(value=0.0, delta=0.0)' __slots__ = () def __new__(_cls, value=0.0, delta=0.0): 'Defaults to 0.0 ยฑ delta' return super().__new__(_cls, float(value), abs(float(delta))) ...
Python
{ "resource": "" }
q131
List rooted trees
test
def bags(n,cache={}): if not n: return [(0, "")] upto = sum([bags(x) for x in range(n-1, 0, -1)], []) return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)] def bagchain(x, n, bb, start=0): if not n: return [x] out = [] for i in range(start, len(bb)): c,s = bb[i] if c <= n: out += bagchain((x[0]...
Python
{ "resource": "" }
q132
Longest common suffix
test
from itertools import takewhile from functools import reduce def longestCommonSuffix(xs): def allSame(cs): h = cs[0] return all(h == c for c in cs[1:]) def firstCharPrepended(s, cs): return cs[0] + s return reduce( firstCharPrepended, takewhile( ...
Python
{ "resource": "" }
q133
Sum of elements below main diagonal of matrix
test
from numpy import array, tril, sum A = [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]] print(sum(tril(A, -1)))
Python
{ "resource": "" }
q134
FASTA format
test
import io FASTA= 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: ...
Python
{ "resource": "" }
q135
Elementary cellular automaton_Random number generator
test
from elementary_cellular_automaton import eca, eca_wrap def rule30bytes(lencells=100): cells = '1' + '0' * (lencells - 1) gen = eca(cells, 30) while True: yield int(''.join(next(gen)[0] for i in range(8)), 2) if __name__ == '__main__': print([b for i,b in zip(range(10), rule30bytes())])
Python
{ "resource": "" }
q136
Pseudo-random numbers_PCG32
test
mask64 = (1 << 64) - 1 mask32 = (1 << 32) - 1 CONST = 6364136223846793005 class PCG32(): def __init__(self, seed_state=None, seed_sequence=None): if all(type(x) == int for x in (seed_state, seed_sequence)): self.seed(seed_state, seed_sequence) else: self.state = self.i...
Python
{ "resource": "" }
q137
Sierpinski pentagon
test
from turtle import * import math speed(0) hideturtle() part_ratio = 2 * math.cos(math.radians(72)) side_ratio = 1 / (part_ratio + 2) hide_turtles = True path_color = "black" fill_color = "black" def pentagon(t, s): t.color(path_color, fill_color) t.pendown() t.right(36) t.begin_fill() for i...
Python
{ "resource": "" }
q138
Rep-string
test
def is_repeated(text): 'check if the first part of the string is repeated throughout the string' for x in range(len(text)//2, 0, -1): if text.startswith(text[x:]): return x return 0 matchstr = for line in matchstr.split(): ln = is_repeated(line) print('%r has a repetition length of %i i.e....
Python
{ "resource": "" }
q139
Changeable words
test
from collections import defaultdict, Counter def getwords(minlength=11, fname='unixdict.txt'): "Return set of lowercased words of > given number of characters" with open(fname) as f: words = f.read().strip().lower().split() return {w for w in words if len(w) > minlength} words11 = getwords() word...
Python
{ "resource": "" }
q140
Monads_List monad
test
from __future__ import annotations from itertools import chain from typing import Any from typing import Callable from typing import Iterable from typing import List from typing import TypeVar T = TypeVar("T") class MList(List[T]): @classmethod def unit(cls, value: Iterable[T]) -> MList[T]: return...
Python
{ "resource": "" }
q141
Special factorials
test
from math import prod def superFactorial(n): return prod([prod(range(1,i+1)) for i in range(1,n+1)]) def hyperFactorial(n): return prod([i**i for i in range(1,n+1)]) def alternatingFactorial(n): return sum([(-1)**(n-i)*prod(range(1,i+1)) for i in range(1,n+1)]) def exponentialFactorial(n): if n in...
Python
{ "resource": "" }
q142
Four is magic
test
import random from collections import OrderedDict numbers = { 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: 's...
Python
{ "resource": "" }
q143
Getting the number of decimals
test
In [6]: def dec(n): ...: return len(n.rsplit('.')[-1]) if '.' in n else 0 In [7]: dec('12.345') Out[7]: 3 In [8]: dec('12.3450') Out[8]: 4 In [9]:
Python
{ "resource": "" }
q144
Parse an IP Address
test
from ipaddress import ip_address from urllib.parse import urlparse tests = [ "127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "::192.168.0.1", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80" ] def parse_ip_port(netloc): try: ip = ip_address(netloc) port = Non...
Python
{ "resource": "" }
q145
Textonyms
test
from collections import defaultdict import urllib.request CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars} URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt' def getwords(url): return urllib.request.urlopen(url).read().decode("utf-8").lower(...
Python
{ "resource": "" }
q146
Teacup rim text
test
from itertools import chain, groupby from os.path import expanduser from functools import reduce def main(): print('\n'.join( concatMap(circularGroup)( anagrams(3)( lines(readFile('~/mitWords.txt')) ) ) )) def anagrams(n): ...
Python
{ "resource": "" }
q147
Increasing gaps between consecutive Niven numbers
test
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) ...
Python
{ "resource": "" }
q148
Print debugging statement
test
import logging, logging.handlers LOG_FILENAME = "logdemo.log" FORMAT_STRING = "%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s" LOGLEVEL = logging.DEBUG def print_squares(number): logger.info("In print_squares") for i in range(number): print("square of {0} is {1}".format(...
Python
{ "resource": "" }
q149
Range extraction
test
def range_extract(lst): 'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints' lenlst = len(lst) i = 0 while i< lenlst: low = lst[i] while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1 hi = lst[i] if hi - low >= 2: yield (low, hi) ...
Python
{ "resource": "" }
q150
Maximum triangle path sum
test
fun maxpathsum(t): let a = val t for i in a.length-1..-1..1, c in linearindices a[r]: a[r, c] += max(a[r+1, c], a[r=1, c+1]) return a[1, 1] let test = [ [55], [94, 48], [95, 30, 96], [77, 71, 26, 67], [97, 13, 76, 38, 45], [07, 36, 79, 16, 37, 68], [48, 07, 09, 18, 70, ...
Python
{ "resource": "" }
q151
Variable declaration reset
test
s = [1, 2, 2, 3, 4, 4, 5] for i in range(len(s)): curr = s[i] if i > 0 and curr == prev: print(i) prev = curr
Python
{ "resource": "" }
q152
Numbers with equal rises and falls
test
import itertools def riseEqFall(num): height = 0 d1 = num % 10 num //= 10 while num: d2 = num % 10 height += (d1<d2) - (d1>d2) d1 = d2 num //= 10 return height == 0 def sequence(start, fn): num=start-1 while True: num += 1 while...
Python
{ "resource": "" }
q153
Koch curve
test
l = 300 def setup(): size(400, 400) background(0, 0, 255) stroke(255) translate(width / 2.0, height / 2.0) translate(-l / 2.0, l * sqrt(3) / 6.0) for i in range(4): kcurve(0, l) rotate(radians(120)) translate(-l, 0) def kcurve(x1, x2): s = (x2 - x1) / 3.0...
Python
{ "resource": "" }
q154
Words from neighbour ones
test
import urllib.request from collections import Counter urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() filteredWords = [chosenWord for chosenWord in wordList if ...
Python
{ "resource": "" }
q155
Magic squares of singly even order
test
import math from sys import stdout LOG_10 = 2.302585092994 def build_oms(s): if s % 2 == 0: s += 1 q = [[0 for j in range(s)] for i in range(s)] p = 1 i = s // 2 j = 0 while p <= (s * s): q[i][j] = p ti = i + 1 if ti >= s: ti = 0 tj = j - 1 if ...
Python
{ "resource": "" }
q156
Generate Chess960 starting position
test
>>> from itertools import permutations >>> pieces = 'KQRrBbNN' >>> starts = {''.join(p).upper() for p in permutations(pieces) if p.index('B') % 2 != p.index('b') % 2 and ( p.index('r') < p.index('K') < p.index('R') or p.index('R') < p.index('K') <...
Python
{ "resource": "" }
q157
File size distribution
test
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)...
Python
{ "resource": "" }
q158
Unix_ls
test
>>> import os >>> print('\n'.join(sorted(os.listdir('.')))) DLLs Doc LICENSE.txt Lib NEWS.txt README.txt Scripts Tools include libs python.exe pythonw.exe tcl >>>
Python
{ "resource": "" }
q159
Magic squares of doubly even order
test
def MagicSquareDoublyEven(order): sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ] n1 = order/4 for r in range(n1): r1 = sq[r][n1:-n1] r2 = sq[order -r - 1][n1:-n1] r1.reverse() r2.reverse() sq[r][n1:-n1] = r2 sq[order -r - 1][n1:-n1] = r1 ...
Python
{ "resource": "" }
q160
Pseudo-random numbers_Xorshift star
test
mask64 = (1 << 64) - 1 mask32 = (1 << 32) - 1 const = 0x2545F4914F6CDD1D class Xorshift_star(): def __init__(self, seed=0): self.state = seed & mask64 def seed(self, num): self.state = num & mask64 def next_int(self): "return random int between 0 and 2**32" x =...
Python
{ "resource": "" }
q161
ASCII art diagram converter
test
def validate(diagram): rawlines = diagram.splitlines() lines = [] for line in rawlines: if line != '': lines.append(line) if len(lines) == 0: print('diagram has no non-empty lines!') return None width = len(line...
Python
{ "resource": "" }
q162
Same fringe
test
try: from itertools import zip_longest as izip_longest except: from itertools import izip_longest def fringe(tree): for node1 in tree: if isinstance(node1, tuple): for node2 in fringe(node1): yield node2 else: yield node1 def sa...
Python
{ "resource": "" }
q163
Peaceful chess queen armies
test
from itertools import combinations, product, count from functools import lru_cache, reduce _bbullet, _wbullet = '\u2022\u25E6' _or = set.__or__ def place(m, n): "Place m black and white queens, peacefully, on an n-by-n board" board = set(product(range(n), repeat=2)) placements = {frozenset(c) for c in ...
Python
{ "resource": "" }
q164
Numbers with same digit set in base 10 and base 16
test
col = 0 for i in range(100000): if set(str(i)) == set(hex(i)[2:]): col += 1 print("{:7}".format(i), end='\n'[:col % 10 == 0]) print()
Python
{ "resource": "" }
q165
Largest proper divisor of n
test
def lpd(n): for i in range(n-1,0,-1): if n%i==0: return i return 1 for i in range(1,101): print("{:3}".format(lpd(i)), end=i%10==0 and '\n' or '')
Python
{ "resource": "" }
q166
Move-to-front algorithm
test
from __future__ import print_function from string import ascii_lowercase SYMBOLTABLE = list(ascii_lowercase) def move2front_encode(strng, symboltable): sequence, pad = [], symboltable[::] for char in strng: indx = pad.index(char) sequence.append(indx) pad = [pad.pop(indx)] + pad re...
Python
{ "resource": "" }
q167
Sum of first n cubes
test
def main(): fila = 0 lenCubos = 51 print("Suma de N cubos para n = [0..49]\n") for n in range(1, lenCubos): sumCubos = 0 for m in range(1, n): sumCubos = sumCubos + (m ** 3) fila += 1 print(f'{sumCubos:7} ', end='') if fila % 5 == 0: ...
Python
{ "resource": "" }
q168
Test integerness
test
>>> def isint(f): return complex(f).imag == 0 and complex(f).real.is_integer() >>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))] [True, True, True, False, False, False] >>> ... >>> isint(25.000000) True >>> isint(24.999999) False >>> isint(25.000100) False >>> isint(-2.1e120) True >>> isint(-5...
Python
{ "resource": "" }
q169
Longest increasing subsequence
test
def longest_increasing_subsequence(X): N = len(X) P = [0] * N M = [0] * (N+1) L = 0 for i in range(N): lo = 1 hi = L while lo <= hi: mid = (lo+hi)//2 if (X[M[mid]] < X[i]): lo = mid+1 else: hi = mid-1 ...
Python
{ "resource": "" }
q170
Superpermutation minimisation
test
"Generate a short Superpermutation of n characters A... as a string using various algorithms." from __future__ import print_function, division from itertools import permutations from math import factorial import string import datetime import gc MAXN = 7 def s_perm0(n): allchars = string.ascii_uppercase...
Python
{ "resource": "" }
q171
One of n lines in a file
test
from random import randrange try: range = xrange except: pass def one_of_n(lines): choice = None for i, line in enumerate(lines): if randrange(i+1) == 0: choice = line return choice def one_of_n_test(n=10, trials=1000000): bins = [0] * n if n: for i in ...
Python
{ "resource": "" }
q172
Summarize and say sequence
test
from itertools import groupby, permutations def A036058(number): return ''.join( str(len(list(g))) + k for k,g in groupby(sorted(str(number), reverse=True)) ) def A036058_length(numberstring='0', printit=False): iterations, last_three, queue_index = 1, ([None] * 3), 0 def A036058(numb...
Python
{ "resource": "" }
q173
Spelling of ordinal numbers
test
irregularOrdinals = { "one": "first", "two": "second", "three": "third", "five": "fifth", "eight": "eighth", "nine": "ninth", "twelve": "twelfth", } def num2ordinal(n): conversion = int(float(n)) num = spell_integer(conversion) hyphen = num.rsplit("-", 1) num = num.rsplit(" ", 1) ...
Python
{ "resource": "" }
q174
Self-describing numbers
test
>>> def isSelfDescribing(n): s = str(n) return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s)) >>> [x for x in range(4000000) if isSelfDescribing(x)] [1210, 2020, 21200, 3211000] >>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)] [(1210, True), (2020, True...
Python
{ "resource": "" }
q175
Addition chains
test
def prepend(n, seq): return [n] + seq def check_seq(pos, seq, n, min_len): if pos > min_len or seq[0] > n: return min_len, 0 if seq[0] == n: return pos, 1 if pos < min_len: return try_perm(0, pos, seq, n, min_len) return min_len, 0 def try_perm(i, pos, seq, n, min_len): ...
Python
{ "resource": "" }
q176
Repeat
test
def repeat(f,n): for i in range(n): f(); def procedure(): print("Example"); repeat(procedure,3);
Python
{ "resource": "" }
q177
Sparkline in unicode
test
bar = 'โ–โ–‚โ–ƒโ–„โ–…โ–†โ–‡โ–ˆ' barcount = len(bar) def sparkline(numbers): mn, mx = min(numbers), max(numbers) extent = mx - mn sparkline = ''.join(bar[min([barcount - 1, int((n - mn) / extent * barcount)])] for n in numbers) return mn, mx, sparkline if __...
Python
{ "resource": "" }
q178
Modular inverse
test
>>> def extended_gcd(aa, bb): lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) x, lastx = lastx - quotient*x, x y, lasty = lasty - quotient*y, y return l...
Python
{ "resource": "" }
q179
Sunflower fractal
test
from turtle import * from math import * iter = 3000 diskRatio = .5 factor = .5 + sqrt(1.25) screen = getscreen() (winWidth, winHeight) = screen.screensize() x = 0.0 y = 0.0 maxRad = pow(iter,factor)/iter; bgcolor("light blue") hideturtle() tracer(0, 0) for i in range(iter+1): r = pow(i,factor)/iter;...
Python
{ "resource": "" }
q180
Vogel's approximation method
test
from collections import defaultdict costs = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17}, 'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15}, 'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50}, 'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}} demand = {'A': 30, 'B': 20, 'C': 70...
Python
{ "resource": "" }
q181
Permutations by swapping
test
from operator import itemgetter DEBUG = False def spermutations(n): sign = 1 p = [[i, 0 if i == 0 else -1] for i in range(n)] if DEBUG: print ' yield tuple(pp[0] for pp in p), sign while any(pp[1] for pp in p): i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) i...
Python
{ "resource": "" }
q182
Minimum multiple of m where digital sum equals m
test
from itertools import count, islice def a131382(): return ( elemIndex(x)( productDigitSums(x) ) for x in count(1) ) def productDigitSums(n): return (digitSum(n * x) for x in count(0)) def main(): print( table(10)([ str(x) for x ...
Python
{ "resource": "" }
q183
Pythagorean quadruples
test
def quad(top=2200): r = [False] * top ab = [False] * (top * 2)**2 for a in range(1, top): for b in range(a, top): ab[a * a + b * b] = True s = 3 for c in range(1, top): s1, s, s2 = s, s + 2, s + 2 for d in range(c + 1, top): if ab[s1]: ...
Python
{ "resource": "" }
q184
Steady squares
test
print("working...") print("Steady squares under 10.000 are:") limit = 10000 for n in range(1,limit): nstr = str(n) nlen = len(nstr) square = str(pow(n,2)) rn = square[-nlen:] if nstr == rn: print(str(n) + " " + str(square)) print("done...")
Python
{ "resource": "" }
q185
Pseudo-random numbers_Middle-square method
test
seed = 675248 def random(): global seed seed = int(str(seed ** 2).zfill(12)[3:9]) return seed for _ in range(5): print(random())
Python
{ "resource": "" }
q186
Dice game probabilities
test
from itertools import product def gen_dict(n_faces, n_dice): counts = [0] * ((n_faces + 1) * n_dice) for t in product(range(1, n_faces + 1), repeat=n_dice): counts[sum(t)] += 1 return counts, n_faces ** n_dice def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2): c1, p1 = gen_dict(n_s...
Python
{ "resource": "" }
q187
Plasma effect
test
pal = [0] * 128 r = 42 g = 84 b = 126 rd = gd = bd = False def setup(): global buffer size(600, 600) frameRate(25) buffer = [None] * width * height for x in range(width): for y in range(width): value = int(((128 + (128 * sin(x / 32.0))) + (128 + (128 *...
Python
{ "resource": "" }
q191
Literals_String
test
'c' == "c" 'text' == "text" ' " ' " ' " '\x20' == ' ' u'unicode string' u'\u05d0'
Python
{ "resource": "" }
q192
Enumerations
test
>>> from enum import Enum >>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE') >>> Contact.__members__ mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)])) >>> >>> >>> class Contact2(Enum): FIRST_NAME = 1 LAST_NAME = 2 P...
Python
{ "resource": "" }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
341