从输入列表中查找最大数量

时间:2019-04-04 17:47:17

标签: python numbers max

我正在尝试从列表中找到最大数量,但无法在代码中找到逻辑错误

def find_max(numbers):
    data = numbers.split(" ")
    maximum = data[0]
    for number in data:
        if number > maximum:
            maximum = number
        return maximum


number = input("Enter number with space:")
answer = find_max(number)
print(answer)

4 个答案:

答案 0 :(得分:1)

您可以更改

data = numbers.split(" ")

data = map(int, numbers.split(" "))

使其起作用。对于Python 3,您需要

data = list(map(int, numbers.split(" "))

答案 1 :(得分:1)

return语句位于for内,因此它将始终返回第一个输入的数字。另外,您正在将字符串与int进行比较。试试看(这是您自己的代码的一种解决方案,有更好的方法来实现)

def find_max(numbers):
    data = numbers.split(" ")
    maximum = int(data[0])
    for number in data:
        if int(number) > maximum:
            maximum = int(number)
    return maximum


number = input("Enter number with space:")
answer = find_max(number)
print(answer)

答案 2 :(得分:0)

您可以在此处使用max。 您的代码无法正常工作的原因是,您没有将数字转换为整数,它们仍然是脚本中的字符串。

经典方式:

def find_max(numbers):

    # if the list is empty return nothing
    if len(numbers) <= 0:
        return None

    # iterate to find the maximum
    maximum = numbers[0]
    for number in numbers:
        if number > maximum:
            maximum = number

    return maximum


numbers = input("Enter numbers with space:")

# transform the numbers string into a list of strings
numbers = numbers.split(" ")

# prepare numbers by converting them into integers
integers = []
for i in range(len(numbers)):
    number_as_integer = int(numbers[i])
    integers.append(number_as_integer)

# find the max
answer = find_max(integers)
print(answer)

增强的方式:

def find_max(numbers):
    return max(map(int, numbers.split(" ")))


number = input("Enter numbers with space:")
answer = find_max(number)
print(answer)

答案 3 :(得分:0)

发现了问题。 有两个问题。 1)我需要将字符串转换为int 2)我的返回功能应该已经低于for循环。 这是更正的代码

def find_max(numbers):
    data1 = numbers.split(" ")
    data = list(map(int, data1))
    maximum = data[0]
    for number in data:
        if number > maximum:
            maximum = number
    return maximum


number = input("Enter number with space:")
answer = find_max(number)
print(answer)