14
\$\begingroup\$

Problem:

Given a set of integers, find the sum of all positive integers in it.

Input:

  • t – number of test cases [t < 1000]
  • On each of next t lines, an integer N [-1000 ≤ N ≤ 1000]

Output

The program should output the sum of all the positive integers.

Check your code in online judge

Score

Score is equal to size of source code of your program except symbols with ASCII code ≤ 32.

Here is the best score list: Python Best Scores (Best score is 29)

\$\endgroup\$

closed as unclear what you're asking by cat, rink.attendant.6, DJMcMayhem, Downgoat, Blue Apr 23 '16 at 22:47

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 13
    \$\begingroup\$ There are a lot more codegolf challenges at spoj.pl/SHORTEN. Don't see the point of duplicating them here though. \$\endgroup\$ – hallvabo Feb 24 '11 at 12:22
  • 3
    \$\begingroup\$ why is this question tagged python.. Are we interested in python solution only? \$\endgroup\$ – Aman ZeeK Verma Feb 24 '11 at 13:56
  • 24
    \$\begingroup\$ I don't think questions from contest sites should be posted here. \$\endgroup\$ – fR0DDY Feb 24 '11 at 14:01
  • 2
    \$\begingroup\$ I already did this one on SPOJ. A while ago they promoted all the Python2.6 answers to Python3 even though some of them wont run under Python3 and would be longer in Python3 - eg have to use int(input()) instead of input() and print(x) instead of print x. So I don't take SPOJ very seriously anymore. I'm tied with Tim Peters and that's good enough for me :) \$\endgroup\$ – gnibbler Feb 24 '11 at 21:22
  • 4
    \$\begingroup\$ I just want to point out, that skipping the T (number of ...errr...numbers (?) ) is not an option...since the testcases involve extra data after T numbers...your code will fail at SPOJ. Everyone (3 answers below) seemed to have cleverly skipped the first integer. \$\endgroup\$ – st0le Feb 25 '11 at 9:36

49 Answers 49

0
\$\begingroup\$

Perl, 30

so close to that python best of 29, but had to add +1 for the -p switch

$s.=$_}{$s=~s/\s\d+/$_+=$&/eg
\$\endgroup\$
  • \$\begingroup\$ This can be modified into an alternative 20 char solution: -p0 s/\n\d+/$\+=$&/ge}{. 19 when not counting \n. \$\endgroup\$ – nutki Feb 11 '15 at 10:21
0
\$\begingroup\$

Python 3, score: 63 61

r=0
q=input
w=int
for i in[1]*w(q()):
 t=w(q())
 r+=t+abs(t)
print(r/2)

I don't really know python, so I'm having a considerably difficult time making this any smaller.

Python, score: 49 48

r=0
q=input
for i in[1]*q():
 t=q()
 r+=t+abs(t)
print r/2

Same as above, but python 2 doesn't need the casting to int, apparently.

\$\endgroup\$
  • \$\begingroup\$ So do I. I'm not entirely sure where 49 came from. \$\endgroup\$ – Cereal Jul 9 '13 at 19:34
  • \$\begingroup\$ my mistake -- apparently characters with ascii value < 33 are discounted. \$\endgroup\$ – boothby Jul 9 '13 at 19:49
  • \$\begingroup\$ if whitespace etc doesn't count, then it's shorter to put "compound" statements like r,q,w=0,input,int as single statements on separate lines; r=0 q=input w=int (where space is newline) \$\endgroup\$ – daniero Jul 10 '13 at 11:40
  • \$\begingroup\$ The reason for casting to int in Python 3 is input is not the same function : see this SO answer \$\endgroup\$ – ThinkChaos Feb 2 '14 at 11:04
0
\$\begingroup\$

Python

One-statement Solution

Python 3 (60 chars, 66 with spaces)

print(sum(x for x in(int(input())for _ in[1]*int(input()))if x>0))

Python 2 (48 chars, 55 with spaces)

print sum(x for x in(input()for _ in[1]*input())if x>0)

May be shortened by one character

i=input
print sum(x for x in(i()for _ in[1]*i())if x>0)
\$\endgroup\$
0
\$\begingroup\$

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
 static class Program
 {
   static void Main(string[] args)
   {
     Console.WriteLine(Console.In.ReadToEnd().Split('\n').Sum(l => { Int32 v; return Int32.TryParse(l, out v) ? v.To(1000).Where(x => x > 0).Sum() : 0; }));

    }
    static IEnumerable<int> To(this int a, int b) { for (var i = a; a <= b; a++) { yield return i; } }
  }
}
\$\endgroup\$
0
\$\begingroup\$

PERL, 21 chars (score 20)

$a+=<>for 1..<>;say$a
\$\endgroup\$
  • \$\begingroup\$ I don't get it, how this eliminates negative numbers from the sum? \$\endgroup\$ – nutki Feb 11 '15 at 10:04
0
\$\begingroup\$

dc, 22 chars

0?[sa?+la1-d0<b]dsbxrp

Negative numbers must be specified in the dc notation, i.e. with underscore: _20.

\$\endgroup\$
0
\$\begingroup\$

Smalltalk, 79

b:=[:x|Number readFrom:Stdin].(((1 to:(b value:1))collect:b)select:[:i|i>0])sum
\$\endgroup\$
0
\$\begingroup\$

Windows Batch, 68 (characters >= 32)

I was about to post an extremely simple solution, but then I realised you have to read the number of test cases. Initially I just had for %%a in (%*)do set/a"i+=%%a" echo %i%.

set/p t=
for /l %%i in (1 1 %t%)do call :a
echo %i%
:a
set/p N=
if %n% geq 0 set/a"i+=N"

It reads t, then each N from stdin.

\$\endgroup\$
0
\$\begingroup\$

Python, 41

i=input
print sum(len(" "*i())for j in[0]*i())

Python, 42

c=""
i=input
exec'c+=" "*i();'*i()
print len(c)
\$\endgroup\$
  • \$\begingroup\$ This is a pretty smart solution. FWIW, I think the \n should count as two characters, as that's what it is in your source code before being executed. \$\endgroup\$ – mackthehobbit Mar 5 '14 at 11:07
0
\$\begingroup\$

J - 22 char

All these inputs blowing up the character count. Envious of APL here...

+/0>.".1!:1#&1".1!:1]1

Explained:

  • 1!:1]1 - Read in a line of input (1!:1) from input (file handle 1).
  • #&1". - Convert to an integer (".) and create a list of 1s that long (#&1).
  • ".1!:1 - Read in a line for each 1 in the list, and convert them to integers.
  • 0>. - Take the greater of each integer and 0, effectively zeroing the negative numbers.
  • +/ - Sum all the integers together.

Usage:

   +/0>.".1!:1#&1".1!:1]1
3
11
909
-67
920
\$\endgroup\$
  • \$\begingroup\$ You can use echo for the output. \$\endgroup\$ – FUZxxl Jul 19 '15 at 11:59
0
\$\begingroup\$

K - 20 char -2 = 18 pts

Had two 20 char solutions, and this one has more whitespace.

(. 0:`){x+0|. 0:`}/0

Explained:

  • n f/0 - Apply the function f to 0, n times.

  • (. 0:`) - Read in a line (0:) from input (file handle `) and convert to integer (.).

  • {x+0|. 0:`} - Read in an integer (. 0:`), take the greater of it and zero (0|), and add it to the argument (x+).

Usage:

  (. 0:`){x+0|. 0:`}/0
4
123
-99
12
9
144
\$\endgroup\$
0
\$\begingroup\$

JavaScript 93

Works for t integers, but said integers need to be entered with spaces in between.

y=(x=prompt().replace(/-\d{1,4}/g,"").replace(/ /g,"")).length;for(s=0;y--;)s+=+x[y];alert(s)

Takes the prompt, strips negative numbers and spaces, and adds the numbers...

\$\endgroup\$
0
\$\begingroup\$

Pyth - 7

Input in pyth is only one line, so it accepts comma-delimited instead of newline delimited. Pyth is not on Spoj, but there wasn't any rule saying it had to be.

sf>TZtQ

Very simple:

s      sum
f      filter by
>TZ    filter arg greater than zero
tQ     run filter on all but first element of evaluated input
\$\endgroup\$
0
\$\begingroup\$

C#, score: 174

using System;

class P
{
    static void Main(string[] a)
    {
        uint s = 0, t, n;
        for (uint.TryParse(Console.ReadLine(), out t); t-- > 0; uint.TryParse(Console.ReadLine(), out n), s += n) ;
        Console.WriteLine(s);
    }
}
\$\endgroup\$
0
\$\begingroup\$

C, 60 characters

There doesn't seem to be much to improve.

c;

main(x)
{
    while (0 < scanf("%d", &x))
        c += x * (x > 0);

    printf("%d", c);
}
\$\endgroup\$
0
\$\begingroup\$

Factor, 95 bytes

[ [ readln dup string>number ] [ string>number dup [ 2 * ] [ ] if ] produce [ 0 max ] map sum ]

Like a lambda; use it with call.

\$\endgroup\$
-1
\$\begingroup\$

C++ (96 points)

#include<iostream>
main()
{
int t,n,s=0;
for(std::cin>>t;t;std::cin>>n, --t, n>0?s+=n:s);
std::cout<<s;
}
\$\endgroup\$
-1
\$\begingroup\$

Python, 43

c=0
i=input
exec'b=i();c+=b*(b>0);'*i()
print c
\$\endgroup\$
-1
\$\begingroup\$

Python 52 Characters

c = 0
for i in range(t):
    k = input()
    if k>0:
        c+=k
print c 
\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG! It appears that neither spaces nor newlines should be included in the score, so I count your answer as 43, not 52. Also, it looks like three lines of your code are missing the indentation required by the for loop. \$\endgroup\$ – Martin Ender Sep 24 '15 at 10:58
  • \$\begingroup\$ @MartinBüttner Thanks for the correction. When i submitted my code, 52 was what i saw. \$\endgroup\$ – rajasekhar vanjarapu Sep 24 '15 at 14:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.