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)
解决方案
像这样的东西应该满足要求:
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()
.
推荐阅读
- c++ - 只有 2 和 5 作为数字的特殊数字
- html - 似乎无法让我的 css 网格在整个页面宽度上拉伸
- c++ - 如何知道 Visual Studio 的构建命令是什么?
- javascript - 如何维护每个输入文本的消息位置?
- spring - Springboot 2.3.x 应用程序在启动时卡住
- python - 使用 Beautiful Soup 从 HTML 标签中提取数据
- python - 未找到 MySQL.connector 模块
- postgresql - Postgres:附加到大型 jsonb 数组是否昂贵?
- sql - 如何编写一个 sql where 过滤器,它将返回时间戳大于给定日期和时间的行?
- batch-file - 如何编写一个 Windows 批处理文件,通过数值更新文件夹中的所有文件名?