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;








2















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









share|improve this question
























  • 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











  • @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

















2















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









share|improve this question
























  • 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











  • @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













2












2








2


0






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









share|improve this question
















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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). 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











  • @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












  • 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












2 Answers
2






active

oldest

votes


















3














There are just a few steps.



  1. Split each of your original strings on | to get lists of strings.

  2. Compute the permutations of your list of lists of strings.

  3. Compute the product of each permutation

  4. 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)]





share|improve this answer

























  • 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 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


















1














There is a solution with two stages:



  1. generate permutations of list_of_strings


  2. 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





share|improve this answer

























  • 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 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











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
);



);













draft saved

draft discarded


















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









3














There are just a few steps.



  1. Split each of your original strings on | to get lists of strings.

  2. Compute the permutations of your list of lists of strings.

  3. Compute the product of each permutation

  4. 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)]





share|improve this answer

























  • 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 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















3














There are just a few steps.



  1. Split each of your original strings on | to get lists of strings.

  2. Compute the permutations of your list of lists of strings.

  3. Compute the product of each permutation

  4. 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)]





share|improve this answer

























  • 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 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













3












3








3







There are just a few steps.



  1. Split each of your original strings on | to get lists of strings.

  2. Compute the permutations of your list of lists of strings.

  3. Compute the product of each permutation

  4. 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)]





share|improve this answer















There are just a few steps.



  1. Split each of your original strings on | to get lists of strings.

  2. Compute the permutations of your list of lists of strings.

  3. Compute the product of each permutation

  4. 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)]






share|improve this answer














share|improve this answer



share|improve this answer








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 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

















  • 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 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
















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













1














There is a solution with two stages:



  1. generate permutations of list_of_strings


  2. 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





share|improve this answer

























  • 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 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















1














There is a solution with two stages:



  1. generate permutations of list_of_strings


  2. 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





share|improve this answer

























  • 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 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













1












1








1







There is a solution with two stages:



  1. generate permutations of list_of_strings


  2. 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





share|improve this answer















There is a solution with two stages:



  1. generate permutations of list_of_strings


  2. 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






share|improve this answer














share|improve this answer



share|improve this answer








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 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 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 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 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

















draft saved

draft discarded
















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현