0

Im farely new to python but I want to convert a string of both numbers and letters into an array. Is there somehow that I can make the numbers without a string and keep the letters as a string?

Example: string = "2A3M4D8"

I want the A's to be an addition numbers on both side. The M to be multiply, D, divide and S, subtract. So the program should be calculating ((2+3)*4)/8=2,5

import numpy as np
def compile(program):
    program=map(int,program())

    newvector=np.array([])

    for i in range(len(program)):
        if program[i]=="A":
            R=program[i-1]+program[i+1]
            
        elif program[i]=="S":
            R=program[i-1]-program[i+1]
        
        elif program[i]=="M":
            R=program[i-1]*program[i+1]
            
        elif program[i]=="D":
            R=program[i-1]/program[i+1]
            
            newvector=np.concatenate(newvector,R)
    
        result=sum(newvector)
    
    return result

print(compile("3A3"))
wwii
  • 23,232
  • 7
  • 37
  • 77
  • 1
    did you try anything and what error you faced? – Krishna Chaurasia Jan 20 '21 at 15:26
  • Sound like you can replace `'A'` with `'+'` etc using something like `str.translate`, then use [something like this](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) to evaluate the final expression. – Cory Kramer Jan 20 '21 at 15:28
  • I tried using map(int) and then set op a forloopis but i only receve 0 as the output. – Julie Rønnov Jan 20 '21 at 15:30
  • I just updatet the question with my code ^^ – Julie Rønnov Jan 20 '21 at 15:32
  • Please always format code/traceback/data - select it and type `ctrl-k`. [Formatting help](https://stackoverflow.com/editing-help)... [Formatting sandbox](https://meta.stackexchange.com/questions/3122/formatting-sandbox) – wwii Jan 20 '21 at 15:35
  • What's the logic for getting as an output `((2+3)*4)/8=2,5` with input `2A3M4D8`? Is the string you are excpecting always of the same format (same length eveything the same just with different numbers)? – Countour-Integral Jan 20 '21 at 15:36
  • Thanks didnt know how it worked ^^ – Julie Rønnov Jan 20 '21 at 15:36
  • No not always the same lenght but same format ^^ – Julie Rønnov Jan 20 '21 at 15:37
  • Is this homework? – wwii Jan 20 '21 at 15:39
  • No not homework but yes im currently looking at assignments about introduction to programming in python. ^^ – Julie Rønnov Jan 20 '21 at 15:42
  • Related:[Splitting letters from numbers within a string](https://stackoverflow.com/questions/15572387/splitting-letters-from-numbers-within-a-string), [Product code looks like abcd2343, what to split by letters and numbers](https://stackoverflow.com/questions/3340081/product-code-looks-like-abcd2343-what-to-split-by-letters-and-numbers), [Split a string consisting of letters and numbers into parts](https://stackoverflow.com/questions/22863430/split-a-string-consisting-of-letters-and-numbers-into-parts) ... more searching with `python split letters and numbers in string site:stackoverflow.com` – wwii Jan 20 '21 at 16:16

3 Answers3

0
import re

string="2A3M4D8"

string = re.sub(r"([0-9]+)A([0-9]+)",'('+r'\1'+'+'+r'\2'+')',string)

string = re.sub(r"M","*",string)

string = re.sub(r"D","/",string)

print (eval(string))

Output:

2.5

You use re.sub() to format correctly for operation priority and to replace letter operators by math operators. Then you eval() and get it.

Synthase
  • 5,849
  • 2
  • 12
  • 34
  • I just updatet my question with mu code. Im glad you answered but I'm not sure i know how this function works. Maybe you can help with my forloop ? – Julie Rønnov Jan 20 '21 at 15:35
0
s = '2A3M4D8'
    s = re.split('(\d+)', s)
    s = list(filter(None, s))
    print(s)

    stack = []
    res = 0
    letter = ''

    for x in s:
        if x.isnumeric():
            stack.append(int(x))
            if letter != '':
                print(stack)
                if letter == 'M':
                    res = stack[0] * stack[1]
                elif letter == 'A':
                    res = stack[0] + stack[1]
                elif letter == 'D':
                    res = stack[0] / stack[1]
                stack = []
                print(res)
                stack.append(res)
                print(stack)
                res = 0
                letter = ''
        else:
            letter = x
    print(stack[0])

0

you can use replace also to replace A,M,D,S with operators and than put parenthesis once you obtain the string with operators included and evaluate the same .

j='2A3M4D8'
for i in j:
    if i == 'A':
        j = j.replace('A','+')
    if i == 'M':
        j = j.replace('M','*')
    if i == 'D':
        j = j.replace('D','/')
    if i == 'S':
        j = j.replace('S','-')

count = 0
a = '('
b = ')'
arr = []
for i in j:
    if i.isdigit() and count%2 == 0:
        i = a + i
        arr.append(i)
    elif i.isdigit() and count%2 == 1:
        i = i + b
        arr.append(i)
    else:
        arr.append(i)
        count -= 1
        
    count += 1
        

print (eval(''.join(arr)))
Diwakar SHARMA
  • 573
  • 7
  • 24