Question

In: Computer Science

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 , in .

You MUST make use of 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
"""

pass

replace the word pass with a function body by implementing the 1st function. make sure nested loops can be a max of 3. try to keep it as short as possible and fulfill the docstring requirements

Solutions

Expert Solution

from typing import List


def longest_chain(submatrix : List[int]) ->int:
    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:
    temp = []
    # calculating the longest chain
    for i in range(x, len(matrix)):
        temp.append( longest_chain(matrix[i][y:]))
    max = 0
    # longest chain will not be longer than first element of temp Array
    # it can be less but not more than that
    firstMax = temp[0]
    for elem in set(temp):
        # if elem is more then we should not move further
        if elem > firstMax :
            continue
        # calculating count
        cnt = 0
        for i in range(len(temp)):
            if elem <= temp[i]:
                cnt += 1
        # calculating max
        if max < cnt * elem:
            max = cnt * elem

    return max


case1 = [
    [1, 0, 1, 0, 0],
    [1, 0, 1, 1, 1],
    [1, 1, 1, 1, 1],
    [1, 0, 0, 1, 0]
]

print(largest_rectangle_at_position(case1, 0, 0))
print(largest_rectangle_at_position(case1, 2, 0))
print(largest_rectangle_at_position(case1, 1, 2))
print(largest_rectangle_at_position(case1, 1, 4))

Code

Output


Related Solutions

from partition import partition def quicksort(a: list, l: int, u: int) -> None: '''Sort the given...
from partition import partition def quicksort(a: list, l: int, u: int) -> None: '''Sort the given list a in non-descending order. Precondition: 0 <= l and u < len(a)''' if l < u: mid = (l + u) // 2 three = [a[l], a[mid], a[u]] three.sort() if three[1] == a[l]: pivot_loc = l elif three[1] == a[u]: pivot_loc = u else: pivot_loc = mid a[u], a[pivot_loc] = a[pivot_loc], a[u] pivot = a[u] i = partition(a, l, u - 1, pivot)...
def warmer_year(temps_then: List[int], temps_now: List[int]) -> List[str]: """Return a list of strings representing whether this year's...
def warmer_year(temps_then: List[int], temps_now: List[int]) -> List[str]: """Return a list of strings representing whether this year's temperatures from temps_now are warmer than past temperatures in temps_then. The resulting list should contain "Warmer" at the indexes where this year's temperature is warmer, and "Not Warmer" at the indexes where the past year was warmer, or there is a tie. Precondition: len(temps_then) == len(temps_now) >>> warmer_year([10], [11]) ['Warmer'] >>> warmer_year([26, 27, 27, 28], [25, 28, 27, 30]) ['Not Warmer', 'Warmer', 'Not Warmer',...
Qno.1 Part(A). IN jAVA if 1.Int abc; 2. Int def = 8; 3. abc = def;...
Qno.1 Part(A). IN jAVA if 1.Int abc; 2. Int def = 8; 3. abc = def; ➢ Describe the procedure how much memory will be allocated when these three lines of codes will execute. ➢ Describe what will happened after execution of each of these line of code in term of memory allocation and data storage Qno.1 Part(B) A capacitor is constructed from two conductive metal plates 30cm x 50cm which are spaced 6mm apart from each other, and uses...
from PIL import Image def stringToBits(string):     return str(bin(int.from_bytes(string.encode(), 'big')))[2:] def bitsToString(bits):     if bits[0:2] != '0b':         bits.
from PIL import Image def stringToBits(string):     return str(bin(int.from_bytes(string.encode(), 'big')))[2:] def bitsToString(bits):     if bits[0:2] != '0b':         bits = '0b' + bits     value = int(bits, 2)     return value.to_bytes((value.bit_length() + 7) // 8, 'big').decode() def writeMessageToRedChannel(file, message):     image = Image.open(file)     width, height = image.size     messageBits = stringToBits(message)     messageBitCounter = 0     y = 0     while y < height:         x = 0         while x < width:             r, g, b, a = image.getpixel((x, y))             print("writeMessageToRedChannel: Reading pixel %d, %d - Original values (%d, %d, %d, %d)"...
Given the method static int test(int x, int y, int z){ return(x=y+z); } Which of the...
Given the method static int test(int x, int y, int z){ return(x=y+z); } Which of the follwing is true: public static void main(String[] args) { A System.out.println(test ( 7, 14, 23)) ; B System.out.println(test ( test ( 7,9, 14) , 23 ); C System.out.println( test ( 14, 23 ) ; D System.out.println(test(1,2,4), 14, 23)) ;
import java.io.*; import java.util.Scanner; class Node { int data; Node next; Node(int d){ // Constructor   ...
import java.io.*; import java.util.Scanner; class Node { int data; Node next; Node(int d){ // Constructor    data = d;    next = null; } } class ACOLinkedList {// a Singly Linked List    Node head; // head of list    public void insert(int data){ // Method to insert a new node        Node new_node = new Node(data); // Create a new node with given data        new_node.next = null;        if (head == null) // If the...
import java.io.*; import java.util.Scanner; class Node { int data; Node next; Node(int d){ // Constructor   ...
import java.io.*; import java.util.Scanner; class Node { int data; Node next; Node(int d){ // Constructor    data = d;    next = null; } } class ACOLinkedList {// a Singly Linked List    Node head; // head of list    public void insert(int data){ // Method to insert a new node        Node new_node = new Node(data); // Create a new node with given data        new_node.next = null;        if (head == null) // If the...
import java.io.*; import java.util.Scanner; class Node { int data; Node next; Node(int d){ // Constructor   ...
import java.io.*; import java.util.Scanner; class Node { int data; Node next; Node(int d){ // Constructor    data = d;    next = null; } } class ACOLinkedList {// a Singly Linked List    Node head; // head of list    public void insert(int data){ // Method to insert a new node        Node new_node = new Node(data); // Create a new node with given data        new_node.next = null;        if (head == null) // If the...
import java.util.*; class A { int i, j, k; public A(int i, int j, int k)...
import java.util.*; class A { int i, j, k; public A(int i, int j, int k) { this.i=i; this.j=j; this.k=k; } public String toString() { return "A("+i+","+j+","+k+")"; } } class Main { public static void main(String[] args) { ArrayList<A> aL=new ArrayList<A>(); Random rand= new Random(1000); //1000 is a seed value for (int p=0; p<10; p++) { int i = rand.nextInt(100); int j = rand.nextInt(200); int k = rand.nextInt(300); aL.add(new A(i, j, k)); } System.out.println("----- Original arraylist------"); for (A a: aL)...
PYTHON PROBLEM: TASKED TO FIND THE FLAW WITH THE FOLLOWING CODE: from itertools import count def...
PYTHON PROBLEM: TASKED TO FIND THE FLAW WITH THE FOLLOWING CODE: from itertools import count def take_e(n, gen):     return [elem for (i, elem) in enumerate(gen) if i < n] def take_zc(n, gen):     return [elem for (i, elem) in zip(count(), gen) if i < n] FIBONACCI UNBOUNDED: def fibonacci_unbounded():     """     Unbounded Fibonacci numbers generator     """     (a, b) = (0, 1)     while True:         # return a         yield a         (a, b) = (b, a + b) SUPPOSED TO RUN THIS TO ASSIST WITH...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT