Adding occurrences of specific items to a value for each iteration of a for loop

Hi. I’m very new to programming (about a week in) and have started making some little projects on my own. I had a bizarre little idea that I thought would be good practice. I have a list of five words. A function randomizes the order and turns it into a string separated by spaces. Then I want to count each time the sentence orders a sentence that is syntactically correct in English (‘the dog eats the man’ or ‘the man eats the dog’).

I thought the following code would be ok, but when I run it, it prints correctCount = 0 and incorrectcount = 10000 (or whatever number for the range) even though, looking at the output, there are occurrences of what I want to be added to correctCount. I was struggling for a while and thought my question was too specific to look for elsewhere. Since I have been coding for so short a time, I expect there to be other issues with the code other than what I’m looking for. If you would be so kind as to point those out as well, I’d be more than pleased.

Sorry if this post is a strange read and doesn’t conform to typical Topic etiquette, this is the first time I’m using the site. Thanks so much! : )

import random
def shuffler(lst):
    while True:
        random.shuffle(lst)
        r = ' '.join(lst)
        return(r)

words = ['the', 'man', 'eats', 'the', 'dog']
correctCount = 0
incorrectCount = 0
for i in range(10000):
    print(shuffler(words))
    if str(words) != 'the man eats the dog':
        incorrectCount = incorrectCount + 1
    elif str(words) != 'the dog eats the man':
        incorrectCount = incorrectCount + 1
    else:
        correctCount = correctCount + 1 
print(correctCount)
print(incorrectCount)

In shuffler, the while True: is pointless because the code starts the loop, shuffles the list, and then returns a result. The loop never repeats.

print(shuffler(words)) doesn’t store the value that was returned, it only prints it.

str(words) converts the list of words into a string, e.g. str(['the', 'man', 'eats', 'the', 'dog']) returns "['the', 'man', 'eats', 'the', 'dog']", which matches neither 'the man eats the dog' nor 'the dog eats the man'.

3 Likes

Thank you so much for your help! Your advice got the thing up and running exactly how I envisioned.