Implementing python slice notation

前端 未结 6 660
轻奢々
轻奢々 2021-02-07 05:06

I\'m trying to reimplement python slice notation in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is,

6条回答
  •  我寻月下人不归
    2021-02-07 05:42

    I can't say there's no bug in the codes, but it had past your test program :)

    def mySlice(L, start=None, stop=None, step=None):
        ret = []
        le = len(L)
        if step is None: step = 1
    
        if step > 0: #this situation might be easier
            if start is None: 
                start = 0
            else:
                if start < 0: start += le
                if start < 0: start = 0
                if start > le: start = le
    
            if stop is None: 
                stop = le
            else:
                if stop < 0: stop += le
                if stop < 0: stop = 0
                if stop > le: stop = le
        else:
            if start is None:
                start = le-1
            else:
                if start < 0: start += le
                if start < 0: start = -1
                if start >= le: start = le-1
    
            if stop is None: 
                stop = -1 #stop is not 0 because we need L[0]
            else:
                if stop < 0: stop += le
                if stop < 0: stop = -1
                if stop >= le: stop = le
    
        #(stop-start)*step>0 to make sure 2 things: 
        #1: step != 0
        #2: iteration will end
        while start != stop and (stop-start)*step > 0 and start >=0 and start < le:
            ret.append( L[start] )
            start += step
    
        return ret
    

提交回复
热议问题