Мой папа - учитель на пенсии, и он давал комбинированные тесты по орфографии и математике, где студент записывал слово, а затем «набирал» слово, складывая буквы, где a = 1, b = 2 и т. Д. (например, кошка = 3 + 1 + 20 = 24). Это облегчало оценку тестов, так как он должен был просто проверять правильность «оценок», а не неправильно написанных слов, и имел дополнительное преимущество в тестировании 2 навыков одновременно.
Он нанял моего друга, чтобы он написал программу, которая будет набирать слова для него, чтобы он мог генерировать длинные ключи ответа без ошибок. Эта проблема вдохновлена этой программой.
Требования:
- Принять любое слово с прописными и строчными буквами
- Вернуть ошибку для любых специальных символов, например пробелов, дефисов, @ ^% # и т. Д.
- a = 1, b = 2, ... и A = 1, B = 2, ...
- Распечатать счет слова
- (Необязательно) проверьте, что слово находится в словаре после оценки, и выведите предупреждение, если это не так.
- Нет импорта внешнего письма-> словарь цифр. Вы должны создать это самостоятельно.
Любой язык приемлем. Это похоже на « цифровую корневую битву» , но намного проще.
code-golf
тэга.aaaaaaaaaaaaaaaaaaaaaaaa
. Папа: оценка 24? Это верно!Ответы:
Golfscript - 23 chars
Ensure there are no trailing newlines in input (e.g. use
echo -n
).источник
echo -n
really doesn't count as external filtering -- in fact the answer you linked suggests it as a valid form for input.Brainf*** (100)
I do have to admit though, this does not quite comply with all of the requirements. First, it only accepts capital letters, and the word must be ended with a tab. It has undefined behaviour for invalid characters, and does not throw an error. It displays the sum of the letters as an ASCII character. For example, if the word is "HELLO", (8+5+12+12+15 = 52) it will display the character "4", which is the ASCII character for 52. This also means that the program freaks out when the sum is more than 255.
But other than that, it works just fine. Give me a break, my brain can only handle small doses of...well, you know.
источник
\n
or\r\n
or\n\r
. And If I used newline, I wouldn't have a nice round number like 100 as the character count.Python (
6564)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.input
; forces user to put quotes around input strings, but "user-friendly" and "not dangerous" aren't in the spec!raw_input
→input
print sum([i,ord(i)-64]['@'<i<'[']for i in raw_input().upper())
another byte shavedRuby, 43 characters
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
The warning message consists of the single character "W". The path to the dictionary has to be supplied via ARGV. Example usage:
источник
Python 2.6 (72 Chars) Without dictionary check
Python 2.6 (178 Chars*) With dictionary check
*Can be lowered to 156 with a less helpful error message. :-)
Thanks to all commenters for helping improve this.
источник
sum
builtin with a generator expression, rather than afor
loop. It would let you trim off a few chars (~17).a
just once, so use the literal itself..."0abc....z".index(i)
will work equivalently.0
in your scoring array is clever, but it also means thatcat0
is accepted without error, which isn't right, I think. Which is too bad, since it would allow you to passmap(a.index,w)
tosum
instead (substituting the literal fora
as st0le suggests).Perl
(52)(48)golfed even more thanks to Timwi
perl -lpe "($w=uc)=~/[^A-Z]/&¨$w=~s/./$_-=64-ord$&/ge"
источник
-e
flag there.p
andl
interpreter flags in your character count. See this discussion on meta.syntax error at -e line 1, near "(=" Execution of -e aborted due to compilation errors.
What am I doing wrong?Python (80)
Python v2 (65 but char ` will get accepted)
v3 (60 chars, @ will be accepted but not counted, thanks jloy)
источник
Scala: 59 chars, 7 of them payload, no dict:
No dictionary so far. Negative result means: Negative!
Handles German Umlaute gracefully, by the way:
источник
alpha.pl
and started them byperl alpha.pl
. Do they just handle Ascii? Well - at Perl is such an old beast ... :)perl -M5.010 alpha.pl
or something like that.Java + Google Guava libraries, 347 characters, with dictionary check
Unreadable 1 long string version :-)
Human-readable version (sort of :-))
The dictionary path is now passed in via
a[1]
, for assertions to work you have to use the-ea
flag (+3 more chars). As for the dictionary, the dict/usr/share/dict/words
(should be available on most *nix systems) has been used.источник
UTF-8
is shorter than the other charsets :-).Python 3, 95 chars with dictionary
The dictionary has to be in a file called d.
Python 3, 61 without dictionary, but stolen idea
источник
Perl (71)
источник
VB.NET,
84827371Edit: With validation is:
129 characters. In which case:
C#, 118
источник
Improving slightly on John's answer: Python (90)
источник
Erlang, 104
источник
Golfscript - 39 chars
The error it throws is not exactly the best, but hey, it aborts execution.
источник
PYTHON
6268* CharactersRequires 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.источник
input
/raw_input
difference.Ruby 1.9, 69
источник
GolfScript, 50(53)
Gives an error on bad characters, but not a very good one (50 characters):
Gives "E" on error instead (53 characters):
The alphabet-generating snippet
123,97>+
is stolen from Ventero .источник
J (55)
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.
источник
Haskell (127)
(raises an error on weird characters)
(also: the space between
toUpper.
and\x
is needed otherwise it parses it as(toUpper)
.\
(x)
)Haskell (70)
(does not raise an error, but 45% shorter)
источник
C++ (
111107)The "set up"/etc:
"Undefined" behavior (It's more 'bad practice' than 'undefined', but oh well):
void main()
That says it all.new
withoutdelete
.источник
JavaScript 1.8, 80 chars
Surprisingly readable!
источник
alert(prompt().toLowerCase().split("").reduce(function(a,b){return a+b.charCodeAt(0)-96},0))
. I still like JavaScript solutions most :)APL (34)
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 inputA←⎕UCS⍵
: store the ASCII value of the current character inA
A-32×96<A
: make character uppercase: fromA
is subtracted 32 if96<A
(so, if it's uppercase), otherwise 064-⍨
: 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 aVALUE 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
If the program must return an error on invalid inputs, then 80 bytes:
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,
5855without dictionary or stolen idea but still unhelpful error ;)
thx @Eᴀsᴛᴇʀʟʏ
Test here.
источник
print<SPACE>sum(ord(.......
, removing the 2 parentheses around the expression.input()
in python3 israw_input()
in python2C, 98 bytes
источник
F# (no validation)
7957 charsисточник
C# with validation: 108 chars (with 12 for error message):
C# without validation:
6053 chars:источник
Perl (
4231)I hope counting F, p, a and l as 1 character was correct.
источник
JavaScript, 68 Bytes
This can almost certainly be golfed more
With dictionary check (Node.js & Unix Descendants only) 195 Bytes
Uses
/usr/share/dict/words
, and can definitely be shortened (see the warn message)источник
console.error()
, notconsole.warn()
.