首页 > 解决方案 > 获得更好的时间复杂度

问题描述

此代码用于将值断言 列表中 ,直到用户输入负数。

有没有更好的方法来实现它?

下面是我尝试过的版本。

i = -1
while i > -1:
    x = raw_input("Enter array limit")
    for i in limit(x):
        listArr = list()
        y = raw_input("Enter number")
        y.append(listArr)
        print (listArr)
        


        

标签: pythonarrayslistwhile-looptime-complexity

解决方案


像这样的东西应该满足要求:

odds = []                     # similiar to `listArr` but we only want odd numbers

limit = 5

for _ in range(limit):        # Input 5 numbers into an array
    y = int(input('Enter number: '))        
    if y > -1 and y % 2 !=0:  # if odd number
        odds.append(y)        # add to array
    else:
        break                 # break after a negative number as input 

if odds:
    print(min(odds))          # and display minimum odd number 
                              # and if no negative integer input then also display minimum odd number 
else:
    print(0)                  # and if no odd number display zero

如果 Python2 使用raw_input()问题代码,否则使用input().


推荐阅读