473,386 Members | 1,720 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,386 software developers and data experts.

count objects in a list and random numb gen

New to Python... trying to figure out how to count the objects in a list
and then map the count to the objects or convert the list to a dict... I
think the latter would be better as I need a number associated with each
entry. Any pointers?

Also, does this bit of code look to be truely random?

def random_number_gen():
winner = []
winner.append(random.sample(xrange(100000), 1))
print winner

TIA, Bart

Jul 18 '05 #1
4 2936
Bart Nessux <ba*********@hotmail.com> writes:
New to Python... trying to figure out how to count the objects in a
list and then map the count to the objects or convert the list to a
dict... I think the latter would be better as I need a number
associated with each entry. Any pointers?
I'm sorry but I just can't understand the above description. To count
the objects in a list L, use len(L). To find the k'th element of L,
list, use L[k].
Also, does this bit of code look to be truely random?

def random_number_gen():
winner = []
winner.append(random.sample(xrange(100000), 1))
print winner


If you want to choose one random winner out of a list, you can say
print random.randint(100000).

Note that Python's random function doesn't try to be really seriously
random, but only to have reasonable statistical properties. If you
need random numbers that can stand up to an adversary (e.g. you're
using it in an online game where the winners get substantial prizes),
you shouldn't generate them with the random module.
Jul 18 '05 #2
Paul Rubin wrote:
Bart Nessux <ba*********@hotmail.com> writes:
New to Python... trying to figure out how to count the objects in a
list and then map the count to the objects or convert the list to a
dict... I think the latter would be better as I need a number
associated with each entry. Any pointers?

I'm sorry but I just can't understand the above description


I want to count the objects in a list. len works well for this. Once I
have a count, I want to map that count to the items in the list like this:

entry one is 1
entry two is 2
entry three is 3
....

This is why I thought a dictionary may be better suited for this.

Also, does this bit of code look to be truely random?

def random_number_gen():
winner = []
winner.append(random.sample(xrange(100000), 1))
print winner

If you want to choose one random winner out of a list, you can say
print random.randint(100000).

Note that Python's random function doesn't try to be really seriously
random, but only to have reasonable statistical properties. If you
need random numbers that can stand up to an adversary (e.g. you're
using it in an online game where the winners get substantial prizes),
you shouldn't generate them with the random module.


I think random.sample is better than you think:

sample( population, k)

Returns a new list containing elements from the population while leaving
the original population unchanged. The resulting list is in selection
order so that all sub-slices will also be *valid random samples*. This
allows raffle winners (the sample) to be partitioned into grand prize
and second place winners (the subslices).

Jul 18 '05 #3
Bart Nessux fed this fish to the penguins on Thursday 08 January 2004
15:57 pm:

I want to count the objects in a list. len works well for this. Once I
have a count, I want to map that count to the items in the list like
this:

entry one is 1
entry two is 2
entry three is 3
...
Other than the fact that lists are indexed from zero...

alist = [ 'one', 'three', 'four' ] #since "one", "two" etc. is not clear

alist[0] is "one", alist[1] is "three", etc.

Unless you edit the list, that association remains -- the first item
is index 0, etc. You would have to delete something /in/ the list to
change the associations.

If you went with a dictionary, you need to clarify what you intend to
have as the key...

adict1 = {}
adict2 = {}
for i in xrange(len(alist)):
adict1[i] = alist[i]
adict2[alist[i]] = i

Which do you want, items as keys with the "lookup" the original index,
or index as key with the lookup to the item. NOTE: the first will have
problems in two items are identical ( ['same', 'same'] ) as you have
two indices for the value. The second is just adding a bunch of
overhead to produce the same result as indexing into the list.
adict1 {0: 'one', 1: 'three', 2: 'four'} adict2 {'four': 2, 'three': 1, 'one': 0}
adict1[1] 'three' alist[1] 'three'
Also, does this bit of code look to be truely random?

def random_number_gen():
winner = []
winner.append(random.sample(xrange(100000), 1))
print winner


Ignoring the randomness of random.sample(), this procedure is doing
the sequence:

Create empty list
append one item to the list
print the one-element LIST

on EVERY call... So why use a list? Just print the item itself.

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Bestiaria Home Page: http://www.beastie.dm.net/ <
Home Page: http://www.dm.net/~wulfraed/ <


Jul 18 '05 #4
Bart Nessux <ba*********@hotmail.com> wrote:

Also, does this bit of code look to be truely random?
The code doesn't look random at all, but of course that's not really the
question you meant to ask.
def random_number_gen():
winner = []
winner.append(random.sample(xrange(100000), 1))
print winner


It depends entirely on your definition of "truly random". There is no
single definition of that phrase.

However, that specific example provides no benefit over this simpler and
more efficient code:

def random_number_gen():
print int(random.uniform(0,100000))

which is itself just a shortcut for:

def random_number_gen():
print int(random.random()*100000))

What are you using the random numbers for? Tell us what you want to do
with them, and we'll suggest the right method.
--
- Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

22
by: Ling Lee | last post by:
Hi all. I'm trying to write a program that: 1) Ask me what file I want to count number of lines in, and then counts the lines and writes the answear out. 2) I made the first part like this: ...
3
by: phil | last post by:
Using Tkinter Canvas to teach High School Geometry with A LOT of success. My drawing gets very slow after a lot of actions. For instance I have created code to rotate a set of objects about a...
7
by: Fred Hedges | last post by:
I'm wondering if a tool exists that will integrate with the VS 2005 debugger, such that when I set a breakpoint I can inspect a reference and see how many other references exist to that object. ...
16
by: Kittyhawk | last post by:
I would like to sort an Arraylist of objects on multiple properties. For instance, I have a Sort Index property and an ID property (both integers). So, the results of my sort would look like this:...
14
by: avanti | last post by:
Hi, I need to generate random alphanumeric password strings for the users in my application using Javascript. Are there any links that will have pointers on the same? Thanks, Avanti
4
evilmonkey
by: evilmonkey | last post by:
Is there a way to use index of in java to pull the number of occurrences of every letter in a user defined sentence? I can brute force this but is there a faster more elegant way to achieve the same...
9
by: active | last post by:
Can you see why this does not sort the list? It displays OK but is not sorted Thanks for any help
26
by: Ping | last post by:
Hi, I'm wondering if it is useful to extend the count() method of a list to accept a callable object? What it does should be quite intuitive: count the number of items that the callable returns...
9
by: smarttechie | last post by:
Hii all please help its urgent i have developed an application in xsl. what i want to do is i m searching the xml file based on a search.and based on that search im creating one tree like...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.