[Tutor] Hanging myself on substitution
kromag@nsacom.net
kromag@nsacom.net
Fri, 3 Aug 2001 10:07:54 -0700 (PDT)
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.
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?