_id
stringlengths
2
5
title
stringlengths
2
76
partition
stringclasses
3 values
text
stringlengths
8
6.97k
language
stringclasses
1 value
meta_information
dict
q194
Modulinos
test
def meaning_of_life(): return 42 if __name__ == "__main__": print("Main: The meaning of life is %s" % meaning_of_life())
Python
{ "resource": "" }
q196
Execute a system command
test
import os exit_code = os.system('ls') output = os.popen('ls').read()
Python
{ "resource": "" }
q198
Brace expansion
test
def getitem(s, depth=0): out = [""] while s: c = s[0] if depth and (c == ',' or c == '}'): return out,s if c == '{': x = getgroup(s[1:], depth+1) if x: out,s = [a+b for a in out for b in x[0]], x[1] continue if c...
Python
{ "resource": "" }
q203
Variables
test
example1 = 3 example2 = 3.0 example3 = True example4 = "hello" example1 = "goodbye"
Python
{ "resource": "" }
q205
Literals_Floating point
test
2.3 .3 .3e4 .3e+34 .3e-34 2.e34
Python
{ "resource": "" }
q206
Church numerals
test
from itertools import repeat from functools import reduce def churchZero(): return lambda f: identity def churchSucc(cn): return lambda f: compose(f)(cn(f)) def churchAdd(m): return lambda n: lambda f: compose(m(f))(n(f)) def churchMult(m): return lambda n: compose(m)(n) ...
Python
{ "resource": "" }
q207
Break OO privacy
test
>>> class MyClassName: __private = 123 non_private = __private * 2 >>> mine = MyClassName() >>> mine.non_private 246 >>> mine.__private Traceback (most recent call last): File "<pyshell mine.__private AttributeError: 'MyClassName' object has no attribute '__private' >>> mine._MyClassName__private 123 >>>
Python
{ "resource": "" }
q208
Object serialization
test
import pickle class Entity: def __init__(self): self.name = "Entity" def printName(self): print self.name class Person(Entity): def __init__(self): self.name = "Cletus" instance1 = Person() instance1.printName() instance2 = Entity() instance2.printName() target = file("objects.dat", "w") pickle...
Python
{ "resource": "" }
q209
Long year
test
from datetime import date def longYear(y): return 52 < date(y, 12, 28).isocalendar()[1] def main(): for year in [ x for x in range(2000, 1 + 2100) if longYear(x) ]: print(year) if __name__ == '__main__': main()
Python
{ "resource": "" }
q210
Associative array_Merging
test
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"} update = {"price":15.25, "color":"red", "year":1974} result = {**base, **update} print(result)
Python
{ "resource": "" }
q211
Markov chain text generator
test
import random, sys def makerule(data, context): rule = {} words = data.split(' ') index = context for word in words[index:]: key = ' '.join(words[index-context:index]) if key in rule: rule[key].append(word) else: rule[key] = [word] index...
Python
{ "resource": "" }
q212
Dijkstra's algorithm
test
from collections import namedtuple, deque from pprint import pprint as pp inf = float('inf') Edge = namedtuple('Edge', ['start', 'end', 'cost']) class Graph(): def __init__(self, edges): self.edges = [Edge(*edge) for edge in edges] self.vertices = {e.start for e in self.edges} | {e.en...
Python
{ "resource": "" }
q213
Associative array_Iteration
test
myDict = { "hello": 13, "world": 31, "!" : 71 } for key, value in myDict.items(): print ("key = %s, value = %s" % (key, value)) for key in myDict: print ("key = %s" % key) for key in myDict.keys(): print ("key = %s" % key) for value in myDict.values(): print ("value = %s" % value)
Python
{ "resource": "" }
q214
Here document
test
print()
Python
{ "resource": "" }
q215
Hash join
test
from collections import defaultdict def hashJoin(table1, index1, table2, index2): h = defaultdict(list) for s in table1: h[s[index1]].append(s) return [(s, r) for r in table2 for s in h[r[index2]]] table1 = [(27, "Jonah"), (18, "Alan"), (28, "Glory"), (18, "...
Python
{ "resource": "" }
q216
Respond to an unknown method call
test
class Example(object): def foo(self): print("this is foo") def bar(self): print("this is bar") def __getattr__(self, name): def method(*args): print("tried to handle unknown method " + name) if args: print("it had arguments: " + str(args)) ...
Python
{ "resource": "" }
q217
Inheritance_Single
test
class Animal: pass class Dog(Animal): pass class Cat(Animal): pass class Lab(Dog): pass class Collie(Dog): pass
Python
{ "resource": "" }
q218
Associative array_Creation
test
hash = dict() hash = dict(red="FF0000", green="00FF00", blue="0000FF") hash = { 'key1':1, 'key2':2, } value = hash[key]
Python
{ "resource": "" }
q219
Polymorphism
test
class Point(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __repr__(self): return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y) class Circle(object): def __init__(self, center=None, radius=1.0): self.center = center or Point() self.rad...
Python
{ "resource": "" }
q220
Monads_Writer monad
test
from __future__ import annotations import functools import math import os from typing import Any from typing import Callable from typing import Generic from typing import List from typing import TypeVar from typing import Union T = TypeVar("T") class Writer(Generic[T]): def __init__(self, value: Union[T, Wri...
Python
{ "resource": "" }
q249
A_ search algorithm
test
from __future__ import print_function import matplotlib.pyplot as plt class AStarGraph(object): def __init__(self): self.barriers = [] self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)]) def heuristic(self, start, goal): D = 1 D2 = 1 dx = abs(start[0] -...
Python
{ "resource": "" }
q252
Zhang-Suen thinning algorithm
test
beforeTxt = smallrc01 = rc01 = def intarray(binstring): return [[1 if ch == '1' else 0 for ch in line] for line in binstring.strip().split()] def chararray(intmatrix): return '\n'.join(''.join(str(p) for p in row) for row in intmatrix) def toTxt(intmatrix): Return 8-neighb...
Python
{ "resource": "" }
q263
Four is the number of letters in the ...
test
import inflect def count_letters(word): count = 0 for letter in word: if letter != ',' and letter !='-' and letter !=' ': count += 1 return count def split_with_spaces(sentence): sentence_list = [] curr_word = "" for c in sentence: if...
Python
{ "resource": "" }
q268
Lucky and even lucky numbers
test
from __future__ import print_function def lgen(even=False, nmax=1000000): start = 2 if even else 1 n, lst = 1, list(range(start, nmax + 1, 2)) lenlst = len(lst) yield lst[0] while n < lenlst and lst[n] < lenlst: yield lst[n] n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst...
Python
{ "resource": "" }
q277
GUI component interaction
test
import random, tkMessageBox from Tkinter import * window = Tk() window.geometry("300x50+100+100") options = { "padx":5, "pady":5} s=StringVar() s.set(1) def increase(): s.set(int(s.get())+1) def rand(): if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"): s.set(random.randrange(0,5000)) ...
Python
{ "resource": "" }
q283
Chemical calculator
test
assert 1.008 == molar_mass('H') assert 2.016 == molar_mass('H2') assert 18.015 == molar_mass('H2O') assert 34.014 == molar_mass('H2O2') assert 34.014 == molar_mass('(HO)2') assert 142.036 == molar_mass('Na2SO4') assert ...
Python
{ "resource": "" }
q285
Sokoban
test
from array import array from collections import deque import psyco data = [] nrows = 0 px = py = 0 sdata = "" ddata = "" def init(board): global data, nrows, sdata, ddata, px, py data = filter(None, board.splitlines()) nrows = max(len(r) for r in data) maps = {' ':' ', '.': '.', '@':' ', ' mapd =...
Python
{ "resource": "" }
q286
Practical numbers
test
from itertools import chain, cycle, accumulate, combinations from typing import List, Tuple def factors5(n: int) -> List[int]: 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 ...
Python
{ "resource": "" }
q287
Solve a Numbrix puzzle
test
from sys import stdout neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] exists = [] lastNumber = 0 wid = 0 hei = 0 def find_next(pa, x, y, z): for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == z: ...
Python
{ "resource": "" }
q288
Solve a Hopido puzzle
test
from sys import stdout neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] cnt = 0 pWid = 0 pHei = 0 def is_valid(a, b): return -1 < a < pWid and -1 < b < pHei def iterate(pa, x, y, v): if v > cnt: return 1 for i in range(len(neighbours)): a = x + neighb...
Python
{ "resource": "" }
q289
Nonogram solver
test
from itertools import izip def gen_row(w, s): def gen_seg(o, sp): if not o: return [[2] * sp] return [[2] * x + o[0] + tail for x in xrange(1, sp - len(o) + 2) for tail in gen_seg(o[1:], sp - x)] return [x[1:] for x in gen_seg([[1] * i for i in ...
Python
{ "resource": "" }
q290
Word search
test
import re from random import shuffle, randint dirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]] n_rows = 10 n_cols = 10 grid_size = n_rows * n_cols min_words = 25 class Grid: def __init__(self): self.num_attempts = 0 self.cells = [['' for _ in range(n_cols)] for _ in r...
Python
{ "resource": "" }
q291
Eertree
test
from __future__ import print_function class Node(object): def __init__(self): self.edges = {} self.link = None self.len = 0 class Eertree(object): def __init__(self): self.nodes = [] self.rto = Node() self.rte = Node() self.rto.link = self.rte.link = self.rto; self.rto.len = -1 self.r...
Python
{ "resource": "" }
q292
Zumkeller numbers
test
from sympy import divisors from sympy.combinatorics.subsets import Subset def isZumkeller(n): d = divisors(n) s = sum(d) if not s % 2 and max(d) <= s/2: for x in range(1, 2**len(d)): if sum(Subset.unrank_binary(x, d).subset) == s/2: return True return False def ...
Python
{ "resource": "" }
q293
Metallic ratios
test
from itertools import count, islice from _pydecimal import getcontext, Decimal def metallic_ratio(b): m, n = 1, 1 while True: yield m, n m, n = m*b + n, m def stable(b, prec): def to_decimal(b): for m,n in metallic_ratio(b): yield Decimal(m)/Decimal(n) getcontext()...
Python
{ "resource": "" }
q294
Geometric algebra
test
import copy, random def bitcount(n): return bin(n).count("1") def reoderingSign(i, j): k = i >> 1 sum = 0 while k != 0: sum += bitcount(k & j) k = k >> 1 return 1.0 if ((sum & 1) == 0) else -1.0 class Vector: def __init__(self, da): self.dims = da def dot(self, ot...
Python
{ "resource": "" }
q295
Suffix tree
test
class Node: def __init__(self, sub="", children=None): self.sub = sub self.ch = children or [] class SuffixTree: def __init__(self, str): self.nodes = [Node()] for i in range(len(str)): self.addSuffix(str[i:]) def addSuffix(self, suf): n = 0 i = ...
Python
{ "resource": "" }
q296
Define a primitive data type
test
>>> class num(int): def __init__(self, b): if 1 <= b <= 10: return int.__init__(self+0) else: raise ValueError,"Value %s should be >=0 and <= 10" % b >>> x = num(3) >>> x = num(11) Traceback (most recent call last): File "<pyshell x = num(11) File "<pyshell...
Python
{ "resource": "" }
q297
Penrose tiling
test
def penrose(depth): print( <g id="A{d+1}" transform="translate(100, 0) scale(0.6180339887498949)"> <use href=" <use href=" </g> <g id="B{d+1}"> <use href=" <use href=" </g> <g id="G"> <use href=" <use href=" </g> </defs> <g transform="scale(2, 2)"> <use href=" <use href=" <use href=" <use hr...
Python
{ "resource": "" }
q298
Sphenic numbers
test
from sympy import factorint sphenics1m, sphenic_triplets1m = [], [] for i in range(3, 1_000_000): d = factorint(i) if len(d) == 3 and sum(d.values()) == 3: sphenics1m.append(i) if len(sphenics1m) > 2 and i - sphenics1m[-3] == 2 and i - sphenics1m[-2] == 1: sphenic_triplets1m.app...
Python
{ "resource": "" }
q299
Find duplicate files
test
from __future__ import print_function import os import hashlib import datetime def FindDuplicateFiles(pth, minSize = 0, hashName = "md5"): knownFiles = {} for root, dirs, files in os.walk(pth): for fina in files: fullFina = os.path.join(root, fina) isSymLink = os.path.isli...
Python
{ "resource": "" }
q300
Solve a Holy Knight's tour
test
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 an...
Python
{ "resource": "" }
q301
Order disjoint list items
test
from __future__ import print_function def order_disjoint_list_items(data, items): itemindices = [] for item in set(items): itemcount = items.count(item) lastindex = [-1] for i in range(itemcount): lastindex.append(data.index(item, lastindex[-1] + 1)) it...
Python
{ "resource": "" }
q302
Sierpinski curve
test
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import hsv_to_rgb as hsv def curve(axiom, rules, angle, depth): for _ in range(depth): axiom = ''.join(rules[c] if c in rules else c for c in axiom) a, x, y = 0, [0], [0] for c in axiom: match c: case '+'...
Python
{ "resource": "" }
q303
Most frequent k chars distance
test
import collections def MostFreqKHashing(inputString, K): occuDict = collections.defaultdict(int) for c in inputString: occuDict[c] += 1 occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True) outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K]) return outputStr d...
Python
{ "resource": "" }
q304
Pig the dice game_Player
test
from random import randint from collections import namedtuple import random from pprint import pprint as pp from collections import Counter playercount = 2 maxscore = 100 maxgames = 100000 Game = namedtuple('Game', 'players, maxscore, rounds') Round = namedtuple('Round', 'who, start, scores, safe') class Play...
Python
{ "resource": "" }
q305
Lychrel numbers
test
from __future__ import print_function def add_reverse(num, max_iter=1000): i, nums = 0, {num} while True: i, num = i+1, num + reverse_int(num) nums.add(num) if reverse_int(num) == num or i >= max_iter: break return nums def reverse_int(num): return int(str(num)...
Python
{ "resource": "" }
q306
Sierpinski square curve
test
import matplotlib.pyplot as plt import math def nextPoint(x, y, angle): a = math.pi * angle / 180 x2 = (int)(round(x + (1 * math.cos(a)))) y2 = (int)(round(y + (1 * math.sin(a)))) return x2, y2 def expand(axiom, rules, level): for l in range(0, level): a2 = "" for c in axiom: ...
Python
{ "resource": "" }
q307
Powerful numbers
test
from primesieve import primes import math def primepowers(k, upper_bound): ub = int(math.pow(upper_bound, 1/k) + .5) res = [(1,)] for p in primes(ub): a = [p**k] u = upper_bound // a[-1] while u >= p: a.append(a[-1]*p) u //= p res.append(tuple(a)) ...
Python
{ "resource": "" }
q308
Polynomial synthetic division
test
from __future__ import print_function from __future__ import division def extended_synthetic_division(dividend, divisor): out = list(dividend) normalizer = divisor[0] for i in xrange(len(dividend)-(len(divisor)-1)): out[i] /= normalizer coef...
Python
{ "resource": "" }
q309
Odd words
test
import urllib.request 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() oddWordSet = set({}) for word in wordList: if len(word)>=9 and word[::2] in wordList: ...
Python
{ "resource": "" }
q310
Ramanujan's constant
test
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt...
Python
{ "resource": "" }
q311
Word break problem
test
from itertools import (chain) def stringParse(lexicon): return lambda s: Node(s)( tokenTrees(lexicon)(s) ) def tokenTrees(wds): def go(s): return [Node(s)([])] if s in wds else ( concatMap(nxt(s))(wds) ) def nxt(s): return lambda w: parse( ...
Python
{ "resource": "" }
q312
Brilliant numbers
test
from primesieve.numpy import primes from math import isqrt import numpy as np max_order = 9 blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)] def smallest_brilliant(lb): pos = 1 root = isqrt(lb) for blk in blocks: n = len(blk) if blk[-1]*blk[-1] < lb: pos += n*(n...
Python
{ "resource": "" }
q313
Word ladder
test
import os,sys,zlib,urllib.request def h ( str,x=9 ): for c in str : x = ( x*33 + ord( c )) & 0xffffffffff return x def cache ( func,*param ): n = 'cache_%x.bin'%abs( h( repr( param ))) try : return eval( zlib.decompress( open( n,'rb' ).read())) except : pass s = func( *param ) ...
Python
{ "resource": "" }
q314
Earliest difference between prime gaps
test
from primesieve import primes LIMIT = 10**9 pri = primes(LIMIT * 5) gapstarts = {} for i in range(1, len(pri)): if pri[i] - pri[i - 1] not in gapstarts: gapstarts[pri[i] - pri[i - 1]] = pri[i - 1] PM, GAP1, = 10, 2 while True: while GAP1 not in gapstarts: GAP1 += 2 start1 = gapstarts[GAP...
Python
{ "resource": "" }
q315
Latin Squares in reduced form
test
def dList(n, start): start -= 1 a = range(n) a[start] = a[0] a[0] = start a[1:] = sorted(a[1:]) first = a[1] r = [] def recurse(last): if (last == first): for j,v in enumerate(a[1:]): if j + 1 == v: ...
Python
{ "resource": "" }
q316
UPC
test
import itertools import re RE_BARCODE = re.compile( r"^(?P<s_quiet> +)" r"(?P<s_guard> r"(?P<left>[ r"(?P<m_guard> r"(?P<right>[ r"(?P<e_guard> r"(?P<e_quiet> +)$" ) LEFT_DIGITS = { (0, 0, 0, 1, 1, 0, 1): 0, (0, 0, 1, 1, 0, 0, 1): 1, (0, 0, 1, 0, 0, 1, 1): 2, (0, 1,...
Python
{ "resource": "" }
q317
Playfair cipher
test
from string import ascii_uppercase from itertools import product from re import findall def uniq(seq): seen = {} return [seen.setdefault(x, x) for x in seq if x not in seen] def partition(seq, n): return [seq[i : i + n] for i in xrange(0, len(seq), n)] def playfair(key, from_ = 'J', to = None): if ...
Python
{ "resource": "" }
q318
Closest-pair problem
test
from random import randint, randrange from operator import itemgetter, attrgetter infinity = float('inf') def bruteForceClosestPair(point): numPoints = len(point) if numPoints < 2: return infinity, (None, None) return min( ((abs(point[i] - point[j]), (point[i], point[j])) for ...
Python
{ "resource": "" }
q319
Color wheel
test
size(300, 300) background(0) radius = min(width, height) / 2.0 cx, cy = width / 2, width / 2 for x in range(width): for y in range(height): rx = x - cx ry = y - cy s = sqrt(rx ** 2 + ry ** 2) / radius if s <= 1.0: h = ((atan2(ry, rx) / PI) + 1.0) /...
Python
{ "resource": "" }
q320
Hello world_Newbie
test
print "Goodbye, World!"
Python
{ "resource": "" }
q321
Wagstaff primes
test
from sympy import isprime def wagstaff(N): pri, wcount = 1, 0 while wcount < N: pri += 2 if isprime(pri): wag = (2**pri + 1) // 3 if isprime(wag): wcount += 1 print(f'{wcount: 3}: {pri: 5} => ', f'{wag:,}' if ...
Python
{ "resource": "" }
q322
Create an object_Native demonstration
test
from collections import UserDict import copy class Dict(UserDict): def __init__(self, dict=None, **kwargs): self.__init = True super().__init__(dict, **kwargs) self.default = copy.deepcopy(self.data) self.__init = False def __delitem__(self, key): if key in sel...
Python
{ "resource": "" }
q323
Rare numbers
test
from math import floor, sqrt from datetime import datetime def main(): start = datetime.now() for i in xrange(1, 10 ** 11): if rare(i): print "found a rare:", i end = datetime.now() print "time elapsed:", end - start def is_square(n): s = floor(sqrt(n + 0.5)) return s * s == n def reverse(n): return ...
Python
{ "resource": "" }
q324
Arithmetic evaluation
test
import operator class AstNode(object): def __init__( self, opr, left, right ): self.opr = opr self.l = left self.r = right def eval(self): return self.opr(self.l.eval(), self.r.eval()) class LeafNode(object): def __init__( self, valStrg ): self.v = int(valStrg) def eval(sel...
Python
{ "resource": "" }
q325
Special variables
test
names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split())) print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )
Python
{ "resource": "" }
q326
Execute CopyPasta Language
test
import sys def fatal_error(errtext): print("%" + errtext) print("usage: " + sys.argv[0] + " [filename.cp]") sys.exit(1) fname = None source = None try: fname = sys.argv[1] source = open(fname).read() except: fatal_error("error while trying to read from specified file") lines = source.split("\n") clipboard...
Python
{ "resource": "" }
q337
Kosaraju
test
def kosaraju(g): class nonlocal: pass size = len(g) vis = [False]*size l = [0]*size nonlocal.x = size t = [[]]*size def visit(u): if not vis[u]: vis[u] = True for v in g[u]: visit(v) t[v] = t[v] + [u] non...
Python
{ "resource": "" }
q376
Include a file
test
import one
Python
{ "resource": "" }
q379
Loops_Infinite
test
while 1: print "SPAM"
Python
{ "resource": "" }
q381
Zebra puzzle
test
from logpy import * from logpy.core import lall import time def lefto(q, p, list): return membero((q,p), zip(list, list[1:])) def nexto(q, p, list): return conde([lefto(q, p, list)], [lefto(p, q, list)]) houses = var() zebraRules = lall( (eq, (var(), var(), var(), var(), var()), houses), (memb...
Python
{ "resource": "" }
q382
First-class functions_Use numbers analogously
test
IDLE 2.6.1 >>> >>> x,xi, y,yi = 2.0,0.5, 4.0,0.25 >>> >>> z = x + y >>> zi = 1.0 / (x + y) >>> >>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m) >>> >>> numlist = [x, y, z] >>> numlisti = [xi, yi, zi] >>> >>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)] [0.5, 0.5, 0.5] >>>
Python
{ "resource": "" }
q383
Almkvist-Giullera formula for pi
test
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**ex...
Python
{ "resource": "" }
q384
Consecutive primes with ascending or descending differences
test
from sympy import sieve primelist = list(sieve.primerange(2,1000000)) listlen = len(primelist) pindex = 1 old_diff = -1 curr_list=[primelist[0]] longest_list=[] while pindex < listlen: diff = primelist[pindex] - primelist[pindex-1] if diff > old_diff: curr_list.append(primelist[pindex]) i...
Python
{ "resource": "" }
q385
Odd squarefree semiprimes
test
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': for p in range(3, 999): if not isPrime(p): continue for q in range(p+1, 1000//p): if not isPrime(q): ...
Python
{ "resource": "" }
q386
Address of a variable
test
var num = 12 var pointer = ptr(num) print pointer @unsafe pointer.addr = 0xFFFE
Python
{ "resource": "" }
q449
Sieve of Pritchard
test
from numpy import ndarray from math import isqrt def pritchard(limit): members = ndarray(limit + 1, dtype=bool) members.fill(False) members[1] = True steplength, prime, rtlim, nlimit = 1, 2, isqrt(limit), 2 primes = [] while prime <= rtlim: if steplength < limit: for...
Python
{ "resource": "" }
q450
Arithmetic derivative
test
from sympy.ntheory import factorint def D(n): if n < 0: return -D(-n) elif n < 2: return 0 else: fdict = factorint(n) if len(fdict) == 1 and 1 in fdict: return 1 return sum([n * e // p for p, e in fdict.items()]) for n in range(-99, 101): print('{:5...
Python
{ "resource": "" }
q451
Permutations with some identical elements
test
from itertools import permutations numList = [2,3,1] baseList = [] for i in numList: for j in range(0,i): baseList.append(i) stringDict = {'A':2,'B':3,'C':1} baseString="" for i in stringDict: for j in range(0,stringDict[i]): baseString+=i print("Permutations for " + str(baseList) + " :...
Python
{ "resource": "" }
q452
Tree from nesting levels
test
def to_tree(x, index=0, depth=1): so_far = [] while index < len(x): this = x[index] if this == depth: so_far.append(this) elif this > depth: index, deeper = to_tree(x, index, depth + 1) so_far.append(deeper) else: index -=1 break ...
Python
{ "resource": "" }
q453
Sylvester's sequence
test
from functools import reduce from itertools import count, islice def sylvester(): def go(n): return 1 + reduce( lambda a, x: a * go(x), range(0, n), 1 ) if 0 != n else 2 return map(go, count(0)) def main(): print("First 10 terms of OEI...
Python
{ "resource": "" }
q454
Achilles numbers
test
from math import gcd from sympy import factorint def is_Achilles(n): p = factorint(n).values() return all(i > 1 for i in p) and gcd(*p) == 1 def is_strong_Achilles(n): return is_Achilles(n) and is_Achilles(totient(n)) def test_strong_Achilles(nachilles, nstrongachilles): print('First', nachill...
Python
{ "resource": "" }
q455
Palindromic primes
test
from itertools import takewhile def palindromicPrimes(): def p(n): s = str(n) return s == s[::-1] return (n for n in primes() if p(n)) def main(): print('\n'.join( str(x) for x in takewhile( lambda n: 1000 > n, palindromicPrimes() ) ...
Python
{ "resource": "" }
q456
Find words which contains all the vowels
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() for word in wordList: if len(word)>10: frequency = Co...
Python
{ "resource": "" }
q457
Tropical algebra overloading
test
from numpy import Inf class MaxTropical: def __init__(self, x=0): self.x = x def __str__(self): return str(self.x) def __add__(self, other): return MaxTropical(max(self.x, other.x)) def __mul__(self, other): return MaxTropical(self.x + other.x) def __pow__(s...
Python
{ "resource": "" }
q458
Base 16 numbers needing a to f
test
def p(n): return 9 < n and (9 < n % 16 or p(n // 16)) def main(): xs = [ str(n) for n in range(1, 1 + 500) if p(n) ] print(f'{len(xs)} matches for the predicate:\n') print( table(6)(xs) ) def chunksOf(n): def go(xs): return ( ...
Python
{ "resource": "" }
q459
Range modifications
test
class Sequence(): def __init__(self, sequence_string): self.ranges = self.to_ranges(sequence_string) assert self.ranges == sorted(self.ranges), "Sequence order error" def to_ranges(self, txt): return [[int(x) for x in r.strip().split('-')] for r in txt.strip...
Python
{ "resource": "" }
q460
Juggler sequence
test
from math import isqrt def juggler(k, countdig=True, maxiters=1000): m, maxj, maxjpos = k, k, 0 for i in range(1, maxiters): m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m) if m >= maxj: maxj, maxjpos = m, i if m == 1: print(f"{k: 9}{i: 6,}{maxjpos: 6}{len(str(...
Python
{ "resource": "" }
q461
Fixed length records
test
infile = open('infile.dat', 'rb') outfile = open('outfile.dat', 'wb') while True: onerecord = infile.read(80) if len(onerecord) < 80: break onerecordreversed = bytes(reversed(onerecord)) outfile.write(onerecordreversed) infile.close() outfile.close()
Python
{ "resource": "" }
q462
Find words whose first and last three letters are equal
test
import urllib.request 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() for word in wordList: if len(word)>5 and word[:3].lower()==word[-3:].lower(): print(wo...
Python
{ "resource": "" }
q463
Giuga numbers
test
from math import sqrt def isGiuga(m): n = m f = 2 l = sqrt(n) while True: if n % f == 0: if ((m / f) - 1) % f != 0: return False n /= f if f > n: return True else: f += 1 if f > l: ...
Python
{ "resource": "" }
q464
Tree datastructures
test
from pprint import pprint as pp def to_indent(node, depth=0, flat=None): if flat is None: flat = [] if node: flat.append((depth, node[0])) for child in node[1]: to_indent(child, depth + 1, flat) return flat def to_nest(lst, depth=0, level=None): if level is None: le...
Python
{ "resource": "" }
q465
Selectively replace multiple instances of a character within a string
test
from collections import defaultdict rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}} def trstring(oldstring, repdict): seen, newchars = defaultdict(lambda:1, {}), [] for c in oldstring: i = seen[c] newchars.append(repdict[c][i] if c in repdict and i in repd...
Python
{ "resource": "" }
q466
Repunit primes
test
from sympy import isprime for b in range(2, 17): print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])
Python
{ "resource": "" }
q467
Curzon numbers
test
def is_Curzon(n, k): r = k * n return pow(k, n, r + 1) == r for k in [2, 4, 6, 8, 10]: n, curzons = 1, [] while len(curzons) < 1000: if is_Curzon(n, k): curzons.append(n) n += 1 print(f'Curzon numbers with k = {k}:') for i, c in enumerate(curzons[:50]): print...
Python
{ "resource": "" }
q468
Joystick position
test
import sys import pygame pygame.init() clk = pygame.time.Clock() if pygame.joystick.get_count() == 0: raise IOError("No joystick detected") joy = pygame.joystick.Joystick(0) joy.init() size = width, height = 600, 600 screen = pygame.display.set_mode(size) pygame.display.set_caption("Joystick Tester") frame...
Python
{ "resource": "" }
q469
Ormiston pairs
test
from sympy import primerange PRIMES1M = list(primerange(1, 1_000_000)) ASBASE10SORT = [str(sorted(list(str(i)))) for i in PRIMES1M] ORMISTONS = [(PRIMES1M[i - 1], PRIMES1M[i]) for i in range(1, len(PRIMES1M)) if ASBASE10SORT[i - 1] == ASBASE10SORT[i]] print('First 30 Ormiston pairs:') for (i, o) in en...
Python
{ "resource": "" }
q470
Harmonic series
test
from fractions import Fraction def harmonic_series(): n, h = Fraction(1), Fraction(1) while True: yield h h += 1 / (n + 1) n += 1 if __name__ == '__main__': from itertools import islice for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)): print(n,...
Python
{ "resource": "" }
q471
External sort
test
import io def sort_large_file(n: int, source: open, sink: open, file_opener = open)->None: mergers = [] while True: text = list(source.read(n)) if not len(text): break; text.sort() merge_me = file_opener() merge_me.write(''.join(text)) ...
Python
{ "resource": "" }