简体   繁体   中英

The fastest and most efficient way to get max number from a list of numbers

How can I improve the code and make it the fastest and most efficient way to take 10 numbers from the user, and then calculate the highest number from the list? It can be anything, Pythonic, etc..

I have this code, and I want you please to improve it.

numbers = []
for _ in range(11):
    numbers.append(input('Enter Num: '))

result = max(numbers)
print(result)

I have not included the program execution time because I'm taking inputs.

Most compact way I could think of:

result = max([input("Enter num: ") for _ in range(11)])
print(result)

You can simply:

max = 0
for _ in range(11):
    next = input('Enter Num: ')
    if next > max:
        max = next
print(max)
numbers = []
for _ in range(11):
    numbers.append(input('Enter Num: ')
numbers.sort() 
print("Largest element is:", numbers[-1]) 
numbers = raw_input("Enter 10 numbers seperated by a comma (IE 1,2,3,..,..): ")
numbers = [int(i) for i in numbers.split(",")]
results = set()
for _ in range(len(numbers)+1):
    results.add(_)
print(max(results))

Demo:

 >>> numbers = raw_input("Enter 10 numbers seperated by a comma (IE 1,2,3,..,..): ")
Enter 10 numbers seperated by a comma (IE 1,2,3,..,..): 1,2,3,4,5,6,7,8,9,10
>>> numbers = [int(i) for i in numbers.split(",")]
>>> results = set()
>>> for _ in range(len(numbers)+1):
...     results.add(_)
...
>>> results
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> print(list(results).sort())
None
>>> print(max(results))
10
>>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM