Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this always produce true?

The code is supposed to take any string input and check if the word is an isogram (word that does not use repeating letters). But it doesn’t actually do that sadly.

# word input and defining variables
word = list(str(input()))
letter = 0
letters = len(word)
x = 0

while letter <= letters: # while loop to repeat once for each letter
    if word.count([letter]) > 1: # checks if the letter is repeated more than once
        x += 1
        letter += 1 # letter is raised by one so it moves onto the next place in the list
    else:
        letter += 1

# printing result
if x == 0:
    print("true")
else:
    print("false")

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

letter as you’ve defined it is a number. word.count(<substring>) will count how many times <substring> appears in word. Why would you count how many time the number you are storing in letter appear in word?

Instead, loop through every letter in word and test word.count(letter). If it’s greater than one, then set a flag variable that stores whether this is an isogram or not, and break the loop since we have discovered at this point that it’s not an isogram.

word = input()

isogram = True
for letter in word:
    if word.count(letter) > 1: 
        isogram = False       
        break
    

if isogram:
    print("true")
else:
    print("false")

Granted, there are more elegant ways to solve this and it could be code-golfed to death, but I think this is what you were originally aiming for before your lost your way with counter variables and lists.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading