Search code examples
pythonarrayspython-3.xlist

Can't remove some of the numbers from the list (from, to), only removes first number


array1 = []

while True:
    try:
        number = input("number('end' to continue): ")
        if number == "end":
            break
        number = int(number)
    except ValueError:
        continue
    else:
        array1.append(number)

if len(array1) == 0:
    print("There is no elements in the array!")
    exit()
else:
    array1.sort()
    print("Your array:", array1)

while True:
    try:
        numberFrom = int(input("Remove elements 'from': "))
    except ValueError:
        continue
    else:
        if numberFrom in array1:
            break
        else:
            continue

while True:
    try:
        numberTo = int(input("Remove elements 'to': "))
    except ValueError:
        continue
    else:
        if numberTo in array1:
            if numberTo >= numberFrom:
                break
        else:
            continue

for i in array1:
    if i in range(numberFrom, numberTo):
        array1.remove(i)

print(array1)

For exaple:

entered 1, 2, 3, 4, 5 got [1, 2, 3, 4, 5] enter 1 enter 3 got [2, 3, 4, 5]

Need to get [4, 5] (because from 1 to 3 is 1, 2, 3)

Please help idk what to do :c

For those who interested, text from the original exercise that i tried to complete:

"Given a one-dimensional array of numeric values, numbering N elements. Exclude from the array elements belonging to the interval [B;C]." (GoogleTranslate)


Solution

  • Here is the fixed code

    i modified the last 3 lines to actually get an index and then return the rest of the array by concatenating them

    array1 = []
    
    while True:
        try:
            number = input("number('end' to continue): ")
            if number == "end":
                break
            number = int(number)
        except ValueError:
            continue
        else:
            array1.append(number)
    
    if len(array1) == 0:
        print("There is no elements in the array!")
        exit()
    else:
        array1.sort()
        print("Your array:", array1)
    
    while True:
        try:
            numberFrom = int(input("Remove elements 'from': "))
        except ValueError:
            continue
        else:
            if numberFrom in array1:
                break
            else:
                continue
    
    while True:
        try:
            numberTo = int(input("Remove elements 'to': "))
        except ValueError:
            continue
        else:
            if numberTo in array1:
                if numberTo >= numberFrom:
                    break
            else:
                continue
    
    # Here is what I have added
    index1 = array1.index(numberFrom)
    index2 = array1.index(numberTo)
    array1 = array1[:index1] + array1[index2 + 1:]
    
    print(array1)