I
I
Iqv2016-12-29 16:36:02
Python
Iqv, 2016-12-29 16:36:02

What is wrong in the code (Python3)?

There is a task:
A string is entered in the format
ax + b = 0
or
ax - b = 0
where instead of a - an integer, instead of b - a non-negative integer. Modulo numbers do not exceed 1000. The number a can be omitted if it is equal to 1. b is always present, x is also always present, even if a = 0.
Print the roots of the equation if there are a finite number of them; 'NO' if there are no roots and 'INF' if there are infinitely many roots.
My decision:

s = input()
a = s[:s.index("x")]
if s.find('+') != -1:
    b = -int(s[s.index("+")+1:s.index("=")])
else:
    b = int(s[s.index("-")+1:s.index("=")])
if a == "0" and b == 0:
    print("INF")
elif a == "0" and b != 0:
    print("NO")
elif a == "":
    print(b)
else:
    print(b/int(a))

Part Solution. Your score is = 9, 9/10
What's wrong with the code?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sly_tom_cat ., 2016-12-30
@Iqv

Better use regular expressions:

s = input()
res = re.findall(r'(-?\d?)x([+-]\d)=0', s)[0]
a = (-1 if res[0] == '-' else
     1 if not res[0] else
     int(res[0]))
b = int(res[1]) 
print(('INF' if b == 0 else 'NO') if a == 0 else -b/a)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question