Skip to content

Instantly share code, notes, and snippets.

@jhallard
Last active November 18, 2019 22:21
Show Gist options
  • Save jhallard/cb439a59b652e709972a52f2565a0569 to your computer and use it in GitHub Desktop.
Save jhallard/cb439a59b652e709972a52f2565a0569 to your computer and use it in GitHub Desktop.
bUsINeSS JoHN - take a string and print all combinations of upper/lower case letters in the string to stdout
#!/usr/bin/env python
"""
This is a dumb script and isn't too well written. The entire point is to take a string
like "business john" and print all combinations of upper/lower case letters for all
alpha characters in the string, e.g.
bUsiNEsS joHn
BuSInEsS JoHn
...
call like
$ python business_john.py "some string" --shuffle
"""
import sys
import random
import os
import argparse
def format_according_to_bin(s, b):
"'abc' & '010' = 'aBc'"
ret = ''
for ch, n in zip(s, b):
ret += ch.upper() if int(n) == 1 else ch.lower()
return ret
def de_only_alpha(only_alpha, non_alpha):
ret = ''
alpha_idx = 0
for i in range(len(only_alpha)+len(non_alpha)):
if i in non_alpha:
ret += non_alpha[i]
else:
ret += only_alpha[alpha_idx]
alpha_idx += 1
return ret
def show_combinations(s, shuffle=False, per_row=1):
combos = list()
non_alpha = dict()
only_alpha = ''.join(filter(lambda c: c.isalpha(), s))
for index, c in enumerate(s):
if not c.isalpha():
non_alpha[index] = c
n_combos = 2**len(only_alpha)
for i in range(n_combos):
b = format(i, '0%db' % len(only_alpha))
mod_alpha = format_according_to_bin(only_alpha, b)
final_format = de_only_alpha(mod_alpha, non_alpha)
combos.append(final_format)
if shuffle:
random.shuffle(combos)
for i in range(len(combos[0:-1:per_row])):
out = ""
for a in range(i, i+per_row):
out += combos[a]
out += "\t"
sys.stdout.write(out + '\n')
def parse_args():
a = argparse.ArgumentParser()
a.add_argument('iterable', type=str, help="the string to iterate over the combinations of upper/lower case letters")
a.add_argument('--shuffle', action='store_true', help="if set, shuffle the outputs to random orderings")
a.add_argument('--per-row', type=int, default=1, help="the number of items to print per row")
return a.parse_args()
def main():
args = parse_args()
show_combinations(args.iterable, args.shuffle, args.per_row)
return True
if __name__ == '__main__':
sys.exit(not main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment