a1 = ['arp', 'bull', 'mice']
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
I need it to return:
['arp']
My code is:
def in_array(array1, array2):
x = array1
return sorted(x)
which works for:
a1 = ["live", "arp", "strong"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
r = ['arp', 'live', 'strong']
How do I sort through an array and only match the sorted elements that are substrings of a2?
You can simply use a filter
and check whether there is any(..)
element in a2
that contains such a substring:
def in_array(a1,a2):
return filter(lambda e1: any(e1 in e2 for e2 in a2),a1)
In case you want the result to be sorted as well, you can use sorted(..)
:
def in_array(a1,a2):
return sorted(filter(lambda e1: any(e1 in e2 for e2 in a2),a1))
If you want to eliminate duplicates, you can use set(..)
:
def in_array(a1,a2):
return sorted(set(filter(lambda e1: any(e1 in e2 for e2 in a2),a1)))
The algorithm will run in O(n×m+n×log(n)) with n the number of elements in a1
, and m the number of elements in a2
.
You can boost the algorithm complexity in terms of O(n) in case you can do preprocessing on ar2
(and generate for instance a trie). But this is only beneficial if the number of elements in a1
is huge compared to the number of elements in a2
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.