Hey (sorry bad english) so let me explain a little further. i want to make a function that takes in a list. let's say a list with a countries and their capital also added their population. i want to return every country-capital pair that dosen't contain the same letter. like this:
countries = [
["China PR", "Beijing", 20693000],
["India", "New Delhi", 16787949],
["Japan", "Tokyo", 13491000],
["Philippines", "Manilla", 12877253],
["Russia", "Moscow", 11541000],
["Egypt", "Cairo", 10230350]
]
#the output should be:
>>> no_common_letters(countries)
[["Japan", "Tokyo"], ["Egypt", "Cairo"]]
because Japan and Tokyo dosen't contain the same letters. anyone know a sulotion to this? i have tried looking around and all i can find is a program that finds a specified letter and check's if it's in. i want to check every word. i am new to python and trying to learn
CodePudding user response:
You can use this code:
def no_common_letters(array_of_arrays):
new_array = []
for array in array_of_arrays:
determination = []
for x in array[0]:
if x not in array[1]:
determination.append('1')
else:
determination.append('0')
if '0' not in determination:
new_array.append(array[0:2])
return new_array
print(no_common_letters([
["China PR", "Beijing", 20693000],
["India", "New Delhi", 16787949],
["Japan", "Tokyo", 13491000],
["Philippines", "Manilla", 12877253],
["Russia", "Moscow", 11541000],
["Egypt", "Cairo", 10230350]
]))
Returns
>> [["Japan", "Tokyo"], ["Egypt", "Cairo"]]
OR using SETS
def no_common_letters(array_of_arrays):
new_array = []
for array in array_of_arrays:
set1 = set(array[0])
set2 = set(array[1])
if not set1.intersection(set2):
new_array.append(array[0:2])
return new_array
print(no_common_letters([
["China PR", "Beijing", 20693000],
["India", "New Delhi", 16787949],
["Japan", "Tokyo", 13491000],
["Philippines", "Manilla", 12877253],
["Russia", "Moscow", 11541000],
["Egypt", "Cairo", 10230350]
]))
Returns
>> [["Japan", "Tokyo"], ["Egypt", "Cairo"]]
CodePudding user response:
you can use set intersection method to filter:
In [2]: [[i[0], i[1]] for i in countries if not set(i[0].lower()).intersection(set(i[1].lower()))]
Out[2]: [['Japan', 'Tokyo'], ['Egypt', 'Cairo']]
CodePudding user response:
I think you can try with set
for x,y,_ in countries:
if not set(x.lower()).intersection(y.lower()):
print(x,y)