Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Faster algorithm
#1
I need faster algorithm. Problem - to leave only the last occurrences of each element in the sequence; the remaining elements must be removed from the sequence. Thank you.

Given: 1 2 3 3 2 1 4 1 2 0
Answer:3 4 1 2 0
My algorithm:
k = input().split()  
    s=[] 
    for i in k:
        if i not in s:
          s.append(i)
        else:
          s.remove(i)  
          s.append(i)
Reply
#2
Stop thinking about python for a minute. This is an easy problem.

Write down a list on a piece of paper. What is the last number in the answer?
Output:
1 2 3 3 2 1 4 1 2 0 ^ Answer = 0
What number do you check next. Is it added to the answer?
Output:
1 2 3 3 2 1 4 1 2 0 ^ Answer = 2 0
This is repeated for 1, 4, 1, 2, 3, 3, 2, 1
What happens when we encounter a number that is already in the answer?
output]
1 2 3 3 2 1 4 1 2 0
^
Answer = 4 1 2 0[/output]
1 is already in Answer, so it does not get added to the answer list.

That is the algorithm. Now all you need to do is convert it to code. I wonder if python has a way to get items from a list starting at the end? I wonder if python has a way to insert items at the front of a list?



The next n
Reply
#3
Another thought - from your description you want just the unique values. A set is a collection with unique values. Convert the list to a set, then back again. Voila. Bet that will be really fast.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020