Trying to find the average of a list of outputs but 'int' object is not iterable

Viewed 30

I'm currently learning python and have been given the following task: create a program that will generate random lower-case letters, stopping when the sequence 'Hello' is created. It should then print the total number of characters that had to be created to generate the sequnce. As a part 2 I then need to process this 10 times taking an average of the results. I think I've managed to get the first part functionaing correctly:


import string
import random

for i in range(10):

    def task8(word):
        word = word.lower()
        x = 0
        attempts = 0
        while x < len(word):
            attempts += 1
            z = random.choice(string.ascii_lowercase)
            if z == word[x]:
                x += 1
        return attempts

    attempts = task8("hello")
    print(attempts)

Output: 130 169 56 62 60 62 147 99 31 51

However, at this point I'm struggling to get an average of this list due to a TypeError. I've tried importing statistics and taking the mean from attempts like so:

import string
import random
import statistics

for i in range(10):

    def task8(word):
        word = word.lower()
        x = 0
        attempts = 0
        while x < len(word):
            attempts += 1
            z = random.choice(string.ascii_lowercase)
            if z == word[x]:
                x += 1
        return attempts

    attempts = task8("hello")
    average = statistics.mean(attempts)
    print(average)

line 324, in mean if iter(data) is data: TypeError: 'int' object is not iterable

Not sure what I'm missing here but any help would be appreciated.

1 Answers

I figured this out, I'm not 100% on why but it seems like I needed to output a list from the function so I used list comprehension.

# import external libraries
import string
import random
import statistics


# Define function for task 8
def task8(word):
    # where x is the position in the word
    x = 0
    # number of attempts guessing correct letters
    attempts = 0
    # While the position in the word is less than the length of the word
    while x < len(word):
        # Add one to attempts value
        attempts += 1
        # Define z as a random letter
        z = random.choice(string.ascii_lowercase)
        # If the random letter is at position x of the word
        if z == word[x]:
            # Then add one to the position in the word
            x += 1
            # Return the total number of attempts
    return attempts


# Define lst as the task 8 function returned 10 times as list comprehension
lst = [task8("was") for i in range(10)]
# Define the average as the mean of the defined list of values
average = statistics.mean(lst)
# Print the list and mean
print("Attempts per run: ", lst, " Average (mean): ", average)
Related