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

i need to write a function that takes an array of numbers and finds the maximum sum of all the numbers. In other words, I need to find the sum of just the positive numbers. I wrote this, I’m getting «list is out of range»

thoughts?

    def maximum_sub(A):
        x = 0
        i = 0
        for i in A:
            while A[i] > 0:
            x+=A[i]
            i+=1
        return x

asked Oct 27, 2016 at 23:21

SHirsch's user avatar

3

Use super functions and list comprehension instead:

>>> a = [1, 2, 3, -4, 5, -3, 7, 8, 9, 6, 4, -7]
>>> sum(x for x in a if x > 0)
45

[x for x in a if x > 0] will create an array made of the positive values in a.

sum(...) will return the sum of the elements in that array.

answered Oct 27, 2016 at 23:24

Uriel's user avatar

UrielUriel

15.4k6 gold badges24 silver badges46 bronze badges

6

There are better approaches with sums and comprehensions, but I’ll assume you’re writing a function as an exercise in algorithms.

You don’t need the while loop. Use an if to check if it is positive, and add it to the sum. Otherwise, don’t do anything. The for loop will automatically iterate over the values for you.

def maximum_sum(A):
    x = 0
    for i in A:
        if i > 0:
            x += i
    return x

A few words of advice: name things expressively. Here’s some names I might use:

def maximum_sum(arr):
    max_sum = 0
    for num in arr:
        if num > 0:
            max_sum += num
    return max_sum

answered Oct 27, 2016 at 23:31

Jordan McQueen's user avatar

1

0 / 0 / 0

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

Сообщений: 29

1

Вычислить сумму и количество положительных элементов массива

15.10.2018, 18:54. Показов 29747. Ответов 1


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

Вычислить сумму и количество положительных элементов массива X(n), где 1<=n<=100
Буду очень признателен



0



Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

15.10.2018, 18:54

Ответы с готовыми решениями:

Найти сумму и количество положительных элементов массива, предшествующих первому нулевому элементу (C++ -> Python)
int A = {1,2,3,-4,0,6,7,8,9,10};
int sum = 0, count = 0;
for (int i = 0; i &lt; 10; ++i)

Найти сумму и количество положительных элементов, расположенных между минимальным и максимальным элементами массива
/*
Дан массив А(30). Найти сумму и количество положительных элементов,
расположенных между…

Определить количество отрицательных, произведение положительных и количество нулевых элементов массива
Ввести массив, состоящий из 15 элементов целого типа. Определить количество отрицательных,…

В массиве вычислить сумму четных положительных элементов
3. В массиве, содержащем положительные и отрицательные целые числа, вычислить сумму четных…

1

ProgSad

8 / 5 / 7

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

Сообщений: 36

16.10.2018, 14:34

2

Лучший ответ Сообщение было отмечено Kolyanus12 как решение

Решение

Python
1
2
3
4
5
6
7
8
9
X = [1,32,6,-8,-6,8,9] #не полностью понял какой тебе массив нужен, так что поправишь
count = 0
Sum = 0
for i in X:
    if i > 0:
        count += 1
        Sum += i
print('Сумма: ', Sum)
print("Количество: ", count)



1



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

16.10.2018, 14:34

2

@VladHub18

Star

Embed

What would you like to do?

1. Подсчитайте число и сумму положительных, число и произведение отрицательных элементов заданного массива A(N).


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

from random import randint as rnd
A=[rnd(10,10) for i in range(10)]
def sum_pos(A):
k=0
summa=0
for i in range(len(A)):
if A[i]>0:
k+=1
summa+=A[i]
return k,summa
def mult_nigga(A):
n=0
multi=1
for i in range(len(A)):
if A[i]<0:
n+=1
multi*=A[i]
return n,multi
print(A)
print(sum_pos(A))
print(mult_nigga(A))

Ответы

n = int(input(«Введите количество элементов в списке: «))

a = [float(input()) for i in range(n)]

s = 0

for i in range(n):

   if a[i] > 0:

       s += a[i]

print(a)

print(s)


Интересные вопросы

Предмет: Алгебра,
автор: loskarevan80

Предмет: Алгебра,
автор: shocolate121

2. Тему тексту виражатиме заголовок.
А Удосконалюймо себе як особистість.
Б У чому цінність людського життя?
В Мить, що єднає минуле й майбутнє.
Г Не забуваймо батьків.
3. Подане нижче висловлювання належить до…
Гуманітарна аура нації… чи не правда, це приємне для слуху поєднання слів? Справді, кожна нація повинна мати гуманітарну ауру, тобто комплекс наук, що охоплюють усі сфери суспільного життя, включаючи освіту, літературу, мистецтво, у їхній інтегральній причетності до світової культури і, звичайно ж, у своєму неповторно національному варіанті (Л.Костенко)
А Розповіді.
Б Опису.
В Розповіді з елементами опису.
Г Роздуму

Предмет: Алгебра,
автор: nanakiriya

To find the sum of numbers in an iterable in Python, we can

  • Use the built-in sum() function
  • Use a loop
  • Use recursion

In today’s post, we’ll discuss how to use each of the methods above and highlight some of the things to take note when using the built-in sum() function.

For our practice question, we’ll work on a function that accepts multiple inputs (of various data types) and returns the sum of all numerical inputs.

Here are some concepts we’ll cover in today’s post:

  • How to find sum of numbers in an iterable in Python
  • How to use recursion
  • The difference between the sum() and fsum() functions

Using the built-in sum() function

The easiest way to find the sum of numbers in an iterable is to use a built-in function called sum(). This function accepts two arguments – the iterable to sum and an optional value to add to the sum. Its syntax is as follows:

sum(iterable, value_to_add)

If the function is unable to sum the numbers in the iterable, it throws a TypeError exception. Let’s look at some examples:

Finding sum of numbers in a list, set, dictionary and tuple

#Sum numbers in a list
myList = [1, 2, 3.5, 2.1, 6]
print(sum(myList))

#Sum numbers in a set
mySet = {1, 5, 2.7, 8}
print(sum(mySet))

#Sum numbers in a dictionary
myDict = {1:101, 2:102, 3:103, 4:104}
print(sum(myDict))

#Sum numbers in a tuple
myTuple = (1, 2, 6.7, 1.1, 5)
print(sum(myTuple))

If you run the code above, you’ll get the following output:

14.6
16.7
10
15.799999999999999

The sum() function adds the numbers in an iterable and returns the result.

For instance, in the first example, the function adds the numbers in myList (1 + 2 + 3.5 + 2.1 + 6) and returns 14.6 as the result.

In the second example, the function adds the numbers in mySet (1 + 5 + 2.7 + 8) and returns 16.7 as the result.

In the third example, we pass a dictionary to the sum() function. When we do that, the function sums the keys of the dictionary, not the values. Hence, we get 1 + 2 + 3 + 4 = 10 as the result.

Finally, in the fourth example, the function sums the values in myTuple and returns the result. However, notice that the result is not exact? Instead of getting 1 + 2 + 6.7 + 1.1 + 5 = 15.8, we get 15.799999999999999.

This is not due to a bug in our code or in Python. Rather, it has to do with the way floating-point numbers (i.e. numbers with decimal parts) are represented in our computers. We’ve seen another example of this issue previously when we learned to square a number in Python.

If you are interested in finding out more about how floating-point numbers work, you can check out the following website: https://docs.python.org/3/tutorial/floatingpoint.html

If you need to ensure that you always get an exact result when finding the sum of floating-point numbers, you can use another function called fsum(). We’ll discuss this function in a later section.

Passing a second argument to the sum() function

Next, let’s look at an example of how the second argument for the sum() function works.

If we do not pass any value for the second argument, the sum() function simply adds the numbers in the iterable and returns the result. However, if we pass a value for the second argument, the function adds the value of the argument to the sum of numbers in the iterable. Let’s look at an example:

myList = [1, 2, 3.5, 2.1, 6]

#Without second argument
print(sum(myList))

#With second argument
print(sum(myList, 1000))

If you run the code above, you’ll get the following output:

14.6
1014.6

Passing invalid arguments to the sum() function

Last but not least, let’s look at what happens when we pass an invalid argument to the sum() function.

When that happens, the function throws a TypeError exception. Examples of invalid arguments include passing a string to the function, or passing a list that includes strings as elements.

For instance, the examples below will all give us a TypeError exception if we try to run them.

myString = '123456'
print(sum(myString))

myStrList = [1, 2, 3, '4', 5]
print(sum(myStrList))

myList = [1, 2, 3.5, 2.1, 6]
print(sum(myList, '100'))

myList2 = [1, 2, 3, 4, [1, 5]]
print(sum(myList2))

The first three examples fail as the sum() function does not work with strings. If we pass a string to the function, the function throws an exception. The last example fails as myList2 contains a nested list.

Using a loop

Now that we are familiar with the built-in sum() function, let’s proceed to discuss how we can use a loop to find the sum of numbers in an iterable.

The code below shows an example of using a for loop to sum the numbers in a list:

myList = [1, 2, 3.5, 2.1, 6]
sum = 0

for i in myList:
    sum += i

print(sum)

On lines 1 and 2, we declare and initialize two variables – myList and sum.

Next, we use a for loop to iterate through myList. For each element in myList, we add its value to sum (on line 5).

After we finish iterating through myList, we use the print() function (outside the for loop) to print the value of sum.

If you run the code above, you’ll get

14.6

as the output.

Using a for loop gives us more flexibility in terms of what we want to sum. For instance, if we use the built-in sum() function to sum the elements in a dictionary, it returns the sum of the keys in the dictionary. If we want to sum the values instead, we can use a for loop:

myDict = {1:101, 2:102, 3:103, 4:104}
sum = 0

for i in myDict:
    sum += myDict[i]

print(sum)

When we use a for loop to iterate through a dictionary, Python accesses the key of the items in the dictionary, not the value. For instance, in the for loop above, i stores the keys of the items in myDict.

If we want to sum the values of the items, we need to add myDict[i] (instead of i) to sum, as shown in line 5 above.

If you run the code above, you’ll get the following output:

410

The loop sums the values in myDict. Hence, we get 101 + 102 + 103 + 104 = 410 as the output.

Using recursion

Next, let’s discuss the final method to find the sum of numbers in an iterable. This method involves using recursion. We’ve discussed recursion multiple times in previous posts. If you are not familiar with recursion, you should definitely check out some of those posts (e.g. here and here).

Technically speaking, using recursion is kind of unnecessary in this case, as using the built-in sum() function or a simple loop is much more straightforward. However, recursion can be a very powerful technique for solving more complex questions like a Sudoku or permutation problem. Hence, it helps to see more examples of how recursion works, especially with easier questions like the current one.

As mentioned previously, recursion can be used to solve problems where solution to the problem relies on solving smaller instances of the same problem.

When it comes to finding the sum of numbers in an iterable, suppose we have a list with five numbers. We can find the sum of all five numbers by adding the first number to the sum of the remaining four numbers (a smaller instance of the same problem).

This can be easily implemented using recursion.

myList = [1, 2, 3.5]

def sumRec(iterToSum):
    if len(iterToSum) > 1:
        return iterToSum [0] + sumRec(iterToSum [1:])
    else:
        return iterToSum [0]

print(sumRec(myList))

Here, we first declare and initialize a list called myList.

Next, we define a function called sumRec() (from lines 3 to 7) that has one parameter – iterToSum.

Inside the function, we check if the length of iterToSum is greater than 1 (line 4). If it is, we add the first element in iterToSum (i.e. iterToSum [0]) to the result of sumRec(iterToSum[1:]) and return the sum (line 5).

sumRec(iterToSum[1:]) represents a smaller instance of sumRec(iterToSum).

While the latter sums all numbers in iterToSum, the former sums all elements except the first (as the slice [1:] selects all elements starting from index 1 to the end of the list).

We keep calling the sumRec() function recursively until the length of the list we pass to it is no longer greater than 1. When that happens, we have what is known as a base case (lines 6 and 7).

A base case is the case the stops the recursion. When the length of the list to sum is no longer greater than 1, we do not need to use recursion to find the sum of the elements in the list. As there is only one element in the list now, the sum is simply the number itself. For instance, the sum of [12] is simply 12.

Once we reach the base case, the recursion stops and the result is returned to the caller of each recursive call. This gives us the result of the sum of all numbers in the list.

To see how this works, let’s suppose we call the sumRec() function with [1, 2, 3.5] as the argument.

The recursive calls and return values are shown in the diagram below:

recursive function to find sum of numbers in iterable

Line 9 starts by calling sumRec([1, 2, 3.5]), which in turn calls sumRec([2, 3.5]), which calls sumRec([3.5]).

sumRec([3.5]) is the base case. It returns 3.5 to its caller sumRec([2, 3.5]).

sumRec([2, 3.5]) (which is not a base case) in turn returns 2 + sumRec([3.5]) = 2 + 3.5 = 5.5 to its caller sumRec([1, 2, 3.5]).

sumRec([1, 2, 3.5]) (which is also not a base case) returns 1 + sumRec([2, 3.5]) = 1 + 5.5 = 6.5 to its caller line 9.

Therefore, if you run the code above, you’ll get

6.5

as the output.

That’s it. That’s how recursion can be used to help us find the sum of numbers in an iterable. You may need to read through this section more than once to fully appreciate how recursion works.

Working with floating-point numbers

We’ve covered three main ways to find the sum of numbers in an iterable in Python. Now, let’s move on to a topic we skipped previously.

In the previous section, we learned to use the built-in sum() function to sum numbers in an iterable. While this function is very easy to use, we saw that it does not always return an exact value. For instance, when we pass the tuple (1, 2, 6.7, 1.1, 5) to the function, we get 15.799999999999999 as the output.

If it is crucial for us to get an exact answer when finding the sum of numbers in an iterable, we should use another built-in function – fsum().

This function is available in the math module.

Let’s look at an example:

import math

myTuple = (1, 2, 6.7, 1.1, 5)

#Using sum()
print(sum(myTuple))

#Using fsum()
print(math.fsum(myTuple))

If you run the code above, you’ll get the following output:

15.799999999999999
15.8

The fsum() is very similar to the sum() function. The main difference is that the fsum() function gives an exact output while the sum() function does not always do that.

Another difference is the fsum() does not have a second optional argument. Other than that, the two functions are very similar.

That’s it. We are now ready to proceed to the practice question for today.

Practice Question

Today’s practice question requires us to write a function called mySum() that prompts users to enter a list of values, separated by commas. The values entered can be of any data type. For instance, they can be text, symbols, or numbers. The function needs to return the sum of all the numbers entered. This sum should be rounded off to 2 decimal places.

Expected Results

To test your function, you can run the function and enter the following inputs:

1, 2, 3.1, 4, hello, [2, 3], #, $

The function should return 10.1 as the result.

Suggested Solution

The suggested solution is as follows:

Click to see the suggested solution

def mySum():
    userInput = input('Pleae enter the values, separated by commas: ')
    myList = userInput.split(',')

    result = 0

    for i in myList:
        try:
            result += float(i)
        except:
            pass

    return round(result, 2)

sumOfNumbers = mySum()
print(sumOfNumbers)

In the code above, we first define a function called mySum() on line 1.

Inside the function, we use the built-in input() function to prompt users for an input. This function prompts users for an input and returns the input as a string. We store this string in a variable called userInput.

Next, we use a built-in function called split() to split userInput into a list of substrings, using a comma (https://docs.python.org/3/library/stdtypes.html#str.split) as the delimiter. If the input string is '1, 2, 3, 4, 5', we’ll get ['1', ' 2', ' 3', ' 4', ' 5'] as the result, which we store in a variable called myList.

Next, we declare and initialise a variable called result.

We then use a for loop to iterate through myList.

Inside the for loop, we use a try-except statement to try converting i to a float. If that can be done, we add the value of the resulting float to result (line 9).

On the other hand, if i cannot be converted to a float, the float() function throws an exception and the except block is executed. Inside the except block (lines 10 to 11), we use the pass statement to indicate that we do not want to do anything when i cannot be converted to a float.

After we finish iterating through all the elements in myList, we use the round() function to round the sum to 2 decimal places and use the return statement to return the result.

With that, the function is complete.

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