Created
January 31, 2025 15:33
-
-
Save anthonykasza/b99d23695cbd8b4457a8bbf7bb20061c to your computer and use it in GitHub Desktop.
generate capitalization variants
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://stackoverflow.com/questions/905317/permutations-of-capitalization | |
# chatgpt solved it right away using python's built-ins. i need to brush up on my itertools. | |
import itertools | |
def generate_case_combinations(input_string): | |
# Create a list of lists with each character's possible case | |
case_options = [[char.lower(), char.upper()] if char.isalpha() else [char] for char in input_string] | |
# Use itertools.product to generate the Cartesian product of all the case variations | |
all_combinations = itertools.product(*case_options) | |
# Join each tuple of characters into a string and return the result as a list | |
return [''.join(combination) for combination in all_combinations] | |
print(generate_case_combinations("foo")) | |
# my first idea: recursion. but recurision is dumb. | |
import copy | |
def doit(input, output=[]): | |
if len(input) == 0: | |
return output | |
for idx in range(len(input)): | |
new_input = input[idx+1:] | |
up = input[idx].upper() | |
down = input[idx].lower() | |
if len(output) == 0: | |
new_output = [up, down] | |
else: | |
new_output = copy.deepcopy(output) | |
for idx in range(len(output)): | |
new_output.append(output[idx] + up) | |
new_output.append(output[idx] + down) | |
return doit(new_input, new_output) | |
print(doit("foo")) | |
# my second idea: binary mask. more superior. | |
def segundoit(input_string): | |
''' foo, foO, fOo, fOO, Foo, FoO, FOo, FOO | |
000, 001, 010, 011, 100, 101, 110, 111 | |
''' | |
n = len(input_string) | |
output = [] | |
for i in range(2 ** n): | |
tmp = '' | |
for j in range(n): | |
if i & (1 << j): # i still had to use a GTP for this | |
tmp = tmp + input_string[j].upper() | |
else: | |
tmp = tmp + input_string[j].lower() | |
output.append(tmp) | |
return output | |
print(segundoit("foo")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment