iT邦幫忙

2022 iThome 鐵人賽

DAY 6
0

題目(6kyu):

Write a function that takes an array of numbers (integers for the tests) and a target >number. It should find two different items in the array that, when added together, give >the target value. The indices of these items should then be returned in a tuple / list >(depending on your language) like so: (index1, index2).

For the purposes of this kata, some tests may have multiple answers; any valid >solutions will be accepted.

The input will always be valid (numbers will be an array of length 2 or greater, and >all of the items will be numbers; target will always be the sum of two different items >from that array).

two_sum([1, 2, 3], 4) # returns [0, 2] or [2, 0]

解題思路

題目理解:給定目標數字target,並從列表number中找到兩元素x&y之和等於該數,並回傳x&y在列表中的位置索引。


def two_sum(numbers :list, target :int):
    #逐一將目標數字減去列表中元素i,檢查是否有對應值存在於列表中
    for i in numbers:
        another_num = target - i
        if another_num in numbers: 
            if another_num == i:
            #若該對應值與元素i相等(即x=y),可先利用list.index()找到第一個元素值
               x = numbers.index(i)
               #再利用list.pop()刪除x在number中位置
               numbers.pop(x)
               #則下次再用index時找到的位置加上1後,即為y原本存在於列表中位置
               y = numbers.index(i)+1
               return (x,y)
            else:
                return  numbers.index(i),numbers.index(another_num)

上一篇
[Day5] Codewars >>>Take a Number And Sum Its Digits Raised To The Consecutive Powers (Python)
下一篇
[Day7] Codewars >>> Number of trailing zeros of N!(Python)
系列文
Udemy課程上完你也可以開始Codewars 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言