[Tutor] Python Questions Help
Caroline H
carolineharlow0 at gmail.com
Sun Oct 26 23:15:51 CET 2014
Hi Python Tutor,
I'm having a lot of trouble with this python problem and I'm wondering if
you can help me.
"Given the lists, lst1 and lst2 , create a new sorted list consisting of
all the elements of lst1 that also appears in lst2 . For example, if lst1
is [4, 3, 2, 6, 2] and lst2 is [1, 2, 4], then the new list would be [2, 2,
4]. Note that duplicate elements in lst1 that appear in lst2 are also
duplicated in the new list. Associate the new list with the variable
new_list , and don't forget to sort the new list."
The code I wrote almost works, it just needs to be able to add a number
more than once in the third list.
For example,
lst1 = [2,5,6,7,2]
lst2 = [2,4]
it comes up with new_list = [2] when I need it to come up with new_list =
[2,2]
The code I have so far is:
new_list = []
i = 0
j = 0
if len(lst1)<=len(lst2):
for i in range(len(lst1)):
if lst1[i] in lst2:
new_list.append(lst1[i])
else:
for j in range(len(lst2)):
if lst2[j] in lst1:
new_list.append(lst2[j])
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20141026/2d455589/attachment.html>
More information about the Tutor
mailing list