滴滴出行笔试 算术表达式交换

题目描述:输入一个算术表达式,可以进行任意次相邻数字的交换,使其按字典序排序,同时保证表达式的最终结果不变,例如a

很丑陋的代码,考虑所有特殊情况,但考试时没有考虑到减和除也存在可以交换的情况,如果大家有简单的思路欢迎交流。

import sys
loop = int(sys.stdin.readline().strip())
n = [str(x) for x in sys.stdin.readline().strip().split()]
l = len(n)
operator = []
number = []
flag = 1
i = 0
while i < l: 
    if flag:
        arr = []
        arr.append(n[i])
        i += 1
        if i < l:
            while n[i].isdigit():
                arr.append(n[i])
                i += 1
        string = ''.join(arr)
        number.append(int(string))
        flag = 0
    else:
        operator.append(n[i])
        i += 1
        flag = 1
for _ in range(loop):
    for i in range(loop-1):
        if number[i] > number[i+1]:
            if i != 0 and i != loop-2:
                if operator[i] == '*' and operator[i-1] != '/':
                    number[i], number[i+1] = number[i+1], number[i]
                if operator[i] == '+' and (operator[i+1] != '/' and operator[i+1] != '*') and operator[i-1] == '+':
                    number[i], number[i+1] = number[i+1], number[i]
                if operator[i] == '-' and operator[i-1] == '-' and (operator[i+1] != '/' and operator[i+1] != '*'):
                    number[i], number[i+1] = number[i+1], number[i]
                if operator[i] == '/' and operator[i-1] == '/':
                    number[i], number[i+1] = number[i+1], number[i]
            elif i == 0:
                if operator[i] == '*':
                    number[i], number[i+1] = number[i+1], number[i]
                if operator[i] == '+' and (operator[i+1] != '/' and operator[i+1] != '*'):
                    number[i], number[i+1] = number[i+1], number[i]
                if operator[i] == '-' and operator[i-1] == '-' and (operator[i+1] != '/' and operator[i+1] != '*'):
                    number[i], number[i+1] = number[i+1], number[i]
            else:
                if operator[i] == '*' and operator[i-1] != '/':
                    number[i], number[i+1] = number[i+1], number[i]
                if operator[i] == '+' and operator[i-1] == '+':
                    number[i], number[i+1] = number[i+1], number[i]
                if operator[i] == '-' and operator[i-1] == '-':
                    number[i], number[i+1] = number[i+1], number[i]
                if operator[i] == '/' and operator[i-1] == '/':
                    number[i], number[i+1] = number[i+1], number[i]
result = ''
result += str(number[0])
for i in range(loop-2):
    result += ' ' + operator[i]
    result += ' ' + str(number[i+1])
result += ' ' + operator[loop-2]
result += ' ' + str(number[loop-1])
print(result)

你可能感兴趣的:(算法工程师)