단어 계산기


14

영어 숫자 계산기 의 간단한 버전

직무

문자열을 입력으로 받아서 표현식의 결과를 출력하는 프로그램을 작성하십시오.

규칙

입력 문자열은 숫자가 아닌 단어로 표시됩니다.

괄호는 없습니다.

계산 순서는 나누고 곱하고 빼고 더합니다.

동일한 작업을 수행하려면 왼쪽에서 오른쪽으로 계산해야합니다.

모든 입력 숫자는 -999에서 999 사이의 정수입니다 (둘 다 포함).

출력은 모든 범위의 정수입니다.

나눗셈은 항상 완벽하게 나눌 수 있으며 0은 분모가 될 수 없습니다.

입력 케이스 제한은 선택 사항입니다. 입력의 유효성을 확인할 필요는 없습니다.

숫자 형식

0 to 20 -> zero,one,two...nineteen,twenty
21 to 99 -> twenty one,twenty two.....ninety eight,ninety nine
100 to 999 -> one hundred, one hundred one, one hundred two...one hundred ten....two hundred fifty....nine hundred ninety eight,nine hundred ninety nine

음수의 경우 : minus양의 값에 더합니다

작업 형식

Addition: one plus two
Subtraction: one minus two
Multiplication: one time two #Note that for one on the left of multiplication, it is one time and not times.
                two times one hundred
Division: forty divided by two

예 :

o/p <- input

20     four times five
35     twenty plus fifteen
70     fifty plus five times four
-90    minus one time ninety
25     twenty one minus minus four
45     ninety divided by two
700    one time seven hundred 
555    one hundred eleven times two plus three hundred thirty three
99     one hundred plus minus one
45     forty five plus two hundred times zero
 4     four
-3     three minus three minus three

이것은 코드 골프이므로 가장 짧은 코드가 승리합니다.


1
복제? -그렇게 생각하기에 충분히 가깝다고 생각합니다.
Kirill L.

2
실제로 매우 가깝습니다. 그러나 나는 이것이 더 명확하고 합리적인 한계가 있다고 생각합니다.
Arnauld

1
@Arnauld 나는 이것을 열어두고 다른 사람들이 다르게 생각하면 그것을 중복으로 표시하십시오.
Vedant Kandoi

15
나는 말한다 one times two. time정상적으로 사용하고 있습니까?
조 왕

2
나는 당신이 '한 번 의미 생각 칠백'?
ouflak

답변:


18

자바 스크립트 (ES6), 257 252 249 235 바이트

@Shaggy 덕분에 3 바이트 절약

s=>eval(s.split` `.map(w=>(i='zeonwohrr44fx3n5t54nn3leel8tou7fn7n98etetwthfofisiseeinihuplmitidiby'.match(/../g).findIndex(x=>~(w+w.length+w).search(x)))>28?n+' '+'+-*/ '[n='',i-29]:(n=+n+(i<28?i<20?i:i*10-180:n*99),''),n='').join``+n)

온라인으로 사용해보십시오!

어떻게?

나는++

번호

 index | word              | word + length + word         | key substring
-------+-------------------+------------------------------+---------------
    0  | "zero"            | "zero4zero"                  | "ze"
    1  | "one"             | "one3one"                    | "on"
    2  | "two"             | "two3two"                    | "wo"
    3  | "three"           | "three5three"                | "hr"
    4  | "four"            | "four4four"                  | "r4"
    5  | "five"            | "five4five"                  | "4f"
    6  | "six"             | "six3six"                    | "x3"
    7  | "seven"           | "seven5seven"                | "n5"
    8  | "eight"           | "eight5eight"                | "t5"
    9  | "nine"            | "nine4nine"                  | "4n"
   10  | "ten"             | "ten3ten"                    | "n3"
   11  | "eleven"          | "eleven6eleven"              | "le"
   12  | "twelve"          | "twelve6twelve"              | "el"
   13  | "thirteen"        | "thirteen8thirteen"          | "8t"
   14  | "fourteen"        | "fourteen8fourteen"          | "ou"
   15  | "fifteen"         | "fifteen7fifteen"            | "7f"
   16  | "sixteen"         | "sixteen7sixteen"            | "n7"
   17  | "seventeen"       | "seventeen9seventeen"        | "n9"
   18  | "eighteen"        | "eighteen8eighteen"          | "8e"
   19  | "nineteen"        | "nineteen8nineteen"          | "te"
   20  | "twenty"          | "twenty6twenty"              | "tw"
   21  | "thirty"          | "thirty6thirty"              | "th"
   22  | "forty"           | "forty5forty"                | "fo"
   23  | "fifty"           | "fifty5fifty"                | "fi"
   24  | "sixty"           | "sixty5sixty"                | "si"
   25  | "seventy"         | "seventy7seventy"            | "se"
   26  | "eighty"          | "eighty6eighty"              | "ei"
   27  | "ninety"          | "ninety6ninety"              | "ni"
   28  | "hundred"         | "hundred7hundred"            | "hu"

연산자

 index | word              | word + length + word         | key substring
-------+-------------------+------------------------------+---------------
   29  | "plus"            | "plus4plus"                  | "pl"
   30  | "minus"           | "minus5minus"                | "mi"
   31  | "times" or "time" | "times5times" or "time4time" | "ti"
   32  | "divided"         | "divided7divided"            | "di"
   33  | "by"              | "by2by"                      | "by"

해석

현재 번호는 나는

i > 28 ?                  // if the word is an operator:
  n +                     //   append n (which is either an empty string or a number)
  ' ' +                   //   append a space
  '+-*/ '[n = '', i - 29] //   reset n to an empty string and append the operator
                          //   the useless keyword 'by' is translated into a harmless space
: (                       // else:
    n =                   //   update n:
      +n + (              //     force the coercion of the current value of n to a number
        i < 28 ?          //     if the word is not 'hundred':
          i < 20 ?        //       if the value of the word is less than 'twenty':
            i             //         add i
          :               //       else:
            i * 10 - 180  //         add i * 10 - 180 (e.g. 'fifty' -> 23 * 10 - 180 = 50)
        :                 //     else:
          n * 99          //       multiply n by 100 by adding 99 * n to itself
      ),                  //
    ''                    //   remove this word from the original string
  )                       //

11

Perl 6 , 170139129128124122 바이트

nwellnhof 덕분에 -13 바이트!

{S:g/(<:N>+)+%\s/({'+'X$0})/.EVAL}o{S:g/" ҈"/00/}o{TR"⁢ʼn؊⟠"*/൰ "}o*.words>>.&{chr first *.uniname.comb(.uc),1..*}

온라인으로 사용해보십시오!

unival구조에 다시! 이것은 (현재) 심지어 같은 골프 언어를 때리는 것입니다 05AB1E!

설명:

*.words     # Split by word boundaries (in this case spaces)
       >>.{                            }  # Map each word to
           chr first             ,1..*    # The first character where:
                     *.uniname      # The unicode name of that character
                                    # e.g. DIGIT FIVE
                      .comb(.uc)    # Contains the uppercase of the word
{             }o  # Pass this list to another function
                  # That converts the list to a string
 TR"⁢ʼn؊⟠"*/൰ "    #"# And parse out the garbage characters that were wrong
                  # INVISIBLE TIMES => "*"
                  # LOZENGE DIVIDED BY HORIZONTAL RULE => "/"
                  # ARABIC-INDIC PER TEN THOUSAND SIGN => "൰" (value ten)
                  # LATIN SMALL LETTER N PRECEDED BY APOSTROPHE => " "
{S:g/" ҈"/00/}o   # Replace the character for "hundred" with 00

{                                }o   # And finally combine with
 S:g/(<:N>+)+%\s/   # Substitute each number-like character separated by spaces
                /({'+'X$0})/   # With the numbers prefixed by '+'s, in brackets
               # This works because Perl 6 supports numeric unicode literals, like
               # ፳ => 20, ፴ => 30, ፺ => 90, etc.
                            .EVAL   # And finally evaluate the whole expression

7

파이썬 2 , 333 ... 284 277 275 바이트

lambda s:eval(''.join((list('+-/*')+[`N(w,0)*100+N(w,2)`])['pmdt'.find(w)]for w in re.split(' *(?:(p|m)|(t|d)i|by).*? ',s)if w))
N=lambda x,y:sum(10*(w[-3:]in'lveen')+'zeontwthfofisiseeiniteel'.find(w[:2])/2*10**('y'in w)for w in x.rpartition('hundred')[y].split())
import re

온라인으로 사용해보십시오!


5

볼프람 언어 95 94 82 바이트

Interpreter["SemanticExpression"][#~StringReplace~{"me "->"mes ","plus m"->"m"}]&

# 순수 함수의 입력을 나타냅니다.

필요한 경우 StringReplace"시간"을 "시간"으로, "플러스 빼기"를 "빼기"( 각각 "me "->"mes ", "plus m"->"m")로 바꿉니다 . 에서 제안한 단축 된 대체 양식은 lirtosiast12 바이트를 절약했습니다.

Interpreter["SemanticExpression"] 나머지는 모두 수행합니다.


당신은 변경할 수 "time "->"times ""me"->"mes""plus minus"->"minus""plus m"->"m"?
lirtosiast

예. 훌륭한 제안.
DavidC

3

05AB1E , 166 (147) 141 (139) 135 바이트

„byK“¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁÏ“#vyN:}'tK'…§¦'+T«:'°¡„ *т«©:.•1×j›o!ĆÖ•3ôŽ9oS:'y®¨:©“‰´Øè„Æ€ººß“'tK#UX¡εð¡õK2ôJ.EO}®áX"+-**/"S:Sðì.ιJ.E

너무 깁니다. 여기에서 골프를 치려고합니다.

@Emigna 덕분에 -4 바이트 . @JoKing
덕분에 -2 바이트 .

온라인으로 시도 하거나 모든 테스트 사례를 확인하십시오 .

설명:

byK                 # Remove "by" from the (implicit) input-string
“¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁÏ“
                     # Push string "zero one two three four five six seven eight nine ten eleven twelve"
 #                   # Split by spaces
  v   }              # Loop over each of these items:
   yN:               #  Replace the item with its 0-indexed index
'tK                 '# Remove all "t"
'…§¦                '# Push string "teen", and remove the first character: "een"
    '+              '# Push string "+"
      T«             # Append 10: "+10"
        :            # Replace all "een" with "+10"
'°¡                 '# Push string "hundred"
    *               # Push string " *"
      т«             # Append 100: " *100"
        ©            # Store it in the register (without popping)
         :           # Replace all "hundred" with " *100"
.•4º»Ÿć'Rþн•        '# Push string "wenhirforfif"
            3ô       # Split the string into parts of size 3: ["wen","hir","for","fif"]
              Ž9o    # Push integer 2345
                 S   # Split to digits: [2,3,4,5]
                  :  # Replace each
'y                  '# Push string "y"
  ®                  # Push the " *100" from the register
   ¨                 # Remove the last character: " *10"
    :                # Replace all "y" with " *10"
©                    # Save the current string in the register (without popping)
 “‰´Øè„Æ€ººß“        # Push string "plus minus times time divided"
             'tK    '# Remove all "t": "plus minus imes ime divided"
                #    # Split by spaces: ["plus","minus","imes","ime","divided"]
                 U   # Pop and save it in variable `X`
                  X  # And push variable `X` back again
                   ¡ # Split the string by those operator-strings
ε          }         # Map each substring to:
 ð¡                  #  Split by spaces (NOTE: cannot be `#`; if the string contains no
                     #   spaces, `#` remains string, whereas `ð¡` wraps it in a list)
   õK                #  Remove empty strings from the list
     2ô              #  Split the list into parts of two
       J             #  Join each pair together
        .E           #  Evaluate each as a Python `eval` expression
          O          #  Sum them
®                    # Put the string from the register to the stack again
 á                   # Remove everything except for letters
  X                  # Push variable `X`: ["plus","minus","imes","ime","divided"]
   "+-**/"           # Push string "+-**/"
          S          # Split to characters: ["+","-","*","*","/"]
           :         # Replace each
S                    # Split the string of operators to loose characters
 ðì                  # Prepend a space before each
                   # Interweave all sums with these operator-characters
     J               # Join everything together to a single string
.E                   # Evaluate each as a Python `eval` expression (and output implicitly)

내이 05AB1E 팁을 참조하십시오 (섹션 어떻게 사전을 사용할 수 있나요? , 어떻게 압축 문자열 사전의 일부에? , 그리고 어떻게 큰 정수를 압축하는 방법? ) 을 이해하는 방법 “¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁÏ“, '…§, '°¡, .•4º»Ÿć'Rþн•, Ž9o, 및“‰´Øè„Æ€ººß“ 작업.

단계별 예 :

  • 입력: two hundred twenty two divided by two times minus fifty seven plus three hundred eighteen minus minus ten
  • 1 단계 : "by"제거 : two hundred twenty two divided two times minus fifty seven plus three hundred eighteen minus minus ten
  • 2 단계 : 올바른 숫자로 "0"에서 "12"까지 변환 : 2 hundred twenty 2 divided 2 times minus fifty 7 plus 3 hundred 8een minus minus 10
  • 3 단계 : "t"모두 제거 : 2 hundred weny 2 divided 2 imes minus fify 7 plus 3 hundred 8een minus minus 10
  • 4 단계 : "een"을 모두 "+10"으로 바꿉니다. 2 hundred weny 2 divided 2 imes minus fify 7 plus 3 hundred 8+10 minus minus 10
  • 5 단계 : "100"을 모두 "* 100"으로 바꿉니다. 2 *100 weny 2 divided 2 imes minus fify 7 plus 3 *100 8+10 minus minus 10
  • 6 단계 : 모든 [ "wen", "hir", "for", "fif"]를 올바른 숫자로 바꿉니다. 2 *100 2y 2 divided 2 imes minus 5y 7 plus 3 *100 8+10 minus minus 10
  • 7 단계 : "y"를 모두 "* 10"으로 바꿉니다. 2 *100 2 *10 2 divided 2 imes minus 5 *10 7 plus 3 *100 8+10 minus minus 10
  • 8 단계 : [ "plus", "minus", "ime", "imes", "divided"]로 나누기 : ["2 *100 2 *10 2 "," 2 "," "," 5 *10 7 "," 3 *100 8+10 "," "," 10"]
  • 9 단계 : 공백으로 각각 분할 : [["2","","*100","2","*10","2",""],["","","2",""],["",""],["","5","*10","7",""],["","3","","*100","8+10",""],["",""],["","10"]]
  • 10 단계 : 빈 항목 제거 [["2","*100","2","*10","2"],["2"],[],["5","*10","7"],["3","*100","8+10"],[],["10"]]
  • 11 단계 : 크기 2의 부분으로 분할하고 결합합니다. [["2*100","2*10","2"],["2"],"",["5*10","7"],["3*100","8+10"],"",["10"]]
  • 12 단계 : Python eval각각 :[[200,20,2],[2],"",[50,7],[300,18],"",[10]]
  • 13 단계 : 각각 요약 : [222,2,"",57,318,"",10]
  • 14 단계 : 레지스터에서 문자열을 다시 푸시하고 문자를 제외한 모든 것을 제거하십시오. dividedimesminusplusminusminus
  • 15 단계 : "plus", "빼기", "imes", "ime", "divided"를 연산자 문자로 바꾸고 공백을 추가하십시오. [" /"," *"," -"," +"," -"," -"]
  • 16 단계 : 서로 짜 여서 결합 : 222 /2 * -57 +318 - -10
  • 출력 :eval 문자열을 파이썬으로 내재적으로 출력합니다.-5999.0

처음부터 솔루션을 만들려고 시도하지 않았거나 상세하게 연구했지만 골프하나 있습니다.
Emigna

@Emigna 감사합니다!
케빈 크루이 ssen

2

sfk , 572 449 423 바이트

이것은 모두 한 줄이 될 수 있지만 읽을 목적으로 공백 대신 줄 바꿈을 사용했습니다.

xed -i
_plus_+_
_minus_-_
_times[ortext]time_*_
_divided?by_/_
+xed
"_[white][2 chars of a-z][chars of a-z]ty_[parts 1,2]0_"
"_[white][2 chars of a-z][chars of a-z]een_[part1]1[part2]_"
_ten_10_
_lev_11_
_twe_12_
+xed
_ze_0_
_on_1_
_tw_2_
_th_3_
_fo_4_
_fi_5_
_si_6_
_se_7_
_ei_8_
_ni_9_
+xed
_0[white][keep][digit]__
"_[chars of e-z ]__"
+xed
"_?dd[keep][2 digits]_[part1]_"
_?dd[keep][digit]_[part1]0_
_dd_00_
+calc #text

온라인으로 사용해보십시오!

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.