I had a friend of mine show me an interesting problem he had on a coding challange at an interview. So you have a number like n = 3413289830 and a pattern like p = a-bcdefghij, you need to create a function that takes this input and outputs -413289827. Obviously it should work for any combination of numbers and letters for addition and subtraction. I worked out this code but I am pretty sure it can be improved as I think it's a bit inefficient.
pattern = 'a-bcdefghij'
n = '3413289830'
lst = []
def splitnb(n, pattern):
save = dict()
if(len(n) != len(pattern) - 1):
print('Pattern needs to match number')
else:
if( '-' in pattern):
patlst = pattern.split('-')
elif('+' in pattern):
patlst = pattern.split('+')
for char in n:
a = list(n)
for pat in patlst:
first = patlst[0].split()
rest = pat.split()
for l in first[0]:
f1 = l
lst.append(f1)
for l2 in rest[0]:
f2 = l2
lst.append(f2)
save = dict(zip(lst, a))
nb = ''
if( '-' in pattern):
for i in first[0]:
numb = int(save.get(i))
for j in rest[0]:
nb += save.get(j)
numb1 = numb - int(nb)
elif('+' in pattern):
for i in first[0]:
numb = int(save.get(i))
for j in rest[0]:
nb += save.get(j)
numb1 = numb + int(nb)
return numb1
f1 = splitnb(n, pattern)
f2 = splitnb('1234', 'ab+cd')
f3 = splitnb('22', 'a-b')