_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 == '\\' and len(s) > 1:
s, c = s[1:], c + s[1]
out, s = [a+c for a in out], s[1:]
return out,s
def getgroup(s, depth):
out, comma = [], False
while s:
g,s = getitem(s, depth)
if not s: break
out += g
if s[0] == '}':
if comma: return out, s[1:]
return ['{' + a + '}' for a in out], s[1:]
if s[0] == ',':
comma,s = True, s[1:]
return None
for s in .split('\n'):
print "\n\t".join([s] + getitem(s)[0]) + "\n"
|
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)
def churchExp(m):
return lambda n: n(m)
def churchFromInt(n):
return lambda f: (
foldl
(compose)
(identity)
(replicate(n)(f))
)
def churchFromInt_(n):
if 0 == n:
return churchZero()
else:
return churchSucc(churchFromInt(n - 1))
def intFromChurch(cn):
return cn(succ)(0)
def main():
'Tests'
cThree = churchFromInt(3)
cFour = churchFromInt(4)
print(list(map(intFromChurch, [
churchAdd(cThree)(cFour),
churchMult(cThree)(cFour),
churchExp(cFour)(cThree),
churchExp(cThree)(cFour),
])))
def compose(f):
return lambda g: lambda x: g(f(x))
def foldl(f):
def go(acc, xs):
return reduce(lambda a, x: f(a)(x), xs, acc)
return lambda acc: lambda xs: go(acc, xs)
def identity(x):
return x
def replicate(n):
return lambda x: repeat(x, n)
def succ(x):
return 1 + x if isinstance(x, int) else (
chr(1 + ord(x))
)
if __name__ == '__main__':
main()
|
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.dump((instance1, instance2), target)
target.close()
print "Serialized..."
target = file("objects.dat")
i1, i2 = pickle.load(target)
print "Unserialized..."
i1.printName()
i2.printName()
|
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 += 1
return rule
def makestring(rule, length):
oldwords = random.choice(list(rule.keys())).split(' ')
string = ' '.join(oldwords) + ' '
for i in range(length):
try:
key = ' '.join(oldwords)
newword = random.choice(rule[key])
string += newword + ' '
for word in range(len(oldwords)):
oldwords[word] = oldwords[(word + 1) % len(oldwords)]
oldwords[-1] = newword
except KeyError:
return string
return string
if __name__ == '__main__':
with open(sys.argv[1], encoding='utf8') as f:
data = f.read()
rule = makerule(data, int(sys.argv[2]))
string = makestring(rule, int(sys.argv[3]))
print(string)
|
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.end for e in self.edges}
def dijkstra(self, source, dest):
assert source in self.vertices
dist = {vertex: inf for vertex in self.vertices}
previous = {vertex: None for vertex in self.vertices}
dist[source] = 0
q = self.vertices.copy()
neighbours = {vertex: set() for vertex in self.vertices}
for start, end, cost in self.edges:
neighbours[start].add((end, cost))
neighbours[end].add((start, cost))
while q:
u = min(q, key=lambda vertex: dist[vertex])
q.remove(u)
if dist[u] == inf or u == dest:
break
for v, cost in neighbours[u]:
alt = dist[u] + cost
if alt < dist[v]:
dist[v] = alt
previous[v] = u
s, u = deque(), dest
while previous[u]:
s.appendleft(u)
u = previous[u]
s.appendleft(u)
return s
graph = Graph([("a", "b", 7), ("a", "c", 9), ("a", "f", 14), ("b", "c", 10),
("b", "d", 15), ("c", "d", 11), ("c", "f", 2), ("d", "e", 6),
("e", "f", 9)])
pp(graph.dijkstra("a", "e"))
|
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, "Popeye"),
(28, "Alan")]
table2 = [("Jonah", "Whales"),
("Jonah", "Spiders"),
("Alan", "Ghosts"),
("Alan", "Zombies"),
("Glory", "Buffy")]
for row in hashJoin(table1, 1, table2, 0):
print(row)
|
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))
return method
example = Example()
example.foo()
example.bar()
example.grill()
example.ding("dong")
|
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.radius = radius
def __repr__(self):
return '<Circle 0x%x x: %f y: %f radius: %f>' % (
id(self), self.center.x, self.center.y, self.radius)
|
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, Writer[T]], *msgs: str):
if isinstance(value, Writer):
self.value: T = value.value
self.msgs: List[str] = value.msgs + list(msgs)
else:
self.value = value
self.msgs = list(f"{msg}: {self.value}" for msg in msgs)
def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
writer = func(self.value)
return Writer(writer, *self.msgs)
def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
return self.bind(func)
def __str__(self):
return f"{self.value}\n{os.linesep.join(reversed(self.msgs))}"
def __repr__(self):
return f"Writer({self.value}, \"{', '.join(reversed(self.msgs))}\")"
def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:
@functools.wraps(func)
def wrapped(value):
return Writer(func(value), msg)
return wrapped
if __name__ == "__main__":
square_root = lift(math.sqrt, "square root")
add_one = lift(lambda x: x + 1, "add one")
half = lift(lambda x: x / 2, "div two")
print(Writer(5, "initial") >> square_root >> add_one >> half)
|
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] - goal[0])
dy = abs(start[1] - goal[1])
return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)
def get_vertex_neighbours(self, pos):
n = []
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:
x2 = pos[0] + dx
y2 = pos[1] + dy
if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:
continue
n.append((x2, y2))
return n
def move_cost(self, a, b):
for barrier in self.barriers:
if b in barrier:
return 100
return 1
def AStarSearch(start, end, graph):
G = {}
F = {}
G[start] = 0
F[start] = graph.heuristic(start, end)
closedVertices = set()
openVertices = set([start])
cameFrom = {}
while len(openVertices) > 0:
current = None
currentFscore = None
for pos in openVertices:
if current is None or F[pos] < currentFscore:
currentFscore = F[pos]
current = pos
if current == end:
path = [current]
while current in cameFrom:
current = cameFrom[current]
path.append(current)
path.reverse()
return path, F[end]
openVertices.remove(current)
closedVertices.add(current)
for neighbour in graph.get_vertex_neighbours(current):
if neighbour in closedVertices:
continue
candidateG = G[current] + graph.move_cost(current, neighbour)
if neighbour not in openVertices:
openVertices.add(neighbour)
elif candidateG >= G[neighbour]:
continue
cameFrom[neighbour] = current
G[neighbour] = candidateG
H = graph.heuristic(neighbour, end)
F[neighbour] = G[neighbour] + H
raise RuntimeError("A* failed to find a solution")
if __name__=="__main__":
graph = AStarGraph()
result, cost = AStarSearch((0,0), (7,7), graph)
print ("route", result)
print ("cost", cost)
plt.plot([v[0] for v in result], [v[1] for v in result])
for barrier in graph.barriers:
plt.plot([v[0] for v in barrier], [v[1] for v in barrier])
plt.xlim(-1,8)
plt.ylim(-1,8)
plt.show()
|
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-neighbours of point p1 of picture, in order'''
i = image
x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1
return [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1],
i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]
def transitions(neighbours):
n = neighbours + neighbours[0:1]
return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))
def zhangSuen(image):
changing1 = changing2 = [(-1, -1)]
while changing1 or changing2:
changing1 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P4 * P6 * P8 == 0 and
P2 * P4 * P6 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing1.append((x,y))
for x, y in changing1: image[y][x] = 0
changing2 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P2 * P6 * P8 == 0 and
P2 * P4 * P8 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing2.append((x,y))
for x, y in changing2: image[y][x] = 0
return image
if __name__ == '__main__':
for picture in (beforeTxt, smallrc01, rc01):
image = intarray(picture)
print('\nFrom:\n%s' % toTxt(image))
after = zhangSuen(image)
print('\nTo thinned:\n%s' % toTxt(after))
|
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 c == " " and curr_word != "":
sentence_list.append(curr_word+" ")
curr_word = ""
else:
curr_word += c
if len(curr_word) > 0:
sentence_list.append(curr_word)
return sentence_list
def my_num_to_words(p, my_number):
number_string_list = p.number_to_words(my_number, wantlist=True, andword='')
number_string = number_string_list[0]
for i in range(1,len(number_string_list)):
number_string += " " + number_string_list[i]
return number_string
def build_sentence(p, max_words):
sentence_list = split_with_spaces("Four is the number of letters in the first word of this sentence,")
num_words = 13
word_number = 2
while num_words < max_words:
ordinal_string = my_num_to_words(p, p.ordinal(word_number))
word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))
new_string = " "+word_number_string+" in the "+ordinal_string+","
new_list = split_with_spaces(new_string)
sentence_list += new_list
num_words += len(new_list)
word_number += 1
return sentence_list, num_words
def word_and_counts(word_num):
sentence_list, num_words = build_sentence(p, word_num)
word_str = sentence_list[word_num - 1].strip(' ,')
num_letters = len(word_str)
num_characters = 0
for word in sentence_list:
num_characters += len(word)
print('Word {0:8d} is "{1}", with {2} letters. Length of the sentence so far: {3} '.format(word_num,word_str,num_letters,num_characters))
p = inflect.engine()
sentence_list, num_words = build_sentence(p, 201)
print(" ")
print("The lengths of the first 201 words are:")
print(" ")
print('{0:3d}: '.format(1),end='')
total_characters = 0
for word_index in range(201):
word_length = count_letters(sentence_list[word_index])
total_characters += len(sentence_list[word_index])
print('{0:2d}'.format(word_length),end='')
if (word_index+1) % 20 == 0:
print(" ")
print('{0:3d}: '.format(word_index + 2),end='')
else:
print(" ",end='')
print(" ")
print(" ")
print("Length of the sentence so far: "+str(total_characters))
print(" ")
word_and_counts(1000)
word_and_counts(10000)
word_and_counts(100000)
word_and_counts(1000000)
word_and_counts(10000000)
|
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[n]]
lenlst = len(lst)
for i in lst[n:]:
yield i
|
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))
def update(e):
if not e.char.isdigit():
tkMessageBox.showerror('Error', 'Invalid input !')
return "break"
e = Entry(text=s)
e.grid(column=0, row=0, **options)
e.bind('<Key>', update)
b1 = Button(text="Increase", command=increase, **options )
b1.grid(column=1, row=0, **options)
b2 = Button(text="Random", command=rand, **options)
b2.grid(column=2, row=0, **options)
mainloop()
|
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 84.162 == molar_mass('C6H12')
assert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')
assert 176.124 == molar_mass('C6H4O2(OH)4')
assert 386.664 == molar_mass('C27H46O')
assert 315 == molar_mass('Uue')
|
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 = {' ':' ', '.': ' ', '@':'@', '
for r, row in enumerate(data):
for c, ch in enumerate(row):
sdata += maps[ch]
ddata += mapd[ch]
if ch == '@':
px = c
py = r
def push(x, y, dx, dy, data):
if sdata[(y+2*dy) * nrows + x+2*dx] == '
data[(y+2*dy) * nrows + x+2*dx] != ' ':
return None
data2 = array("c", data)
data2[y * nrows + x] = ' '
data2[(y+dy) * nrows + x+dx] = '@'
data2[(y+2*dy) * nrows + x+2*dx] = '*'
return data2.tostring()
def is_solved(data):
for i in xrange(len(data)):
if (sdata[i] == '.') != (data[i] == '*'):
return False
return True
def solve():
open = deque([(ddata, "", px, py)])
visited = set([ddata])
dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'),
(0, 1, 'd', 'D'), (-1, 0, 'l', 'L'))
lnrows = nrows
while open:
cur, csol, x, y = open.popleft()
for di in dirs:
temp = cur
dx, dy = di[0], di[1]
if temp[(y+dy) * lnrows + x+dx] == '*':
temp = push(x, y, dx, dy, temp)
if temp and temp not in visited:
if is_solved(temp):
return csol + di[3]
open.append((temp, csol + di[3], x+dx, y+dy))
visited.add(temp)
else:
if sdata[(y+dy) * lnrows + x+dx] == '
temp[(y+dy) * lnrows + x+dx] != ' ':
continue
data2 = array("c", temp)
data2[y * lnrows + x] = ' '
data2[(y+dy) * lnrows + x+dx] = '@'
temp = data2.tostring()
if temp not in visited:
if is_solved(temp):
return csol + di[2]
open.append((temp, csol + di[2], x+dx, y+dy))
visited.add(temp)
return "No solution"
level = """\
psyco.full()
init(level)
print level, "\n\n", solve()
|
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
while not n%c:
n,p,d = n//c, p*c, d + (p,)
yield(d)
if n > 1: yield((n,))
r = [1]
for e in prime_powers(n):
r += [a*b for a in r for b in e]
return r[:-1]
def powerset(s: List[int]) -> List[Tuple[int, ...]]:
return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))
def is_practical(x: int) -> bool:
if x == 1:
return True
if x %2:
return False
f = factors5(x)
ps = powerset(f)
found = {y for y in {sum(i) for i in ps}
if 1 <= y < x}
return len(found) == x - 1
if __name__ == '__main__':
n = 333
p = [x for x in range(1, n + 1) if is_practical(x)]
print(f"There are {len(p)} Practical numbers from 1 to {n}:")
print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])
x = 666
print(f"\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")
|
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:
return a, b
return -1, -1
def find_solution(pa, x, y, z):
if z > lastNumber:
return 1
if exists[z] == 1:
s = find_next(pa, x, y, z)
if s[0] < 0:
return 0
return find_solution(pa, s[0], s[1], z + 1)
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] == 0:
pa[a][b] = z
r = find_solution(pa, a, b, z + 1)
if r == 1:
return 1
pa[a][b] = 0
return 0
def solve(pz, w, h):
global lastNumber, wid, hei, exists
lastNumber = w * h
wid = w
hei = h
exists = [0 for j in range(lastNumber + 1)]
pa = [[0 for j in range(h)] for i in range(w)]
st = pz.split()
idx = 0
for j in range(h):
for i in range(w):
if st[idx] == ".":
idx += 1
else:
pa[i][j] = int(st[idx])
exists[pa[i][j]] = 1
idx += 1
x = 0
y = 0
t = w * h + 1
for j in range(h):
for i in range(w):
if pa[i][j] != 0 and pa[i][j] < t:
t = pa[i][j]
x = i
y = j
return find_solution(pa, x, y, t + 1), pa
def show_result(r):
if r[0] == 1:
for j in range(hei):
for i in range(wid):
stdout.write(" {:0{}d}".format(r[1][i][j], 2))
print()
else:
stdout.write("No Solution!\n")
print()
r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17"
" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9)
show_result(r)
r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37"
" . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9)
show_result(r)
r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55"
" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9)
show_result(r)
|
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 + neighbours[i][0]
b = y + neighbours[i][1]
if is_valid(a, b) and pa[a][b] == 0:
pa[a][b] = v
r = iterate(pa, a, b, v + 1)
if r == 1:
return r
pa[a][b] = 0
return 0
def solve(pz, w, h):
global cnt, pWid, pHei
pa = [[-1 for j in range(h)] for i in range(w)]
f = 0
pWid = w
pHei = h
for j in range(h):
for i in range(w):
if pz[f] == "1":
pa[i][j] = 0
cnt += 1
f += 1
for y in range(h):
for x in range(w):
if pa[x][y] == 0:
pa[x][y] = 1
if 1 == iterate(pa, x, y, 2):
return 1, pa
pa[x][y] = 0
return 0, pa
r = solve("011011011111111111111011111000111000001000", 7, 6)
if r[0] == 1:
for j in range(6):
for i in range(7):
if r[1][i][j] == -1:
stdout.write(" ")
else:
stdout.write(" {:0{}d}".format(r[1][i][j], 2))
print()
else:
stdout.write("No solution!")
|
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 s], w + 1 - sum(s))]
def deduce(hr, vr):
def allowable(row):
return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)
def fits(a, b):
return all(x & y for x, y in izip(a, b))
def fix_col(n):
c = [x[n] for x in can_do]
cols[n] = [x for x in cols[n] if fits(x, c)]
for i, x in enumerate(allowable(cols[n])):
if x != can_do[i][n]:
mod_rows.add(i)
can_do[i][n] &= x
def fix_row(n):
c = can_do[n]
rows[n] = [x for x in rows[n] if fits(x, c)]
for i, x in enumerate(allowable(rows[n])):
if x != can_do[n][i]:
mod_cols.add(i)
can_do[n][i] &= x
def show_gram(m):
for x in m:
print " ".join("x
print
w, h = len(vr), len(hr)
rows = [gen_row(w, x) for x in hr]
cols = [gen_row(h, x) for x in vr]
can_do = map(allowable, rows)
mod_rows, mod_cols = set(), set(xrange(w))
while mod_cols:
for i in mod_cols:
fix_col(i)
mod_cols = set()
for i in mod_rows:
fix_row(i)
mod_rows = set()
if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):
print "Solution would be unique"
else:
print "Solution may not be unique, doing exhaustive search:"
out = [0] * h
def try_all(n = 0):
if n >= h:
for j in xrange(w):
if [x[j] for x in out] not in cols[j]:
return 0
show_gram(out)
return 1
sol = 0
for x in rows[n]:
out[n] = x
sol += try_all(n + 1)
return sol
n = try_all()
if not n:
print "No solution."
elif n == 1:
print "Unique solution."
else:
print n, "solutions."
print
def solve(p, show_runs=True):
s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]
for l in p.splitlines()]
if show_runs:
print "Horizontal runs:", s[0]
print "Vertical runs:", s[1]
deduce(s[0], s[1])
def main():
fn = "nonogram_problems.txt"
for p in (x for x in open(fn).read().split("\n\n") if x):
solve(p)
print "Extra example not solvable by deduction alone:"
solve("B B A A\nB B A A")
print "Extra example where there is no solution:"
solve("B A A\nA A A")
main()
|
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 range(n_rows)]
self.solutions = []
def read_words(filename):
max_len = max(n_rows, n_cols)
words = []
with open(filename, "r") as file:
for line in file:
s = line.strip().lower()
if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:
words.append(s)
return words
def place_message(grid, msg):
msg = re.sub(r'[^A-Z]', "", msg.upper())
message_len = len(msg)
if 0 < message_len < grid_size:
gap_size = grid_size // message_len
for i in range(0, message_len):
pos = i * gap_size + randint(0, gap_size)
grid.cells[pos // n_cols][pos % n_cols] = msg[i]
return message_len
return 0
def try_location(grid, word, direction, pos):
r = pos // n_cols
c = pos % n_cols
length = len(word)
if (dirs[direction][0] == 1 and (length + c) > n_cols) or \
(dirs[direction][0] == -1 and (length - 1) > c) or \
(dirs[direction][1] == 1 and (length + r) > n_rows) or \
(dirs[direction][1] == -1 and (length - 1) > r):
return 0
rr = r
cc = c
i = 0
overlaps = 0
while i < length:
if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:
return 0
cc += dirs[direction][0]
rr += dirs[direction][1]
i += 1
rr = r
cc = c
i = 0
while i < length:
if grid.cells[rr][cc] == word[i]:
overlaps += 1
else:
grid.cells[rr][cc] = word[i]
if i < length - 1:
cc += dirs[direction][0]
rr += dirs[direction][1]
i += 1
letters_placed = length - overlaps
if letters_placed > 0:
grid.solutions.append("{0:<10} ({1},{2})({3},{4})".format(word, c, r, cc, rr))
return letters_placed
def try_place_word(grid, word):
rand_dir = randint(0, len(dirs))
rand_pos = randint(0, grid_size)
for direction in range(0, len(dirs)):
direction = (direction + rand_dir) % len(dirs)
for pos in range(0, grid_size):
pos = (pos + rand_pos) % grid_size
letters_placed = try_location(grid, word, direction, pos)
if letters_placed > 0:
return letters_placed
return 0
def create_word_search(words):
grid = None
num_attempts = 0
while num_attempts < 100:
num_attempts += 1
shuffle(words)
grid = Grid()
message_len = place_message(grid, "Rosetta Code")
target = grid_size - message_len
cells_filled = 0
for word in words:
cells_filled += try_place_word(grid, word)
if cells_filled == target:
if len(grid.solutions) >= min_words:
grid.num_attempts = num_attempts
return grid
else:
break
return grid
def print_result(grid):
if grid is None or grid.num_attempts == 0:
print("No grid to display")
return
size = len(grid.solutions)
print("Attempts: {0}".format(grid.num_attempts))
print("Number of words: {0}".format(size))
print("\n 0 1 2 3 4 5 6 7 8 9\n")
for r in range(0, n_rows):
print("{0} ".format(r), end='')
for c in range(0, n_cols):
print(" %c " % grid.cells[r][c], end='')
print()
print()
for i in range(0, size - 1, 2):
print("{0} {1}".format(grid.solutions[i], grid.solutions[i+1]))
if size % 2 == 1:
print(grid.solutions[size - 1])
if __name__ == "__main__":
print_result(create_word_search(read_words("unixdict.txt")))
|
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.rte.len = 0
self.S = [0]
self.maxSufT = self.rte
def get_max_suffix_pal(self, startNode, a):
u = startNode
i = len(self.S)
k = u.len
while id(u) != id(self.rto) and self.S[i - k - 1] != a:
assert id(u) != id(u.link)
u = u.link
k = u.len
return u
def add(self, a):
Q = self.get_max_suffix_pal(self.maxSufT, a)
createANewNode = not a in Q.edges
if createANewNode:
P = Node()
self.nodes.append(P)
P.len = Q.len + 2
if P.len == 1:
P.link = self.rte
else:
P.link = self.get_max_suffix_pal(Q.link, a).edges[a]
Q.edges[a] = P
self.maxSufT = Q.edges[a]
self.S.append(a)
return createANewNode
def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):
for lnkName in nd.edges:
nd2 = nd.edges[lnkName]
self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)
if id(nd) != id(self.rto) and id(nd) != id(self.rte):
tmp = "".join(charsToHere)
if id(nodesToHere[0]) == id(self.rte):
assembled = tmp[::-1] + tmp
else:
assembled = tmp[::-1] + tmp[1:]
result.append(assembled)
if __name__=="__main__":
st = "eertree"
print ("Processing string", st)
eertree = Eertree()
for ch in st:
eertree.add(ch)
print ("Number of sub-palindromes:", len(eertree.nodes))
result = []
eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result)
eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result)
print ("Sub-palindromes:", result)
|
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 printZumkellers(N, oddonly=False):
nprinted = 0
for n in range(1, 10**5):
if (oddonly == False or n % 2) and isZumkeller(n):
print(f'{n:>8}', end='')
nprinted += 1
if nprinted % 10 == 0:
print()
if nprinted >= N:
return
print("220 Zumkeller numbers:")
printZumkellers(220)
print("\n\n40 odd Zumkeller numbers:")
printZumkellers(40, True)
|
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().prec = prec
last = 0
for i,x in zip(count(), to_decimal(b)):
if x == last:
print(f'after {i} iterations:\n\t{x}')
break
last = x
for b in range(4):
coefs = [n for _,n in islice(metallic_ratio(b), 15)]
print(f'\nb = {b}: {coefs}')
stable(b, 32)
print(f'\nb = 1 with 256 digits:')
stable(1, 256)
|
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, other):
return (self * other + other * self) * 0.5
def __getitem__(self, i):
return self.dims[i]
def __setitem__(self, i, v):
self.dims[i] = v
def __neg__(self):
return self * -1.0
def __add__(self, other):
result = copy.copy(other.dims)
for i in xrange(0, len(self.dims)):
result[i] += self.dims[i]
return Vector(result)
def __mul__(self, other):
if isinstance(other, Vector):
result = [0.0] * 32
for i in xrange(0, len(self.dims)):
if self.dims[i] != 0.0:
for j in xrange(0, len(self.dims)):
if other.dims[j] != 0.0:
s = reoderingSign(i, j) * self.dims[i] * other.dims[j]
k = i ^ j
result[k] += s
return Vector(result)
else:
result = copy.copy(self.dims)
for i in xrange(0, len(self.dims)):
self.dims[i] *= other
return Vector(result)
def __str__(self):
return str(self.dims)
def e(n):
assert n <= 4, "n must be less than 5"
result = Vector([0.0] * 32)
result[1 << n] = 1.0
return result
def randomVector():
result = Vector([0.0] * 32)
for i in xrange(0, 5):
result += Vector([random.uniform(0, 1)]) * e(i)
return result
def randomMultiVector():
result = Vector([0.0] * 32)
for i in xrange(0, 32):
result[i] = random.uniform(0, 1)
return result
def main():
for i in xrange(0, 5):
for j in xrange(0, 5):
if i < j:
if e(i).dot(e(j))[0] != 0.0:
print "Unexpected non-null scalar product"
return
elif i == j:
if e(i).dot(e(j))[0] == 0.0:
print "Unexpected non-null scalar product"
a = randomMultiVector()
b = randomMultiVector()
c = randomMultiVector()
x = randomVector()
print (a * b) * c
print a * (b * c)
print
print a * (b + c)
print a * b + a * c
print
print (a + b) * c
print a * c + b * c
print
print x * x
main()
|
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 = 0
while i < len(suf):
b = suf[i]
x2 = 0
while True:
children = self.nodes[n].ch
if x2 == len(children):
n2 = len(self.nodes)
self.nodes.append(Node(suf[i:], []))
self.nodes[n].ch.append(n2)
return
n2 = children[x2]
if self.nodes[n2].sub[0] == b:
break
x2 = x2 + 1
sub2 = self.nodes[n2].sub
j = 0
while j < len(sub2):
if suf[i + j] != sub2[j]:
n3 = n2
n2 = len(self.nodes)
self.nodes.append(Node(sub2[:j], [n3]))
self.nodes[n3].sub = sub2[j:]
self.nodes[n].ch[x2] = n2
break
j = j + 1
i = i + j
n = n2
def visualize(self):
if len(self.nodes) == 0:
print "<empty>"
return
def f(n, pre):
children = self.nodes[n].ch
if len(children) == 0:
print "--", self.nodes[n].sub
return
print "+-", self.nodes[n].sub
for c in children[:-1]:
print pre, "+-",
f(c, pre + " | ")
print pre, "+-",
f(children[-1], pre + " ")
f(0, "")
SuffixTree("banana$").visualize()
|
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
raise ValueError,"Value %s should be >=0 and <= 10" % b
ValueError: Value 11 should be >=0 and <= 10
>>> x
3
>>> type(x)
<class '__main__.num'>
>>>
|
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 href="
<use href="
</g>
</svg>''')
penrose(6)
|
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.append(i)
print('Sphenic numbers less than 1000:')
for i, n in enumerate(sphenics1m):
if n < 1000:
print(f'{n : 5}', end='\n' if (i + 1) % 15 == 0 else '')
else:
break
print('\n\nSphenic triplets less than 10_000:')
for i, n in enumerate(sphenic_triplets1m):
if n < 10_000:
print(f'({n - 2} {n - 1} {n})', end='\n' if (i + 1) % 3 == 0 else ' ')
else:
break
print('\nThere are', len(sphenics1m), 'sphenic numbers and', len(sphenic_triplets1m),
'sphenic triplets less than 1 million.')
S2HK = sphenics1m[200_000 - 1]
T5K = sphenic_triplets1m[5000 - 1]
print(f'The 200_000th sphenic number is {S2HK}, with prime factors {list(factorint(S2HK).keys())}.')
print(f'The 5000th sphenic triplet is ({T5K - 2} {T5K - 1} {T5K}).')
|
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.islink(fullFina)
if isSymLink:
continue
si = os.path.getsize(fullFina)
if si < minSize:
continue
if si not in knownFiles:
knownFiles[si] = {}
h = hashlib.new(hashName)
h.update(open(fullFina, "rb").read())
hashed = h.digest()
if hashed in knownFiles[si]:
fileRec = knownFiles[si][hashed]
fileRec.append(fullFina)
else:
knownFiles[si][hashed] = [fullFina]
sizeList = list(knownFiles.keys())
sizeList.sort(reverse=True)
for si in sizeList:
filesAtThisSize = knownFiles[si]
for hashVal in filesAtThisSize:
if len(filesAtThisSize[hashVal]) < 2:
continue
fullFinaLi = filesAtThisSize[hashVal]
print ("=======Duplicate=======")
for fullFina in fullFinaLi:
st = os.stat(fullFina)
isHardLink = st.st_nlink > 1
infoStr = []
if isHardLink:
infoStr.append("(Hard linked)")
fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ')
print (fmtModTime, si, os.path.relpath(fullFina, pth), " ".join(infoStr))
if __name__=="__main__":
FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)
|
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 and pz[x][y] == 0:
pz[x][y] = idx
if 1 == solve(pz, sz, x, y, idx + 1, cnt):
return 1
pz[x][y] = 0
return 0
def find_solution(pz, sz):
p = [[-1 for j in range(sz)] for i in range(sz)]
idx = x = y = cnt = 0
for j in range(sz):
for i in range(sz):
if pz[idx] == "x":
p[i][j] = 0
cnt += 1
elif pz[idx] == "s":
p[i][j] = 1
cnt += 1
x = i
y = j
idx += 1
if 1 == solve(p, sz, x, y, 2, cnt):
for j in range(sz):
for i in range(sz):
if p[i][j] != -1:
stdout.write(" {:0{}d}".format(p[i][j], 2))
else:
stdout.write(" ")
print()
else:
print("Cannot solve this puzzle!")
find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8)
print()
find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
|
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))
itemindices += lastindex[1:]
itemindices.sort()
for index, item in zip(itemindices, items):
data[index] = item
if __name__ == '__main__':
tostring = ' '.join
for data, items in [ (str.split('the cat sat on the mat'), str.split('mat cat')),
(str.split('the cat sat on the mat'), str.split('cat mat')),
(list('ABCABCABC'), list('CACA')),
(list('ABCABDABE'), list('EADA')),
(list('AB'), list('B')),
(list('AB'), list('BA')),
(list('ABBA'), list('BA')),
(list(''), list('')),
(list('A'), list('A')),
(list('AB'), list('')),
(list('ABBA'), list('AB')),
(list('ABAB'), list('AB')),
(list('ABAB'), list('BABA')),
(list('ABCCBA'), list('ACAC')),
(list('ABCCBA'), list('CACA')),
]:
print('Data M: %-24r Order N: %-9r' % (tostring(data), tostring(items)), end=' ')
order_disjoint_list_items(data, items)
print("-> M' %r" % tostring(data))
|
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 '+':
a += 1
case '-':
a -= 1
case 'F' | 'G':
x.append(x[-1] + np.cos(a*angle*np.pi/180))
y.append(y[-1] + np.sin(a*angle*np.pi/180))
l = len(x)
for i in range(l - 1):
plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))
plt.gca().set_aspect(1)
plt.show()
curve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)
|
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
def MostFreqKSimilarity(inputStr1, inputStr2):
similarity = 0
for i in range(0, len(inputStr1), 2):
c = inputStr1[i]
cnt1 = int(inputStr1[i + 1])
for j in range(0, len(inputStr2), 2):
if inputStr2[j] == c:
cnt2 = int(inputStr2[j + 1])
similarity += cnt1 + cnt2
break
return similarity
def MostFreqKSDF(inputStr1, inputStr2, K, maxDistance):
return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))
|
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 Player():
def __init__(self, player_index):
self.player_index = player_index
def __repr__(self):
return '%s(%i)' % (self.__class__.__name__, self.player_index)
def __call__(self, safescore, scores, game):
'Returns boolean True to roll again'
pass
class RandPlay(Player):
def __call__(self, safe, scores, game):
'Returns random boolean choice of whether to roll again'
return bool(random.randint(0, 1))
class RollTo20(Player):
def __call__(self, safe, scores, game):
'Roll again if this rounds score < 20'
return (((sum(scores) + safe[self.player_index]) < maxscore)
and(sum(scores) < 20))
class Desparat(Player):
def __call__(self, safe, scores, game):
'Roll again if this rounds score < 20 or someone is within 20 of winning'
return (((sum(scores) + safe[self.player_index]) < maxscore)
and( (sum(scores) < 20)
or max(safe) >= (maxscore - 20)))
def game__str__(self):
'Pretty printer for Game class'
return ("Game(players=%r, maxscore=%i,\n rounds=[\n %s\n ])"
% (self.players, self.maxscore,
',\n '.join(repr(round) for round in self.rounds)))
Game.__str__ = game__str__
def winningorder(players, safescores):
'Return (players in winning order, their scores)'
return tuple(zip(*sorted(zip(players, safescores),
key=lambda x: x[1], reverse=True)))
def playpig(game):
players, maxscore, rounds = game
playercount = len(players)
safescore = [0] * playercount
player = 0
scores=[]
while max(safescore) < maxscore:
startscore = safescore[player]
rolling = players[player](safescore, scores, game)
if rolling:
rolled = randint(1, 6)
scores.append(rolled)
if rolled == 1:
round = Round(who=players[player],
start=startscore,
scores=scores,
safe=safescore[player])
rounds.append(round)
scores, player = [], (player + 1) % playercount
else:
safescore[player] += sum(scores)
round = Round(who=players[player],
start=startscore,
scores=scores,
safe=safescore[player])
rounds.append(round)
if safescore[player] >= maxscore:
break
scores, player = [], (player + 1) % playercount
return winningorder(players, safescore)
if __name__ == '__main__':
game = Game(players=tuple(RandPlay(i) for i in range(playercount)),
maxscore=20,
rounds=[])
print('ONE GAME')
print('Winning order: %r; Respective scores: %r\n' % playpig(game))
print(game)
game = Game(players=tuple(RandPlay(i) for i in range(playercount)),
maxscore=maxscore,
rounds=[])
algos = (RollTo20, RandPlay, Desparat)
print('\n\nMULTIPLE STATISTICS using %r\n for %i GAMES'
% (', '.join(p.__name__ for p in algos), maxgames,))
winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)
for i in range(playercount)),
rounds=[]))[0])
for i in range(maxgames))
print(' Players(position) winning on left; occurrences on right:\n %s'
% ',\n '.join(str(w) for w in winners.most_common()))
|
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)[::-1])
def split_roots_from_relateds(roots_and_relateds):
roots = roots_and_relateds[::]
i = 1
while i < len(roots):
this = roots[i]
if any(this.intersection(prev) for prev in roots[:i]):
del roots[i]
else:
i += 1
root = [min(each_set) for each_set in roots]
related = [min(each_set) for each_set in roots_and_relateds]
related = [n for n in related if n not in root]
return root, related
def find_lychrel(maxn, max_reversions):
'Lychrel number generator'
series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]
roots_and_relateds = [s for s in series if len(s) > max_reversions]
return split_roots_from_relateds(roots_and_relateds)
if __name__ == '__main__':
maxn, reversion_limit = 10000, 500
print("Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds"
% (maxn, reversion_limit))
lychrel, l_related = find_lychrel(maxn, reversion_limit)
print(' Number of Lychrel numbers:', len(lychrel))
print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel))
print(' Number of Lychrel related:', len(l_related))
pals = [x for x in lychrel + l_related if x == reverse_int(x)]
print(' Number of Lychrel palindromes:', len(pals))
print(' Lychrel palindromes:', ', '.join(str(n) for n in pals))
|
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:
if c in rules:
a2 += rules[c]
else:
a2 += c
axiom = a2
return axiom
def draw_lsystem(axiom, rules, angle, iterations):
xp = [1]
yp = [1]
direction = 0
for c in expand(axiom, rules, iterations):
if c == "F":
xn, yn = nextPoint(xp[-1], yp[-1], direction)
xp.append(xn)
yp.append(yn)
elif c == "-":
direction = direction - angle
if direction < 0:
direction = 360 + direction
elif c == "+":
direction = (direction + angle) % 360
plt.plot(xp, yp)
plt.show()
if __name__ == '__main__':
s_axiom = "F+XF+F+XF"
s_rules = {"X": "XF-F+F-XF+F+XF-F+F-X"}
s_angle = 90
draw_lsystem(s_axiom, s_rules, s_angle, 3)
|
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))
return res
def kpowerful(k, upper_bound, count_only=True):
ps = primepowers(k, upper_bound)
def accu(i, ub):
c = 0 if count_only else []
for p in ps[i]:
u = ub//p
if not u: break
c += 1 if count_only else [p]
for j in range(i + 1, len(ps)):
if u < ps[j][0]:
break
c += accu(j, u) if count_only else [p*x for x in accu(j, u)]
return c
res = accu(0, upper_bound)
return res if count_only else sorted(res)
for k in range(2, 11):
res = kpowerful(k, 10**k, count_only=False)
print(f'{len(res)} {k}-powerfuls up to 10^{k}:',
' '.join(str(x) for x in res[:5]),
'...',
' '.join(str(x) for x in res[-5:])
)
for k in range(2, 11):
res = [kpowerful(k, 10**n) for n in range(k+10)]
print(f'{k}-powerful up to 10^{k+10}:',
' '.join(str(x) for x in res))
|
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 = out[i]
if coef != 0:
for j in xrange(1, len(divisor)):
out[i + j] += -divisor[j] * coef
separator = -(len(divisor)-1)
return out[:separator], out[separator:]
if __name__ == '__main__':
print("POLYNOMIAL SYNTHETIC DIVISION")
N = [1, -12, 0, -42]
D = [1, -3]
print(" %s / %s =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
|
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:
oddWordSet.add(word[::2])
[print(i) for i in sorted(oddWordSet)]
|
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(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
|
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(
w, go(s[len(w):])
) if s.startswith(w) else []
def parse(w, xs):
return [Node(w)(xs)] if xs else xs
return lambda s: go(s)
def showParse(tree):
def showTokens(x):
xs = x['nest']
return ' ' + x['root'] + (showTokens(xs[0]) if xs else '')
parses = tree['nest']
return tree['root'] + ':\n' + (
'\n'.join(
map(showTokens, parses)
) if parses else ' ( Not parseable in terms of these words )'
)
def main():
lexicon = 'a bc abc cd b'.split()
testSamples = 'abcd abbc abcbcd acdbc abcdd'.split()
print(unlines(
map(
showParse,
map(
stringParse(lexicon),
testSamples
)
)
))
def Node(v):
return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}
def concatMap(f):
return lambda xs: list(
chain.from_iterable(map(f, xs))
)
def unlines(xs):
return '\n'.join(xs)
if __name__ == '__main__':
main()
|
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 + 1)//2
continue
i = np.searchsorted(blk, root, 'left')
i += blk[i]*blk[i] < lb
if not i:
return blk[0]*blk[0], pos
p = blk[:i + 1]
q = (lb - 1)//p
idx = np.searchsorted(blk, q, 'right')
sel = idx < n
p, idx = p[sel], idx[sel]
q = blk[idx]
sel = q >= p
p, q, idx = p[sel], q[sel], idx[sel]
pos += np.sum(idx - np.arange(len(idx)))
return np.min(p*q), pos
res = []
p = 0
for i in range(100):
p, _ = smallest_brilliant(p + 1)
res.append(p)
print(f'first 100 are {res}')
for i in range(max_order*2):
thresh = 10**i
p, pos = smallest_brilliant(thresh)
print(f'Above 10^{i:2d}: {p:20d} at
|
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 )
open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' )))
return s
dico_url = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt'
read_url = lambda url : urllib.request.urlopen( url ).read()
load_dico = lambda url : tuple( cache( read_url,url ).split( b'\n'))
isnext = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1
def build_map ( words ):
map = [(w.decode('ascii'),[]) for w in words]
for i1,(w1,n1) in enumerate( map ):
for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ):
if isnext( w1,w2 ):
n1.append( i2 )
n2.append( i1 )
return map
def find_path ( words,w1,w2 ):
i = [w[0] for w in words].index( w1 )
front,done,res = [i],{i:-1},[]
while front :
i = front.pop(0)
word,next = words[i]
for n in next :
if n in done : continue
done[n] = i
if words[n][0] == w2 :
while n >= 0 :
res = [words[n][0]] + res
n = done[n]
return ' '.join( res )
front.append( n )
return '%s can not be turned into %s'%( w1,w2 )
for w in ('boy man','girl lady','john jane','alien drool','child adult'):
print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))
|
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[GAP1]
GAP2 = GAP1 + 2
if GAP2 not in gapstarts:
GAP1 = GAP2 + 2
continue
start2 = gapstarts[GAP2]
diff = abs(start2 - start1)
if diff > PM:
print(f"Earliest difference >{PM: ,} between adjacent prime gap starting primes:")
print(f"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\n")
if PM == LIMIT:
break
PM *= 10
else:
GAP1 = GAP2
|
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:
return
b = [x + 1 for x in a]
r.append(b)
return
for i in xrange(last, 0, -1):
a[i], a[last] = a[last], a[i]
recurse(last - 1)
a[i], a[last] = a[last], a[i]
recurse(n - 1)
return r
def printSquare(latin,n):
for row in latin:
print row
print
def reducedLatinSquares(n,echo):
if n <= 0:
if echo:
print []
return 0
elif n == 1:
if echo:
print [1]
return 1
rlatin = [None] * n
for i in xrange(n):
rlatin[i] = [None] * n
for j in xrange(0, n):
rlatin[0][j] = j + 1
class OuterScope:
count = 0
def recurse(i):
rows = dList(n, i)
for r in xrange(len(rows)):
rlatin[i - 1] = rows[r]
justContinue = False
k = 0
while not justContinue and k < i - 1:
for j in xrange(1, n):
if rlatin[k][j] == rlatin[i - 1][j]:
if r < len(rows) - 1:
justContinue = True
break
if i > 2:
return
k += 1
if not justContinue:
if i < n:
recurse(i + 1)
else:
OuterScope.count += 1
if echo:
printSquare(rlatin, n)
recurse(2)
return OuterScope.count
def factorial(n):
if n == 0:
return 1
prod = 1
for i in xrange(2, n + 1):
prod *= i
return prod
print "The four reduced latin squares of order 4 are:\n"
reducedLatinSquares(4,True)
print "The size of the set of reduced latin squares for the following orders"
print "and hence the total number of latin squares of these orders are:\n"
for n in xrange(1, 7):
size = reducedLatinSquares(n, False)
f = factorial(n - 1)
f *= f * n * size
print "Order %d: Size %-4d x %d! x %d! => Total %d" % (n, size, n, n - 1, f)
|
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, 1, 1, 1, 0, 1): 3,
(0, 1, 0, 0, 0, 1, 1): 4,
(0, 1, 1, 0, 0, 0, 1): 5,
(0, 1, 0, 1, 1, 1, 1): 6,
(0, 1, 1, 1, 0, 1, 1): 7,
(0, 1, 1, 0, 1, 1, 1): 8,
(0, 0, 0, 1, 0, 1, 1): 9,
}
RIGHT_DIGITS = {
(1, 1, 1, 0, 0, 1, 0): 0,
(1, 1, 0, 0, 1, 1, 0): 1,
(1, 1, 0, 1, 1, 0, 0): 2,
(1, 0, 0, 0, 0, 1, 0): 3,
(1, 0, 1, 1, 1, 0, 0): 4,
(1, 0, 0, 1, 1, 1, 0): 5,
(1, 0, 1, 0, 0, 0, 0): 6,
(1, 0, 0, 0, 1, 0, 0): 7,
(1, 0, 0, 1, 0, 0, 0): 8,
(1, 1, 1, 0, 1, 0, 0): 9,
}
MODULES = {
" ": 0,
"
}
DIGITS_PER_SIDE = 6
MODULES_PER_DIGIT = 7
class ParityError(Exception):
class ChecksumError(Exception):
def group(iterable, n):
args = [iter(iterable)] * n
return tuple(itertools.zip_longest(*args))
def parse(barcode):
match = RE_BARCODE.match(barcode)
left = group((MODULES[c] for c in match.group("left")), MODULES_PER_DIGIT)
right = group((MODULES[c] for c in match.group("right")), MODULES_PER_DIGIT)
left, right = check_parity(left, right)
return tuple(
itertools.chain(
(LEFT_DIGITS[d] for d in left),
(RIGHT_DIGITS[d] for d in right),
)
)
def check_parity(left, right):
left_parity = sum(sum(d) % 2 for d in left)
right_parity = sum(sum(d) % 2 for d in right)
if left_parity == 0 and right_parity == DIGITS_PER_SIDE:
_left = tuple(tuple(reversed(d)) for d in reversed(right))
right = tuple(tuple(reversed(d)) for d in reversed(left))
left = _left
elif left_parity != DIGITS_PER_SIDE or right_parity != 0:
error = tuple(
itertools.chain(
(LEFT_DIGITS.get(d, "_") for d in left),
(RIGHT_DIGITS.get(d, "_") for d in right),
)
)
raise ParityError(" ".join(str(d) for d in error))
return left, right
def checksum(digits):
odds = (digits[i] for i in range(0, 11, 2))
evens = (digits[i] for i in range(1, 10, 2))
check_digit = (sum(odds) * 3 + sum(evens)) % 10
if check_digit != 0:
check_digit = 10 - check_digit
if digits[-1] != check_digit:
raise ChecksumError(str(check_digit))
return check_digit
def main():
barcodes = [
"
"
"
"
"
"
"
"
"
"
"
]
for barcode in barcodes:
try:
digits = parse(barcode)
except ParityError as err:
print(f"{err} parity error!")
continue
try:
check_digit = checksum(digits)
except ChecksumError as err:
print(f"{' '.join(str(d) for d in digits)} checksum error! ({err})")
continue
print(f"{' '.join(str(d) for d in digits)}")
if __name__ == "__main__":
main()
|
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 to is None:
to = 'I' if from_ == 'J' else ''
def canonicalize(s):
return filter(str.isupper, s.upper()).replace(from_, to)
m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)
enc = {}
for row in m:
for i, j in product(xrange(5), repeat=2):
if i != j:
enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]
for c in zip(*m):
for i, j in product(xrange(5), repeat=2):
if i != j:
enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]
for i1, j1, i2, j2 in product(xrange(5), repeat=4):
if i1 != i2 and j1 != j2:
enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]
dec = dict((v, k) for k, v in enc.iteritems())
def sub_enc(txt):
lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt))
return " ".join(enc[a + (b if b else 'X')] for a, b in lst)
def sub_dec(encoded):
return " ".join(dec[p] for p in partition(canonicalize(encoded), 2))
return sub_enc, sub_dec
(encode, decode) = playfair("Playfair example")
orig = "Hide the gold in...the TREESTUMP!!!"
print "Original:", orig
enc = encode(orig)
print "Encoded:", enc
print "Decoded:", decode(enc)
|
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 i in range(numPoints-1)
for j in range(i+1,numPoints)),
key=itemgetter(0))
def closestPair(point):
xP = sorted(point, key= attrgetter('real'))
yP = sorted(point, key= attrgetter('imag'))
return _closestPair(xP, yP)
def _closestPair(xP, yP):
numPoints = len(xP)
if numPoints <= 3:
return bruteForceClosestPair(xP)
Pl = xP[:numPoints/2]
Pr = xP[numPoints/2:]
Yl, Yr = [], []
xDivider = Pl[-1].real
for p in yP:
if p.real <= xDivider:
Yl.append(p)
else:
Yr.append(p)
dl, pairl = _closestPair(Pl, Yl)
dr, pairr = _closestPair(Pr, Yr)
dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)
closeY = [p for p in yP if abs(p.real - xDivider) < dm]
numCloseY = len(closeY)
if numCloseY > 1:
closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))
for i in range(numCloseY-1)
for j in range(i+1,min(i+8, numCloseY))),
key=itemgetter(0))
return (dm, pairm) if dm <= closestY[0] else closestY
else:
return dm, pairm
def times():
import timeit
functions = [bruteForceClosestPair, closestPair]
for f in functions:
print 'Time for', f.__name__, timeit.Timer(
'%s(pointList)' % f.__name__,
'from closestpair import %s, pointList' % f.__name__).timeit(number=1)
pointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]
if __name__ == '__main__':
pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]
print pointList
print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)
print ' closestPair:', closestPair(pointList)
for i in range(10):
pointList = [randrange(11)+1j*randrange(11) for i in range(10)]
print '\n', pointList
print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)
print ' closestPair:', closestPair(pointList)
print '\n'
times()
times()
times()
|
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) / 2.0
colorMode(HSB)
c = color(int(h * 255), int(s * 255), 255)
set(x, y, c)
|
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 wcount < 11 else f'[{len(str(wag))} digit number]')
wagstaff(24)
|
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 self.default:
self.data[key] = self.default[key]
else:
raise NotImplementedError
def __setitem__(self, key, item):
if self.__init:
super().__setitem__(key, item)
elif key in self.data:
self.data[key] = item
else:
raise KeyError
def __repr__(self):
return "%s(%s)" % (type(self).__name__, super().__repr__())
def fromkeys(cls, iterable, value=None):
if self.__init:
super().fromkeys(cls, iterable, value)
else:
for key in iterable:
if key in self.data:
self.data[key] = value
else:
raise KeyError
def clear(self):
self.data.update(copy.deepcopy(self.default))
def pop(self, key, default=None):
raise NotImplementedError
def popitem(self):
raise NotImplementedError
def update(self, E, **F):
if self.__init:
super().update(E, **F)
else:
haskeys = False
try:
keys = E.keys()
haskeys = Ture
except AttributeError:
pass
if haskeys:
for key in keys:
self[key] = E[key]
else:
for key, val in E:
self[key] = val
for key in F:
self[key] = F[key]
def setdefault(self, key, default=None):
if key not in self.data:
raise KeyError
else:
return super().setdefault(key, default)
|
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 int(str(n)[::-1])
def is_palindrome(n):
return n == reverse(n)
def rare(n):
r = reverse(n)
return (
not is_palindrome(n) and
n > r and
is_square(n+r) and is_square(n-r)
)
if __name__ == '__main__':
main()
|
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(self):
return self.v
class Yaccer(object):
def __init__(self):
self.operstak = []
self.nodestak =[]
self.__dict__.update(self.state1)
def v1( self, valStrg ):
self.nodestak.append( LeafNode(valStrg))
self.__dict__.update(self.state2)
def o2( self, operchar ):
def openParen(a,b):
return 0
opDict= { '+': ( operator.add, 2, 2 ),
'-': (operator.sub, 2, 2 ),
'*': (operator.mul, 3, 3 ),
'/': (operator.div, 3, 3 ),
'^': ( pow, 4, 5 ),
'(': ( openParen, 0, 8 )
}
operPrecidence = opDict[operchar][2]
self.redeuce(operPrecidence)
self.operstak.append(opDict[operchar])
self.__dict__.update(self.state1)
def syntaxErr(self, char ):
print 'parse error - near operator "%s"' %char
def pc2( self,operchar ):
self.redeuce( 1 )
if len(self.operstak)>0:
self.operstak.pop()
else:
print 'Error - no open parenthesis matches close parens.'
self.__dict__.update(self.state2)
def end(self):
self.redeuce(0)
return self.nodestak.pop()
def redeuce(self, precidence):
while len(self.operstak)>0:
tailOper = self.operstak[-1]
if tailOper[1] < precidence: break
tailOper = self.operstak.pop()
vrgt = self.nodestak.pop()
vlft= self.nodestak.pop()
self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))
state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }
state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }
def Lex( exprssn, p ):
bgn = None
cp = -1
for c in exprssn:
cp += 1
if c in '+-/*^()':
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
if c=='(': p.po(p, c)
elif c==')':p.pc(p, c)
else: p.o(p, c)
elif c in ' \t':
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
elif c in '0123456789':
if bgn is None:
bgn = cp
else:
print 'Invalid character in expression'
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
if bgn is not None:
p.v(p, exprssn[bgn:cp+1])
bgn = None
return p.end()
expr = raw_input("Expression:")
astTree = Lex( expr, Yaccer())
print expr, '=',astTree.eval()
|
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 = ""
loc = 0
while(loc < len(lines)):
command = lines[loc].strip()
try:
if(command == "Copy"):
clipboard += lines[loc + 1]
elif(command == "CopyFile"):
if(lines[loc + 1] == "TheF*ckingCode"):
clipboard += source
else:
filetext = open(lines[loc+1]).read()
clipboard += filetext
elif(command == "Duplicate"):
clipboard += clipboard * ((int(lines[loc + 1])) - 1)
elif(command == "Pasta!"):
print(clipboard)
sys.exit(0)
else:
fatal_error("unknown command '" + command + "' encountered on line " + str(loc + 1))
except Exception as e:
fatal_error("error while executing command '" + command + "' on line " + str(loc + 1) + ": " + e)
loc += 2
|
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]
nonlocal.x = nonlocal.x - 1
l[nonlocal.x] = u
for u in range(len(g)):
visit(u)
c = [0]*size
def assign(u, root):
if vis[u]:
vis[u] = False
c[u] = root
for v in t[u]:
assign(v, root)
for u in l:
assign(u, u)
return c
g = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]
print kosaraju(g)
|
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),
(membero, ('Englishman', var(), var(), var(), 'red'), houses),
(membero, ('Swede', var(), var(), 'dog', var()), houses),
(membero, ('Dane', var(), 'tea', var(), var()), houses),
(lefto, (var(), var(), var(), var(), 'green'),
(var(), var(), var(), var(), 'white'), houses),
(membero, (var(), var(), 'coffee', var(), 'green'), houses),
(membero, (var(), 'Pall Mall', var(), 'birds', var()), houses),
(membero, (var(), 'Dunhill', var(), var(), 'yellow'), houses),
(eq, (var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses),
(eq, (('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses),
(nexto, (var(), 'Blend', var(), var(), var()),
(var(), var(), var(), 'cats', var()), houses),
(nexto, (var(), 'Dunhill', var(), var(), var()),
(var(), var(), var(), 'horse', var()), houses),
(membero, (var(), 'Blue Master', 'beer', var(), var()), houses),
(membero, ('German', 'Prince', var(), var(), var()), houses),
(nexto, ('Norwegian', var(), var(), var(), var()),
(var(), var(), var(), var(), 'blue'), houses),
(nexto, (var(), 'Blend', var(), var(), var()),
(var(), var(), 'water', var(), var()), houses),
(membero, (var(), var(), var(), 'zebra', var()), houses)
)
t0 = time.time()
solutions = run(0, houses, zebraRules)
t1 = time.time()
dur = t1-t0
count = len(solutions)
zebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0]
print "%i solutions in %.2f seconds" % (count, dur)
print "The %s is the owner of the zebra" % zebraOwner
print "Here are all the houses:"
for line in solutions[0]:
print str(line)
|
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")**exponent_term(n)
for n in range(10):
print("Term ", n, ' ', int(integer_term(n)))
def almkvist_guillera(floatprecision):
summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')
for n in range(100000000):
nextadd = summed + nthterm(n)
if abs(nextadd - summed) < 10.0**(-floatprecision):
break
summed = nextadd
return nextadd
print('\nπ to 70 digits is ', end='')
mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)
print('mpmath π is ', end='')
mp.nprint(mp.pi, 71)
|
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])
if len(curr_list) > len(longest_list):
longest_list = curr_list
else:
curr_list = [primelist[pindex-1],primelist[pindex]]
old_diff = diff
pindex += 1
print(longest_list)
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])
if len(curr_list) > len(longest_list):
longest_list = curr_list
else:
curr_list = [primelist[pindex-1],primelist[pindex]]
old_diff = diff
pindex += 1
print(longest_list)
|
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):
continue
print(p*q, end = " ");
|
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 w in range(1, len(members)):
if members[w]:
n = w + steplength
while n <= nlimit:
members[n] = True
n += steplength
steplength = nlimit
np = 5
mcpy = members.copy()
for w in range(1, len(members)):
if mcpy[w]:
if np == 5 and w > prime:
np = w
n = prime * w
if n > nlimit:
break
members[n] = False
if np < prime:
break
primes.append(prime)
prime = 3 if prime == 2 else np
nlimit = min(steplength * prime, limit)
newprimes = [i for i in range(2, len(members)) if members[i]]
return sorted(primes + newprimes)
print(pritchard(150))
print('Number of primes up to 1,000,000:', len(pritchard(1000000)))
|
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}'.format(D(n)), end='\n' if n % 10 == 0 else '')
print()
for m in range(1, 21):
print('(D for 10**{}) divided by 7 is {}'.format(m, D(10 ** m) // 7))
|
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) + " : ")
[print(i) for i in set(permutations(baseList))]
print("Permutations for " + baseString + " : ")
[print(i) for i in set(permutations(baseString))]
|
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
index += 1
return (index, so_far) if depth > 1 else so_far
if __name__ == "__main__":
from pprint import pformat
def pnest(nest:list, width: int=9) -> str:
text = pformat(nest, width=width).replace('\n', '\n ')
print(f" OR {text}\n")
exercises = [
[],
[1, 2, 4],
[3, 1, 3, 1],
[1, 2, 3, 1],
[3, 2, 1, 3],
[3, 3, 3, 1, 1, 3, 3, 3],
]
for flat in exercises:
nest = to_tree(flat)
print(f"{flat} NESTS TO: {nest}")
pnest(nest)
|
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 OEIS A000058:")
xs = list(islice(sylvester(), 10))
print('\n'.join([
str(x) for x in xs
]))
print("\nSum of the reciprocals of the first 10 terms:")
print(
reduce(lambda a, x: a + 1 / x, xs, 0)
)
if __name__ == '__main__':
main()
|
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', nachilles, 'Achilles numbers:')
n, found = 0, 0
while found < nachilles:
if is_Achilles(n):
found += 1
print(f'{n: 8,}', end='\n' if found % 10 == 0 else '')
n += 1
print('\nFirst', nstrongachilles, 'strong Achilles numbers:')
n, found = 0, 0
while found < nstrongachilles:
if is_strong_Achilles(n):
found += 1
print(f'{n: 9,}', end='\n' if found % 10 == 0 else '')
n += 1
print('\nCount of Achilles numbers for various intervals:')
intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]
for interval in intervals:
print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))
test_strong_Achilles(50, 100)
|
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()
)
))
def primes():
n = 2
dct = {}
while True:
if n in dct:
for p in dct[n]:
dct.setdefault(n + p, []).append(p)
del dct[n]
else:
yield n
dct[n * n] = [n]
n = 1 + n
if __name__ == '__main__':
main()
|
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 = Counter(word.lower())
if frequency['a']==frequency['e']==frequency['i']==frequency['o']==frequency['u']==1:
print(word)
|
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__(self, other):
assert other.x // 1 == other.x and other.x > 0, "Invalid Operation"
return MaxTropical(self.x * other.x)
def __eq__(self, other):
return self.x == other.x
if __name__ == "__main__":
a = MaxTropical(-2)
b = MaxTropical(-1)
c = MaxTropical(-0.5)
d = MaxTropical(-0.001)
e = MaxTropical(0)
f = MaxTropical(0.5)
g = MaxTropical(1)
h = MaxTropical(1.5)
i = MaxTropical(2)
j = MaxTropical(5)
k = MaxTropical(7)
l = MaxTropical(8)
m = MaxTropical(-Inf)
print("2 * -2 == ", i * a)
print("-0.001 + -Inf == ", d + m)
print("0 * -Inf == ", e * m)
print("1.5 + -1 == ", h + b)
print("-0.5 * 0 == ", c * e)
print("5**7 == ", j**k)
print("5 * (8 + 7)) == ", j * (l + k))
print("5 * 8 + 5 * 7 == ", j * l + j * k)
print("5 * (8 + 7) == 5 * 8 + 5 * 7", j * (l + k) == j * l + j * k)
|
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 (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
def table(n):
def go(xs):
w = len(xs[-1])
return '\n'.join(
' '.join(row) for row in chunksOf(n)([
s.rjust(w, ' ') for s in xs
])
)
return go
if __name__ == '__main__':
main()
|
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().split(',') if r]
def remove(self, rem):
ranges = self.ranges
for i, r in enumerate(ranges):
if r[0] <= rem <= r[1]:
if r[0] == rem:
if r[1] > rem:
r[0] += 1
else:
del ranges[i]
elif r[1] == rem:
if r[0] < rem:
r[1] -= 1
else:
del ranges[i]
else:
r[1], splitrange = rem - 1, [rem + 1, r[1]]
ranges.insert(i + 1, splitrange)
break
if r[0] > rem:
break
return self
def add(self, add):
ranges = self.ranges
for i, r in enumerate(ranges):
if r[0] <= add <= r[1]:
break
elif r[0] - 1 == add:
r[0] = add
break
elif r[1] + 1 == add:
r[1] = add
break
elif r[0] > add:
ranges.insert(i, [add, add])
break
else:
ranges.append([add, add])
return self
return self.consolidate()
def consolidate(self):
"Combine overlapping ranges"
ranges = self.ranges
for this, that in zip(ranges, ranges[1:]):
if this[1] + 1 >= that[0]:
if this[1] >= that[1]:
this[:], that[:] = [], this
else:
this[:], that[:] = [], [this[0], that[1]]
ranges[:] = [r for r in ranges if r]
return self
def __repr__(self):
rr = self.ranges
return ",".join(f"{r[0]}-{r[1]}" for r in rr)
def demo(opp_txt):
by_line = opp_txt.strip().split('\n')
start = by_line.pop(0)
ex = Sequence(start.strip().split()[-1][1:-1])
lines = [line.strip().split() for line in by_line]
opps = [((ex.add if word[0] == "add" else ex.remove), int(word[1]))
for word in lines]
print(f"Start: \"{ex}\"")
for op, val in opps:
print(f" {op.__name__:>6} {val:2} => {op(val)}")
print()
if __name__ == '__main__':
demo()
demo()
demo()
|
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(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}")
return i
print("ERROR: Juggler series starting with $k did not converge in $maxiters iterations")
print(" n l(n) i(n) h(n) or d(n)\n-------------------------------------------")
for k in range(20, 40):
juggler(k, False)
for k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:
juggler(k)
|
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(word)
|
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:
return False
if __name__ == '__main__':
n = 3
c = 0
print("The first 4 Giuga numbers are: ")
while c < 4:
if isGiuga(n):
c += 1
print(n)
n += 1
|
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:
level = []
while lst:
d, name = lst[0]
if d == depth:
children = []
level.append((name, children))
lst.pop(0)
elif d > depth:
to_nest(lst, d, children)
elif d < depth:
return
return level[0] if level else None
if __name__ == '__main__':
print('Start Nest format:')
nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]),
('mocks', [('trolling', [])])])
pp(nest, width=25)
print('\n... To Indent format:')
as_ind = to_indent(nest)
pp(as_ind, width=25)
print('\n... To Nest format:')
as_nest = to_nest(as_ind)
pp(as_nest, width=25)
if nest != as_nest:
print("Whoops round-trip issues")
|
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 repdict[c] else c)
seen[c] += 1
return ''.join(newchars)
print('abracadabra ->', trstring('abracadabra', rep))
|
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(f'{c: 5,}', end='\n' if (i + 1) % 25 == 0 else '')
print(f' Thousandth Curzon with k = {k}: {curzons[999]}.\n')
|
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")
frameRect = pygame.Rect((45, 45), (510, 510))
crosshair = pygame.surface.Surface((10, 10))
crosshair.fill(pygame.Color("magenta"))
pygame.draw.circle(crosshair, pygame.Color("blue"), (5,5), 5, 0)
crosshair.set_colorkey(pygame.Color("magenta"), pygame.RLEACCEL)
crosshair = crosshair.convert()
writer = pygame.font.Font(pygame.font.get_default_font(), 15)
buttons = {}
for b in range(joy.get_numbuttons()):
buttons[b] = [
writer.render(
hex(b)[2:].upper(),
1,
pygame.Color("red"),
pygame.Color("black")
).convert(),
((15*b)+45, 560)
]
while True:
pygame.event.pump()
for events in pygame.event.get():
if events.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(pygame.Color("black"))
x = joy.get_axis(0)
y = joy.get_axis(1)
screen.blit(crosshair, ((x*250)+300-5, (y*250)+300-5))
pygame.draw.rect(screen, pygame.Color("red"), frameRect, 1)
for b in range(joy.get_numbuttons()):
if joy.get_button(b):
screen.blit(buttons[b][0], buttons[b][1])
pygame.display.flip()
clk.tick(40)
|
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 enumerate(ORMISTONS):
if i < 30:
print(f'({o[0] : 6} {o[1] : 6} )',
end='\n' if (i + 1) % 5 == 0 else ' ')
else:
break
print(len(ORMISTONS), 'is the count of Ormiston pairs up to one million.')
|
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, '/', d)
|
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))
mergers.append(merge_me)
merge_me.seek(0)
stack_tops = [f.read(1) for f in mergers]
while stack_tops:
c = min(stack_tops)
sink.write(c)
i = stack_tops.index(c)
t = mergers[i].read(1)
if t:
stack_tops[i] = t
else:
del stack_tops[i]
mergers[i].close()
del mergers[i]
def main():
input_file_too_large_for_memory = io.StringIO('678925341')
t = list(input_file_too_large_for_memory.read())
t.sort()
expect = ''.join(t)
print('expect', expect)
for memory_size in range(1,12):
input_file_too_large_for_memory.seek(0)
output_file_too_large_for_memory = io.StringIO()
sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO)
output_file_too_large_for_memory.seek(0)
assert(output_file_too_large_for_memory.read() == expect)
print('memory size {} passed'.format(memory_size))
if __name__ == '__main__':
example = main
example()
|
Python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.