Home > other >  Indexing with integer division
Indexing with integer division

Time:04-28

This practice question I just went over is confusing me despite having the answer already, if someone could break down what's happening in a more understandable way I'd appreciate it.

instructions: Given an index using INTEGER division and a list, return the value of the list with the given index.

starter code:

    def value_at(lst,index):

values it's testing against:

    Test.assert_equals(value_at([1, 2, 3, 4, 5, 6], 10 // 2), 6)
    Test.assert_equals(value_at([1, 2, 3, 4], 6.535355314 // 2), 4)
    Test.assert_equals(value_at([1, 2], 1.0 // 2), 1)
    Test.assert_equals(value_at([1, 2, 3, 4, 5, 6], 8.0 // 2), 5)

solution:

    return lst[int(index)]

CodePudding user response:

List indexes have to be an integer. The integer division operator // rounds its result down to an integer, but if either of the operands is a float it returns this as a float, not an integer. For instance, 10 // 2 == 5, but 10.0 // 2 == 5.0.

So your function must convert the parameter to an integer so it can be used as a list index. int(5.0) == 5.

CodePudding user response:

So with the test cases for context, it's telling you that you'll be called with a value that is the result of integer division (it's a slight lie; the test cases make it clear you receive the result of floor division, which doesn't always produce an int, though it will always be equivalent to some int), not that you do any such division yourself.

Since floor division can produce a float (when one or more of the operands is float), you have to handle that by coercing the float to an int, which is what the int() in the solution does. It would also coerce floats that aren't equivalent to an int to int, so that might be a problem in production code, but then, using floats for indices is weird and evil in the first place. But aside from that int coercion, the function is just doing normal list indexing.

CodePudding user response:

It is very simple. You give it a list, lets say [1, 2, 3, 4, 5, 6]. And an index in the form of int division, lets say (10 // 2) this is equal to (5).

The function returns the list object at index 5. Which in this case is (6).

The int() part is to convert the result of the division to an integer in case one of the divided numbers is a float. Floats cannot be used as index thats why we need to convert it to an integer.

  • Related