python为什么用两个等于号_刷Leetcode学python(一)两数之和
本代碼來自好友詹神公眾號《小詹學python》
原題:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
題目大意:
給出一個數字列表和一個目標值(target),假設列表中有且僅有兩個數相加等于目標值,我們要做的就是找到這兩個數,并返回他們的索引值。
例如:
方法一:兩層循環
def twoSum(nums, target):
""":type nums: List[int]:type target: int:rtype: List[int]"""
result = []
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
result.append(i)
result.append(j)
return result
我們接著來調用twoSum函數
twoSum([2, 7, 11, 15],9)
可以看到結果是列表的第一個索引和第二個索引的值相加等于9
這個題目,是非常有意義的,我們可以學習到python中如何定義函數、如何傳遞實參、for循環和if語句的結合用法,以及python當中操作列表的方法。
方法二:一層循環
因為我們知道有且僅有一個解;我們可以通過判斷target與某一個元素的差值是否也在列表之中即可,
def secondtwoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = []
for i in range(len(nums)):
oneNum = nums[i]
twoNum = target - oneNum
if twoNum in nums:
j = nums.index(twoNum)
if i != j:
result.append(i)
result.append(j)
return result
同樣,我們傳入實參來調用secondtwoSum函數
同樣可看到結果是列表的第一個索引和第二個索引的值
其相加會等于target的值9
往期精彩回顧
圖片攝于2017年12月24日于江西明月山
總結
以上是生活随笔為你收集整理的python为什么用两个等于号_刷Leetcode学python(一)两数之和的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 辛格林电梯速度有没有1.6,常见的速度是
- 下一篇: 2020京东物流行业的发展趋势 开放战略