Home > OS >  Count Positive values in python [(2, 3, 4 , 5)]
Count Positive values in python [(2, 3, 4 , 5)]

Time:06-18

I am new in python and I am struggling to count the postive values, I have this values [(2, 3, 4 , 5)] , and how i can count how many postive values from the given values? and this format is list or tupple i am not sure about that. If the count is more than 0 i ahve to print "Ok"

a=-2,-4
b=3,5
p=[]
p.append((a,b))
if p.count() > 1:
  print("Ok")

CodePudding user response:

Your list,

[(2,3,4,5)]

is a tuple inside an array. im not even sure if it will work syntax-wise.

a=2,4
b=3,5
p=[]
p.append((a,b))

im not sure about the functionality purpose of this code. Is this homework? but to answer your question, if you only want to return "Ok" if any of them is positive, you do want to iterate over every element first. since you have a tuple inside an array, you would have to do

list_of_numbers = p[0]

to get,

(2,3,4,5)

then you do this.

for i in list_of_numbers:
    if i > 0:
        print("ok")
        break

This loop will print ok and abort if any value in the list is bigger than 0. If you want to make a count, the solution is quite similar.

Also, for future questions, i would recommend you to google and research some time before asking question. There is nothing wrong about asking, but having the skill to look up answers online is quite useful in coding. I would also recommend you to rewrite your code if you dont have to have an tuple inside an array.

Hope this solved your problem.

CodePudding user response:

p=[2,3,4,5]
positives = 0
for number in p:
 if number>0:
  positives  = 1
print_result = str(positives)
print ("We have "   print_result   " positive numbers")

CodePudding user response:

You could try using a more functional way with a lambda function.

scores = [1,2,3,-4,5,6]
filtered = filter(lambda score: score > 0, scores)

filtered_list = list(filtered)
count_positives = len(filtered_list)
print(count_positives) #5

Taken from https://www.pythontutorial.net/python-basics/python-filter-list/

CodePudding user response:

import numpy as np


a=-2,-4
b=3,5
p=[]
p.append((a,b))

count = 0

for i in np.nditer(p):
    if i > 0 :
        count = count   1
        
print(count)

if count > 0 :
    print('OK')
  • Related