A comprehensive Python package for discrete mathematics automation
Project description
๐งฎ Discrete Math Toolkit
Your Python companion for discrete mathematics!
Whether you're a student tackling homework, an educator creating examples, or a researcher exploring mathematical concepts, this toolkit automates the tedious calculations so you can focus on understanding the concepts.
๐ฏ What Can You Do With This?
For Students ๐
- โ Verify your homework answers instantly
- โ Generate truth tables for logic assignments
- โ Calculate permutations and combinations without manual work
- โ Visualize graph algorithms step-by-step
- โ Check if your relations are reflexive, symmetric, or transitive
For Educators ๐จโ๐ซ
- โ Generate examples and test cases quickly
- โ Create consistent problem sets
- โ Demonstrate algorithms programmatically
- โ Build interactive demonstrations
For Developers ๐
- โ Integrate discrete math operations into your applications
- โ Build educational tools and games
- โ Prototype algorithms before optimization
- โ Add mathematical validation to your systems
๐ฆ Installation
Super simple! Just one command:
pip install discrete-math-toolkit
That's it! No complicated setup, no additional dependencies to worry about.
๐ Quick Start - Get Results in 30 Seconds
from discrete_math import logic, sets, combinatorics
# Example 1: Check if a logical statement is always true
print(logic.is_tautology("p OR (NOT p)")) # True - this is always true!
# Example 2: Find what elements two sets share
students_in_math = {1, 2, 3, 4, 5}
students_in_cs = {3, 4, 5, 6, 7}
print(sets.intersection(students_in_math, students_in_cs)) # {3, 4, 5}
# Example 3: How many ways can you choose 3 people from 10?
print(combinatorics.combinations(10, 3)) # 120 different ways!
๐ Complete Feature Guide
1๏ธโฃ Logic Module โ Work with Logical Statements
What it does:
Analyze propositional logic expressions, generate truth tables, evaluate expressions, check logical properties, convert to normal forms, and extract minterms/maxterms.
This module is ideal for Discrete Mathematics, Logic Design, and Computer Organization students.
๐น Supported Logical Operators
| Operator | Syntax |
|---|---|
| AND | AND, &, โง |
| OR | OR, ` |
| NOT | NOT, ~, ยฌ |
| IMPLIES | IMPLIES, -> |
| IFF (โ) | IFF, <-> |
| XOR | XOR, ^ |
๐ Example Usage
from discrete_math.logic import *
โ 1. Generate Truth Tables
table = generate_truth_table("p AND q")
print(table)
Output:
[
{'p': False, 'q': False, 'result': False},
{'p': False, 'q': True, 'result': False},
{'p': True, 'q': False, 'result': False},
{'p': True, 'q': True, 'result': True}
]
๐ Useful for understanding all possible outcomes of a logical expression.
โ 2. Check Logical Properties
๐น Tautology (Always True)
print(is_tautology("p OR (NOT p)"))
โ๏ธ Output:
True
๐น Contradiction (Always False)
print(is_contradiction("p AND (NOT p)"))
โ๏ธ Output:
True
๐น Contingency (Sometimes True, Sometimes False)
print(is_contingency("p AND q"))
โ๏ธ Output:
True
โ 3. Evaluate an Expression with Given Values
result = evaluate("p AND q", {"p": True, "q": False})
print(result)
โ๏ธ Output:
False
๐ Helpful in exams and quick verification.
โ 4. Convert to Normal Forms
๐น Conjunctive Normal Form (CNF)
cnf = convert_to_cnf("(p OR q) IMPLIES r")
print(cnf)
โ๏ธ Output:
(~p | r) & (~q | r)
๐น Disjunctive Normal Form (DNF)
dnf = convert_to_dnf("(p AND q) OR (p AND r)")
print(dnf)
โ๏ธ Output:
p & (q | r)
โ 5. Simplify Logical Expressions
simple = simplify("(p AND p) OR (q AND True)")
print(simple)
โ๏ธ Output:
p | q
๐ Applies logical identities automatically.
โ 6. Check Logical Equivalence
expr1 = "p IMPLIES q"
expr2 = "(NOT p) OR q"
print(are_equivalent(expr1, expr2))
โ๏ธ Output:
True
๐ Confirms whether two expressions mean the same thing.
โ 7. Find Minterms
print(get_minterms("p OR q"))
โ๏ธ Output:
[1, 2, 3]
๐ Indexes represent rows where the expression is TRUE.
โ 8. Find Maxterms
print(get_maxterms("p OR q"))
โ๏ธ Output:
[0]
๐ Indexes represent rows where the expression is FALSE.
๐ Student Tip
- Use truth tables to verify exam answers
- Use CNF/DNF for SAT solvers and logic circuits
- Use minterms/maxterms in Boolean algebra & K-maps
2๏ธโฃ Sets Module โ Master Set Operations
What it does:
Perform all fundamental and advanced set theory operations such as union, intersection, difference, power sets, Cartesian products, partitions, and set relationships.
This module is ideal for Discrete Mathematics, Computer Science, and Logic Foundations.
๐ Example Usage
from discrete_math.sets import *
โ 1. Basic Set Operations
๐น Union
result = union({1, 2}, {2, 3}, {3, 4})
print(result)
Output:
{1, 2, 3, 4}
๐น Intersection
result = intersection({1, 2, 3}, {2, 3, 4})
print(result)
Output:
{2, 3}
๐น Difference (A โ B)
result = difference({1, 2, 3}, {2, 3, 4})
print(result)
Output:
{1}
๐น Symmetric Difference (A โณ B)
result = symmetric_difference({1, 2, 3}, {2, 3, 4})
print(result)
Output:
{1, 4}
๐น Complement
universal = {1, 2, 3, 4, 5}
subset = {1, 2}
print(complement(subset, universal))
Output:
{3, 4, 5}
โ 2. Power Sets
๐น Generate Power Set
ps = power_set({1, 2})
print(ps)
Output:
{frozenset(), frozenset({1}), frozenset({2}), frozenset({1, 2})}
๐ Each subset is returned as a frozenset.
๐น Power Set Cardinality (Without Generating)
print(power_set_cardinality({1, 2, 3}))
Output:
8
๐ Uses the formula: 2โฟ
โ 3. Cartesian Products
๐น Cartesian Product of Two Sets
pairs = cartesian_product({1, 2}, {'a', 'b'})
print(pairs)
Output:
{(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')}
๐น Cartesian Product of N Sets
result = cartesian_product_n({1, 2}, {'a', 'b'}, {True, False})
print(result)
๐ Returns all possible n-tuples.
โ 4. Set Relationships
๐น Subset (โ)
print(is_subset({1, 2}, {1, 2, 3}))
Output:
True
๐น Proper Subset (โ)
print(is_proper_subset({1, 2}, {1, 2, 3}))
Output:
True
๐น Superset (โ)
print(is_superset({1, 2, 3}, {1, 2}))
Output:
True
๐น Disjoint Sets
print(is_disjoint({1, 2}, {3, 4}))
Output:
True
๐น Set Equality
print(are_equal({1, 2, 3}, {3, 2, 1}))
Output:
True
โ 5. Cardinality
print(cardinality({10, 20, 30, 40}))
Output:
4
๐ Returns the number of elements in a set.
โ 6. Partition of a Set
result = partition({1, 2, 3, 4}, {1, 2}, {3}, {4})
print(result)
Output:
True
๐ Checks whether subsets form a valid partition.
โ 7. Set-Builder Notation
evens = set_builder(lambda x: x % 2 == 0, {1, 2, 3, 4, 5, 6})
print(evens)
Output:
{2, 4, 6}
๐ Mimics mathematical set-builder notation.
Got it ๐
Iโll fix and extend your README section so that it covers all public functions exposed by your Combinatorics Module, based strictly on the __all__ list in your code.
Below is a drop-in replacement for your current README section, written in the same style, with clear examples for every function.
3๏ธโฃ Combinatorics Module โ Count Like a Pro
What it does: Perform combinatorial calculations such as permutations, combinations, binomial coefficients, and advanced counting sequences used in probability, algorithms, and discrete mathematics.
๐ Real-World Use Case: Counting, Probability & Algorithms
from discrete_math.combinatorics import *
๐ข Basic Building Block
Factorial
# 5! = 5 ร 4 ร 3 ร 2 ร 1
print(factorial(5)) # 120
๐ Permutations & Combinations
Permutations (order matters)
# Arrange 3 items from 5
print(permutations(5, 3)) # 60
Combinations (order does NOT matter)
# Choose 3 students from 10
print(combinations(10, 3)) # 120
๐ With Repetition Allowed
Permutations with repetition
# 3-character password from 4 symbols (repetition allowed)
print(permutations_with_repetition(4, 3)) # 64
Combinations with repetition
# Choose 3 candies from 5 types
print(combinations_with_repetition(5, 3)) # 35
๐ Binomial & Multinomial Coefficients
Binomial Coefficient
# C(5,2)
print(binomial_coefficient(5, 2)) # 10
Multinomial Coefficient
# Distribute items into groups of sizes 2,1,1
print(multinomial_coefficient([2, 1, 1])) # 12
๐ Pascalโs Triangle
triangle = pascals_triangle(5)
for row in triangle:
print(row)
# [1]
# [1, 1]
# [1, 2, 1]
# [1, 3, 3, 1]
# [1, 4, 6, 4, 1]
๐ฑ Famous Sequences
Fibonacci Numbers
print(fibonacci(10)) # 55
Catalan Numbers
# Used in counting trees, valid parentheses, etc.
print(catalan_number(5)) # 42
๐ Special Counting Problems
Derangements (no element in original position)
# Secret Santa problem
print(derangements(4)) # 9
Stirling Numbers (Second Kind)
# Partition 5 elements into 2 non-empty sets
print(stirling_second_kind(5, 2)) # 15
Bell Numbers
# Number of ways to partition a set of size 4
print(bell_number(4)) # 15
๐ Generators (Actual Arrangements)
Generate permutations
for p in generate_permutations([1, 2, 3], 2):
print(p)
# (1, 2)
# (1, 3)
# (2, 1)
# ...
Generate combinations
for c in generate_combinations([1, 2, 3, 4], 2):
print(c)
Generate combinations with repetition
for c in generate_combinations_with_repetition([1, 2, 3], 2):
print(c)
๐ก Student Tip
- Permutations โ order matters (rankings, passwords)
- Combinations โ order doesnโt matter (teams, selections)
- Catalan & Stirling numbers often appear in DSA, trees, and recursion problems
5๏ธโฃ Number Theory Module - Explore Number Properties
Perfect โ Iโll repeat the same process as before ๐
Below is a clean, complete, drop-in README.md section for your Number Theory Module, covering every function listed in __all__, written in the same tone, structure, and teaching style you used.
You can copy-paste this directly into README.md.
5๏ธโฃ Number Theory Module โ Explore Number Properties
What it does: Work with prime numbers, divisibility, GCD/LCM, modular arithmetic, and classic number-theoretic functions used in cryptography, algorithms, and discrete mathematics.
๐ Real-World Use Case: Cryptography, Scheduling & Mathematics
from discrete_math.number_theory import *
๐ข Fundamental Operations
Greatest Common Divisor (GCD)
# Simplifying fractions, checking coprimality
print(gcd(48, 18)) # 6
print(gcd(17, 19)) # 1
Least Common Multiple (LCM)
# Scheduling and periodic events
print(lcm(12, 18)) # 36
print(lcm(7, 5)) # 35
๐ Extended Euclidean Algorithm
# Finds gcd(a, b) and x, y such that ax + by = gcd(a, b)
g, x, y = extended_gcd(30, 20)
print(g, x, y) # 10, 1, -1
๐ Used in: Modular inverse, cryptography, Diophantine equations
๐ Prime Number Utilities
Prime Test
print(is_prime(17)) # True
print(is_prime(100)) # False
Prime Factorization
factors = prime_factorization(60)
print(factors) # {2: 2, 3: 1, 5: 1}
# 60 = 2ยฒ ร 3ยน ร 5ยน
Generate Primes (Sieve of Eratosthenes)
print(sieve_of_eratosthenes(30))
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
๐ Modular Arithmetic (Cryptography Core)
Modular Inverse
# Find x such that (a * x) % m == 1
inverse = mod_inverse(3, 11)
print(inverse) # 4
โ ๏ธ Raises error if inverse does not exist.
Fast Modular Exponentiation
print(mod_exp(2, 100, 17)) # Efficient for huge powers
print(mod_exp(3, 10, 7)) # 4
๐ Used in: RSA, Diffie-Hellman, hashing
๐ข Eulerโs Totient Function
# Counts integers โค n that are coprime with n
print(euler_totient(9)) # 6
print(euler_totient(10)) # 4
๐ Key idea in RSA encryption
๐งฎ Chinese Remainder Theorem (CRT)
# Solve:
# x โก 2 (mod 3)
# x โก 3 (mod 5)
# x โก 2 (mod 7)
solution = chinese_remainder_theorem([2, 3, 2], [3, 5, 7])
print(solution) # 23
๐ Used in: Distributed systems, cryptography, time synchronization
๐ Coprimality
print(is_coprime(15, 28)) # True
print(is_coprime(15, 25)) # False
๐ Divisor Functions
All Divisors
print(divisors(24))
# [1, 2, 3, 4, 6, 8, 12, 24]
Sum of Divisors
print(sum_of_divisors(12)) # 28
โญ Perfect Numbers
print(is_perfect_number(6)) # True
print(is_perfect_number(28)) # True
print(is_perfect_number(12)) # False
๐ A perfect number equals the sum of its proper divisors.
Got it ๐
Below is the complete, polished README.md section for the Relations Module, written in the same style, structure, tone, and teaching depth as your previous modules.
It covers all functions listed in __all__ and aligns perfectly with the code you shared.
You can copy-paste this directly into README.md.
6๏ธโฃ Relations Module โ Analyze Relationships
What it does: Work with binary relations, check their properties, compute closures, and analyze structured relationships mathematically.
๐ Real-World Use Case: Databases, Hierarchies & Graphs
from discrete_math.relations import *
๐ Defining a Relation
# Relation R on set {1, 2, 3, 4}
# (a, b) means "a is related to b"
R = {(1, 1), (1, 2), (2, 2), (3, 3), (4, 4), (2, 3)}
domain = {1, 2, 3, 4}
โ Relation Properties
Reflexive
print(is_reflexive(R, domain)) # True
๐ Every element relates to itself Example: โEvery person knows themselvesโ
Symmetric
print(is_symmetric(R)) # False
๐ If a โ b, then b โ a
Example: Friendship (symmetric), Twitter follow (not symmetric)
Antisymmetric
print(is_antisymmetric(R)) # True or False depending on R
๐ If a โ b and b โ a, then a = b
Used in: Partial orders (โค)
Transitive
print(is_transitive(R)) # False
๐ If a โ b and b โ c, then a โ c
Example: Ancestor relationships
๐ฐ Special Relations
Equivalence Relation
print(is_equivalence_relation(R, domain))
โ Reflexive โ Symmetric โ Transitive
๐ Partitions a set into equivalence classes
Partial Order
partial_order = {(1,1), (2,2), (3,3), (1,2), (2,3), (1,3)}
print(is_partial_order(partial_order, {1, 2, 3})) # True
๐ Used in: Task scheduling, version control systems
๐ Relation Closures
Reflexive Closure
ref_closure = reflexive_closure(R, domain)
print(ref_closure)
Adds (a, a) for all a โ domain
Symmetric Closure
sym_closure = symmetric_closure(R)
print(sym_closure)
Makes every relation bidirectional
Transitive Closure
trans_closure = transitive_closure(R)
print(trans_closure)
Adds all implied indirect relationships
๐ Uses Warshallโs Algorithm
๐งฉ Equivalence Classes
R_eq = {(1,1), (2,2), (3,3), (1,2), (2,1)}
classes = equivalence_classes(R_eq, {1, 2, 3})
print(classes) # [{1, 2}, {3}]
๐ Only valid for equivalence relations
๐ Relation Operations
Composition of Relations
R1 = {(1, 2), (2, 3)}
R2 = {(0, 1), (1, 2)}
print(compose(R1, R2)) # {(0, 2), (1, 3)}
๐ Used in function chaining and graph traversal
Inverse Relation
print(inverse_relation({(1, 2), (2, 3)}))
# {(2, 1), (3, 2)}
๐ Swaps direction of every pair
๐ฆ Domain & Range
print(get_domain(R)) # {1, 2, 3, 4}
print(get_range(R)) # {1, 2, 3, 4}
๐ Helps analyze inputs and outputs of relations
๐งฎ Matrix Representation
matrix = relation_matrix({(1, 2), (2, 3)}, {1, 2, 3})
for row in matrix:
print(row)
Output:
[0, 1, 0]
[0, 0, 1]
[0, 0, 0]
๐ Used in: Graph theory, adjacency matrices, algorithms
Perfect โ repeating the exact same style, depth, and structure as your previous modules.
Below is a clean, complete, production-ready README.md section for the Functions Module, fully aligned with your code and __all__.
You can copy-paste this directly.
7๏ธโฃ Functions Module โ Analyze Mappings
What it does: Analyze mathematical functions, verify their properties (injective, surjective, bijective), perform composition, inversion, and convert between representations.
๐ Real-World Use Case: Data Mapping & Transformations
from discrete_math.functions import *
๐ Defining a Function
Functions are represented as sets of ordered pairs or Python dictionaries.
# Function as a dictionary
grades = {
101: 'A',
102: 'B',
103: 'A',
104: 'C',
105: 'B'
}
domain = {101, 102, 103, 104, 105}
codomain = {'A', 'B', 'C', 'D', 'F'}
# Convert dictionary to function form
relation = dict_to_function(grades)
โ Valid Function Check
print(is_function(relation, domain)) # True
๐ Each domain element must map to exactly one output.
๐ Function Properties
Injective (One-to-One)
print(is_injective(relation)) # False
๐ No two inputs share the same output
โ Here, multiple students received 'A'
Surjective (Onto)
print(is_surjective(relation, codomain)) # False
๐ Every element of codomain must be used
โ Grades 'D' and 'F' are unused
Bijective (One-to-One & Onto)
print(is_bijective(relation, domain, codomain)) # False
๐ Only bijective functions are invertible
๐ Function Composition
# f(x) = x + 1
f = {(1, 2), (2, 3), (3, 4)}
# g(x) = 2x
g = {(2, 4), (3, 6), (4, 8)}
# Composition: g โ f
composition = compose_functions(g, f)
print(composition) # {(1, 4), (2, 6), (3, 8)}
๐ Apply f first, then g
๐ Inverse Function
bijection = {(1, 'a'), (2, 'b'), (3, 'c')}
inverse = inverse_function(bijection, {1, 2, 3}, {'a', 'b', 'c'})
print(inverse) # {('a', 1), ('b', 2), ('c', 3)}
โ ๏ธ Only works for bijective functions
๐ง Real-Life Mapping Example
age_mapping = {
'Alice': 25,
'Bob': 30,
'Charlie': 25,
'David': 35
}
relation = dict_to_function(age_mapping)
print(is_injective(relation)) # False
๐ Two people share the same age โ not injective
๐ฆ Domain & Range
print(get_domain(relation))
# {'Alice', 'Bob', 'Charlie', 'David'}
print(get_range(relation))
# {25, 30, 35}
๐ Helps analyze inputs vs outputs
๐ Representation Conversion
Function โ Dictionary
print(function_to_dict({(1, 'a'), (2, 'b')}))
# {1: 'a', 2: 'b'}
Dictionary โ Function
print(dict_to_function({1: 'x', 2: 'y'}))
# {(1, 'x'), (2, 'y')}
โ๏ธ Function Evaluation (Callable)
square = lambda x: x * x
print(evaluate_function(square, 5)) # 25
๐ Works with any Python callable
๐ ๏ธ Development & Contributing
Want to Contribute? We'd Love Your Help!
This is an open-source project, and contributions are always welcome! Whether you're fixing bugs, adding features, or improving documentation - every contribution matters.
Setup Your Development Environment
# Step 1: Fork and clone the repository
git clone https://github.com/CodewithTanzeel/pypi-package-dm.git
cd pypi-package-dm
# Step 2: Create a virtual environment
python -m venv venv
# Step 3: Activate it
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
# Step 4: Install in development mode with all dev tools
pip install -e ".[dev]"
Running Tests
Make sure everything works before submitting changes:
# Run all tests
pytest
# Run tests with coverage report (see which code is tested)
pytest --cov=discrete_math --cov-report=html
# Run a specific test file
pytest tests/test_logic.py
# Run tests in verbose mode (see each test individually)
pytest -v
Code Quality Tools
Keep the codebase clean and consistent:
# Auto-format your code (makes it pretty!)
black src/
# Check for code style issues
flake8 src/
# Type checking (catch bugs early)
mypy src/
How to Contribute
- Fork the repository on GitHub
- Create a branch for your feature:
git checkout -b feature/AmazingFeature - Make your changes and add tests
- Run tests to ensure nothing breaks:
pytest - Commit your changes:
git commit -m 'Add some AmazingFeature' - Push to your branch:
git push origin feature/AmazingFeature - Open a Pull Request on GitHub
For major changes, please open an issue first to discuss what you'd like to change!
๐ Common Use Cases & Recipes
Recipe 1: Homework Helper - Verify Set Theory Answers
from discrete_math import sets
# Your homework problem:
# Given A = {1,2,3,4,5} and B = {4,5,6,7}
# Find: A โช B, A โฉ B, A - B, |P(A)|
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7}
print(f"A โช B = {sets.union(A, B)}") # {1,2,3,4,5,6,7}
print(f"A โฉ B = {sets.intersection(A, B)}") # {4,5}
print(f"A - B = {sets.difference(A, B)}") # {1,2,3}
print(f"|P(A)| = {len(sets.power_set(A))}") # 32 subsets
Recipe 2: Password Strength Analyzer
from discrete_math import combinatorics
def analyze_password_strength(length, use_lowercase=True, use_uppercase=True,
use_digits=True, use_special=True):
"""Calculate how many possible passwords exist."""
charset_size = 0
if use_lowercase: charset_size += 26 # a-z
if use_uppercase: charset_size += 26 # A-Z
if use_digits: charset_size += 10 # 0-9
if use_special: charset_size += 32 # !@#$%^&*...
total_combinations = charset_size ** length
print(f"Password length: {length}")
print(f"Character set size: {charset_size}")
print(f"Total possible passwords: {total_combinations:,}")
print(f"Entropy: {length * charset_size} bits")
return total_combinations
# 8-character password with all character types
analyze_password_strength(8, True, True, True, True)
# Result: Over 6 quadrillion combinations!
Recipe 3: Social Network Analysis
from discrete_math.graphs import Graph
def analyze_social_network(friendships):
"""Analyze a social network graph."""
network = Graph()
# Build the network
for person1, person2 in friendships:
network.add_edge(person1, person2)
# Analysis
print(f"Total people: {len(network.vertices)}")
print(f"Total friendships: {len(network.edges)}")
print(f"Network is connected: {network.is_connected()}")
# Find most central person (most connections)
connections = {person: network.degree(person) for person in network.vertices}
most_connected = max(connections, key=connections.get)
print(f"Most connected person: {most_connected} ({connections[most_connected]} friends)")
return network
friendships = [
('Alice', 'Bob'), ('Bob', 'Charlie'), ('Charlie', 'David'),
('Alice', 'David'), ('Eve', 'Alice')
]
analyze_social_network(friendships)
Recipe 4: Class Scheduling Conflict Checker
from discrete_math import sets
def check_schedule_conflicts(student_schedule):
"""Check if a student's schedule has time conflicts."""
# Each course is (course_name, time_slot)
time_slots = {}
conflicts = []
for course, time in student_schedule:
if time in time_slots:
conflicts.append((time_slots[time], course, time))
else:
time_slots[time] = course
if conflicts:
print("โ ๏ธ Schedule conflicts found:")
for course1, course2, time in conflicts:
print(f" {course1} and {course2} both at {time}")
else:
print("โ
No conflicts! Schedule is valid.")
return len(conflicts) == 0
schedule = [
('Math 101', 'Mon 9AM'),
('CS 201', 'Mon 11AM'),
('Physics 101', 'Mon 9AM'), # Conflict!
('History 101', 'Tue 10AM')
]
check_schedule_conflicts(schedule)
Recipe 5: Cryptography - Simple RSA Key Generation
from discrete_math.number_theory import *
def generate_simple_rsa_keys(p, q):
"""Generate RSA public and private keys (simplified educational version)."""
# Step 1: Calculate n
n = p * q
# Step 2: Calculate Euler's totient ฯ(n)
phi_n = (p - 1) * (q - 1)
# Step 3: Choose public exponent e (commonly 65537)
e = 65537
if gcd(e, phi_n) != 1:
e = 3 # Fallback
# Step 4: Calculate private exponent d
d = mod_inverse(e, phi_n)
print(f"Public Key: (e={e}, n={n})")
print(f"Private Key: (d={d}, n={n})")
print(f"ฯ(n) = {phi_n}")
return (e, n), (d, n)
# Example with small primes (educational only!)
if is_prime(61) and is_prime(53):
public_key, private_key = generate_simple_rsa_keys(61, 53)
# Encrypt a message (m = 42)
m = 42
e, n = public_key
encrypted = mod_exp(m, e, n)
print(f"\nOriginal message: {m}")
print(f"Encrypted: {encrypted}")
# Decrypt
d, n = private_key
decrypted = mod_exp(encrypted, d, n)
print(f"Decrypted: {decrypted}")
โ FAQ - Frequently Asked Questions
Q: Do I need to know advanced math to use this library?
A: Not at all! The library is designed to help you learn discrete math. Start with the examples and experiment.
Q: Can I use this for my homework?
A: Yes! It's a great tool to verify your answers and understand concepts. But make sure you understand why the answers are correct.
Q: Is this suitable for production applications?
A: The library is educational-focused. For production cryptography, use established libraries like cryptography or pycryptodome.
Q: How can I visualize graphs?
A: The library uses NetworkX under the hood. You can export graphs and use matplotlib for visualization.
Q: What Python version do I need?
A: Python 3.8 or higher. Check with python --version.
Q: The library is missing feature X. Can I request it?
A: Absolutely! Open an issue on GitHub with your feature request.
Q: I found a bug. What should I do?
A: Please report it on GitHub Issues with:
- Python version
- Code that reproduces the bug
- Expected vs actual behavior
๐ Learning Resources
Want to dive deeper into Discrete Mathematics?
Recommended Books
- "Discrete Mathematics and Its Applications" by Kenneth Rosen
- "Concrete Mathematics" by Graham, Knuth, Patashnik
- "Introduction to Graph Theory" by Douglas West
Online Courses
- MIT OpenCourseWare: Mathematics for Computer Science
- Coursera: Discrete Mathematics Specialization
- Khan Academy: Discrete Math Topics
Practice Problems
- Use this library to verify your solutions
- Check out Project Euler for challenging problems
- LeetCode has many discrete math algorithm problems
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
What does this mean?
You can freely use, modify, and distribute this library, even for commercial purposes. Just include the original license.
๐ค Author
CodewithTanzeel
- GitHub: @CodewithTanzeel
- Email: Tanzeelofficial@outlook.com
๐ Acknowledgments
- Students of MS-207 Discrete Mathematics - This library was built with you in mind!
- Open Source Community - Built on amazing libraries like NumPy, SymPy, NetworkX, and Matplotlib
- Educators worldwide - For inspiring the need for better educational tools
- Contributors - Everyone who has helped improve this project
๐ฌ Support & Community
- Questions? Open a GitHub Discussion
- Found a bug? File an Issue
- Want to contribute? Check out our Contributing Guidelines
- Need help? Reach out via email or GitHub
๐ Project Stats
๐บ๏ธ Roadmap
Version 0.2.0 (Coming Soon)
- Interactive Jupyter Notebook examples
- Graph visualization helpers
- More number theory algorithms
- Performance optimizations
- Enhanced documentation
Version 0.3.0 (Planned)
- CLI tool for quick calculations
- LaTeX output for formulas
- Step-by-step solution explanations
- More real-world examples
Have ideas? Share them in GitHub Issues!
๐ Changelog
Version 0.1.0 (Initial Release)
- โ Logic operations and truth tables
- โ Complete set theory operations
- โ Relations and properties
- โ Combinatorics functions
- โ Graph theory algorithms
- โ Number theory utilities
- โ Function analysis tools
- โ Comprehensive test suite (46 tests passing)
- โ Full documentation and examples
Happy Computing! ๐
Remember: Discrete mathematics is everywhere - from computer science to cryptography, from scheduling to social networks. This library is your companion in exploring these fascinating concepts!
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file discrete_math_toolkit-0.1.1.tar.gz.
File metadata
- Download URL: discrete_math_toolkit-0.1.1.tar.gz
- Upload date:
- Size: 52.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
309c376dfb9035cbaf3819497ab760f7e34f19a6b9de44e7aa68adbf8a911b96
|
|
| MD5 |
d89a8963fe72e3b58d5739bb44e0d9ac
|
|
| BLAKE2b-256 |
7fed7dcd0bc5b693b7b44d94077ba5312dabdd0f94492089290565b1e77cd5d6
|
File details
Details for the file discrete_math_toolkit-0.1.1-py3-none-any.whl.
File metadata
- Download URL: discrete_math_toolkit-0.1.1-py3-none-any.whl
- Upload date:
- Size: 30.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
591485a91ea84bd3d1b14fdf88af3be643ed95bdb1a78f781a7129818a213778
|
|
| MD5 |
3b0f7ff4c193341769652894d2862050
|
|
| BLAKE2b-256 |
2af24b1734bdd945b1354f2a6a7e8cd691f8ea8f1f5fdefe03cff1566b403d76
|