# Sum of positive integers. [closed]

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

• There are a lot more codegolf challenges at spoj.pl/SHORTEN. Don't see the point of duplicating them here though. – hallvabo Feb 24 '11 at 12:22
• why is this question tagged python.. Are we interested in python solution only? – Aman ZeeK Verma Feb 24 '11 at 13:56
• I don't think questions from contest sites should be posted here. – fR0DDY Feb 24 '11 at 14:01
• 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 :) – gnibbler Feb 24 '11 at 21:22
• 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. – st0le Feb 25 '11 at 9:36

## 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  • This can be modified into an alternative 20 char solution: -p0 s/\n\d+/$\+=$&/ge}{. 19 when not counting \n. – nutki Feb 11 '15 at 10:21 # Python 3, score: 63 61 r=0 q=input w=int for i in*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*q(): t=q() r+=t+abs(t) print r/2  Same as above, but python 2 doesn't need the casting to int, apparently. • So do I. I'm not entirely sure where 49 came from. – Cereal Jul 9 '13 at 19:34 • my mistake -- apparently characters with ascii value < 33 are discounted. – boothby Jul 9 '13 at 19:49 • 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) – daniero Jul 10 '13 at 11:40 • The reason for casting to int in Python 3 is input is not the same function : see this SO answer – ThinkChaos Feb 2 '14 at 11:04 # Python One-statement Solution ## Python 3 (60 chars, 66 with spaces) print(sum(x for x in(int(input())for _ in*int(input()))if x>0))  ## Python 2 (48 chars, 55 with spaces) print sum(x for x in(input()for _ in*input())if x>0)  May be shortened by one character i=input print sum(x for x in(i()for _ in*i())if x>0)  # 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; } } } }  # PERL, 21 chars (score 20) $a+=<>for 1..<>;say\$a

• I don't get it, how this eliminates negative numbers from the sum? – nutki Feb 11 '15 at 10:04

# dc, 22 chars

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


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

# Smalltalk, 79

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


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

## Python, 41

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


## Python, 42

c=""
i=input
exec'c+=" "*i();'*i()
print len(c)

• 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. – mackthehobbit Mar 5 '14 at 11:07

# 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

• You can use echo for the output. – FUZxxl Jul 19 '15 at 11:59

# 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


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

# 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


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


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


# Factor, 95 bytes

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


Like a lambda; use it with call.

# 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;
}


# Python, 43

c=0
i=input
exec'b=i();c+=b*(b>0);'*i()
print c


Python 52 Characters

c = 0
for i in range(t):
k = input()
if k>0:
c+=k
print c

• 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. – Martin Ender Sep 24 '15 at 10:58
• @MartinBüttner Thanks for the correction. When i submitted my code, 52 was what i saw. – rajasekhar vanjarapu Sep 24 '15 at 14:46