How to breakup a list of list in a given way in Python [closed]

2024/7/5 10:52:33

Given a list of list of integers, task is to write a function which will output another list of list of integers. It's hard to tell the nature of the desired output in words, I am writing some examples:

# list with one element will be returned
>>> func([[1, 2, 3, 4]])
[[1, 2, 3, 4]]>>> func([[1], [1, 2]])
[[1], [2]]>>> func([[1, 2], [1]])
[[1], [2]]>>> func([[1], [1, 2, 3]])
[[1], [2, 3]]>>> func([[1], [1, 2, 3], [1, 4]])
[[1], [2, 3], [4]]>>> func([[1, 2], [2, 3]])
[[1], [2], [3]]>>> func([[1], [2], [1, 2, 3]]) 
[[1], [2], [3]]>>> func([[1, 2], [1, 2, 3]])
[[1, 2], [3]]>>> func([[1], [1, 2], [1, 2, 3]])
[[1], [2], [3]]

(UPDATE) You can use the following preconditions:

  1. Each inner list contains integers already sorted and there is no duplicate entry.

  2. The outer list has no duplicate entry.

(UPDATE) As you asked, here's what I think I'm stuck with:

This is a problem on some optimization on a Directed Graph, with numbers as nodes and inner lists as starting points of edges (the outer list is the set of starting points of all edges). Now, you might ask, "How there be multiple start points to a single edge, which is shown in some test cases?"

This is what I am trying to do: for func ([1, 2]) the node 1 & node 2 can be merged to a single node. The output [1, 2] shows that these two can be merged.

Now look at func ([[1], [1, 2]]). The 2nd inner list tries to merge node 1 & 2 together, but the 1st inner list says node 1 cannot be merged to anything. So, the output is [[1], [2]], indicating that node 1 & node 2 are to be kept separated.

For func ([[1], [2, 3], [1, 2, 3]]), node 1 is to be separated, but node 2 & 3 can be merged; so the output would be [[1], [2, 3]]

In case of func ([[1, 2], [2, 3]]), neither node 1 & 2 nor 2 & 3 can be merged as node 1 & 3 can be merged, so the expected result is [[1], [2], [3]].

There is a list of integers also, which comprises of end points of vertices, each integer corresponds to each inner list. When elements of an inner list are merged to one, there remains only 1 edge. When they are separated, there are singleton lists, and elements from each of which is taken as starting points; the list of end points are updated accordingly.

I think it will help you to realize my needs.

Answer

This relies on the list of lists being sorted in ascending length (and the outputs needs sorting), but works with all provided input as of time of posting.

def removeFromList(elementsToRemove):def closure(list):for element in elementsToRemove:if list[0] != element:returnelse:list.pop(0)return closuredef func(listOfLists):result = []for i, thisList in enumerate(listOfLists):result.append(thisList)map(removeFromList(thisList), listOfLists[i+1:])return result

You can remove the closure using more for loops, but it looked too ugly, and too deeply nested.

Edit: based on updates, this is the naive solution to the actual problem:

from itertools import combinationsdef isSubsetOrDisjointTo(listA, listB):return all(item in listB for item in listA) or all(item not in listB for item in listA)def func(nodesToJoin):#flatten list, extracting duplicatesallNodes = sorted(set(itertools.chain(*nodesToJoin)))result = []seen = set()for length in xrange(max(map(len, nodesToJoin)), 0, -1): #start with longest possible, work to shortestfor sublist in combinations(allNodes, length):if any(item in seen for item in sublist):#skip possible sublists with options we've already seen in the resultcontinueif all(isSubsetOrDisjointTo(sublist, node) for node in nodesToJoin):result.append(sublist)seen.update(sublist)return result

There are probably a number of ways this can be optimised or improved.

https://en.xdnf.cn/q/120097.html

Related Q&A

Incrementing a counter while assigning it in python

Is it possible to do the following in python somehow?nodename = node%s % (++num if ct[0] != J else num)Or do I need to first do the increment and the assign it on the next line:if ct[0] != J:num += 1n…

Append two arrays together into one? (Numpy/Python)

I currently have an array of strings and Im trying to join it together with another array of strings to form a complete word to do some web parsing. For example:`Var1 [A B C, .... ....] Var2 …

Python 2.7 Isolate multiple JSON objects in a string

Ive to parse a text file that contains different kind of data. The most challenging is a line that contains three different JSON object (strings) and other data between them. Ive to divide the Json da…

pass different C functions with pointer arrays as the function argument to a class

I am trying to pass different functions which have pointers as arguments to a python function. One example of the input function as input parameter is the given normal function: Sample.pyxfrom cpython …

dynamic filter choice field in django

I am using django-filter to filter results on a page. I am able to use static choice filters like this:filters.pyFILTER_CHOICES = ( (, All States), (AL, Alabama), (AK, Alaska), (AZ, Arizona), #and so f…

How to print a table from a text file and fill empty spaces?

I have the following table in a txt file:|Client | Container weight | Country of Origin | Product code ||S4378 | 450 Ton | China | 457841 || | 350 Ton | Japan…

Open a file in python from 2 directory back

I want to read a file from 2 folders back.. with open(../../test.txt, r) as file:lines = file.readlines()file.close()I want to read from ../../ two folders back. but not work.. How i can do that ?

Do string representations of dictionaries have order in Python 3.4?

I know dictionaries themselves in Python do not have order. However, Im rather curious if when you call str() on a dictionary if it is always in the same order. It appears to be sorted (by key), no mat…

BeautifulSoup Scraping Results not showing

I am playing around with BeautifulSoup to scrape data from websites. So I decided to scrape empireonlines website for 100 greatest movies of all time. Heres the link to the webpage: https://www.empireo…

How to verify username and password from CSV file in Python?

I am doing a Python project where I have to verify my username and password from a csv file where the first two rows and columns have the username and password as hi.Current Code: answer = input("…