I have a school assignment to delete a specific element from an inputted list. Here are the specifics:
What you have to do:
- Input a list, with at least one element repeating itself at least two times
- Delete the last occurrence of that element from the list
For example: If the input is [1, 2, 3, 4, 3, 6, 3, 8] The output should be [1, 2, 3, 4, 3, 6, 8]
However, you can't:
- Use deletion methods on the list except for pop; del, remove, etc are not allowed
- Reverse the list, you have to read it from left to right
Here's what I've got so far:
l= mid=0 found=0 for m in range(0,10): num=int(input("Enter the numbers for the list(10)")) l.append(num) nan=int(input("Enter the number which u want to remove")) for i in range(0,10): if l[i]==nan: mid=i for j in range(mid,10): if l[j]==nan: found=1 mid=j for k in range(mid,9): l[k]=l[k+1] break if nan not in l: found==-1 if found==1: l.pop() print (l) if found==-1: print("Number doesnt exist in given list")
But I don't understand how the program isn't working. It should be deleting the second occurrence of the inputted element, not the last one.
For say, if the list is: [1, 2, 3, 2, 5, 6, 7, 2, 9, 10] Shouldn't the outcome be: [1, 2, 3, 5, 6, 7, 2, 9, 10]? If not, why? If someone could explain that to me, it'd be a great help!
l = [1, 2, 3, 4, 3, 6, 3, 8] seen = set() duplicates =  remove_after_occurrence = 3 for number in l: if number not in seen: seen.add(number) else: if number not in duplicates: duplicates.append(number) counter = 0 for remove in duplicates: for index, number in enumerate(l): if remove == number: counter += 1 if counter == remove_after_occurrence: l.pop(index) counter = 0 print(l) print(seen) print(duplicates)
This solution uses a set to indicate the duplicate values. And after removes the duplicate values in the list with pop. It is a little bit easier to read.