# Multiple random lists given user input

• (2 Pages)
• 1
• 2

## 16 Replies - 2967 Views - Last Post: 29 April 2012 - 12:09 PMRate Topic: 1 Votes //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=277280&amp;s=00c8700867b3453b9108596a6d4a627c&md5check=' + ipb.vars['secure_hash'], cur_rating: 5, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 thatOnekid

Reputation: 1
• Posts: 9
• Joined: 28-April 12

# Multiple random lists given user input

Posted 28 April 2012 - 07:00 PM

Hey all, was playing with Python and came across some problems. I wanted to prompt the user for the minimum array size, size of array increment, and number of test arrays. The arrays will be used to generate sort time data for arrays of different sizes. Then use a random number generator to create an array of the desired size etc. and then sort the array using
the desired algorithm and time the sort. But the problem was how do I create multiple lists in one go? I wrote up some code that creates a random list based on some user info given.
```def whichFunction():
loop = 1
choice = 0
while loop == 1:
print "Welcome to the cool sorting function!"
user_choice = input("Which sorting function would you like to use? Type 1-3.\n
1. BubbleSort\n 2. QuickSort\n 3. Isort\n ")

sortingType = input("Which type of data pattern would you like? Type 1-3\n
1.Random\n 2.sorted\n 3.reverse sorted\n")

n = input("What is the minimum array size?")
x = input("what is the size of array increments?")
y = input("What is the number of test arrays?")

# a = [[] for i in range(y)]

a = [random.randint(0,x) for r in xrange(n)]
print a

```

```[1, 0, 2, 0, 2, 2, 2, 2, 2, 1]
```

for n = 10, x=2, y=2

Now the MAIN question is, how do i create "y" number of lists that can be implemented into my while loop, that will be sorted into my bubble sort, quick sort, or insertion sort based on my user preference. Thanks, I can post my sorting functions if needed, though they are pretty standard.

Is This A Good Question/Topic? 1

## Replies To: Multiple random lists given user input

### #2 atraub

• Pythoneer

Reputation: 828
• Posts: 2,235
• Joined: 23-December 08

## Re: Multiple random lists given user input

Posted 28 April 2012 - 07:21 PM

```import random
def whichFunction():
choice = 0
while True:
print "Welcome to the cool sorting function!"
user_choice = input("Which sorting function would you like to use? Type 1-3.\n 1. BubbleSort\n 2. QuickSort\n 3. Isort\n ")

sortingType = input("Which type of data pattern would you like? Type 1-3\n 1.Random\n 2.sorted\n 3.reverse sorted\n")

n = input("What is the minimum array size?")
x = input("what is the size of array increments?")
y = input("What is the number of test arrays?")

a= []
for i in range(y):
a.append([random.randint(0,x) for r in xrange(n)])
print a

```

EDIT:
if you REALLY want to do a 1 liner, you could use
```import random
def whichFunction():
choice = 0
while True:
print "Welcome to the cool sorting function!"
user_choice = input("Which sorting function would you like to use? Type 1-3.\n 1. BubbleSort\n 2. QuickSort\n 3. Isort\n ")

sortingType = input("Which type of data pattern would you like? Type 1-3\n 1.Random\n 2.sorted\n 3.reverse sorted\n")

n = input("What is the minimum array size?")
x = input("what is the size of array increments?")
y = input("What is the number of test arrays?")

a = [([random.randint(0,x) for r in xrange(n)]) for i in range(y)]
print a

```

but that looks ugly and is hard to read, which is exactly what you don't want to do in python

Edit 2:
Also, might I suggest better variable names? n, x, y, a are not very descriptive.

This post has been edited by atraub: 28 April 2012 - 07:29 PM
Reason for edit:: for completeness

### #3 thatOnekid

Reputation: 1
• Posts: 9
• Joined: 28-April 12

## Re: Multiple random lists given user input

Posted 28 April 2012 - 07:34 PM

...Wow, thank you so much! Not sure why I couldn't think of it. Mind helping me with sorting functions...getting some errors when i try to run them. And any idea whats a good way to run the timing function? Below is my entire python program.
```import numpy
import random
import sys
from time import clock

def whichFunction():
loop = 1
choice = 0
while loop == 1:
print "Welcome to the cool sorting function!"
user_choice = input("Which sorting function would you like to use? Type 1-3.\n 1. BubbleSort\n 2. QuickSort\n 3. Isort\n ")

sortingType = input("Which type of data pattern would you like? Type 1-3\n 1.Random\n 2.sorted\n 3.reverse sorted\n")
n = input("What is the minimum array size?")
x = input("what is the size of array increments?")
y = input("What is the number of test arrays?")

a= []
for i in range(y):
a.append([random.randint(0,x) for r in xrange(n)])
print a
if user_choice == 1:
""" bubble sort """

#takes in a,n
for m in reversed(xrange(0,n+1)):
for i in xrange(0,m-1):
if a[i] > a[i+1]:
t = a[i]# inlineswap
a[i] = a[i+1]
a[i+1] = t

if sortingType == 1:
a = random.shuffle(t)
print a
return a
if sortingType == 2:
print sorted(a)
return a
if sortingType == 3:
a = sorted(a, cmp=reverse_numeric)
print a
return a
if user_choice == 2:
""" quick sort """
if a == []:
return []
else:
pivot = a[0]
lesser = qsort1([x for x in a[1:] if x < pivot])
greater = qsort1([x for x in a[1:] if x >= pivot])
a = lesser + [pivot] + greater
if sortingType == 1:
print random.shuffle(a)
return a
if sortingType == 2:
print sorted(a)
return a
if sortingType == 3:
a = sorted(a, cmp=reverse_numeric)
print a
return a
if user_choice == 3:
""" Isort """
# takes a and n
for i in xrange(1,n):
j = 1
while j>0 and a[j-1]>a[j]:
a[j-1],a[j] =a[j],a[j-1]
j -=1
if sortingType == 1:
print random.shuffle(a)
return a
if sortingType == 2:
print sorted(a)
return a
if sortingType == 3:
a = sorted(a, cmp=reverse_numeric)
print a
return a

def reverse_numeric(x, y):
return y - x

```

### #4 atraub

• Pythoneer

Reputation: 828
• Posts: 2,235
• Joined: 23-December 08

## Re: Multiple random lists given user input

Posted 28 April 2012 - 07:41 PM

Getting times is easy in python
```import time

startTime = time.time()

elapsedTime = time.time() - startTime
```

As for your errors, could you be more specific? If you don't mind, copy and paste the exact error message, in code tags preferably.

Also, welcome to Dream In Code! The best way to thank someone here is to click on the + sign at the bottom of their post

### #5 thatOnekid

Reputation: 1
• Posts: 9
• Joined: 28-April 12

## Re: Multiple random lists given user input

Posted 28 April 2012 - 07:44 PM

Yeah, I chose variables to go smoothly into sorting functions, though I guess I could leave some doc strings.

I tried running my program, and it went something like this.

```
Which sorting function would you like to use? Type 1-3.
1. BubbleSort
2. QuickSort
3. Isort
1
Which type of data pattern would you like? Type 1-3
1.Random
2.sorted
3.reverse sorted
1
What is the minimum array size?10
what is the size of array increments?10
What is the number of test arrays?2
[[0, 0, 3, 7, 8, 1, 5, 10, 9, 0], [7, 3, 8, 10, 7, 2, 7, 7, 3, 9]]
Traceback (most recent call last):
File "main.py", line 96, in <module>
main()
File "main.py", line 95, in main
whichFunction()
File "main.py", line 31, in whichFunction
if a[i] > a[i+1]:
IndexError: list index out of range
>>>

```

This post has been edited by atraub: 28 April 2012 - 08:17 PM
Reason for edit:: no need to quote the entire post

### #6 atraub

• Pythoneer

Reputation: 828
• Posts: 2,235
• Joined: 23-December 08

## Re: Multiple random lists given user input

Posted 28 April 2012 - 07:53 PM

here's your first problem, you're putting a into the bubble sort, but a holds 2 lists. you want to use the lists inside of a.

Also, let's break those sorting algorithms into functions. Here's an example for bubbleSort:

```def bubbleSort(numberList):
for m in reversed(xrange(0,len(numberList)+1)):
for i in xrange(0,m-1):
if numberList[i] > numberList[i+1]:
t = numberList[i]# inlineswap
numberList[i] = numberList[i+1]
numberList[i+1] = t

```

here's a more pythonic version of bubble sort
```def bubbleSort(numberList):
for m in reversed(xrange(0,len(numberList)+1)):
for i in xrange(0,m-1):
if numberList[i] > numberList[i+1]:
numberList[i],numberList[i+1]=numberList[i+1],numberList[i]

```

Here's an example using the interpreter:
```>>> a = [[1,8,3,7,2],[2,6,3,8,9]]
>>> for eachList in a:
bubbleSort(eachList)

>>> a
[[1, 2, 3, 7, 8], [2, 3, 6, 8, 9]]
>>>

```

EDIT:
Oh, for fun, let's not forget timing

```>>> a = [[1,8,3,7,2],[2,6,3,8,9]]
>>> times = []
>>> for eachList in a:
startTime = time.time()
bubbleSort(eachList)
times.append(time.time() - startTime)

>>> a
[[1, 2, 3, 7, 8], [2, 3, 6, 8, 9]]
>>> times
[0.0, 0.0]
>>>

```

What happened? The code executed so fast that the time measurement didn't pick anything up, for a much bigger set, that would't happen

Edit 2 - better example:
```>>> a = []
>>> for i in range(4):
a.append([random.randint(1,1000) for i in range(1500)])

>>> times = []
>>> for eachList in a:
start = time.time()
bubbleSort(eachList)
times.append(time.time() - start)

>>> times
[0.31100010871887207, 0.31599998474121094, 0.31299996376037598, 0.3059999942779541]

```

This post has been edited by atraub: 28 April 2012 - 08:06 PM

### #7 thatOnekid

Reputation: 1
• Posts: 9
• Joined: 28-April 12

## Re: Multiple random lists given user input

Posted 28 April 2012 - 08:12 PM

Genius! slowly trying to fix my code, and fix minor bugs but your help is invaluable! thanks so much. Duly noted on the +1 on comments.

This post has been edited by atraub: 28 April 2012 - 08:14 PM
Reason for edit:: no need to quote me

### #8 atraub

• Pythoneer

Reputation: 828
• Posts: 2,235
• Joined: 23-December 08

## Re: Multiple random lists given user input

Posted 28 April 2012 - 08:15 PM

Glad it helped boss! Feel free to post again if you hit anymore snags.

### #9 thatOnekid

Reputation: 1
• Posts: 9
• Joined: 28-April 12

## Re: Multiple random lists given user input

Posted 28 April 2012 - 10:03 PM

Dang, I almost got my program done, just got stuck on quicksort.
```What is the minimum array size?10
what is the size of array increments?100
What is the number of test arrays?2
a: [[65, 83, 25, 51, 78, 10, 81, 99, 72, 67], [1, 43, 71, 2, 34, 95, 95, 48, 70, 43]]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "main2.py", line 60, in main
QuickSort(eachList)
File "main2.py", line 90, in QuickSort
sortedList = quickSort(low)
NameError: global name 'quickSort' is not defined
```

Am i supposed to import something into my file?? Code looks like:
```def QuickSort(numberList):
a = numberList
if len(a) <= 1:
return a
end = len(a) -1
pivot = a[end]
low = []
high = []
for num in a[:end:]:
if num <= pivot:
low.append(num)
else:
high.append(num)

sortedList = quickSort(low)
sortedList.appned(pivot)
sortedList.extend(quickSort(high))
return sortedList

```

### #10 Simown

• Blue Sprat

Reputation: 321
• Posts: 650
• Joined: 20-May 10

## Re: Multiple random lists given user input

Posted 29 April 2012 - 06:55 AM

The error:

```NameError: global name 'quickSort' is not defined

```

Your function is called "QuickSort" and then your recursive call calls "quickSort" (lower case q) on line 17.

Change one of them so they match and you should be set

### #11 thatOnekid

Reputation: 1
• Posts: 9
• Joined: 28-April 12

## Re: Multiple random lists given user input

Posted 29 April 2012 - 08:45 AM

Worked Great, Thanks for the help all! Program done and now the fun part!! (taking various test cases and timing my functions!!)

### #12 atraub

• Pythoneer

Reputation: 828
• Posts: 2,235
• Joined: 23-December 08

## Re: Multiple random lists given user input

Posted 29 April 2012 - 08:54 AM

Incidentally, there's a little error in your quicksort code, but that could just be from copying and pasting it into DIC. The code under your first condition isn't indented.

### #13 thatOnekid

Reputation: 1
• Posts: 9
• Joined: 28-April 12

## Re: Multiple random lists given user input

Posted 29 April 2012 - 10:55 AM

Yeah, just copied it badly. Though I had some problems trying to write the results to a file. I am trying to write it where every time I run the main(), I ask user if they want to save. I gotten that part down, but when I run the code a second time, it removes what ever was saved in the file. Trying to keep all results in the file so i could import it to excel and graph each sorting function result.

```  alogrithm = user_choice
print "Alogrithm:%s" %(alogrithm)
print "Input Data:%s"%(inputData)
print "  n      time (secs)"
print "_"*50
print n,sum(times),
info = n,sum(times)
saveit = raw_input("Would you like to save it to a file? (y/n)")
if saveit == 'y':
whichFile = raw_input("Which file would you like to save it to?")
fo = open(whichFile,"w")
fo.write("n  time \n")
fo.write("_"*50)
fo.write(str(info))
fo.close()
if saveit == 'n':
print " Ok, wont save"
quit = raw_input("Would you like to quit or repeat? (q / r)")
if quit == 'q':
exit()
else:
pass

```

When I run the program, this is what i get.

```Which sorting function would you like to use? Type 1-3.
1. BubbleSort
2. Insertion Sort
3. QuickSort
3
Which type of data pattern would you like? Type 1-3
1.Random
2.sorted
3.reverse sorted
2
What is the minimum array size?20
what is the size of array increments?20
What is the number of test arrays?2
a: [[19, 18, 5, 7, 6, 11, 7, 11, 2, 10, 18, 3, 0, 3, 0, 14, 7, 16, 4, 11], [12, 18, 12, 14, 15, 14, 14, 16, 5, 4, 0, 12, 0, 11, 18, 10, 2, 18, 15, 5]]
Alogrithm:3
Input Data:Sorted
n      time
__________________________________________________
20 0.000219106674194 secs
Would you like to save it to a file? (y/n)y
Which file would you like to save it to?test2.csv
Would you like to quit or repeat? (q / r)q

```

### #14 atraub

• Pythoneer

Reputation: 828
• Posts: 2,235
• Joined: 23-December 08

## Re: Multiple random lists given user input

Posted 29 April 2012 - 11:20 AM

fo = open(whichFile,"w") should be fo = open(whichFile,"a") . Write mode overwrites, you want append mode.

EDIT:
Also, you may want to make writing to your file a function:

```alogrithm = user_choice
print "Alogrithm:%s" %(alogrithm)
print "Input Data:%s"%(inputData)
print "  n      time (secs)"
print "_"*50
print n,sum(times),
info = n,sum(times)
saveit = raw_input("Would you like to save it to a file? (y/n)")
if saveit == 'y':
saveFile()
if saveit == 'n':
print " Ok, wont save"
quit = raw_input("Would you like to quit or repeat? (q / r)")
if quit == 'q':
exit()
else:
pass

def saveFile(info, whichFile = false): #this allows you to optionally provide a filename
if not whichFile:
whichFile = raw_input("Which file would you like to save it to?")
fo = open(whichFile,"a")
fo.write("n  time \n" + ("_"*50) + str(info))
fo.close()

```

This post has been edited by atraub: 29 April 2012 - 11:51 AM

### #15 thatOnekid

Reputation: 1
• Posts: 9
• Joined: 28-April 12

## Re: Multiple random lists given user input

Posted 29 April 2012 - 11:45 AM

Never mind, figured it out!! I had to append the wanted information.
```whichFile = raw_input("Which file would you like to save it to?")
with open(whichFile, "a") as fo:
fo.write("n  time(secs) \n")
fo.write(str(info))
fo.close()

```

Well that's all folks! Thanks again for the BIG help.