Task: In a list filled with random numbers you need to count:
- A sum of negative numbers
- A sum of even numbers
- A sum of odd numbers
- A product of elements with indexes that multiple 3
- A product of elements between min and max element
- A sum of elements, which located between first and last element
I can’t figure out how to solve last two issues
The code I have so far:
import random size = int(input('Enter the size of a list: ')) begin = int(input('Enter the beginning of a list: ')) end = int(input('Enter the end of a list: ')) my_list = list() for i in range(size): my_list.append(random.randint(begin, end)) for i in range(0, len(my_list)): print(f'{my_list[i]}[{i}]', end=' ') print() mul = 1 for i in range(0, len(my_list), 3): print(f'{mul} * {my_list[i]}[{i}] = ', end=' ') mul *= my_list[i] print(mul) sum_list = [0] * 3 for item in my_list: if item < 0: sum_list[0] += item if item % 2 == 0: sum_list[1] += item if item % 2 != 0: sum_list[2] += item print(f'Sum negative: {sum_list[0]}') print(f'Sum even: {sum_list[1]}') print(f'Sum odd: {sum_list[2]}') print(f'Mul even 3 index: {mul}')
Advertisement
Answer
A product of elements between min and max element
For this task, you can use .sort() method of the “list” object to sort it in-place then use list indexes to exclude the first and last item (min and max because it is sorted) and then use math.prod to calculate the product of rest
import math my_list.sort() math.prod(my_list[1:-1]) if len(my_list) > 2 else 0
A sum of elements, which located between the first and last element
Use list indexes to get the remaining elements and sum() them
sum(my_list[1:-1]) if len(my_list) > 2 else 0 # we need to check if list is long enough