[英]How do I make a string of numbers to have no spaces in between them if they are double digit?
如果這沒有意義,讓我舉個例子。
現在,我正在嘗試評估一個后綴表達式。 我已經做了所有需要的事情,但是有一個問題。
當我在表達式中有個位數時,一切正常。 這是因為在我的代碼中,我必須去掉所有的空格。
例如,后綴表達式2 1 + 3 *
的計算結果為9
。 但是當我有后綴表達式4 13 5 / +
時,評估的表達式不正確。
這是因為當我去掉那個表達式中的所有空格時,數字 13 變成了兩個數字。 (1 和 3)我不希望這種情況發生,但我不知道如何解決這個錯誤!
Input = 4 13 5 / +
Output = 2
output 應該是6
。
我正在使用.replace(" ", "")
方法。
我該如何解決? 這是我的代碼示例。
from __future__ import division
import random
formula = input()
formula = formula.replace(" ", "")
OPERATORS = set(['+', '-', '*', '/', '(', ')'])
PRIORITY = {'+':1, '-':1, '*':2, '/':2}
stack = []
prev_op = None
for ch in formula:
if not ch in OPERATORS:
stack.append(ch)
else:
b = stack.pop()
a = stack.pop()
if ch == "+":
output = int(b)+int(a)
if ch == "-":
output = int(b)-int(a)
if ch == "*":
output = int(b)*int(a)
if ch == "/":
output = int(b)/int(a)
stack.append(output)
print(output)
您的代碼存在一些問題。
formula.split()
我在下面標記了更改。 試試看。
from __future__ import division
import random
formula = input().split() #<------
OPERATORS = set(['+', '-', '*', '/', '(', ')'])
PRIORITY = {'+':1, '-':1, '*':2, '/':2}
stack = []
prev_op = None
for ch in formula:
if not ch in OPERATORS:
stack.append(ch)
else:
a = stack.pop() #<---------
b = stack.pop() #<---------
if ch == "+":
output = int(b)+int(a)
if ch == "-":
output = int(b)-int(a)
if ch == "*":
output = int(b)*int(a)
if ch == "/":
output = int(b)/int(a)
stack.append(output)
print(output)
4 13 5 / +
6
您應該保留空格,而不是刪除空格:這將使使用split
從輸入中提取單詞變得容易:
for ch in formula.split():
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.