fork(1) download
  1. # solve for a*b=c*d in python 2.7
  2. # should work for arbitrary number of variables on each side ie abc=def
  3.  
  4. # user inputs
  5. a = 1
  6. b = 2
  7. c = 7
  8. d = 'solve' # solve for this value
  9.  
  10. lhs = [a,b] # left hand side of eq
  11. rhs = [c,d] # right hand side of eq
  12.  
  13. if 'solve' in lhs:
  14. value = c*d # get right hand side
  15. divide = lhs
  16. elif 'solve' in rhs:
  17. value = a*b # get right hand side
  18. divide = rhs
  19. else:
  20. raise ValueError('cannot tell which variable to solve for')
  21.  
  22. for num in divide: # divide by terms on 'solve' side
  23. if num == 'solve':
  24. continue # don't divide by 'solve' ... that would be silly
  25. value = value/float(num)
  26.  
  27. easyCheck = a*b/float(c) # the easy way to do it (less dynamic though)
  28.  
  29. print 'solution is ',value
  30. print 'easy check value is',easyCheck
Success #stdin #stdout 0.01s 7736KB
stdin
Standard input is empty
stdout
solution is  0.285714285714
easy check value is 0.285714285714