Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-4041-

shit challenge: numerics to words

Name: Anonymous 2010-07-25 3:01

Weekly Challenge: Programmatically convert any1 string of digits, such as "1234567" to word form, "one million, two hundred thirty-four thousand, five hundred sixty-seven"

Here is mine: http://codepad.org/gyqbaKxx

Criticize my code.  I know it sucks anus.  I would like to make it better.  Submit your own versions as well.

Use whatever language you like[i]!/i]

_____________________________________
1. Up to 18 significant digits is fine.

Name: Anonymous 2010-07-25 3:40


import org.4chan.dis.Prog;

class MySolution {
    public static void main(String[] args) {
        Prog.newInstance().getSolution();
    }
}

Name: Anonymous 2010-07-25 3:59

I thought I had done this about a year ago, lo and behold.
http://dis.4chan.org/read/prog/1242279244/11

Name: Anonymous 2010-07-25 4:21

In Common Lisp:

CL-USER> (format t "~r" 1234567)
one million two hundred thirty-four thousand five hundred sixty-seven

Name: Anonymous 2010-07-25 5:59

we already did this, over two years ago:
http://hotaru.thinkindifferent.net/code/number.c

Name: Anonymous 2010-07-25 6:28

>>5
if(!num){
   puts("zero.");
   return 0;
  }
f(num < 0){
   num *= -1;
   printf("negative ");
  }

Stopped reading right there.

Name: Anonymous 2010-07-25 8:55

Use a real language (i.e. British English) where there are some ands in your huge fucking number string.

Name: Anonymous 2010-07-26 13:56

>>7
I don't have a British English compiler!

Name: Anonymous 2010-07-26 14:16

>>7
"and" goes between the integral and fractional parts of a number. There should never be an "and" anywhere else in a number string.

Name: Anonymous 2010-07-26 14:28

>integral
U MEAN INTEGER

Name: Anonymous 2010-07-26 14:34

>>10
Nah. >>9 is alright. Even Feynman would use "integral" in that sense.

Name: Anonymous 2010-07-26 14:35

>>10
http://en.wikipedia.org/wiki/Decimal#Decimal_fractions
The integer [sic] part or integral part of a decimal number is the part to the left of the decimal separator (see also floor function).

Name: Anonymous 2010-07-26 14:38

>>10
You're an idiot.

Name: Anonymous 2010-07-26 15:04

>>13
*your and idort

Name: Anonymous 2010-07-26 15:06

Now adapt you're code to deal with any spoken language.

$ say -lang en_US 14319
Fourteen thousand three hundred nineteen
$ say -lang en_GB 14319
Fourteen thousand and three hundred and nineteen
$ say -lang es_ES 14319
Catorce mil trescientos diecinueve
$ say -lang ja_JP 14319
一万四千三百十九

Name: Anonymous 2010-07-26 15:08

Forgot my monospace.


$ say -lang en_US 14319
Fourteen thousand three hundred nineteen
$ say -lang en_GB 14319
Fourteen thousand and three hundred and nineteen
$ say -lang es_ES 14319
Catorce mil trescientos diecinueve
$ say -lang ja_JP 14319
一万四千三百十九

Name: !XarnWayDP. 2010-07-26 16:12

Your challenge is boring, so I did it the other way around.

#!/usr/bin/python

import sys, re

def parse_number(s):
    def parse_ones(s):
        ones = { "":      0
               , "zero":  0
               , "a":     1
               , "one":   1
               , "two":   2
               , "three": 3
               , "four":  4
               , "five":  5
               , "six":   6
               , "seven": 7
               , "eight": 8
               , "nine":  9
               }

        return ones[s]

    def parse_tens(s):
        teens = { "ten":       10
                , "eleven":    11
                , "twelve":    12
                , "thirteen":  13
                , "fourteen":  14
                , "fifteen":   15
                , "sixteen":   16
                , "seventeen": 17
                , "eighteen":  18
                , "nineteen":  19
                }

        if s in teens:
            return teens[s]
   
        n = 0

        tens = { "twenty":  20
               , "thirty":  30
               , "forty":   40
               , "fifty":   50
               , "sixty":   60
               , "seventy": 70
               , "eighty":  80
               , "ninety":  90
               }

        for l in set(map(len, tens)):
            if s[:l] in tens:
                n += tens[s[:l]]
                s = s[l:]

        n += parse_ones(s)

        return n


    def parse_hundreds(s):
        if not "hundred" in s:
            return parse_tens(s)

        n = 0
   
        hundreds, tens = s.split("hundred")

        n += 100 * parse_ones(hundreds) or 100
        n += 0 if tens == '' else parse_tens(tens)

        return n

    def parse_thousands(s):
        if not "thous" in s:
            return parse_hundreds(s)

        n = 0

        thousands, hundreds = s.split("thous")

        n += 1000 * parse_hundreds(thousands) or 1000
        n += 0 if hundreds == '' else parse_hundreds(hundreds)

        return n

    def parse_millions(s):
        if not "million" in s:
            return parse_thousands(s)

        n = 0
   
        millions, thousands = s.split("million")
   
        n += 1000000 * parse_hundreds(millions) or 1000000
        n += 0 if thousands == '' else parse_thousands(thousands)

        return n

    def parse_billions(s):
        if not "billion" in s:
            return parse_millions(s)

        n = 0

        billions, millions = s.split("billion")
   
        n += 1000000000 * parse_hundreds(billions) or 1000000000
        n += 0 if millions == '' else parse_millions(millions)
   
        return n

    s = re.sub("[^a-z]", "", s.lower())
    s = re.sub("and", "", s)

    m = 1

    if s[:5] == "minus":
        s = s[5:]
        m = -1
    elif s[:8] == "negative":
        s = s[8:]
        m = -1

    try:
        return parse_billions(s) * m
    except:
        return None


if __name__ == '__main__':
    if len(sys.argv) > 1:
        num = " ".join(sys.argv[1:])
        n = parse_number(num)

        print n if n is not None \
                else "\033[1mNot a number: %s\033[0m" % num

    elif not sys.stdin.isatty():
        for num in sys.stdin.readlines():
            n = parse_number(num)
            print n if n is not None \
                    else "\033[1mNot a number: %s\033[0m" % num[:-1]

    else:
        print "NUMBERS, GODDAMMIT"

Name: Anonymous 2010-07-26 16:24

>>9
You're the kind of person who thinks MM/DD/YYYY is a good idea, right?

Name: Anonymous 2010-07-26 16:46

[b]x@www:/prog/num$[/b] python n.py
NUMBERS, GODDAMMIT
[b]x@www:/prog/num$[/b] python n.py 420
0
[b]x@www:/prog/num$[/b] python n.py -420
0
[b]x@www:/prog/num$[/b] python n.py -a 420
1
[b]x@www:/prog/num$[/b] python n.py -b 420
Not a number: -b 420
[b]x@www:/prog/num$[/b] python n.py -c 420
Not a number: -c 420

Name: Anonymous 2010-07-26 16:58

>>19
Maybe you should learn to read.

$ ./parse.py four hundred twenty
420

Name: Anonymous 2010-07-26 17:18

[0]user: python fucking-numbers one thousand million
Not a number: one thousand million
[0]user: python fucking-numbers one milliard
Not a number: one milliard

So... which is it?

Name: Anonymous 2010-07-26 17:19

NUMBERS, GODDAMMIT

Name: Anonymous 2010-07-26 17:30


#!/usr/bin/python
number = raw_input("What number: ")
if (number == 1):
    Print "One."
else:
    Print "Can you please put a different number?"

Name: Anonymous 2010-07-26 17:40

>>18
You're the type of person who thinks the equally nonsensical DD/MM/YYYY is any better than MM/DD/YYYY, right?
Sensible date format (YYYY/MM/DD) user here.

Name: Anonymous 2010-07-26 17:43

>>24
it is better

Name: Anonymous 2010-07-26 17:44

>>24
I'm sorry, but DD/MM/YYYY is surely better than MM/DD/YYYY -- the endianess is sane, at least.

Name: Anonymous 2010-07-26 17:55

>>24
Well, it translates directly to speech rather well. So, yes.

Name: Anonymous 2010-07-26 18:01

>>26
DD/MM/YYYY HH:MM:SS is not sane endianness.

Name: Anonymous 2010-07-26 18:03

>>28
Agreed, but we were talking date formats, not datetime formats

Name: Anonymous 2010-07-26 18:18

>>28
Stop changing the argument as you please. You know full-well that DD/MM/YYYY does what it means in an intuitive manner, and that MM/DD/YYYY is just nonsensical. You're only trying to boost your own ego by saying ``Aha! This similar, but irrelevant situation is insane! Thus I win.''

Name: Anonymous 2010-07-26 18:28

>>29-30
Using a different order for dates and datetimes does not make sense. I'll admit that only reversing endianness once is slightly better than reversing endianness twice, but both are a lot less sensible than just using the same endianness all the way through.

Name: Anonymous 2010-07-26 18:32

>>31
You're not thinking outside your Pentium II box. In the real world, nobody says “In the year 2010, the month of July, the twenty-sixth day”.
It's “The twenty-sixth of July, 2010” (or “July [the] twenty-sixth, 2010” but we've already ruled this out as ludicrous).

Name: Anonymous 2010-07-26 19:20

>>32
In normal speech, people don't usually say the year, and they don't say "The twenty-sixth of July". They just say "July twenty-sixth". That's a lot closer to 2010/07/26 than it is to 26/07/2010.

Name: Anonymous 2010-07-26 19:39

>>30

My brother's argument for MM/DD/YYYY is that putting the month first gives you a better feel for the time of year it is.

He is an engineer.

Name: Anonymous 2010-07-26 19:40

>>33
But we're clearly including the year here, you can't exclude it for one case just because it suits your point. Also, stop pretending countries other than your glorious homeland don't speak normally.

Name: Anonymous 2010-07-26 19:51

Saying "twenty-sixth of July" (which I often do) or "July twenty-sixth" isn't really as useful as it sounds since months don't have the same calendar organization.  We should start a new shorthand date system that includes and starts with the day of the week.
"Monday, July 26th 2010" becomes 1/07/26/2010, for example.

Name: Anonymous 2010-07-26 19:55

>>36
Including the day of the week doesn't add any information that isn't already there. It actually takes longer to read that extra number and figure out what order the numbers are in than it does to just calculate the day of the week.

Name: Anonymous 2010-07-26 20:15

You wouldn't say my/hax/anus.

Name: Anonymous 2010-07-26 20:33

perl -MLingua::EN::Numbers -e 'print Lingua::EN::Numbers->num2en(shift(@ARGV)) . "\n"'

Have a nice day.

Name: Anonymous 2010-07-26 20:53

>>39
Can't locate Lingua/EN/Numbers.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.8.8 /usr/local/share/perl/5.8.8 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.8 /usr/share/perl/5.8 /usr/local/lib/site_perl .).
BEGIN failed--compilation aborted.
Your solution is as effective as >>2's.

Name: Anonymous 2010-07-26 22:33

>>40
Nah, Lingua::EN::Numbers actually exists and does the needful. I'd direct you to Acme::CPAN::InstallAndUse but that a) would provoke the same complaint and b) might not actually exist.

Name: >>17 2010-07-27 0:21

>>21
You know, I considered adding a British mode, but completely forgot about it before posting.

Name: Anonymous 2010-07-27 0:25

>>42
Why would you do that? British people aren't smart enough to use computers. Anyone who claims to be British on the internet is just trolling.

Name: Anonymous 2010-07-27 0:46

>>43
Anyone who claims to be British on the internet is just trolling.
trolling
0/10

Name: Anonymous 2010-07-27 1:31

middle endian is superior

Name: Anonymous 2010-07-27 2:41

Middle Earth is superior

Name: Anonymous 2010-07-27 4:23

middle finger is superior

Name: Anonymous 2010-07-27 7:11

>>42
Don't worry, it even converts strings like ``one hundred and two'', I was impressed

Name: Anonymous 2010-07-27 13:16

>>48
On the other hand, it also accepts ``zero thous a''. It's a beautiful mess.

Name: Anonymous 2010-07-27 13:41

>>49
And any otherwise-valid number string with absolutely no spaces in it.

Name: toekutr 2010-07-27 17:34

(require simply.scm)

(define (number-name num)
(name-triples (sub-in-names (make-triples num) namelist)))

(define (name-triples triples)
    (cond
      ((empty? triples) '())
      ((number? (first triples)) (se (name-triple (first triples)) (name-triples (bf triples))))
      (else (se (first triples) (name-triples (bf triples))))))

(define (make-triples num)
    (cond
      ((empty? num) '())
      ((= (length num) 2) num)
      ((= (length num) 1) num)
      (else
       (se (make-triples (bl (bl (bl num)))) (last-three num)))))

(define (length num)
    (if (empty? num)
        0
        (+ 1 (length (bf num)))))

(define (last-three wd)
    (word (last (bl (bl wd))) (last (bl wd)) (last wd)))

(define (sub-in-names triples names)
    (cond
      ((<= (length triples) 1) (se triples (first names)))
      ((> (length triples) 12) '(Overflow, try entering a smaller number))
      (else (if (all-zeros? (last triples))
            (se (sub-in-names (bl triples) (bf names)) (last triples))
            (se (sub-in-names (bl triples) (bf names)) (first names) (last triples))))))

(define (name-triple triple)
    (let ((fst (first triple)) (rest (bf triple)))
    (cond
      ((= (length triple) 3)
       (if (= fst 0)
           (se (name-triple rest))
           (se (name-single (first triple)) 'hundred (name-triple (bf triple)))))
      ((= (length triple) 2)
       (if (= fst 0)
           (se (name-single rest))
           (cond
             ((= fst 1) (cond
                          ((= triple 10) 'ten)
                          ((= triple 11) 'eleven)
                          ((= triple 12) 'twelve)
                          ((= triple 13) 'thirteen)
                          ((= triple 14) 'fourteen)
                          ((= triple 15) 'fifteen)
                          ((= triple 16) 'sixteen)
                          ((= triple 17) 'seventeen)
                          ((= triple 18) 'eighteen)
                          (else 'nineteen)))
             ((= fst 2) (se 'twenty (name-triple rest)))
             ((= fst 3) (se 'thirty (name-triple rest)))
             ((= fst 4) (se 'forty (name-triple rest)))
             ((= fst 5) (se 'fifty (name-triple rest)))
             ((= fst 6) (se 'sixty (name-triple rest)))
             ((= fst 7) (se 'seventy (name-triple rest)))
             ((= fst 8) (se 'eighty (name-triple rest)))
             ((= fst 9) (se 'ninety (name-triple rest)))
             (else (se (name-triple rest))))))
      (else
       (name-single triple)))))

(define (name-single num)
    (if empty? num) '(Whoops)
    (cond
      ((= num 0) '())
      ((= num 1) 'one)
      ((= num 2) 'two)
      ((= num 3) 'three)
      ((= num 4) 'four)
      ((= num 5) 'five)
      ((= num 6) 'six)
      ((= num 7) 'seven)
      ((= num 8) 'eight)
      (else 'eight)))

(define (name-triples triples)
    (cond
      ((empty? triples) '())
      ((number? (first triples)) (se (name-triple (first triples)) (name-triples (bf triples))))
      (else (se (first triples) (name-triples (bf triples))))))

(define namelist '(thousand million billion trillion quadrillion quintillion
  sextillion septillion octillion nonillion decillion))



This was made back a year or so ago, and I still suck at Scheme, but here ya go anyway.

 It goes up to about 10^33, and I'm using a few functions that aren't built into scheme (this was a textbook assignment, here's the list if you want to try this; http://www.cs.berkeley.edu/~bh/ssch27/appendix-simply.html). 



There's also a bug that I never bothered fixing


>(number-name 12000123)
'(twelve million thousand one hundred twenty three)

>(number-name 12010123)
'(twelve million ten thousand one hundred twenty three)

>(number-name 1231231352344135)
'(one quadrillion two hundred thirty one trillion two hundred thirty one billion three hundred fifty two
million three hundred forty four thousand one hundred thirty five)

As you can see, it has problems when all three digits of a
"triple" are zeros.

Name: toekutr 2010-07-27 17:36

ffffuuuck forgot code tags sorry.

http://paste.lisp.org/display/112882

Name: Anonymous 2010-07-27 17:45

>>52
Are you high?

Name: Anonymous 2010-07-27 18:14

>>53

not really no

Name: Anonymous 2010-07-27 18:15

>>54
By process of elimination, I have deduced that you are merely a fool.

Name: toekutr 2010-07-27 18:20

>>55

I clicked on the wrong tab when I pasted the code in the first time, and when I recopied it to paste into the correct tab, I forgot about the code tags. Nothing foolish, just a simple mistake.  Unless you're talking about the code, then sure, I know it sucks.

Name: Anonymous 2010-07-27 18:22

>>56
Oh, very well, it's just the 'fffuuuck' in the second mistake aroused my suspicions somewhat.

Name: Anonymous 2010-07-27 18:24

>>57

What? I can't type verbal obscenities into a text box now?

Name: Anonymous 2010-07-27 18:31

>>58
It was slow and clumsy, as if it were the end of the world for your marijuana-affected mind.

Name: Anonymous 2010-07-27 23:18

I decided to give this a go. I steered clear of looking at any of the other posts and came up with what follows. This could very easily be rewritten in C.


def num_to_name( num_str ):
    global exact, tens, powers
    # Convert to int and back, which fixes whitespace and leading zeroes.
    try:
        num_str = str(int(num_str))
    except ValueError:
        return "That was not a number!"
   
    if num_str == "0":
        return "zero"
   
    strlen = len(num_str)
   
    if strlen > 18 + 1 :
        return "That number is too large for my puny brain!"
   
    ans = [] # List to hold number words.
   
    i = -1
    while i < (strlen - 1):
        i += 1
       
        if num_str[i] != "0":
            m = (strlen - i - 1) % 3
       
            if m == 2:
                # Hundreds
                ans.append( exact[ num_str[i] ] )
                ans.append( "hundred " )
                continue
           
            elif m == 1:
                # Tens
                if num_str[i] == "1":
                    ans.append( exact[ num_str[i:i+2] ] )
                    i += 1
                else:
                    ans.append ( tens[ num_str[i] ] )
                    continue
            else:
                # Ones
                ans.append( exact[ num_str[i] ] )
       
        # Powers
        o = strlen - i - 1
               
        if o and not (o % 3) :
            ans.append( powers[o] )
                   
   
    return "".join(ans).rstrip(" ,")

Name: Anonymous 2010-07-27 23:20

>>60

Whoops, forgot my globals.



exact = { "1" : "one ", "2" : "two ", "3" : "three ", "4" : "four ", "5" : "five ", "6" : "six ", "7" : "seven ", "8" : "eight ", "9" : "nine ", "10" : "ten ", "11" : "eleven ", "12" : "twelve ", "13" : "thirteen ", "14" : "fourteen ", "15" : "fifteen ", "16" : "sixteen ", "17" : "seventeen ", "18" : "eighteen ", "19" : "nineteen " }

tens = { "2" : "twenty-", "3" : "thirty-", "4" : "fourty-", "5" : "fifty-", "6" : "sixty-", "7" : "seventy-", "8" : "eighty-", "9" : "ninety-" }

powers = { 3 : "thousand, ", 6 : "million, ",  9 : "billion, ", 12 : "trillion, ", 15 : "quadrillion, ", 18 : "quintillion, " }

Name: Anonymous 2010-07-27 23:41


package org.4chan.dis.read.prog._1280041293._62;

public class Numerics2Words
{ public static final String[] words = {"", "one", "two", "three", "four", "five",
                                        "six", "seven", "eight", "nine"};
 
  public static void main(String... args)
  { if (args.length < 1)
    { throw new IllegalArgumentException("Usage: java Numerics2Words ");
 
    final String numeric = args[0];
    final StringBuilder result = new StringBuilder();
    for (int i = 0; i < numeric.length; i++)
    { final char c = numeric.charAt(i);
      result.append(words[Integer.parseInt(c).intValue()]);   
    }
   
    System.out.println(result.toString());
  }
}

Name: Anonymous 2010-07-28 0:01

>>60

I came back and i noticed a few mistakes. I fixed them. Sorry about that.

exact = { "1" : "one ", "2" : "two ", "3" : "three ", "4" : "four ", "5" : "five ", "6" : "six ", "7" : "seven ", "8" : "eight ", "9" : "nine ", "10" : "ten ", "11" : "eleven ", "12" : "twelve ", "13" : "thirteen ", "14" : "fourteen ", "15" : "fifteen ", "16" : "sixteen ", "17" : "seventeen ", "18" : "eighteen ", "19" : "nineteen " }

tens = { "2" : "twenty-", "3" : "thirty-", "4" : "fourty-", "5" : "fifty-", "6" : "sixty-", "7" : "seventy-", "8" : "eighty-", "9" : "ninety-" }

powers = { 3 : "thousand, ", 6 : "million, ",  9 : "billion, ", 12 : "trillion, ", 15 : "quadrillion, ", 18 : "quintillion, " }

def num_to_name( num_str ):
    global exact, tens, powers
    # Convert to int and back, which fixes whitespace and leading zeroes.
    try:
        num_str = str(int(num_str))
    except ValueError:
        return "That was not a number!"
   
    if num_str == "0":
        return "zero"
   
    strlen = len(num_str)
   
    if strlen > 18 + 1 :
        return "That number is too large for my puny brain!"
   
    ans = [] # List to hold number words.
   
    i = -1
    while i < (strlen - 1):
        i += 1
       
        if num_str[i] != "0":
            m = (strlen - i - 1) % 3
       
            if m == 2:
                # Hundreds
                ans.append( exact[ num_str[i] ] )
                ans.append( "hundred " )
                continue
           
            elif m == 1:
                # Tens
                if num_str[i] == "1":
                    ans.append( exact[ num_str[i:i+2] ] )
                    i += 1
                else:
                    ans.append ( tens[ num_str[i] ] )
                   
                    if num_str[i + 1] == "0":
                        # Correct dashes for 20, 30, etc.
                        ans[-1] = ans[-1][:-1] + " "
                   
                    continue
            else:
                # Ones
                ans.append( exact[ num_str[i] ] )
       
        # Powers
        o = strlen - i - 1
       
        if o and not (o % 3) :
            ans.append( powers[o] )
       
        while i < (strlen - 1) and num_str[i + 1] == "0":
            # Correct for trailing zeroes.
            i += 1
   
    return "".join(ans).rstrip(" ,")

Name: Anonymous 2010-07-28 0:08

Name: Anonymous 2010-07-28 1:19

>>62,64
The indentation annoys me more than the choice of language. If K&R is too hard for you, at least stick to Sun's style guidelines.

Name: Anonymous 2010-07-28 1:43

hi,
how can convert the rupees into word.
Rupees could be more than million as well asd it may contain paise.

for example : 58234453434.50

with regards,
gopi

Name: Anonymous 2010-07-28 1:51

echo 12^2|bc
what?

Name: Anonymous 2010-07-28 2:21

When are the results announced?

Name: Anonymous 2010-07-28 3:15

>>68
What do you care? Xarn wins anyway.

Name: Anonymous 2010-07-28 3:17

>>69
Which one is Sarns?

Name: Anonymous 2010-07-28 5:21

>>66
I lol'd.

Name: Anonymous 2010-07-28 13:49

>>69
Xarn hasn't won most challenges in /prog/'s history. Still, if you're worried, these challenges could probably have one category for Xarn, and one for best of the rest.

>>70
>>17, I'm pretty sure.

Name: Anonymous 2010-07-28 13:58

>>72
Actually Xarn wouldn't post any code written the ``Xarn Way'' as he is not an egotist; the tripcode in >>17 is clearly someone else's attempt at satire. Xarn would just use his usual name and tripcode.

Name: Anonymous 2010-11-25 9:10

Name: Anonymous 2011-02-03 5:34

<

Name: Anonymous 2011-02-04 15:35

Name: Anonymous 2011-02-18 14:19

<-- check 'em dubz
Don't change these.
Name: Email:
Entire Thread Thread List