반응형
Description:
Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.
For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.
[10, 343445353, 3453445, 3453545353453] should return 3453455.
Solution:
1. Find the two smallest numbers.
2. Returns the sum of two numbers.
def sum_two_smallest_numbers(numbers):
return numbers.pop(numbers.index(min(numbers))) + numbers.pop(numbers.index(min(numbers)))
This time, I solved it using 'pop' for fun.
Find the index of the minimum value and add it by 'pop' it out.
Still, the standard is a method of adding in order after sorting.
The code is more concise and the array operation can be minimized.
def sum_two_smallest_numbers(numbers):
return sum(sorted(numbers)[:2])
반응형
'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글
String ends with? (0) | 2022.04.21 |
---|---|
Remove the minimum (0) | 2022.04.20 |
Square Every Digit (0) | 2022.04.18 |
Sort Numbers (0) | 2022.04.17 |
Regex validate PIN code (0) | 2022.04.16 |