More or less code in python?

Peter Otten __peter__ at web.de
Sun Mar 15 15:15:22 EDT 2015


jonas.thornvall at 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 ;)





More information about the Python-list mailing list