is there a shorter way to write this

Andreas Tawn andreas.tawn at ubisoft.com
Thu Jan 29 09:29:15 EST 2009


> I had a task in a book to pick 5 items from a list of 26 ensuring the
items are not repeated
>
>
> import random
> list = ['a','b','c','d','e','f','g','h','i','j','k','l','m',
>        'n','o','p','q','r','s','t','u','v','w','x','y','z']
> word = ' '
> a = random.choice(list)
> list.remove(a)
> b = random.choice(list)
> list.remove(b)
> c = random.choice(list)
> list.remove(c)
> d = random.choice(list)
> list.remove(d)
> e = random.choice(list)
> list.remove(e)
> word = a + b + c + d + e
> print (word)
> print(list) 
 
Hmm, sounds like homework, but I'll bite.
 
How about...
 
import random, string
indices = range(26)
random.shuffle(indices)
word = "".join([string.ascii_lowercase[i] for i in indices[:5]])
print word
 
Cheers,
 
Drea
 
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090129/0ab2122c/attachment-0001.html>


More information about the Python-list mailing list