Answer the question
In order to leave comments, you need to log in
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))
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question