Search code examples
pythonlistadjacency-matrix

What went wrong with my code?Is there a better way to do this?


So I got this list

integer_data=[[2, 3, 4, 5], [1, 2, 3, 6], [1, 3, 6], [0, 1, 5, 6], [1, 2, 3, 4]]

and I got another list of list

adjList=[[1, 0], [0, 2, 3, 1], [1, 3, 4, 5, 2], [1, 2, 4, 5, 3], [2, 3, 5, 6, 4], [2, 3, 4, 6, 5], [4, 5, 6]]

and an empty list

listPrint=[]

I want to take the first number in each list of integer_data;e.g. no.2 then find the list in adjList which last number matches that number(in this case no.2),which is list [1, 3, 4, 5, 2].If there are items in the list in integer_data that is not in [1, 3, 4, 5, 2] then I append 'No' to listPrint, else I append 'Yes'.Then I move on to the next list in integer_data and repeat.

The last number of each list in adjList is unique.The output should be

resultList=['Yes','No','No','No','No','No']

I tried with this code and the result was quite far off.I'm new to Python so any help will be appreciated.

for item in integer_data:
itemToCheck=item[0]
 for itemTwo in adjList:
    itemTwoToCheck=itemTwo[-1]
    if itemToCheck==itemTwoToCheck:
        itemToCompareOne=item
        itemToCompareTwo=itemTwo
        for itemThree in itemToCompareOne:
            if itemThree not in itemToCompareTwo:
                listPrint.append('No')
            else:
                listPrint.append('Yes')

Solution

  • Let us work through your example. Based on your description, I assume the expected answer is ['yes', 'no', 'no', 'no', 'no'], since there are only 5 lists in integer_data.

    Also, for brevity, I renamed the two lists to A and B.

    A=[[2, 3, 4, 5], [1, 2, 3, 6], [1, 3, 6], [0, 1, 5, 6], [1, 2, 3, 4]]
    B=[[1, 0], [0, 2, 3, 1], [1, 3, 4, 5, 2], [1, 2, 4, 5, 3], [2, 3, 5, 6, 4], [2, 3, 4, 6, 5], [4, 5, 6]]
    listPrint=[]
    
    # Construct dictionary d. 
    # For every list in B, map its last element to the list itself
    d={}
    for list_b in B:
        d[list_b[-1]] = list_b
    
    '''
    In your example, d is
    {   0: [1, 0],
        1: [0, 2, 3, 1],
        2: [1, 3, 4, 5, 2],
        3: [1, 2, 4, 5, 3],
        4: [2, 3, 5, 6, 4],
        5: [2, 3, 4, 6, 5],
        6: [4, 5, 6]
    }
    '''
    
    for list_a in A:
        list_b = d[list_a[0]] # find the corresponding list_b
        answer = 'yes'
        for a in list_a:
            if a not in list_b:
                answer = 'no'
                break
        listPrint.append(answer)
    
    print(listPrint) # ['yes', 'no', 'no', 'no', 'no']