Error preparing CommonHTML output (postProcess)
Solutions of Expression - MarisaOJ: Marisa Online Judge

Solutions of Expression

Select solution language

Write solution here.


User Avatar phphongyd    Created at    34 likes

Hiểu về bài toán

Bài toán yêu cầu chúng ta:

Nhập: Một biểu thức toán học chỉ bao gồm các phép tính cộng, trừ, nhân.

Xử lý: Đánh giá biểu thức và thực hiện các phép tính.

Xuất: Kết quả của phép tính.

Giải pháp sử dụng hàm eval()

Hàm eval() trong Python là một hàm vô cùng tiện lợi, cho phép chúng ta đánh giá một biểu thức được biểu diễn dưới dạng một chuỗi.

Đây là một công cụ mạnh mẽ để giải quyết bài toán trên.

Code s=put()pr(eval(s))s=put()pr(eval(s))


User Avatar Kaizen    Created at    4 likes

1.Khởi tạo: Một biến num để thành lập số trong xâu Một biến op (toán tử) ban đầu là ‘+’ để xử lý số đầu tiên. Một stack để lưu trữ các giá trị tạm thời.

2.Duyệt xâu: Khi gặp một ký tự không phải số (hoặc đã đến cuối xâu), xử lý số và toán tử trước đó: Nếu op là ‘+’, đẩy num vào stack. Nếu op là ‘-‘, đẩy -num vào stack. Nếu op là ‘*’ hoặc ‘/‘, lấy phần tử trên cùng của stack, thực hiện phép nhân hoặc chia với num, rồi đẩy kết quả trở lại vào stack. Cập nhật op thành ký tự hiện tại và đặt lại num về 0.

3.Tính kết quả: Sau khi duyệt hết xâu, tổng tất cả các giá trị trong stack sẽ cho ra kết quả cuối cùng của biểu thức. Vì kết quả có thể rất lớn nên cần sử dụng long long

Sử dụng stack để tận dụng việc ưu tiên toán tử ‘*’,’/‘ là một giải pháp hợp lí trong bài toán này

Lưu ý: Hãy tự code trước khi xem code mẫu để tham khảo :

Code: #clude<iostream>#clude<stack>#clude<strg>#defelonglongusingnamespacestd;calca̲te(strgs){stack<>st;νm=0;charop=+;for(i=0;i<s.size();i++){charc=s[i];if(isdigit(c)){νm=νm10+(c-0);}if((!isdigit(c)&&c)i==s.size()-1){if(op==+){st.push(νm);}elseif(op==-){st.push(-νm);}elseif(op==){=st.();st.pop();st.push(νm);}elseif(op==){=st.();st.pop();st.push(νm);}op=c;νm=0;}}rest̲=0;whi(!st.empty()){rest̲+=st.();st.pop();}returnrest̲;}sigdma(){strgs;tle(c,s);coutcalca̲te(s);return0;}


User Avatar JoonYorigami    Created at    1 likes

This is extremely trivial with python using the eval or exec function
Their differences don’t really matter to us as they both do what we want, which is evaluating expressions

Both exec and eval will perform the string inputted as long as it is a legal python expression, since our input will always be a legal python expression (contains only numbers, and the operations +, -, *, /), we can use both of these

An example usage of eval is: pythoneval(print(‘owo’)) In this case, eval() will evaluate the string as normal code, so it does pr(owo) which prints owo to stdout

We can then apply this to our problem pythons=put()ans=eval(s)#evaluatestrgpr(ans) eval will parse whatever arithmetic expression is passed, which returns the result, we can then just simply print the result

Bonus: Golfed pythonpr(eval(put()))