SPOJ模式给出运行时错误Python
问题描述如下: 过程:将两个列表作为输入,使用Python中的sort方法对它们进行排序,然后打印总和 代码:SPOJ模式给出运行时错误Python,python,Python,问题描述如下: 过程:将两个列表作为输入,使用Python中的sort方法对它们进行排序,然后打印总和 代码: import sys,os #Need to maximize the product of two lists def process(index,line): p=line.split(" ") #print 'Line after splitting',p for i in p: if(index==0): men
import sys,os
#Need to maximize the product of two lists
def process(index,line):
p=line.split(" ")
#print 'Line after splitting',p
for i in p:
if(index==0):
men.append(int(i))
else:
women.append(int(i))
global men
global women
men=[]
women=[]
''' First, you enter number of times you want to compare .
Second, you enter number of men/women
Then, you enter the real data
'''
n=int(raw_input()) #This is for number of shows
num = int(raw_input()) #This is number of men/women
for t in range(0,n): #Do this "n" times
men = []
women = []
for i in range(0,2): #Now, enter the men data first and women next
line=raw_input()
process(i,line)
p=0
temp = []
men.sort()
women.sort()
for i in range(0,num):
p = p + men[i] * women[i]
print p
问题:它不断给出运行时错误:
我处理过的一些案例:
In [16]: %run /home/crazyabtliv/SPOJ/Fashion.py
2
3
1 1 1
2 3 4
9
4 5 6
0 9 8
94
In [14]: %run /home/crazyabtliv/SPOJ/Fashion.py
1
5
1 1 0 0 0
10 10 9 9 9
20
谢谢 这就是SPOJ所期望的:
Input:
2
2
1 1
3 2
3
2 3 2
1 3 2
Output:
5
15
但是,尝试运行程序会产生以下结果:
2
2
1 1
3 2
5 <- that is the output for the first contest. should not output yet
3
2 3 2
Traceback (most recent call last):
File "dasdsad.py", line 35, in <module>
p = p + men[i] * women[i]
IndexError: list index out of range
C:\Python26\programas\zz_so>
但代码仍然可以大大简化:
def process(line):
return sorted([int(i) for i in line.split()])
n = int(raw_input()) #This is for number of shows
results = []
for t in range(n): #Do this "n" times
num = int(raw_input()) #This is number of men/women
men = process(raw_input())
women = process(raw_input())
p = sum(m*w for m, w in zip(men, women))
results.append(p)
for item in results:
print item
编辑:我用sumgenerator_expression而不是for循环对代码进行了一些优化您的代码是什么?为什么不尝试用。您得到相同的输出吗?谢谢!这两件事。修改后的代码教会了我很多:下一次会写得更好!再次感谢不客气。如果关注代码,您可以做更多的事情。例如,你可以用p=sum[m*w代表m,w代表zipmen,women]@crazyaboutliv改变'p=0代表rangenum中的i:p=p+men[i]*women[i]`最后一件事:如果你正在编写spoj代码,并且想用其他人的意见分析和改进你的运行代码,你可能想发布你的建议以表示感谢!非常感谢!我们将从现在开始这样做。现在与主发电机战斗:可以吗soon@crazyaboutliv行动!错了,似乎是斯波吉人。嗯,我承认他们是对的。
def process(line):
return sorted([int(i) for i in line.split()])
n = int(raw_input()) #This is for number of shows
results = []
for t in range(n): #Do this "n" times
num = int(raw_input()) #This is number of men/women
men = process(raw_input())
women = process(raw_input())
p = sum(m*w for m, w in zip(men, women))
results.append(p)
for item in results:
print item