mercredi 5 septembre 2018

My code for tracking processing timing for brute-forcing and using two versions of Euclid's Algorithm to calculate GCD is freezing up

The goal is to generate a pseudo-random list of 100 integer-pairs, then find the GCD of them using a brute-force method, and two versions of Euclid's Algorithm, timing each one and calculating statistics from said times, exporting said data to Excel. This is for a class, but the assignment was already turned in, in a C++ version, but I wanted to make a Python rendition and make it easily expandable for future programming assignments (they will all be various timings of algorithms and exported to Excel).

To that end, here is my current attempt at it:

#Imports
import random
import xlwt         #Must be installed via pip to run without full compile.
import timeit
import sys
import statistics   #Must be installed via pip to run without full compile.
#------------------

#Defines/Global
randomNumbers = []
times = []
#------------------

#-------------Excel Workbook Set-up--------------------
wb = xlwt.Workbook()
wb2 = xlwt.Workbook()
wb3 = xlwt.Workbook()
wb4 = xlwt.Workbook()
wb5 = xlwt.Workbook()
wb6 = xlwt.Workbook()
sheet1 = wb.add_sheet('sheet 1')
sheet2 = wb2.add_sheet('sheet 2')
sheet3 = wb3.add_sheet('sheet 3')
sheet4 = wb4.add_sheet('sheet 4')
sheet5 = wb5.add_sheet('sheet 5')
sheet6 = wb6.add_sheet('sheet 6')
#----------------------------------------------------


#Random Number Pairs Generator
def randomNumberPairs():
    randPairs = []
    for _ in range(100):
        x = random.randint(1, 998)
        n = random.randint(x, 999)
        randPairs.append(x)
        randPairs.append(n)
    return randPairs

#Brute Force
def bf(a,b):
    startTime = timeit.default_timer()
    for i in range(1, b + 1):
        if a % i == 0 and b % i == 0:
            gcd = i
    times.append(timeit.default_timer() - startTime)
    return gcd
#--------------------------------------------   

#"Original" Euclid
def euclid1(x,y):
    r = None
    startTime = timeit.default_timer()
    while 0 != r:
        #q = x%y
        r = x%y
        x = y
        y = r
    times.append(timeit.default_timer() - startTime)
    return x
#--------------------------------------------   

#"Enhanced" Euclid
def euclid2(x,y):
    r = None
    startTime = timeit.default_timer()
    while 0 != r:
        r = x-y
        if(r > y):
            r = r - y
            if(r > y):
                r = r - y
                if(r > y):
                    r = x%y
        x = y
        y = r
    times.append(timeit.default_timer() - startTime)
    return x
#--------------------------------------------   

#Main function for programming assignment 1.
def ProgAssign1(times):
    count = 0
    progAssign1WorkbookExtendedSetup()
    randomNumbers = randomNumberPairs()

    #Brute Force.
    while count < 100:
        sheet1.write(count+1,0,randomNumbers[(count*2)])
        sheet1.write(count+1,1,randomNumbers[(count*2)+1])
        sheet1.write(count+1, 2, bf(randomNumbers[(count*2)],randomNumbers[(count*2)+1]))
        sheet1.write(count+1, 3, times[count])
        count += 1
    sheet2.write(1,1,max(times))
    sheet2.write(2,2,min(times))
    sheet2.write(3,3,(sum(times) / float(len(times))))
    sheet2.write(4,4,statistics.median(times))
    #-------------------------------------------------------

    #Original Euclid's Algorithm main.
    count = 0
    del times[:]
    while count < 100:
        sheet3.write(count+1,0,randomNumbers[(count*2)])
        sheet3.write(count+1,1,randomNumbers[(count*2)+1])
        sheet3.write(count+1, 2, euclid1(randomNumbers[(count*2)],randomNumbers[(count*2)+1]))
        sheet3.write(count+1, 3, (times[count]))
        count += 1
    sheet4.write(1,1,max(times))
    sheet4.write(2,2,min(times))
    sheet4.write(3,3,(sum(times) / float(len(times))))
    sheet4.write(4,4,statistics.median(times))
    #-------------------------------------------------------

    #Enhanced Euclid's Algorithm
    count = 0
    del times[:]
    while count < 100:
        sheet5.write(count+1,0,randomNumbers[(count*2)])
        sheet5.write(count+1,1,randomNumbers[(count*2)+1])
        sheet5.write(count+1, 2, euclid2(randomNumbers[(count*2)],randomNumbers[(count*2)+1]))
        sheet5.write(count+1, 3, times[count])
        count += 1
    sheet6.write(1,1,max(times))
    sheet6.write(2,2,min(times))
    sheet6.write(3,3,(sum(times) / float(len(times))))
    sheet6.write(4,4,statistics.median(times))
    #-------------------------------------------------------    


while True:
    print("Please choose a programming assignment.")
    choice = input("1 for Programming Assignment 1. 0 to Exit.")
    if choice == 1:
        ProgAssign1(times)
        wb.save('Brute_Force_Results.xls')
        wb2.save('Brute_Force_Statistics.xls')
        wb3.save("Original_Euclid_Results.xls")
        wb4.save("Original_Euclid_Statistics.xls")
        wb5.save("Second_Euclid_Results.xls")
        wb6.save("Second_Euclid_Statistics.xls")
        input("Data written to .xls files. Press Enter to continue.")
    elif choice == 0:
        sys.exit("Good bye.")

I fixed any errors that cropped up while debugging, but I've hit an error-less wall, as it sits processing for seemingly forever like shown here. Its still using about 15% of my cpu (but memory usage is not moving), so something is happening, and I'm sure I've messed it up in some way, so I'm looking for some advice.

Side: I cut the excel formatting stuff, because I doubt that is where the issue lies, but here it is in case its relevant:

#Excel Column and Row Titles
def progAssign1WorkbookExtendedSetup():
    sheet1.write(0,0,"Number One")
    sheet1.write(0,1,"Number Two")
    sheet1.write(0,2,"Their GCD")
    sheet1.write(0,3,"Time (Milliseconds)")

    sheet2.write(0,0,"Statistics")
    sheet2.write(0,1,"Milliseconds")
    sheet2.write(1,0,"Max Time")
    sheet2.write(2,0,"Min Time")
    sheet2.write(3,0,"Avg Time")
    sheet2.write(4,0,"Median Time")
    #------------------------------
    sheet3.write(0,0,"Number One")
    sheet3.write(0,1,"Number Two")
    sheet3.write(0,2,"Their GCD")
    sheet3.write(0,3,"Time (Milliseconds)")

    sheet4.write(0,0,"Statistics")
    sheet4.write(0,1,"Milliseconds")
    sheet4.write(1,0,"Max Time")
    sheet4.write(2,0,"Min Time")
    sheet4.write(3,0,"Avg Time")
    sheet4.write(4,0,"Median Time")
    #------------------------------
    sheet5.write(0,0,"Number One")
    sheet5.write(0,1,"Number Two")
    sheet5.write(0,2,"Their GCD")
    sheet5.write(0,3,"Time (Milliseconds)")

    sheet6.write(0,0,"Statistics")
    sheet6.write(0,1,"Milliseconds")
    sheet6.write(1,0,"Max Time")
    sheet6.write(2,0,"Min Time")
    sheet6.write(3,0,"Avg Time")
    sheet6.write(4,0,"Median Time")
    return
#--------------------------------------------------------

If you see a lot of unrelated improvements I can make, feel free to throw those my way, too. I'm looking to improve! Thanks a bunch!




Aucun commentaire:

Enregistrer un commentaire