Friday, May 13, 2016

Python itertools efficient looping tools

I created a python program to solve the Goldbach conjecture.  This is nothing more than get a number from the user, checks to make sure that it is even, and then finds two prime numbers that sum to the number.  To my surprise it was a bit tricky and I had to rewrite my program a few times before it started to make sense.

One tool that was extremely powerful was the itertools  I was able to use the itertools.permutations function that will perform the following arrangement for me to map out all possible cases.
Here is an example:
list(itertools.permutations([1,2,3,4], 2))
[(1, 2), (1, 3), (1, 4),
(2, 1), (2, 3), (2, 4),
(3, 1), (3, 2), (3, 4),
(4, 1), (4, 2), (4, 3)]
Credit To: how to generate all permutations of a list in python & Python Itertools
I listed my programs below if anyone was looking for an example.
Here is my chap8_5_prog_exercise.py:
import sys
import math
import time


def calcPrime(number):
    nSqrt = math.sqrt(number)
    n = number / nSqrt
    
    return n, number%n==0


def main():
    num = eval(input("Enter a number:"))
    n = 0
    nSqrt = 0
    if num < 2:
        sys.exit(0)
    
    n, status = calcPrime(num)
    print(status)
    
    if status == True:
        print("Number:",n, "is prime")
    else:
        while status != True:
            n, status = calcPrime(num)
            print(n, "and", status, "Index", num,)
            num += 1
            time.sleep(.1)
        print("Number:",num-1, "is prime")

if __name__ == "__main__":
    main()

Here is my chap8_6_prog_exercise.py:
import sys
import time
import itertools
from chap8_5_prog_exercise import calcPrime

def modcheckSumOfTwoNumbers(bList,inputNum, index):
     
    try:
        for x in bList:
            #print("X", x, "x[0]+x[1]", x[0]+x[1], "inputNum", inputNum)
            if int(x[0])+int(x[1])==inputNum:
                return x, True
            index += 1
    except IndexError:
        gotdata = 'null'
    
    return [0,0], False
        
    

def main():
    inputnum = eval(input("Enter a number:"))
    num = inputnum
    status = False
    SumOfTwoNumbersStatus = False
    aList = list()
    bList = list(tuple())
    cList = list()
    
    if inputnum%2 != 0 :
        print("Number is not even")
        sys.exit(0)
    
    aList.append(1)
    
    if inputnum == 2:
        cList.append(1)
        cList.append(1)
    else:
        indexInner = 0
        while not SumOfTwoNumbersStatus:
            num += 1
            n, status = calcPrime(num)
            if status == True:
                bList = list(itertools.permutations(aList, 2))
                aList.append(n)
                cList, SumOfTwoNumbersStatus = (modcheckSumOfTwoNumbers(bList,inputnum, 0))
                indexInner += 1
            time.sleep(.25)
    
    print("The sum of the two primes that equal the number submitted: "+"{0:0}".format(inputnum)+" are: "+"{0:0}".format(int(cList[0]))+"+"+"{0:0}".format(int(cList[1])))

if __name__ == "__main__":
    main()

Tuesday, May 3, 2016

What is the purpose of __name__ and __main__ in Python

There are several different ways of running Python programs. Some Python module files are designed to be run directly. These are usually referred to as “programs” or “scripts.” Other Python modules are designed primarily to be imported and used by other programs; these are often called “libraries.” Sometimes we want to create a sort of hybrid module that can be used both as a stand-alone program and as a library that can be imported by other programs.

So far, most of our programs have had a line at the bottom to invoke the main function.
main()

As you know, this is what actually starts a program running. These programs are suitable for
running directly. In a windowing environment, you might run a file by (double-)clicking its icon.
Or you might type a command like python <myfile>.py.

Since Python evaluates the lines of a module during the import process, our current programs
also run when they are imported into either an interactive Python session or into another Python
program. Generally, it is nicer not to have modules run as they are imported. When testing a
program interactively, the usual approach is to first import the module and then call its main (or
some other function) each time we want to run it.

In a program designed to be either imported (without running) or run directly, the call to main
at the bottom must be made conditional. A simple decision should do the trick.

if <condition>:
main()

We just need to figure out a suitable condition.
Whenever a module is imported, Python sets a special variable in the module called __name__
to be the name of the imported module. Here is an example interaction showing what happens
with the math library:

>>> import math
>>> math.__name__
’math’

You can see that, when imported, the __name__ variable inside the math module is assigned the
string ’math’.
However, when Python code is being run directly (not imported), Python sets the value of
__name__ to be ’__main__’. To see this in action, you just need to start a Python shell and look at
the value.

>>> __name__
’__main__’

So, if a module is imported, the code in that module will see a variable called __name__ whose
value is the name of the module. When a file is run directly, the code will see that __name__ has
the value ’__main__’. A module can determine how it is being used by inspecting this variable.
Putting the pieces together, we can change the final lines of our programs to look like this:

if __name__ == ’__main__’:
main()

This guarantees that main will automatically run when the program is invoked directly, but it will
not run if the




This excerpt was taken from section 7.1.3 Example: Conditional Program Execution, Python Porgramming - An Intro to Computer Science  2nd edition - John Zelle.