August 19th, 2013, 12:09 PM
Another ebook exercise prob
Hi, I have another ebook exercise problem I cant get my head round.
Exercise 10.6 Write a function called remove_duplicates that takes a list and returns a new list
with only the unique elements from the original. Hint: they donít have to be in the same order.
Ive come up with this-
I know isn't quite right because the use of set hasn't come up in the ebook yet and it should be accomplished without having to sort the list. I had to google to find out how to subtract the elements of one list from the elements of another in the line x=set(t)-set(new), is there an alternative.
for s in range(len(t)-1):
How should I approach this exercise?
August 19th, 2013, 12:43 PM
I'll try not to totally give it away here, but here's some pointers:
First, using this construct in python is almost always wrong:
Pretty much every collection object (list, set, dict, tuple, string, etc) in python is iterable, so you can (and should) just do this:
for item in range(len(some_collection)):
If you really need the index of the item as well as the value (though I'll tell you that you don't need it in this case), you can do:
for item in some_collection:
for index, item in enumerate(some_collection):
Second, if you want to check if some collection c contains some value v, you can just do this:
Finally, adding a value to a list can be done with the append() method, like so:
Those three things put together should get you where you need to go.
Last edited by admoore; August 19th, 2013 at 12:46 PM.
August 19th, 2013, 01:32 PM
Using sets, and that all the objects in the list are hashable,
run doctests with
Shellprompt> python -m doctest thisfile.py
[/code] are essential for python code and Makefiles!
August 19th, 2013, 01:36 PM
Thanks for the replies, ill try and figure it out. It should be a question that reflects or has aspects of the chapter preceding it, but I must be not seeing something obvious. Ill read it through again.