Click here to Skip to main content
15,357,293 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wrote the code, its essence is to place brackets so that the answer is the maximum example input 1 + 2 * 3-2 * 4 output 28 and my code outputs 20 Help solve the error


What I have tried:

Python
<pre>ops = ('+-*')
s = input( f'Enter an arithmetic expression with operation signs { list(ops) }: ' )
lis = list( map( lambda x: ') '+x+' (' if x in ops else x, list(s) ) )
s = ''.join(lis)
s = '(' + s + ')'
max_val = float('-inf')
max_str = None
par_count = s.count( '(' ) + s.count( ')' )
for i in range( 2 ** par_count ):
    b = bin(i)[2:].zfill(par_count)
    b_ind = 0
    ss = ''
    for symb in s:
        if symb in '()':
            ss += ( '',symb )[ int( b[b_ind] ) ]
            b_ind += 1
        else:
            ss += symb
    try:
        val = eval( ss )
        if val > max_val:
            max_val = val
            max_str = ss
    except:
        pass
print( f'{ max_str } = { max_val }' )
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900