Skip to content

Commit 8bea72b

Browse files
committed
Added an example in Backtracking in python
1 parent 1d9f03f commit 8bea72b

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#Backtracking is a form of recursion. But it involves choosing only option out of any possibilities. We begin by choosing an option and backtrack from it, if we reach a state where we conclude that this specific option does not give the required solution. We repeat these steps by going across each available option until we get the desired solution.
2+
#This is an example of finding all possible order of arrangements of a given set of letters. When we choose a pair we apply backtracking to verify if that exact pair has already been created or not. If not already created, the pair is added to the answer list else it is ignored.
3+
def permute(list, s):
4+
if list == 1:
5+
return s
6+
else:
7+
return [ y + x
8+
for y in permute(1, s)
9+
for x in permute(list - 1, s)
10+
]
11+
12+
print(permute(1, ["a","b","c"]))
13+
print(permute(2, ["a","b","c"]))
14+
15+
#The ouput should be :
16+
#['a', 'b', 'c']
17+
#['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
18+
#Contributed by The-N3rd. Thank you.

0 commit comments

Comments
 (0)