Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
What are Variables?Numbers — Integers and FloatsNumber OperationsStrings — Creating and Using TextString FormattingBooleans and NoneType ConversionGetting User InputBest Practices
Python/Variables Data Types/Number Operations

🔢 Number Operations — Advanced Arithmetic and Bitwise Operations

Master bitwise operations, performance optimization, and advanced arithmetic techniques.


🎯 Bitwise Operations

Bitwise operators work on the binary representations of integers. Essential for systems programming, cryptography, and performance optimization.

# AND, OR, XOR, NOT
a = 12  # 1100 in binary
b = 10  # 1010 in binary

print(a & b)   # 8   (1000) - both bits set
print(a | b)   # 14  (1110) - either bit set
print(a ^ b)   # 6   (0110) - different bits
print(~a)      # -13 (two's complement)

# Bit shifts
x = 5  # 101 in binary
print(x << 1)  # 10 (101 << 1 = 1010)
print(x >> 1)  # 2  (101 >> 1 = 010)

# Practical: Check if number is power of 2
def is_power_of_two(n):
    return n > 0 and (n & (n - 1)) == 0

print(is_power_of_two(8))   # True
print(is_power_of_two(6))   # False

Use case: Flags and permissions

# Bitwise flags for permissions
READ = 1 << 0   # 001
WRITE = 1 << 1  # 010
EXECUTE = 1 << 2  # 100

user_perms = READ | WRITE  # 011

print(user_perms & READ)    # 1 (has READ)
print(user_perms & EXECUTE) # 0 (no EXECUTE)

💡 Advanced Math Operations

import math

# Exponentiation and roots
print(pow(2, 10))          # 1024
print(pow(2, 10, 1000))    # 24 (2^10 mod 1000, faster)

# Factorial and combinations
print(math.factorial(5))    # 120
from math import comb, perm
print(comb(10, 3))         # 120 (10 choose 3)
print(perm(10, 3))         # 720 (10 permute 3)

# Summation and products
from math import prod
print(prod([2, 3, 4]))     # 24
print(math.fsum([0.1, 0.1, 0.1]))  # 0.3 (accurate summation)

# Statistics
print(math.hypot(3, 4))    # 5.0 (Euclidean distance)
print(math.degrees(math.pi))  # 180.0
print(math.radians(180))      # 3.14159...

🎨 Integer Bit Manipulation

# Bit counting
n = 42
print(bin(n))              # '0b101010'
print(n.bit_length())      # 6
print(bin(n).count('1'))   # 3 (number of 1-bits)

# Population count (count set bits)
def popcount(n):
    """Count the number of 1-bits."""
    count = 0
    while n:
        count += n & 1
        n >>= 1
    return count

print(popcount(15))  # 4

# Bit reversal
def reverse_bits(n, width=32):
    """Reverse bits in n."""
    result = 0
    for _ in range(width):
        result = (result << 1) | (n & 1)
        n >>= 1
    return result

print(bin(reverse_bits(5, 8)))  # 0b10100000

📊 Numeric Stability and Performance

# Avoid catastrophic cancellation
def unstable_quadratic(a, b, c, x):
    """Numerically unstable root calculation."""
    return a * x**2 + b * x + c

def stable_quadratic(a, b, c, x):
    """Numerically stable alternative."""
    # Use Horner's method
    return ((a * x + b) * x + c)

# For very large/small values, order matters
values = [1.0, 1e-10, 1e-10, 1e-10]
print(sum(values))  # May lose precision
print(math.fsum(values))  # Maintains precision

# Use math.prod for better numerical stability than manual multiplication
large_nums = [1e20, 1e20, 1e-40]
product = math.prod(large_nums)
print(product)  # More stable than a*b*c

🔑 Performance Optimization

import timeit

# Exponentiation: use ** over pow() for small exponents
print(timeit.timeit('2**10'))      # Faster
print(timeit.timeit('pow(2, 10)')) # Slower

# Integer division is faster than float division + int()
print(timeit.timeit('10 // 3'))   # Faster
print(timeit.timeit('int(10 / 3)'))  # Slower

# Use bit shifts for powers of 2
print(timeit.timeit('8 << 1'))    # Fastest (shift left)
print(timeit.timeit('8 * 2'))     # Slower

🔑 Key Takeaways

ConceptRemember
Bitwise OpsUse for flags, permissions, and performance-critical code
Bit Shifting`<<` and `>>` are fastest for powers of 2
Math Module`factorial()`, `comb()`, `fsum()` for specialized operations
StabilityUse `math.fsum()` and Horner's method for precision
PerformanceBit operations faster than arithmetic for powers of 2

🔗 What's Next?

Master string manipulation in Strings — Creating and Using Text.


Ready to practice? Challenges | Quiz


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn