Simple python solution


  • 1
        def calPoints(self, ops):
            point_list = []
            for op in ops:
                if op == '+':
                    point_list.append(sum(point_list[-2:]))
                elif op == 'C':
                    if point_list:
                        del point_list[-1]
                elif op == 'D':
                    if point_list:
                        point_list.append(point_list[-1] * 2)
                else:
                    point_list.append(int(op))
    
            return sum(point_list)
    

  • 1

    Could sum over a slice, much shorter:

            if op == '+':
                point_list.append(sum(point_list[-2:]))
    

    Python is friendly and does the intended thing without complaining:

    >>> [1, 2, 3, 4][-2:]
    [3, 4]
    >>> [1][-2:]
    [1]
    >>> [][-2:]
    []
    

  • 0

    Thanks a lot Stefan, this is awesome, Java complains on indexes a lot.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.