Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for a sequence in a python list

Tags:

python

list

I have a list [T20, T5, T10, T1, T2, T8, T16, T17, T9, T4, T12, T13, T18]

I have stripped out the T's, coverted to integer type and sorted the list to get this:

sorted_ids=[1, 2, 4, 5, 8, 9, 10, 12, 13, 16, 17, 18, 20]

I'm looping over the list and checking if the next number to current number is in numerical sequence. If not I want to insert a "V" in its position.

So eventually the list should look like: [1, 2, V, 4, 5, V, V, 8, 9, 10, V, 12, 13, V, V, 16, 17, 18, V, 20]

However, I'm not able to insert the exact no of V's at the right positions.

def arrange_tickets(tickets_list):

    ids=[]
    for item in tickets_list:
        new_str=item.strip("T")
        ids.append(int(new_str))
    sorted_ids = sorted(ids)
    temp_ids = []
    print("Sorted: ",sorted_ids)
    #size = len(sorted_ids)
    for i in range(len(sorted_ids)-1):
        temp_ids.append(sorted_ids[i])
    
        if sorted_ids[i]+1 != sorted_ids[i+1] :
            temp_ids.insert(i+1,"V")
    print(temp_ids)
    #print(sorted_ids)
    

tickets_list = ['T20', 'T5', 'T10', 'T1', 'T2', 'T8', 'T16', 'T17', 'T9', 'T4', 'T12', 'T13', 'T18']
print("Ticket ids of all the available students :")
print(tickets_list)
result=arrange_tickets(tickets_list)

Actual Result: [1, 2, 'V', 4, 'V', 5, 8, 'V', 9, 'V', 10, 12, 'V', 13, 16, 17, 18]

Expected Result: [T1, T2, V, T4, T5, V, V, T8, T9, T10, V, T12, T13, V, V, T16, T17, T18, V, T20]

like image 356
HackersInside Avatar asked Dec 03 '22 10:12

HackersInside


2 Answers

Here is a list comprehension which gets you what you want:

sorted_ids=[1, 2, 4, 5, 8, 9, 10, 12, 13, 16, 17, 18, 20]
a = sorted_ids[0]
b = sorted_ids[-1]
nums = set(sorted_ids)
expected = ["T" + str(i) if i in nums else 'V' for i in range(a,b+1)]
print(expected)

Output:

['T1', 'T2', 'V', 'T4', 'T5', 'V', 'V', 'T8', 'T9', 'T10', 'V', 'T12', 'T13', 'V', 'V', 'T16', 'T17', 'T18', 'V', 'T20']
like image 138
John Coleman Avatar answered Dec 22 '22 19:12

John Coleman


Here is a solution:

sorted_ids=[1, 2, 4, 5, 8, 9, 10, 12, 13, 16, 17, 18, 20]

def arrange(inList):
    newList = []
    newList.append('T'+str(inList[0]))
    for i in range(1,len(inList)):
        diff = inList[i] - inList[i-1]
        if diff > 1:
            for d in range(diff-1):
                newList.append('V')
            newList.append('T'+str(inList[i]))
        else:
            newList.append('T'+str(inList[i]))
    return newList

print(arrange(sorted_ids))

Output:

['T1', 'T2', 'V', 'T4', 'T5', 'V', 'V', 'T8', 'T9', 'T10', 'V', 'T12', 'T13', 'V', 'V', 'T16', 'T17', 'T18', 'V', 'T20']
like image 31
Vasilis G. Avatar answered Dec 22 '22 21:12

Vasilis G.