Home > database >  ValueError: list.remove(x) : x not in list
ValueError: list.remove(x) : x not in list

Time:12-08

I am trying to write a program that sees if there is a repetition in letters in the given string but I was getting a problem(error) "ValueError: list.remove(x) : x not in list" check below for the code that I used in my program.

import random

word = input("write the word that you want to permutate in all different ways  : ")
n = len(word)

def check() :
    s = set ()
    list = [0]
    i = 0

    while True :
        i  = i 1
        if i == n :
            break
        list.append(i)
        
    print(list)

    while True :
        number = random.randint(0,n-1)
        list.remove(number)
        checknum = random.choice(list)
        if checknum == number :
            checknum = random.randint(0,n-1)
        if word[number] == word[checknum] :
            print("there is a repetition of characters in the given string.....")

        if len(list) == 0 :
            break

check()

CodePudding user response:

First of all, you should really avoid using built in types as your variable names (instead of list you can use number_list).

Regarding your question - here's a counter question - what happens if you remove a random number it gets randomized again?

CodePudding user response:

In bellow code, the random.choice() method is used to choose a random number from the list instead of using random.randint(). This ensures that the chosen number is always in the list, and avoids the "ValueError:

import random

word = input("write the word that you want to permutate in all different ways  : ")
n = len(word)

def check() :
    s = set ()
    list = [0]
    i = 0

    while True :
        i  = i 1
        if i == n :
            break
        list.append(i)
        
    print(list)

    while True :
        # Use the random.choice() method to choose a random number from the list, instead of using random.randint()
        number = random.choice(list)
        # Check if the number is in the list before trying to remove it
        if number in list:
            list.remove(number)
        checknum = random.choice(list)
        if checknum == number :
            checknum = random.randint(0,n-1)
        if word[number] == word[checknum] :
            print("there is a repetition of characters in the given string.....")

        if len(list) == 0 :
            break

check()
  • Related