Recursive Function - Compare 2 lists, return the elements that don't exist in both - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Recursive Function - Compare 2 lists, return the elements that don't exist in both (/thread-14894.html) |
Recursive Function - Compare 2 lists, return the elements that don't exist in both - KellyBaptist - Dec-22-2018 I have to do a RECURSIVE FUNCTION, comparing two lists and returning the elements that they don't have in common. This is what I have so far: def compare(list1, list2): if list2[0] in list1: list1.remove(list2[0]) return compare(list1[1:], list2[1:]) return list1 #Example >>>>compare([2, 3, 4, 5], [2, 3]) [4, 5]I can compare if the first element of the list (list[0]) is the same but I am having trouble on how to compare the elements if they are not in the first position...I've tried many options but I'm a begginer in programming and don't really know how to do it. It must be a RECURSIVE FUNCTION, I can't use FOR or WHILE. And is there any way that I can do it without using remove()? Thank you so much RE: Recursive Function - Compare 2 lists, return the elements that don't exist in both - Gribouillis - Dec-23-2018 Recursion works by supposing that you have the solution for a shorter copy of the problem. In your case, assuming that list2 is not empty, the listresult = compare(list1, list2[1:])contains all the items that are in list1 but not in list2[1:] or in list2[1:] but not in list1 . If list2[0] is in list1 , it needs to be removed from the result. If it is not in list1 , it needs to be added to the result.In the case where list2 is empty you can return a copy of list1 (don't return list1 itself because the result is modified by the recursive calls)
|