簡體   English   中英

有沒有辦法打印在 Python 中生成 integer 的數學?

[英]Is there a way to print the math that makes an integer in Python?

假設我有這個代碼:

int1 = (2 + 2) * 4
print(int1)

OUTPUT: 16

但是有沒有辦法在不使用字符串的情況下打印 int 的數學? literal() function 什么的?

示例程序:

int1 = 2 + 2
int2 = 4

print('{} times {} equals:'.format(literal(int1), literal(int2))
print(int1 * int2)

OUTPUT:
2 + 2 times 4 equals:
16

我覺得我正在尋找一個不存在的問題的解決方案,但我是 Python 的新手,我很好奇。

本機 python “忘記”您所做的操作,只記住您擁有的變量的值。 因此,當您執行x = int1 * int2時, python 會將相應的值分配給x ,但不會存儲任何有關產生該值的操作的信息。

然而,這可能是一個(不那么容易的)編碼練習:設計你自己的 integer class 來存儲計算歷史。

class Math():

    def __init__ (self):
        self.val = 0
        self.opList = []
    def add(self,val):
        self.val += val
        self.opList.append(" + "+str(val))
    def sub(self,val):
        self.val -= val
        self.opList.append(" - "+str(val))
    def printOps(self):
        print(self.val," = 0",end="")
        for i in self.opList:print(i,end="")

t = Math()

t.add(10)

t.sub(5)

t.printOps()

python 確實有運算符重載,但寫起來很痛苦

更合理的方法是使用字符串,然后評估它們。 除非您從不受信任的輸入中獲取字符串,否則使用eval不會不安全,如果它們來自源代碼就可以了。

-- juanpa.arrivillaga評論

int1 = '2 + 2'
int2 = '4'

print('{} times {} equals:'.format(int1, int2))
print(eval(int1) * eval(int2))

Output:

2 + 2 times 4 equals:
16

您可以做類似的事情,除了將文字公司存儲在字符串中,並使用simpleeval模塊中的simple_eval方法:

from simpleeval import simple_eval

int1 = '2 + 2'
int2 = 4

print('{} times {} equals:'.format(int1, int2))
print(simple_eval(int1) * int2)

Output:

2 + 2 times 4 equals:
16

simpleeval是一個安全評估數學表達式的模塊,與臭名昭著的eval方法相反,它允許對您的操作系統進行惡意攻擊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM