[Tutor] Hanging myself on substitution

Andrei Kulakov ak@silmarill.org
Fri, 03 Aug 2001 10:52:00 -0400


On Fri, Aug 03, 2001 at 10:07:54AM -0700, kromag@nsacom.net wrote:
> I have asked variants of this question several times, but for some reason it 
> just doesn't stick. This is a simple "pick ten cards" reader that guffs a 
> list out of a text file, chooses one "card", prints it to the screen, then 
> removes the "card" from the list. 

I'm sorry I didn't read the code carefully, but it /sounds/ like you may
want to use random.choice(list) that returns a random item from list.

> 
> What I am trying to do recalculate the number of items in the list. I count 
> them, then put that number as the second integer in a random.randint() 
> function.
> 
> -------begin pickacard.py-----------
> 
> import random
> import string
> cards=open('\windows\desktop\cards.txt','r')
> schmack=cards.readlines()
> counter=0
> while counter <10:
>         total_cards=len(schmack)
> '''here is where my pain begins...'''
>         choose=random.randint(1,%i)% total_cards #<-grrr!
> 	chosen=schmack[choose] 
> 	del schmack[choose]
> 	print chosen
> 	counter=counter+1
> -------end pickacard.py------------
> 
> of course the depricated:
> 
> random.randint(1, string.atoi(`total_cards`))
> 
> as in:
> 
> ------begin uglypickacard.py------
> import random
> import string
> cards=open('\windows\desktop\cards.txt','r')
> schmack=cards.readlines()
> total_cards=len(schmack)
> counter=0
> while counter <10:
> 	total_cards=len(schmack)
> 	choose=random.randint(1,string.atoi(`total_cards`))
> 	chosen=schmack[choose] 
> 	del schmack[choose]
> 	print chosen
> 	counter=counter+1
> -------end uglypickacard.py---------
> 
> seems to work fine. What is the proper method so's I don't shoot myself in 
> the foot later?
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: http://silmarill.org/cymbaline