#Card Games (Python) - TypeError for 6) average_even_is_average_odd

16 messages · Page 1 of 1 (latest)

timid breach
#

def card_average(hand): return sum(hand) / len(hand)
def average_even_is_average_odd(hand): evens = hand[::2] odds = hand[1::2] return card_average(evens) == card_average(odds)
I am expecting this function to return True if the average of the even-indexed elements in the list "hand" is equal to the average of the odd-indexed elements, and False if not. This is the error that's being thrown for every test:
TypeError: list indices must be integers or slices, not float
I have tried int() on every number but still nothing seems to work. Any suggestions?

velvet creek
#

Would you mind posing the whole code and whole error

timid breach
#

`input_data = [[0, 1, 5], [3, 6, 9, 12, 150], [1, 2, 3, 5, 9],
[2, 3, 4, 7, 8], [1, 2, 3], [2, 3, 4],
[2, 3, 4, 8, 8], [1, 2, 4, 5, 8]]

result_data = [False, False, False, False, True, True, True, True]

for variant, (hand, expected) in enumerate(zip(input_data, result_data), start=1):
with self.subTest(f'variation #{variant}', hand=hand, expected=expected):
actual_result = approx_average_is_average(hand)
error_message = (f'Called approx_average_is_average({hand}). '
f'The function returned {actual_result}, but '
f'the hand {hand} {"does" if expected else "does not"} '
f'yield the same approximate average.')

    self.assertEqual(actual_result, expected, msg=error_message)

TEST FAILURE
TypeError: list indices must be integers or slices, not float`

#

That's the whole error, I posted the whole code

velvet creek
#

This error TypeError: list indices must be integers or slices, not float
come from somewhere else, that's why i ask for the whole code aka other functions as well

#

your implementation of those 2 functions already look correct. so this is likely from somewhere else

timid breach
#

Oh thank you. You're right. It's from the previous exercise 🤦‍♂️

#

def approx_average_is_average(hand): average_first_and_last = (hand[0] + hand[-1]) / 2 middle_card_index = int((len(hand) + 1) / 2) median = hand[middle_card_index] return median == card_average(hand) or average_first_and_last == card_average(hand) pass

#

This is the one throwing the error

velvet creek
#

If there are 5 cards, what is the index of the middle card?

timid breach
#

Ah it should be -1 shouldn't it

#

0 indexed not 1 indexed

#

Thanks!

velvet creek
#

did everything pass now?

timid breach
#

Yeh all passed now. Thank you so much!

velvet creek
#

no problem, have fun coding!