user2469407
user2469407

Reputation: 1

Python looping through two sets to compare all elements of each set

I am attempting to write a function that when given a set of Country names and a set of State names will compare the two sets to see if there is at least one country and one state that start with the same three letters.

I have tried many different ways to do this from creating a new set containing the first three letters of all the state and country names but I cannot seem to get it to work.

Any help would be greatly appreciated!

    def StartsWithSameThreeLetters(x,y):
        common = set(state[:3] for state in x) and set(country[:3] for country in y)
        length = len(x) + len(y)
        if length != len(common):
            return True
        else:
            return False

if x is the set of state names and y is the set of country names

Upvotes: 0

Views: 257

Answers (1)

Blender
Blender

Reputation: 298176

You can use set comprehensions:

common = {country[:3] for country in countries} & {state[:3] for state in states}

If your Python installation is too old to use them, there's always set():

set(country[:3] for country in countries)

Upvotes: 4

Related Questions