Itertools permutation with OR operatorHow to generate all permutations of a list in PythonDoes Python have a ternary conditional operator?Behaviour of increment and decrement operators in PythonApply a permutation to a list with a different length multiple timesClassified permutations using itertools or numpyPython regex with w does not workItertools permutation with lambdaItertools permutationsItertools permutationItertools permutations with replacement one by one
Is superuser the same as root?
Complications of displaced core material?
What is the purpose of the yellow wired panels on the IBM 360 Model 20?
ifconfig shows UP while ip link shows DOWN
Why is this integration method not valid?
"Official wife" or "Formal wife"?
Team has team lunch everyday, am I forced to go?
How does Dreadhorde Arcanist interact with split cards?
Visual Block Mode edit with sequential number
How do you earn the reader's trust?
Is a world with one country feeding everyone possible?
Are there historical examples of audiences drawn to a work that was "so bad it's good"?
Why'd a rational buyer offer to buy with no conditions precedent?
How does the Earth's center produce heat?
Status of proof by contradiction and excluded middle throughout the history of mathematics?
How to create a `range`-like iterable object of floats?
Count all vowels in string
How can I minimize the damage of an unstable nuclear reactor to the surrounding area?
Why did OJ Simpson's trial take 9 months?
Is this homebrew "Cactus Grenade" cantrip balanced?
Possibility of faking someone's public key
Why was this character made Grand Maester?
Quantum corrections to geometry
Is keeping the forking link on a true fork necessary (Github/GPL)?
Itertools permutation with OR operator
How to generate all permutations of a list in PythonDoes Python have a ternary conditional operator?Behaviour of increment and decrement operators in PythonApply a permutation to a list with a different length multiple timesClassified permutations using itertools or numpyPython regex with w does not workItertools permutation with lambdaItertools permutationsItertools permutationItertools permutations with replacement one by one
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
Given a list
of strings
, I want to return all possible permutations where the strings may contain an OR operator.
How can I do this? A pointer to which functions I should use is ok (with code will be helpful, but not required).
For example,
#!/usr/bin/env python3
import itertools
list_of_strings = ['a|b', 'c']
# I probably need to add some '|' splitter here
for permutation in itertools.permutations(list_of_strings, 2):
print(''.join(str(word) for word in permutation))
prints
a|bc
ca|b
but I want
ac
bc
ca
cb
That is, using either 'a' or 'b', but not both.
There may be multiple strings strings with '|'. For example, list_of_strings = ['a|b', 'c', 'd|e']
.
There may be multiple ORs within a string. For example, list_of_strings = ['a|b|d|e', 'c']
.
The previous example should print
ac
bc
dc
ec
ca
cb
cd
ce
The strings may be longer than one character. For example, list_of_strings = ['race', 'car|horse']
.
The output should be
racecar
racehorse
carrace
horserace
python python-3.x itertools
add a comment |
Given a list
of strings
, I want to return all possible permutations where the strings may contain an OR operator.
How can I do this? A pointer to which functions I should use is ok (with code will be helpful, but not required).
For example,
#!/usr/bin/env python3
import itertools
list_of_strings = ['a|b', 'c']
# I probably need to add some '|' splitter here
for permutation in itertools.permutations(list_of_strings, 2):
print(''.join(str(word) for word in permutation))
prints
a|bc
ca|b
but I want
ac
bc
ca
cb
That is, using either 'a' or 'b', but not both.
There may be multiple strings strings with '|'. For example, list_of_strings = ['a|b', 'c', 'd|e']
.
There may be multiple ORs within a string. For example, list_of_strings = ['a|b|d|e', 'c']
.
The previous example should print
ac
bc
dc
ec
ca
cb
cd
ce
The strings may be longer than one character. For example, list_of_strings = ['race', 'car|horse']
.
The output should be
racecar
racehorse
carrace
horserace
python python-3.x itertools
There was an answer that words, but gives duplicated results.def perm(s, n=2): for p in itertools.product(*[k.split("|") for k in s]): yield from itertools.permutations(p, n)
. Withperm(['a|b', 'c', 'd|e'])
,['a', 'c']
is duplicated. In my case, I could generate the file with all permutations and usesort
anduniq
to remove duplicates.
– gxowrrqgc
Mar 23 at 21:14
Would you mind try to use my answer and see if it suits your needs?
– Sanyash
Mar 23 at 21:21
@Sanyash Yes, your code is more efficient than creating the file and then sorting. I've added a comment to your post to fit my needs.
– gxowrrqgc
Mar 23 at 22:19
add a comment |
Given a list
of strings
, I want to return all possible permutations where the strings may contain an OR operator.
How can I do this? A pointer to which functions I should use is ok (with code will be helpful, but not required).
For example,
#!/usr/bin/env python3
import itertools
list_of_strings = ['a|b', 'c']
# I probably need to add some '|' splitter here
for permutation in itertools.permutations(list_of_strings, 2):
print(''.join(str(word) for word in permutation))
prints
a|bc
ca|b
but I want
ac
bc
ca
cb
That is, using either 'a' or 'b', but not both.
There may be multiple strings strings with '|'. For example, list_of_strings = ['a|b', 'c', 'd|e']
.
There may be multiple ORs within a string. For example, list_of_strings = ['a|b|d|e', 'c']
.
The previous example should print
ac
bc
dc
ec
ca
cb
cd
ce
The strings may be longer than one character. For example, list_of_strings = ['race', 'car|horse']
.
The output should be
racecar
racehorse
carrace
horserace
python python-3.x itertools
Given a list
of strings
, I want to return all possible permutations where the strings may contain an OR operator.
How can I do this? A pointer to which functions I should use is ok (with code will be helpful, but not required).
For example,
#!/usr/bin/env python3
import itertools
list_of_strings = ['a|b', 'c']
# I probably need to add some '|' splitter here
for permutation in itertools.permutations(list_of_strings, 2):
print(''.join(str(word) for word in permutation))
prints
a|bc
ca|b
but I want
ac
bc
ca
cb
That is, using either 'a' or 'b', but not both.
There may be multiple strings strings with '|'. For example, list_of_strings = ['a|b', 'c', 'd|e']
.
There may be multiple ORs within a string. For example, list_of_strings = ['a|b|d|e', 'c']
.
The previous example should print
ac
bc
dc
ec
ca
cb
cd
ce
The strings may be longer than one character. For example, list_of_strings = ['race', 'car|horse']
.
The output should be
racecar
racehorse
carrace
horserace
python python-3.x itertools
python python-3.x itertools
edited Mar 23 at 21:50
gxowrrqgc
asked Mar 23 at 19:18
gxowrrqgcgxowrrqgc
164
164
There was an answer that words, but gives duplicated results.def perm(s, n=2): for p in itertools.product(*[k.split("|") for k in s]): yield from itertools.permutations(p, n)
. Withperm(['a|b', 'c', 'd|e'])
,['a', 'c']
is duplicated. In my case, I could generate the file with all permutations and usesort
anduniq
to remove duplicates.
– gxowrrqgc
Mar 23 at 21:14
Would you mind try to use my answer and see if it suits your needs?
– Sanyash
Mar 23 at 21:21
@Sanyash Yes, your code is more efficient than creating the file and then sorting. I've added a comment to your post to fit my needs.
– gxowrrqgc
Mar 23 at 22:19
add a comment |
There was an answer that words, but gives duplicated results.def perm(s, n=2): for p in itertools.product(*[k.split("|") for k in s]): yield from itertools.permutations(p, n)
. Withperm(['a|b', 'c', 'd|e'])
,['a', 'c']
is duplicated. In my case, I could generate the file with all permutations and usesort
anduniq
to remove duplicates.
– gxowrrqgc
Mar 23 at 21:14
Would you mind try to use my answer and see if it suits your needs?
– Sanyash
Mar 23 at 21:21
@Sanyash Yes, your code is more efficient than creating the file and then sorting. I've added a comment to your post to fit my needs.
– gxowrrqgc
Mar 23 at 22:19
There was an answer that words, but gives duplicated results.
def perm(s, n=2): for p in itertools.product(*[k.split("|") for k in s]): yield from itertools.permutations(p, n)
. With perm(['a|b', 'c', 'd|e'])
, ['a', 'c']
is duplicated. In my case, I could generate the file with all permutations and use sort
and uniq
to remove duplicates.– gxowrrqgc
Mar 23 at 21:14
There was an answer that words, but gives duplicated results.
def perm(s, n=2): for p in itertools.product(*[k.split("|") for k in s]): yield from itertools.permutations(p, n)
. With perm(['a|b', 'c', 'd|e'])
, ['a', 'c']
is duplicated. In my case, I could generate the file with all permutations and use sort
and uniq
to remove duplicates.– gxowrrqgc
Mar 23 at 21:14
Would you mind try to use my answer and see if it suits your needs?
– Sanyash
Mar 23 at 21:21
Would you mind try to use my answer and see if it suits your needs?
– Sanyash
Mar 23 at 21:21
@Sanyash Yes, your code is more efficient than creating the file and then sorting. I've added a comment to your post to fit my needs.
– gxowrrqgc
Mar 23 at 22:19
@Sanyash Yes, your code is more efficient than creating the file and then sorting. I've added a comment to your post to fit my needs.
– gxowrrqgc
Mar 23 at 22:19
add a comment |
2 Answers
2
active
oldest
votes
There are just a few steps.
- Split each of your original strings on
|
to get lists of strings. - Compute the permutations of your list of lists of strings.
- Compute the product of each permutation
- Join each element of those products with the null string.
Using the itertools
and operator
modules, it looks like this:
>>> from itertools import product, permutations
>>> from operator import methodcaller
>>> splitter = methodcaller("split", "|")
>>> list_of_strings = ["a|b", "c", "foo|bar"]
>>> strings = ["".join(y) for x in permutations(map(splitter, list_of_strings)) for y in product(*x)]
>>> for s in strings:
... print(s)
...
acfoo
acbar
bcfoo
bcbar
afooc
abarc
bfooc
bbarc
cafoo
cabar
cbfoo
cbbar
cfooa
cfoob
cbara
cbarb
fooac
foobc
barac
barbc
fooca
foocb
barca
barcb
The long line more readably is
strings = ["".join(y)
for x in permutations(map(splitter, list_of_strings))
for y in product(*x)]
If you are not as prone to using map
as I usually am, you can get rid of methodcaller
and use a generator expression for the argument to permutations
.
strings = ["".join(z)
for y in permutations(x.split("|") for x in list_of_strings)
for z in product(*y)]
Cool! And generator expression will make it even a one-liner.
– Sanyash
Mar 23 at 22:32
This is even more efficient and clear than the other correct answer!
– gxowrrqgc
Mar 23 at 22:35
For future readers, remember to usepermutations(..., n)
for large lists if you only want a permutation that only uses n elements from the list.
– gxowrrqgc
Mar 23 at 22:35
There's no need for a second argument topermutations
; I'm computing the permutations of a list constructed from the original list of strings, which means you want all permutations.
– chepner
Mar 23 at 22:38
add a comment |
There is a solution with two stages:
generate permutations of
list_of_strings
recursively parse
or
operators
Have a look, seems to pass all your test cases, feel free to ask clarification in comments.
import itertools
def permutations_with_ors(list_of_strings):
for item in itertools.permutations(list_of_strings):
yield from parse_ors(item)
def parse_ors(tuple_of_strings):
for i, string in enumerate(tuple_of_strings):
if '|' in string:
for item in string.split('|'):
replaced = (
tuple_of_strings[:i] +
(item,) +
tuple_of_strings[i + 1:]
)
yield from parse_ors(replaced)
break
else:
yield ''.join(tuple_of_strings)
list_of_strings = ['a|b', 'c']
for item in permutations_with_ors(list_of_strings):
print(item)
# output:
# ac
# bc
# ca
# cb
print()
list_of_strings = ['a|b|d|e', 'c']
for item in permutations_with_ors(list_of_strings):
print(item)
# output:
# ac
# bc
# dc
# ec
# ca
# cb
# cd
# ce
print()
list_of_strings = ['a|b', 'c', 'd|e']
for item in permutations_with_ors(list_of_strings):
print(item)
# output is quite long, please check it yourself
print()
list_of_strings = ['race', 'car|horse']
for item in permutations_with_ors(list_of_strings):
print(item)
# output:
# racecar
# racehorse
# carrace
# horserace
I just tested this real data and forgot to mention that the strings may be longer than one character. I have added an example case in the post.
– gxowrrqgc
Mar 23 at 21:51
Updated my answer, now it passes the test case you added.
– Sanyash
Mar 23 at 21:58
For anyone wondering, replace''.join
inelse: yield ''.join(tuple_of_strings)
with'A'.join
to have "A" separate the original entries
– gxowrrqgc
Mar 23 at 22:18
I'm also usingfor item in itertools.permutations(list_of_strings, n):
to create permutations of length n.
– gxowrrqgc
Mar 23 at 22:21
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55317483%2fitertools-permutation-with-or-operator%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
There are just a few steps.
- Split each of your original strings on
|
to get lists of strings. - Compute the permutations of your list of lists of strings.
- Compute the product of each permutation
- Join each element of those products with the null string.
Using the itertools
and operator
modules, it looks like this:
>>> from itertools import product, permutations
>>> from operator import methodcaller
>>> splitter = methodcaller("split", "|")
>>> list_of_strings = ["a|b", "c", "foo|bar"]
>>> strings = ["".join(y) for x in permutations(map(splitter, list_of_strings)) for y in product(*x)]
>>> for s in strings:
... print(s)
...
acfoo
acbar
bcfoo
bcbar
afooc
abarc
bfooc
bbarc
cafoo
cabar
cbfoo
cbbar
cfooa
cfoob
cbara
cbarb
fooac
foobc
barac
barbc
fooca
foocb
barca
barcb
The long line more readably is
strings = ["".join(y)
for x in permutations(map(splitter, list_of_strings))
for y in product(*x)]
If you are not as prone to using map
as I usually am, you can get rid of methodcaller
and use a generator expression for the argument to permutations
.
strings = ["".join(z)
for y in permutations(x.split("|") for x in list_of_strings)
for z in product(*y)]
Cool! And generator expression will make it even a one-liner.
– Sanyash
Mar 23 at 22:32
This is even more efficient and clear than the other correct answer!
– gxowrrqgc
Mar 23 at 22:35
For future readers, remember to usepermutations(..., n)
for large lists if you only want a permutation that only uses n elements from the list.
– gxowrrqgc
Mar 23 at 22:35
There's no need for a second argument topermutations
; I'm computing the permutations of a list constructed from the original list of strings, which means you want all permutations.
– chepner
Mar 23 at 22:38
add a comment |
There are just a few steps.
- Split each of your original strings on
|
to get lists of strings. - Compute the permutations of your list of lists of strings.
- Compute the product of each permutation
- Join each element of those products with the null string.
Using the itertools
and operator
modules, it looks like this:
>>> from itertools import product, permutations
>>> from operator import methodcaller
>>> splitter = methodcaller("split", "|")
>>> list_of_strings = ["a|b", "c", "foo|bar"]
>>> strings = ["".join(y) for x in permutations(map(splitter, list_of_strings)) for y in product(*x)]
>>> for s in strings:
... print(s)
...
acfoo
acbar
bcfoo
bcbar
afooc
abarc
bfooc
bbarc
cafoo
cabar
cbfoo
cbbar
cfooa
cfoob
cbara
cbarb
fooac
foobc
barac
barbc
fooca
foocb
barca
barcb
The long line more readably is
strings = ["".join(y)
for x in permutations(map(splitter, list_of_strings))
for y in product(*x)]
If you are not as prone to using map
as I usually am, you can get rid of methodcaller
and use a generator expression for the argument to permutations
.
strings = ["".join(z)
for y in permutations(x.split("|") for x in list_of_strings)
for z in product(*y)]
Cool! And generator expression will make it even a one-liner.
– Sanyash
Mar 23 at 22:32
This is even more efficient and clear than the other correct answer!
– gxowrrqgc
Mar 23 at 22:35
For future readers, remember to usepermutations(..., n)
for large lists if you only want a permutation that only uses n elements from the list.
– gxowrrqgc
Mar 23 at 22:35
There's no need for a second argument topermutations
; I'm computing the permutations of a list constructed from the original list of strings, which means you want all permutations.
– chepner
Mar 23 at 22:38
add a comment |
There are just a few steps.
- Split each of your original strings on
|
to get lists of strings. - Compute the permutations of your list of lists of strings.
- Compute the product of each permutation
- Join each element of those products with the null string.
Using the itertools
and operator
modules, it looks like this:
>>> from itertools import product, permutations
>>> from operator import methodcaller
>>> splitter = methodcaller("split", "|")
>>> list_of_strings = ["a|b", "c", "foo|bar"]
>>> strings = ["".join(y) for x in permutations(map(splitter, list_of_strings)) for y in product(*x)]
>>> for s in strings:
... print(s)
...
acfoo
acbar
bcfoo
bcbar
afooc
abarc
bfooc
bbarc
cafoo
cabar
cbfoo
cbbar
cfooa
cfoob
cbara
cbarb
fooac
foobc
barac
barbc
fooca
foocb
barca
barcb
The long line more readably is
strings = ["".join(y)
for x in permutations(map(splitter, list_of_strings))
for y in product(*x)]
If you are not as prone to using map
as I usually am, you can get rid of methodcaller
and use a generator expression for the argument to permutations
.
strings = ["".join(z)
for y in permutations(x.split("|") for x in list_of_strings)
for z in product(*y)]
There are just a few steps.
- Split each of your original strings on
|
to get lists of strings. - Compute the permutations of your list of lists of strings.
- Compute the product of each permutation
- Join each element of those products with the null string.
Using the itertools
and operator
modules, it looks like this:
>>> from itertools import product, permutations
>>> from operator import methodcaller
>>> splitter = methodcaller("split", "|")
>>> list_of_strings = ["a|b", "c", "foo|bar"]
>>> strings = ["".join(y) for x in permutations(map(splitter, list_of_strings)) for y in product(*x)]
>>> for s in strings:
... print(s)
...
acfoo
acbar
bcfoo
bcbar
afooc
abarc
bfooc
bbarc
cafoo
cabar
cbfoo
cbbar
cfooa
cfoob
cbara
cbarb
fooac
foobc
barac
barbc
fooca
foocb
barca
barcb
The long line more readably is
strings = ["".join(y)
for x in permutations(map(splitter, list_of_strings))
for y in product(*x)]
If you are not as prone to using map
as I usually am, you can get rid of methodcaller
and use a generator expression for the argument to permutations
.
strings = ["".join(z)
for y in permutations(x.split("|") for x in list_of_strings)
for z in product(*y)]
edited Mar 23 at 22:35
answered Mar 23 at 22:22
chepnerchepner
269k38259353
269k38259353
Cool! And generator expression will make it even a one-liner.
– Sanyash
Mar 23 at 22:32
This is even more efficient and clear than the other correct answer!
– gxowrrqgc
Mar 23 at 22:35
For future readers, remember to usepermutations(..., n)
for large lists if you only want a permutation that only uses n elements from the list.
– gxowrrqgc
Mar 23 at 22:35
There's no need for a second argument topermutations
; I'm computing the permutations of a list constructed from the original list of strings, which means you want all permutations.
– chepner
Mar 23 at 22:38
add a comment |
Cool! And generator expression will make it even a one-liner.
– Sanyash
Mar 23 at 22:32
This is even more efficient and clear than the other correct answer!
– gxowrrqgc
Mar 23 at 22:35
For future readers, remember to usepermutations(..., n)
for large lists if you only want a permutation that only uses n elements from the list.
– gxowrrqgc
Mar 23 at 22:35
There's no need for a second argument topermutations
; I'm computing the permutations of a list constructed from the original list of strings, which means you want all permutations.
– chepner
Mar 23 at 22:38
Cool! And generator expression will make it even a one-liner.
– Sanyash
Mar 23 at 22:32
Cool! And generator expression will make it even a one-liner.
– Sanyash
Mar 23 at 22:32
This is even more efficient and clear than the other correct answer!
– gxowrrqgc
Mar 23 at 22:35
This is even more efficient and clear than the other correct answer!
– gxowrrqgc
Mar 23 at 22:35
For future readers, remember to use
permutations(..., n)
for large lists if you only want a permutation that only uses n elements from the list.– gxowrrqgc
Mar 23 at 22:35
For future readers, remember to use
permutations(..., n)
for large lists if you only want a permutation that only uses n elements from the list.– gxowrrqgc
Mar 23 at 22:35
There's no need for a second argument to
permutations
; I'm computing the permutations of a list constructed from the original list of strings, which means you want all permutations.– chepner
Mar 23 at 22:38
There's no need for a second argument to
permutations
; I'm computing the permutations of a list constructed from the original list of strings, which means you want all permutations.– chepner
Mar 23 at 22:38
add a comment |
There is a solution with two stages:
generate permutations of
list_of_strings
recursively parse
or
operators
Have a look, seems to pass all your test cases, feel free to ask clarification in comments.
import itertools
def permutations_with_ors(list_of_strings):
for item in itertools.permutations(list_of_strings):
yield from parse_ors(item)
def parse_ors(tuple_of_strings):
for i, string in enumerate(tuple_of_strings):
if '|' in string:
for item in string.split('|'):
replaced = (
tuple_of_strings[:i] +
(item,) +
tuple_of_strings[i + 1:]
)
yield from parse_ors(replaced)
break
else:
yield ''.join(tuple_of_strings)
list_of_strings = ['a|b', 'c']
for item in permutations_with_ors(list_of_strings):
print(item)
# output:
# ac
# bc
# ca
# cb
print()
list_of_strings = ['a|b|d|e', 'c']
for item in permutations_with_ors(list_of_strings):
print(item)
# output:
# ac
# bc
# dc
# ec
# ca
# cb
# cd
# ce
print()
list_of_strings = ['a|b', 'c', 'd|e']
for item in permutations_with_ors(list_of_strings):
print(item)
# output is quite long, please check it yourself
print()
list_of_strings = ['race', 'car|horse']
for item in permutations_with_ors(list_of_strings):
print(item)
# output:
# racecar
# racehorse
# carrace
# horserace
I just tested this real data and forgot to mention that the strings may be longer than one character. I have added an example case in the post.
– gxowrrqgc
Mar 23 at 21:51
Updated my answer, now it passes the test case you added.
– Sanyash
Mar 23 at 21:58
For anyone wondering, replace''.join
inelse: yield ''.join(tuple_of_strings)
with'A'.join
to have "A" separate the original entries
– gxowrrqgc
Mar 23 at 22:18
I'm also usingfor item in itertools.permutations(list_of_strings, n):
to create permutations of length n.
– gxowrrqgc
Mar 23 at 22:21
add a comment |
There is a solution with two stages:
generate permutations of
list_of_strings
recursively parse
or
operators
Have a look, seems to pass all your test cases, feel free to ask clarification in comments.
import itertools
def permutations_with_ors(list_of_strings):
for item in itertools.permutations(list_of_strings):
yield from parse_ors(item)
def parse_ors(tuple_of_strings):
for i, string in enumerate(tuple_of_strings):
if '|' in string:
for item in string.split('|'):
replaced = (
tuple_of_strings[:i] +
(item,) +
tuple_of_strings[i + 1:]
)
yield from parse_ors(replaced)
break
else:
yield ''.join(tuple_of_strings)
list_of_strings = ['a|b', 'c']
for item in permutations_with_ors(list_of_strings):
print(item)
# output:
# ac
# bc
# ca
# cb
print()
list_of_strings = ['a|b|d|e', 'c']
for item in permutations_with_ors(list_of_strings):
print(item)
# output:
# ac
# bc
# dc
# ec
# ca
# cb
# cd
# ce
print()
list_of_strings = ['a|b', 'c', 'd|e']
for item in permutations_with_ors(list_of_strings):
print(item)
# output is quite long, please check it yourself
print()
list_of_strings = ['race', 'car|horse']
for item in permutations_with_ors(list_of_strings):
print(item)
# output:
# racecar
# racehorse
# carrace
# horserace
I just tested this real data and forgot to mention that the strings may be longer than one character. I have added an example case in the post.
– gxowrrqgc
Mar 23 at 21:51
Updated my answer, now it passes the test case you added.
– Sanyash
Mar 23 at 21:58
For anyone wondering, replace''.join
inelse: yield ''.join(tuple_of_strings)
with'A'.join
to have "A" separate the original entries
– gxowrrqgc
Mar 23 at 22:18
I'm also usingfor item in itertools.permutations(list_of_strings, n):
to create permutations of length n.
– gxowrrqgc
Mar 23 at 22:21
add a comment |
There is a solution with two stages:
generate permutations of
list_of_strings
recursively parse
or
operators
Have a look, seems to pass all your test cases, feel free to ask clarification in comments.
import itertools
def permutations_with_ors(list_of_strings):
for item in itertools.permutations(list_of_strings):
yield from parse_ors(item)
def parse_ors(tuple_of_strings):
for i, string in enumerate(tuple_of_strings):
if '|' in string:
for item in string.split('|'):
replaced = (
tuple_of_strings[:i] +
(item,) +
tuple_of_strings[i + 1:]
)
yield from parse_ors(replaced)
break
else:
yield ''.join(tuple_of_strings)
list_of_strings = ['a|b', 'c']
for item in permutations_with_ors(list_of_strings):
print(item)
# output:
# ac
# bc
# ca
# cb
print()
list_of_strings = ['a|b|d|e', 'c']
for item in permutations_with_ors(list_of_strings):
print(item)
# output:
# ac
# bc
# dc
# ec
# ca
# cb
# cd
# ce
print()
list_of_strings = ['a|b', 'c', 'd|e']
for item in permutations_with_ors(list_of_strings):
print(item)
# output is quite long, please check it yourself
print()
list_of_strings = ['race', 'car|horse']
for item in permutations_with_ors(list_of_strings):
print(item)
# output:
# racecar
# racehorse
# carrace
# horserace
There is a solution with two stages:
generate permutations of
list_of_strings
recursively parse
or
operators
Have a look, seems to pass all your test cases, feel free to ask clarification in comments.
import itertools
def permutations_with_ors(list_of_strings):
for item in itertools.permutations(list_of_strings):
yield from parse_ors(item)
def parse_ors(tuple_of_strings):
for i, string in enumerate(tuple_of_strings):
if '|' in string:
for item in string.split('|'):
replaced = (
tuple_of_strings[:i] +
(item,) +
tuple_of_strings[i + 1:]
)
yield from parse_ors(replaced)
break
else:
yield ''.join(tuple_of_strings)
list_of_strings = ['a|b', 'c']
for item in permutations_with_ors(list_of_strings):
print(item)
# output:
# ac
# bc
# ca
# cb
print()
list_of_strings = ['a|b|d|e', 'c']
for item in permutations_with_ors(list_of_strings):
print(item)
# output:
# ac
# bc
# dc
# ec
# ca
# cb
# cd
# ce
print()
list_of_strings = ['a|b', 'c', 'd|e']
for item in permutations_with_ors(list_of_strings):
print(item)
# output is quite long, please check it yourself
print()
list_of_strings = ['race', 'car|horse']
for item in permutations_with_ors(list_of_strings):
print(item)
# output:
# racecar
# racehorse
# carrace
# horserace
edited Mar 23 at 21:57
answered Mar 23 at 19:46
SanyashSanyash
3,85451533
3,85451533
I just tested this real data and forgot to mention that the strings may be longer than one character. I have added an example case in the post.
– gxowrrqgc
Mar 23 at 21:51
Updated my answer, now it passes the test case you added.
– Sanyash
Mar 23 at 21:58
For anyone wondering, replace''.join
inelse: yield ''.join(tuple_of_strings)
with'A'.join
to have "A" separate the original entries
– gxowrrqgc
Mar 23 at 22:18
I'm also usingfor item in itertools.permutations(list_of_strings, n):
to create permutations of length n.
– gxowrrqgc
Mar 23 at 22:21
add a comment |
I just tested this real data and forgot to mention that the strings may be longer than one character. I have added an example case in the post.
– gxowrrqgc
Mar 23 at 21:51
Updated my answer, now it passes the test case you added.
– Sanyash
Mar 23 at 21:58
For anyone wondering, replace''.join
inelse: yield ''.join(tuple_of_strings)
with'A'.join
to have "A" separate the original entries
– gxowrrqgc
Mar 23 at 22:18
I'm also usingfor item in itertools.permutations(list_of_strings, n):
to create permutations of length n.
– gxowrrqgc
Mar 23 at 22:21
I just tested this real data and forgot to mention that the strings may be longer than one character. I have added an example case in the post.
– gxowrrqgc
Mar 23 at 21:51
I just tested this real data and forgot to mention that the strings may be longer than one character. I have added an example case in the post.
– gxowrrqgc
Mar 23 at 21:51
Updated my answer, now it passes the test case you added.
– Sanyash
Mar 23 at 21:58
Updated my answer, now it passes the test case you added.
– Sanyash
Mar 23 at 21:58
For anyone wondering, replace
''.join
in else: yield ''.join(tuple_of_strings)
with 'A'.join
to have "A" separate the original entries– gxowrrqgc
Mar 23 at 22:18
For anyone wondering, replace
''.join
in else: yield ''.join(tuple_of_strings)
with 'A'.join
to have "A" separate the original entries– gxowrrqgc
Mar 23 at 22:18
I'm also using
for item in itertools.permutations(list_of_strings, n):
to create permutations of length n.– gxowrrqgc
Mar 23 at 22:21
I'm also using
for item in itertools.permutations(list_of_strings, n):
to create permutations of length n.– gxowrrqgc
Mar 23 at 22:21
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55317483%2fitertools-permutation-with-or-operator%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
There was an answer that words, but gives duplicated results.
def perm(s, n=2): for p in itertools.product(*[k.split("|") for k in s]): yield from itertools.permutations(p, n)
. Withperm(['a|b', 'c', 'd|e'])
,['a', 'c']
is duplicated. In my case, I could generate the file with all permutations and usesort
anduniq
to remove duplicates.– gxowrrqgc
Mar 23 at 21:14
Would you mind try to use my answer and see if it suits your needs?
– Sanyash
Mar 23 at 21:21
@Sanyash Yes, your code is more efficient than creating the file and then sorting. I've added a comment to your post to fit my needs.
– gxowrrqgc
Mar 23 at 22:19