convert tradingview script into python3 - python

I am looking for a converting from TV to python. Just a little code. This is the code in tradingview :
last_signal = 0
long_final = longCond and (nz(last_signal[1]) == 0 or nz(last_signal[1]) == -1)
short_final = shortCond and (nz(last_signal[1]) == 0 or nz(last_signal[1]) == 1)
last_signal := long_final ? 1 : short_final ? -1 : last_signal[1]
for variable :
-> longCond and shortCond, i have the right value (I compared between plot)
But for others, i have some differences (i think, because of last_signal)
this is my code in python :
for x in range(0,len(mavi),1):
last_signal[i] = 0
if x == 0:
longCond_tmp = 0
shortCond_tmp = 0
last_signal_tmp = 0
short_final_tmp = 0
long_final_tmp = 0
else:
if ((longCond_tmp and ((last_signal[i-1])) == 0) or ((last_signal[i-1]) == -1)):
long_final_tmp = 1
else:
long_final_tmp = 0
if ((shortCond_tmp and ((last_signal[i-1])) == 0) or ((last_signal[i-1]) == 1)):
short_final_tmp = 1
else:
short_final_tmp = 0
if long_final_tmp != 0:
last_signal_tmp = 1
else:
if short_final_tmp != 0:
last_signal_tmp = -1
else:
last_signal_tmp = last_signal[i-1]
last_signal[i] += last_signal_tmp
Are there errors in my script in python ?

Ok i found.
Just the number of "(" in
if ((longCond_tmp and ((last_signal[i-1])) == 0) or ((last_signal[i-1]) == -1)):
long_final_tmp = 1
else:
long_final_tmp = 0
if ((shortCond_tmp and ((last_signal[i-1])) == 0) or ((last_signal[i-1]) == 1)):
short_final_tmp = 1
else:
short_final_tmp = 0

Related

I receive this attribute error "AttributeError: 'float' object has no attribute 'type_of_payment'" I am fairly new to python so I apologize if dumb

These are the definitions
Payment = Enum('Payment', ['food', 'consulting', 'honoraria', 'travel', 'services', 'gift', 'education','entertainment', 'grant', 'space_rental', 'royalties', 'investment', 'charity'])
# interp. types/natures of payments or transactions
#examples are redundant for enumerations
GeneralPaymentTypeDistribution = NamedTuple ('GeneralPaymentTypeDistribution', [('total_amount', float), # in range[0, ...)
('type_of_payment', Payment),
('degree', str)])
# interp. general information about a payment with the total amount, type of payment, and type of medical doctor
this is the code. It takes the compound list and adds the amount to the corresponding sum and adds a value to counter to know how many additions have been done. These to values are then sent to another average function where they are divided. However I keep on receiving an error about float for type_of_payment when that var is an enumeration. I understand that the code may be inefficient but it should still work??
def average_list(avg: List[GeneralPaymentTypeDistribution]) -> List[float]:
"""
returns a list containing averages of each of the transaction types
"""
#return [] #stub
# template from List[GeneralPaymentTypeDistribution]
# acc contains the result so far
acc = [] # type: List[only_do]
sum_1 = 0
sum_2 = 0
sum_3 = 0
sum_4 = 0
sum_5 = 0
sum_6 = 0
sum_7 = 0
sum_8 = 0
sum_9 = 0
sum_10 = 0
sum_11 = 0
sum_12 = 0
counter_1 = 0
counter_2 = 0
counter_3 = 0
counter_4 = 0
counter_5 = 0
counter_6 = 0
counter_7 = 0
counter_8 = 0
counter_9 = 0
counter_10 = 0
counter_11 =0
counter_12 = 0
for a in avg:
if a.type_of_payment == Payment.food:
sum_1 = sum_1 + a.total_amount
counter_1 = counter_2 + 1
elif a.type_of_payment == Payment.consulting:
sum_2 = sum_2 + a.total_amount
counter_2 = counter_2 + 1
elif a.type_of_payment == Payment.honoraria:
sum_3 = sum_3 + a.total_amount
counter_3 = counter_3 + 1
elif a.type_of_payment == Payment.travel:
sum_4 = sum_4 + a.total_amount
counter_4 = counter_4 + 1
elif a.type_of_payment == Payment.services:
sum_5 = sum_5 + a.total_amount
counter_5 = counter_5 + 1
elif a.type_of_payment == Payment.gift:
sum_6 = sum_6 + a.total_amount
counter_6 = counter_6 + 1
elif a.type_of_payment == Payment.education :
sum_7 = sum_7 + a.total_amount
counter_7 = counter_7 + 1
elif a.type_of_payment == Payment.entertainment :
sum_7 = sum_7 + a.total_amount
counter_7 = counter_7 + 1
elif a.type_of_payment == Payment.grant :
sum_8 = sum_8 + a.total_amount
counter_8 = counter_8 + 1
elif a.type_of_payment == Payment.space_rental:
sum_9 = sum_9 + a.total_amount
counter_9 = counter_9 + 1
elif a.type_of_payment == Payment.royalties :
sum_10 = sum_10 + a.total_amount
counter_10 = counter_10 + 1
elif a.type_of_payment == Payment.investment :
sum_11 = sum_11 + a.total_amount
counter_11 = counter_11 + 1
elif a.type_of_payment == Payment.charity :
sum_12 = sum_12 + a.total_amount
counter_12 = counter_12 + 1
return acc.append([average_calculation(sum_1,counter_1),
average_calculation(sum_2,counter_2),
average_calculation(sum_3,counter_3),
average_calculation(sum_4,counter_4),
average_calculation(sum_5,counter_5),
average_calculation(sum_6,counter_6),
average_calculation(sum_7,counter_7),
average_calculation(sum_8,counter_8),
average_calculation(sum_9,counter_9),
average_calculation(sum_10,counter_10),
average_calculation(sum_11,counter_11),
average_calculation(sum_12,counter_12)])
#typecheck
def average_calculation(sum0: float, counter: int) -> float:
"""
return average by dividing the sum by the number of instances
"""
# return 0 #stub
# template from GeneralPaymentTypeDistribution
if counter == 0:
return 0
else:
return sum0/counter
Here is the error message
AttributeError: 'float' object has no attribute 'type_of_payment'
I suppose you do average_list(data) instead of average_list([data]) (your function expects a list of namedtuples but you pass single namedtuple instead).

Python Scipy fsolve function returns roots which are equal to starting points

I need to get all roots of a scalar equation. But fsolve can only return 1 root for each call. So I design a self-call function find_root_recursively of fsolve. This function will call itself until the new root is equal the previous root, which means fsovle has found all roots and no more new roots will be added. I use this logic to end self calling. But in some cases fsolve will return a root which is exactly the same as starting point. one_root = start always. Obviously this start is not a root. So the list_root is always adding new roots, it never ends.
min_value = df_group['strike'].min()
start_point = int(float(min_value) * 0.8)
def find_root_by_small_step(function, start_0, increment):
start = start_0
one_root = fsolve(function, start)
def get_transaction_data(self, expiry_date, df_group):
return df_group[df_group['expiration_date'] == expiry_date].loc[(df_group['type'] == 1) & (df_group['position'] == 1)], \
df_group[df_group['expiration_date'] == expiry_date].loc[(df_group['type'] == 1) & (df_group['position'] == 0)], \
df_group[df_group['expiration_date'] == expiry_date].loc[(df_group['type'] == 0) & (df_group['position'] == 1)], \
df_group[df_group['expiration_date'] == expiry_date].loc[(df_group['type'] == 0) & (df_group['position'] == 0)]
def calculate_one_payoff(self, stock_price, df_long_call, df_short_call, df_long_put, df_short_put):
# buy call
df_buy_call_executed = df_long_call[stock_price >= df_long_call['strike']]
if len(df_buy_call_executed) > 0:
buy_call_executed_sum = ((stock_price - df_buy_call_executed['breakeven_price']) * df_buy_call_executed['option_amount']).sum()
else:
buy_call_executed_sum = 0
df_buy_call_noExec = df_long_call[stock_price < df_long_call['strike']]
if len(df_buy_call_noExec) > 0:
buy_call_noExec_sum = (-1 * df_buy_call_noExec['option_price'] * df_buy_call_noExec['option_amount']).sum()
else:
buy_call_noExec_sum = 0
# sell call
df_sell_call_executed = df_short_call[stock_price >= df_short_call['strike']]
if len(df_sell_call_executed) > 0:
sell_call_executed_sum = ((df_sell_call_executed['breakeven_price'] - stock_price) * df_sell_call_executed['option_amount']).sum()
else:
sell_call_executed_sum = 0
df_sell_call_noExec = df_short_call[stock_price < df_short_call['strike']]
if len(df_sell_call_noExec) > 0:
sell_call_noExec_sum = (df_sell_call_noExec['option_price'] * df_sell_call_noExec['option_amount']).sum()
else:
sell_call_noExec_sum = 0
# buy put
df_buy_put_executed = df_long_put[stock_price < df_long_put['strike']]
if len(df_buy_put_executed) > 0:
buy_put_executed_sum = ((df_buy_put_executed['breakeven_price'] - stock_price) * df_buy_put_executed['option_amount']).sum()
else:
buy_put_executed_sum = 0
df_buy_put_noExec = df_long_put[stock_price >= df_long_put['strike']]
if len(df_buy_put_noExec) > 0:
buy_put_noExec_sum = (-1 * df_buy_put_noExec['option_price'] * df_buy_put_noExec['option_amount']).sum()
else:
buy_put_noExec_sum = 0
# sell put
df_sell_put_executed = df_short_put[stock_price < df_short_put['strike']]
if len(df_sell_put_executed) > 0:
sell_put_executed_sum = ((stock_price - df_sell_put_executed['breakeven_price']) * df_sell_put_executed['option_amount']).sum()
else:
sell_put_executed_sum = 0
df_sell_put_noExec = df_short_put[stock_price >= df_short_put['strike']]
if len(df_sell_put_noExec) > 0:
sell_put_noExec_sum = (df_sell_put_noExec['option_price'] * df_sell_put_noExec['option_amount']).sum()
else:
sell_put_noExec_sum = 0
one_stock_price_sum = buy_call_executed_sum + buy_call_noExec_sum + sell_call_executed_sum + sell_call_noExec_sum + \
buy_put_executed_sum + buy_put_noExec_sum + sell_put_executed_sum + sell_put_noExec_sum
one_stock_price_sum = float(one_stock_price_sum)
return one_stock_price_sum
df_long_call, df_short_call, df_long_put, df_short_put = self.get_transaction_data(expiry_date, df_group)
find_root_by_small_step(function=calculate_one_payoff, start=start_point, increment=increment)
ticker type position expiration_date strike option_price option_amount breakeven_price
AAPL 1 0 2021-11-19 145.0000 5.1700 2500.0000 150.1700
AAPL 0 1 2021-11-19 145.0000 2.9700 2500.0000 142.0300
AAPL 0 1 2021-11-19 145.0000 2.7000 5000.0000 142.3000
AAPL 1 1 2021-11-19 145.0000 5.8500 5000.0000 150.8500
AAPL 1 1 2021-11-19 155.0000 1.6000 1050.0000 156.6000
True root = 139.9 and 159.0

function unable to work with user inputs?

I have the following code, which is a code for a connect 4 game, the problem is that the functions seem to break in the user input part of the code. I don't know if I accidentally edited something to break it but I'm almost certain that it isn't as typing the adding this to the code:
addcounter(1,1)
addcounter(1,1)
addcounter(1,1)
addcounter(1,1)
addcounter(2,1)
addcounter(2,1)
addcounter(2,1)
addcounter(3,1)
addcounter(3,1)
addcounter(4,1)
checkdiagonal(4,1,1)
The output of this does return true as expected.
The code is as follows:
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 22 17:24:35 2019
#author: Norbert
"""
import numpy as np
h = 8
w = 9
x = 0
y = 0
playspace = np.zeros((h,w))
playspace[:, [0,-1]] = 8
def addcounter(column,team):
placed = False
while not placed:
for i in range(h-1,0,-1):
if playspace[i,column] > 0:
continue
else:
if team == 1:
playspace[i,column] = 1
if team == 2:
playspace[i,column] = 2
if team != 1 and team != 2:
print("error, invalid team")
placed = True
break
def height(column):
for i in range(h-1,0,-1):
if playspace[i,column] > 0:
continue
else:
return i
def checkhorizontal(y,x,team):
a1 = 0
a2 = 0
a3 = 0
a4 = 0
for i in range(4):
try:
if playspace[h-y,x+i] == team:
a1 += 1
if playspace[h-y,x+i-1] == team:
a2 += 1
if playspace[h-y,x+i-2] ==team:
a3 += 1
if playspace[h-y,x+i-3] ==team:
a4 += 1
except:
pass
if (a1 == 4) or (a2 == 4) or (a3 == 4) or (a4 == 4):
return True
def checkvertical(y,x,team):
a1 = 0
a2 = 0
a3 = 0
a4 = 0
checking = playspace[:,x]
for i in range(4):
try:
if checking[h-(y+i)] == team:
a1 += 1
if checking[h-(y+i-1)] == team:
a2 += 1
if checking[h-(y+i-2)] ==team:
a3 += 1
if checking[h-(y+i-3)] == team:
a4 += 1
except:
pass
if (a1 == 4) or (a2 == 4) or (a3 == 4) or (a4 == 4):
return True
def checkdiagonal(y,x,team):
diag1 = 0
diag2 = 0
if playspace[h-y,x] == team:
diag1 += 1
diag2 += 1
for i in range(1,4):
broken1 = False
try:
if playspace[h-y+i,x+i] == team and not broken1:
diag1 += 1
if playspace[h-y+i,x+i] != team:
broken1 = True
except:
pass
for i in range(1,4):
broken2 = False
try:
if playspace[h-y-i,x-i] == team and not broken2:
diag1 += 1
if playspace[h-y-i,x-i] != team:
broken2 = True
except:
pass
for i in range(1,4):
broken3 = False
try:
if playspace[h-y+i,x-i] == team and not broken3:
diag2 += 1
if playspace[h-y+i,x-i] != team:
broken3 = True
except:
pass
for i in range(1,4):
broken4 = False
try:
if playspace[h-y-i,x+i] == team and not broken4:
diag2 += 1
if playspace[h-y-i,x+i] != team:
broken4 = False
except:
pass
if (diag1 >= 4) or (diag2 >= 4):
return True
finished = False
turn = 0
team_turn = 1
print(playspace)
while not finished:
valid = False
print("turn: {}".format(turn))
print("It is player {}'s turn".format(team_turn))
while not valid:
player_input = int(input("Where would you like to drop a counter?"))
if playspace[0,player_input] != 0:
print("That isn't a valid column")
else:
valid = True
if team_turn == 1:
addcounter(player_input,team_turn)
if checkhorizontal(height(player_input),player_input,team_turn) == True or checkvertical(height(player_input),player_input,team_turn) == True or checkdiagonal(height(player_input),player_input,team_turn) == True:
print("Player {} wins".format(team_turn))
finished = True
if team_turn == 2:
addcounter(player_input,team_turn)
if checkhorizontal(height(player_input),player_input,team_turn) == True or checkvertical(height(player_input),player_input,team_turn) == True or checkdiagonal(height(player_input),player_input,team_turn) == True:
print("Player {} wins".format(team_turn))
finished = True
turn += 1
turn_changed = False
while not turn_changed:
if team_turn == 1:
team_turn = 2
turn_changed = True
break
if team_turn == 2:
team_turn = 1
turn_changed = True
break
print(playspace)
any help in trying to solve the bugs in the code would be grately appreciated. The connect 4 game uses simple 2-d arrays to display and store the game board. I have plans to use this array to create a pygame later on.
EDIT:
To clarify, the checks don't run to execute a victory message and end the game. despite the if statements being True. Only the vertical win seems to end the game.
I managed to correct the horizontal part, the code correction is as follows:
if (checkhorizontal(height(player_input)+1,player_input,team_turn) == True) or (checkvertical(height(player_input),player_input,team_turn) == True) or (checkdiagonal(height(player_input),player_input,team_turn) == True):
and in the horizontalcheck function:
def checkhorizontal(y,x,team):
a1 = 0
a2 = 0
a3 = 0
a4 = 0
checking = playspace[y,:]
print(checking)
for i in range(4):
try:
if checking[x+i] == team:
a1 += 1
if checking[x+i-1] == team:
a2 += 1
if checking[x+i-2] ==team:
a3 += 1
if checking[x+i-3] ==team:
a4 += 1
except:
pass
print(a1,a2,a3,a4)
if (a1 == 4) or (a2 == 4) or (a3 == 4) or (a4 == 4):
return True
Ignore the prints, they're for debugging. But I basically removed one dimension and flipped the h-y value to become the y value.

IndentationError in the Following Python Script

My code is not running although everything is properly indented and I have been using Python for a while now, so I am no longer in the world of programming. I couldn't find the solution.
def revisedRussianRoulette(doors):
counter = 0
for i in range(0, len(doors), 2):
i = int(i)
if doors[i] == 1 & counter == 0:
counter += 1
elif doors[i] == 1 & counter == 1:
doors[i] = 0
doors[i-2] = 0
doors[i+2] = 0
elif doors[i] == 0 & counter == 1:
doors[i-2] = 0
return doors
n = int(input().strip())
doors = list(map(int, input().strip().split(' ')))
result = revisedRussianRoulette(doors)
print (" ".join(map(str, result)))
The thing I want to do with this code does not matter. I just want to ask if the syntax is correct because I am getting the following error.
C:\Users\lenovo\Desktop\Practice Files>2nd_answer_week_of_code_36.py
File "C:\Users\lenovo\Desktop\PracticeFiles\2nd_answer_week_of_code_36.py", line 13
return doors
^
IndentationError: unindent does not match any outer indentation level
Please, could anyone tell me the solution fast?
EDIT:
The solution provided by Vikas was accurate, although there were no differences between his and my code.
Do indenation like this :
def revisedRussianRoulette(doors):
counter = 0
for i in range(0, len(doors), 2):
i = int(i)
if doors[i] == 1 & counter == 0:
counter += 1
elif doors[i] == 1 & counter == 1:
doors[i] = 0
doors[i-2] = 0
doors[i+2] = 0
elif doors[i] == 0 & counter == 1:
doors[i-2] = 0
return doors
def revisedRussianRoulette(doors):
counter = 0
for i in range(0, len(doors), 2):
i = int(i)
condition_one = doors[i] == 1 & counter == 0
condition_two = doors[i] == 1 & counter == 1
condition_three = doors[i] == 0 & counter == 1
if condition_one:
counter += 1
elif condition_two:
doors[i] = 0
doors[i-2] = 0
doors[i+2] = 0
elif condition_three:
doors[i-2] = 0
return doors
n = int(input().strip())
doors = list(map(int, input().strip().split()))
result = revisedRussianRoulette(doors)
print (" ".join(map(str, result)))

Need help in adding binary numbers in python

If I have 2 numbers in binary form as a string, and I want to add them I will do it digit by digit, from the right most end. So 001 + 010 = 011
But suppose I have to do 001+001, how should I create a code to figure out how to take carry over responses?
bin and int are very useful here:
a = '001'
b = '011'
c = bin(int(a,2) + int(b,2))
# 0b100
int allows you to specify what base the first argument is in when converting from a string (in this case two), and bin converts a number back to a binary string.
This accepts an arbitrary number or arguments:
>>> def bin_add(*bin_nums: str) -> str:
... return bin(sum(int(x, 2) for x in bin_nums))[2:]
...
>>> x = bin_add('1', '10', '100')
>>> x
'111'
>>> int(x, base = 2)
7
Here's an easy to understand version
def binAdd(s1, s2):
if not s1 or not s2:
return ''
maxlen = max(len(s1), len(s2))
s1 = s1.zfill(maxlen)
s2 = s2.zfill(maxlen)
result = ''
carry = 0
i = maxlen - 1
while(i >= 0):
s = int(s1[i]) + int(s2[i])
if s == 2: #1+1
if carry == 0:
carry = 1
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
elif s == 1: # 1+0
if carry == 1:
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
else: # 0+0
if carry == 1:
result = "%s%s" % (result, '1')
carry = 0
else:
result = "%s%s" % (result, '0')
i = i - 1;
if carry>0:
result = "%s%s" % (result, '1')
return result[::-1]
Can be simple if you parse the strings by int (shown in the other answer). Here is a kindergarten-school-math way:
>>> def add(x,y):
maxlen = max(len(x), len(y))
#Normalize lengths
x = x.zfill(maxlen)
y = y.zfill(maxlen)
result = ''
carry = 0
for i in range(maxlen-1, -1, -1):
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
# r can be 0,1,2,3 (carry + x[i] + y[i])
# and among these, for r==1 and r==3 you will have result bit = 1
# for r==2 and r==3 you will have carry = 1
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1
if carry !=0 : result = '1' + result
return result.zfill(maxlen)
>>> add('1','111')
'1000'
>>> add('111','111')
'1110'
>>> add('111','1000')
'1111'
It works both ways
# as strings
a = "0b001"
b = "0b010"
c = bin(int(a, 2) + int(b, 2))
# as binary numbers
a = 0b001
b = 0b010
c = bin(a + b)
you can use this function I did:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
#a = int('10110', 2) #(0*2** 0)+(1*2**1)+(1*2**2)+(0*2**3)+(1*2**4) = 22
#b = int('1011', 2) #(1*2** 0)+(1*2**1)+(0*2**2)+(1*2**3) = 11
sum = int(a, 2) + int(b, 2)
if sum == 0: return "0"
out = []
while sum > 0:
res = int(sum) % 2
out.insert(0, str(res))
sum = sum/2
return ''.join(out)
def addBinary(self, A, B):
min_len, res, carry, i, j = min(len(A), len(B)), '', 0, len(A) - 1, len(B) - 1
while i>=0 and j>=0:
r = carry
r += 1 if A[i] == '1' else 0
r += 1 if B[j] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
i -= 1
j -= 1
while i>=0:
r = carry
r += 1 if A[i] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
i -= 1
while j>=0:
r = carry
r += 1 if B[j] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
j -= 1
if carry == 1:
return '1' + res
return res
#addition of two binary string without using 'bin' inbuilt function
numb1 = input('enter the 1st binary number')
numb2 = input("enter the 2nd binary number")
list1 = []
carry = '0'
maxlen = max(len(numb1), len(numb2))
x = numb1.zfill(maxlen)
y = numb2.zfill(maxlen)
for j in range(maxlen-1,-1,-1):
d1 = x[j]
d2 = y[j]
if d1 == '0' and d2 =='0' and carry =='0':
list1.append('0')
carry = '0'
elif d1 == '1' and d2 =='1' and carry =='1':
list1.append('1')
carry = '1'
elif (d1 == '1' and d2 =='0' and carry =='0') or (d1 == '0' and d2 =='1' and
carry =='0') or (d1 == '0' and d2 =='0' and carry =='1'):
list1.append('1')
carry = '0'
elif d1 == '1' and d2 =='1' and carry =='0':
list1.append('0')
carry = '1'
else:
list1.append('0')
if carry == '1':
list1.append('1')
addition = ''.join(list1[::-1])
print(addition)
Not an optimal solution but a working one without use of any inbuilt functions.
# two approaches
# first - binary to decimal conversion, add and then decimal to binary conversion
# second - binary addition normally
# binary addition - optimal approach
# rules
# 1 + 0 = 1
# 1 + 1 = 0 (carry - 1)
# 1 + 1 + 1(carry) = 1 (carry -1)
aa = a
bb = b
len_a = len(aa)
len_b = len(bb)
min_len = min(len_a, len_b)
carry = 0
arr = []
while min_len > 0:
last_digit_aa = int(aa[len(aa)-1])
last_digit_bb = int(bb[len(bb)-1])
add_digits = last_digit_aa + last_digit_bb + carry
carry = 0
if add_digits == 2:
add_digits = 0
carry = 1
if add_digits == 3:
add_digits = 1
carry = 1
arr.append(add_digits) # will rev this at the very end for output
aa = aa[:-1]
bb = bb[:-1]
min_len -= 1
a_len_after = len(aa)
b_len_after = len(bb)
if a_len_after > 0:
while a_len_after > 0:
while carry == 1:
if len(aa) > 0:
sum_digit = int(aa[len(aa) - 1]) + carry
if sum_digit == 2:
sum_digit = 0
carry = 1
arr.append(sum_digit)
aa = aa[:-1]
else:
carry = 0
arr.append(sum_digit)
aa = aa[:-1]
else:
arr.append(carry)
carry = 0
if carry == 0 and len(aa) > 0:
arr.append(aa[len(aa) - 1])
aa = aa[:-1]
a_len_after -= 1
if b_len_after > 0:
while b_len_after > 0:
while carry == 1:
if len(bb) > 0:
sum_digit = int(bb[len(bb) - 1]) + carry
if sum_digit == 2:
sum_digit = 0
carry = 1
arr.append(sum_digit)
bb = bb[:-1]
else:
carry = 0
arr.append(sum_digit)
bb = bb[:-1]
else:
arr.append(carry)
carry = 0
if carry == 0 and len(bb) > 0:
arr.append(bb[len(bb) - 1])
bb = bb[:-1]
b_len_after -= 1
if carry == 1:
arr.append(carry)
out_arr = reversed(arr)
out_str = "".join(str(x) for x in out_arr)
return out_str

Categories