How can I write the following script in Python? -
so programme wanna write adding 2 strings s1 , s2 made of int. example: s1='129782004977', s2='754022234930', sum='883804239907' far i've done still has problem because not rive me whole sum.
def adds1s2(s1,s2): n=abs(len(s2)-len(s1)) if len(s1)<len(s2): s1=n*'0'+s1 if len(s2)<len(s1): s2=n*'0'+s2 #the first part create 2 strings same len. s='' r=0 in range(len(s1)-1,-1,-1): s=int(s1[i])+int(s2[i])+r if s>9: r=1 s=str(10-s)+s if s<9: r=0 s=str(s)+s print(s) if r==1: s=str(r)+s homecoming s
this appears homework, not give total code few pointers.
there 3 problems algorithm. if prepare those, should work.
10-s
give negative numbers, -
signs in sum. alter s-10
you missing 9
s. alter if s<9:
if s<=9:
, or better, else:
you should not add together r
string in every iteration, @ end, after loop. also, instead of using convoluted if
statements check r
, substract 10 s
can utilize partition , modulo instead: r = s/10
, s = s%10
, or r, s = divmod(s, 10)
.
if not homework: utilize int(s1) + int(s2)
.
python-3.x
No comments:
Post a Comment