PAT 1041 Be Unique python解法

1041 Be Unique (20 分)
Being unique is so important to people on Mars that even their lottery is designed in a unique way. The rule of winning is simple: one bets on a number chosen from [1,10​4]. The first one who bets on a unique number wins. For example, if there are 7 people betting on { 5 31 5 88 67 88 17 }, then the second one who bets on 31 wins.

Input Specification:
Each input file contains one test case. Each case contains a line which begins with a positive integer N (≤105​​ ) and then followed by N bets. The numbers are separated by a space.

Output Specification:
For each test case, print the winning number in a line. If there is no winner, print None instead.

Sample Input 1:
7 5 31 5 88 67 88 17
Sample Output 1:
31
Sample Input 2:
5 888 666 666 888 888
Sample Output 2:
None

解题思路:题意是找第一个与其他数不相同的数,输入的一行数据中,第一个数n是一共有几个数,后面跟着n个数。
第一个思路:建立两个列表,unique储存不相同的数,same存储去掉重复值之后的数,对输入l进行循环判断,如果l中元素在unique中,则将unique中该数删除,如果l中元素不在same中,则将该元素添加到same和unique中,循环结束后,如果unique中有元素,则输出第一个元素,如果为空,则输出None。此方法在2个测试点中超时。

#2个测试点运行超时
l = list(map(int,input().split()))
#l = [5, 888, 666, 666, 888, 888]
#l = [7, 5, 31, 5, 88, 67, 88, 17]
d = {}
for i in l[1:]:
    if i not in d.keys():
        d[i] = 1
    else:
        d[i] += 1
out = 0
for i in l[1:]:
    if i in d.keys() and d[i] == 1:
        out = i
        break
if out:
    print(out)
else:
    print('None')

第二个思路:建立一个字典d,对输入l进行循环判断,如果l中元素不在字典d中,则添加到字典d中,键为该元素,值为1,如果在字典d中,则将对应值加1。再对列表进行循环判断,找到第一个在字典d中的元素后跳出循环并将该元素保存到out中。out的初始值为0,因为题目所给的数据在[1,10​4],0不在其中。最后判断out是否为0,如果为0,则输出None,否则输出out。

l = list(map(int,input().split()))
#l = [5, 888, 666, 666, 888, 888]
#l = [7, 5, 31, 5, 88, 67, 88, 17]
d = {}
for i in l[1:]:
    if i not in d.keys():
        d[i] = 1
    else:
        d[i] += 1
out = 0
for i in l[1:]:
    if i in d.keys() and d[i] == 1:
        out = i
        break
if out:
    print(out)
else:
    print('None')

你可能感兴趣的:(python,用Python刷PAT,(Advanced,Level),Practice)