我为什么要为此获得KeyError?

发布于 2025-02-13 05:41:12 字数 1330 浏览 2 评论 0原文

问题是: 给定一个包含0和1s的数组,如果允许您用1s替换不超过“ K” 0,请找到具有所有1s的最长连续子阵列的长度。

输入:array = [0、1、1、0、0、0、1、1、0、1、1],k = 2 输出:6 说明:在索引5和8处替换“ 0”,具有1s的最长连续子阵列,长度为6。

def length_of_longest_substring(arr, k):
    '''
    Create a hashmap that records the values of 0 and 1, initialize them to 0. Do a sliding 
    window.
    WHILE the frequency of 0 is greater than k, subtract arr[windowStart] from HM and then 
    increment 
    wS.
    Use the max function to record longest substring length. Return that.
    '''

    hm = {'0': '0', '1': '0'}
    (windowStart, longest) = (0, 0)
    for windowEnd in range(len(arr)):
        right = arr[windowEnd]
        hm[right] = hm.get(right, 0) + 1
        while hm["0"] > k:
            hm[arr[windowStart]] -= 1
            windowStart += 1
        longest = max(longest, windowEnd - windowStart + 1)
    return longest


def main():
    print(length_of_longest_substring([1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], 2)) 
    #Return 6
    print(length_of_longest_substring([1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1], 3))
    #Return 9
main()

我在hm [hm [0“”]> k中遇到

File "main.py", line 12, in length_of_longest_substring
    while hm["0"] > k:
KeyError: 0

错误使用0开始索引。 我尝试了.get函数。我做了hm.get(“ 0”),同样的错误。 我希望while循环计算0。我该如何实现?预先感谢您,非常感谢。

The problem is:
Given an array containing 0s and 1s, if you are allowed to replace no more than ‘k’ 0s with 1s, find the length of the longest contiguous subarray having all 1s.

Input: Array=[0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], k=2
Output: 6
Explanation: Replace the '0' at index 5 and 8 to have the longest contiguous subarray of 1s having length 6.

def length_of_longest_substring(arr, k):
    '''
    Create a hashmap that records the values of 0 and 1, initialize them to 0. Do a sliding 
    window.
    WHILE the frequency of 0 is greater than k, subtract arr[windowStart] from HM and then 
    increment 
    wS.
    Use the max function to record longest substring length. Return that.
    '''

    hm = {'0': '0', '1': '0'}
    (windowStart, longest) = (0, 0)
    for windowEnd in range(len(arr)):
        right = arr[windowEnd]
        hm[right] = hm.get(right, 0) + 1
        while hm["0"] > k:
            hm[arr[windowStart]] -= 1
            windowStart += 1
        longest = max(longest, windowEnd - windowStart + 1)
    return longest


def main():
    print(length_of_longest_substring([1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], 2)) 
    #Return 6
    print(length_of_longest_substring([1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1], 3))
    #Return 9
main()

I am getting error with "while hm["0"] > k:" it says

File "main.py", line 12, in length_of_longest_substring
    while hm["0"] > k:
KeyError: 0

It works if I replace both starting indices with 0.
I tried the .get function aswell. I did hm.get("0"), same error.
I want the while loop to count the VALUES of 0. How can I achieve that? Thank you in advance, all is very much appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半世晨晓 2025-02-20 05:41:12

我认为您在循环的中误解了逻辑。我已经对其进行了修改,并且错误已修复。

# While the frequency of 0 is greater than k, subtract arr[windowStart] from hm and then increment windowStart.
if hm[0] > k:
    hm[arr[windowStart]] -= 1
    windowStart += 1

# Record longest substring length.
longest = max(longest, windowEnd - windowStart + 1)

# Increment the frequency of arr[windowEnd] in hm.
hm[arr[windowEnd]] += 1

输出:

6
10

I think you got the logic wrong in your for loop. I have modified it and the error got fixed.

# While the frequency of 0 is greater than k, subtract arr[windowStart] from hm and then increment windowStart.
if hm[0] > k:
    hm[arr[windowStart]] -= 1
    windowStart += 1

# Record longest substring length.
longest = max(longest, windowEnd - windowStart + 1)

# Increment the frequency of arr[windowEnd] in hm.
hm[arr[windowEnd]] += 1

Output:

6
10
一紙繁鸢 2025-02-20 05:41:12

您正在比较整数,然后将str转换为int

注意:我不是在解决问题,而是根据问题的要求解决错误。

def length_of_longest_substring(arr, k):
    '''
    Create a hashmap that records the values of 0 and 1, initialize them to 0. Do a sliding 
    window.
    WHILE the frequency of 0 is greater than k, subtract arr[windowStart] from HM and then 
    increment 
    wS.
    Use the max function to record longest substring length. Return that.
    '''

    hm = {'0': '0', '1': '0'}
    (windowStart, longest) = (0, 0)
    for windowEnd in range(len(arr)):
        right = arr[windowEnd]
        hm[right] = hm.get(right, 0) + 1
        while (((int)(hm["0"])) > k):
            hm[arr[windowStart]] -= 1
            windowStart += 1
        longest = max(longest, windowEnd - windowStart + 1)
    return longest


def main():
    print(length_of_longest_substring([1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], 2)) 
    #Return 6
    print(length_of_longest_substring([1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1], 3))
    #Return 9
main()

You are comparing integer and STR convert the STR to int

Note: I am not solving the problem but resolving the error as requested by the question.

def length_of_longest_substring(arr, k):
    '''
    Create a hashmap that records the values of 0 and 1, initialize them to 0. Do a sliding 
    window.
    WHILE the frequency of 0 is greater than k, subtract arr[windowStart] from HM and then 
    increment 
    wS.
    Use the max function to record longest substring length. Return that.
    '''

    hm = {'0': '0', '1': '0'}
    (windowStart, longest) = (0, 0)
    for windowEnd in range(len(arr)):
        right = arr[windowEnd]
        hm[right] = hm.get(right, 0) + 1
        while (((int)(hm["0"])) > k):
            hm[arr[windowStart]] -= 1
            windowStart += 1
        longest = max(longest, windowEnd - windowStart + 1)
    return longest


def main():
    print(length_of_longest_substring([1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], 2)) 
    #Return 6
    print(length_of_longest_substring([1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1], 3))
    #Return 9
main()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文