Honza Synek
Honza Synek

Reputation: 125

comparing numbers in 2 string A and B

I am solving a problem in python.

I have 2 strings with numbers and I need to find out whether a number from string B is located in a string A.

for example:

a = "5, 7" 
b = "6,5"

A and B may contain any number and quantity.

If the number of string B is in A I want result true or false.

Unfortunately, I do not know how to do this.

Upvotes: 0

Views: 91

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121924

You have strings, not integers, so you'd have to convert them to integers first:

a_nums = [int(n) for n in a.split(',')]
b_nums = [int(n) for n in b.split(',')]

This uses a list comprehension to turn each result of a str.split() method call into integers with the int() function.

To test if there are numbers in both sequences, you'd use sets, then test if there is an intersection:

set(a_nums) & set(b_nums)

If the result is not empty, there were numbers shared between the sequences. Since non-empty sets are considered 'true', in Python, you'd convert this to a boolean with bool():

bool(set(a_nums) & set(b_nums))

Sets are by far the most efficient method to test for such intersections.

You can do all this in one line, and a little more efficiently, with generator expressions and the set.intersection() method:

bool(set(int(n) for n in a.split(',')).intersection(int(n) for n in b.split(',')))

or perhaps a little more compact still with the map() function:

bool(set(map(int, a.split(','))).intersection(map(int, b.split(','))))

Demo:

>>> a = "5, 7" 
>>> b = "6,5"
>>> bool(set(map(int, a.split(','))).intersection(map(int, b.split(','))))
True

or breaking it down a little:

>>> [int(n) for n in a.split(',')]
[5, 7]
>>> [int(n) for n in b.split(',')]
[6, 5]
>>> set(map(int, a.split(',')))
set([5, 7])
>>> set(map(int, a.split(','))).intersection(map(int, b.split(',')))
set([5])
>>> bool(set(map(int, a.split(','))).intersection(map(int, b.split(','))))
True

Upvotes: 5

CyanogenCX
CyanogenCX

Reputation: 404

#This should do the trick
a_ints = [int(i) for i in a.split(',')]
b_ints = [int(i) for i in b.split(',')]
for item in b_ints:
    for items in a_ints:
        if item==items: return true
return false

Upvotes: 1

xnx
xnx

Reputation: 25518

If the numbers are integers, to obtain a list of True / False entries corresponding to whether each number in b is in a, try:

a = "5, 7" 
b = "6,5"
A = [int(x) for x in a.split(',')]
B = [int(x) for x in b.split(',')]
c = [x in A for x in B]
print(c)

Output:

[False, True]

To find out if any of the numbers in b are in a, then:

any(c)

Output:

True

Upvotes: 3

Related Questions