/
12.02.2021 at 12:55 am
Cuttings

46 Simple Python Exercises/#10

Define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise.
Table of Contents

Problem

Define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise.

  • You may use your is_member() function, or the in operator.
  • But for the sake of the exercise, you should (also) write it using two nested for-loops.

Discussion

  1. I mainly compare Python's in-built set functions against 'standard' looping mechanisms.

  2. The results of all 3 solutions are the same. Only the implementation differs.

  3. Solution #1 uses the Set's .intersection() method, to find common elements between two lists.

  4. Solution #2 loops against two lists, and maintains another list of common elements to check against.

  5. Solution #3 loops against one list only. It breaks immediately when a common member is found. (Reason: the condition is to "have at least one member in common", and not anything more complex. ) This is possibly a performant solution, but also one likely to introduce bugs.

  6. I'd go with Solution #1 - it appears cleanest. Also, due to the use of sets, is perhaps more performant than Solution #3.

Solution

    def overlapping_1(l1, l2) -> bool:

        if set(l1).intersection(l2):
            return True
        else:
            return False


    def overlapping_2(l1, l2) -> bool:

        common = []
        for i in l1:
            for j in l2:
                if i == j:
                    common.append(i)

        if common != []:
            return True
        else:
            return False


    def overlapping_3(l1, l2) -> bool:

        for i in l1:
            if i in l2:
                return True  # Immediately exit
        else:
            return False


    if __name__ == "__main__":

        test_l1 = ["a", "b", "c"]
        test_l2 = ["c", "d", "e"]
        test_l3 = [1, 2, 3]

        funcs = overlapping_1, overlapping_2, overlapping_3

        for f in funcs:
            print(f(test_l1, test_l2), test_l1, test_l2)
            print(f(test_l1, test_l3), test_l1, test_l3)
Filed under:
#
#
Words: 318 words approx.
Time to read: 1.27 mins (at 250 wpm)
Keywords:
, , , , , , , , ,

Other suggested posts

  1. 11.06.2022 at 07:24 am / Vampiric Pathology
  2. 14.03.2020 at 09:18 pm / Sheets for People
  3. 14.12.2018 at 03:09 pm / Recursion, Succinctly Put
  4. 23.08.2018 at 01:33 am / Darwin's Details
  5. 12.07.2016 at 12:00 am / Refunctin' Blocks
  6. 24.01.2016 at 12:00 am / Prayers Like Magic
  7. 18.07.2014 at 12:00 am / Keep Learning Songs
  8. 02.12.2013 at 12:00 am / Coloured Plasmids
  9. 11.11.2013 at 12:00 am / 下戸 - Lower House
  10. 24.08.2010 at 12:00 am / Correspondences With Matt Treyvaud
© Wan Zafran. See disclaimer.