Code:

import sys a,b,c = input().split() data = { "a" : int(a), "b" : int(b), "c" : int(c), } if data["a"] == 0: del(data["a"]) if data["b"] == 0: del(data["b"]) if data["c"] == 0: del(data["c"]) if len(data)==0: print("0") sys.exit() for i in data.keys(): if data[i] == 1: if "b" == i: data[i] = "x" if "c" == i: data[i] = "y" if data[i] == -1: if "b" == i: data[i] = "-x" if "c" == i: data[i] = "-y" else: if i == "b": if data[i] != "x": data[i] = "%sx" % data[i] if i == "c": if data[i] != "y": data[i] = "%sy" % data[i] a = b = c = "" for i in data.keys(): if i == "a": a += "%s+" % data[i] if i == "b": b += "%s+" % data[i] if i == "c": c += data[i] string = a+b+c string = list(string) i = 0 while i < len(string)-1: if string[i] == "+" and string[i+1] == "-": del(string[i]) i+=1 if string[len(string)-1] == "+": del(string[len(string)-1]) if "" == ''.join(string): print('0') else: print(''.join(string)) 

Task: School algebra (Time: 1 sec. Memory: 16 MB Complexity: 27%)

 Трёхчлен a + bx + сy от двух переменных x и y однозначно определяется коэффициентами a, b и c. Написать программу, которая по заданным a, b и c выводит соответствующий трёхчлен, записанный с использованием алгебраических соглашений: 1.коэффициент при члене, содержащем переменную, опускается, если его модуль равен единице; 2.член, коэффициент при котором равен нулю, опускается (кроме случая, когда все коэффициенты равны нулю, тогда трехчлен состоит из одной цифры 0); 3.знак "+" опускается, если он предшествует отрицательному коэффициенту; 4.знак "+" опускается, если он стоит в начале выражения (так называемый унарный плюс); 5.знак умножения между коэффициентом и переменной опускается. При этом запрещено менять местами члены. Во входном файле INPUT.TXT через пробел записаны целые коэффициенты a, b и с, каждое из которых не превосходит 30000 по абсолютной величине. Выходной файл OUTPUT.TXT должен содержать трехчлен, записанный с использованием алгебраических соглашений. 

Example:

0 2 -1 -> 2x-y
3 0 -2 -> 3-2y

In the code I have a lot of conditional statements. How to reduce their count? And how to make the code beautiful?

  • Move both the code and the task directly to the text of the question without references to third-party resources - andreymal
  • @andreymal corrected - Aminev Timur

2 answers 2

In the code I have a lot of conditional statements. How to reduce their count?

It is possible to use one / two if for each rule in declarative style:

 def format_polynom(*coeffs, vars=("", "x", "y")): return ( "".join( # VVV rule #3 VVV rule #1 VVV rule #3 rule #5 VVV ("{:+}".format(c) if abs(c) != 1 or not v else "-" if c < 0 else "+") + v if c # rule #2 else "" for c, v in zip(coeffs, vars) ).lstrip("+") # rule #4 or "0" # rule #2 ) 

 <script src="https://cdn.rawgit.com/brython-dev/brython/3.4.0/www/src/brython.js"></script><body onload="brython()"><script type="text/python"> def format_polynom(*coeffs, vars=("", "x", "y")): return ( "".join( ("-" if c < 0 else "+") # sign + (str(abs(c)) if abs(c) != 1 or not v else "") # magnitude + v # variable name if c else "" # rule #2 for c, v in zip(coeffs, vars) ).lstrip("+") # rule #4 or "0" # rule #2 ) from browser import document @document["mybutton"].bind("click") def on_click(event): coeffs = [int(document[c].value) for c in 'abc'] print(*coeffs, '->', format_polynom(*coeffs)) on_click('dummy on start') </script><div><label for="a">a&nbsp;=</label>&nbsp;<input id="a" value="3"></div><div><label for="b">b&nbsp;=</label>&nbsp;<input id="b" value="0"></div><div><label for="c">c&nbsp;=</label>&nbsp;<input id="c" value="-2"></div><button id="mybutton">Форматировать трёхчлен</button></body> 

Example:

 >>> format_polynom(0, -1, 2) '-x+2y' >>> format_polynom(3, 0, -2) '3-2y' 

All interesting cases can be itertools.product() using itertools.product() :

 from itertools import product for coeffs in product(range(-2, 3), repeat=3): print(*coeffs, "->", format_polynom(*coeffs)) 

Result

 -2 -2 -2 -> -2-2x-2y -2 -2 -1 -> -2-2x-y -2 -2 0 -> -2-2x -2 -2 1 -> -2-2x+y -2 -2 2 -> -2-2x+2y -2 -1 -2 -> -2-x-2y -2 -1 -1 -> -2-xy -2 -1 0 -> -2-x -2 -1 1 -> -2-x+y -2 -1 2 -> -2-x+2y -2 0 -2 -> -2-2y -2 0 -1 -> -2-y -2 0 0 -> -2 -2 0 1 -> -2+y -2 0 2 -> -2+2y -2 1 -2 -> -2+x-2y -2 1 -1 -> -2+xy -2 1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1 0 -2 -> 1-2y 1 0 -1 -> 1-y 1 0 0 -> 1 1 0 1 -> 1+y 1 0 2 -> 1+2y 1 1 -2 -> 1+x-2y 1 1 -1 -> 1+xy 1 1 0 -> 1+x 1 1 1 -> 1+x+y 1 1 2 -> 1+x+2y 1 2 -2 -> 1+2x-2y 1 2 -1 -> 1+2x-y 1 2 0 -> 1+2x 1 2 1 -> 1+2x+y 1 2 2 -> 1+2x+2y 2 -2 -2 -> 2-2x-2y 2 -2 -1 -> 2-2x-y 2 -2 0 -> 2-2x 2 -2 1 -> 2-2x+y 2 -2 2 -> 2-2x+2y 2 -1 -2 -> 2-x-2y 2 -1 -1 -> 2-xy 2 -1 0 -> 2-x 2 -1 1 -> 2-x+y 2 -1 2 -> 2-x+2y 2 0 -2 -> 2-2y 2 0 -1 -> 2-y 2 0 0 -> 2 2 0 1 -> 2+y 2 0 2 -> 2+2y 2 1 -2 -> 2+x-2y 2 1 -1 -> 2+xy 2 1 0 -> 2+x 2 1 1 -> 2+x+y 2 1 2 -> 2+x+2y 2 2 -2 -> 2+2x-2y 2 2 -1 -> 2+2x-y 2 2 0 -> 2+2x 2 2 1 -> 2+2x+y 2 2 2 -> 2+2x+2y 

It may be easier to understand the variant that each member represents as a sign plus an absolute value plus the name of a variable :

 def format_polynom(*coeffs, vars=("", "x", "y")): return ( "".join( ("-" if c < 0 else "+") # sign + (str(abs(c)) if abs(c) != 1 or not v else "") # magnitude + v # variable name if c else "" # rule #2 for c, v in zip(coeffs, vars) ).lstrip("+") # rule #4 or "0" # rule #2 ) 

The output is identical to the first option.

  • What does str(abs(c)) if abs(c) != 1 or not v else "" mean str(abs(c)) if abs(c) != 1 or not v else "" ? - Aminev Timur
  • a if b else c ? A concrete example is the implementation of rule No. 1 - jfs
  • and we conceive or not v ? What is it like? - Aminev Timur
  • @AminevTimur: to determine if the variable name is empty or not. Checking the list for emptiness - jfs

Instead of (two in your code)

 for i in data.keys(): 

you can just write

 for i in data: 

and instead

 if data["a"] == 0: del(data["a"]) if data["b"] == 0: del(data["b"]) if data["c"] == 0: del(data["c"]) 

can write

 for char in "abc": if data[char] == 0: del(data[char]) 

Style

 if "b" == i: 

old-fashioned (was for security - = instead of correct == ) - and not only in Python, write simply and more clearly

 if i == "b": 

Instead

 while i < len(string)-1: if string[i] == "+" and string[i+1] == "-": del(string[i]) i+=1 

can write more clearly

 for i, __ in enumerate(string): if string[i] == "+" and string[i+1] == "-": del(string[i]) 

but this part of you is wrong - you change the list you are going through in a cycle!

  • And how to remove items from the list? - Aminev Timur
  • One possibility is not to delete, but to create a new empty list (string) in which you will add the appropriate elements (signs). - MarianD