ALL permutations of a list with repetition but not doubles

2024/11/17 2:59:10

I have seen similar but not the same: here. I definitely want the permutations, not combinations, of all list elements. Mine is different because itertools permutation of a,b,c returns abc but not aba (soooo close). How can I get results like aba returned as well?

('a',)     <-excellent
('b',)     <-excellent
('c',)     <-excellent
('a', 'b') <-excellent
('a', 'c') <-excellent
('b', 'a') <-excellent
('b', 'c') <-excellent
('c', 'a') <-excellent
('c', 'b') <-excellent
('a', 'b', 'c') <-- I need a,b,a
('a', 'c', 'b') <-- I need a,c,a
('b', 'a', 'c') <-- I need b,a,b... you get the idea

Oh max length of permutations ("r" in the python.org itertools) is equal to len(list), and I don't want to include 'doubles' such as aab or abb ...or abba :P The list could be any length.

import itertools
from itertools import product
my_list = ["a","b","c"]
#print list(itertools.permutations(my_list, 1))
#print list(itertools.permutations(my_list, 2))
#print list(itertools.permutations(my_list, 3)) <-- this *ALMOST* works

I combined the above into a for loop

def all_combinations(varsxx):repeat = 1all_combinations_result = []for item in varsxx:if repeat <= len(varsxx):all_combinations_result.append(list(itertools.permutations(varsxx, repeat)))repeat += 1return all_combinations_result

For reference, when I did this on paper I got 21 results.

Also is there any merit in converting the list of strings into a list of numbers. My thought was that numbers would be easier to work with for the permutations tool. Strings might be 10 to 50 chars..ish.

Answer

Even though you "definitely want the permutations", it sounds like you don't really want that, you actually want the Cartesian product of your sequence with itself from 1 to len(sequence) times, with results with neighbouring equal elements filtered out.

Something like:

In [16]: from itertools import productIn [17]: def has_doubles(x): return any(i==j for i,j in zip(x, x[1:]))In [18]: seq = ["a","b","c"]In [19]: [x for n in range(len(seq)) for x in product(seq, repeat=n+1) if not has_doubles(x)]
Out[19]: 
[('a',),('b',),('c',),('a', 'b'),('a', 'c'),('b', 'a'),('b', 'c'),('c', 'a'),('c', 'b'),('a', 'b', 'a'),('a', 'b', 'c'),('a', 'c', 'a'),('a', 'c', 'b'),('b', 'a', 'b'),('b', 'a', 'c'),('b', 'c', 'a'),('b', 'c', 'b'),('c', 'a', 'b'),('c', 'a', 'c'),('c', 'b', 'a'),('c', 'b', 'c')]In [20]: len(_)
Out[20]: 21
https://en.xdnf.cn/q/119123.html

Related Q&A

NameError: name current_portfolio is not defined

I am getting NameError: name current_portfolio is not defineddef initialize(context): context.sym = symbol(xxx) context.i = 0def handle_data(context, data):context.i += 1 if context.i < 60:returnsma…

Scrape an Ajax form with .submit() with Python and Selenium

I am trying to get the link from a web page. The web page sends the request using javascript, then the server sends a response which goes directly to download a PDF. This new PDF is automatically downl…

How to process break an array in Python?

I would like to use a double array. But I still fail to do it. This what I did. Folder = "D:\folder" Name = [gadfg5, 546sfdgh] Ver = [None, hhdt5463]for dn in Name :for dr in Ver :if dr is No…

Why am I getting replacement index 1 out of range for positional args tuple error

I keep getting this error: Replacement index 1 out of range for positional args tuple on this line of code: print("{1}, {2}, {3}, {4}".format(question[3]), question[4], question[5], question[…

Python: Find keywords in a text file from another text file

Take this invoice.txt for exampleInvoice NumberINV-3337Order Number12345Invoice DateJanuary 25, 2016Due DateJanuary 31, 2016And this is what dict.txt looks like:Invoice DateInvoice NumberDue DateOrder …

How to split a list into chucks of different sizes specified by another list? [duplicate]

This question already has answers here:How to Split or break a Python list into Unequal chunks, with specified chunk sizes(3 answers)Closed 4 years ago.I have an array I am trying to split into chunks …

Python Sum of digits in a string function

My function needs to take in a sentence and return the sum of the numbers inside. Any advice?def sumOfDigits(sentence):sumof=0for x in sentence:if sentence.isdigit(x)== True:sumof+=int(x)return sumof

How to select columns using dynamic select query using window function

I have sample input dataframe as below, but the value (clm starting with m) columns can be n number. customer_id|month_id|m1 |m2 |m3 .......m_n 1001 | 01 |10 |20 1002 | 01 |20…

Downloading Books from website with python

Im downloading books from the website, and almost my code runs smoothly, but when I try to open the pdf Book on my PC. An error generated by Adobe Acrobat Reader that this is not supported file type.He…

Discord.py How can I make a bot delete messages after a specific amount of time

I have a discord bot that sends images to users when they use the !img command, I dont want people to request an image and then have it sit there until someone deletes it. Is there any way I can make i…