kyramichel
kyramichel

Reputation: 491

Python code to find the sum of common elements in two sequences of integers in a range

"""A better Python code to find find the sum of common elements in two sequences #of integers in a range ??"""

#F() constructs a sequence:

def F():
    bot=int(input("Enter start value:")) 
#start value
    top = int(input("Enter stop value:"))
#stop value
    L=range(bot,top+1)
    return(L)
# Let L1 and L2 two sequences
L1=F()
L2=F()
print(L1, L2)


#G()returns the sum of the common elements in L1 and L2:

def G(L1, L2):
    res = []
    for x in L1:
        if x in L2:
            res.append(x)
    return sum(res)
print(G(L1, L2))


# Example: L1=range(1,11), L2=range(5,21): 45(=5+6+7+8+9+10)

Upvotes: 0

Views: 309

Answers (1)

chapelo
chapelo

Reputation: 2562

If your solution is working, Why looking for a "better Python code"? Your code is good enough. The only change I would do is the list res. You don't really need it:

def G(L1, L2):
    total = 0
    for x in L1:
        if x in L2:
            total += x
    return total

The solution using set is good if you are sure that all the elements in L1 and L2 are unique. In this case, because you generated them with a range, they are unique, and you could use:

sum(set(L1).intersection(set(L2))

If there are duplicates, you could filter the elements:

sum(filter(lambda x: x in L2, L1))

Or you could also use list comprehension:

sum([x for x in L1 if x in L2])

But I repeat: I think your solution is good Python code.

Upvotes: 1

Related Questions