0

I’m new to Python and having trouble just understanding what exactly this question is asking me to do:

"A grasshopper is trying to reach a flower that’s N feet away by hopping to it. However, there are some restrictions on how it can hop.

It can only hop forward, not backward. If it passes the flower, it can’t come back.

At any given point, it can hop either M feet, or just 1 foot.

On a single line of input, you’re given 2 integer values: N and M.

Determine the minimum number of hops it will take the grasshopper to reach the flower exactly."

Please help! So far...

def num_of_hops(n, m):
    while m < n / n % 1: 
        m += 1 
        if m > n:
            break
JSchock
  • 5
  • 1
  • 2
  • Return the number of times it can hop `m` feet plus the remainder. Python offers an [integer division operator](https://stackoverflow.com/questions/183853/what-is-the-difference-between-and-when-used-for-division) and a [modulo operator](https://stackoverflow.com/questions/4432208/what-is-the-result-of-in-python) – Pynchia Jul 25 '20 at 05:12
  • The frog can do full jumps or tiny jumps.you need to work out how many full jumps go into the distance to the lily and how much is left over. The integer division returns whole numbers, and the percent operator (modulus) returns the remainder. – Peter Wood Jul 25 '20 at 05:18
  • How would you do it by hand? – Karl Knechtel Jul 25 '20 at 05:43
  • As a side note: "deciphering this python code" means that somebody else already wrote code for you, and you're trying to understand how it works. – Karl Knechtel Jul 25 '20 at 05:45

1 Answers1

2

As stated, you’re given 2 integer values: N and M.. M is a variable, it can represent any number of feet per hop, but we assume that it is always bigger than 1. Your goal is to get to the flower, which is N feet away, with the minimum number of hops.

So basically, there are 2 kinds of hops:

  • 1 foot hop.
  • M feet hop (M > 1). You would probably want to reach the flower, using as much M sized hops as possible.

A suggestion for a solution would be:

def num_of_hops(n, m):
    counter = 0  # This counter represents the number of hops done
    while n > 0:  # As long as we haven't reached the flower - keep going
        if n - m >= 0:  # If it is possible to make an M sized hop...
            n -= m  # n = n - m
        else:  # If we must make a 1 foot hop...
            n -= 1  # n = n - 1
        counter += 1  # counter = counter + 1
    return counter;  # Return the number of hops done

Please note: as said in the comments, it is possible to use the modulo (%) operator, but according to the given tags, I suppose that you are talking about loops.

Daniel Reyhanian
  • 579
  • 4
  • 26