We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I felt like cheating too so opened the discussion forum for the first time to see this post :D
n=float(raw_input())
numbers=map(int,raw_input().split())
print round(len([x for x in numbers if x>0])/n,3)
print round(len([x for x in numbers if x<0])/n,3)
print round(len([x for x in numbers if x==0])/n,3)
n = float(raw_input())
lst = [int(x) for x in raw_input().split()]
print format(len([x for x in lst if x > 0])/n, ".6f")
print format(len([x for x in lst if x < 0])/n, ".6f")
print format(len([x for x in lst if x == 0])/n, ".6f")
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
double a=0,b=0,c=0;
int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++){
arr[arr_i] = in.nextInt();
}
for(int arr_i=0; arr_i < n; arr_i++){
if (arr[arr_i]>0)
{a++;}
else if (arr[arr_i]<0){b++;}
else if (arr[arr_i]==0){c++;}
}
System.out.println(a/n);
System.out.println(b/n);
System.out.println(c/n);
}
Could have done the conditionals and assigning arr the scanner.nextInt() numbers all in one for loop:
importjava.io.*;importjava.util.*;publicclassSolution{publicstaticvoidmain(String[]args){/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */Scannerscanner=newScanner(System.in);intsize=scanner.nextInt();int[]a=newint[size];doublefractionPositive=0;doublefractionZero=0;doublefractionNegative=0;for(inti=0;i<size;i++){a[i]=scanner.nextInt();if(a[i]>0)fractionPositive+=1;elseif(a[i]==0)fractionZero+=1;elseif(a[i]<0)fractionNegative+=1;}System.out.println(fractionPositive/size);System.out.println(fractionNegative/size);System.out.println(fractionZero/size);}}
You also don't need to count one of them, for instance, if you don't count negative ones, your output is:
System.out.println((size-fractionPositive-fractionZero)/size);
Most programing languages do not like when variable types mix with eachother. An integer divided by an integer produces a floating point in most cases, but the computer only works with variables that all have the same data type; such as a double divided by a double producing a double. The problem seems like you are having is because of inconsistant varible types.
The folowing case does not work because there are two differant variable types:
double = integer / integer
A solution to this problem is to use a STATIC CAST. The following line could be read as "turn my (positiveIntegerCount) into a double before i divide by its length":
# Complete this function
positive = sum(x > 0 for x in arr) / len(arr)
negative = sum(x < 0 for x in arr) / len(arr)
zero = sum(x == 0 for x in arr) / len(arr)
print('%.6f' % positive,'%.6f' % negative, '%.6f' % zero, sep="\n")
Because, in Python, if you divide two ints, you would get the result of the integer division, in this case 0. But if the N is stored as a float, you are already forcing the floating point division here.
int n = Convert.ToInt32(Console.ReadLine());
string[] arr_temp = Console.ReadLine().Split(' ');
int[] array_temp= Array.ConvertAll(arr_temp,Int32.Parse);
int PositiveNumbers= array_temp.Where(x=>x>0).ToList().Count;
int NegativeNubers=array_temp.Where(x=>x<0).ToList().Count;
int zeroNumbers=array_temp.Length-(PositiveNumbers + NegativeNubers);
head = float(raw_input())
mylist = [float(i) for i in raw_input().split()]
zero = sum(j == 0 for j in mylist)
ng = sum(j < 0 for j in mylist)
ps = sum(j > 0 for j in mylist)
print round(ps/head, 3)
print round(ng/head, 3)
print round(zero/head, 3)
When i read it correctly, she walks through 'mylist' 3 times. If she would go through each element once and do the compareision in that loop, she would walk through the list only once.
But because she also reads the input in a list and than splits it, she basicly is creating a temp list which isn't necessary. In java you can say (when using a Scanner) nextInt and don't even need a list at all.
As far as complexity goes, repeating an iteration 3 times is the same as doing it once so it's not the end of the world. Especially with the constraint that N <100.
The code idea is correct but we don't need to perform three O(n) operations for same stuff. The time complexity will remain O(n) but if taken for large array length, there will be slight difference in time in microseconds probably compared to that with one or two O(n) time complexity program.
We mostly don't care for space complexity (just for single list), thus, we may use it.
Guys! I have a question related to Python, in this piece of code of yours - [x for x in numbers if x>0].
What if I wanted to create a "new list" (which contains only negative numbers) from "numbers list" where numbers list is sorted in ascending order. I want to break the loop when x>= 0. So,
a = [x for x in numbers if x >= 0: break]
As you know this syntax is wrong, can you guys suggest me what is the proper way? I am new to Python.
In this above solution the run time is O(3n) and we could make this as O(n) by using the dict to track the count of integers like positive, negative and zero values.
size_of_list = int(input())
list_of_int = map(int, raw_input().split(" "))
count_of_deci = {"posi" : 0,
"neg" : 0,
"zero" : 0}
for ele in list_of_int:
if ele < 0:
count_of_deci["neg"] += 1
elif ele == 0:
count_of_deci["zero"] += 1
elif ele > 0:
count_of_deci["posi"] += 1
print "%.3f" % float(float(count_of_deci["posi"])/size_of_list)
print "%.3f" % float(float(count_of_deci["neg"])/size_of_list)
print "%.3f" % float(float(count_of_deci["zero"])/size_of_list)
n = float(raw_input())
lst = [int(x) for x in raw_input().split()]
print format(len([x for x in lst if x > 0])/n, ".6f")
print format(len([x for x in lst if x < 0])/n, ".6f")
print format(len([x for x in lst if x == 0])/n, ".6f")
n = float(raw_input())
lst = [int(x) for x in raw_input().split()]
print format(len([x for x in lst if x > 0])/n, ".6f")
print format(len([x for x in lst if x < 0])/n, ".6f")
print format(len([x for x in lst if x == 0])/n, ".6f")
@paul_schmeida I am not getting my desired output as the x < 0 and x == 0 are not passing the test. I am using the Python 3 language for coding. Help me out.
three print statements with for loop, you are linearly searching 3 times the array which increases the complexity right? what special in this code other than reducing LOC
There is nothing special about it, the code is not very efficient.
- looking at the prettiness of the code, I would say it's around decent - pretty. It's very readable, and understandable. Compared to this s*** for instance:
(I didn't write it)
the first code is not only ugly but innefficient.
Yout code is simple yes, good performance but it is 0 pythonic and you have two variables with the same value (n and Length). It is not bad but if you are using python you should make use of their tricks. Efficient is wrost in my solution for small inputs.
In this case is clean and almost more efficient than your solution for small inputs (as map and join presents better performance than a list comprehension and a triple print)
My code is almost same as yours but my code does not pass case 2,4,5,6. Can you tell what might be wrong?
importsysdefplusMinus(arr):# Complete this functionpos=0neg=0zero=0foriinarr:ifi>0:pos+=1result=float(pos/n)elifi<0:neg+=1num=float(neg/n)else:zero+=1count=float(zero/n)print("%.6f"%result)print("%.6f"%num)print("%.6f"%count)
Kotlin is also really nice and clean. Especially like how clean the syntax for populating the initial array is. It has a little bit more boilerplate than Python, but still super pleasant compared to what you'd have to do in java 7 or lower.
def plusMinus(arr):
lis1=[x for x in arr if x>0]
lis2=[x for x in arr if x<0]
lis3=[x for x in arr if x==0]
print(f'{round(len(lis1)/len(arr),6)}\n{round(len(lis2)/len(arr),6)}\n{round(len(lis3)/len(arr),6)}')
It will iterate through the array just once and count all the (+ve) , (-ve) nos and zeros and will divide their count by total numbers of arrays in the array. I have edited my solution in proper format with the same code,have a look.
Plus Minus
You are viewing a single comment's thread. Return to all comments →
It's a draw! :) Python:
I felt like cheating too so opened the discussion forum for the first time to see this post :D
High five!
Quick help? How do I format code snippet in my reply? I used
and it isn't formatted. Thanks in advance.
Nevermind! got it from a comment below :)
n = float(raw_input()) lst = [int(x) for x in raw_input().split()] print format(len([x for x in lst if x > 0])/n, ".6f") print format(len([x for x in lst if x < 0])/n, ".6f") print format(len([x for x in lst if x == 0])/n, ".6f")
public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); double a=0,b=0,c=0; int arr[] = new int[n]; for(int arr_i=0; arr_i < n; arr_i++){ arr[arr_i] = in.nextInt(); }
Could have done the conditionals and assigning arr the scanner.nextInt() numbers all in one for loop:
Should've used printf for more precise result. Cool solution tho'.
https://www.hackerrank.com/challenges/plus-minus/forum/comments/236802
is it ("%.6f % n") regular expression and how it is formatting the result
Ahh got it to limit the output after decimal..
but in between " " this will coment than how wil be this work??
thank u...
("%.6f %n", this "," sould we use +
no this will print the whole string
import java.io.; import java.util.; import java.text.; import java.math.; import java.util.regex.*;
public class Solution {
} why this code is not being approved???
because there is one \n at the beginning which is not necasary
System.out.printf("%1$.6f", p/al);
add \n after 6f in each s.o.pln then it will pass all test cases
just remove \n from first printf not add !
just remove \n from first printf as its starting from end of line which is against the format
cool solution bro
We can also use float instead of double. It will work.
Didn't really need an array.
You also don't need to count one of them, for instance, if you don't count negative ones, your output is: System.out.println((size-fractionPositive-fractionZero)/size);
This could be used as a replacement for your print statement
good solution to union all sout.
Can someone exaplin how to get this regex? %.06f%n%.06f%n%.06f I am a little confused
It is not a regex, Google pls - print format in Java
awesome thanks
where did you set the precision in this code??
i am trying to do the same thing but the output remains 0.000000 i dont know how?
Are your variables of type
double
instead ofint
?no.
Same for me...
yea.. same for me also...
code is working in VS IDE, but submited code here not passing the test cases. Don`t why. Submitted code is correct
did you round the results of the division?
Most programing languages do not like when variable types mix with eachother. An integer divided by an integer produces a floating point in most cases, but the computer only works with variables that all have the same data type; such as a double divided by a double producing a double. The problem seems like you are having is because of inconsistant varible types.
The folowing case does not work because there are two differant variable types: double = integer / integer
A solution to this problem is to use a STATIC CAST. The following line could be read as "turn my (positiveIntegerCount) into a double before i divide by its length":
typecast into float
same here....!
apply casting while dividing number of positive(negative or zeroes)by number of elements e.g. a=(float)b/n;
python 2 maybe?
This won't give decimal output
but what is data type of a&b&c???
def plusMinus(arr):
Why your "N" a float , it is the length of the Array and i think it must be integer because you can't an Array with 2.5 in size !!!
Because, in Python, if you divide two ints, you would get the result of the integer division, in this case 0. But if the N is stored as a float, you are already forcing the floating point division here.
To my knowledge, that is only the case for Python 2. Python 3 returns the fractional part as well even if you divide two ints. :)
yeah I think that's right
Right, in python3 if you dont want the fraction just use floor division a//x.
In C# as well. Took me "forever" to find out.
int n = Convert.ToInt32(Console.ReadLine()); string[] arr_temp = Console.ReadLine().Split(' '); int[] array_temp= Array.ConvertAll(arr_temp,Int32.Parse); int PositiveNumbers= array_temp.Where(x=>x>0).ToList().Count; int NegativeNubers=array_temp.Where(x=>x<0).ToList().Count; int zeroNumbers=array_temp.Length-(PositiveNumbers + NegativeNubers);
you could also import division from future which fixes the integer and float division as in Python 3.
It's for the division, using integer will give an integer
nice idea! not wasting memory and more importantly time in creating a list. Thanks for sharing!
When i read it correctly, she walks through 'mylist' 3 times. If she would go through each element once and do the compareision in that loop, she would walk through the list only once.
But because she also reads the input in a list and than splits it, she basicly is creating a temp list which isn't necessary. In java you can say (when using a Scanner) nextInt and don't even need a list at all.
As far as complexity goes, repeating an iteration 3 times is the same as doing it once so it's not the end of the world. Especially with the constraint that N <100.
The code idea is correct but we don't need to perform three O(n) operations for same stuff. The time complexity will remain O(n) but if taken for large array length, there will be slight difference in time in microseconds probably compared to that with one or two O(n) time complexity program. We mostly don't care for space complexity (just for single list), thus, we may use it.
REDUCE COMPLEXITY TO WHATEVER YOU CAN!!
can you please explain this? scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
Nice ! But I think its better to use format than round since round will not display zeros after decimal.
Try this:
can you plzz explain this scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
Guys! I have a question related to Python, in this piece of code of yours - [x for x in numbers if x>0].
What if I wanted to create a "new list" (which contains only negative numbers) from "numbers list" where numbers list is sorted in ascending order. I want to break the loop when x>= 0. So,
As you know this syntax is wrong, can you guys suggest me what is the proper way? I am new to Python.
There is no recommended way to interrupt an "expression" loop (i.e., comprehension, filter, map, reduce). You must use a conventional loop.
More on this, with a hack: http://stackoverflow.com/questions/9572833/break-list-comprehension
Depends if you really need to break.
If not -- simply:
why u r using n as float,how no. of elements can be float
please explain me the print part
Its less code, but less efficent than just iterating the list once isnt it?
what does this mean [deleted]?
The post isn't available anymore
In this above solution the run time is O(3n) and we could make this as O(n) by using the dict to track the count of integers like positive, negative and zero values.
Some problems are so simple that running time doesn't matter and writing short and concise code is more challenging and more fun, that's it.
In big O notation the 3 drops off and becomes O(n) we only care when it goes from O(n) to say O(n^2) or even worse O(x^n).
A variation of this using the cmp built-in function
doesn't work in python3
very efficient!
O(3n) is wrong, Big O notation does not contain constants.
I did not realize you could turn list elemetns into Ints using [int(x) for x in ....], this is amazing, thank you!
oh wow, awesome! Silly Java.
n = float(raw_input()) lst = [int(x) for x in raw_input().split()] print format(len([x for x in lst if x > 0])/n, ".6f") print format(len([x for x in lst if x < 0])/n, ".6f") print format(len([x for x in lst if x == 0])/n, ".6f")
n = float(raw_input()) lst = [int(x) for x in raw_input().split()] print format(len([x for x in lst if x > 0])/n, ".6f") print format(len([x for x in lst if x < 0])/n, ".6f") print format(len([x for x in lst if x == 0])/n, ".6f")
I'm not sure if python can optimize this?
Internally I feel that this is still performing 3 loops, instead of doing only one using 3 counters.
i dont get it, we could linearly perform search for 3 types and get count instead of 3 counters or 3 for loops. am i missing something here?
late to the party, but you are right, the solutions with 3 counters are not optimal. I'm even surprised that was accepted.
yes
Scala!
Its no where near draw :)
Here is a PHP version. $arr is the input array.
pretty cool!, a little more readable for me:
$res = array_reduce($arr, function($carry, $val) {
($val>0 and carry[0]++) or ($val<0 and $carry[1]++) or (!val and $carry[2]++); return $carry;},[]);
printf ("%f\n%f\n%f", $res[0]/$n, $res[1]/$n, `$res[2]/$``n);
@paul_schmeida I am not getting my desired output as the x < 0 and x == 0 are not passing the test. I am using the Python 3 language for coding. Help me out.
Thanks!
This was really smart
three print statements with for loop, you are linearly searching 3 times the array which increases the complexity right? what special in this code other than reducing LOC
updated
There is nothing special about it, the code is not very efficient. - looking at the prettiness of the code, I would say it's around decent - pretty. It's very readable, and understandable. Compared to this s*** for instance: (I didn't write it)
This was my solution:
the best possible performance, and it's easy to read, and just looks overall pretty.
the first code is not only ugly but innefficient. Yout code is simple yes, good performance but it is 0 pythonic and you have two variables with the same value (n and Length). It is not bad but if you are using python you should make use of their tricks. Efficient is wrost in my solution for small inputs.
Check mine:
Both have the same performance and both are clear but in mine you are not using excessive code for a simple things.
Anyways a variation of yours with your logic can be:
In this case is clean and almost more efficient than your solution for small inputs (as map and join presents better performance than a list comprehension and a triple print)
Wow, well said. I love how you coded this:
Edit: it seems like you made a mistake, if 'i>0' zeroes will increase with 1. if i=0 positive will increase with 1
You need to swap the statements 'not i' and 'i>0'
Yes! sorry for the mistake ^^"
My code is almost same as yours but my code does not pass case 2,4,5,6. Can you tell what might be wrong?
You need to add n to the plusMinus function like so: def plusMinus(n, arr): # Complet this function # print("#.6f" % result) etc...
Python I could not run the above code. Below is the final code. Just check once.
def plusMinus(arr): # Complete this function pos=0 neg=0 zero=0 for i in arr: if i>0: pos+=1
print float(len(filter(lambda x: x>0, arr)))/len(arr) print float(len(filter(lambda x: x<0, arr)))/len(arr) print float(len(filter(lambda x: x==0, arr)))/len(arr)
I think this is prettier:
Can you please elaborate on what "format(..)" does? I'm a beginner in python.
this may be consice but it's not very efficient because you are iterating though the array 3 times when this can be done with one iteration.
Kotlin is also really nice and clean. Especially like how clean the syntax for populating the initial array is. It has a little bit more boilerplate than Python, but still super pleasant compared to what you'd have to do in java 7 or lower.
why we have to use square brackets inside len()
This will not work in Python2 because you are doing integer divison.
CAn you please explain this syntax.
well first it's a cool solution but what i mean here is that in each result you are reading the whole array and this is "i think" not efficient.
Dear paul_schmeida,
can u please explain why u have used ".6f" inside the format function.Please Help.Advance thanks and regards.
Just so we're clear, you're aware there are three different loops, right? Seems pretty inefficient to me.
def plusMinus(arr): lis1=[x for x in arr if x>0] lis2=[x for x in arr if x<0] lis3=[x for x in arr if x==0] print(f'{round(len(lis1)/len(arr),6)}\n{round(len(lis2)/len(arr),6)}\n{round(len(lis3)/len(arr),6)}')
Going three times through the input data?
Am I reading this right that this will iterate over the array three times? If thats the case while this looks nice, its less efficient!
It will iterate through the array just once and count all the (+ve) , (-ve) nos and zeros and will divide their count by total numbers of arrays in the array. I have edited my solution in proper format with the same code,have a look.
Your code is extremely inefficient, it only looks short. You are using three loops when you require only 1. The complexity of your solution is O(3n)
print('%.6f'%(len(list(filter(lambda num: num>0, arr)))/len(arr)))
print('%.6f'%(len(list(filter(lambda num: num<0, arr)))/len(arr)))
print('%.6f'%(len(list(filter(lambda num: num==0, arr)))/len(arr)))
time complexity goes crazy, watch out!