49
Phil15
30 56 64 Leader of the month
23040/ 25141
Last seen 1 hour ago
Member for 6 years, 2 months, 16 days
Difficulty Advanced
I was a math teacher in France for two years. I'm currently reconverting to IT, I'm here to improve my Python skills, and practice English.

Missions (540) / Solutions (647)
Best solutions / Newest solutions
Initiation
itertools recipe from python docs
All the Same
groupby
itertools.groupby
next
itertools
not
6
First
Multiply (Intro)
lambda
7
4
zip
Goes Right After
zip
bool
False
str
for
First
Time Converter (12h to 24h)
lambda
inline-if
elif
list-comp
split
1-liner: set(string.ascii_lowercase).isdisjoint
All Upper I
isdisjoint
set
3
List/Iterator versions
All the Same
StopIteration
iter
next
all
except
try word.index
Goes Right After
ValueError
index
bool
except
try
lambda with counter.most_common
Sort Array by Element Frequency
collections.Counter
Counter
collections
lambda
list-comp
try except
Between Markers
ValueError
index
except
try
len
6
not set(text) & low_letters
All Upper I
ascii_lowercase
string.ascii_lowercase
string
set
not
generator and simple generalization
Split Pairs
divmod
yield
range
len
for
My flat_list program
Flatten a List
type
is
all
append
list
collections.Counter and list comprehension
Non-unique Elements
collections.Counter
Counter
collections
if-comprehension
list-comp
1
sum "safe bools"
Pawn Brotherhood
find
None
lambda
or
inline-if
1
Home
Generate ugly numbers in a priority queue to get them in order
Ugly Numbers
heappush
heapq.heappush
heappop
heapq.heappop
heapq
1
5
v3: Dynamic Programming, more memory-friendly for large numbers
Ugly Numbers
inline-if
and
range
int
for
1
3
List key possibilities for each clue and cautiously merge them into one full key
Playfair Cipher Attack
collections.abc.Iterator
Iterator
bisect.bisect
issuperset
bisect
1
1
1-liner (clear version in 3rd party)
Rotating Grille Cipher
iter
any
zip
None
lambda
1
2
Find first/last occurence of a sub-string, rotations to filter candidates
Grille Cipher Attack
setdefault
union
raise
divmod
collections.Counter
1
2
groups of signed diffs
Changing direction
itertools.pairwise
pairwise
operator.sub
itertools.starmap
starmap
1
5
numpy for easy rotations, itertools.compress and zip (length-check py3.10+)
Rotating Grille Cipher
compress
itertools.compress
numpy.rot90
rot90
Optional
1
3
.translate(table) done with operator.methodcaller
Atbash Cipher
methodcaller
operator.methodcaller
ascii_uppercase
string.ascii_uppercase
operator
2
3
::diameter
Scytale Encryption
Optional
typing.Optional
None
typing
join
2
[py3.8+] 50 chars with walrus
Split List
lambda
len
5
1
class XY(NamedTuple)
Find Enemy
NamedTuple
typing.NamedTuple
math.atan2
atan2
class
5
1
[py3.8+] 1-liner: 115 chars
Time Converter (24h to 12h)
map
lambda
inline-if
split
int
6
1
Dynamic programming - indexes of the next multiples of 2, 3, 5
Ugly Numbers
inline-if
range
int
for
if
6
islice
Split List
islice
itertools.islice
iter
yield
itertools
10
1
lines generator
Xs and Os Referee
next
yield
zip
if-comprehension
comprehension
11
11
Best-first search with heapq and POO
8 Puzzle
class
heappush
heapq.heappush
heappop
heapq.heappop
12
1
Count recursively because of intersections; intersection function doctested
Mountain Scape
typing.Set
Set
Optional
typing.Optional
Tuple
13
1
update dimensions with rotations
Life Counter
itertools.zip_longest
zip_longest
itertools.product
product
reversed
18
more-itertools import + 1-liner
Changing direction
more_itertools
more_itertools.triplewise
more_itertools.unique_justseen
triplewise
unique_justseen
19
1
sort, get next with diff != min_diff
Missing Number
itertools.pairwise
pairwise
islice
itertools.islice
next
4-lines: ''.join(generator)
Bird Language
yield
isalpha
lambda
join
while
3
Obvious generator
Sort by Removing
typing.Iterator
Iterator
yield
float
List
[py3.8+] 1-liner: 117 chars
Sun Angle
round
map
lambda
inline-if
split
pop words until it's short enough
Cut Sentence
pop
join
while
True
split
1
Ancestor(s?), check last generations
What Is Wrong With This Family?
set-comp
any
zip
map
set
3
20 random searches
Open Labyrinth
random.choice
choice
random
reversed
items
1
First
Time Converter (24h to 12h)
lambda
inline-if
list-comp
split
comprehension
First
Bird Language
ascii_lowercase
string.ascii_lowercase
string
set
while
re.sub(r'_[a-z]', repl lambda function, name.capitalize())
Conversion into CamelCase
capitalize
re.sub
sub
r-string
upper
First
Sun Angle
round
or
list-comp
split
comprehension
index of next non-zero char
Beginning Zeros
next
enumerate
lambda
if-comprehension
comprehension
Electronic Station
8-liner: Even-odd rule with origin point simplifications
Inside Block
zip
min
max
and
True
1
2
3-liner: 177 chars
Similar Triangles
map
set
lambda
sorted
comprehension
1
1
7-liner: Queue of dicts to determine the decimal, decode from hex
Cipher Dict (decryption)
bytes
f-string
items
pop
while
1
3
Obfuscated milp
Blood distribution
dict
zip
lambda
list-comp
range
1
1
[scipy 1.9+] milp: Mixed-integer linear programming
Blood distribution
scipy.optimize.LinearConstraint
scipy.optimize.milp
LinearConstraint
milp
scipy
1
filename.rpartition('.'), partial(sorted, key=...)
Sort by Extension
rpartition
functools.partial
partial
functools
inline-if
2
6
dict.setdefault
Surjection Strings
setdefault
all
zip
comprehension
2
1
re.sub(r'[A-Z]', repl lambda function, name)
Conversion from CamelCase
re.sub
sub
r-string
re
lower
2
1
Determine the decimal, group digits, queue of empty dicts
Cipher Dict
hex
map
pop
not
or
2
Two versions: Max-heap, Min-heap, 4 lines each
The Final Stone
_heapify_max
_heappop_max
_heapreplace_max
heapq._heapify_max
heapq._heappop_max
4
7
(Print version) Recursively generate parenthesization on split digits and operations
Mathematically Lucky Tickets
math.inf
inf
itertools.product
product
combinations
6
1
min-heap of negative weigths & heapq.heapreplace
The Final Stone
heapq.heapreplace
heapreplace
heapify
heapq.heapify
heappop
6
and 'password' not in password.lower()
Acceptable Password V
any
map
isdigit
bool
not
7
1
(Shorter code) Recursively generate parenthesization on split digits and operations
Mathematically Lucky Tickets
math.inf
inf
operator.sub
operator.add
mul
7
1
neighbors generator, sort decorator
Chess Knight
union
yield
decorator
index
set
10
1
From neighbors to neighbors with memorisation of previous steps...
Can You Pass?
any
abs
if-comprehension
False
True
13
1
not password.isdigit()
Acceptable Password III
any
map
isdigit
bool
not
14
1
[Generalized] All equal distance² fractions
Similar Triangles
Fraction
fractions.Fraction
fractions
combinations
itertools.combinations
20
1
[py3.8+] 1-liner: 82 chars with rpartition
Sort by Extension
rpartition
lambda
sorted
len(password) >= 10 or
Acceptable Password IV
any
map
isdigit
bool
not
obvious 1-liner
Acceptable Password I
bool
str
len
any(map(str.isdigit, ...))
Acceptable Password II
any
map
isdigit
bool
and
With chain rows/cols/diags generators
Find Sequence
chain
itertools.chain
any
itertools
enumerate
1
translation dict and zip
Surjection Strings
zip
bool
elif
False
True
6
replace; fullmatch
Unix Match. Part 1
fullmatch
re.fullmatch
r-string
re
None
1
compose(product, trues, ints, str)
Digits Multiplication
functools.partial
partial
mul
operator.mul
operator
2
and len(set(password)) >= 3
Acceptable Password VI
any
map
isdigit
bool
set
lambda reduce mul
Digits Multiplication
mul
operator.mul
operator
functools.reduce
reduce
My first
Verify Anagrams
ascii_letters
string.ascii_letters
string
sort
lower
Scientific Expedition
suppress ZeroDivisionError caused by eval
Aggregate by Operation
contextlib.suppress
suppress
contextlib
with
ZeroDivisionError
1
1
take zipped while all equal
Longest Common Prefix
itertools.takewhile
takewhile
as
itertools
zip
2
2
3-liner
Combining Celebrity Names
lstrip
inline-if
sum
join
list-comp
2
basic 1-liner
Common Words
set
lambda
sorted
join
split
4
1
Naive but cached
Remove Brackets
functools.lru_cache
lru_cache
decorator
functools
None
5
5
composition of methods/types
Pangram
issubset
frozenset
next
reversed
ascii_lowercase
9
2
operator
Aggregate by Operation
floordiv
operator.floordiv
operator.sub
operator.add
mul
9
groupby, del [...:], lstrip
Combining Celebrity Names
string.translate
translate
groupby
itertools.groupby
ascii_lowercase
9
list
Letter Queue
startswith
pop
join
elif
and
1
capture stdout decorator
Caps Lock
contextlib.redirect_stdout
redirect_stdout
functools.wraps
wraps
StringIO
v2: using slicing, sets, generator and translation of punctuation =)
Striped Words
punctuation
string.punctuation
translate
ascii_uppercase
string.ascii_uppercase
Total cost of some calls
Call to Home
values
sum
in
list-comp
split
decorated for doc
I Love Python!
lambda
join
2
Simple generator of characters (decorated to ''.join output)
Caps Lock
functools.partial
partial
yield
decorator
functools
4
Man, I can find hidden words in poetry! :-)
The Hidden Word
find
replace
max
lower
inline-if
1
My morse clock
Morse Clock
translate
format
bin
enumerate
lambda
basic 1-liner
Pangram
set-comp
isalpha
lower
lambda
if-comprehension
First
Secret Message
filter
isupper
lambda
join
str
lambda function generalization
Sum by Type
isinstance
zip
lambda
sum
join
So simple...
Follow Instructions
count
2
Read the password from cipher map
Cipher Map
lambda
join
if-comprehension
list-comp
range
sorted with abs key
Absolute Sorting
abs
lambda
sorted
O'Reilly
Three solutions + 1 in comments
Replace Last
collections.deque
deque
insert
collections
pop
1
10
max(start_watching or end, end)
Lightbulb Start Watching
Optional
typing.Optional
datetime.datetime
datetime
List
1
5
We can sum booleans (False == 0 and True == 1)
Majority
bool
sum
list
len
1
7
try return slice except
Remove All After
ValueError
index
except
try
list
1
8
yield from reversed(ascending list)
Reverse Every Ascending
reversed
and
append
for
if
1
2
sympy.topological_sort
Determine the Order
sympy.topological_sort
topological_sort
sympy
set-comp
add
1
1
Bruteforce with previous solution
Staircase
compress
itertools.compress
itertools.product
product
yield
1
List segments
Cut Into Squares
matplotlib
matplotlib.pyplot
matplotlib.pyplot.plot
matplotlib.pyplot.show
plot
1
add end time to els; min(end_watching or end, ...)
Lightbulb End Watching
Optional
typing.Optional
datetime.datetime
datetime
List
2
2
1-liner: sympy.topological_sort
Determine the Order
union
set-comp
map
enumerate
set
2
2
Cached recursion and GCD
Cut Into Squares
cache
functools.cache
math.gcd
gcd
chain
2
Operating cut
Lightbulb Operating
datetime.min
datetime.max
Dict
typing.Dict
itertools.zip_longest
4
Merge datetime intervals
Multiple Lightbulbs
itertools.zip_longest
zip_longest
typing.Union
Union
setdefault
5
Ugly-ish but short enough
Bridge Routine
get
upper
index
min
or
5
product, filterfalse
All Roads Lead to Rome!
filterfalse
itertools.filterfalse
frozenset
itertools.product
product
7
Enumerate string digits
"Lunar" Multiply
enumerate
min
max
join
int
7
Row by row
All Roads Lead to Rome!
frozenset
tuple
continue
in
range
8
Digit by digit
"Lunar" Multiply
enumerate
min
max
join
if-comprehension
8
takewhile workaround, and not just lists
Remove All After
TypeVar
typing.TypeVar
typing.Iterator
Iterator
itertools.tee
9
re
Chemical Analysis
re.sub
sub
findall
re.findall
re.search
12
Compare, deduce, choose with lexicographic order
Determine the Order
discard
union
next
values
dict-comp
14
2
Sum comprehension in lambda function
Count Inversions
lambda
sum
range
comprehension
len
15
[wrong code] unions of sets and resolve all conflicts
Determine the Order
union
combinations
itertools.combinations
set-comp
dict-comp
18
1
6-lines: min, itertools.combinations
Loading Cargo
chain
itertools.chain
combinations
itertools.combinations
itertools
sum timedelta.total_seconds()
Lightbulb Intro
datetime.datetime
datetime
List
typing.List
zip
My "flat dictionary" program
The Flat Dictionary
type
is
values
keys
all
4
[typed, py3.10+] timelines, intervals, cut moments, count
Lightbulb More
datetime.min
datetime.max
itertools.pairwise
pairwise
itertools.zip_longest
1-liner + imports: O(n²) but faster than with "for"
Count Inversions
gt
operator.gt
itertools.starmap
starmap
combinations
2
Two solutions
Chunk
divmod
yield
typing.Iterable
Iterable
typing
1
short, recursive, max with default argument
How Deep
isinstance
map
max
inline-if
list
1
Sort with a key
Frequency Sorting
lambda
count
sorted
True
1
obviously itertools.groupby
Compress List
groupby
itertools.groupby
itertools
list-comp
list
any_iterable, func = statistics.median, n = 3
Median of Three
yield
enumerate
pop
append
else
count true
Majority
bool
count
True
list
len
Fully typed generalization
Sort Except Zero
typing.Callable
Callable
iter
next
filter
1
lambda
Index Power
lambda
inline-if
len
1
import it
Median
as
2
Incinerator
Army with 3 properties : is_alive, warrior, pop
Army Battles
class
property
super
decorator
pop
1
16
dataclass, functools.singledispatchmethod and decorated methods
Voice TV Control
functools.singledispatchmethod
singledispatchmethod
functools.wraps
wraps
dataclasses.field
1
5
First
Capital City
class
super
is
None
lambda
1
2
Deprecated version
The Warlords
issubclass
setattr
class
getattr
hasattr
1
v2 (from flpo veky and myself): Party(Named, set), Friends(str) with lambda show_invite
Party Invitations
class
getattr
f-string
add
remove
2
Equipements class for list weapons, and new init_... attributes for manage weapons.
The Weapons
issubclass
class
hasattr
staticmethod
property
2
1
With (new) hit method returning damage, adapted for vampires.
The Vampires
class
staticmethod
next
property
super
3
With zip(army_1, army_2) and remove_the_dead property in Army class
Straight Fight
class
hasattr
staticmethod
property
decorator
3
1
Short
Army Units
class
f-string
5
12-lines with lambda methods (except init)
Building Base
class
getattr
property
f-string
dict-comp
5
2
With Ngone class
Geometry Figures
math.tan
tan
class
math.pi
pi
7
1
Robot = Human(str)
Dialogues
class
add
set
lower
lambda
12
1
My 3 chefs
3 Chefs
class
format
Dataclasses and a property
Microwave Ovens
dataclass
dataclasses
dataclasses.dataclass
class
eval
2
[clear v2] dataclasses, army deque, properties
The Warlords
asdict
dataclasses.asdict
issubclass
dataclasses.field
field
7
First
Hacker Language
class
chr
format
ord
isalpha
6
New battle.fight method, and a different management of attributes/method.
The Lancers
class
hasattr
staticmethod
property
decorator
1
My healers
The Healers
class
hasattr
staticmethod
property
decorator
1
first with copy.copy and SavedText(list)
Text Editor
delattr
copy.copy
class
hasattr
copy
My party invitations
Party Invitations
class
f-string
add
remove
set
_health attribute, health property, @health.setter to manage the defense attribute
The Defenders
class
staticmethod
next
property
super
6
Be lenient, it's my first class ever
Friends
class
pop
break
set
in
2
Simple dataclass
Every Person is Unique
dataclass
dataclasses
dataclasses.dataclass
class
typing.Union
1
IOs
Hacker Language
StringIO
io
io.StringIO
issuperset
class
First
Multicolored Lamp
class
index
None
inline-if
2
My warriors with super().__init__()
The Warriors
class
property
super
decorator
not
Both partial, cycle
Multicolored Lamp
functools.partialmethod
partialmethod
functools.partial
partial
cycle
Mine
9-liner: BFS
Fast Train
all
pop
sum
while
if-comprehension
1
1
max(..., key, default)
The Longest Word
max
split
str
len
1
2
match changes
One Switch Strings
case
match-case
itertools.zip_longest
zip_longest
itertools
1
1
str method
Replace All Occurrences
replace
str
1
1
Backtracking
Peaceable Queens
frozenset
or
list-comp
range
comprehension
1
1
[sympy] Intersections and reflections of rays with jar segments
Escape
Ray2D
Segment2D
sympy.Ray2D
sympy.Segment2D
sympy
1
1
sympy can handle permutations
15-puzzle Solvability
sympy.combinatorics.permutations.Permuta
Permutation
sympy
divmod
index
1
1
itertools.groupby, what else?!
Count And Say
groupby
itertools.groupby
as
itertools
join
1
Row by row (cryptic)
The Hollow Diamond
f-string
abs
lambda
join
list-comp
1
math trick
Close Enough
itertools.count
math.log
log
math.ceil
ceil
1
speedy 1-line
Close Enough
next
abs
lambda
count
if-comprehension
1
Minimize differences
Tricky String
ne
operator.ne
operator
as
map
1
First
Leap Year Checking
bool
or
and
int
2
1
str
Reverse Integer
abs
int
str
2
Generate perfect powers near n for reasonable exponents
Checking Perfect Power
math.log2
log2
itertools.repeat
repeat
itertools.takewhile
2
log floor/ceil
Close Enough
itertools.count
math.log
log
math.ceil
ceil
2
Basic formula
Sum of Integers
int
3
yield
Quadratic Equation Roots
collections.abc.Iterable
yield
collections
Iterable
else
3
1
basic 1-liner
Caesar Cipher (decryptor)
chr
ord
isalpha
lambda
inline-if
3
Use the OEIS sequence
Peaceable Queens
3
Simply import
Count Divisibles in Range (simplified)
as
4
1
First
String-2-Matrix
divmod
f-string
tuple
ord
map
4
First
e+pi
OverflowError
itertools.zip_longest
zip_longest
raise
eval
4
First
Matrix-2-String
case
match-case
raise
f-string
ValueError
5
1
Mostly deduce, consider all remaining possibilities
Garland
popitem
frozenset
copy
f-string
values
5
Sorted joined perms
All Permutations
itertools.permutations
permutations
as
itertools
map
5
yield:=breaks
Beat The Previous
yield
break
while
True
range
6
Side by side
The Hollow Diamond
ascii_lowercase
string.ascii_lowercase
as
string
map
6
next(filter(balance, indexes), -1)
Can Balance
next
reversed
filter
enumerate
lambda
7
functools.cmp_to_key
Bigger Together
cmp_to_key
functools.cmp_to_key
reversed
functools
map
8
2
[py3.9+] just import math.gcd
The Greatest Common Divisor
10
1
Row by row
The Hollow Diamond
ljust
ascii_lowercase
string.ascii_lowercase
as
string
10
Optional ascending information
Sort Sorted Groups
itertools.pairwise
pairwise
is
itertools
sort
10
max
Maximum Among Three
max
11
2
Lambda function with sympy.matrices package
Determinant
sympy.matrices.Matrix
Matrix
sympy
lambda
int
12
4
re (sub, fullmatch), translate/maketrans for exchange ',' and '.'
Currency Style
fullmatch
re.fullmatch
translate
re.sub
sub
12
2
sum(map(int, str(num))) while 2+ digits
Sum of Digits
map
sum
while
int
str
13
lambda
Moore Neighbourhood
itertools.product
product
as
itertools
set
14
3
min(routes generator, key=len)
Disposable Teleports
yield
min
set
if-comprehension
in
14
3
Counter
Count Vowels
collections.Counter
Counter
collections
map
lower
16
1
1-liner: functools.partial(re.sub, regex, lambda repl)
Currency Style
translate
r-string
lambda
str
16
basic 1-liner
Caesar Cipher (encryptor)
chr
ord
isalpha
lambda
inline-if
18
1-liner: itertools
Champernowne Word
islice
itertools.islice
itertools.count
chain
itertools.chain
18
First
Convert and Aggregate
dict
tuple
continue
not
or
20
1
Bruteforce
Domino Chain
set-comp
None
set
not
lambda
in (UPPER, lower, Capitalize)
Correct Capital
capitalize
upper
bool
lower
in
1
isupper, islower or == capitalize
Correct Capital
capitalize
islower
isupper
bool
or
1
lambda d: max(d, key=d.get)
Best Stock
get
max
lambda
Sets/dicts reunions, deduct the missing values
The Einstein Problem-Lite
isdisjoint
update
set-comp
values
dict-comp
I solved the equation, that's all.
Achilles and the Tortoise
lambda
3
Borrowed code for colour graph, then adapted
Color Map
union
set-comp
any
map
min
I just wanted to try for a change
The Greatest Common Divisor
abs
except
try
while
2
First
Binary Count
format
lambda
count
2
Ice Base
stack
Adjacent Letters
pop
join
and
append
else
1
5
1-liner, no import
Ordinary Cardinals
map
lambda
count
sorted
str
1
(.)\1
Adjacent Letters
re.sub
sub
r-string
re
while
1
Backtracking
Stepping Stones Puzzle
itertools.product
product
itertools
tuple
min
1
I
Frogs Collision
sympy.I
sympy
I
float
tuple
1
DFS on colored network graph without crashed nodes
Node Disconnected Users
set-comp
values
dict-comp
items
set
2
Priority queue: minimize used brushes and uncolored positions
Grid Painting
heappush
heapq.heappush
heappop
heapq.heappop
heapq
2
Colored connected components
Count Chains
math.hypot
hypot
combinations
itertools.combinations
extend
4
4
Look for sure things thanks to comparisons
Cipher Crossword
intersection
isinstance
dict-comp
all
get
4
This is the key 🔑
Ordinary Cardinals
functools.partial
partial
digits
string.digits
functools
4
math.prod
The Brick Factory Problem
math.prod
prod
is
math
None
5
Match operators
Postfix Evaluation
case
match-case
raise
isinstance
f-string
7
First
Count Divisibles in Range
divmod
int
8
Thinking about indexes
Matrix "Hatching"
TypeVar
typing.TypeVar
typing.Iterator
Iterator
yield
9
DFS on colored (integers) networks (without a crash) for connected components
City's Happiness
next
set-comp
values
dict-comp
items
11
symmetry & (solid, partial or break)
Counting Tiles
math.hypot
hypot
math.ceil
ceil
math
12
1
To the moon
Armstrong Number Checking
bool
sum
comprehension
int
str
12
Dynamic programming with minimal storage (EAFP style)
Making Change
KeyError
ValueError
pass
get
min
12
With fractions module
Oil Pie
Fraction
fractions.Fraction
fractions
abs
sum
13
2
Percentages then diff then lesser angle
Clock Angle
map
min
abs
split
int
18
[v2] Simple BFS with collections.defaultdict & deque
How to Find Friends
collections.deque
deque
collections.defaultdict
defaultdict
extend
DFS on colored (integers) net without crashes, return max color int
New Cities
union
next
set-comp
values
dict-comp
4
groups and lengths
Long Pressed
itertools.zip_longest
zip_longest
groupby
itertools.groupby
itertools
1
Generate histograms with a "simple" iteration on heights
Largest Rectangle in a Histogram
class
super
yield
dict
items
max with default argument
Berserk Rook
set-comp
yield
index
break
set
1
All blocks considered at top left, and dictionary of blocks built with rotations of an example of each type.
Identify Block
divmod
set-comp
dict-comp
items
min
Sets of friends
How to Find Friends
pop
set
while
in
list-comp
Feed previous pigeons, and maybe feed some new pigeons
Feed Pigeons
while
if
re.findall
Find Quotes
r-string
lambda
comprehension
lambda function
Morse Encoder
lower
lambda
join
split
comprehension
lambda
The Most Numbers
min
max
lambda
inline-if
1
sum booleans
Monkey Typing
lower
sum
in
comprehension
2
My "long repeat" letter program
Long Repeat
range
else
len
for
if
Alice In Wonderland
1-liner: quick naming and weird slicing
Zigzag Array
lambda
list-comp
range
comprehension
1
4
enumerate(text.split()) and increasing indexes
Words Order
values
dict-comp
enumerate
bool
set
1
2
2-liner: 140 chars
Tree Walker
type
values
dict
lambda
inline-if
1
1
Powers of the adjacency matrix of a graph to find a path between numbers
Digits Doublets
min
not
lambda
inline-if
sum
1
1
Recursive max
The Cookie Monster
float
None
set
max
lambda
1
1
Cached tiling counts
Count Domino Tilings
cache
functools.cache
itertools.pairwise
pairwise
decorator
1
1
Any sweep line
Overlapping Disks
complex
tuple
remove
enumerate
abs
1
Matrix of probabilities, generalized
Cleaning Robot
string.index
numpy.zeros
zeros
frozenset
ascii_uppercase
1
yield holes
Duplicate Zeros
yield
not
for
if
2
4
Lambda function with sum/list comprehension, eval "&", "|" and "^".
Multiplication Table
eval
format
lambda
sum
join
2
1
[scipy] Precompute all distances with Floyd Warshall
The Shortest Knight's Path
floyd_warshall
scipy.sparse.csgraph.floyd_warshall
csr_matrix
scipy.sparse.csr_matrix
scipy
2
partial, regex substitution, composition
Unique Email Addresses
functools.partial
partial
next
reversed
re.sub
2
Count cube coordinates
Ulam-Warburton Automaton Hex
set-comp
collections.Counter
Counter
add
items
3
1
basic 1-liner
Days Between
abs
lambda
3
2
heapq: nlargest, nsmallest
Shorter Set
heapq.nsmallest
nsmallest
heapq.nlargest
nlargest
heapq
3
[Crystal clear] Powers of the adjacency matrix
Digits Doublets
ndarray
numpy.ndarray
typing.Iterator
Iterator
numpy.array
3
DFS
Bishop vs Aliens
frozenset
add
tuple
continue
pop
3
Replace ',' and '.' by ' ', one split and it's over.
First Word
replace
split
str
4
4
7-liner without modules
IP Network: Route Summarization
f-string
zip
enumerate
min
replace
5
9-liner: generator with itertools.accumulate for altitudes
Flood Area
contextlib.suppress
suppress
contextlib
with
itertools.accumulate
5
1
First, improvable
YAML. List and Comments
splitlines
startswith
rstrip
re.compile
compile
5
reduce
Excel Column Number
functools.reduce
reduce
functools
ord
lambda
5
2
[v2] enumerate, try line.index, max(..., key=len)
Long Non Repeat
ValueError
continue
enumerate
index
except
6
6
[py3.8+] 1-liner 169 chars: not windows-friendly
Date and Time Converter
f-string
lambda
6
2
timedelta(max(0, 5 - weekday))
Birthday Party
datetime.timedelta
timedelta
date
datetime.date
datetime
6
O(n)
Stock Profit
is
None
or
elif
list
7
1
rotate?, count groups of X, fill with zeros first, rotate back?
Nonogram Encode
groupby
itertools.groupby
itertools
zip
map
7
BFS
The Shortest Knight's Path
update
yield
pop
index
while
8
Grid, naive
Ulam–Warburton Automaton
map
not
sum
if-comprehension
False
9
1
Second "reduce" with 0 as initial
Excel Column Number
functools.reduce
reduce
functools
ord
lambda
9
1
A139250
Toothpicks
inline-if
while
if
10
1
with sens function
Zigzag Array
reversed
lambda
inline-if
list-comp
range
11
next(generator, 0)
The Good Radix
digits
string.digits
ascii_uppercase
string.ascii_uppercase
next
11
heapq again 🙂
Huffman Encode
heapify
heapq.heapify
heappush
heapq.heappush
heappop
12
Simple stack
Backspace Apply
pop
join
elif
append
str
12
Always take the biggest digit, ignoring the "last" digits
Greedy Number
enumerate
None
max
lambda
or
12
My "Digits Doublets" solution
Digits Doublets
enumerate
min
lambda
inline-if
sum
13
1
collections.Counter for letters, min with key
The Most Wanted Letter
collections.Counter
Counter
collections
isalpha
min
14
2
enumerate iterable
Swap Nodes
yield
enumerate
not
else
for
18
1
[typed] 3 simple functions
Tree Walker
Dict
typing.Dict
typing.Union
Union
Any
20
2
My "long non repeat"
Long Non Repeat
find
break
max
count
else
next, datetime module
When is Friday?
datetime.strptime
strptime
datetime.timedelta
timedelta
next
[v3] Tested on big texts
Long Non Repeat
finally
collections.deque
deque
ValueError
collections
1-liner: simple min with key
Nearest Value
min
abs
lambda
First
Date and Time Converter
re.split
r-string
map
re
lambda
datetime.strftime : "%-d" or "%#d"
Date and Time Converter
datetime.strptime
strptime
f-string
datetime.datetime
ValueError
1
counter
When "k" is Enough!
yield
collections.Counter
Counter
collections
for
py3.10+ itertools.pairwise
Ascending List
lt
operator.lt
itertools.pairwise
pairwise
itertools.starmap
1
min & max with key
The Fastest Horse
min
set
max
count
list-comp
py3.10+ my_compose(all, partial(starmap, lt), pairwise)
Ascending List
lt
operator.lt
itertools.pairwise
pairwise
itertools.starmap
One line of course
Transposed Matrix
lambda
list-comp
range
comprehension
len
1
1-liner: sorted(key and reverse)[:limit]
Bigger Price
lambda
sorted
True
1
morse_decoder lambda function
Morse Decoder
capitalize
lambda
join
split
comprehension
lambda all zip
Ascending List
all
zip
lambda
comprehension
1
try next / except / finally
Swap Nodes
finally
StopIteration
iter
next
yield
two solutions
Easy Unpack
lambda
3-liner: divmod(... ,2), slicing
Middle Characters
divmod
inline-if
len
operator.itemgetter
Easy Unpack
itemgetter
operator.itemgetter
operator
2
Three solutions
End Zeros
rstrip
re.search
search
re
not
except (ValueError, AssertionError)
Words Order
AssertionError
ValueError
index
bool
except
range intersection for fun
Long Non Repeat
setdefault
values
zip
enumerate
pop
split and join ; partial(re.sub, r'\S+', inversion repl)
Backward Each Word
functools.partial
partial
re.sub
sub
functools
3
Second
Correct Sentence
endswith
upper
str
GitHub
~i
Common Tail
TypeVar
typing.TypeVar
min
None
break
1
3
6-liner relatively clear/creative
Broken Clock
datetime.strptime
strptime
datetime.datetime
datetime
split
1
1-liner
Evenly Spaced Trees
lambda
comprehension
len
1
1
reversed, take while equal
Common Tail
TypeVar
typing.TypeVar
itertools.takewhile
takewhile
collections.deque
1
1
Dijkstra with priority queue
The Cheapest Flight
heappush
heapq.heappush
heappop
heapq.heappop
heapq
2
10
21-liner: Dynamic programming to get scopes, heapq to minimize unsupplied cities
Power Plants
heappush
heapq.heappush
heappop
heapq.heappop
heapq
2
5
group rays
Reversi: Othello Moves
itertools.count
frozenset
groupby
itertools.groupby
itertools.product
2
First
Merge Intervals
max
and
append
else
for
4
1
scipy.ndimage for delete useless paper, numpy for movements and shape (a bit too complicated)
Paper Dice
asscalar
find_objects
numpy.asscalar
scipy.ndimage.find_objects
scipy.ndimage.label
4
1
[9-liner] complex numbers / math formula and python3.8 for radius
Searchlights
cmath.sin
cmath.exp
cmath.pi
cmath
exp
6
simple
Power Supply
popitem
discard
union
set-comp
dict-comp
7
Rotate/turn. Dimensions? Spaces? Sum 7?
Paper Dice
reversed
values
all
any
zip
7
1
Two solutions
Create Intervals
items
tuple
map
enumerate
pop
9
3
2-lines: SuperPhil15
Solution for Anything
class
lambda
True
19
1
iterative without regex, repeatable parts
Long Repeat Inside
break
while
True
str
len
20
First
Shooting Range
math.hypot
hypot
round
math
min
1
union set of intervals, zip for union, enumerate(op, 1)
Painting Wall
set-comp
add
zip
enumerate
min
Area of a convex N-gon is area of N-2 triangles (with Heron's formula)
Area of a Convex Polygon
math.hypot
hypot
math.sqrt
sqrt
math
3
reduce, gcd and clear names
Evenly Spaced Trees
math.gcd
gcd
functools.reduce
reduce
functools
2
[EAFP way] markers, forward/backward, right/left/first digits, checksum
Barcode Reader
KeyError
Optional
typing.Optional
translate
dict-comp
datetime.date of course
The Most Frequent Weekdays
date
datetime.date
datetime
sorted
list-comp
My "long repeat inside" program
Long Repeat Inside
math.sqrt
sqrt
all
math
bool
2
[Typed OOP] Minimax strategy
Xs and Os Champion
typing.Iterator
Iterator
class
Tuple
typing.Tuple
Obvious 1-liner
Expand Intervals
lambda
range
comprehension
split('; ') and startswith(name+'=')
Cookies
startswith
split
len
for
if
Max of a list of tuples with a key
The Highest Building
max
lambda
sum
list-comp
range
Third [py3.10+]
Evenly Spaced Trees
itertools.pairwise
pairwise
operator.sub
itertools.starmap
starmap
1
My solution
The End of Other
endswith
any
or
elif
False
Dropbox
defaultdict(set)
Switch Keys to Values
collections.defaultdict
defaultdict
add
items
collections
1
1
First
Integer Sign Determination
int
str
if
1
Complex
Count Squares
frozenset
combinations
itertools.combinations
set-comp
as
1
2
Columns 0,1 OR naively
Exploring Wythoff Array
filterfalse
itertools.filterfalse
itertools.count
next
yield
1
1
sum(square_exist for each segment and orientation) // 4
Count Squares
frozenset
combinations
itertools.combinations
as
itertools
1
sum(map(str.isdigit, ...))
Count Digits
map
isdigit
sum
int
str
2
5
islice(cycle)
Fibonacci Spiral's End
islice
itertools.islice
cycle
itertools.cycle
as
2
[4-liner] 170 chars
On the same path
yield
list-comp
comprehension
for
2
2
Bruteforced combinations(2)
Longest Substring of Unique Characters
combinations
itertools.combinations
as
itertools
set
2
Filter reversed text, join formatted text
Revorse the vewels
next
as
filter
upper
isupper
2
With dict of hashlib functions, utf-8 encode, hexdigest
Simple Hashlib
hashlib.sha1
hashlib.sha224
hashlib.sha256
hashlib.sha384
hashlib.sha512
3
1
sympy with creative itertools
Hubspot Amulet
sympy.abc.y
sympy.abc.z
y
z
solve_linear_system
3
1
quick and dirty regexes
Reveal the Number
finditer
re.finditer
findall
re.findall
float
3
base = 10 or not ; divmod to find digits ; stop if encounter the maximal digit
Max Digit
divmod
max
while
and
4
[15-lines] Timing a single recursive DFS
On the same path
or
and
list-comp
comprehension
for
4
5
sum divisors == 2 * ...
Perfect Number Checking
rstrip
bin
bool
while
int
4
2
textwrap, operator.methodcaller, str.replace with all 3 arguments
Text Formatting
fill
textwrap.fill
methodcaller
operator.methodcaller
textwrap.wrap
5
2
import, or reduce(mul, range, 1)
Number With Exclamation
5
Dispatch
Collatz Ztalloc
functools.singledispatch
singledispatch
decorator
functools
pass
5
2
2(L+W)
Rectangle Perimeter
int
6
1
fullmatch
Is String a Number? (Part II)
fullmatch
re.fullmatch
r-string
re
None
6
DFS (+ queen generalization)
Checkers Capture
case
match-case
itertools.count
as
pass
6
Simply import
Find Remainder
as
7
isdigit method
Is String a Number?
isdigit
str
8
4
Compute volume and area of a spheroid
Humpty Dumpty Form
math.log
log
math.asin
asin
math.pi
10
sum(starmap(!=, zip_longest))
Fuzzy String Matching
ne
operator.ne
itertools.starmap
starmap
itertools.zip_longest
10
str method
Convert To Title Case
title
str
11
islices
Fibonacci Poem
islice
itertools.islice
iter
as
itertools
11
Bruteforce with improvements
Nonogram Row
itertools.zip_longest
zip_longest
itertools.permutations
permutations
combinations
12
Recursion
Count Morse
startswith
enumerate
sum
if-comprehension
comprehension
13
2
main[i:].startswith(sub)
Count Substring Occurrences
startswith
lower
sum
range
comprehension
14
Bruteforce with taken rows, columns, and descending/ascending diagonals
Place Queens
set-comp
any
index
None
set
15
xs and ys both intersect
Interesting, intersecting
tuple
bool
or
and
int
20
Decimal
Is String a Number? (Part II)
InvalidOperation
decimal.InvalidOperation
Decimal
decimal.Decimal
decimal
3
sum(map(operator.ne
Not in Order
ne
operator.ne
operator
map
sum
1
First
Three Points Circle
math.hypot
hypot
eval
rstrip
f-string
1
First
URL Normalization
re.I
I
match
re.match
re.sub
Rajesh decorator: SOS I SEE 69 ...
The Best Number Ever
translate
lambda
print
str
3
next palindromic substring by decreasing length
The Longest Palindromic
next
if-comprehension
range
comprehension
len
1-liner: max(map(int, string number))
Max Digit
map
max
lambda
int
str
Max with a key, with a worth dict
Worth of Words
max
lambda
sum
comprehension
Simply my speech module
Speech Module
join
elif
append
else
if
Counter, re.findall
Popular Words
collections.Counter
Counter
findall
re.findall
dict-comp
Two solutions
Sum Numbers
re.compile
compile
filter
r-string
map
any, all boolean functions, string split
Three Words
digits
string.digits
string
all
any
3
PyCon TW
sympy.linsolve
How Much Gold
c
g
i
sympy.abc.c
sympy.abc.g
3
[OOP] Map class (a bit too long)
Dark Labyrinth
class
hasattr
next
update
property
3
Basic
Simple Areas
math.pi
pi
math.sqrt
sqrt
math
4
1
lambda next zip
Ryerson Letter Grade
next
zip
lambda
if-comprehension
list-comp
4
1
Dijkstra
Express Delivery
next
reversed
yield
dict-comp
float
5
1
[typed] Cuboid class and volumes of the connected components of the graph
Fused Cubes
NamedTuple
typing.NamedTuple
Dict
typing.Dict
class
5
itertools.groupby to group consecutives, sum to sum
Sum Consecutives
lambda
sum
list-comp
comprehension
7
Hide parts of faces by cutting a rect into up to 4 sub-rects
Building Visibility
class
collections.namedtuple
namedtuple
set-comp
collections
12
try next
Robot Sort
StopIteration
next
f-string
zip
enumerate
15
Generate all electoral splits into districts, take the first good one
Unfair Districts
StopIteration
union
itertools.product
product
combinations
17
blankplank's version, modified
Double Substring
elif
range
len
for
if
Recursive solution with arguments row and col initialized to 0.
Golden Pyramid
max
len
if
1
Dijkstra
Network Attack
math.inf
inf
values
dict-comp
get
Basic
Digit Stack
startswith
pop
elif
and
append
1
Compare line[i:i+n] and line[j:j+n] for descending n and possibles (i,j).
Double Substring
while
len
if
2
match case
Simple Areas
case
match-case
raise
math.pi
pi
First
House Password
raise
f-string
ValueError
all
isupper
1
4-liner: scipy.ndimage.label
Calculate Islands
scipy.ndimage.label
label
scipy
sum
sorted
Storage
max, with a key
Latest ISO datetime
functools.partial
partial
functools
datetime.datetime
datetime
1
2
That's it?!
Latest ISO datetime
max
1
3
with re.findall and generators
Moria Doors
reversed
findall
re.findall
r-string
enumerate
1
2
heapq, cut the search
Flip of Time
heappush
heapq.heappush
heappop
heapq.heappop
heapq
2
Itertools combinations, axis intersection and slope.
The Rows of Cakes
math.inf
inf
Fraction
fractions.Fraction
fractions
3
6
With natural coordinate system
Square Spiral
math.ceil
ceil
math.sqrt
sqrt
math
5
1
First
Earth Distances
math.radians
radians
math.cos
cos
math.sin
7
3
str[pf]time, catch value errors
Convert Date
datetime.datetime
ValueError
datetime
except
try
7
2
Distance in one hexagonal coordinate system
Hexagon Spiral
divmod
abs
max
lambda
inline-if
7
1
[v2] Dynamic programming, verbose OOP
Battle Dice
class
itertools.product
product
collections.defaultdict
defaultdict
9
My english to braille translator
English to Braille Translator
digits
string.digits
zfill
ascii_uppercase
string.ascii_uppercase
11
1
My playfair cipher
Playfair Cipher
digits
string.digits
ascii_lowercase
string.ascii_lowercase
string
13
operator.itemgetter(1) itertools.groupby
Group Equal consecutive
itemgetter
operator.itemgetter
groupby
itertools.groupby
operator
18
1-liner: itertools.groupby
Group Equal consecutive
lambda
list-comp
list
comprehension
20
2
Swaps dict, list of disjoints cycles, and finally permutations to do
Mind Switcher
union
dict-comp
enumerate
pop
set
1
Counter power recursively cached
Battle Dice
functools.lru_cache
lru_cache
itertools.product
product
decorator
Basic loop
Group Equal consecutive
inline-if
append
else
for
if
1
3-lines: zips and slices
Group Equal consecutive
zip
enumerate
if-comprehension
list-comp
comprehension
1
(1-2)-liner: numpy and math generalization
Skew-symmetric Matrix
numpy.array
array
numpy
any
not
6
[Typed OOP cached] Minimax strategy
Haunted House
typing.Callable
typing.Iterator
Callable
Iterator
dataclass
My "Saw the Stick" program
Saw the Stick
math.sqrt
sqrt
math
break
lambda
1
Dijkstra distance
Digging a Canal
math.inf
inf
set-comp
remove
math
Compute minima with key (sum of resistances)
Weak Point
min
lambda
sum
list-comp
range
count '.'*... / yield numbers
Restricted Prime
yield
not
count
while
False
lambda
Word Pattern
zfill
bin
isalpha
lambda
join
First check the diagonal, then the bottom of the matrix.
Skew-symmetric Matrix
all
range
comprehension
len
1
Maya
[typed] Apply the rule and a simple reasoning
Unruly
typing.Set
Ellipsis
Set
Optional
typing.Optional
1
5
[actually inefficient] Maximize lit area with a priority queue
Light Up
itertools.takewhile
takewhile
typing.Set
Set
itertools.count
1
6
v2: BFS to find gems, avoiding dead ends (detected by Kosaraju)
Inertia
StopIteration
setdefault
next
Tuple
typing.Tuple
1
Unique neighbors and small paths search
Signpost
collections.defaultdict
defaultdict
intersection
yield
pass
1
5
[typed] Light paths and backtrack on the position of the monsters
House of Mirrors
typing.Iterator
Iterator
Dict
typing.Dict
Ellipsis
1
1-liner: Cryptic version of my clear code (py3.10)
House of Mirrors
exec
bytes
compile
type
None
1
[Typed, bit of OOP] Rectangle intersections
Find Rectangles
NamedTuple
typing.NamedTuple
typing.Iterator
Iterator
Dict
2
Backtracking to avoid dead ends, BFS to find gems
Inertia
Tuple
typing.Tuple
set-comp
yield
add
3
[Typed OOP] Grid of switch & watcher cells
Visibilities
typing.Iterator
scipy.ndimage.label
label
Iterator
dataclass
3
[typed] Look at row/column counts, avoid cycles/articulation points/bridges, store "candidate/on track/secured" positions and partial tracks
Train Tracks
Deque
typing.Deque
Dict
typing.Dict
typing.Set
7
[Typed OOP] Grid parts of labelled cells (1.3 seconds)
Net Game
FrozenSet
typing.FrozenSet
typing.Iterator
Iterator
filterfalse
11
HubSpot
Three solutions + 1 in comments
Replace First
collections.deque
deque
collections
pop
append
1
47
divmod%
Square Board
divmod
1
6
[py3.8+] 1-liner/98 chars with walrus/shifts operators
Univocalic davasaan
lambda
1
7
DFS with neighbors function; math.isqrt
Triangular Islands
isqrt
math.isqrt
typing.Set
Set
discard
1
1
[py3.8+] 1-liner: walruses and datetime
Weekly Calendar
lambda
list-comp
range
comprehension
1
1-liner: naive max
Home Coming
values
max
lambda
sum
if-comprehension
1
1
[py3.8+] 6-liner: DFS with 1-liner neighbors
Triangular Islands
yield
pop
set
while
int
1
2
[py3.8+] 4-liner: binary search (3 lines) + workout lambda
Workout
items
zip
max
lambda
sum
1
1-liner / 178 chars: scipy & walrus operator
Connect Stars
zip
lambda
list-comp
comprehension
1
Easy with scipy
Connect Stars
scipy.sparse.csgraph.minimum_spanning_tr
minimum_spanning_tree
scipy
math.hypot
hypot
2
Generalization to any base 2-36 (and to negative fractions)
Repeating Decimals
f-string
not
while
True
if
2
ast module and collections.Counter
Count Comprehensions
DictComp
GeneratorExp
ListComp
SetComp
ast.DictComp
3
With collections.Counter and cutting generator
Most Efficient Cutting
yield
collections.Counter
Counter
keys
collections
5
4-liner: heapq.nlargest
Team Play
heapq.nlargest
nlargest
heapq
List
typing.List
5
[8lines+old code] Rectangles based on edges from convex hull, change complex coordinates to have bounding boxes
Inscribe a Contour
complex
collections.namedtuple
namedtuple
set-comp
ValueError
5
6
[numpy] 9-liner: Math magic with Markov chain
Expected Dice
numpy.identity
identity
matrix
numpy.matrix
numpy.linalg
5
2
BFS resolution order and backtracking
Crossword Solver
fromkeys
groupby
itertools.groupby
chain
itertools.chain
6
2
Dynamic programming and itertools.accumulate
Family Dinner
itertools.accumulate
accumulate
itertools
List
typing.List
6
1
text.split(maxsplit=1)[0]
First Word (simplified)
lambda
split
8
4
Compute 'lengths' before compute decimals
Repeating Decimals
math.gcd
gcd
math
max
while
8
Binary search, explicit number of sessions required
Workout
typing.Callable
Callable
operator.sub
math.ceil
ceil
8
1
Minimal distance from Dijkstra on the war game map graph
Supply Line
math.inf
inf
string.index
union
ascii_uppercase
9
4
try birthdate.replace(year=...)
Next Birthday
Dict
typing.Dict
Tuple
typing.Tuple
date
9
1
Naive and short max
Home Coming
combinations
itertools.combinations
as
collections.Counter
Counter
9
1-liner: array[bool][bool]
Fizz Buzz
lambda
str
10
1
[typed] Generate routes simultaneously, and a priority queue
Supply Stations
Rectangle
hlines
matplotlib.pyplot.Rectangle
matplotlib.pyplot.hlines
matplotlib.pyplot.subplot
10
Priority queue to maximize total length
Park Benches
Dict
typing.Dict
itertools.takewhile
takewhile
typing.Set
11
First
Stressful Subject
ascii_lowercase
string.ascii_lowercase
string
any
upper
14
6
4-liner: date and timedelta from datetime module
Weekly Calendar
datetime.timedelta
timedelta
date
datetime.date
datetime
17
Tricky reversed use
The Hamming Distance
reversed
f-string
zip
map
sum
1
@join(',') on generator with Counter
Auto Painting
yield
decorator
collections.Counter
Counter
collections
1
take the nth of the iterator of all answers
Fizz Buzz
islice
itertools.islice
cycle
itertools.cycle
itertools.count
sum bool(striped line)
Non Empty Lines
splitlines
strip
map
bool
sum
is_divisible_by(2)
Is Even
not
lambda
sum, splitlines, strip
Non Empty Lines
splitlines
strip
sum
if-comprehension
comprehension
sets of lower/upper letters
All Upper II
ascii_uppercase
string.ascii_uppercase
ascii_lowercase
string.ascii_lowercase
string
5
dropwhile
Remove All Before
ne
operator.ne
dropwhile
itertools.dropwhile
functools.partial
My "min" and "max" built-in functions
Min and Max
get
None
lambda
or
len
try return slice except
Remove All Before
ValueError
index
except
try
list
1-liner: join and replace
Right to Left
replace
lambda
join
comprehension
recursively pop, length 42
Restricted Sum
pop
lambda
inline-if
1
try except
Number Base
ValueError
except
try
int
1
string length
Number Length
lambda
str
len
Non recursive generalization (EAFP style)
Second Index
contextlib.suppress
suppress
contextlib
with
functools.partial
[::-1]
Backward String
lambda
[basic] text.index and slice
Between Markers (simplified)
index
1-liner: [::2]
Even the Last
lambda
inline-if
sum
1
Hamming Distance
The Hamming Distance
format
sum
sorted
range
comprehension
2
Blizzard
fromisoformat (with python 3.7)
The First Working Day
datetime.fromisoformat
fromisoformat
datetime.timedelta
timedelta
date
1
3
6-liner: Generator, divmod, list.pop, math.factorial
Reversed Permutation Index
math.factorial
factorial
divmod
yield
math
1
3
2-lines: Bruteforce with integers
Rectangles Union
union
set
lambda
range
comprehension
1
3
[scipy 1.9+] milp: Mixed-integer linear programming
Knapsack Problem
scipy.optimize.Bounds
scipy.optimize.LinearConstraint
scipy.optimize.milp
Bounds
LinearConstraint
1
"php\";
Palindromic Palindrome
lambda
2
[py3.8+] 1-liner: 103 chars
Permutation Index
lambda
sum
range
comprehension
len
2
[200th mission] DFS and great neighbors function
Safe Coasts
itertools.product
product
any
itertools
enumerate
3
1
All pairs of cities, all flights of minimal prices, multiple Dijkstra
Useless Flights
functools.lru_cache
lru_cache
heappush
heapq.heappush
heappop
3
1
generator
Move Zeros
yield
append
else
for
if
4
2
Dynamic programming
Knapsack Problem
ValueError
tuple
min
except
try
4
1
'[%s]' ; sep.join ; f'{n: >{w}'
List Beautify
f-string
zip
map
max
join
4
recursive with decreasing upperbounds
Sum of Distinct Cubes
cbrt
math.cbrt
float
math
min
4
10-lines: np.array, decreasing dimensions, next
Spaceship Landing Strip
numpy.array
array
itertools.product
product
next
4
Wagner-Fischer algorithm
String Conversion
enumerate
min
not
or
inline-if
5
2
([], [])[is_zero].append
Move Zeros
sum
append
for
5
n-th permutation and dichotomy
Permutation Index
itertools.accumulate
accumulate
divmod
yield
itertools
6
no fromisoformat?
The First Working Day
datetime.timedelta
timedelta
date
datetime.date
datetime
7
divmod
Weekend Counter
divmod
sum
range
comprehension
11
DFS, itertools.count(1), collections.Counter
Radiation Search
itertools.count
StopIteration
itertools.product
product
next
16
It works
Stair Steps
max
else
len
if
Backtracking
Sudoku Solver
union
divmod
map
set
True
2
datetime
Unlucky Days
datetime.timedelta
timedelta
next
date
datetime.date
My "The Angles of a Triangle" program
The Angles of a Triangle
math.degrees
degrees
math.acos
acos
round
2
Rock
match case sympy expand
Write Quadratic Equation
sympy.abc.x
x
sympy
case
match-case
1
sympy expand
Write Quadratic Equation
sympy.abc.x
x
sympy
f-string
inline-if
2
1
Boring string manipulation
Write Quadratic Equation
filter
f-string
ValueError
None
except
5
1
First
Web Log Sessions
extend
f-string
datetime.datetime
ValueError
items
6
[23 useful lines] '@:', cube coords & components with DFS
Hexagonal Islands
set-comp
yield
extend
add
tuple
7
1
class BlackHole(sympy.Circle) & matplotlib visualization
Black Holes
sympy.acos
sympy.sqrt
sympy.Circle
Circle
center
7
Mixed methods: Hamiltonian decompositions (extensions/reductions) & random seaches
Family Gifts
random.shuffle
shuffle
random
union
iter
7
[OOP, typed, doctests] Easy cases or BFS: list all boat loads
River Crossing
dataclasses.field
field
dataclass
dataclasses
dataclasses.dataclass
8
[typed] BFS avoiding each other
Chicken Hunt
Dict
typing.Dict
functools.lru_cache
lru_cache
Ellipsis
15
Newton's method for the search of the root of f(x) = x*log(x)-N.
Super Root
fabs
math.fabs
math.log
log
math
17
2
NamedTuple
Rolling 🎲!
Self
typing.Self
NamedTuple
typing.NamedTuple
case
18
max(right_elements, default=-1)
Replace with Biggest
yield
max
range
len
for
accumulate maxima
Replace with Biggest
itertools.accumulate
accumulate
reverse
itertools
pop
Brute force a little bit smart
Water Jars
f-string
all
index
lambda
inline-if
join decorator on a generator
Parity Bit Generator
yield
decorator
chr
bin
map
Shelter
Look at as few points as possible by dividing the rectangle until it is too small
Four To The Floor
functools.lru_cache
lru_cache
typing.Set
Set
class
1
5
1-liner
Delivery Drone
zip
enumerate
min
abs
lambda
1
1
Ugly speedy
Four To The Floor
class
intersection
set-comp
all
tuple
2
2
scipy.ndimage.label, multiple BFS and itertools.permutations (clear and relatively short)
Climbing Route
scipy.ndimage.label
label
scipy
numpy.array
array
3
6
8-liner: pure numpy
Pattern Recognition
numpy.array_equal
array_equal
numpy.array
array
itertools.product
4
3 lines wrote by a monster (363 chars)
Halloween Monsters
next
values
dict-comp
zip
max
4
sets and sum of bools
Seven Segment
set-comp
upper
set
lambda
sum
5
Eulerian path
One line Drawing
union
set-comp
dict-comp
pop
index
6
25 lines: dot product with cube coords
Fortress Cannons
operator.sub
mul
operator.mul
union
itertools.product
7
1
My first use of zip, zip_longest and accumulate. And useful slicing.
ADFGVX Cipher
itertools.accumulate
accumulate
itertools.zip_longest
zip_longest
clear
10
[v2] scipy.ndimage for simple peaks detection, multiple bfs to find explicit path
Climbing Route
scipy.ndimage.maximum_position
maximum_position
scipy.ndimage.label
label
arange
10
collections.Counter and a bit of itertools
Halloween Monsters
itertools.count
itertools.product
product
next
as
11
1
try iterate from it except TypeError
Completely Empty
TypeError
all
except
try
False
13
1
Neighboring neighboring... area of obstacles and border
Landing Site
typing.Iterator
Iterator
typing.Set
Set
chain
16
1
Scary solution : come here to give me a vote or I take your sordid life
Ghosts Age
all
round
inline-if
while
in
1
First
The Nearest Square Number
math.floor
floor
math.sqrt
sqrt
math
flow lru cached with zip and EAFP
The Lantern Festival
functools.lru_cache
lru_cache
StopIteration
next
set-comp
Encode the list [0,1,2, ..., len(message)-1] to decode the message.
AMSCO Cipher
enumerate
index
replace
lower
sum
1-liner: Code (py3.10) of Pouf's Boo, no space
Ghosts Age
exec
bytes
compile
type
None
Codeship
6-liner: scipy.integrate and probabilities power
Probably Dice
integrate
scipy.integrate
scipy.quad
quad
cmath.exp
1
date time timedelta
Working Hours Calculator
datetime.fromisoformat
fromisoformat
datetime.time
time
frozenset
1
[creative] Scientific imports + 1-liner: Markov chain
Pearls in the Box
scipy.sparse.spdiags
spdiags
linspace
numpy.linspace
numpy.roll
1
1
OOP, Counter, combinations, lambdas
Texas Referee
class
getattr
combinations
itertools.combinations
collections.Counter
2
1
Dijkstra, equation and round functions
Bats Bunker
math.inf
inf
math.hypot
hypot
math.floor
4
3
Bruteforced recursion
The Centrifuge Problem
sympy.primefactors
primefactors
sympy
sort
bool
4
Markov chain, numpy, scipy.sparse.spdiags
Pearls in the Box
scipy.sparse.spdiags
spdiags
linspace
numpy.linspace
numpy.roll
6
3
Color Black/White stones graphs to get B/W territories, look B/W borders, sum lengths of B/W eaten territories
Eaten Go Stones
union
set-comp
dict
enumerate
index
7
Random backtracking with time limitation
Magic Domino
time.time
random.shuffle
shuffle
contextlib.suppress
suppress
8
My solver with obvious and real searches
Minesweeper
discard
raise
combinations
itertools.combinations
set-comp
9
1
Markov chains
Pearls in the Box
round
lambda
count
sum
elif
17
Priority queue (heapq) to find cherry, BFS to not be stuck
Snake Lite
heappush
heapq.heappush
heappop
heapq.heappop
heapq
17
BFS
The 88th Puzzle
tuple
zip
pop
while
append
18
1
Color unoccupied points graph to get territories, look Black/White borders, sum lengths.
The Territory of Go
union
set-comp
enumerate
index
set
19
v2: unoriented lines, generate square lines
The Square Chest
itertools.tee
tee
issuperset
frozenset
itertools.product
4
Define right move, deduce others moves
Behind 2048
any
lambda
if-comprehension
list-comp
split
My first real yield generator: recursively generates partitions/dices until we have solution (if it exists).
Unfair Dice
partition
yield
max
lambda
inline-if
1
unoriented lines, generate square lines
The Square Chest
frozenset
divmod
next
set-comp
yield
1
Hermit
[v3] 1-liner: count odd divisors (the naive way)
Count Consecutive Summers
lambda
sum
range
comprehension
1
17
lambda and math upper bound
Count Consecutive Summers
math.ceil
ceil
math.sqrt
sqrt
math
1
[4th version] fast (and limited memory)
Count Consecutive Summers
not
while
3
Generate big stacks with a bit of OOP
Stacking Cubes
class
Tuple
typing.Tuple
set-comp
yield
3
2
[typed] Coroutine, filters, cached expressions
Reverse Engineer
typing.Generator
Generator
typing.Callable
Callable
cache
3
1
Proud of my math skills to prove that ^^
Strawberry Fields
atan
math.atan
math.degrees
degrees
math.sqrt
6
1
b/o/d/x format or handle as int
Integer Palindrome
case
match-case
math.log
log
math.floor
6
[OOP] "To infinity, and beyond !" for determine coefficients
Simplification
class
eval
property
decorator
is
7
4 clear lines: next(possible points generator)
Ore In The Desert
math.hypot
hypot
next
all
round
7
1
Coroutine
Colder-Warmer
gt
operator.gt
lt
operator.lt
dist
8
2
[5th] 1-liner: count odd divisors, complexity: O(sqrt(n))
Count Consecutive Summers
set
lambda
sum
range
comprehension
10
Use infos to filter grid cells and pick any cell
Colder-Warmer
math.hypot
hypot
set-comp
float
math
13
3
max(cycles generator, key=len, default=[])
Network Loops
union
set-comp
yield
dict-comp
None
14
1
heapq, stacks memory, only 10 02 12 21 (not really good but it works)
Anagrams By Stacks
heapify
heapq.heapify
heappush
heapq.heappush
heappop
15
Itertools & random powers
Reverse Engineer
randint
random.randint
itertools.starmap
starmap
ZeroDivisionError
15
With fractions module, and divmod
Fractions Addition
Fraction
fractions.Fraction
fractions
divmod
inline-if
16
1
1234321
Integer Palindrome
math.log
log
math.floor
floor
divmod
17
str
Integer Palindrome
bool
int
str
1
minimize errors
Mono Captcha
insert
map
enumerate
pop
index
not str but math module
Integer Palindrome
math.log10
log10
math.floor
floor
divmod
Keep or break the ring with a maximum of rings connected to it, that's the question
Break Rings
union
functools.reduce
reduce
functools
min
3
[v2] count odd divisors with math formula
Count Consecutive Summers
math.sqrt
sqrt
math
break
set
1
My 100th mission revisited with set methods
Break Rings
isdisjoint
issubset
union
filter
map
Watchtower
Short thanks to scipy.ndimage.label
Boundary Blocks
scipy.ndimage.label
label
scipy
numpy.array
array
1
10
With continued fractions
Exploring Calkin-Wilf Tree
Fraction
fractions.Fraction
fractions
groupby
itertools.groupby
1
scipy.ndimage power
Bacteria Colonies
scipy.ndimage.binary_dilation
binary_dilation
numpy.vectorize
vectorize
find_objects
2
Generate all solutions: sympy to solve linear equation system, itertools for bruteforce.
Magic Square
sympy.solve
sympy.symbols
symbols
solve
sympy
2
3 guesses max: divisor with max futures remainders to divide possibilities
Number Guess
intersection
set-comp
min
set
max
4
1
v2: Short thanks to scipy.ndimage.label
Boundary Blocks
scipy.ndimage.label
label
slice
scipy
numpy.array
4
[13 clear lines] Numpy array mod 2
Wall Keeper
numpy.array
array
numpy
abs
in
5
Dynamic Programming: (lcs set, common length) table
DNA Common Sequence
set-comp
enumerate
max
inline-if
sorted
7
[1-liner 257 chars] sympy.Matrix, reduced row-echelon form mod 2, last column
Wall Keeper
enumerate
abs
lambda
if-comprehension
in
9
Find the right key...
Vigenere Cipher
string.index
startswith
ascii_uppercase
string.ascii_uppercase
string
17
1
1/e
Bag of Santa Claus
math.e
e
math
or
and
20
try except, slope, min/max with key, bad complexity
Convex Hull
tuple
index
min
except
try
1
Best solution for a M x N grid, using matrices (modulo 2)
Wall Keeper
combinations
itertools.combinations
next
yield
all
1
Trust the random on filtered possibilities
Bulls and Cows
random.choice
choice
random
itertools.permutations
permutations
[typed] Simplier than I thought
Ethernet Ring Dimensioning
StopIteration
typing.Union
Union
math.ceil
ceil
Descending score, exclude cases, positionning and flip chips
Numbered Triangles
itertools.permutations
permutations
itertools.product
product
yield
Escher
sum bool
The Secret Room
divmod
None
lambda
sum
join
1
4
with items coordinates dictionary (so seaside traveled once)
Compass, Map and Spyglass
dict-comp
enumerate
abs
max
sum
1
1
3-lines: Counter
The Tower
index
min
lambda
comprehension
1
2
@maxi(paths generator)
Graphical Key
itertools.product
product
set-comp
yield
decorator
2
12
Buttons generator (with DFS) and a reverse_sorting decorator
The Buttons
StopIteration
splitlines
next
yield
decorator
2
2
min(enumerate(cols(wall)), count '#' lambda key)[0]
The Stone Wall
strip
zip
enumerate
min
lambda
2
with collections.Counter
Wild Dogs
math.hypot
hypot
combinations
itertools.combinations
collections.Counter
3
1
Try to remove from deck with sorted hand
Card Game
KeyError
set-comp
remove
sort
pop
3
1
next(generator, -1), eval and re
Safe Code
startswith
digits
string.digits
eval
next
7
With lru_cache/setrecursionlimit and without
The Stones
any
add
min
set
if-comprehension
8
1
I wanted to use itertools.filterfalse alongside with filter
The Ship Teams
filterfalse
itertools.filterfalse
filter
get
itertools
10
Neighboring coordinates?
Hypercube
itertools.product
product
dict-comp
all
any
15
1
with python 3.8+
Keys and Locks
splitlines
reversed
strip
any
zip
16
color counter and rearrangements
The Tower
collections.Counter
Counter
collections
index
min
17
strip and split with \n, zip(*rows)
Ground for the House
strip
zip
enumerate
min
max
1
lambda function [sorted(gen), sorted(gen)]
The Ship Teams
items
lambda
or
sorted
if-comprehension
First
Treasures
collections.fromkeys
OrderedDict
collections.OrderedDict
fromkeys
items
Not On Map
with collections.Counter
Most Wanted Letter
collections.Counter
Counter
items
collections
isalpha
1
Composition/functools: three uses of itertools, one counter
Aggregate and Count
itertools.repeat
repeat
itertools.starmap
starmap
functools.partial
1
First
Word Search
collections.defaultdict
defaultdict
set-comp
collections.Counter
Counter
2
1-liner: three uses of itertools, one counter
Aggregate and Count
itertools.repeat
repeat
itertools.starmap
starmap
chain
3
1
divmod to list digits
Base change - Position System
reverse
divmod
or
join
while
6
String method "__len__"
Length of the String
str
12
3
just the built-in function "len" really
Length of the String
len
1