본문 바로가기
나는 이렇게 학습한다/Algorithm & SQL

Even numbers in an array

by daco2020 2022. 5. 6.

Given an array of numbers, return a new array of length number containing the last even numbers from the original array (in the same order). The original array will be not empty and will contain at least "number" even numbers.

 

For example:

([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) => [4, 6, 8]
([-22, 5, 3, 11, 26, -6, -7, -8, -9, -8, 26], 2) => [-8, 26]
([6, -25, 3, 7, 5, 5, 7, -3, 23], 1) => [6]

 

 

Solution:

1. Find an even number among the elements.
2. Cut 'n' from the end and return it.

 

def even_numbers(arr,n):
    return [i for i in arr if not i % 2][-n:]