Skip to content

Commit bc0bfcd

Browse files
committed
small fixes
1 parent ff4e184 commit bc0bfcd

File tree

3 files changed

+42
-10
lines changed

3 files changed

+42
-10
lines changed

LCA.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,12 @@ def lca(root, a, b):
1717
if root.value == a or root.value == b: return root
1818
left = lca(root.left, a, b)
1919
right = lca(root.right, a, b)
20-
if left and right: # if p and q are on both sides
20+
if left and right:
21+
# a & b are on both sides
2122
return root
22-
else: # either a/b is on one side OR a/b is not in L&R subtrees
23+
else:
24+
# EITHER a/b is on one side
25+
# OR a/b is not in L&R subtrees
2326
return left if left else right
2427

2528

scramble_str.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -98,25 +98,28 @@ def scramble_str1(s1, s2):
9898
# a | tten <---> tten | a
9999
# ti | on <---> it | no
100100
# o | n <---> n | o
101-
102101
# t | i <---> i | t
102+
def elem(s):
103+
return ''.join(sorted(s))
104+
105+
def same_elems(s1, s2):
106+
return elem(s1) == elem(s2)
107+
103108
def matching(s1, s2):
104109
#print s1, s2
105110
if s1 == s2: return True
106111
if len(s1) != len(s2): return False
107112
for i in range(1,len(s1)):
108113
x1, y1 = s1[:i], s1[i:]
109-
110114
x2, y2 = s2[:i], s2[i:]
111-
if (''.join(sorted(x1)) == ''.join(sorted(x2))) and \
112-
(''.join(sorted(y1)) == ''.join(sorted(y2))) and \
115+
x3, y3 = s2[-i:], s2[:-i]
116+
117+
if same_elems(x1,x2) and same_elems(y1,y2) and \
113118
matching(x1, x2) and matching(y1, y2):
114119
return True
115120

116-
x3, y3 = s2[-i:], s2[:-i]
117-
if (''.join(sorted(x1)) == ''.join(sorted(x3))) and \
118-
(''.join(sorted(y1)) == ''.join(sorted(y3))) and \
119-
matching(x1, x3) and matching(y1, y3):
121+
if same_elems(x1,x3) and same_elems(y1,y3) and \
122+
matching(x1,x3) and matching(y1,y3):
120123
return True
121124

122125
return False

valid_sudoku.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,32 @@ def check_conflict(M, x, y, val):
3131
return False
3232

3333

34+
# whether the sudoku is valid
35+
def is_valid_sudoku(M):
36+
N = 9
37+
assert len(M) == N and len(M[0]) == N
38+
# row; no repetition between 0~9.
39+
for i in range(N):
40+
if not valid_array(M[i]):
41+
return False
42+
# col
43+
for j in range(N):
44+
if not valid_array([M[i][j] for i in range(N)]):
45+
return False
46+
47+
# 3x3 cells
48+
for x in range(0,9,3):
49+
for y in range(0,9,3):
50+
A = [M[i][j] for i in range(x,x+3) for j in range(y,y+3)]
51+
if not valid_array(A):
52+
return False
53+
return True
54+
55+
56+
def valid_array(A):
57+
if len(set(A)) == len(A) and min(A) >= 1 and max(A) <= 9: return True
58+
return False
59+
3460

3561
if __name__ == '__main__':
3662
M = [[5,3,0,0,7,0,0,0,0],

0 commit comments

Comments
 (0)