Question

from typing import List def longest_chain(submatrix: List[int]) -> int: """ Given a list of integers, return...

from typing import List


def longest_chain(submatrix: List[int]) -> int:
"""
Given a list of integers, return the length of the longest chain of 1's
that start from the beginning.

You MUST use a while loop for this! We will check.

>>> longest_chain([1, 1, 0])
2
>>> longest_chain([0, 1, 1])
0
>>> longest_chain([1, 0, 1])
1
"""
i = 0
a = []
while i < len(submatrix) and submatrix[i] != 0:
a.append(submatrix[i])
i += 1
return sum(a)


def largest_rectangle_at_position(matrix: List[List[int]], x: int, y: int
) -> int:
"""
Returns the area of the largest rectangle whose top left corner is at
position <x>, <y> in <matrix>.

You MUST make use of <longest_chain> here as you loop through each row
of the matrix. Do not modify the input matrix.

>>> case1 = [[1, 0, 1, 0, 0],
... [1, 0, 1, 1, 1],
... [1, 1, 1, 1, 1],
... [1, 0, 0, 1, 0]]
>>> largest_rectangle_at_position(case1, 0, 0)
4
>>> largest_rectangle_at_position(case1, 2, 0)
5
>>> largest_rectangle_at_position(case1, 1, 2)
6
"""
i = x + 1
if longest_chain(submatrix_row) > 1:
submatrices_row.append(submatrix_row)
while i < len(matrix):
submatrix_row = matrix[i][y:]
i += 1
if longest_chain(submatrix_row) > 1:
matrices_row.append(submatrix_row)
else:
for mat in submatrices_row:
if len(mat) == len(submatrices_row[0]):
area += sum(mat)
else:
return area
else:
submatrix_col = []
i = x
while i < len(matrix) and matrix[i][y] != 0:
submatrix_col.append(matrix[i][y])
i += 1
if longest_chain(submatrix_col) > 1:
area = sum(submatrix_col)
return area


def largest_rectangle_in_matrix(matrix: List[List[int]]) -> int:
"""
Returns the area of the largest rectangle in <matrix>.

The area of a rectangle is defined as the number of 1's that it contains.

Again, you MUST make use of <largest_rectangle_at_position> here. If you
managed to code largest_rectangle_at_position correctly, this function
should be very easy to implement.

Similarly, do not modify the input matrix.

Precondition:
<matrix> will only contain the integers 1 and 0.

>>> case1 = [[1, 0, 1, 0, 0],
... [1, 0, 1, 1, 1],
... [1, 1, 1, 1, 1],
... [1, 0, 0, 1, 0]]
>>> largest_rectangle_in_matrix(case1)
6
"""

pass

write the body of the function with the word pass

Homework Answers

Answer #1

Code Screenshot :

Executable Code:

from typing import List

#Required function
def longest_chain(submatrix: List[int]) -> int:
   x = 0
   temp = []
   while x<len(submatrix) and submatrix[x] != 0:
       temp.append(submatrix[x])
       x += 1
   #Return the sum
   return sum(temp)


#Testing and Result


print(longest_chain([1, 1, 0]))
print(longest_chain([0, 1, 1]))
print(longest_chain([1, 0, 1]))
print()

Sample Output :

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
def count_evens(values: List[List[int]]) -> List[int]: """Return a list of counts of even numbers in each of...
def count_evens(values: List[List[int]]) -> List[int]: """Return a list of counts of even numbers in each of the inner lists of values.    >>> count_evens([[10, 20, 30]]) [3] >>> count_evens([[1, 2], [3], [4, 5, 6]]) [1, 0, 2] """   
Which of the following strings P is a Python program. (b) P = “def f(x): x...
Which of the following strings P is a Python program. (b) P = “def f(x): x = 'am I a Python program?'” (d) P = “def f(x,y,z): return y” (e) P = “def f(x): return y” For each of the following Python programs P and input strings I, give the output P(I), (f) P = “def f(x): return str(len(x+x+'x'))”, I = “GAGAT” (g) P = “def f(x): return str(len(x))”, I=P (h) P = “def f(x): return str(1/int(x))”, I = “0”
import pandas as pd import numpy as np import matplotlib.pyplot as plt mtcars = pd.read_csv("mtcars.csv", index_col...
import pandas as pd import numpy as np import matplotlib.pyplot as plt mtcars = pd.read_csv("mtcars.csv", index_col = 0) mtcars x = mtcars["hp"] y = mtcars["mpg"] plt.plot(x,y,"*") plt.grid(True) plt.xlabel("Horse Power") plt.ylabel("Miles per Gallon") plt.show() def standardize(x): return (x-x.mean())/x.std(), x.mean(), x.std() x, muX, stdX = standardize(x) y, muY, stdY = standardize(y) if len(x.shape) == 1: num_var = 1 else: num_var = x.shape[1] beta0 = np.random.rand() beta1 = np.random.rand() def predict(x, beta0, beta1): return beta0 + beta1*x def loss(y, ypred): return np.mean((y-ypred)**2)/2 def...
# Parts to be completed are marked with '<<<<< COMPLETE' import random N = 8 MAXSTEPS...
# Parts to be completed are marked with '<<<<< COMPLETE' import random N = 8 MAXSTEPS = 5000 # generates a random n-queens board # representation: a list of length n the value at index i is # row that contains the ith queen; # exampe for 4-queens: [0,2,0,3] means that the queen in column 0 is # sitting in row 0, the queen in colum 1 is in row, the queen in column 2 # is in row 0,...
#Constructor def tree(label, branches=[]): for branch in branches: assert is_tree(branch) return [label] + list(branches) #Selectors def...
#Constructor def tree(label, branches=[]): for branch in branches: assert is_tree(branch) return [label] + list(branches) #Selectors def label(tree): return tree[0] def branches(tree): return tree[1:] def is_tree(tree): if type(tree) != list or len(tree) < 1: return false return True def is_leaf(tree): return not branches(tree) def print_tree(t, indent=0):    print(' ' * indent + str(label(t))) for b in branches(t): print_tree(b, indent + 1) Write a function that takes in a tree and doubles every value. It should return a new tree. You can...
convert this code to accept int value instead of float values using python. Make sure to...
convert this code to accept int value instead of float values using python. Make sure to follow the same code. do not change the steps and make sure to point to what code you replaced. make sure to have 2 files Method:----------------------- #define a python user difined method def get_float_val (prompt): is_num = False str_val = input (prompt) #prming read for our while #while is_num == False: (ignore this but it works) old school while not is_num: try: value =...
Implement the following functions in the given code: def random_suit_number(): def get_card_suit_string_from_number(n): def random_value_number(): def get_card_value_string_from_number(n):...
Implement the following functions in the given code: def random_suit_number(): def get_card_suit_string_from_number(n): def random_value_number(): def get_card_value_string_from_number(n): def is_leap_year(year): def get_letter_grade_version_1(x): def get_letter_grade_version_2(x): def get_letter_grade_version_3(x): Pay careful attention to the three different versions of the number-grade-to-letter-grade functions. Their behaviors are subtly different. Use the function descriptions provided in the code to replace the pass keyword with the necessary code. Remember: Parameters contain values that are passed in by the caller. You will need to make use of the parameters that each...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String courseName;     private String[] students = new String[1];     private int numberOfStudents;     public COurseCom666(String courseName) {         this.courseName = courseName;     }     public String[] getStudents() {         return students;     }     public int getNumberOfStudents() {         return numberOfStudents;     }     public void addStudent(String student) {         if (numberOfStudents == students.length) {             String[] a = new String[students.length + 1];            ...
int main() { while (1) { float d; scanf("%f", &d); float x; for (x = d;...
int main() { while (1) { float d; scanf("%f", &d); float x; for (x = d; x <= d + 1000.0; x = x + 1000.0) { } printf("loop exited with x = %.14g\n", x); } return 0; } If you run the program, you will see. What number should I use as an input to make this an infinite loop?
in C++ Please and thanks Here is a list of 6 numbers. Use the selection sort...
in C++ Please and thanks Here is a list of 6 numbers. Use the selection sort algorithm to sort this list. Fill in this table with each iteration of the loop in the selection sort algorithm. Mark the place from which you are looking for the 'next smallest element'. In this display, the upper numbers are the indices, the lower numbers are in the corresponding positions. Use the several rows provided to show the sequence of steps. 0 1 2...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT