1

I want to write a program that would take a string, let's say "abc", then it would display:

abc, Abc, ABc, ABC, AbC, aBc, aBC, AbC

After digging for a while I found this question which solves my problem however, if the string contains some special chars such as @ and . , it will give me some duplicates in the output , how can I make it so only alphabetic characters are upper/lower? for example if the input is a@c the output should only be:

A@c
a@C
A@C
a@c

Here is the code I am using:

import itertools

string = 'abc12@abc.com'
x = map(''.join, itertools.product(*((c.upper(), c.lower()) for c in string)))
print(x)
iacob
  • 20,084
  • 6
  • 92
  • 119
user00239123
  • 270
  • 4
  • 16

2 Answers2

3

@Caius's answer works, but it's more efficient to remove the duplicate characters up front instead of waiting until you have all the results and then removing the duplicates there.

The difference in my code is just set((c.upper(), c.lower())) instead of just (c.upper(), c.lower()):

import itertools
string = 'abc12@abc.com'
x = map(''.join, itertools.product(*(set((c.upper(), c.lower())) for c in string)))
assert len(list(x)) == 512
user94559
  • 59,196
  • 6
  • 103
  • 103
0

Try converting the array into a set:

x = set(map(''.join, itertools.product(*((c.upper(), c.lower()) for c in string))))
Caius
  • 243
  • 1
  • 5