160k views
2 votes
Implement the function create_prefix_lists(list) that will return a sequence of lists, each containing a prefix of list. All the lists should be collected as one big list. For example, for [2, 4, 6, 8, 10] the function should return [[], [2], [2, 4], [2, 4, 6], [2, 4, 6, 8], [2, 4, 6, 8, 10]]. Note: recursion can not be used for this solution, if you are familiar with the concept.

2 Answers

3 votes

Answer:

See Explaination

Step-by-step explanation:

code below

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

public class Prefix_test_check {

public static void create_prefix_lists(List elementList) {

if (elementList.size() > 0) {

Collections.sort(elementList);

List newArrayList = new ArrayList();

newArrayList.add("[");

System.out.print(newArrayList);

System.out.print(",");

newArrayList.clear();

int counterDataObj = 0;

for (int iObjectData = 0; iObjectData < elementList.size(); iObjectData++) {

newArrayList.add(elementList.get(iObjectData));

counterDataObj++;

if (counterDataObj == elementList.size()) {

System.out.print(newArrayList);

System.out.print("]");

} else {

System.out.print(newArrayList);

if (counterDataObj != elementList.size()) {

System.out.print(",");

}

}

}

} else {

List emptyDataList = new ArrayList();

emptyDataList.add("]");

System.out.print(emptyDataList);

}

}

public static void main(String args[]) {

List elementList = new ArrayList();

elementList.add(2);

elementList.add(4);

elementList.add(6);

elementList.add(8);

elementList.add(10);

create_prefix_lists(elementList);

}

}

User WeeniehuahuaXD
by
4.9k points
1 vote

Answer:

The below code was written in Python language, kindly let me know if you'll want to see the implementation done in another language.

Step-by-step explanation:

As python is tab specific, you need align the as per the screenshot of the code that I have attached below the code and text version of the code is also provided.

Code:

======

result = []

def create_prefix_lists(lst):

for i in range(len(lst)):

l = []

for j in range(i):

l.append(lst[j])

result.append(l)

result.append(lst)

return result

lis = [2,4,6,8,10]

print create_prefix_lists(lis)

Code indentation screen and code output can be seen in the attached images below:

====================

Implement the function create_prefix_lists(list) that will return a sequence of lists-example-1
Implement the function create_prefix_lists(list) that will return a sequence of lists-example-2
User Allen Pike
by
4.1k points