【问题标题】:Largest odd number Python code simplification最大奇数 Python 代码简化
【发布时间】: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 请看我的编辑。
  • 比较/算术呢?循环理解?函数rangefiltermaplist?
  • @user202729 这些都是不允许的,for 循环也是如此。

标签: python python-3.x algorithm optimization


【解决方案1】:

这是我对 Guttag 的手指练习的解决方案,第 2 章。如果输入一个或多个条目为空白,则以下代码也有效。

def max_odd():
    """Returns largest odd number from given 10 numbers by the use.
    if the input is not valid, the message is displayed to enter valid numbers"""
    x = [input('Enter a value: ') for i in range(10)]
    x = [int(i) for i in x if i]
    if x:
        try:
            x = [i for i in x if i%2 != 0]
            return(max(x))
        except:
            return('All even numbers provided.')
    else:
        return('Please enter a valid input')

【讨论】:

    【解决方案2】:

    如果您将它们全部输入一行,那么您可以简单地 max()split() 加上一个守卫,如果没有任何东西通过守卫,则捕获异常,例如:

    In []:
    msg = 'Enter 10 numbers: '
    try:
        print('Max odd number:', max(int(n) for n in input(msg).split() if int(n)%2))
    except ValueError:
        print('No odd number entered')
    
    # 2 2 2 2 2 2 2 2 4 2
    Out[]:
    No odd number entered
    
    # 2 2 2 2 2 3 2 2 5 2
    Out[]:
    Max odd number: 5
    

    for 循环中的相同逻辑没有例外:

    m = None
    for n in input('Enter 10 numbers: ').split():
        n = int(n)
        if n % 2:
            m = max(m, n) if m else n
    
    if m:
        print('Max odd number:', m)
    else:
        print('No odd number entered')
    

    【讨论】:

    • 不幸的是,该练习中不允许有例外(本书尚未介绍)。
    【解决方案3】:

    假设您的输入是一个由 10 个数字组成的字符串,即“3265491232”,

    from sys import maxsize
    
    string = input("Enter 10 numbers consecutively as a string :\n")
    
    if len(string) != 10:
        print("There should be 10 numbers. Please enter input again")
    
    max_odd_number = -maxsize # set it to the maximum negative value
    hasOdd = False # to check if input has any odd numbers 
    
    for number in string:
        if int(number) % 2 != 0: # if number in string is an odd number
            hasOdd = True
            if int(number) > max_odd_number: # if current number is greater than the current max odd number previously saved
                max_odd_number = int(number)
    if hasOdd:
        print("Max odd number: " + str(max_odd_number))
    else:
        print ("No odd number in input string")
    

    【讨论】:

    • 仅供参考:Python 中的注释以 # 开头。
    【解决方案4】:
    read_count = 0
    largest_odd = None
    
    while read_count < 10:
        user_input = input('Enter any number')
    
        try:
            user_input = int(input('Enter a number'))
        except ValueError:
            print("user input {} is not a number".format(user_input))
            continue
    
        if user_input & 1:
            if largest_odd is None:
                largest_odd = user_input
            largest_odd = max(largest_odd, user_input)
    
        read_count += 1
    
    if largest_odd is None:
        print("No odd numbers found")
    else:
        print("Largest odd number found was {}".format(largest_odd))
    

    现在让我们稍微剖析一下,我们声明了变量read_countlargest_odd 来跟踪我们看到了多少个数字以及最大的奇数是多少。 请注意,我特别选择在我们看不到奇数的情况下创建largest_odd = None

    接下来,我们循环,直到用户输入有效数字 10 次。

    try-catch 逻辑对你来说有点矫枉过正,但它有助于防止程序因用户输入错误而崩溃。尝试打开 Python shell 并运行 int('x')。你会明白为什么我想在这样做之后抓住ValueError

    起初,if user_input &amp; 1 行可能会令人困惑,但它是确定数字是否为奇数的一种非常快速的方法。当然,您可以使用user_input % 2 == 1,但您真正需要检查的是是否设置了第一个(最低有效位或 LSB),我们使用带有数字1 的按位AND

    【讨论】:

    • 如果我输入所有偶数这将不起作用,您需要将if user_input is None:更改为if largest_odd is None:
    猜你喜欢
    • 1970-01-01
    • 2015-01-16
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    相关资源
    最近更新 更多