Advertisement
Guest User

Untitled

a guest
Oct 10th, 2015
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.44 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import sys
  3. import collections
  4. import time
  5. import re
  6. import decimal
  7.  
  8.  
  9. def get_new_form(polynomial, variables):
  10.     dic = {}
  11.     splitted = split_polynomial(polynomial)
  12.     for mono in splitted:
  13.         coefficients = []
  14.         coefficients.append(1.0)
  15.         powers = []
  16.         power_zero = []
  17.         for v in variables:
  18.             powers.append(0)
  19.             power_zero.append(0)
  20.         i = 0
  21.         while i < len(mono):
  22.             if mono[i] == '-':
  23.                 coefficients.append(-1.0)
  24.             elif mono[i] in variables:
  25.                 variable = mono[i]
  26.                 if i < len(mono)-1 and mono[i+1] == '^':
  27.                     i += 2
  28.                     power = float(mono[i])
  29.                 else:
  30.                     power = 1.0
  31.                 powers[variables.index(variable)] += power
  32.             elif is_number(mono[i]):
  33.                 coefficients.append(float(mono[i]))
  34.             i += 1
  35.         final_coef = 1.0
  36.         for e in coefficients:
  37.             e = float(e)
  38.             final_coef *= e
  39.         a = tuple(powers)
  40.         if len(coefficients) == 1 and power_zero == powers:
  41.             dic[a] = 0
  42.         else:
  43.             if a in dic:
  44.                 dic[a] += final_coef
  45.             else:
  46.                 dic[a] = final_coef
  47.         final_poly = Polynomial(dic)
  48.     return final_poly
  49.  
  50.  
  51. def calculate_polynomial(polynomial, variables):
  52.     standart_operators = ["+", "-", "*", "/", "^"]
  53.     polynomial_good_form = ['(']
  54.     open_bracket = False
  55.     close_bracket = False
  56.     i = 0
  57.     polynomial.insert(0, '(')
  58.     polynomial.append(')')
  59. #    #if polynomial[0] == '(':
  60.     #    i += 1
  61.     i += 1
  62.     while i < len(polynomial):
  63.         if polynomial[i] == '(' or polynomial[i] == ')':
  64.             list = []
  65.             next = i
  66.             open_bracket = False
  67.             close_bracket = False
  68.             if polynomial[i] == '(':
  69.                 open_bracket = True
  70.                 if polynomial[i-1] in standart_operators:
  71.                     operand = polynomial[i-1]
  72.                 else:
  73. #                    #print(i)
  74.                     #print('(')
  75.                     polynomial_good_form.append('(')
  76.                     i += 1
  77.                     continue
  78.                 i -= 1
  79.             elif polynomial[i] == ')':
  80.                 if polynomial[i-1] == ')':
  81. #                    #print(i)
  82.                     #print(')k')
  83.                     polynomial_good_form.append(')')
  84.                     i += 1
  85.                     continue
  86.                 elif (i < len(polynomial)-2):
  87.                         if polynomial[i+2] != '(' and polynomial[i+1] != '(' and polynomial[i+1] != ')':
  88. #                            #print(i)
  89.                             close_bracket = True
  90.                             #print(close_bracket)
  91.                             operand = polynomial[i+1]
  92.                             if operand == '-':
  93.                                 operand = '+'
  94.             i -= 1
  95.             while polynomial[i] != '(' and polynomial[i] != ')' and i >= 0:
  96.                 list.append(polynomial[i])
  97.                 i -= 1
  98.             list.reverse()
  99.             #print(list)
  100.             if len(list) == 0:
  101.                 pass
  102. #                #polynomial_good_form.append(operand)
  103.             else:
  104.                 polynomial_good_form.append(get_new_form(list, variables))
  105. ##dict pered skobkoi
  106.             if open_bracket:
  107. #                #print(operand)
  108.                 #print('operando')
  109.                 polynomial_good_form.append(operand)
  110.                 open_bracket = False
  111. #                #print(next)
  112.                 #print(polynomial[next])
  113.                 polynomial_good_form.append(polynomial[next])
  114.             elif close_bracket:
  115. #                #print(next)
  116.                 #print(polynomial[next])
  117.                 polynomial_good_form.append(polynomial[next])
  118. #                #print('operandc')
  119.                 #print(operand)
  120.                 polynomial_good_form.append(operand)
  121.                 close_bracket = False
  122.             else:
  123. #                #print(next)
  124.                 #print(polynomial[next])
  125.                 polynomial_good_form.append(polynomial[next])
  126.             i = next + 1
  127.         else:
  128.             i += 1
  129.     return polynomial_good_form
  130.  
  131.  
  132. def convert_to_postfix_notation(input):
  133.     outputSeparated = []
  134.     stack = []
  135.     operators = ['(', ')', '+', '-', '*', '/', '^']
  136.     for c in input:
  137.         if c in operators:
  138.             if len(stack) > 0 and c != '(':
  139.                 if c == ')':
  140.                     s = stack.pop()
  141.                     while s != '(':
  142.                         outputSeparated.append(s)
  143.                         s = stack.pop()
  144.                 elif get_priority(c) > get_priority(stack[len(stack)-1]):
  145.                     stack.append(c)
  146.                 else:
  147.                     while len(stack) > 0 and get_priority(c) <= get_priority(stack[len(stack)-1]):
  148.                         outputSeparated.append(stack.pop())
  149.                     stack.append(c)
  150.             else:
  151.                 stack.append(c)
  152.         else:
  153.             outputSeparated.append(c)
  154.     if (len(stack) > 0):
  155.         for i in range(len(stack)):
  156.             outputSeparated.append(stack[len(stack)-1-i])
  157.     return outputSeparated
  158.  
  159.  
  160. def get_priority(s):
  161.     if s in ['(', ')']:
  162.         return 0
  163.     if s in ['+', '-']:
  164.         return 1
  165.     if s in ['*', '/']:
  166.         return 2
  167.     if s in ['^']:
  168.         return 3
  169.     else:
  170.         return 4
  171.  
  172.  
  173. def split_polynomial(polynomial):
  174.     monomials = []
  175.     monomial = []
  176.     sign_in_the_begin = False
  177.     if polynomial[0] == '-':
  178.         monomial.append('-')
  179.         sign_in_the_begin = True
  180.         k = 1
  181.     elif polynomial[0] == '+':
  182.         monomial.append('+')
  183.         sign_in_the_begin = True
  184.         k = 1
  185.     else:
  186.         monomial.append('+')
  187.         k = 0
  188.     for i in range(k, len(polynomial)):
  189.         if polynomial[i] != '+' and polynomial[i] != '-':
  190.             monomial.append(polynomial[i])
  191.         else:
  192.             monomials.append(monomial)
  193.             monomial = []
  194.             monomial.append(polynomial[i])
  195.     monomials.append(monomial)
  196.     return monomials
  197.  
  198.  
  199. class Polynomial:
  200.     dict = {}
  201.  
  202.     def __init__(self, poly):
  203.         self.dict = poly
  204.  
  205.     def __str__(self):
  206.         return str(self.dict)
  207.  
  208.     def __add__(self, poly2):
  209.         for key in poly2.dict:
  210.             if key in self.dict:
  211.                 self.dict[key] += poly2.dict[key]
  212.             else:
  213.                 self.dict[key] = poly2.dict[key]
  214.         return self.simplify()
  215.  
  216.     def __mul__(self, poly2):
  217.         result_poly = {}
  218.         for e1 in self.dict:
  219.             for e2 in poly2.dict:
  220.                 e3 = list()
  221.                 for i in range(len(e1)):
  222.                     e3.append(e1[i] + e2[i])
  223.                 e3 = tuple(e3)
  224.                 if e3 in result_poly:
  225.                     result_poly[e3] += self.dict[e1] * poly2.dict[e2]
  226.                 else:
  227.                     result_poly[e3] = self.dict[e1] * poly2.dict[e2]
  228.         self.dict = result_poly
  229.         result_poly = self.simplify()
  230.         return self
  231.  
  232.     def simplify(self):
  233.         list_for_delete = []
  234.         for e in self.dict:
  235.             if self.dict[e] == 0:
  236.                 list_for_delete.append(e)
  237.         for e in list_for_delete:
  238.             self.dict.pop(e)
  239.         return self
  240.  
  241.  
  242. def is_number(s):
  243.     try:
  244.         float(s)
  245.         return True
  246.     except ValueError:
  247.         return False
  248.  
  249.  
  250. def separate(input):
  251.     tokens = []
  252.     pos = 0
  253.     while pos < len(input):
  254.         standart_operators = ["(", ")", "+", "-", "*", "/", "^"]
  255.         s = input[pos]
  256.         if not input[pos] in standart_operators:
  257.             if input[pos].isdigit():
  258.                 for i in range(pos+1, len(input)):
  259.                     if not input[i].isdigit(()) and input[i] != ',' and input[i] != '.':
  260.                         break
  261.                     s += input[i]
  262.             elif input[pos].isalpha():
  263.                 for i in range(pos+1, len(input)):
  264.                     if not input[i].isalpha() and not input[i].isdigit():
  265.                         s += input[i]
  266.                 tokens.append(s)
  267.                 pos += len(s)
  268.     return tokens
  269.  
  270.  
  271. def delete_spaces(input):
  272.     list_without_spaces = []
  273.     for i in range(len(input)):
  274.         if input[i] != ' ':
  275.             list_without_spaces.append(input[i])
  276.     return list_without_spaces
  277.  
  278.  
  279. def add_multiple_symbol(input):
  280.     list1 = []
  281.     symbols = ["(", ")", "+", "-", "*", "/", "^"]
  282.     for i in range(len(input)):
  283.         if i > 0 and input[i].isdigit() and input[i-1].isdigit():
  284.             list1[len(list1)-1] = list1[len(list1)-1] + input[i]
  285.         elif i > 0 and ((input[i-1] not in symbols and input[i] not in symbols) or
  286.         (input[i] == '(' and input[i-1] not in symbols) or
  287.         (input[i-1] == ')' and input[i] not in symbols) or
  288.         (input[i-1] == ')' and input[i] == '(')):
  289.             list1.append('*')
  290.             list1.append(input[i])
  291.         else:
  292.             list1.append(input[i])
  293.     return list1
  294.  
  295. '''
  296. def parse_polynomial(text):
  297.    return re.split(r'-+', text).strip()
  298.  
  299.  
  300. def get_dictionary_of_polynomial(polynomial):
  301.    dictionary = {}
  302.    i = 0
  303.    while i < len(polynomial):
  304.        power = ''
  305.        factor = '
  306.        if polynomial[i] == ' ':
  307.            i+=1
  308.            continue
  309.        if polynomial[i] == '+' or polynomial[i] == '-':
  310.            sign =  polynomial[i]
  311.            i+=1
  312.            while polynomial[i].isdigit() and i < len(polynomial)-1 or polynomial[i] == r'/':
  313.                factor = factor + polynomial[i]
  314.                i += 1
  315.            if i == len(polynomial)-1 and polynomial[i].isdigit():
  316.                factor = factor + polynomial[i]
  317.        if factor != '':
  318.            if factor.find(r'/') == -1:
  319.                factor = float(factor)
  320.            else:
  321.                numerator = factor[:factor.index(r'/')]
  322.                denominator = factor[factor.index(r'/') +1:]
  323.                factor = float(numerator)/ float(denominator)
  324.            if sign == '-':
  325.                factor = -factor
  326.        else:
  327.            if sign == '-':
  328.                factor = -1.0
  329.            else:
  330.                factor = 1.0
  331.        print('factor:', factor)
  332.        if polynomial[i] == 'x':
  333.            i += 1
  334.            if polynomial[i] == '^':
  335.                i+=1
  336.                while polynomial[i].isdigit():
  337.                    power = power + polynomial[i]
  338.                    i+=1
  339.                power = float (power)
  340.            else:
  341.                power = 1.0
  342.            print('power', power)
  343.        else:
  344.            power = 0.0
  345.            print('power', power)
  346.        if power in dictionary:
  347.            dictionary[power] += factor
  348.        else:
  349.            dictionary[power] = factor
  350.        i+=1
  351.    return dictionary
  352.    '''
  353.  
  354.  
  355. def final_move(notation):
  356.     stack = []
  357.     standart_operators = ["+", "-", "*", "/", "^"]
  358.     for e in notation:
  359.         if e in standart_operators:
  360.             w1 = stack.pop()
  361.             w2 = stack.pop()
  362.             result = make_operation(e, w1, w2)
  363.             stack.append(result)
  364.         else:
  365.             stack.append(e)
  366.     return stack[0]
  367.  
  368.  
  369. def make_operation(e, w1, w2):
  370.     if e == '+':
  371.         return w1 + w2
  372.     if e == '*':
  373.         return w1*w2
  374.     if e == '-':
  375.         w2 = w2 * get_new_form(['-', '1'], ['x', 'y', 'z'])
  376.         return w1 + w2
  377.  
  378.  
  379. def main():
  380.     variables = ['x', 'y', 'z']
  381.     polynomial1 = '(x+z)(y+x)-z(x+y)'
  382.     polynomial2 = 'x(y+x)'
  383.     if final_move(convert_to_postfix_notation(calculate_polynomial(add_multiple_symbol(delete_spaces(polynomial1)),
  384.                                                                    variables))).dict ==\
  385.             final_move(convert_to_postfix_notation(calculate_polynomial(add_multiple_symbol(delete_spaces(polynomial2)),
  386.                                                                         variables))).dict:
  387.         print('Polynomials are the same')
  388.     else:
  389.         print(final_move(convert_to_postfix_notation(calculate_polynomial(add_multiple_symbol(delete_spaces(polynomial1)),
  390.                                                                    variables))).dict)
  391.         print(final_move(convert_to_postfix_notation(calculate_polynomial(add_multiple_symbol(delete_spaces(polynomial2)),
  392.                                                                           variables))).dict)
  393.     '''
  394.    print(calculate_polynomial(['(', 'x', '+', 'y', ')', '*', '(', 'x', '-', 'y', ')'], variables))
  395.    print(calculate_polynomial(['(', '(', '(', 'x', '+', 'z', ')', '*',  '(', 'x', '-', 'y', ')', '-', '6', '*', 'x',
  396.                                ')', ')'], ['x', 'y', 'z']))
  397.    print(calculate_polynomial(['x', '+' ,'(', 'y', '+', '4', '*', 'x', '-', '(','5', '*', 'y' ,'-', '6',')','+', '(',
  398.    '6','*', 'y','+','x',')','*','(', '5', '*', 'y', '-', '6',')',')','*','(','x','-','y' ,')'],  ['x', 'y', 'z']))
  399.  
  400.    polynomial1 ='+x^2 +2/4x^3 +54 -21'
  401.    polynomial2 = '+8/16x^3 +1x^2 +33'
  402.    dictionary1 = get_dictionary_of_polynomial(polynomial1)
  403.    dictionary2 = get_dictionary_of_polynomial(polynomial2)
  404.    for e in dictionary1:
  405.        print (e, dictionary1[e])
  406.    if dictionary1 == dictionary2:
  407.        print('True')
  408.    else:
  409.        print('False')
  410.    for e in dictionary2:
  411.        print (e, dictionary2[e])
  412.    '''
  413. if __name__ == '__main__':
  414.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement