To solve this problem, we need to compute the sum of all even numbers from a given list of integers.
Approach
- Read Input: First, we read the input line which contains space-separated integers.
- Convert to Integer List: Convert the input string into a list of integers.
- Filter Even Numbers: Use a generator expression to filter out even numbers from the list (a number is even if it is divisible by 2 with no remainder).
- Sum Even Numbers: Calculate the sum of the filtered even numbers.
- Output Result: Print the computed sum.
Solution Code
nums = list(map(int, input().split()))
print(sum(x for x in nums if x % 2 == 0))
Explanation
- Reading Input: The
input().split()method reads the input line and splits it into a list of strings. - Converting to Integers: The
map(int, ...)function converts each string in the list to an integer, andlist(...)converts the result into a list of integers. - Filtering Even Numbers: The generator expression
(x for x in nums if x % 2 == 0)iterates over each number in the list and includes only those numbers that are even. - Summing Even Numbers: The
sum()function computes the sum of the even numbers from the generator expression. - Output: The result is printed directly, which is the sum of all even numbers in the input list.
This approach is efficient and concise, leveraging Python's built-in functions to handle the operations with minimal code. The time complexity is O(n) where n is the number of elements in the input list, as we process each element exactly once. The space complexity is O(1) if we consider the generator expression (since it doesn't store all even numbers in memory at once), making it memory efficient.


作者声明:本文包含人工智能生成内容。