230k views
4 votes
Sublist(xs, total)'

Description: It finds the smallest square-size sublist of a 2D list xs that the sum of its values is greater than or equal to total. Minimum size of a sublist is 2x2. If there are more than one equally sized sublists that satisfy the requirements, it returns the one with the largest sum.
If no sublist satisfies the requirements it returns False.

Parameters: xs (list of list of int), total (int). You’re not allowed to modify xs.
Return value: a square size list of list of int
Example:
sublist([[0,1,2], [-4,5,6), [7,8,3]],5) → [[5,6],[8,3]]
sublist([[0,1,2], [-4,5,6], [7,8,3]], 23) → [[0,1,2], [-4,5,6],[7,8,3]]

Code this in python 3.
•Built-in functions: range(),len(),int(),str()
•list methods: .append(), .insert()
•Not allowed to use slicing
•allowed to use the del operator

User Shuriquen
by
5.6k points

1 Answer

0 votes

Answer:

# ths functionfind a sub matrix from the list

def findSubMatrix(xs, startR, startC, size):

# an empty list named data is initialized

data = []

for i in range(startR, startR+size):

row = []

for j in range(startC, startC+size):

row.append(xs[i][j])

data.append(row)

return data

# this function find the sum of each list in the matrix

def FindSum(matrix):

# s represent the sum and is initialized to 0

s = 0

# loop through the matrix

# sum each list and add to s

for m in matrix:

s += sum(m)

# the value of s is returned

return s

# this function return a sublist

def sublist(xs, total):

# length of entire list is assigned to r

r = len(xs)

# length of first list is assigned to c

c = len(xs[0])

# for loop that loop from 2 to least value between r and c

for size in range(2, min(r, c) + 1):

# None is first assigned to result

result = None

for startR in range(0, r-size+1):

for startC in range(0, c-size+1):

d = findSubMatrix(xs, startR, startC, size)

# findSum is use to compute the sum of d

s = FindSum(d)

# if s is greater than total

# and if result is None or the sum of result is less than s

# d is assigned to result

if s > total:

if result is None or FindSum(result) < s:

result = d

# if result is not None, it is returned

if result is not None:

return result

return None

# the sublist function is called having two parameter

# a list of list of integer and a total

print(sublist([[0,1,2], [-4,5,6], [7,8,3]], 5))

print(sublist([[0,1,2], [-4,5,6], [7,8,3]], 23))

Step-by-step explanation:

The program is written in Python and well commented. An image showing the output of the program when executed is attached.

Sublist(xs, total)' Description: It finds the smallest square-size sublist of a 2D-example-1
User Shreyash Mishra
by
5.8k points