获得更好的时间复杂度

2024-04-25 04:37:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有没有更好的实施方法?

下面是我试用过的版本

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)
        


        

Tags: 方法代码用户版本列表inputraw断言
1条回答
网友
1楼 · 发布于 2024-04-25 04:37:20

类似的内容应满足以下要求:

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使用问题代码中使用的^{},则使用^{}

相关问题 更多 >