I've started to follow Stanford's CS161 on Coursera, "an online course on Algorithms and Data Structures."
I've looked up to find grade-school algorithms around integer arithmetic.
I have the addition algorithm in pseudo-code and was interest in implementing it in Python 2.7 (accordingly with MIT standards).
I've analyzed my implementation and think it's almost correct but the Python interpreter provided some feedback possibly on uninitialized lists and variables.
Note that I'm not fully proficient in Python and there may be some obvious syntactic mistakes due to a lack of knowledge in basic data structures and code structuring.
I have a few questions on the code below:
def add(a,b):
i = 0
carry = 0
x[i] = [None]*N
y[i] = [None]*N
while x[i] > 0 and y[i] > 0:
x[i], y[i] = a%10, b%10
a , b = a/pow(10,i+1), b/pow(10,i+1)
N += i
for i in range(N):
x[i] = x[N-i]
y[i] = y[N-i]
r[i] = (x[i] + y[i] + carry)%10
carry = (x[i] + y[i] + carry)/10
r[N] = carry
return r
Description of the algorithm:
The add()
function takes two N-digit integers a and b as input and returns an integer with N or N+1 digits corresponding to the sum of a
and b
.
It first breaks up a
and b
into lists of size N holding and storing the N digits of a
(respectively b
) by extracting each digit from the least powered digit to the digit with the largest power of 10.
It then replaces all x[i]
with x[N-i]
(resp. y[i]
with y[N-i]
) and then computes x[i]+y[i]
by taking care of the addition's carry at each iteration.
The carry dynamically increments by value. when the for loop ends, we assign the latest digit r[N] of the sum as the value of the carry (>=0).
Questions:
- Is it a good thing to initialize the lists
x[i]
andy[i]
by assigning its elements' value as[None]
N times ? - With
x[i]
andy[i]
initialized as such, should thewhile
loop works again as my conditions are onx[i]
andy[i]
? - How to return an entire list namely the list
r[N]
? Should we type returnr[N]
or just returnr
?
Other useful contributions and comments are welcome.