_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//se... | 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, ... | 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 fact... | 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 enumera... | 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... | 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",
"gr... | 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... | 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.')
... | 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... | 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)):
... | 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)... | 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 = xgri... | 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... | 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):
... | 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... | 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... | 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 p... | 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... | 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, ... | 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), toke... | 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
whi... | 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]),
... | 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=1000... | 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:
... | 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 ... | 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(
(
... | 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
... | 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)... | 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)]... | 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:
... | 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
de... | 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... | 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:
... | 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)([
... | 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,... | 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 ... | 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... | 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 fourt... | 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_... | 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... | 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 __getite... | 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ŭ',
... | 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:
... | 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)) f... | 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 i... | 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
e... | 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:
... | 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):
... | 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==-... | 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)
... | 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
)
... | 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 =... | 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 [de... | 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'... | 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+)',... | 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... | 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, 'Ma... | 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), in... | 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, justi... | 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(',')
sto... | 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.classn... | 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 -... | 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 word... | 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 enum... | 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:... | 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 +=... | 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,)
... | Python | {
"resource": ""
} |
q649 | Towers of Hanoi | train |
நிரல்பாகம் ஹோனாய்(வட்டுகள், முதல்அச்சு, இறுதிஅச்சு,வட்டு)
@(வட்டுகள் == 1 ) ஆனால்
பதிப்பி “வட்டு ” + str(வட்டு) + “ஐ \t (” + str(முதல்அச்சு) + “ —> ” + str(இறுதிஅச்சு)+ “) அச்சிற்கு நகர்த்துக.”
இல்லை
@( ["இ", "அ", "ஆ"] இல் அச்சு ) ஒவ்வொன்றாக
@( (முதல்அச்சு != அச்சு) && (இறுதிஅச்சு != அ... | 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 * ot... | 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))... | 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 ... | 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(squar... | Python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.