Home > Enterprise >  Why does this always produce true?
Why does this always produce true?

Time:11-04

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")

CodePudding user response:

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.

CodePudding user response:

Why not just count the number of unique letters in your word and compare it with total number of letters in the word with something like

word = str(input())
if len(set(word)) == len(word):
    print("true")
else:
    print("false")
  • Related