What i am trying to do is to prompt the user for an sort function type, sort patter, array size, size of array increment and number of test. Then i want it to save it. However, there are couple problems with this program.
-
Somehow when i choose the random pattern it gives me some weird answer like:
1543 0.002
600 0.020
1400 0.08
Its not really in an order. I think that something wrong is with the for loop.
def rand_array(n):
''' returns sorted array of integers of size n'''
R=[randint(1, 1000*n) for i in xrange(n)]
return R
def sorted_array(n):
''' returns a sorted array of n integers'''
return [i for i in xrange(1,n+1)]
def rev_array(n):
'''returns an array of n integers in reverse order'''
R= [i for i in reversed(xrange(1,n+1))]
return R
def sort_timehelp(x,f):
''' This times the quick sort algorithm as it must take 3 variables'''
high=len(x)
low=0
t0=clock()
f(x,low,high)
t1=clock()
dt=t1-t0
return dt
def main():
myinfo()
info()
while True:
print '==================== to quit enter Control-c=================='
sortfunction=input("Choose a sort function: ")
s=input("Choose a pattern: ")
n=input("Array Size: ")
increment=input("Increment size: ")
y=input("Number of tests: ")
if s == 1:
x=rand_array(n)
elif s ==2:
x= sorted_array(n)
elif s==3:
x=rev_array(n)
if sortfunction==1:
i=0
output="algorith: quick sort \n input data: %s" %s
print output
while i<y:
i=i+1
ff=0.0
array=x[increment-1:n:increment]
for my in array:
ff+=sort_timehelp(x,quick_sort)
output="%d\t %f" %(my, ff)
print output
saving=input("You want to save data ? type 0 to continue or 1 to save " )
if saving == 0:
continue
if saving == 1:
ask=raw_input("Type the name file: ")
fileout=open(ask+".csv","w")
fileout.write(output)
fileout.close()
Second problem is that when i am trying to save the data it only saves the last data, but i want to save everything.
I would appreciate any help.
Edit:
timing function takes and array and a sorting algorithm
i want to save the numbers by increments and corresponding timing to it. (thats where my for loop)
There are a lot of issues. Let’s go through them…
This doesn’t return a sorted array of random numbers. It returns a list of random integers chosen from successively larger domains. You probably want:
This should simply be:
is simply:
So you’re sorting as many times (in the inner loop) as you have array elements? Not sure why. Anyway, the business with
ishould simply be done with aforloop:The
if saving==0clause can be removed; any value ofsavingother than1will skip saving.As Scott pointed out, you want
"a"instead of"w"inopen. Another thing you could do is move theopenandcloseout of the loop. You might also want to use the built-in Pythoncsvmodule.