简体   繁体   English

有没有更好的pythonic方法来重写while循环?

[英]Is there a better pythonic way to rewrite the while loop?

I wrote this function to do the strStr function:我写了这个 function 来做 strStr function:

def strStr(haystack: str, needle: str) -> int:
    if not needle:
        return 0

    len_h = len(haystack)
    len_n = len(needle)

    if len_n > len_h:
        return -1

    index_h = 0
    index_n = 0
    matched_count = 0
    while index_h < len_h and index_n < len_n:
        v_h = haystack[index_h]
        v_n = needle[index_n]
        if v_h != v_n:
            index_h = index_h - matched_count + 1
            index_n = 0
            matched_count = 0
        else:
            index_h += 1
            index_n += 1
            matched_count += 1

        if index_n == len_n:
            return (index_h - len_n)

    return -1


print(strStr('hello', 'll'))
print(strStr('mississippi', 'issip'))

The while loop is the C or Java way. while 循环是 C 或 Java 方式。 I tried to use for... in range in Python.我尝试在 Python 的范围内使用 for...。 But failed to do it, because I need to update the indexes based on conditions.但没能做到,因为我需要根据条件更新索引。 The for loop in Python doesn't seem to work. Python 中的 for 循环似乎不起作用。 Still, is there a python way to replace the while loop?不过,是否有 python 方法来替换 while 循环?

Python has a string method.find() that's implemented using the Boyer-Moore method ( https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm ). Python 有一个使用 Boyer-Moore 方法( https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_al )实现的字符串 method.find()。

This contains a couple of while loops.这包含几个 while 循环。 So I would say it's a reasonably pythonic way to do it.所以我会说这是一种合理的pythonic方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM