Python Forum
Recursive Function - Compare 2 lists, return the elements that don't exist in both
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Recursive Function - Compare 2 lists, return the elements that don't exist in both
#1
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
Reply
#2
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 list
result = 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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  function for extracting data from lists Paulman 9 2,720 Nov-09-2021, 04:00 PM
Last Post: Paulman
  Use of function/return Paulman 6 2,307 Oct-24-2021, 11:07 PM
Last Post: Paulman
  Multiple return from function Grimmar 7 3,490 Mar-22-2021, 09:20 PM
Last Post: Grimmar
  Lambda function not return value mbilalshafiq 4 3,252 Jul-04-2020, 07:47 AM
Last Post: ndc85430
  Child class function of Log return "None" mbilalshafiq 2 2,182 Jun-30-2020, 07:22 PM
Last Post: mbilalshafiq
  Question on "define function"; difference between return and print extricate 10 4,598 Jun-09-2020, 08:56 PM
Last Post: jefsummers
  "Plotting and Computation of Logistic Function by Using Taylor Series with Recursive canatilaa 1 1,786 May-13-2020, 04:01 PM
Last Post: jefsummers
  [split] problem with function return value ops 1 3,279 Apr-13-2020, 01:48 PM
Last Post: buran
  Compare elements of tuples / Find edges between nodes Daniel94 1 1,739 Apr-06-2020, 03:32 PM
Last Post: deanhystad
  Function to return today's month, day, and year sbabu 9 4,828 Jan-28-2020, 06:20 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020