4

The task is writing a function, which returns average hours of sleep in a week. Excluding fridays and saturdays. The input is a list of hours, starting at monday.

def averageSleep(hours):
    fridays = hours[4::-5]
    saturdays = hours[5::-6]
    length = len(hours)
    final = (sum(hours)-sum(fridays)-sum(saturdays)) / (length - 2)
    return final
        



print(averageSleep([6, 7.5, 3.5, 6, 9, 10, 7, 6, 7, 4])) 

The function that I wrote returns:

5.875

Which is correct. Excluding items 9 and 10 (friday and saturday) from the list. The problem is, however, that passing in more list items (yielding more fridays and saturdays) makes the function return wrong results. hours[4::-5] and hours[5::-6] just don't work for more fridays and saturdays.

Any idea how to pick all the fridays and saturdays from the list?

1 Answers1

3

Look up how list slicing works. hours[x:y:z] gives you elements of hours starting at the xth index, up to (but not including) the yth index, with a step of z elements. To get fridays, you want to skip 7 elements, starting at the 4th index, so you need to do

fridays = hours[4::7]
saturdays = hours[5::7]

Also note that you'll have to divide the sum by (len(hours) - len(fridays) - len(saturdays)) to get the correct mean.

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70