1337holiday - 4 months ago 6x

Python Question

I have a problem with this question from my professor. Here is the question:

Write the definition of a function typing_speed , that receives two parameters. The first is the number of words that a person has typed (an int greater than or equal to zero) in a particular time interval. The second is the length of the time interval in seconds (an int greater than zero). The function returns the typing speed of that person in words per minute (a float ).

Here is my code:

`def typing_speed(num_words,time_interval):`

if(num_words >= 0 and time_interval > 0):

factor = float(60 / time_interval)

print factor

return float(num_words/(factor))

I know that the "factor" is getting assigned 0 because its not being rounded properly or something. I dont know how to handle these decimals properly. Float isnt doing anything apparently.

Any help is appreciated, thankyou.

Answer

When you call `float`

on the division result, it's *after the fact* the division was treated as an integer division (note: this is Python 2, I assume). It doesn't help, what does help is initially specify the division as a floating-point division, for example by saying `60.0`

(the float version of `60`

):

```
factor = 60.0 / time_interval
```

Another way would be divide 60 by `float(time_interval)`

Note this sample interaction:

```
In [7]: x = 31
In [8]: 60 / x
Out[8]: 1
In [9]: 60.0 / x
Out[9]: 1.935483870967742
```

Source (Stackoverflow)

Comments