关于#python#的问题,如何解决?

python编写程序,完成以下任务:重定义”+“和”-“,对 ^ 排列的图形进行递加(减)操作,依次对上一行进行加减。
19. 例如,输入 ;1+2+3-4-5-6,输出图形为下图所示

img


说明:考察对列表的操作,正数排列在右,负数排列在左,(可以把区间定在【-80,80】)

input_str = input()
num_list = []
temp = ''
start = 0

if input_str[0] == '-':
    start = 1
    temp = '-'
for i in range(start, len(input_str)):
    if input_str[i].isdigit():
        temp += input_str[i]
    elif input_str[i] in ['+', '-']:
        num_list.append(int(temp))
        temp = input_str[i]
num_list.append(int(temp))

sum = 0
for i in num_list:
    sum += i
    if sum < 0:
        print(' '*(40 + sum)+'*'* (0-sum))
    elif sum > 0:
        print(' '*40+ '*' * sum)
    else:
        print('')

运行结果

                                        *
                                        ***
                                        ******
                                        **
                                     ***
                               *********

exp = input()
left = eval(exp)
q = list()
for i in exp:
    if i.isdigit():
        if len(q) > 1:
            op = q.pop()
            if op == "+":
                qty = q.pop()+int(i)
            elif op == "-":
                qty = q.pop()-int(i)
        else:
            qty = int(i)
        q.append(qty)
        space = abs(max(left, left-qty))
        print(" "*space+"^"*abs(qty))
    else:
        q.append(i)

该回答引用chatgpt:


def plot_expression(expr):
    x = []
    y = []
    current_x = 0
    current_y = 0
    for char in expr:
        if char == '+':
            current_x += 1
        elif char == '-':
            current_x -= 1
        elif char == '^':
            y.append(current_y)
            x.append(current_x)
            current_y += 1
        else:
            continue
    y.append(current_y)
    x.append(current_x)

    # plot the graph
    import matplotlib.pyplot as plt
    plt.scatter(x, y)
    plt.show()

expr = input("请输入加减表达式(只能包含+、-和^):")
plot_expression(expr)

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^