Home > Software engineering >  Function to check whether a word repeats itself in Python
Function to check whether a word repeats itself in Python

Time:03-29

I'm a newbie in Python. I want to know how to make a function that checks whether a word/string repeats itself, returning true if yes and vice-versa.

Specifically, I'm requiring inputs from the user in a text-based game. At one point you're required to pick some items. If you pick an item twice, then the section repeats and you're required to do it again. I want to make a function that checks whether a list contains duplicates.

I tried something like

>>> your_list = ['one', 'two', 'one']
>>> len(your_list) != len(set(your_list))

But maybe I'm doing something wrong

CodePudding user response:

If you store the picked items in a list, you can simply check if the newly requested item is already in the list or not:

# item_list is the list of already picked items
new_item = ask_for_item() # your function to request a new item from the user

while new_item in item_list:
    new_item = ask_for_item() # already in the list, ask again

# if you get out of the loop, then it means new_item is not in the list
item_list.append(new_item)

If you already have a list and want to check, your code is correct:

len(your_list) != len(set(your_list))

# Will return True if there is at least one duplicated value

CodePudding user response:

all thing is fine with this it return true when the list is duplicate

>>> your_list = ['one', 'two', 'one']
>>> len(your_list) != len(set(your_list))
  • Related