Archive
How to solve a two-variable equation with Sympy
Problem
You have a two-variable equation and you want to solve it with Python / Sympy.
Solution
Let’s see this example:
7x + 9y = 8
9x - 8y = 69
What is the value of ‘x’ and ‘y’?
We could solve it manually too, of course, but let’s say we have hundreds of these. So let’s solve it with Python using the Sympy library.
>>> import sympy as sp
>>>
>>> x = sp.symbols('x')
>>> y = sp.symbols('y')
>>>
>>> eq1 = sp.Eq(7 * x + 9 * y, 8)
>>> eq2 = sp.Eq(9 * x - 8 * y, 69)
>>>
>>> system = [eq1, eq2]
>>>
>>> sol_set = sp.linsolve(system, x, y)
>>> sol_set
{(5, -3)}
>>>
>>> 7 * 5 + 9 * (-3)
8
>>> 9 * 5 - 8 * (-3)
69
Sum the digits of a number until you get just one digit
Problem
Take a positive integer and sum its digits. Repeat this process until you get just one digit.
Example: 1472 🠖 1+4+7+2 = 14 🠖 1+4 = 5. The answer is 5.
Solution
# Python code
n = 1472
result = ((n-1) % 9) + 1
Credits
Thanks to my friend Mocsa who told me this math trick.
angle between two lines
Problem
You have two lines. What is the angle between them?
Or, you have 3 points, say A, B and C. If you go from A to B (vector 1), then from B to C (vector 2), then what is the angle at point B between the two vectors?
Solution
There is a nice blog post about it here: Find the Angle between three points from 2D using python.
Here is a Python code that is based on the one that you can find in the aforementioned blog post:
import math
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
def angle(a: Point, b: Point, c: Point) -> float:
ang = math.degrees(math.atan2(c[1]-b[1], c[0]-b[0]) - math.atan2(a[1]-b[1], a[0]-b[0]))
return ang + 360 if ang < 0 else ang
