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,...
Python program please no def, main, functions Given a list of negative integers, write a Python...
Python program please no def, main, functions Given a list of negative integers, write a Python program to display each integer in the list that is evenly divisible by either 5 or 7. Also, print how many of those integers were found. Sample input/output: Enter a negative integer (0 or positive to end): 5 Number of integers evenly divisible by either 5 or 7: 0 Sample input/output: Enter a negative integer (0 or positive to end): -5 -5 is evenly...
#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]
import kotlinx.coroutines.* // TODO 1 fun sum(valueA: Int, valueB: Int): Int {     return 0 }...
import kotlinx.coroutines.* // TODO 1 fun sum(valueA: Int, valueB: Int): Int {     return 0 } // TODO 2 fun multiple(valueA: Int, valueB: Int): Int {     return 0 } fun main() = runBlocking {     println("Counting...")     val resultSum = async { sum(10, 10) }     val resultMultiple = async { multiple(20, 20) }     // TODO 3     println() } TODO 1: Change it to suspend function with the following conditions: Has a waiting time of 3 seconds...
" line 48"     return delta.days     ^ SyntaxError: 'return' outside function import datetime def nowDate():...
" line 48"     return delta.days     ^ SyntaxError: 'return' outside function import datetime def nowDate():     current_time = datetime.datetime.now()     new_time = datetime.datetime(         current_time.year,         current_time.month,         current_time.day,         0,         0,         0,         )     return new_time def plusOneDay(daytime):     tomorrow = daytime + datetime.timedelta(days=1)     return tomorrow def nDaystoHoliday():     NJCU_holidays = [         (datetime.date(2019, 1, 1), "New Year's Day"),         (datetime.date(2019, 1, 21), 'Martin Luther King, Jr. Day'),         (datetime.date(2019, 2, 19), "President's Day"),...
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 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)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT