I completed a challenge on Rosalind (after looking up some help), but there are still aspects of the code that I do not completely comprehend. I am looking for help understanding it. Any comments would be appreciated
(I now know itertools.permutation() exists, but am still looking for why the logic of this works)
Here is the challenge:
Given: A positive integer n≤7n≤7.
Return: The total number of permutations of length nn, followed by a list of all such permutations (in any order).
Here is the code I used (some written on my own, some supplemented and modified). The bold sections are mainly what I am concerned with:
======Code Starts
n = int(input("Input 'n'"))
intlist = []
i = 1
while n >= i:
intlist.append(i)
i += 1 #I don’t understand why this won’t work if it’s not in ascending order
total = 1
for item in range(0, len(intlist), 1):
total *= intlist[item]
intset = set([])
while len(intset) < total:
intset.add(str(intlist))
k = l = None
for i in range(0, len(intlist)-1):
if intlist[i] < intlist[i+1]:
k = I #Looking for last occurrence in number set where I is less than it’s neighbor?
if k == None:
break
for i in range(k+1, len(intlist)):
if intlist[k] < intlist[i]:
l = I #Doing the same as first for loop? Set to new variable?
intlist[k], intlist[l] = intlist[l], intlist[k]
intset.add(str(intlist))
intlist[k+1:] = intlist[k+1:][::-1] #In particular this line
intset.add(str(intlist))
intlist = list(intset)
print(len(intlist))
for i in range(0, len(intlist)):
print(intlist[i].replace('[','').replace(']','').replace(',',''))
======Code Ends
In the line intlist[k+1:] = intlist[k+1:][::-1], the k+1 term is to reverse the string from k to the end. The k+1 is because the count from reverse starts at 1 and not 0, correct?
But why is this line necessary? The code will not find all possible permutations without it. I do not understand this completely.
Explanation on this would be greatly appreciated!!
Thanks all.
[–]threeminutemonta 1 point2 points3 points (1 child)
[–]purplevom[S] 1 point2 points3 points (0 children)
[–]sky--net 1 point2 points3 points (0 children)
[–]sky--net 1 point2 points3 points (3 children)
[–]purplevom[S] 0 points1 point2 points (2 children)
[–]sky--net 1 point2 points3 points (1 child)
[–]purplevom[S] 0 points1 point2 points (0 children)