[Tutor] Lists and While Loops

2012-03-28 Thread Ricky Brown
So I have to write a program that reads a message from the user and prints
a new message that contains all the words from the original message but in
the same order without repeating any of them unless they show up more than
once in the original message.

What I have thus far looks like this:

message = input("Your message:")
myList = message.split()
y = random.choice(myList)
z = len(myList)
while z !=0:
myList.remove(y)
print(y)

I can't figure out
1) How to remove "y" from the list and continue the loop; when I use
.remove etc. it runs once then give me the error that "y" is not in the
list.

I imagine the answer is quite simple I'm just getting really frustrated
trying to get this done any advice is appreciated.

Thanks
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Lists and While Loops

2012-03-28 Thread Ricky Brown
Thank you all for your input it was extremely helpful. Robert you were spot
on with what I was trying to do, I tried to implement the random.sample
earlier but I couldn't see to get it too work -- running smoothly now.

Sorry for the trouble :)

On Wed, Mar 28, 2012 at 4:14 PM, Robert Sjoblom wrote:

> > I can't figure out
> > 1) How to remove "y" from the list and continue the loop; when I use
> .remove
> > etc. it runs once then give me the error that "y" is not in the list.
> >
> > I imagine the answer is quite simple I'm just getting really frustrated
> > trying to get this done any advice is appreciated.
>
> This should tell you why you run into your error:
>
> >>> message = "This is a message."
> >>> m_list = message.split()
> >>> m_list
> ['This', 'is', 'a', 'message.']
> >>> y = random.choice(m_list)
> >>> y
> 'message.'
> >>> m_list.remove(y)
> >>> m_list
> ['This', 'is', 'a']
> >>> y
> 'message.'
>
> You should probably move your y = random.choice() into the while loop.
>
> A simpler way than to remove items from a list is to use random.sample:
> >>> message = "This is a message."
> >>> m_list = message.split()
> >>> random.sample(m_list, len(m_list))
> ['is', 'This', 'a', 'message.']
>
> --
> best regards,
> Robert S.
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor