|
0 / 0 / 0 Регистрация: 19.09.2018 Сообщений: 29 |
|
|
1 |
|
Вычислить сумму и количество положительных элементов массива15.10.2018, 18:54. Показов 29750. Ответов 1
Вычислить сумму и количество положительных элементов массива X(n), где 1<=n<=100
0 |
|
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
15.10.2018, 18:54 |
|
Ответы с готовыми решениями:
В массиве вычислить сумму четных положительных элементов 1 |
|
ProgSad 8 / 5 / 7 Регистрация: 15.02.2018 Сообщений: 36 |
||||
|
16.10.2018, 14:34 |
2 |
|||
|
Решение
1 |
|
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
16.10.2018, 14:34 |
|
2 |
Given a list of numbers, write a Python program to count positive and negative numbers in a List.
Example:
Input: list1 = [2, -7, 5, -64, -14] Output: pos = 2, neg = 3 Input: list2 = [-12, 14, 95, 3] Output: pos = 3, neg = 1
Example #1: Count positive and negative numbers from the given list using for loop Iterate each element in the list using for loop and check if num >= 0, the condition to check positive numbers. If the condition satisfies, then increase pos_count else increase neg_count.
Python3
list1 = [10, -21, 4, -45, 66, -93, 1]
pos_count, neg_count = 0, 0
for num in list1:
if num >= 0:
pos_count += 1
else:
neg_count += 1
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", neg_count)
Output
Positive numbers in the list: 4 Negative numbers in the list: 3
Time Complexity: O(N), Here N is the number of items in the list.
Auxiliary Space: O(1), As constant extra space is used.
Example #2: Using while loop
Python3
list1 = [-10, -21, -4, -45, -66, 93, 11]
pos_count, neg_count = 0, 0
num = 0
while(num < len(list1)):
if list1[num] >= 0:
pos_count += 1
else:
neg_count += 1
num += 1
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", neg_count)
Output
Positive numbers in the list: 2 Negative numbers in the list: 5
Time Complexity: O(N), Here N is the number of items in the list.
Auxiliary Space: O(1), As constant extra space is used.
Example #3: Using Python Lambda Expressions
Python3
list1 = [10, -21, -4, 45, 66, 93, -11]
neg_count = len(list(filter(lambda x: (x < 0), list1)))
pos_count = len(list(filter(lambda x: (x >= 0), list1)))
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", neg_count)
Output
Positive numbers in the list: 4 Negative numbers in the list: 3
Time Complexity: O(N), Here N is the number of items in the list.
Auxiliary Space: O(1), As constant extra space is used.
Example #4: Using List Comprehension
Python3
list1 = [-10, -21, -4, -45, -66, -93, 11]
only_pos = [num for num in list1 if num >= 1]
pos_count = len(only_pos)
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", len(list1) - pos_count)
Output
Positive numbers in the list: 1 Negative numbers in the list: 6
Time Complexity: O(N), Here N is the number of items in the list.
Auxiliary Space: O(1), As constant extra space is used.
Method: Using enumerate function
Python3
l=[12, -7, 5, 64, -14];c=0
x=[a for j,a in enumerate(l) if a>=0]
print("Length of Positive numbers is:", len(x))
print("Length of Negative numbers is:", len(l)-len(x))
Output
Length of Positive numbers is: 3 Length of Negative numbers is: 2
Time Complexity: O(N), Here N is the number of items in the list.
Auxiliary Space: O(1), As constant extra space is used.
Method : Using startswith() method
Python3
list1 = [10, -21, 4, -45, 66, -93, 1,0]
pos_count, neg_count = 0, 0
list2=list(map(str,list1))
for num in list2:
if num.startswith("-"):
neg_count += 1
elif(num!="0"):
if(not num.startswith("-")):
pos_count+=1
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", neg_count)
Output
Positive numbers in the list: 4 Negative numbers in the list: 3
Time Complexity: O(N), Here N is the number of items in the list.
Auxiliary Space: O(1), As constant extra space is used.
Method: Using sum() method
Python3
l = [12, -7, 5, 64, -14];
x = sum(1 for i in l if i >= 0 )
print("Length of Positive numbers is:", x)
print("Length of Negative numbers is:", len(l)-x)
Output
Length of Positive numbers is: 3 Length of Negative numbers is: 2
Time Complexity: O(N), Here N is the number of items in the list.
Auxiliary Space: O(1), As constant extra space is used.
Method : Using for loop
STEP BY STEP APPROACH :
- Initialize a list of numbers called list1 with integer values.
- Initialize two variables pos_count and neg_count to 0.
- Convert all the numbers in list1 to strings using the map() function and store them in a new list called list2.
- Iterate through each number num in list2 using a for loop.
- For each number num, check the first character of the string representation of the number using num[0]:
a. If the first character is “-“, increment the neg_count variable as the number is negative.
b. Else, check if the number is not equal to “0” using num!=”0″:
i. If the number is positive, increment the pos_count variable. - Print the final values of pos_count and neg_count using the print() function.
Python3
list1 = [10, -21, 4, -45, 66, -93, 1,0]
pos_count, neg_count = 0, 0
list2=list(map(str,list1))
for num in list2:
if num[0]=="-":
neg_count += 1
elif(num!="0"):
if(not num[0]=="-"):
pos_count+=1
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", neg_count)
Output
Positive numbers in the list: 4 Negative numbers in the list: 3
Time Complexity: O(N)
Auxiliary Space: O(N)
Method: Using the collections module and the Counter() function:
- Importing the Counter class from the collections module.
- Using a list comprehension to get a list of boolean values to check whether each number is non-negative or not, based on whether it is greater than or equal to zero.
- Passing the list of booleans to the Counter to get a dictionary mapping for counts.
- Storing the count of positive and negative no.
- Printing the output.
Python3
from collections import Counter
list1 = [10, -21, 4, -45, 66, -93, 1,0]
counts = Counter(num > 0 for num in list1)
pos_count = counts[True]
neg_count = counts[False] - (0 in list1)
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", neg_count)
Output
Positive numbers in the list: 4 Negative numbers in the list: 3
Time Complexity: O(N) as we are traversing the whole list which takes O(N) time complexity.
Auxiliary Space: O(1) as no extra memory is used.
Last Updated :
10 Apr, 2023
Like Article
Save Article
Дан массив действительных чисел из N членов подсчитать сколько в нем отрицательных, положительных и нулевых элементов
задан 27 мар 2020 в 10:50
1
Вот так можно:
my_list = [1, 2, 3, 4, 5, 0, 0, 0, 0, -1, -2, -3, -4, -5]
positive = 0
negative = 0
zero = 0
for num in my_list:
if num > 0:
positive += 1
continue
if num < 0:
negative += 1
continue
zero += 1
print('Положительных: ', positive)
print('Отрицательных: ', negative)
print('Нулей: ', zero)
ответ дан 27 мар 2020 в 11:47
n1tr0xsn1tr0xs
11.2k2 золотых знака9 серебряных знаков28 бронзовых знаков
massive = [1,2,3,4,5,0,5,4,0,-5,3,2,-1] #вместо massive подставляете свой массив
pos = []
neg = []
zero = []
for num in massive:
if num > 0:
pos.append(num)
elif num == 0:
zero.append(num)
else:
neg.append(num)
print("Количество положительных: {}".format(len(pos)))
print("Количество отрицательных: {}".format(len(neg)))
print("Количество нулей: {}".format(len(zero)))
ответ дан 27 мар 2020 в 11:14
Alioshca ZAlioshca Z
1,3731 золотой знак4 серебряных знака10 бронзовых знаков
5
Python задачи
Создайте массив из 20 случайных целых чисел от -10 до 10, запишите их в ячейки массива. Подсчитайте, сколько из них положительных, отрицательных и нулевых. Отобразите элементы массива и значения подсчитанных величин. Разбор задачи на python
Алгоритм решения задачи на python
1) Назначить три переменные под счётчики и присвоить им значение равное 0
2) Написать цикл for, который создаёт случайные числа и записывает их в массив, далее сравнивает и записывает +1 в соответствующий счётчик
3) Вывод на экран значения счётчиков и массива
Код для нахождения количества положительных, отрицательных и равных нулю элементов массива
from random import random
mins = 0
zero = 0
plus = 0
a = []
for i in range(20):
n = int(random() * 20) — 10
a.append(n)
print(n, end=’ ‘)
if n > 0:
plus += 1
elif n < 0:
mins += 1
else:
zero += 1
print(«nПоложительных чисел: «, plus)
print(«Отрицательных чисел: «, mins)
print(«Чисел равных нулю: «, zero)
Python задачи
Все задачи на python
Репост статьи
22 декабря 2022 г.
Комментарии могут оставлять только зарегестрированные пользователи!
Комментарии
Ваш комментарий будет первым !
Уведомления
- Начало
- » Центр помощи
- » Подсчитать количество положительных элементов в массиве и сделать так что бы все элементы массива поменяли знак
#1 Дек. 18, 2019 16:57:56
Подсчитать количество положительных элементов в массиве и сделать так что бы все элементы массива поменяли знак
Задан двумерный массив А из 8-и строк и 3-х столбцов. Составить программу, которая подсчитывает общее число неотрицательных элементов в массиве. Затем организовать формирование нового массива В, в котором значения элементов исходного массива заменить на противоположные по знаку.
k = 9
n = 4
a =
print(“Введите массив по строкам через пробелы. В конце строки нажмите Enter.”)
for i in range(n-1):
print(‘Введите в’ ,i, ‘-ую строку 8 числа через пробел и нажмите Enter’)
row = input().split()
for i in range(k-1):
row = int(row)
a.append(row)
for row in a:
for elem in row:
print(elem, end=’ ‘)
print()
s = 0
pr=1
for i in range(n-1):
for j in range(k-1):
s += a
if a<=-1:
pr=pr*a
print(“Сумма всех элементов массива =”, s, end=’ ‘)
print(“Произведение отрицательных элементов массива = ”, pr)
pr=1
Отредактировано GasGasi (Дек. 18, 2019 18:51:27)
Офлайн
- Пожаловаться
#2 Дек. 18, 2019 17:26:12
Подсчитать количество положительных элементов в массиве и сделать так что бы все элементы массива поменяли знак
>>> s = [1,2,-5,6,-10] >>> len([ x for x in s if x >0 ]) 3 >>> [ x*-1 for x in s ] [-1, -2, 5, -6, 10]
С дураками и сектантами не спорю, истину не ищу.
Ели кому-то правда не нравится, то заранее извиняюсь.
Офлайн
- Пожаловаться
#3 Дек. 18, 2019 17:36:37
Подсчитать количество положительных элементов в массиве и сделать так что бы все элементы массива поменяли знак
Rodegast
Спасибо, но не могли бы вы сказать как это правильно вставить в мой код?
Офлайн
- Пожаловаться
#4 Дек. 19, 2019 08:46:30
Подсчитать количество положительных элементов в массиве и сделать так что бы все элементы массива поменяли знак
GasGasi
Спасибо, но не могли бы вы сказать как это правильно вставить в мой код?
https://younglinux.info/python/feature/generators
1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде 
2. чтобы вставить изображение залейте его куда нибудь (например), нажмите 
…
есчщо
Офлайн
- Пожаловаться
- Начало
- » Центр помощи
- » Подсчитать количество положительных элементов в массиве и сделать так что бы все элементы массива поменяли знак

Найти сумму и количество положительных элементов массива, предшествующих первому нулевому элементу (C++ -> Python)


