Как найти сумму отрицательных элементов массива питон

numbers = [-2, -4, -5, 20, 18]
i = len(numbers) 
total = 0
while i >= 0 and numbers[i] < 0: 
    total += numbers[i]
    i -= 1
    print (total)

Выдаёт ошибку в 4 строке list index out of range, но i изначально равен 5, да и второе условие соблюдается. Что не так, подскажите.

Всем спасибо, решил так:

numbers = [-2, -4, -5, 20, 18]
i = 0
total = 0
while i < len(numbers) and numbers[i] < 0:
total = total + numbers[i]
i = i + 1
print(total)

задан 5 фев 2022 в 14:13

Артур's user avatar

АртурАртур

114 бронзовых знака

2

numbers = [-2, -4, -5, 20, 18]
numbers.sort()

res = 0
i = 0

while i < len(numbers):
    if numbers[i] < 0:
        res += numbers[i]
    else:
        break
    i += 1
print(res)
#-11

ответ дан 5 фев 2022 в 16:28

Anatoly Kritskiy's user avatar

3

индексы в python идут от нуля, следовательно, в вашем массиве максимальным индексом может быть только 4, поэтому у вас происходит выход за границы массива.

numbers = [-2, -4, -5, 20, 18]
numbers = sorted(numbers)
i = 0
total = 0
while numbers[i] < 0: 
    total += numbers[i]
    i += 1
    print(total)

либо сделать так:

numbers = [-2, -4, -5, 20, 18]
numbers = sort(numbers)
total = 0

for n in numbers:
    if n < 0:
        total += n
        print(total)
    else:
        break

ответ дан 5 фев 2022 в 14:34

zolars's user avatar

zolarszolars

5971 серебряный знак16 бронзовых знаков

9

numbers = [-2, -4, -5, 20, 18]
total = 0
i = len(numbers) - 1
while i >= 0:
    if numbers[i] < 0:
        total += numbers[i]
    else:
        break
    i -= 1
print(total)

ответ дан 5 фев 2022 в 14:58

Coder69's user avatar

1

Rbnvlad10

0 / 0 / 0

Регистрация: 27.11.2020

Сообщений: 43

1

Найти сумму отрицательных элементов массива

20.01.2021, 18:19. Показов 8319. Ответов 4

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Найти сумму отрицательных элементов массива. Необходимо ввести кол-во элементов и ввести элементы массива с клавиатуры. Помогите найти ошибку, пожалуйста. Пишет, что сумма элементов массива = 0. КОД ПРОГРАММЫ:

Python
1
2
3
4
5
6
7
8
9
10
n = int(input('Введите количество элементов: '))
nums = []
for i in range(n):
    num = int(input('a[' + str(i) + '] = '))
    nums.append(num)
sum = 0
for i in range(n):
    if i < 0:
        sum += i
print('Сумма отрицательных элементов массива: ', sum)



0



3484 / 2092 / 560

Регистрация: 02.09.2015

Сообщений: 5,336

20.01.2021, 18:21

2

Цитата
Сообщение от Rbnvlad10
Посмотреть сообщение

if i < 0:

Условие никогда не выполнится.



1



Fury67

Заяц, просто Заяц.

663 / 277 / 155

Регистрация: 12.11.2017

Сообщений: 866

20.01.2021, 18:23

3

Цитата
Сообщение от Rbnvlad10
Посмотреть сообщение

for i in range(n):

Надо:

Python
1
for i in nums:



1



Fudthhh

Модератор

Эксперт Python

2872 / 1573 / 510

Регистрация: 21.02.2017

Сообщений: 4,197

Записей в блоге: 1

21.01.2021, 13:36

4

Rbnvlad10,

Python
1
print("Сумма отрицательных элементов массива:", sum(filter(lambda num: num < 0, (int(input()) for _ in range(int(input("Введите количество элементов: ")))))))



0



iSmokeJC

Am I evil? Yes, I am!

Эксперт PythonЭксперт Java

16273 / 9029 / 2605

Регистрация: 21.10.2017

Сообщений: 20,734

21.01.2021, 20:18

5

Python
1
2
3
4
5
import re
 
n = input('Введите элементы через пробел: ')
result = sum(map(int, re.findall(r"-d+", n)))
print(f'Сумма отрицательных элементов массива: {result}')



1



Given a list. The task is to find the sum of Negative, Positive Even, and Positive Odd numbers present in the List.

Examples:

Input: -7 5 60 -34 1 
Output: 
Sum of negative numbers is  -41 
Sum of even positive numbers is  60 
Sum of odd positive numbers is  6

Input: 1 -1 50 -2 0 -3
Output:
Sum of negative numbers is  -6
Sum of even positive numbers is  50
Sum of odd positive numbers is  1

Negative numbers are the numbers less than 0 while positive even numbers are numbers greater than 0 and also divisible by 2. 0 is assumed to be a positive even number, in this case. 

Approach:

  • The first approach input a list of numbers from the user.
  • Two loops are run, one for the positive numbers and the other for the negative numbers, computing the numbers’ summation.
  • If n is the size of the list of numbers,
  • it takes O(2n) time complexity, for iterating over the list of numbers twice.

Python3

class Sumofnumbers:

    def negSum(self, list):

        neg_sum = 0

        for num in list:

            num = int(num)

            if(num < 0):

                neg_sum = neg_sum + num

        print("Sum of negative numbers is ", neg_sum)

    def posSum(self, list):

        pos_even_sum = 0

        pos_odd_sum = 0

        for num in list:

            num = int(num)

            if(num >= 0):

                if(num % 2 == 0):

                    pos_even_sum = pos_even_sum + num

                else:

                    pos_odd_sum = pos_odd_sum + num

        print("Sum of even positive numbers is ",

              pos_even_sum)

        print("Sum of odd positive numbers is ",

              pos_odd_sum)

list_num = [-7, 5, 60, -34, 1]

obj = Sumofnumbers()

obj.negSum(list_num)

obj.posSum(list_num)

Output

Sum of negative numbers is  -41
Sum of even positive numbers is  60
Sum of odd positive numbers is  6

The second approach computes the sum of respective numbers in a single loop. It maintains three counters for each of the three conditions, checks the condition and accordingly adds the value of the number in the current sum . If n is the size of the list of numbers, it takes O(n) time complexity, for iterating over the list of numbers once. 

Space complexity:
The space complexity of the Sumofnumbers class is O(1). This is because the class does not store any additional data and only uses the given list as an input.

Python3

class Sumofnumbers:

    def Sum(self, list):

        neg_sum = 0

        pos_even_sum = 0

        pos_odd_sum = 0

        for num in list:

            num = int(num)

            if(num < 0):

                neg_sum = neg_sum + num

            else:

                if(num % 2 == 0):

                    pos_even_sum = pos_even_sum + num

                else:

                    pos_odd_sum = pos_odd_sum+num

        print("Sum of negative numbers is ",

              neg_sum)

        print("Sum of even positive numbers is ",

              pos_even_sum)

        print("Sum of odd positive numbers is ",

              pos_odd_sum)

list_num = [1, -1, 50, -2, 0, -3]

obj = Sumofnumbers()

obj.Sum(list_num)

Output

Sum of negative numbers is  -6
Sum of even positive numbers is  50
Sum of odd positive numbers is  1

Time Complexity: O(n) ,The time complexity of this algorithm is O(n) as it loops over all the numbers in the list and checks each of them to determine whether they are negative, even, or odd.

Space Complexity: O(1) ,The space complexity of this algorithm is O(1) as we are not creating any additional data structures or arrays. We are simply keeping track of the sums of all the numbers in the list and updating them as we loop through the list.

Method: Using list comprehension 

Python3

lst = [1, -1, 50, -2, 0, -3];i=0

x=[i for i in lst if i>0 and i%2==0]

y=[i for i in lst if i>0 and i%2!=0]

z=[i for i in lst if i<0]

print("even positive numbers sum",sum(x))

print("odd positive numbers sum",sum(y))

print("negative numbers sum",sum(z))

Output

even positive numbers sum 50
odd positive numbers sum 1
negative numbers sum -6

Time Complexity: O(n)
Auxiliary Space: O(n)

Method: Using the lambda function 

Python3

lst = [1, -1, 50, -2, 0, -3]

x=list(filter(lambda i: (i>0 and i%2==0),lst))

y=list(filter(lambda i: (i>0 and i%2!=0),lst))

z=list(filter(lambda i: (i<0),lst))

print("even positive numbers sum",sum(x))

print("odd positive numbers sum",sum(y))

print("negative numbers sum",sum(z))

Output

even positive numbers sum 50
odd positive numbers sum 1
negative numbers sum -6

The time complexity of the code is O(n), where n is the length of the input list lst. 

The auxiliary space complexity of the code is O(n), where n is the length of the input list lst.

Method: Using enumerate function

Python3

lst = ['1', '-1', '50', '-2',' 0', '-3']

x=[int(i) for a,i in enumerate(lst) if int(i)%2==0 and int(i)>0]

y=[int(i) for a,i in enumerate(lst) if int(i)%2!=0 and int(i)>0]

z=[int(i) for a,i in enumerate(lst) if int(i)<0]

print("even positive numbers sum",sum(x))

print("odd positive numbers sum",sum(y))

print("negative numbers sum",sum(z))

Output

even positive numbers sum 50
odd positive numbers sum 1
negative numbers sum -6

Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of list.

Method: Using recursion

Python3

def recursive_sum(lst, i=0, x=[], y=[], z=[]):

    if i == len(lst):

        return (sum(x), sum(y), sum(z))

    elif lst[i] > 0 and lst[i] % 2 == 0:

        x.append(lst[i])

    elif lst[i] > 0 and lst[i] % 2 != 0:

        y.append(lst[i])

    elif lst[i] < 0:

        z.append(lst[i])

    return recursive_sum(lst, i+1, x, y, z)

lst = [1, -1, 50, -2, 0, -3]

x,y,z = recursive_sum(lst)

print("even positive numbers sum",x)

print("odd positive numbers sum",y)

print("negative numbers sum",z)

Output

even positive numbers sum 50
odd positive numbers sum 1
negative numbers sum -6

Time Complexity: O(n), because n recursive calls are made. 
Auxiliary Space: O(n), because of n recursive calls are made and each recursive call is pushed into stack.

Method: Using reduce from the functools module

Python3

from functools import reduce

lst = [1, -1, 50, -2, 0, -3]

def filter_and_sum(lst, condition):

    filtered = list(filter(condition, lst))

    return reduce(lambda x, y: x + y, filtered)

x = filter_and_sum(lst, lambda num: num > 0 and num % 2 == 0)

y = filter_and_sum(lst, lambda num: num > 0 and num % 2 != 0)

z = filter_and_sum(lst, lambda num: num < 0)

print("even positive numbers sum", x)

print("odd positive numbers sum", y)

print("negative numbers sum", z)

Output

even positive numbers sum 50
odd positive numbers sum 1
negative numbers sum -6

Time Complexity: O(n)

Auxiliary Space: O(n)

Last Updated :
06 Apr, 2023

Like Article

Save Article

В этой статье мы разберем  решение задач с номером 25 егэ по информатике на тему массивы с накопителем на языке программирования python

  В задачах в егэ по информатике на массивы с накопителем  необходимо написать программу, которая бы вводила массив с клавиатуры, рассчитывала сумму элементов или среднее арифметическое элементов массива , которые удовлетворяли бы определённому условию. Например , рассчитать сумму четных элементов массива или сумму  отрицательных элементов массива. Разберем общий алгоритм решения задач на поиск суммы элементов массива на Python, на примере поиска суммы отрицательных элементов массива.
Вначале программы необходимо организовать ввод массива, подробно о вводе массива с клавиатуры в Python
a = []
n=int(input(‘введите длину массива’))
for i in range(0, n):
    a.append(int(input()))

В программе мы должны ввести переменную summa, которая отвечает за подсчет суммы. Сумма обнуляется перед расчетом. Анализ элементов массива и подсчет суммы производится в цикле for. 
summa=0
for i in range(0, n):

В цикле с помощью оператора условия в python  if необходимо проверять элементы на соблюдение необходимого условия. В нашем примере необходимо проверять отрицательный ли элемент массива и если он отрицательный, то прибавлять его к искомой сумме.
for i in range(0, n):
    if a[i]<0:
        summa=summa+a[i]

При выводе результата на экран необходимо проанализировать с помощью оператора условия if  наличие отрицательных элементов. Если сумма отрицательная, то отрицательные элементы есть в массиве, если сумма осталась раной нулю, то отрицательных элементов нет в массиве
if summa<0:
    print(‘сумма отрицательных элементов’,summa) 
else:
    print(‘отрицательных элементов нет’)

Полная программа на Python для решения задачи с номером 25 егэ по информатике на тему массивы, которая подсчитывает сумму отрицательных элементов массива.
a = []
n=int(input(‘введите длину массива’))
for i in range(0, n):
    a.append(int(input()))
summa=0
for i in range(0, n):
    if a[i]<0:
        summa=summa+a[i]
if summa<0:
    print(‘сумма отрицательных элементов’,summa) 
else:
    print(‘отрицательных элементов нет’)

Разберем примеры программы на Python для решения задачи с номером 25 егэ по информатике на тему массивы 
Дан целочисленный массив из 10 элементов. Элементы массива могут принимать значения от 0 до 100. Нужно написать программу на python, которая позволяет подсчитать и вывести среднее арифметическое элементов массива, имеющих нечетное значение
Аналогично предыдущему примеру организуем ввод массива. В данной задаче длину массива не нужно вводить с клавиатуры, она фиксированная n=10, также вводится переменная k для подсчета количества нечетных элементов
a = []
n=10
k=0
for i in range(0, n):
    a.append(int(input()))

Для подсчета среднего арифметического необходимо знать сумму и количество элементов. Среднее арифметическое = сумма элементов/количество элементов
Чтобы подсчитать сумму нечетных элементов массива в цикле for необходимо проверить на нечетность каждый элемент массива  с помощью условия if a[i]%2==1: Если элемент массива нечетный, то он прибавляется к сумме, также необходимо увеличить счетчик нечетных чисел
summa=0
for i in range(0, n):
    if a[i]%2==1:
        summa=summa+a[i]
        k=k+1

Полная программа на Python для решения задачи с номером 25 егэ по информатике, которая подсчитывает среднее арифметическое нечетных элементов массива
a = []
n=10
for i in range(0, n):
    a.append(int(input()))
summa=0
k=0
for i in range(0, n):
    if a[i]%2==1:
        summa=summa+a[i]
        k=k+1
print(‘среднее арифметическое нечетных элементов ‘,summa/k)
 

Перейти к курсу по python

Полезно почитать по теме решение на python задач с номером 25 егэ по информатике на тему массивы

Решение задач на python на пары элементов массива

Поделиться

Комментарии ()

Нет комментариев. Ваш будет первым!

Есть такой массив

a = [-1.1, -1, 0.1, 1, -2.1, -2, 0.2, 2, -3.1, -3, 0.3]

из него с помощью цикла for (и без numpy) надо вывести:

  1. Сумму целых отрицательных чисел: (-1)+(-2)+(-3) = -6
  2. Количество чисел в диапазоне 0..1: 0.1, 0.2, 0.3 = 3

Я новичок в Python и уже как не пытался, могу только найти сумму всех отрицательных чисел, но ЦЕЛЫХ отрицательных не могу

Понравилась статья? Поделить с друзьями:
  • Как найти модуль маг индукции
  • Как составить легенду самим
  • После копчения сало горчит как исправить
  • Как найти автонастройки каналов
  • Как исправить свой отзыв на яндексе