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:
JavaScript
x
36
36
1
import random
2
3
size = int(input('Enter the size of a list: '))
4
begin = int(input('Enter the beginning of a list: '))
5
end = int(input('Enter the end of a list: '))
6
7
my_list = list()
8
for i in range(size):
9
my_list.append(random.randint(begin, end))
10
11
for i in range(0, len(my_list)):
12
print(f'{my_list[i]}[{i}]', end=' ')
13
print()
14
15
mul = 1
16
for i in range(0, len(my_list), 3):
17
print(f'{mul} * {my_list[i]}[{i}] = ', end=' ')
18
mul *= my_list[i]
19
print(mul)
20
21
sum_list = [0] * 3
22
23
for item in my_list:
24
if item < 0:
25
sum_list[0] += item
26
if item % 2 == 0:
27
sum_list[1] += item
28
if item % 2 != 0:
29
sum_list[2] += item
30
31
print(f'Sum negative: {sum_list[0]}')
32
print(f'Sum even: {sum_list[1]}')
33
print(f'Sum odd: {sum_list[2]}')
34
print(f'Mul even 3 index: {mul}')
35
36
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
JavaScript
1
4
1
import math
2
my_list.sort()
3
math.prod(my_list[1:-1]) if len(my_list) > 2 else 0
4
A sum of elements, which located between the first and last element
Use list indexes to get the remaining elements and sum() them
JavaScript
1
2
1
sum(my_list[1:-1]) if len(my_list) > 2 else 0 # we need to check if list is long enough
2