Ad
Python How To Generate Permutations Of Putting A Singular Character Into A Word
No idea how to word this so the title sucks my bad,
Basically, I have a 4 letter word and I want to generate every permutation of putting a dash in it.
So if my word was Cats, I want to get every permutation of it having a dash in it,
Example:
c-ats
ca-ts
-c-ats
etc,
Is anybody able to help me?
Ad
Answer
I assume that you want to generate all possible ways to insert zero or more hyphens into your word s.t. no two hyphens are adjacent. Here is one way to do this with itertools.product
:
from itertools import product
def hyphens(word):
# create template, each {} is to be filled with "" or "-"
template = "{}" + "{}".join(word) + "{}"
# iterate over all possible ways to fill empty braces
for chars in product(["", "-"], repeat=len(word) + 1):
yield template.format(*chars)
list(hyphens('cats'))
# ['cats', 'cats-', 'cat-s', 'cat-s-', 'ca-ts', 'ca-ts-', 'ca-t-s', 'ca-t-s-',
# 'c-ats', 'c-ats-', 'c-at-s', 'c-at-s-', 'c-a-ts', 'c-a-ts-', 'c-a-t-s',
# 'c-a-t-s-', '-cats', '-cats-', '-cat-s', '-cat-s-', '-ca-ts', '-ca-ts-',
# '-ca-t-s', '-ca-t-s-', '-c-ats', '-c-ats-', '-c-at-s', '-c-at-s-', '-c-a-ts',
# '-c-a-ts-', '-c-a-t-s', '-c-a-t-s-']
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad