patternpythonMinor
Plus Minus in Python
Viewed 0 times
minuspluspython
Problem
You're given an array containing integer values. You need to print the
fraction of count of positive numbers, negative numbers and zeroes to
the total numbers. Print the value of the fractions correct to 3
decimal places.
Input Format
First line contains \$N\$, which is the size of the array. Next line
contains \$N\$ integers \$A_1, A_2, A_3, ⋯, A_N\$, separated by spaces.
Constraints
Solution
It seems that this problem has a very straightforward solution but I am more interested if there is a better functional approach.
fraction of count of positive numbers, negative numbers and zeroes to
the total numbers. Print the value of the fractions correct to 3
decimal places.
Input Format
First line contains \$N\$, which is the size of the array. Next line
contains \$N\$ integers \$A_1, A_2, A_3, ⋯, A_N\$, separated by spaces.
Constraints
- \$1 \le N \le 100\$
- \$−100 \le A_{i} \le 100\$
Solution
from __future__ import division
N = int(raw_input())
ary = map(int, raw_input().split())
count_negatives = len(filter(lambda x: x 0, ary))
count_zeros = len(filter(lambda x: x == 0, ary))
print count_positives / N
print count_negatives / N
print count_zeros / NIt seems that this problem has a very straightforward solution but I am more interested if there is a better functional approach.
Solution
Print the value of the fractions correct to 3 decimal places.
You didn't really do this part. You're just printing the full float. You can use
The
Though, since you're just printing the value by itself, you can use the
You don't need a filter to count the zeros. Lists have a built in
You didn't really do this part. You're just printing the full float. You can use
str.format() to print to three places. With this syntax:print "{:.3f}".format(count_positives / N)The
.3f syntax tells Python to print the first three digits only. Note that str.format will actually round the value, not just truncate it:"{:.3f}".format(1.3449)
>>> '1.345'Though, since you're just printing the value by itself, you can use the
format builtin where you pass the string and the format as a string.format(count_positives / N, '.3f')You don't need a filter to count the zeros. Lists have a built in
count function which will return the number of times a particular object occurs in it. Like this:count_zeros = ary.count(0)Code Snippets
print "{:.3f}".format(count_positives / N)"{:.3f}".format(1.3449)
>>> '1.345'format(count_positives / N, '.3f')count_zeros = ary.count(0)Context
StackExchange Code Review Q#105337, answer score: 7
Revisions (0)
No revisions yet.