Search code examples
pythonlistgreatest-common-divisor

Can't find common elements is two lists


I'm writing a little python program, which is supposed to find the greatest common divisor between two numbers. Until now everything went fine but I can't get the program to find the correct common elements in the two lists the program provides. Also you can see that the list 'combines_prime_lst' is assigned in the 'common_member()' function but appears empty when the code gets back to the 'ggT()' function. The variable was assigned at the top of the code as an empty list.

I checked, the lists are actually lists, I tried with the intersection() function and the & method. The output I get is always false.

combined_prime_lst = common_member(prime_number_lst_1, prime_number_lst_2)
    print("Common elements 2:", combined_prime_lst)

    print("Der ggT von", number_1, "und", number_2, "ist:", combined_prime_lst)
def common_member(lst_1, lst_2):
    lst1 = set(lst_1)
    lst2 = set(lst_2)

    combined_prime_lst = list(set(lst1).intersection(lst2))
    print("Common elements:", combined_prime_lst)
    if combined_prime_lst == []:
        print("Keine gemeinsamen Elemente.")

At last this is the output I get when I run the program.

Was ist deine erste Zahl? 36
Wie lautet deine zweite Zahl? 66
Fist list: [2, 2, 3, 3]
Second list: [2, 3, 11]
Common elements 2: []
Der ggT von 36 und 66 ist: []

Solution

  • The problem you are experiencing is because you are assigning to 'combined_prime_lst' the result of common_member(lst_1, lst_2); but this function isn't actually returning anything. So, inside the function 'combined_prime_lst' has a value, but outside it you are assigning 'None' to it

    Here is how I modified the code:

    prime_number_lst_1 = [2, 2, 3, 3]
    prime_number_lst_2 = [2, 3, 11]
    
    def common_member(lst_1, lst_2):
        lst1 = set(lst_1)
        lst2 = set(lst_2)
    
        combined_prime_lst = list(set(lst1).intersection(lst2))
        print("Common elements:", combined_prime_lst)
        if combined_prime_lst == []:
            print("Keine gemeinsamen Elemente.")
    
        return combined_prime_lst
    
    combined_prime_lst = common_member(prime_number_lst_1, prime_number_lst_2)
    print("Common elements 2:", combined_prime_lst)
    
    number_1, number_2 = combined_prime_lst
    print("Der ggT von", number_1, "und", number_2, "ist:", combined_prime_lst)
    

    Output:

    Common elements: [2, 3]
    Common elements 2: [2, 3]
    Der ggT von 2 und 3 ist: [2, 3]