This is the exercise:
*Write a maximum_sequences function that receives two positive integers n and k and a list L1 of integers having length n * k and returns a list L2 of length k constructed as follows:
- we consider the n non-overlapping sub-lists of k elements in L1;
-element L2 [j] contains the maximum of the elements found in position j in the sub-lists.
Example: If n = 4, k = 3 and L1 = [7, 4, 7, 3, 6, 8, 9, 1, 5, 6, 2, 5], then:
-the non-overlapping sublists of 3 elements in L1 are [7, 4, 7], [3, 6, 8], [9, 1, 5] and [6, 2, 5]; - L2 [0] = 9 because the elements in position 0 in the sub-lists are 7, 3, 9 and 6;
- L2 [1] = 6 because the elements in position 1 in the sub-lists are 4, 6, 1 and 2;
- L2 [2] = 8 because the elements in position 2 in the sub-lists are 7, 8, 5 and 5.*
Im stuck here:
def verify_list(n,k,Ll):
if len(Ll) != n*k:
raise SystemError
else:
return Ll
def max_sequenze(n,k,L1):
x = verify_list(n,k,L1)
sub_liste = []
l2 = []
for i in range(0, len(x),k):
sub_liste.append(x[i:i+k])
How you can see i created the sub-arrays and the len check, but I have no idea how to build the L2 array (without Numpy).
tnx
>Solution :
The building of L2 can be done using another for loop. Loop through each index of a sublist, and find the maximum of all the elements at that index in all the sublists.
Something that will help here is the construction of an array for each of the sub_liste[i] elements that are being considered.
In the case where the first element of each sublist is considered, this can be done using this:
[a[0] for a in sub_liste]
Thereby building L2 can be done as shown:
for i in range(k):
l2.append(max([a[i] for a in sub_liste]))