Hamming numbers in python

342 views Asked by At

I came across a question in codewars which asked to find the nth smallest Hamming Number. Basically the number can only have 2, 3, and/or 5 as factors. Below is the code that I made for it.

def hamming(n):
    if n == 1:
        return 1
    elif n == 2:
        return 2
    elif n == 3:
        return 3
    elif n == 5:
        return 5
    else:
        count = 1
        i = 2
        while count < n:
            if check(i):
                count += 1
            i += 1

        return i

def check(n):
    if n == 2:
        return True
    elif n == 3:
        return True
    elif n == 5:
        return True
    else:
        if n % 2 == 0:
            return check(n / 2)
        elif n % 3 == 0:
            return check(n / 3)
        elif n % 5 == 0:
            return check(n / 5)
        else:
            return False

But it's not giving the correct values.

1

There are 1 answers

1
Frank Yellin On

Since your presumably doing codewars to learn more about coding, it doesn't really help you to give you the answers.

Try just running:

for i in range(10):
    print(i, hamming(i))

and look at the output. You can easily figure out what the first ten outputs are supposed to be. Figure out why you're not getting that. What is it giving 5 as an answer twice, and then skipping 6?