close
Content
有三個函數:
f(x) = 2x – 3
g(x, y) = 2x +y – 7
h(x, y, z) = 3x – 2y + z
另有一個由這三個函數所組成的運算式,依序給你其中的函數名稱及參數,請求出這個運算式的值。例如:
h f 5 g 3 4 3
代表
h(f(5), g(3, 4), 3)
=h(7, 3, 3)
=18
python:
from sys import stdin def f(x): return eval(f'2*{x}-3') def g(x,y): return eval(f'2*{x}+{y}-7') def h(x,y,z): return eval(f'3*{x}-2*{y}+{z}') s=stdin.readline().strip().split() p=[i for i ,c in enumerate(s) if c in "fgh"] a=[] while len(s)!=0: a1=s[-1] a.append(s.pop()) if a1=='f': f1=a.pop() f2=a.pop() a.append(f(f2)) if a1=='g': g1=a.pop() g2=a.pop() g3=a.pop() a.append(g(g2,g3)) if a1=='h': h1=a.pop() h2=a.pop() h3=a.pop() h4=a.pop() a.append(h(h2,h3,h4)) print(*a)
C++
#include <iostream> #include <string> using namespace std; int eval() { string s; cin>>s; if(s[0]=='f'){ int x=eval(); return 2*x-3; } else if(s[0]=='g'){ int x=eval(); int y=eval(); return 2 * x + y - 7; } else if (s[0]=='h') { int x=eval(); int y=eval(); int z=eval(); return 3 * x - 2 * y + z; } else{ return stoi(s); //str to int } return 0; } int main(){ cout<<eval()<<'\n'; }
C++
#include <iostream> #include <string> #include <stack> using namespace std; int main(){ string s; stack<string> stk1; stack<int> stk2; while (cin>>s) { stk1.push(s); } while (!stk1.empty()) { s = stk1.top(); stk1.pop(); if(s=="f"){ //都要用雙引號,因為推出來給s的是string int x = stk2.top(); stk2.pop(); stk2.push(2*x-3); } else if(s=="g") { int x = stk2.top(); stk2.pop(); int y = stk2.top(); stk2.pop(); stk2.push(2*x+y-7); } else if (s=="h") { int x = stk2.top(); stk2.pop(); int y = stk2.top(); stk2.pop(); int z = stk2.top(); stk2.pop(); stk2.push(3*x-2*y+z); } else { stk2.push(stoi(s)); } } cout<<stk2.top()<<'\n'; return 0; }
文章標籤
全站熱搜
留言列表