Search code examples
pythonsquare-root

how can I square the numbers between 0 and any input with extremely large numbers in python


I am in codewars and the challenge I have has one part I can't get my head around this is what I am speaking of

You are given a number "n" (n >= 0) and a digit "d" (0 <= d <= 9).

Write a function nbDig(n, d) that finds the square of each integer from 0 to n, and returns the number of times that the digit d appears across all the squares. Note that d might appear multiple times in a single square.

Example:

n=12, d=1 Squares from 0 to n=12: 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144 The function returns 7 because the digit d=1 appears 7 times: in 1, 16, 81, 100, 121 (note: 1 appears twice in 121), and 144.

the part the I have trouble with is how do I get my function to get the square roots of everything between 0 and n and when the numbers I have to solve are large numbers like (5750)(195856) or (74747)


Solution

  • If I am interpreting your question correctly, you simply need to devise a very simple list comprehension program.

    Getting the square root of everything between zero and n is not necessary. Did you mean square?

    Here's my solution:

    def nbDig(n,d):
        int_list = str([str(x*x) for x in range(0,n+1)]).count(str(d))
        return int_list
    

    I can test it like so:

    nbDig(12,1)
    

    This returns 7.

    EDIT: I didn't realize calling .replace was totally unnecessary. Thanks for the feedback!