Skip to content

Instantly share code, notes, and snippets.

@xputerax
Last active November 12, 2021 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xputerax/fddcb7c353ae7aff1dad9b28f843f662 to your computer and use it in GitHub Desktop.
Save xputerax/fddcb7c353ae7aff1dad9b28f843f662 to your computer and use it in GitHub Desktop.
Linear Equations generator (with solution)
#!/usr/bin/python
# Generate 2 linear equations in 2 variables and their solutions
# restrictions: a,b,c,d = positive integeers [1,9]
# matrix:
#| a b || x | = | e |
#| c d || y | | f |
from fractions import Fraction
from random import randint
howmuch = 10
for i in range(1, howmuch + 1):
a = randint(1, 9)
b = randint(1, 9)
c = randint(1, 9)
d = randint(1, 9)
e = randint(-10, randint(0, i))
f = randint(-10, randint(0, i))
determinant = a*d - b*c
no_solution = (determinant == 0)
print('{}x+{}y={}'.format(a, b, e))
print('{}x+{}y={}'.format(c, d, f))
if no_solution:
print('(no solution)')
print()
continue
sol_x = divmod((e*d - b*f), determinant)
sol_y = divmod((a*f - e*c), determinant)
ans_x = Fraction((e*d - b*f), determinant)
ans_y = Fraction((a*f - e*c), determinant)
print('({}, {})'.format(str(ans_x), str(ans_y)))
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment