# 'Add' up the letters in a word

My dad is a retired teacher, and he used to give combined spelling and math quizzes, where the student would spell a word, and then 'score' the word by adding up the letters, where a=1, b=2, etc. (e.g. cat = 3+1+20=24). This made grading the quizzes easier, as he would just have to check for incorrect 'scores' rather than incorrectly spelled words, and had the added benefit of testing 2 skills at once.

He hired a friend of mine to write a program that would score words for him, so he could generate lengthy answer keys without error. This problem is inspired by that program.

Requirements:

1. Accept any word with uppercase and lowercase letters
2. Return an error for any special characters, i.e. spaces, hyphens, @^%# etc.
3. a=1, b=2,... and A=1, B=2,...
4. Print the score of the word
5. (Optional) check that the word is in a dictionary after scoring, and print a warning if it is not.
6. No importing an external letter->number dictionary. You must generate it yourself.

Any language is acceptable. This is similar to the 'digital root battle,' but much simpler.

• Is this supposed to be a code golf? Commented Apr 23, 2011 at 18:08
• @Zach Using the code-golf tag. Commented Apr 23, 2011 at 18:24
• Yeah, only checking scores? I'd spell cat as aaaaaaaaaaaaaaaaaaaaaaaa. Dad: Score is 24? That's right! Commented May 8, 2016 at 14:13
• @ericw31415 Every hashing function has collisions ;-). So far none of his students have tried that attack vector
– Zach
Commented May 9, 2016 at 15:39
• @Zach Also, it would be too complex if his dad made his students do SHA-512 of their words. Commented May 10, 2016 at 20:42

$_=gets.upcase;p~/[^A-Z]/?_:$_.sum-64*~/$/  The error message this generates isn't exactly helpful, though. Both solutions posted here assume the input has no trailing linebreak, so to test them, use echo -n. ## Ruby, 76 characters with dictionary check l=STDIN.gets;$_=l.upcase;p~/[^A-Z]/?_: $_.sum-64*~/$/;[*$<].index(l)||$><<?W


The warning message consists of the single character "W". The path to the dictionary has to be supplied via ARGV. Example usage:

$echo -n asd | ruby addletters.rb /usr/share/dict/words 24 W$ echo -n cat | ruby addletters.rb /usr/share/dict/words
24

• You could chop of 9 characters in the dictionary check version by making the error message an exclamation mark. Commented Apr 24, 2011 at 16:55
• You get a consolation prize for the shortest entry with a dictionary check. Way to go!
– Zach
Commented Apr 26, 2011 at 12:49
• Why was the dictionary check proposed if it doesn't give you any real edge (on the contrary, it just bloated the code)? Commented Apr 27, 2011 at 17:23

## Golfscript - 23 chars

0\{.31&.(.26%=@64///+}/


Ensure there are no trailing newlines in input (e.g. use echo -n).

• We have a new winner!
– Zach
Commented Apr 26, 2011 at 15:48
• Generally, external filtering is supposed to be included in character count somehow (Ctrl-f external filtering.), though I assume it's only 2 extra characters to do without. Commented Apr 26, 2011 at 16:29
• @Jesse: echo -n really doesn't count as external filtering -- in fact the answer you linked suggests it as a valid form for input.
– Nabb
Commented Apr 27, 2011 at 5:25

# Python (65 64)

print sum(['',ord(i)-64]['@'<i<'[']for i in raw_input().upper())


This raises an error if the word contains non-letter characters, but not a helpful or informative one. (Edit: tip of the hat to st0le for the indexing trick.)

• print sum(['',ord(i)-64]['@'<i<'[']for i in raw_input().upper()) shaved a couple of chars. Commented Apr 24, 2011 at 5:03
• Just one char actually. :-\ Commented Apr 24, 2011 at 5:09
• Save 4 characters by using input; forces user to put quotes around input strings, but "user-friendly" and "not dangerous" aren't in the spec!
– jscs
Commented Apr 24, 2011 at 7:15
• Well, just change it to Python 3! raw_inputinput Commented May 3, 2011 at 12:26
• print sum([i,ord(i)-64]['@'<i<'[']for i in raw_input().upper()) another byte shaved Commented May 8, 2016 at 20:01

# Python 2.6 (72 Chars) Without dictionary check

print sum(map(" abcdefghijklmnopqrstuvwxyz".index, raw_input().lower()))


# Python 2.6 (178 Chars*) With dictionary check

w=raw_input().lower()
print sum(map(" abcdefghijklmnopqrstuvwxyz".index, w))
print('Word not in dictionary')


*Can be lowered to 156 with a less helpful error message. :-)

Thanks to all commenters for helping improve this.

• You might want to consider using the sum builtin with a generator expression, rather than a for loop. It would let you trim off a few chars (~17).
– user1011
Commented Apr 24, 2011 at 0:53
• @jloy: Thanks for pointing that out.
– John
Commented Apr 24, 2011 at 2:13
• the parentheses on print can be eliminated Commented Apr 24, 2011 at 5:11
• its seems you're using a just once, so use the literal itself..."0abc....z".index(i) will work equivalently. Commented Apr 24, 2011 at 5:13
• The 0 in your scoring array is clever, but it also means that cat0 is accepted without error, which isn't right, I think. Which is too bad, since it would allow you to pass map(a.index,w) to sum instead (substituting the literal for a as st0le suggests).
– user1011
Commented Apr 24, 2011 at 6:06

## Python (80)

w=raw_input().lower()
s=0
for l in w:s+=range(97,123).index(ord(l))+1
print s


## Python v2 (65 but char  will get accepted)

print sum(map(range(96,123).index,map(ord,raw_input().lower())))


## v3 (60 chars, @ will be accepted but not counted, thanks jloy)

print sum(map(range(64,91).index,map(ord,input().upper())))

• HINT: THERE IS A WAY TO REMOVE ONE MORE CHAR FROM YOUR SOLUTIONS. :)
– user1011
Commented Apr 25, 2011 at 6:49
• @jloy What a helpful 'hint'. ;) Commented May 1, 2011 at 21:14

## Scala: 59 chars, 7 of them payload, no dict:

(0/:"Payload".map(c=>if(c.isLetter)(c-'A')%32 else-999))(_+_)
67


No dictionary so far. Negative result means: Negative!

(0/:"Pay!wall?".map(c=>if(c.isLetter)(c-'A')%32 else-999))(_+_)
-1915


Handles German Umlaute gracefully, by the way:

(0/:"Müllrößchen".map(c=>if(c.isLetter)(c-'A')%32 else-999))(_+_)
155

• Wow, less chars than the Perl version (and still more readable). Commented Apr 24, 2011 at 9:41
• I tried SHiNKiROUs and chinesis-Perl-solution, but they didn't work for me. Saved them as alpha.pl and started them by perl alpha.pl. Do they just handle Ascii? Well - at Perl is such an old beast ... :) Commented Apr 24, 2011 at 11:32
• Perl and Unicode is a big mess. You probably have to run them as perl -M5.010 alpha.pl or something like that. Commented Apr 24, 2011 at 19:38
• I heard that I need single quotes instead of double quotes on Linux, and this worked, thanks. Commented Apr 24, 2011 at 21:48

# Java + Google Guava libraries, 347 characters, with dictionary check

Unreadable 1 long string version :-)

import java.io.*;import com.google.common.base.*;import com.google.common.io.*;class C{public static void main(String[]a)throws Exception{int s=0;for(int c:a[0].toUpperCase().toCharArray()){assert(c>64&&c<91);s+=c-64;}String d=Files.toString(new File(a[1]),Charsets.UTF_8);if(StringUtils.containsIgnoreCase(d,a[0]))System.out.println("w");System.out.println(s);}}


import java.io.*;

class C {
public static void main(String[] a) throws Exception {
int s=0;

for(int c : a[0].toUpperCase().toCharArray()) {
System.out.println(c);
assert(c > 64 && c < 91);
s += c - 64;
}

String d = Files.toString(new File(a[1]), Charsets.UTF_8);

if (d.contains(a[0])) System.out.println("w");

System.out.println(s);
}
}


The dictionary path is now passed in via a[1], for assertions to work you have to use the -eaflag (+3 more chars). As for the dictionary, the dict /usr/share/dict/words (should be available on most *nix systems) has been used.

• So far you're the only one with a dictionary check, so +1
– Zach
Commented Apr 24, 2011 at 0:18
• one line? this isn't particularily readable this way, though i guess it saves chars Commented Apr 24, 2011 at 0:22
• I will add a more readable solution (and also a shorter one using Google Guava to reduce boilerplate code). Commented Apr 24, 2011 at 9:27
• You just allow ascii, but use Charset.UTF-8? Commented Apr 24, 2011 at 11:12
• Because the String UTF-8 is shorter than the other charsets :-). Commented Apr 24, 2011 at 11:18

## Python 3, 95 chars with dictionary

d=input().lower()
print(d in open("d").read()and sum(['',ord(c)-96][''<c<'{']for c in d)or'f')


The dictionary has to be in a file called d.

### Python 3, 61 without dictionary, but stolen idea

print(sum(['',ord(c)-96][''<c<'{']for c in input().lower()))


# VB.NET, 848273 71

Console.Write(Console.ReadLine.Sum(Function(c)Asc(Char.ToUpper(c))-64))


Edit: With validation is:

Dim r=Console.ReadLine


129 characters. In which case:

# C#, 118

var r=Console.ReadLine();Console.Write(r.All(char.IsLetter)?r.Sum(c=>char.ToUpper(c)-64).ToString():"Invalid input.");

• This doesn't validate the input. Commented Apr 23, 2011 at 21:09
• Oops! Hold on a second...
– Ry-
Commented Apr 23, 2011 at 21:22
• I think you should provide complete programs. Your C# solution doesn’t compile; you need to place it in a Main method inside a class declaration, and count all the characters. Commented Apr 24, 2011 at 13:07
• No, because that code doesn't do anything, and it's not fair to disadvantage users of object-oriented languages. This is valid C#/VB.NET anyways.
– Ry-
Commented Apr 24, 2011 at 18:50

# Improving slightly on John's answer: Python (90)

s=0
for i in raw_input().lower():
s+=("abcdefghijklmnopqrstuvwxyz".index(i)+1)
print(s)

• adding the dummy char in the string beginning is shorter...parentheses can be removed Commented Apr 24, 2011 at 5:14

# Erlang, 104

a()->
a(string:to_lower(io:get_line([])),0).
a([_|[]],S)->
S;
a([C|R],S) when C<${, C>=$->
a(R,S+C-$).  ## Perl (52) (48) golfed even more thanks to Timwi perl -lpe "($w=uc)=~/[^A-Z]/&&die;$w=~s/./$_-=64-ord$&/ge" • You're missing the -e flag there. Commented Apr 23, 2011 at 21:11 • You should at least include the p and l interpreter flags in your character count. See this discussion on meta. Commented Apr 23, 2011 at 23:12 • syntax error at -e line 1, near "(=" Execution of -e aborted due to compilation errors. What am I doing wrong? Commented Apr 24, 2011 at 11:22 • if you're running on unix, change double quotes to single ones Commented Apr 24, 2011 at 11:22 • @Timwi: 'Accept any word with uppercase and lowercase letters' went to the wrong thread, sorry. I deleted it now. @chinese: Yes, thanks, with single quotes it's ok. As long as I restrict myself to ascii input. :) Commented Apr 24, 2011 at 16:32 Golfscript - 39 chars n%~{.96>{96}{64}if-..26>\0<|{0/}*}%{+}*  The error it throws is not exactly the best, but hey, it aborts execution. • I don't know anything about golfscript, so I'm going to assume this meets the requirements and declare you the winner! – Zach Commented Apr 26, 2011 at 12:45 • Whoops, you've been beat! I guess 2 days isn't long enough to wait on a code golf question? – Zach Commented Apr 26, 2011 at 15:48 ## PYTHON 62 68* Characters print sum(map(chr,range(65,91)).index(c)+1 for c in input().upper())  Requires user to input strings using quotes, and is not safe (input executes code), but, as I said in a comment to another post, "user-friendly" and "not a security risk" ain't in the spec! * I forgot about print, dammit. • jloy's answer is still shorter, actually, because of the input/raw_input difference. – jscs Commented Apr 24, 2011 at 21:54 # Husk, 17 bytes ?osṁo%32c¹¨eŻ→¨Λ√  Try it online! Returns 'error' for invalid input, score of word otherwise. ? Λ√ # if every element is a letter os # return the string of ṁ c¹ # the sum of all their ASCII values o%32 # MOD 32 ¨eŻ→¨ # otherwise, return the compressed string # "error"  If it's acceptable to return '0' as the 'error' for invalid input, we can have a 11 byte 10 byte 9 byte solution: §&ṁ%32Πm√  # 05AB1E, 15 bytes lvAyk>})D0åi0ëO  Try it online! Returns 0 on error. lvAyk>})D0åi0ëO # full program v # for y in... # implicit input... l # lowercased... k # push 0-based index of... y # y... k # in... A # the lowercase alphabet... k # or -1 if not found... > # plus 1 } # end loop i # if... 0 # 0... å # is in... ) # stack... 0 # push 0 ë # else... O # push sum... D # of stack # implicit output  ## Ruby 1.9, 69 w=gets.chop.upcase w[/[^A-Z]/]&&fail p w.bytes.inject(0){|s,b|s+b-64}  • Does only handle ascii characters. I thought Ruby is from our century? :) Commented Apr 24, 2011 at 11:31 • @user unknown: The spec doesn't say it has to. Doing it would be rather complicated... Commented Apr 24, 2011 at 11:41 ## Perl (71) ($a)=lc<>;$a=~/[^a-z]/i&&die;$x+=ord$_ for split//,$a;die$x-96*length$a;


# GolfScript, 50(53)

Gives an error on bad characters, but not a very good one (50 characters):

);[{""123,97>+91,65>+?}/].-1?0<{{26%1+}%{+}*}{@}if


Gives "E" on error instead (53 characters):

);[{""123,97>+91,65>+?}/].-1?0<{{26%1+}%{+}*}{;"E"}if


The alphabet-generating snippet 123,97>+ is stolen from Ventero .

# J (55)

+/64-~-&32]@.(<&97)_:@.(<&65)_:@.(>&122)"0,I.a.&e."0


This satisfies all the conditions except the dictionary one. As an error condition, it returns "infinity" (the underscore symbol in J) for words that contain anything but letters.

(raises an error on weird characters)
(also: the space between toUpper. and \x is needed otherwise it parses it as(toUpper) .\ (x))

import Char
main=getLine>>=putStrLn.show.sum.(map$(-65+).ord.toUpper. \x->if xelem['A'..'Z']++['a'..'z']then x else error"")  # Haskell (70) (does not raise an error, but 45% shorter) import Char main=getLine>>=putStrLn.show.sum.(map$(-65+).ord.toUpper)


## C++ (111 107)

void main(){int a=0;s8*b=new s8[99];for(cin>>b;*b;)if(isalpha(*b))a+=tolower(*b++)-96;else return;cout<<a;}


The "set up"/etc:

#include <iostream>
#include <cstdio>
#include <cctype>

#ifdef _MSC_VER
typedef __int8 s8;
#else
typedef signed char s8;
#endif


"Undefined" behavior (It's more 'bad practice' than 'undefined', but oh well):

• void main() That says it all.
• I'm using new without delete.

# Jelly, 10 9 bytes

ŒuØAiⱮoµS


Try it online!

Seemingly, it turns out a byte shorter to actually error than to return 0.

Œu           Uppercase the input,
Ɱ       of each letter from the input
ØA         in "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
o      replace any 0 with the corresponding character of the input,
µS    then take the sum.


Jelly errors if it attempts to add integers and strings together, and although two strings can be added together by +, this still errors in the case of a fully symbolic input because S is defined specifically as a reduce starting from zero.

• Nice. It'll be tough to better (or even match) 9-bytes... Commented Nov 19, 2020 at 22:21

## JavaScript 1.8, 80 chars

alert(Array.reduce(prompt().toLowerCase(),function(a,b)a+b.charCodeAt(0)-96,0))

• For use in Chrome I had to convert it a little: alert(prompt().toLowerCase().split("").reduce(function(a,b){return a+b.charCodeAt(0)-96},0)). I still like JavaScript solutions most :) Commented Jun 2, 2011 at 9:32
• It doesn't return an error when you do invalid character??? Commented May 8, 2016 at 14:07

## APL (34)

+/{⍵∊⍳26:⍵}¨{64-⍨A-32×96<A←⎕UCS⍵}⍞


Gives either the score, or a VALUE ERROR if there are non-alphabetic characters in the input.

Explanation:

• ⍞: read a line of input
• {...}: function applied to every character of input
• A←⎕UCS⍵: store the ASCII value of the current character in A
• A-32×96<A: make character uppercase: from A is subtracted 32 if 96<A (so, if it's uppercase), otherwise 0
• 64-⍨: subtract 64 from this, giving A=1, B=2 ...
• ¨: apply this function to every character:
• ⍵∊⍳26: if the character is between 1 and 26...
• :⍵: then return ⍵ (and since there's no else clause there will be a VALUE ERROR if it's not between 1 and 26)
• +/: sum all the values together (and this value is automatically outputted because it's the final result).

# JavaScript, 60 bytes

s=>[...s.toUpperCase()].reduce((a,b)=>a+b.charCodeAt()-64,0)


If the program must return an error on invalid inputs, then 80 bytes:

s=>/[^a-z]/i.test(s)?_:[...s.toUpperCase()].reduce((a,b)=>a+b.charCodeAt()-64,0)


If an input is invalid, then the console will say that _ is not defined (there must not already be a variable defined called _).

# Python 3, 58 55

print(sum(ord(x)%32for x in input()if x.isalpha()or z))


without dictionary or stolen idea but still unhelpful error ;)

thx @Eᴀsᴛᴇʀʟʏ

Test here.

• I think you can save a byte by switching to python 2 and doing print<SPACE>sum(ord(......., removing the 2 parentheses around the expression. Commented May 8, 2016 at 20:48
• @EᴀsᴛᴇʀʟʏIʀᴋ that is right but than the input has to be in parenthesis and I don't want to promote python 2 ;) Commented May 8, 2016 at 20:52
• PYTHON 2 IS LIFE!! and also, I don't think that would require the input to be parenthesized? Commented May 8, 2016 at 21:52
• @EᴀsᴛᴇʀʟʏIʀᴋ sry i meant quoted. input() in python3 is raw_input() in python2 Commented May 8, 2016 at 23:34
• oh, I forgot. Hm. Commented May 9, 2016 at 1:11

# C, 98 bytes

 int a(char *s){int b=0;while(*s){if(!isalpha(*s))throw 1;b+=(toupper(*(s++))-64);}printf("%d",b);}


# F# (no validation) 79 57 chars

let a w=w|>Seq.fold(fun a b->a+(int b)-65)0|>printfn"%i"


# C# with validation: 108 chars (with 12 for error message):

var s=Console.ReadLine();Console.Write(s.All(Char.IsLetter)?s.Sum(x=>x&'_'-'@').ToString():"Invalid input");


# C# without validation: 60 53 chars:

Console.Write(Console.ReadLine().Sum(x=>x&'_'-'@'));

• In the second one without validation, you can reduce the characters even more by removing the s variable declaration and using Console.ReadLine() inline. Commented Jun 3, 2012 at 9:15