I am using Python and am a beginner. I want my program to check if a word inputted by the user is repeated or not, I know I have to use a for loop to check if the word is repeated or not... using 'in'
word = input("Enter a word:")
for "input by user:" in word
doubleWord("cat") -> False
doubleWord("catcat") -> True
doubleWord("contour"*2) -> True
doubleWord("acatcat") -> False
doubleWord("catcatcat") -> False
doubleWord("catcatcatcat") -> True
If you rephrase the question, it might be easier to understand how to go about this: Is the first half of the word equal to the second half of the word?
We can use Python slicing syntax to divide the word in half:
word[:n]: first n characters of
word[n:]: all the other characters
To get the halfway mark, we divide the length of the word
len(word) by 2: we will floor divide so that it is an integer.
The following function will do the trick:
def repeated_word(word): n = len(word) // 2 return word[:n] == word[n:]