-3

Write a function lowest_integer() which takes 2 input arguments:

  • a function f representing an increasing function (),
  • a number fmin,

and returns an integer nmin such that >0 is the smallest integer that satisfies ()>.

To test the function we use code like this where we define f(n) then print(lowest_integer(f, fmin)) and get the expected output:

def f(n):
    return 2*n
print(lowest_integer(f, 10))
## 6

def f(n):
    return n**2 + 6*n - 3
print(lowest_integer(f, 500))
## 20

My attempt at the code:

def lowest_integer(f, fmin):
    f = fmin
    nmin = n + 1
    return nmin

I'm having trouble figuring out how to define the function f(n) within the lowest_integer() function

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

3 Answers3

0

You can loop through the integers starting at 1, until you find one that satisfies your condition, in that case, return it:

def lowest_integer(f, fmin):
    nmin = 1
    while True:
        if f(nmin) > fmin:
            return nmin
        nmin += 1

def f(n):
    return 2*n
print(lowest_integer(f, 10))

def f(n):
    return n**2 + 6*n - 3
print(lowest_integer(f, 500))

Output:

6
20

This approach, of course, is a naive one, and will be slow if the function f is slow and fmin is very big, but in general it does good.

A faster approach would be using a library like sympy or something, that have functions that use more sophisticated methods and techniques that are suited to these kinds of problems.

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
-1

You can do it like that :

def lowest_integer(f, fmin):
    nmin=1
    while f(nmin)<=fmin :
        nmin += 1
    return nmin 

You begin with nmin = 1 and you add 1 to nmin while f(nmin)<=fmin. To do that, you can use a while loop.

By doing f(nmin), you call the function f and calculate its value for the entry nmin.

lauriane.g
  • 337
  • 1
  • 11
  • Thanks a lot! When I try the second code example (i.e. `f(n) = n**2 + 6*n - 3` I get the output `21` instead of `20`, do you know why that might be? – codemachine98 Oct 23 '20 at 13:01
  • 2
    @codemachine98, *please* instead of blindly using code, spend one minute to figure this out for yourself. Ask yourself: is `f(nmin) < fmin` really the opposite of `f(nmin) > fmin`? – mkrieger1 Oct 23 '20 at 13:02
  • Thanks for your comment. I edited my answer to correct this fact. – lauriane.g Oct 23 '20 at 13:11
-1
def f(n):
    return 2*n
def lowest_integer(f, fmin):
    for findmin in range(fmin):
        if f(findmin) > fmin:
            return findmin
    return -1
print(lowest_integer(f, 10))
Aaj Kaal
  • 1,205
  • 1
  • 9
  • 8
  • I appear to get the message `TypeError: 'float' object cannot be interpreted as an integer` when I input a floating number for fmin such as `fmin=1.5`. I tried setting `range(int(fmin))` but I don't get the right output – codemachine98 Oct 23 '20 at 13:13