SPOJ Fashion给出了运行时错误Python

时间:2011-12-29 07:34:59

标签: python

问题描述在这里:http://www.spoj.pl/problems/FASHION/

进程:取两个列表作为输入,使用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.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

谢谢!

1 个答案:

答案 0 :(得分:2)

这就是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>

因此,您必须修改代码以将结果保留在内存中,直到输入最后一个输入。那么你也应该移动一些代码,以便考虑到竞赛之间的num可能会有所不同。

这已被修改为按预期工作:

def process(index,line):
    p = line.split(" ")
    for i in p:
        if(index==0):
            men.append(int(i))
        else:
            women.append(int(i))

n = int(raw_input()) #This is for number of shows
results = []
for t in range(0, n): #Do this "n" times
    men = []
    women = []
    num = int(raw_input()) #This is number of 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
    men.sort()
    women.sort()

    for i in range(0,num):
        p = p + men[i]  * women[i]
    results.append(p)

for item in results:
    print item

代码可以大大简化:

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

编辑我使用sum(generator_expresion)而不是for循环优化了一点代码