Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple Comparison with Integers

I am trying to do tuple comparison. I expected 2 as a result, but this bit of code prints out 0. Why?

tup1 = (1, 2, 3, 4, 5)
tup2 = (2, 7, 9, 8, 5)
count = 0

if tup1[0:5] == tup2[0]:
    count + 1
elif tup1[0:5] == tup2[1]:
    count + 1
elif tup1[0:5] == tup2[2]:
    count + 1
elif tup1[0:5] == tup2[3]:
    count + 1
elif tup1[0:5] == tup2[4]:
    count + 1
print(count)
like image 220
MrMinehart Avatar asked Jan 24 '26 17:01

MrMinehart


2 Answers

You can do what you intend with a set intersection:

len(set(tup1) & set(tup2))

The intersection returns the common items in both tuples:

>>> set(tup1) & set(tup2)
{2, 5}

Calling len on the result of the intersection gives the number of common items in both tuples.

The above will however not give correct results if there are duplicated items in any of the tuples. You will need to do, say a comprehension, to handle this:

sum(1 for i in tup1 if i in tup2) # adds one if item in tup1 is found in tup2

You may need to change the order in which the tuples appear depending on which of them has the duplicate. Or if both contain dupes, you could make two runs juxtaposing both tuples and take the max value from both runs.

like image 97
Moses Koledoye Avatar answered Jan 26 '26 09:01

Moses Koledoye


Your code fails as you are comparing a tuple to an integer, even if you use in as below you would still need to use += count + 1 does not update the count variable:

count = 0

for ele in tup2:
    if ele in tup1:
        count += 1

You can do it in linear time and account for duplicate occurrences in tup2 making only tup1 set:

st = set(tup1)
print(sum(ele in st for ele in tup2))

If you wanted the total sum from both of common elements, you could use a Counter dict:

tup1 = (1, 2, 3, 4, 5, 4, 2)
tup2 = (2, 7, 9, 8, 2, 5)
from collections import Counter

cn = Counter(tup1)

print(sum(cn[i] for i in tup2))
like image 24
Padraic Cunningham Avatar answered Jan 26 '26 10:01

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!