[Python] Use of magic numbers in established mathemetical algorithms [closed]

Discussão em 'Python' iniciado por Stack, Abril 9, 2025.

  1. Stack

    Stack Membro Participativo

    I'm doing a coding task in Python and as a part of it I have to implement a primality test and I have this:

    def is_prime(n: int, primes_cache: dict[int, bool]) -> bool:
    if n in primes_cache:
    return primes_cache[n]
    if n <= 1:
    primes_cache[n] = False
    return False
    if n == 2 or n == 3:
    primes_cache[n] = True
    return True
    if n % 2 == 0 or n % 3 == 0:
    primes_cache[n] = False
    return False
    i = 5
    while i * i <= n:
    if n % i == 0 or n % (i + 2) == 0:
    primes_cache[n] = False
    return False
    i += 6
    primes_cache[n] = True
    return True


    But in the past my application got rejected becuase I used magic numbers (hardcoded numbers and strings etc.) and now I'm super careful. I'm wondering if I should replace stuff like 5 in

    i = 5


    with constants but at the same time I don't really see the point? Becuase it's never going to change - it's a set algorithm and I'm really torn here.

    Continue reading...

Compartilhe esta Página