Google foo.bar 招聘挑战跳过工作

Google foo.bar hiring challenge skipping work

今天早上我开始了 Google 的 foo.bar 挑战。任务是比较 2 个列表并返回不相同的值。

For example, given the lists x = [13, 5, 6, 2, 5] and y = [5, 2, 5, 13], the function solution(x, y) would return 6 because the list x contains the integer 6 and the list y doesn't.

所以我写了这段代码;

x = [13, 5, 6, 2, 5]
y = [5, 2, 5, 13]

list_difference1 = [item for item in x if item not in y]
list_difference2 = [item for item in y if item not in x]


list_difference = list_difference2 + list_difference1
list_difference

输出:[6]

这是脚本中的样子;

def solution(x, y):
    list_difference1 = [item for item in x if item not in y]
    list_difference2 = [item for item in y if item not in x]

    list_difference = list_difference2 + list_difference1

    return list_difference

我不明白我做错了什么。

使用 sets,它比列表更快:

x = [13, 5, 6, 2, 5]
y = [5, 2, 5, 13]

def solution(x, y):
    return list(set(x) ^ set (y))

print(solution(x, y))
# [6]

否则,您的代码似乎是正确的(只是效率不高):

def solution2(x, y):
    list_difference1 = [item for item in x if item not in y]
    list_difference2 = [item for item in y if item not in x]
    list_difference = list_difference2 + list_difference1
    return list_difference

print(solution2(x, y))
# [6]

你应该 return 6,而不是 [6]