Home > Enterprise >  Custom function taking string as input which breaks a math problem into smaller bits and adds them t
Custom function taking string as input which breaks a math problem into smaller bits and adds them t

Time:06-13

I have recently started learning python and am trying to build a simple function to break up a math problem into smaller parts. For example if the problem is (1 2) (2 4) it would break it up and store it in an array: ["(1 2)", " ", "(2 4)"]. Below ill post the code i have so far.

code:

def crush(string):
    crushed_string = []
    for i in range(0, len(string)):
        current_problem = ""
        if string[i] == "(":
            for x in range(i, len(string)):
                if string[x] == ")":
                    for y in range(i, x 1):
                        current_problem  = string[y]
                    print(current_problem)


string = "(1 2) (3 4)"
crush(string)

I am printing current_problem to the terminal instead of adding it to an array just for testing but the output i am getting doesn't make sense to me... the output: (1 2) (1 2)(1 2) (3 4) (3 4)

I'm not looking for a code dump but rather to understand what is happening and why so i can improve and not just copy paste. If anyone could please explain why this is the output i am getting i would be really grateful.

note: I know i haven't added the between the brackets yet but I've ran into this problem before I've gotten to that and would like to first understand what is happening before moving on.

CodePudding user response:

If you want to perform math operations into a string, the best solution is to use regular expressions like this. To learn more about them, please visit the official Python documentation about the re library :

import re

s = "(1 2) (3 4)"
print(re.findall('[ -/*//()]|\d ',s))

Output
As you can see, it breaks down the string to an elemental level, not only reducing parenthesis:

['(', '1', ' ', '2', ')', ' ', '(', '3', ' ', '4', ')']

CodePudding user response:

I highly recommend @Cardstdani method, but here is a complex maze of if else statement which resembles your desired result.

def crush(string):
    crushed_string = []
    for i in range(0, len(string)):
        current_problem = ""
        if string[i] == "(":
            for x in range(i, len(string)):
                if string[x] == ")":
                    for y in range(i, x 1):
                        current_problem  = string[y]
                    crushed_string.append(current_problem)
                    i = x 1
                    break

    return crushed_string

string = "(1 2) (3 4)"
print(crush(string))

output:

['(1 2)', '(3 4)']
  • Related