[PYTHON] One-liner addition with various scripts

The other day, it was a one-liner addition tournament in a company chat, so I will leave it as a reminder.

theme

Add the numbers 1-5 listed in the file below

$ cat num.txt
1
2
3
4
5

ShellScript

$ xargs < num.txt
1 2 3 4 5
$ xargs < num.txt | tr ' ' '+'
1+2+3+4+5
$ xargs < num.txt | tr ' ' '+' | bc
15
$ awk '{a=a+$0}END{print a}' < num.txt
15
$ S=0;while read N; do S=`expr "$N" "+" "$S"` ; done < num.txt ; echo $S
15
$ xargs < num.txt
1 2 3 4 5
$ xargs -n 1 < num.txt
1
2
3
4
5
$ xargs -n 1 seq < num.txt
1
1
2
1
2
3
1
2
3
4
1
2
3
4
5
$ xargs -n 1 seq < num.txt | wc -l
      15

Perl

$ perl -nale 'for(@F[0]){$sum+=$_}END{print $sum}' num.txt
15
$ perl -nE '$sum+=$_;END{say $sum}' num.txt
15

PHP

$ php -R '$a=$a+$argn;echo $a;echo "\n";' < num.txt | tail -n 1 
15
$ php -r "echo array_sum(file('num.txt'));"
15

Ruby

$ ruby -e 'puts ARGF.map(&:to_i).reduce(:+)' num.txt
15
$ ruby -ne 'BEGIN{$sum = 0}; $sum += $_.to_i; END{puts $sum}' num.txt
15
$ ruby -e 'p eval([*$<]* ".+")' num.txt
15

Python

$ python -c "import sys, operator;print reduce(operator.add, map(int, sys.stdin.readlines()))" < num.txt
15
$ python -c "print eval('+'.join(open('num.txt').read().split()))"
15

Recommended Posts

One-liner addition with various scripts
Various colorbars with Matplotlib
Control scripts with exceptions
Try various things with PhantomJS
Addition with Python if statement
Manipulate various databases with Python
Various memorandums developed with Choregraphe
Run scripts with Django's admin command
Utilize Python custom scripts with StackStorm
Various Fine Tuning with Mobilenet v2
[Python] One-liner Stalin sort with 50 characters
Sugoroku game and addition game with python
Handle various date formats with pandas