0

For example if I have the word 'House', is there a way to get every possible version of it and set it to an array.

How it would look

word = 'House'

Function does something and the out put would look something like:

word = ['HOUSE', 'House, house', 'hoUse']


1 Answers1

0

You can use binary combinations 01110, 00011 etc. with itertools.product() to get every combination of cases with a string. This means setting the 1's as uppercase and the 0's as lowercase. So 01110 -> hOUSe, 00011 -> houSE etc.

from itertools import product

def get_all_cases(string):
    return [
        "".join(
            letter.upper() if binary == 1 else letter
            for letter, binary in zip(string.lower(), binary_comb)
        )
        for binary_comb in product([0, 1], repeat=len(string))
    ]

Output:

>>> get_all_cases("House")
>>> ['house', 'housE', 'houSe', 'houSE', 'hoUse', 'hoUsE', 'hoUSe', 'hoUSE', 'hOuse', 'hOusE', 'hOuSe', 'hOuSE', 'hOUse', 'hOUsE', 'hOUSe', 'hOUSE', 'House', 'HousE', 'HouSe', 'HouSE', 'HoUse', 'HoUsE', 'HoUSe', 'HoUSE', 'HOuse', 'HOusE', 'HOuSe', 'HOuSE', 'HOUse', 'HOUsE', 'HOUSe', 'HOUSE']

You can also just map to True and False boolean values instead of 1 and 0.

from itertools import product

def get_all_cases(string):
    return [
        "".join(
            letter.upper() if is_upper else letter
            for letter, is_upper in zip(string.lower(), comb)
        )
        for comb in product([False, True], repeat=len(string))
    ]
RoadRunner
  • 25,803
  • 6
  • 42
  • 75