Jython编码问题

时间:2015-03-26 18:01:20

标签: python jython

设计一个程序,让用户将12个月中每个月的总降雨量输入到列表中。该计划应计算并显示当年的总降雨量,月平均降雨量以及最高和最低量的月份。

def main():
January = requestNumber ("Enter the amount of rainfall for the month of January:") 
February = requestNumber ("Enter the amount of rainfall for the month of February:") 
March = requestNumber ("Enter the amount of rainfall for the month of March:") 
April = requestNumber ("Enter the amount of rainfall for the month of April:") 
May = requestNumber ("Enter the amount of rainfall for the month of May:") 
June = requestNumber ("Enter the amount of rainfall for the month of June:") 
July = requestNumber ("Enter the amount of rainfall for the month of July:") 
August= requestNumber ("Enter the amount of rainfall for the month of August:") 
September = requestNumber ("Enter the amount of rainfall for the month of September:") 
October = requestNumber ("Enter the amount of rainfall for the month of October:") 
November = requestNumber ("Enter the amount of rainfall for the month of November:") 
December = requestNumber ("Enter the amount of rainfall for the month of December:") 

Year = [January, February, March, April, May, June, July, August, September, October, November, December] 

total_rainfall = (sum(Year))
showInformation("The total rainfall for the year is:" + str(total_rainfall))

monthly_average = (sum(Year)) / 12
showInformation ("The monthly average for the year is:" +  str(monthly_average))

这是我到目前为止的代码。我真的在努力研究问题的最后一部分,即显示最高和最低降雨量的月份。我知道如何使用max和min显示数字,但我不知道如何获得对应于最大和最小降雨量的月份。

感谢任何人都能给我的帮助,这是在Jython中。

1 个答案:

答案 0 :(得分:0)

解决方案1:

为您的计划添加月份名称列表:

Names = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
Year = [January, February, March, April, May, June, July, August, September, October, November, December] 

然后,一旦获得用户的输入,同时对两个列表进行排序:

monthsSorted = sorted( zip(Names, Year), cmp=lambda (x1, y1), (x2, y2) : y2 - y1 )

print "MAX=%s" % str(monthsSorted[0])
print "MIN=%s" % str(monthsSorted[-1:])

zip()将创建两个这样的列表:

zip( [1,2,3], [a,b,c] ) -> [(1,a), (2,b), (3, c)]

然后按第二部分(降雨量)排序。

现在最大的月份是在几个月的前面,最小的是它的最后一个元素。

解决方案2: 迭代比较它们的所有元素,比如一轮冒泡排序

print "MAX=%s" % str( reduce(lambda (x1, y1), (x2, y2) : (x1, y1) if y1 > y2 else (x2, y2), zip(Names, Year)) )

print "MIN=%s" % str ( reduce(lambda (x1, y1), (x2, y2) : (x1, y1) if y1 < y2 else (x2, y2), zip(Names, Year)) )