面試題(6)
阿新 • • 發佈:2019-01-08
1、 請使用自己的演算法,按升序合併如下兩個list,並去除重複的元素:
list1 = [2,3,8,4,9,5,6]
list2 = [5,6,10,17,11,2]
list1= [2,3,8,4,9,5,6]
list2= [5,6,10,17,11,2]
for i in list2:
if not i in list1:
list1.append(i)
list1.sort()
print(list1)
2、給定一個紅包的數額屬組gifts以及它的大小n,請返回是否有某個金額出現的次數超過總紅包數的一半。若存在返回該紅包金額,不存在請返回0
def select_most_often_gift(gifts):
gift_items = set(gifts)
n = len(gifts)
for gift in gift_items:
num = gifts.count(gift)
if num > n/2:
return gift
return 0
print(select_most_often_gift([2,3,6,2,24,5,56]))
print(select_most_often_gift([2,2,2,2,24,5,56]))
結果:
0
2