Time complexity of string slice

前端 未结 3 1023
粉色の甜心
粉色の甜心 2020-11-30 04:43

What\'s the time complexity of slicing a Python string? Given that Python strings are immutable, I can imagine slicing them being either O(1) or O(n)

3条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 05:12

    Passing around the indices is not so bad if you just pack them in together in an object

    from dataclasses import dataclass
    
    @dataclass
    class StrSlice:
        str: str
        start: int
        end: int
    
    def middle(slice):
        return slice.str[(slice.start + slice.end) // 2]
    
    def reverse(slice):
        return slice.str[slice.start : slice.end][::-1]
    
    def length(slice):
        return slice.end - slice.start
    
    def chars(slice):
        yield from (slice.str[i] for i in range(slice.start, slice.end)
    
    def equals(slice1, slice2):
        if length(slice1) != length(slice2):
            return False
        return all(c1 == c2 for c1, c2 in zip(chars(slice1), chars(slice2))
    

提交回复
热议问题