Skip to content

Instantly share code, notes, and snippets.

@EldonMcGuinness
Created January 1, 2017 20:03
Show Gist options
  • Save EldonMcGuinness/7eac93c7b021a936e45a09183c9729cb to your computer and use it in GitHub Desktop.
Save EldonMcGuinness/7eac93c7b021a936e45a09183c9729cb to your computer and use it in GitHub Desktop.
A short script to generate permutations based on a rance of numbers.
#!/usr/bin/python2.7
import sys, getopt, itertools
def help():
print('test.py -r <range> -l <length> -o <outputfile> -c <count>')
def main(argv):
genRange = None
genLen = None
genCount = -1
outputfile = None
try:
opts, args = getopt.getopt(argv,'hr:l:o:c:',['range=','length=', 'output=', 'count='])
except getopt.GetoptError:
help()
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
help()
sys.exit()
elif opt in ("-r", "--range"):
genRange = int(arg)
elif opt in ("-l", "--length"):
genLen = int(arg)
elif opt in ("-o", "--output"):
outputfile = arg
elif opt in ("-c", "--count"):
genCount = int(arg)
try:
if not isinstance(genRange,int):
raise ValueError
if not isinstance(genLen,int):
raise ValueError
if not isinstance(genCount,int):
raise ValueError
if not isinstance(outputfile,str):
raise ValueError
loops = 0
with open(outputfile,'w') as f:
for x in itertools.permutations( range(genRange), genLen ):
if genCount < 0 or loops < genCount:
f.write('{}\r\n'.format(x))
loops += 1
else:
break
except ValueError:
help()
if __name__ == "__main__":
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment