如何才能提高此Python代码的效率?

时间:2017-02-07 17:16:12

标签: python-2.7 sum max average min

我刚刚开始学习Python(我的第一次涉及编码),这是我第一次发帖...我希望我不会通过提出这个问题来滥用论坛(我实际上是在请专家来帮我学习)。如果这在社区中不受欢迎,请告诉我。

对于密歇根州开放课程的这项任务,我已被指示要求用户输入,直到用户输入“完成”,此时代码应计算最大,最小,总和和平均值。在我的所有测试中,它都运行良好。但我觉得编写这段代码的方式可能要简单得多。有人可以提出改进建议吗?

largest = None
smallest = None
count = 0
sum = 0
while True:
    try:
        num = raw_input("Enter a number: ")
        if num == "done" : break
        num = float(num)
        count = count + 1
        sum = sum + num
        avg = sum/count
        if largest is None:
            largest = num
        if smallest is None:
            smallest = num
        if num < smallest:
            smallest = num
        elif num > largest:
            largest = num
        continue
    except: print 'Invalid input'

print "Maximum is", int(largest)
print "Minimum is", int(smallest)
print "Count:", int(count)
print "Sum:", int(sum)
print "Average:", avg

2 个答案:

答案 0 :(得分:1)

这里有一些事情:

  • 你可以删除continue语句,因为它仍然是循环的结束;
  • 您可以将if语句压缩为if largest is None or num > largest:这将 shortcircuit 并使循环更小;
  • 您可以使用x += y代替x = x + y;和
  • 您不必计算循环中的内部;在循环结束时计算一次就足够了。

所以:

largest = None
smallest = None
count = 0
sum = 0
while True:
    try:
        num = raw_input("Enter a number: ")
        if num == "done" : break
        num = float(num)
        count += 1
        sum += num
        if largest is None or num > largest:
            largest = num
        if smallest is None or num < smallest:
            smallest = num
    except: print 'Invalid input'

print "Maximum is", int(largest)
print "Minimum is", int(smallest)
print "Count:", int(count)
print "Sum:", int(sum)
print "Average:", sum/count

但就大哦而言,你无法提高太多:计算总和等只需要 O(n),它也需要花费 O( n)无论如何都要读取输入。

此外,一些软件工程建议:不使用一揽子例外,始终指定您期望的例外:

largest = None
smallest = None
count = 0
sum = 0
while True:
    try:
        num = raw_input("Enter a number: ")
        if num == "done" : break
        num = float(num)
        count += 1
        sum += num
        if largest is None or num > largest:
            largest = num
        if smallest is None or num < smallest:
            smallest = num
    except ValueError: print 'Invalid input'

print "Maximum is", int(largest)
print "Minimum is", int(smallest)
print "Count:", int(count)
print "Sum:", int(sum)
print "Average:", sum/count

答案 1 :(得分:1)

实现此目的的另一种方法是将所有输入存储在列表中,然后使用内置插件min()max()len()sum()找到价值观:

num=raw_input("Enter a number: ")
nums=[]
while num!="done":       #check if user has finished entering inputs
    try:
        nums.append(int(num))       #append the input as an integer to a list
        num=raw_input("Enter a number: ")   #get another input
    except ValueError:
        print "Invalid input"

print "Maximum is",max(nums)
print "Minimum is",min(nums)
print "Count:",len(nums)
print "Sum: ",sum(nums)
print "Average: ",sum(nums)/len(nums)

输出:

Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
Enter a number: 6
Enter a number: done
Maximum is 6
Minimum is 1
Count: 6
Sum:  21
Average:  3.5