id/email
password
forgot password | create account
about | help | code help+videos | done | prefs
CodingBat code practice

 

peter@norvig.com pemdas > simp
prev  |  next  |  chance

simp(x) takes an algebraic expression, x, and returns an equivalent expression in simplified form. For example, simp([2, '+', 2]) should return 4. That is, simp can be used as a calculator. But it can be used with symbolic expressions as well -- for example, simp(['x', '-', 'x']) returns 0. The expression, x, can be anything allowed in the differentiation exercise, D, plus a few more extensions. First extension: allow unary operators/functions: -, sin, cos, tan, log. Represent them as lists of length two, so that "-y" is represented as ['-', 'y'] and "sin(x)" is represented as ['sin', 'x']. Second: allow exponentiation to non-integer powers: [2, '^', 'x']. Third: allow extra parentheses, implemented as lists. That is, the algebraic expression "((x+1))" is represented as [['x', '+', 1]]. Fourth: allow differentiation as an operator that is part of an expression. For example, represent "d(y^2)/dx" with the list [['y', '^', 2], 'd/d', 'x'] -- that is, we are introducing a new binary operator, 'd/d'. You will need to extend the function D to handle these new types of expressions. simp(x) should handle the cases of adding 0, multiplying by 1, adding two integers, etc., whether these are in the original formula x, or whether they come from the differentiation rules. For example, simp([['x', '+', ['x', '-', 'y']], 'd/d', 'x']) should return 2, not [1, '+', [1, '-', 0]]. (NOTE: this isn't an ideal problem for the CodingBat format, because sometimes there are multiple answers which are both equally simple, but different. If your program disagrees with the answers we have in the test cases, but your answer is mathematically correct, don't worry about it.) (ALSO NOTE: This exercise will be longer than most, perhaps 100 to 150 lines.)


...Save, Compile, Run (ctrl-enter)

def simp(x):

Editor font size %:
Shorter output


Forget It! -- delete my code for this problem

Progress graphs:
 Your progress graph for this problem
 Random user progress graph for this problem
 Random Epic Progress Graph

Python Help

Difficulty: 531 Post-solution available

Copyright Nick Parlante 2017 - privacy