Generate Every Possibility

matrixdevuk 0 Tallied Votes 182 Views Share

I'm a beginner to Python and I decided to make a permutation finder program.
Have fun and don't question the name. :)

__author__ = 'matrixdevuk'

import itertools, sys, signal

if sys.version_info < (3,4,0):
	print("This program requires a minimum Python version of 3.4. Please consider upgrading.")
	sys.exit()

def signal_handler(signal, frame):
	print("")
	print("")
	print("Goodbye. :)")
	sys.exit()

signal.signal(signal.SIGINT, signal_handler)

def run(letters):
	i = 0
	for word in itertools.permutations(letters):
		i += 1
		word = "".join(word)
		print("[" + str(i) + "] Found: " + word)
	print()
	print("-----------------")
	print("Complete.")

print("   _               _")
print("  /_\  _ __  _ __ | | ___")
print(" //_\\\| '_ \| '_ \| |/ _ \\")
print("/  _  \ |_) | |_) | |  __/")
print("\_/ \_/ .__/| .__/|_|\___|")
print("      |_|   |_|")
print("a permutation finder by matrixdevuk")
print("do not question the name")
print()
uinput = input("Letters: ")
if uinput != "":
	run(uinput)
else:
	print("Error in validation; please restart.")
	sys.exit()
Gribouillis 1,391 Programming Explorer Team Colleague

You can avoid many calls to print() by printing multiline strings such as

banner = '''
  _____           ____             
 |  ___|__   ___ | __ )  __ _ _ __ 
 | |_ / _ \ / _ \|  _ \ / _` | '__|
 |  _| (_) | (_) | |_) | (_| | |   
 |_|  \___/ \___/|____/ \__,_|_|   

 a program by John Doe
 ---------------------
 '''.strip('\n')

print(banner)

Also I think it is better to catch KeyboardInterrupt than to define a signal handler for SIGINT. Python already catches the signal. You can do

def main():
    print(banner)
    uinput = input("Letters: ")
    if uinput != "":
        run(uinput)
    else:
        print("Error in validation; please restart.")

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('\n\nGoodbye. :)')

You could avoid the version check at the top of the program if it is not strictly necessary: people may have older versions of python, don't sys.exit() them immediately.

matrixdevuk 71 6t9.me Founder

@Gribouillis Thank you for the suggestions. Never knew about these. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.