Skip to main content

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

  1. Fork the repository on GitHub
  2. Create a branch for your feature: git checkout -b feature/AmazingFeature
  3. Make your changes and add tests
  4. Run tests to ensure nothing breaks: pytest
  5. Commit your changes: git commit -m 'Add some AmazingFeature'
  6. Push to your branch: git push origin feature/AmazingFeature
  7. 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


๐Ÿ™ 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


๐Ÿ“Š Project Stats

Python Version License Status


๐Ÿ—บ๏ธ 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

discrete_math_toolkit-0.1.1.tar.gz (52.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

discrete_math_toolkit-0.1.1-py3-none-any.whl (30.0 kB view details)

Uploaded Python 3

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

Hashes for discrete_math_toolkit-0.1.1.tar.gz
Algorithm Hash digest
SHA256 309c376dfb9035cbaf3819497ab760f7e34f19a6b9de44e7aa68adbf8a911b96
MD5 d89a8963fe72e3b58d5739bb44e0d9ac
BLAKE2b-256 7fed7dcd0bc5b693b7b44d94077ba5312dabdd0f94492089290565b1e77cd5d6

See more details on using hashes here.

File details

Details for the file discrete_math_toolkit-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for discrete_math_toolkit-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 591485a91ea84bd3d1b14fdf88af3be643ed95bdb1a78f781a7129818a213778
MD5 3b0f7ff4c193341769652894d2862050
BLAKE2b-256 2af24b1734bdd945b1354f2a6a7e8cd691f8ea8f1f5fdefe03cff1566b403d76

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page