cache = {} def f(s): try: return cache[s] except: if not s: ans = 0 elif s[0] == s[-1]: ans = f(s[1:-1]) else: ans = min(f(s[1:]), f(s[:-1])) + 1 cache[s] = ans return ans
Recursion with memoization.
from itertools import* f=lambda a:any(all(x in'369'for x in str(sum(y)))for y in combinations(a,3))
True if a set can be found, False otherwise.
lambda a:all(len(set(x))>3for x in[a[0][:2]+a[1][:2]]+a+zip(*a))
Takes a 2D array of numbers. Gives True
for valid Sudoku solutions, False
otherwise.
Checks if each item in the list [a[0][:2]+a[1][:2]]+a+zip(*a)
has 4 distinct elements. a
gives rows, zip(*a)
(Python idiom for transpose) gives columns. We need to still check for boxes, but we can get away with checking only one box; assuming the rows and columns are verified, we can deduce the remaining boxes like the following.
a b c d e f g h
1) (a,b,c,d) includes each of 1,2,3,4 once 2) (e,f,g,h) includes each of 1,2,3,4 once 3) = 1)+2) => (a,b,c,d,e,f,g,h) includes each of 1,2,3,4 twice 4) (a,b,e,f) includes each of 1,2,3,4 once 5) = 3)-4) => (c,d,g,h) includes each of 1,2,3,4 once
[:|.^:#,~`,/&i.&#{:~
Anonymous tacit monadic verb (function with 1 argument). To use, assign it to a name and pass it an array.
f=:[:|.^:#,~`,/&i.&#{:~ f 5 4 2 9 11 10 6 >> 11 9 5 2 4 6 10 f 10 >> 10 f 21 14 7 82 19 25 63 44 76 2 >> 76 44 21 14 2 7 19 25 63 82
Full test cases here.
[:|.^:#,~`,/&i.&#{:~
:~ Sort in decreasing order ,~`,/&i.&# Generate alternating indexes { Rearrange by the generated indexes [:|.^:# Reverse if the length is odd