context, i am a beginner in coding, barely halfway into my semester for my coding module and just decided to try out a coding question. here is the question, and my code attempt

if it’s possible to separate the digits with either a plus or minus sign to get the final expression to equal zero.

For example: if num is 35132 then it’s possible to separate the digits the following way, 3 – 5 + 1 + 3 – 2, and this expression equals zero. Your program should return a string of the signs you used. if impossible to equate to zero, return “no solution”

import random

number = input ("input the number to be ran through the program: ")
zero = "0"

a = number + zero
a = str(a)
length = len(a) - 1

while True:
    plusminus = "+-"
    op = random.choices(plusminus, k= length)
    operations = "".join(op)

    eqn = ''.join(map(''.join, zip(a, operations)))
    eqn = eqn[0:-1]
    ans = eval(eqn)
    
    if ans == 0:
        print(operations[:-1])
        break

i am unable to get my loop to end with “no solution” if there is no solution, how do i end the loop if there is no solution, and print out the string?
also, this code feels “unclean” to me, with the zero variable added so tat my equation(eqn) ends with a number instead of +/-, and “while true” feels out of place, but i needed it to loop the random function. how would you guys code this? thanks!

i have tried adding print at the end of code, but when there is a solution, it will print “-++-” “no soln”, i have tried using looping at ans ==0, and compiling the possibilities of loops into a list, but it ended up as a an infinite loop of list rather than a list of infinite strings(is it even possible?).



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *