Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #87489

Re: More or less code in python?

From Peter Otten <__peter__@web.de>
Subject Re: More or less code in python?
Date 2015-03-15 20:15 +0100
Organization None
References <8412cc81-fbd2-4590-9db3-12c65ba2ee35@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.400.1426446930.21433.python-list@python.org> (permalink)

Show all headers | View raw


jonas.thornvall@gmail.com wrote:

> <SCRIPT LANGUAGE="Javascript">
> 
> function naiveAdd(base,arrOne,arrTwo) {
> if (arrOne.length>=arrTwo.length) {length=arrOne.length;} else
> {length=arrTwo.length;} out="";
> remainder=0;
> for (i=0;i<length;i++){
> one=arrOne[i];
> two=arrTwo[i];
> one=parseInt(one);
> two=parseInt(two);
> if (isNaN(one)) one = 0;
> if (isNaN(two)) two = 0;
> sum=one+two+remainder;
> 
> if (sum>=base) { sum=sum-base; remainder=1;} else {remainder=0;}
> out=","+sum+out;
> }
> if (remainder==1) out=remainder+out;
> return out;
> }

As to length I expect both languages to end in the same ball park. Here's a 
possible Python implementation:

from itertools import zip_longest

def prepare(s):
    return map(int, reversed(s.split(",")))

def naive_add(base, left, right):
    result = []
    carry = 0
    for a, b in zip_longest(prepare(left), prepare(right), fillvalue=0):
        carry, rest = divmod(a + b + carry, base)
        result.append(rest)
    if carry:
        result.append(carry)
    return ",".join(map(str, reversed(result)))

if __name__ == "__main__":
    print(naive_add(16, "1,2", "13,14"))

The Python code for sure has better indentation ;)

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

More or less code in python? jonas.thornvall@gmail.com - 2015-03-15 11:07 -0700
  Re: More or less code in python? Joel Goldstick <joel.goldstick@gmail.com> - 2015-03-15 14:31 -0400
    Re: More or less code in python? jonas.thornvall@gmail.com - 2015-03-15 11:56 -0700
    Re: More or less code in python? jonas.thornvall@gmail.com - 2015-03-15 12:00 -0700
      Re: More or less code in python? Paul Rubin <no.email@nospam.invalid> - 2015-03-15 12:01 -0700
        Re: More or less code in python? jonas.thornvall@gmail.com - 2015-03-15 12:03 -0700
        Re: More or less code in python? jonas.thornvall@gmail.com - 2015-03-15 12:09 -0700
          Re: More or less code in python? Dave Angel <davea@davea.name> - 2015-03-16 03:32 -0400
          Re: More or less code in python? Chris Angelico <rosuav@gmail.com> - 2015-03-16 18:36 +1100
          Re: More or less code in python? Dave Angel <davea@davea.name> - 2015-03-16 03:44 -0400
  Re: More or less code in python? Peter Otten <__peter__@web.de> - 2015-03-15 20:15 +0100

csiph-web