is there a shorter way to write this

Tim Chase python.list at tim.thechases.com
Thu Jan 29 09:53:45 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)

If you just need the "word", you can use

  >>> word = "".join(random.sample(string.lowercase, 5))

If you need the "leftovers" too:

  >>> letters = list(string.lowercase)
  >>> random.shuffle(letters)
  >>> word = "".join(letters[:5])
  >>> remainder = letters[5:]
  >>> print word
  hjwnq
  >>> print "".join(letters)
  ebultgydafpmrxszicvko

This assumes that your input dataset is unique (which 
string.lowercase is, but your problem definition doesn't 
guarantee) for your definition of "unique" (are upper/lowercase 
considered "unique" or "the same"?).  If you need unique, you'd 
have to pre-process -- likely with set():

  >>> data = "abcdefghijABCDEFGHIJK"
  >>> input_data = list(set(c.lower() for c in data))
  >>> word = "".join(random.sample(input_data, 5))
  >>> random.shuffle(input_data)
  >>> word = "".join(input_data[:5])
  >>> remainder = "".join(input_data[5:])

-tkc












More information about the Python-list mailing list