CodeWars打卡(03)
2018-06-28 本文已影响0人
影醉阏轩窗
Details:
Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2.
Example 1:
a1 = ["arp", "live", "strong"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
returns ["arp", "live", "strong"]
__Example 2: __
a1 = ["tarp", "mice", "bull"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
returns []
Notes:
Arrays are written in "general" notation. See "Your Test Cases" for examples in your language.
In Shell bash a1 and a2 are strings. The return is a string where words are separated by commas.
Beware: r must be without duplicates.
自己写的代码如下:
def in_array(array1, array2):
array1 = set(array1)
num = []
for r1 in array1:
for r2 in array2:
if r2.find(r1)!=-1:
num.append(r1)
break
return sorted(num)
- str.find(num,begin,end)-->>num存在于str中返回index,不存在返回-1,begin和end是搜索的range.
第一名代码:
def in_array(a1, a2):
return sorted({sub for sub in a1 if any(sub in s for s in a2)})
any和all的使用
any(x)判断x对象是否为空对象,如果都为空、0、false,则返回false,如果不都为空、0、false,则返回true
all(x)如果all(x)参数x对象的所有元素不为0、''、False或者x为空对象,则返回True,否则返回False