• + 36 comments

    It's a draw! :) Python:

    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")
    
    • + 7 comments

      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)
      
      • + 2 comments

        High five!

        • + 2 comments

          Quick help? How do I format code snippet in my reply? I used and it isn't formatted. Thanks in advance.

          • + 2 comments

            Nevermind! got it from a comment below :)

            • + 0 comments

              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")

          • + 4 comments

            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);
            }
            
            • + 7 comments

              Could have done the conditionals and assigning arr the scanner.nextInt() numbers all in one for loop:

              import java.io.*;
              import java.util.*;
              
              public class Solution {
              
                  public static void main(String[] args) {
                      /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
                      Scanner scanner = new Scanner(System.in);
                      int size = scanner.nextInt();
                      
                      int[] a = new int[size];
                      
                      double fractionPositive = 0;
                      double fractionZero = 0;
                      double fractionNegative = 0;
                      
                      for (int i = 0; i < size; i++){
                          a[i] = scanner.nextInt();
                          if (a[i] > 0) fractionPositive += 1;
                          else if (a[i] == 0) fractionZero += 1;
                          else if (a[i] < 0) fractionNegative += 1;
                      }
                      
                      System.out.println(fractionPositive/size);
                      System.out.println(fractionNegative/size);
                      System.out.println(fractionZero/size);
                      
                  }
              }
              
              • + 5 comments

                Should've used printf for more precise result. Cool solution tho'.

                System.out.printf("%.6f %n",fractionPositive/n);
                System.out.printf("%.6f %n",fractionNegative/n);
                System.out.printf("%.6f %n",fractionZero/n);
                
                • + 0 comments

                  https://www.hackerrank.com/challenges/plus-minus/forum/comments/236802

                • + 2 comments

                  is it ("%.6f % n") regular expression and how it is formatting the result

                  • + 0 comments

                    Ahh got it to limit the output after decimal..

                  • + 0 comments

                    but in between " " this will coment than how wil be this work??

                • + 0 comments

                  thank u...

                • + 1 comment

                  ("%.6f %n", this "," sould we use +

                  • + 0 comments

                    no this will print the whole string

                • + 3 comments

                  import java.io.; import java.util.; import java.text.; import java.math.; import java.util.regex.*;

                  public class Solution {

                  static void plusMinus(int[] arr) {
                      double p=0,n=0,z=0;
                      int al = arr.length;
                      for(int i=0;i<al;i++)
                      {
                          if(arr[i]>0)
                          {
                              p++;
                          }
                          else if(arr[i]<0)
                          {
                              n++;
                          }
                          else if (arr[i]==0)
                          {
                              z++;
                          }
                  
                      }
                      System.out.printf("\n%1$.6f", p/al);
                      System.out.printf("\n%1$.6f" ,n/al);
                      System.out.printf("\n%1$.6f", z/al);
                  }                  
                  
                  public static void main(String[] args) {
                      Scanner in = new Scanner(System.in);
                      int n = in.nextInt();
                      int[] arr = new int[n];
                      for(int arr_i = 0; arr_i < n; arr_i++){
                          arr[arr_i] = in.nextInt();
                      }
                      plusMinus(arr);
                      in.close();
                  }
                  

                  } why this code is not being approved???

                  • + 0 comments

                    because there is one \n at the beginning which is not necasary

                    System.out.printf("%1$.6f", p/al);

                  • + 1 comment

                    add \n after 6f in each s.o.pln then it will pass all test cases

                    • + 0 comments

                      just remove \n from first printf not add !

                  • + 0 comments

                    just remove \n from first printf as its starting from end of line which is against the format

              • + 0 comments

                cool solution bro

              • + 0 comments

                We can also use float instead of double. It will work.

              • + 0 comments

                Didn't really need an array.

              • + 0 comments

                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);

              • + 2 comments
                System.out.printf("%.06f%n%.06f%n%.06f",fractionPositive/size,fractionNegative/size,fractionZero/size);
                

                This could be used as a replacement for your print statement

                • + 0 comments

                  good solution to union all sout.

                • + 1 comment

                  Can someone exaplin how to get this regex? %.06f%n%.06f%n%.06f I am a little confused

                  • + 1 comment

                    It is not a regex, Google pls - print format in Java

                    • + 0 comments

                      awesome thanks

              • + 0 comments

                where did you set the precision in this code??

            • + 6 comments

              i am trying to do the same thing but the output remains 0.000000 i dont know how?

              • + 1 comment

                Are your variables of type double instead of int?

                • + 2 comments

                  no.

                  • + 0 comments

                    Same for me...

                  • + 1 comment

                    yea.. same for me also...

                    • + 1 comment

                      code is working in VS IDE, but submited code here not passing the test cases. Don`t why. Submitted code is correct

                      • + 0 comments

                        did you round the results of the division?

              • + 0 comments

                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":

                myDoubleAnswer = static_cast<double>(positiveIntCount) / n
                
                static_cast<type>(variableToStaticCast)
                
              • + 0 comments

                typecast into float

              • + 0 comments

                same here....!

              • + 0 comments

                apply casting while dividing number of positive(negative or zeroes)by number of elements e.g. a=(float)b/n;

              • + 0 comments

                python 2 maybe?

            • + 0 comments

              This won't give decimal output

            • + 0 comments

              but what is data type of a&b&c???

        • + 0 comments

          def plusMinus(arr):

          # 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")
          
      • + 2 comments

        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 !!!

        • + 3 comments

          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.

          • + 2 comments

            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. :)

            • + 0 comments

              yeah I think that's right

            • + 0 comments

              Right, in python3 if you dont want the fraction just use floor division a//x.

          • + 1 comment

            In C# as well. Took me "forever" to find out.

            • + 0 comments

              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);

                   decimal Pos=(decimal)PositiveNumbers / n;
                    decimal Neg=(decimal)NegativeNubers / n;
                    decimal Zer=(decimal)zeroNumbers / n;
              
                    Console.WriteLine( string.Format("{0:0.000000}",Pos));
                  Console.WriteLine(string.Format("{0:0.000000}",Neg));
                   Console.WriteLine(string.Format("{0:0.000000}",Zer));
              
          • + 0 comments

            you could also import division from future which fixes the integer and float division as in Python 3.

        • + 0 comments

          It's for the division, using integer will give an integer

      • + 3 comments
        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)
        
        • + 2 comments

          nice idea! not wasting memory and more importantly time in creating a list. Thanks for sharing!

          • + 1 comment

            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.

            • + 0 comments

              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.

          • + 1 comment

            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!!

            • + 0 comments

              can you please explain this? scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        • + 0 comments

        • + 1 comment

          Nice ! But I think its better to use format than round since round will not display zeros after decimal.

          Try this:

          print (format(ps/head,".3f"))  
          print (format(ng/head,'.3f'))
          print (format(zero/head,'.3f'))
          
          • + 0 comments

            can you plzz explain this scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

      • + 2 comments

        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.

        • + 0 comments

          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

        • + 1 comment

          Depends if you really need to break.

          If not -- simply:

          ## list comprehension to get only neg numbs
          a = [i for i in num_list if i < 0] 
          
          ## if u want to break
          for i in num_list:
              if i >= 0:
                  break
          
          • + 0 comments

      • + 0 comments

        why u r using n as float,how no. of elements can be float

      • + 0 comments

        please explain me the print part

      • + 0 comments

        Its less code, but less efficent than just iterating the list once isnt it?

    • + 1 comment
      [deleted]
      • + 1 comment

        what does this mean [deleted]?

        • + 0 comments

          The post isn't available anymore

    • + 5 comments

      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)
      
      • + 0 comments

        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.

      • + 0 comments

        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).

      • + 1 comment

        A variation of this using the cmp built-in function

        n = int(raw_input().strip())
        arr = map(int,raw_input().strip().split(' '))
        
        NEG, EQUAL, POS = -1, 0, +1
        
        D = {NEG : 0, EQUAL: 0, POS: 0}
        
        for i in arr:
            D[cmp(i, 0)] += 1
        
        for k in (POS, NEG, EQUAL):
            f = 1.0 * D[k] / n
            print "%.6f" % f
        
        • + 0 comments

          doesn't work in python3

      • + 0 comments

        very efficient!

      • + 0 comments

        O(3n) is wrong, Big O notation does not contain constants.

    • + 0 comments

      I did not realize you could turn list elemetns into Ints using [int(x) for x in ....], this is amazing, thank you!

    • + 0 comments

      oh wow, awesome! Silly Java.

    • + 0 comments

      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")

    • + 0 comments

      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")

    • + 1 comment

      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.

      • + 1 comment

        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?

        • + 0 comments

          late to the party, but you are right, the solutions with 3 counters are not optimal. I'm even surprised that was accepted.

    • + 0 comments

      yes

    • + 0 comments

      Scala!

      val result = arr.groupBy(x => if (x > 0) 1 else (if (x<0) -1 else 0)).mapValues(y => y.size.toDouble / arr.size)
      
      println(result.getOrElse( 1, 0)) // positive
      println(result.getOrElse(-1, 0)) // negative
      println(result.getOrElse( 0, 0)) // zeroes
      
    • + 0 comments

      Its no where near draw :)

    • + 2 comments

      Here is a PHP version. $arr is the input array.

      `$res = array_reduce($`arr, function(`$carry, $`val) {(`$val>0)?$`carry[0]++:((`$val<0)?$`carry[1]++:`$carry[2]++); return $`carry;},[]);    
      
      printf ("%f\n%f\n%f", `$res[0]/$`n, `$res[1]/$`n, `$res[2]/$`n);
      
      • + 0 comments

        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);

    • + 0 comments

      @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.

    • + 2 comments
      l = [1 if x >0 else -1 for x in arr if x != 0]
      print("%.6f" % float(l.count(1)/n))
      print("%.6f" % float(l.count(-1)/n))
      print("%.6f" % float(abs(len(l)-n) /n))
      
      • + 0 comments

        Thanks!

      • + 0 comments

        This was really smart

    • + 2 comments

      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

      • + 0 comments

        updated

      • + 2 comments

        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)

        print("{:6f}\n{:6f}\n{:6f}".format(len(list(filter(lambda x:x>0,arr)))/len(arr),len(list(filter(lambda x:x<0 , arr)))/len(arr),len(list(filter(lambda x:x==0,arr)))/len(arr)))
        

        This was my solution:

        n = int(input())
        arr = [int(x) for x in input().split()]
        
        positive = 0
        negative = 0
        zeroes = 0
        
        for i in arr:
            if i > 0:
                positive += 1
            elif i < 0:
                negative += 1
            else:
                zeroes += 1
        
        Length = len(arr)
        print(positive/Length)
        print(negative/Length)
        print(zeroes/Length)
        

        the best possible performance, and it's easy to read, and just looks overall pretty.

        • + 1 comment

          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:

          n = int(input())
          arr = [0 if i is 0 else i/abs(i) for i in map(int, input().split())]
          
          for num in map(arr.count, [1, -1, 0]):
              print(round(num/n, 6))
          

          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:

          n = int(input())
          values = {'zeros': 0, 'negative': 0, 'positive': 0}
          
          for i in map(int, input().split()):
              values['positive'*(not i) + 'negative'*(i<0) + 'zeros'*(i>0)] += 1
          
          print('\n'.join(map(lambda x: str(round(x/n, 6)) ,values.values())))
          

          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)

          • + 1 comment

            Wow, well said. I love how you coded this:

            for i in map(int, input().split()):
                values['positive'*(not i) + 'negative'*(i<0) + 'zeros'*(i>0)] += 1
            

            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'

            • + 0 comments

              Yes! sorry for the mistake ^^"

        • + 2 comments

          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?

          import sys
          
          def plusMinus(arr):
              # Complete this function
              pos=0
              neg=0
              zero=0
              for i in arr:
                  if i>0:
                      pos+=1
                      result=float(pos/n)
                  elif i<0:
                      neg+=1
                      num=float(neg/n)
                  else:
                      zero+=1
                      count=float(zero/n)
                      
              print("%.6f" % result)
              print("%.6f" % num)
              print("%.6f" % count)
          
          • + 0 comments

            You need to add n to the plusMinus function like so: def plusMinus(n, arr): # Complet this function # print("#.6f" % result) etc...

          • + 0 comments

            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

                elif i<0:
                    neg+=1
            
                else:
                    zero+=1
            
            result=float(pos)/float(len(arr))
            num=float(neg)/float(len(arr))
            count=float(zero)/float(len(arr))
            
            print("%.6f" % result)
            print("%.6f" % num)
            print("%.6f" % count)
            
    • + 0 comments
      print("{:6f}\n{:6f}\n{:6f}".format(len(list(filter(lambda x:x>0,arr)))/len(arr),len(list(filter(lambda x:x<0 , arr)))/len(arr),len(list(filter(lambda x:x==0,arr)))/len(arr)))
      
    • + 0 comments

      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)

    • + 0 comments

      I think this is prettier:

      n = int(input())
      arr = [0 if i is 0 else i/abs(i) for i in map(int, input().split())]
      
      for num in map(arr.count, [1, -1, 0]):
          print(round(num/n, 6))
      
    • + 0 comments

      Can you please elaborate on what "format(..)" does? I'm a beginner in python.

    • + 0 comments

      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.

    • + 0 comments

      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.

      import java.util.Scanner
      
      fun main(args: Array<String>) {
          val sc = Scanner(System.`in`)
      
          val size = sc.nextInt()
          val inputs = Array(size, { sc.nextDouble() })
      
          println(inputs.count { it > 0.0} / size.toDouble())
          println(inputs.count { it < 0.0} / size.toDouble())
          println(inputs.count { it == 0.0} / size.toDouble())
      }
      
    • + 0 comments

      why we have to use square brackets inside len()

    • + 0 comments

      This will not work in Python2 because you are doing integer divison.

    • + 0 comments

      CAn you please explain this syntax.

    • + 0 comments

      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.

    • + 0 comments

      Dear paul_schmeida,

      can u please explain why u have used ".6f" inside the format function.Please Help.Advance thanks and regards.

    • + 0 comments

      Just so we're clear, you're aware there are three different loops, right? Seems pretty inefficient to me.

    • + 0 comments

      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)}')

    • + 0 comments

    • [deleted]
      + 0 comments

      Going three times through the input data?

    • + 1 comment

      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!

      • + 0 comments

        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.

    • + 0 comments

      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)

    • + 0 comments
      nm = list(map(int, input().split()))
      print(float(len(list(filter(lambda x:x > 0, nm))))/len(nm))
      print(float(len(list(filter(lambda x:x < 0, nm))))/len(nm))
      print(float(len(list(filter(lambda x:x == 0, nm))))/len(nm))
      
    • + 0 comments

      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)))

    • + 0 comments

      time complexity goes crazy, watch out!