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',...
def num_to_digit_rec(num, base): """ Return a list of digits for num with given base; Return an...
def num_to_digit_rec(num, base): """ Return a list of digits for num with given base; Return an empty list [] if base < 2 or num <= 0 """ # Write your code here return [] def digit_sum(num, base): """ Return the sum of all digits for a num with given base Your implementation should use num_to_digit_rec() function """ # Write your code here return 0 def digit_str(num, base): """ Given a number and a base, for base between [2, 36]...
def largest_rectangle_in_matrix(matrix: List[List[int]]) -> int: """ Returns the area of the largest rectangle in <matrix>. The...
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,...
#Write a program in Python that given a list of positive integers, return another list where...
#Write a program in Python that given a list of positive integers, return another list where each element corresponds to the sum of the digits of the elements o#f the given list. #Example: # input # alist=[124, 5, 914, 21, 3421] # output # sum=[7, 5, 14, 3, 18]
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)"...
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...
Given a linked list of integers, remove any nodes from the linked list that have values...
Given a linked list of integers, remove any nodes from the linked list that have values that have previously occurred in the linked list. Your function should return a reference to the head of the updated linked list. (In Python)
import random #the menu function def menu(list, question): for entry in list: print(1 + list.index(entry),end="") print(")...
import random #the menu function def menu(list, question): for entry in list: print(1 + list.index(entry),end="") print(") " + entry) return int(input(question)) plz explain this code
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)) ;
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT