【发布时间】:2019-01-12 10:16:16
【问题描述】:
编写一个程序,要求用户输入 10 个整数,然后打印输入的最大奇数。如果没有输入奇数,它应该打印一条消息。
我需要在不使用数组、异常、导入、列表或 for 循环的情况下执行此操作。只能使用条件和 while 循环。我写了下面的代码,但是我觉得我的算法太冗长了。这个程序可以写得更简洁吗?我的问题的目的是看看是否会有更“Pythonic”的方式来编写相同的程序,我在下面提供了它的代码。
s = (input('Enter 10 numbers: '))
t = '' # initialize empty "number" string
x = len(s)-1
y = 0 # initialize checked integer
z = 0 # initialize preceding integer
i = 0 # initialize counter
while i <= x:
print('i=', i)
while i <= x and s[i] != ' ':
t = t + s[i] # concatenate "string number"
i = i+1
if len(t) > 0: # to not run out of string index
y = int(t)
if y%2 != 0: # compare odd numbers
if y > z:
z = y
if y < z and z%2 == 0: # if y is a negative odd integer
z=y
if i <= x and s[i] == ' ':
i=i+1
t = '' # reset the "number" string
if z == 0:
print('No odd numbers entered')
else:
print('The largest odd number entered is', z)
【问题讨论】:
-
这个问题可能更适合codereview.stackexchange.com
-
低圈复杂度不一定与代码长度有关。如果您试图通过使用单字母变量名称来减少代码长度,请不要这样做,这会使您的代码难以阅读。与其到处使用 cmets,不如试着想出好名字。
-
@user202729 请看我的编辑。
-
比较/算术呢?循环理解?函数
range、filter、map、list? -
@user202729 这些都是不允许的,for 循环也是如此。
标签: python python-3.x algorithm optimization