2019/8/27 滴滴算法笔试题1

本文介绍了一种针对包含加、减、乘、除运算的表达式进行顺序优化的算法,该算法通过重新排列相邻数字以达到不改变运算结果的同时,获得更优的运算顺序组合。示例中,输入表达式为'3+2+1*6*-2/5',输出优化后的顺序为'2+3+-2*1*6/5'。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: utf-8 -*-
"""
Created on Wed Aug 28 09:51:02 2019

@author: QinLong
给定一组四则运算(+ - * /),只能相邻数字相交换,求不改变运算结果的最小顺序组合。
eg:
input: 3 + 2 + 1 * 6 * -2 / 5
out : 2 + 3 + -2 * 1 * 6 / 5
"""

  
        
number = [3,2,1,6,-2,5]
n = len(number)
fuhao = ['+','+','*','*','/']
       
res = []
count = 0       
for j in range(len(fuhao)):
    if fuhao[j] == '*':
        
        count = j
        count_2 = 1
        while count < n-2 and fuhao[count + 1] == '*':
            count += 1
            count_2 += 1
        if j > 0:     
            if fuhao[j-1] == '/':
                j +=1
            
        tem = number[j:count+2]
        tem.sort()
        for k in range(len(tem)):
            number[j+k] = tem[k]
        
        print(number)
    elif fuhao[j] == '/' :
        count = j
        count_2 = 1
        while count < n-2 and fuhao[count + 1] == '/':
            count += 1
            count_2 += 1
        if count_2 > 1:

            tem = number[j+1:count+2]
            tem.sort()
            for k in range(len(tem)):
                number[j+k+1] = tem[k]
                
        print(number)
    elif fuhao[j] == '+':
        count = j
        count_2 = 1
        while count < n-2 and fuhao[count + 1] == '+':
            count += 1
            count_2 += 1
        if j > 0:  
            if fuhao[j-1] == '*' or fuhao[j-1] == '/':
                j +=1  
        if count <n-2: 
            if fuhao[count+1] == '*' or fuhao[count+1] == '/':
                count -= 1

        tem = number[j:count+2]
        tem.sort()
        for k in range(len(tem)):
            number[j+k] = tem[k]  
        print(number)
    else:
        count = j
        count_2 = 1
        while count < n-2 and fuhao[count + 1] == '-':
            count += 1
            count_2 += 1
        if j > 0:    
            if fuhao[j-1] == '*' or fuhao[j-1] == '/':
                j +=1 
        if count <n-2:     
            if fuhao[count + 1] == '*' or fuhao[count + 1] == '/':
                count -= 1
        
        if count_2 > 1:

            tem = number[j+1:count+2]
            tem.sort()
            for k in range(len(tem)):
                number[j+k+1] = tem[k]
        print(number)    
for f in range(n-1):
    res.append(number[f])
    res.append(fuhao[f])           
res.append(number[-1])

for r in res:
    print(r, end=' ')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值