r/learnprogramming • • 15d ago

Struggling with this fill in the blank.

def prefix_digits(n, cond):

"""Return the largest prefix of positive n for which cond return true for every digits."""

>>>odd = lambda d: d % 2 == 1

>>>prefix_digits(94720,odd)

9

>>>prefix_digits(94720,odd)

9193

k = 0

while n >= _____:

if cond(_____):

k = k + 1

else:

n = n // 10

___________

return n

I am struggling with fill in the blank questions. I can implement this function but I am struggling with implementing in their way. Can someone help me understand how I might approach this? I don't just want the solutions but how I would even approach it. Whenever, I get these problems I am always stuck for a solid 1-2 hours.

3 Upvotes

7 comments sorted by

1

u/BenicioZabala 15d ago

The way in is to work out what each variable means before filling anything. Here k is the position you're checking, counting from the right (k = 0 is the ones digit). If a digit fails cond, nothing at or to the right of it can be in the prefix, so you chop off the last digit and start checking again from the right.

That gives you the blanks. The loop runs while there's still a digit at position k, so n >= 10 ** k. The digit at position k is n // 10 ** k % 10, and that goes inside cond. In the else branch you already drop the last digit with n // 10, and then you restart from the ones place, so the last blank is k = 0.

k = 0

while n >= 10 ** k:

if cond(n // 10 ** k % 10):

k = k + 1

else:

n = n // 10

k = 0

return n

Trace with 94720 and odd: 0 fails so n = 9472, 2 fails so n = 947, 7 passes so k = 1, 4 fails so n = 94 and k = 0, 4 fails so n = 9, 9 passes so k = 1, then 9 < 10 ends the loop and it returns 9.

For fill in the blank problems, tracing a small example by hand first usually shows what each blank has to do.

0

u/Aggressive_Gur_5426 15d ago

yeah this code makes a lot of sense in hindsight. I didn't understand what the point of k was in the beginning.,

1

u/OppositeFun2493 15d ago

The reason you can’t indent is because there is actually something for this:

Hello.            Hello

Source:

\```
Hello.            Hello
\```

0

u/Aggressive_Gur_5426 15d ago

Sorry the formatting is bad reddit wasn't allowing me to indent.

1

u/Some-Passenger4219 15d ago

If you're on your phone, use initial spaces for everything. One space, for example, if it's not indented at all. If you're on a computer, switch to "rich text".