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
問題を解く構想:問題は最初の他の数と異なる数を探すことを意味し、入力した1行のデータの中で、最初の数nは全部でいくつかの数があって、後ろにnの数がついています.1つ目の考え方:2つのリストを作成し、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')

第2の考え方:1つの辞書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')