Exercise
This week's exercise was an old exercise (see Exercise 5), requiring the solution in a different way.Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Write this in one line of Python.Extra:
- Randomly generate two lists to test this
I think the solution may be slightly incorrect. The question said without duplicates, and [i for i in a if i in b] will undoubtedly produce duplicates. The reason there are no duplicates in the sample test is because random.sample takes UNIQUE numbers within that range.
ReplyDeleteI had the same confusion!
ReplyDeleteHmm, good points on the solution. At the moment, I agree with Jamie that the /correct/ appropriate solution without using the random.sample arguments is to use:
ReplyDelete[i for i in set(a) if i in b]
Even though technically I didn't talk about sets yet (nothing wrong with Googling!). It's not cheating to use something you find on Google, as long as you understand what it is you are doing.
Thanks for pointing out the mistake. Any headway on finding a better solution without using sets? I'm stumped.
Nope! I wracked my brains, searched google for ages. I also asked my brother (who is a Python Developer) and his response was "yeah, I'd just use sets..."
ReplyDeleteYes, as ConfusedProgrammer said it would add duplicates to the result list if we don't randomise. I am yet to find a single line solution for the list overlap (exercise 5 ) using list comprehension. It would add duplicates if we don't randomise. Any suggestions?
ReplyDelete