python in leecode - questions 1 and 7

 

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int] nums=[2,7,11,15],target=9
        :type target: int
        :rtype: List[int]
        """
        hashmap={}
        for index,num in enumerate(nums):
            another_num=target-num
            if another_num in hashmap:
                return [hashmap[another_num],index]
            hashmap[num]=index
        return None

Notes:

1,enumerate Usage: I don't know his cycle here nummerate(nums)Can we take it out key and value

>>> a=[2,3]
>>> b=enumerate(a)
>>> b
<enumerate object at 0x00000000031C6750>
>>> list(b)
[(0, 2), (1, 3)]
>>>

2,Thought is in[2,7,11,15]Take out the first value and put it in the hashmap Li Yong target9 Subtract the second value if hashmap The existence of this difference in 2+7=9,And put this hashmap Li key-value Lose out.

 

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x<0:
            tmp=-int(str(-x)[::-1])       
        else :
            tmp=int(str(x)[::-1])
        if tmp>=-2**31 and tmp<=2**31-1:
            return tmp
        else:
            return 0

 

Seventh questions

1. The usage of [:: - 1] is actually to reverse the string... That's how it's understood

>>> x
-123
>>> str(x)
'-123'
>>> b=str(x)
>>> b[::-1]
'321-'
>>> x
-123
>>> x=-x
>>> x
123
>>> str(x)
'123'
>>> b=str(x)
>>> b
'123'
>>> b[::-1]
'321'
>>>

 

2. Two loops. The first is to find the reverse order of all numbers. The second loop is to output the value after the condition range is met, not in the range return 0

 

 

 

Conclusion: MLGB, there is something about the legendary leecode. Who knows that it can find a job? But I want to know what mechanism it is to judge whether the code I uploaded is right or not.

Tags: Python

Posted on Wed, 04 Dec 2019 11:06:38 -0800 by slough