Building Permutation with Python

2024/11/17 20:45:52

I'm trying to write a programme to get all permutations of a string of letter using recursion. As I'm a beginner in Python, I learnt about recursion with examples like Fibonacci Number and Factorial. I understand these math examples, but I still struggle with building a functional programme with recursion. I tried to understand other similar issues on web but still cannot grasp the concept.

So the problem is: How to get all permutations of a string of letter? For example str='abc' . My logic goes something like this:

  1. create 3 slots for 3 letters abc
  2. add in a letter, say 'a', and it can go to all 3 slots
  3. building on the previous case, put in 'b'. Now only 2 slots left, and b can go to any of the 2 slot.
  4. repeat until no more slot left. Now we reach a base case where no. of slot = 0.

But I cannot write in code

Answer

I have implemented your algorithm in python, using a string containing dots '.' as the slots. Of course this means the algorithm won't work if you also have dots in the original string.

I have blanked out most of the lines of my implementation; it's up to you to finish it. Before blanking out those lines, I tested it, and it works.

  • create 3 slots for 3 letters abc: '.' * len(s)
  • add in a letter, say 'a', and it can go to all 3 slots: use function insert in a for-loop where i is the position of every '.' in slots
  • building on the previous case, put in 'b'. Now only 2 slots left, and b can go to any of the 2 slot: after every insert, make a recursive call
  • repeat until no more slot left. Now we reach a base case where no. of slot = 0
def permutations(s):return helper_perms(s, '.' * len(s), len(s))def helper_perms(s, slots, k):if ??? # base casereturn ???else:results = []for i,c in enumerate(slots):if c == '.':results.extend(helper_perms(s, ???, ???)) # insert some char from s into slots and make a recursive callreturn resultsdef insert(slots, i, c):return ??? # return a new string with character c inserted at position i in slotsprint( permutations('abc') )
# ['cba', 'cab', 'bca', 'acb', 'bac', 'abc']
https://en.xdnf.cn/q/120159.html

Related Q&A

Python: Is There a builtin that works similar but opposite to .index()?

Just a forewarning: I just recently started programming and Python is my first language and only language so far.Is there a builtin that works in the opposite way of .index()? Im looking for this beca…

Get a subset of a data frame into a matrix

I have this data frame:I want just the numbers under August - September to be placed into a matrix, how can I do this?I tried this cf = df.iloc[:,1:12] which gives me but it gives me the headers as w…

Get Pairs of List Python [duplicate]

This question already has answers here:How can I iterate over overlapping (current, next) pairs of values from a list?(13 answers)Closed 9 years ago.c = [1,2,3,4,5,6,7,8,9,10]for a,b in func(c):doSome…

Python - make a list

How can I turn something like this: (not a file)Edit: Its what I get when I print this:adjusted_coordinate_list = str(adjusted_X_coordinate) + , + str(Y_coordinate)1,1 1,2 1,3 1,4 1,5into this:[1,1,1,2…

Error while running test case

I need to test my code below. I am using one test to see if it is working or not. but dont know what exactly I should pass as a parameter in the test code. Please see the test code at the end and pleas…

How to run something on each line of txt file?

I am trying to get this to run on each line of a .txt file.D1 =int(lines[0])*10 D2 =int(lines[1])*9 D3 =int(lines[2])*8 D4 =int(lines[3])*7 D5 =int(lines[4])*6 D6 =int(lines[5])*5 D7 =int(lines[6])*4 D…

Python np.nditer() - ValueError: Too many operands

I have a few methods which pass different amount of messy data to this function to combine headers with data and return a list of dictionaries:def zip_data(self, indicator_names, indicator_values):valu…

Python 3 - Find the Mode of a List

def mode(L):shows = []modeList = []L.sort()length = len(L)for num in L:count = L.count(num)shows.append(count)print List = , LmaxI = shows.index(max(shows))for i in shows:if i == maxI:if modeList == []…

Create list of sublists [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 9 years ago.Improve…

Python error - list index out of range?

Anyone help me see why I keep getting "list index out of range" as an error ?? def printInfo(average):average.sort() # sorts the list of tuples average.reverse() # reverses the list of tu…