Upper or lower case for each letter
List every string you can make from a text by switching each letter to upper or lower case, with digits left alone, by deciding one position at a time. About 12 minutes.
Branch only at letters
Think of the text as a row of positions. At a position holding a digit there is nothing to decide, so just move on to the next position. At a position holding a letter there are two choices: lower case or upper case.
Make one choice, finish all the positions after it, then make the other choice and finish the positions after that again.
if ch.isalpha():
print(ch.lower(), ch.upper())Position 0 is a letter: try b, then B.
One working copy
Keep the text as a list of characters that you overwrite in place. Setting position i to lower case or to upper case replaces whatever was there, so no explicit undo is needed: the second choice simply overwrites the first.
When you pass the last position, join the characters into a string and save it. The results come out in order: all those with the first letter in lower case first, then those with it in upper case.
cur = list(s) cur[0] = cur[0].upper()
A text has 3 letters and 2 digits. How many variants are there?
- A8
- B10
- C32
Show the answer
8. Each letter doubles the count and digits do not.
Letter case permutation
Given a string s made of letters and digits, return all the strings that can be made by changing each letter to lower case or upper case, leaving digits as they are. List them in the order produced by deciding the positions from left to right, trying the lower case form of a letter before the upper case form.
s = "a1b" → ["a1b", "a1B", "A1b", "A1B"]
1 ≤ length of s ≤ 12 · s has letters and digits · at most 10 letters