From eb1c9f64afed484362a40ccaf8fb45bde7f6f5af Mon Sep 17 00:00:00 2001 From: Pragy Agarwal Date: Mon, 27 Jan 2020 15:59:28 +0530 Subject: [PATCH] Fix code indentation --- Recursion and Backtracking/3.md | 70 ++++++++++++++++----------------- 1 file changed, 34 insertions(+), 36 deletions(-) diff --git a/Recursion and Backtracking/3.md b/Recursion and Backtracking/3.md index bdd65b3..f45ffd9 100644 --- a/Recursion and Backtracking/3.md +++ b/Recursion and Backtracking/3.md @@ -14,31 +14,31 @@ output: 2 ```python def check(a, b): -sq = int((a + b) ** 0.5) -return (sq * sq) == (a + b) + sq = int((a + b) ** 0.5) + return (sq * sq) == (a + b) -if len(A) == 1: # corner case -return int(check(A[0], 0)) + if len(A) == 1: # corner case + return int(check(A[0], 0)) count = 0 def permute_distinct(S, i): -global count -if i == len(S): -count += 1 + global count + if i == len(S): + count += 1 -for j in range(i, len(S)): -if S[j] in S[i:j]: # prevent duplicates -continue + for j in range(i, len(S)): + if S[j] in S[i:j]: # prevent duplicates + continue -if i > 0 and (not check(S[j], S[i-1])): # invalid solution - branch and bound -continue + if i > 0 and (not check(S[j], S[i-1])): # invalid solution - branch and bound + continue -S[i], S[j] = S[j], S[i] -permute_distinct(S, i+1) + S[i], S[j] = S[j], S[i] + permute_distinct(S, i+1) -S[i], S[j] = S[j], S[i] # backtrack -permute_distinct(A, 0) -return count + S[i], S[j] = S[j], S[i] # backtrack + permute_distinct(A, 0) + return count ``` Gray Code @@ -67,11 +67,11 @@ Example G(2) to G(3): ``` ```python def gray(self, n): -codes = [0, 1] # length 1 -for i in range(1, n): -new_codes = [s | (1 << i) for s in reversed(codes)] -codes += new_codes -return codes + codes = [0, 1] # length 1 + for i in range(1, n): + new_codes = [s | (1 << i) for s in reversed(codes)] + codes += new_codes + return codes ``` N Queens @@ -92,20 +92,18 @@ B = ["cat", "cats", "and", "sand", "dog"] Output 1: ["cat sand dog", "cats and dog"] -``` ```python def wordBreak(A, B): -B = set(B) -sents = [] -def foo(i, start, sent): -word = A[start:i+1] -if i == len(A): -if word in B: -sents.append((sent + ' ' + word).strip()) -return - -if word in B: -foo(i+1, i+1, sent + ' ' + word) -foo(i+1, start, sent) -foo(0, 0, '') + B = set(B) + sents = [] + def foo(i, start, sent): + word = A[start:i+1] + if i == len(A): + if word in B: + sents.append((sent + ' ' + word).strip()) + return + if word in B: + foo(i+1, i+1, sent + ' ' + word) + foo(i+1, start, sent) + foo(0, 0, '') ``` \ No newline at end of file