473,385 Members | 1,356 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

how does random.sample work

5
I'm using python to write a program that, when given a list of random numbers, sorts them from lowest to highest then it asks the user for a number and it checks that number's place in the sorted list if the number is present, but i keep getting a syntax error on an "if" statement line near the end. is it because i'm not allowed to look up a number in the sorted list? here's my program with a list of example numbers (highlighted in bold is where i get the syntax error):
Expand|Select|Wrap|Line Numbers
  1. import random
  2. def sort_array2_4():
  3.     unsorted_array = random.sample(xrange(1000), 10)
  4. a=[93,84,200,513,46,1,45,334,92,96,156,82,92,46,]
  5. def bubblesort(a):
  6.     for swap in range(len(a)-1,0,-1):
  7.          for index in range(swap)
  8.              if a[index] > a[index + 1]:
  9.                a[index], a[index + 1] = a[index + 1], a[index]
  10.     return a
  11. while(more==True):
  12.     num=str(input("Enter a number to search for in list.\n")
  13.     if (num in bubblesort(a)):
  14.         print num + "is in list at number: ", bubblesort(a).index(num)
  15.     else:
  16.         print num + "is not recognized in list"
Dec 9 '06 #1
7 9765
bartonc
6,596 Expert 4TB
Great job! you were very close. next time include error message, ok?


Expand|Select|Wrap|Line Numbers
  1. import random
  2. def sort_array2_4():
  3.     unsorted_array = random.sample(xrange(1000), 10)
  4. a=[93,84,200,513,46,1,45,334,92,96,156,82,92,46,]
  5. def bubblesort(a):
  6.     for swap in range(len(a)-1,0,-1):
  7.          for index in range(swap):
  8.              if a[index] > a[index + 1]:
  9.                a[index], a[index + 1] = a[index + 1], a[index]
  10.     return a
  11. more = True  # must assign before reference
  12. while(more==True):
  13.     num=input("Enter a number to search for in list.\n")
  14.     # one too few parens caused syntax error no next line
  15.     # need the int anyway
  16.     b = bubblesort(a)  # use lots of variables for debugging
  17.     print b   # debug "trap"
  18.     if (num in b):
  19.         # print will convert to printable, so you don't have to
  20.         print num, "is in list at number: ", a.index(num)
  21.     else:
  22.         print num, "is not recognized in list"
Dec 9 '06 #2
bvdet
2,851 Expert Mod 2GB
Maybe you know this but the Python list object has an in place sort method:
Expand|Select|Wrap|Line Numbers
  1. a=[93,84,200,513,46,1,45,334,92,96,156,82,92,46,]
  2. a.sort()
  3. print a
  4. >>> [1, 45, 46, 46, 82, 84, 92, 92, 93, 96, 156, 200, 334, 513]
  5.  
Dec 9 '06 #3
Loismustdie129
195 100+
Maybe you know this but the Python list object has an in place sort method:
Expand|Select|Wrap|Line Numbers
  1. a=[93,84,200,513,46,1,45,334,92,96,156,82,92,46,]
  2. a.sort()
  3. print a
  4. >>> [1, 45, 46, 46, 82, 84, 92, 92, 93, 96, 156, 200, 334, 513]
  5.  

I was looking at the code that noob92 wrote and I was confused at what the sort_array2_4() code did. Can anyone explain that to me.
Dec 10 '06 #4
bartonc
6,596 Expert 4TB
I was looking at the code that noob92 wrote and I was confused at what the sort_array2_4() code did. Can anyone explain that to me.
The random module provide the function sample() defined here:

sample( population, k)

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

So the code:
Expand|Select|Wrap|Line Numbers
  1. import random
  2. def sort_array2_4():
  3.     unsorted_array = random.sample(xrange(1000), 10)
creates a 10 element list of random numbers from 0 to 999. If you copied the lines that does the work and run it you would get someting like:

>>> import random
>>> unsorted_array = random.sample(xrange(1000), 10)
>>> print unsorted_array
[461, 231, 423, 725, 696, 203, 8, 692, 745, 886]

Of course, after that the function does nothing (well actually, after that it returns None):

>>> def sort_array2_4():
... unsorted_array = random.sample(xrange(1000), 10)
...
>>> print sort_array2_4()
None

A bubble sort routine incrementally "floats" the biggest value to the top of the list. The lines:
Expand|Select|Wrap|Line Numbers
  1.         if a[index] > a[index + 1]:
  2.             a[index], a[index + 1] = a[index + 1], a[index]
  3.  
swaps the two values from left to right when the left one is bigger.
Dec 10 '06 #5
bartonc
6,596 Expert 4TB
I was looking at the code that noob92 wrote and I was confused at what the sort_array2_4() code did. Can anyone explain that to me.
Also, when you see something like
import random

The first thing to do is go to Start->Programs->Python 2.4->Python Manuals
and click Global Module Index. Scroll 'till you find the name that is being imported, click the link and scroll 'till you see the method or fuction being called.
Dec 10 '06 #6
bvdet
2,851 Expert Mod 2GB
I was looking at the code that noob92 wrote and I was confused at what the sort_array2_4() code did. Can anyone explain that to me.
Barton made some excellent comments. One thing I will point out is that noob92 never made the function call in his sample code. The function call may look something like this:
Expand|Select|Wrap|Line Numbers
  1. import random
  2.  
  3. def unsorted_list(n=10):
  4.     return random.sample(xrange(1000), n)
  5.  
  6. def bubblesort(a):
  7.     for swap in range(len(a)-1,0,-1):
  8.          for index in range(swap):
  9.              if a[index] > a[index + 1]:
  10.                a[index], a[index + 1] = a[index + 1], a[index]
  11.     return a
  12.  
  13. a = unsorted_list(14)
  14. print a
  15.  
  16. b = bubblesort(a)
  17. print b
Dec 10 '06 #7
Loismustdie129
195 100+
Barton made some excellent comments. One thing I will point out is that noob92 never made the function call in his sample code. The function call may look something like this:
Expand|Select|Wrap|Line Numbers
  1. import random
  2.  
  3. def unsorted_list(n=10):
  4.     return random.sample(xrange(1000), n)
  5.  
  6. def bubblesort(a):
  7.     for swap in range(len(a)-1,0,-1):
  8.          for index in range(swap):
  9.              if a[index] > a[index + 1]:
  10.                a[index], a[index + 1] = a[index + 1], a[index]
  11.     return a
  12.  
  13. a = unsorted_list(14)
  14. print a
  15.  
  16. b = bubblesort(a)
  17. print b

Thank you now I understand.
Dec 10 '06 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: Bart Nessux | last post by:
I am using method 'a' below to pick 25 names from a pool of 225. A co-worker is using method 'b' by running it 25 times and throwing out the winning name (names are associated with numbers) after...
21
by: Andreas Lobinger | last post by:
Aloha, i wanted to ask another problem, but as i started to build an example... How to generate (memory and time)-efficient a string containing random characters? I have never worked with...
4
by: james blair | last post by:
Hi I am generating a random number using random.randint(1,10000000000) Whats the possibility that the numbers generated will be same when generated by 100 users at the same time? Whats the best...
1
by: steflhermitte | last post by:
Dear cpp-ians, I want to apply a stratified sampling on an image. Following simplified example will explain my problem. The original image I with nrows and ncols is now a vector V of length...
4
by: Jesse Noller | last post by:
Hello - I'm probably missing something here, but I have a problem where I am populating a list of lists like this: list1 = list2 = list3 = main_list =
1
by: BerkshireGuy | last post by:
Hello everyone, I had a query that took 3,000 random records (which are addresses)from a table. This recordset is to send off surveys. I've noticed by looking at the data, that I have some...
4
by: Garry Freemyer | last post by:
I'm trying to convert this macro to a c# function but I have a big problem. It's on the LEFT side of an assignment statement and I am extremely flustered over this one because I'm a little rusty...
5
by: jordi | last post by:
I need the random.sample functionality where the population grows up to long int items. Do you know how could I get this same functionality in another way? thanks in advance. Jordi
48
by: Jimmy | last post by:
thanks to everyone that helped, unfortunately the code samples people gave me don't work. here is what i have so far: <% Dim oConn, oRS, randNum Randomize() randNum = (CInt(1000 * Rnd) + 1) *...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.