我一直在尝试解决 Spotify 发布的这个难题,但是在查看并尝试了几种方法之后,尽管我的测试还可以,但我无法从他们的系统中得到肯定的答案。
我提出了我的两个解决方案。除了质量计算方法和标准输入读取之外,它们非常相似。代码可以得到细化,我对正确的结果感兴趣。
所以我想问你是否能指出我的错误和误解。谢谢
第一:
import sys, re
try:
p = re.compile('^[a-z0-9_]{1,30}$')
theOutput = sys.stdout.write
line = sys.stdin.readline().strip().split()
n = int(line[0])
if n < 1 or n > 50000:
raise Exception("First inputted number is out of range (1<=n<=50000)")
else:
m = int(line[1])
if m < 1 or m > n:
raise Exception("Second inputted number is out of range (1<=m<=n)")
else:
song_freq = []
freq_max = 10**12
for i in range(n):
line = sys.stdin.readline().strip().split()
line[0] = int(line[0])
if line[0] > freq_max:
raise Exception("Frequency of song " + str(i+1) + "(" + str(line[0]) + ") out of range")
if p.match(line[1]):
song_freq.append((int(line[0]), line[1]))
else:
raise Exception("Songname " + line[1] + " at line " + str(i+1) + " is not valid")
song_zipf = [((song_freq[0][0]/float(i+1)), song_freq[i][1]) for i in range(n)]
song_qual = [((song_freq[i][0]/song_zipf[i][0]), song_freq[i][1]) for i in range(n)]
song_qual = sorted(song_qual, key = lambda tup:tup[0], reverse = True)
for j in range(m):
theOutput(song_qual[j][1]+'\n')
except Exception as e:
print "Exception:", e.message
第二个:
import sys, re
try:
p = re.compile('^[a-z0-9_]{1,30}$')
theInput = sys.stdin.readline().split('\n')
theOutput = sys.stdout.write
line = theInput.pop(0).strip().split()
n = int(line[0])
if n < 1 or n > 50000:
raise Exception("First inputted number is out of range (1<=n<=50000)")
else:
m = int(line[1])
if m < 1 or m > n:
raise Exception("Second inputted number is out of range (1<=m<=n)")
else:
songlist = []
freq_max = 10**12
for i in range(n):
line = theInput.pop(0).strip().split()
line[0] = int(line[0])
if line[0] > freq_max:
raise Exception("Frequency of song " + str(i+1) + "(" + str(line[0]) + ") out of range")
if p.match(line[1]):
songlist.append((int(line[0]), line[1]))
else:
raise Exception("Songname " + line[1] + " at line " + str(i+1) + " is not valid")
song_qual = [((songlist[i][0]*(i+1)), songlist[i][1]) for i in range(n)]
song_qual = sorted(song_qual, key = lambda tup:tup[0], reverse = True)
for j in range(m):
theOutput(song_qual[j][1]+'\n')
except Exception as e:
print "Exception:", e.message