473,835 Members | 1,734 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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_g en():
winner = []
winner.append(r andom.sample(xr ange(100000), 1))
print winner

TIA, Bart

Jul 18 '05 #1
4 2967
Bart Nessux <ba*********@ho tmail.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_g en():
winner = []
winner.append(r andom.sample(xr ange(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*********@ho tmail.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_g en():
winner = []
winner.append(r andom.sample(xr ange(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(alis t)):
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_g en():
winner = []
winner.append(r andom.sample(xr ange(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.netc om.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*********@ho tmail.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_g en():
winner = []
winner.append(r andom.sample(xr ange(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_g en():
print int(random.unif orm(0,100000))

which is itself just a shortcut for:

def random_number_g en():
print int(random.rand om()*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
61431
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: in_file = raw_input("What is the name of the file you want to open: ") in_file = open("test.txt","r")
3
2242
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 rotation point. rotate 360 degrees starts to get slow after 720 degrees its crawling.
7
2438
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. I'm sure there is an internal reference count somewhere but have no idea how to inspect it.
16
2769
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: sort index, id 1000,1 1000,2 1000,3 1001,1 1001,2
14
4757
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
13886
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 result. I've started to try this but not sure I am on the right track. any help or push in the right direction would be appreciated. import java.util.StringTokenizer; import java.util.Scanner; public class Main { public static void...
9
2014
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
2467
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 True or anything logically equivalent (non-empty sequence, non-zero number, etc). This would return the same result as len(filter(a_callable, a_list)), but without constructing an intermediate list which is thrown away after len() is done.
9
2983
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 structure. in this tree structure i need the count of siblings in each level. im not getting the count exactly the same the xslt file ----------------- <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0"...
0
9800
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
10802
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10516
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10557
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10225
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6961
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5630
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5802
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3085
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.