early calculation
This commit is contained in:
parent
a3078cf1c1
commit
37e29f17f0
1 changed files with 75 additions and 7 deletions
|
@ -180,5 +180,73 @@ pub fn form_reverse_polish_notation(regular_math: &str) -> Result<Vec<String>, S
|
||||||
|
|
||||||
// after we have the rpn, we may want to calculate the values with it.
|
// after we have the rpn, we may want to calculate the values with it.
|
||||||
pub fn calc_reverse_polish_notation(rpn: Vec<String>) -> Result<f64, String> {
|
pub fn calc_reverse_polish_notation(rpn: Vec<String>) -> Result<f64, String> {
|
||||||
Ok(0.0)
|
|
||||||
|
// # function to evaluate reverse polish notation
|
||||||
|
// def evaluate(expression):
|
||||||
|
// # splitting expression at whitespaces
|
||||||
|
// expression = expression.split()
|
||||||
|
// # stack
|
||||||
|
// stack = []
|
||||||
|
// # iterating expression
|
||||||
|
// for ele in expression:
|
||||||
|
// # ele is a number
|
||||||
|
// if ele not in '/*+-':
|
||||||
|
// stack.append(int(ele))
|
||||||
|
// # ele is an operator
|
||||||
|
// else:
|
||||||
|
// # getting operands
|
||||||
|
// right = stack.pop()
|
||||||
|
// left = stack.pop()
|
||||||
|
// # performing operation according to operator
|
||||||
|
// if ele == '+':
|
||||||
|
// stack.append(left + right)
|
||||||
|
// elif ele == '-':
|
||||||
|
// stack.append(left - right)
|
||||||
|
// elif ele == '*':
|
||||||
|
// stack.append(left * right)
|
||||||
|
// elif ele == '/':
|
||||||
|
// stack.append(int(left / right))
|
||||||
|
// # return final answer.
|
||||||
|
// return stack.pop()
|
||||||
|
let mut stack: Vec<f64> = Vec::new();
|
||||||
|
|
||||||
|
for group in rpn {
|
||||||
|
dbg!(&group);
|
||||||
|
// find out what the group is, an operator, a number, or a variable.
|
||||||
|
// TODO add variables
|
||||||
|
if (!Operator::is_operator(group.chars().last().unwrap())) {
|
||||||
|
let possible_num = group.parse::<f64>();
|
||||||
|
match possible_num {
|
||||||
|
Ok(valid) => {stack.push(valid);},
|
||||||
|
Err(_whatever) => {
|
||||||
|
eprint!("weird error happened, ending process...");
|
||||||
|
std::process::exit(2);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
dbg!(&stack);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
let op: Operator = Operator::get_operator(group.chars().last().unwrap()).unwrap();
|
||||||
|
let right = stack.pop().unwrap();
|
||||||
|
let left = stack.pop().unwrap();
|
||||||
|
if op == ADDITION {
|
||||||
|
stack.push(right + left);
|
||||||
|
}
|
||||||
|
|
||||||
|
else {
|
||||||
|
todo!();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if stack.is_empty() {
|
||||||
|
return Err("result stack empty".to_string());
|
||||||
|
}
|
||||||
|
if stack.len() > 1 {
|
||||||
|
dbg!(stack);
|
||||||
|
return Err("result stack has too many results.".to_string());
|
||||||
|
}
|
||||||
|
return Ok(stack[0]);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Reference in a new issue