# Create all possible character combinations of any size

I am trying to create all possible character combinations of a given word. For example, “laptop” will include the following possible combinations:

l
la
lap
lapt
lapto
laptop
lp
lpa
lpat
lpato
lpatop


Here is what I have tried:

#!/usr/bin/env python
import argparse
import sys

def parse_args(argv):
"""parsing argument"""
parser = argparse.ArgumentParser()
required = True,
args = parser.parse_args(argv)
return args

def get_patt(patt, patt_index, new_pat):
print new_pat
for i in range(patt_index, len(patt), 1):
new_pat = new_pat + patt[i]
print new_pat
def main(args):
f_pat = ""
input = args.input
for k in range(0, len(input), 1):
for i in range(0, len(input), 1):
f_pat =  input[i]
for j in range(i+1, len(input), 1):
f_pat = f_pat + input[j]
get_patt(input, j+1, f_pat)
input = args.input[k:] + args.input[:k]
print "Input String", input

if __name__ == "__main__":
args =parse_args(sys.argv[1:])
main(args)

• What's with the random print "Input String", input that is interleaving with the actual output ? – Mathias Ettinger Oct 17 '17 at 10:10
• I am trying to rotate string but it is not working with all combination – user765443 Oct 17 '17 at 10:13

# Improvements

1. Use either argparse or sys.argv because this feels just wierd, and kind of surprised it worked at all. I'd recommend sticking with argparse
2. Secondly, be sure to check out the itertools module from python, because what you are looking for are basicly permutations of a word.

# New code

import argparse
from itertools import permutations

def main(string):
for idx in range(1, len(string)+1):
print(list(''.join(p) for p in permutations(string, idx)))

def parse_args():
"""parsing argument"""
parser = argparse.ArgumentParser()
required = True,
return parser.parse_args()

if __name__ == "__main__":
args = parse_args()
main(args.input)

• The parameters should not be passed with spaces around =. For eg. required = True should instead be required=True :) – hjpotter92 Oct 17 '17 at 17:46
• True, but OP should rather look at the parse_args from Mathias :) – Ludisposed Oct 17 '17 at 17:56

Your arguments parsing is a bit off.

If you remove the - in front of the name of the argument, argparse will consider it a required parameter and not an optional one, so you won't have to specify required=True.

Besides, removing it will make the help look cleaner as regard to the fact that the parameter is required:

\$ python2 combinations.py -h
usage: combinations.py [-h] input

positional arguments:

optional arguments:
-h, --help  show this help message and exit


You could also return the word from your parse_args function so the main is agnostic of how you provide your input.

Lastly, a parser's parse_args method, if called without arguments, will automatically take sys.argv[1:] as the reference. So you don't need to specify it yourself:

def parse_args():
"""parsing argument"""
parser = argparse.ArgumentParser()