Python程式,如何求列表中每個元素所有拼接對的和?\n
假設我們有一個名為 nums 的數字列表。我們需要找到 nums 中每對數字的所有拼接組合的總和。這裡,(i, j) 和 (j, i) 被視為不同的對。
因此,如果輸入類似於 nums = [5, 3],則輸出將為 176,因為我們有以下拼接組合:(nums[0] + nums[0]) = (5 拼接 5) = 55,(nums[0] + nums[1]) = (5 拼接 3) = 53,(nums[1] + nums[0]) = (3 拼接 5) = 35,(nums[0] + nums[0]) = (3 拼接 3) = 33,然後總和為 55 + 53 + 35 + 33 = 176
為了解決這個問題,我們將遵循以下步驟
memo := a new map nums1 := nums temp := 0 c := sum of all elements in nums1 a := size of nums for i in range 0 to a, do if nums[i] is same as 0, then temp := temp + c otherwise, if nums[i] is present in memo, then temp := temp + memo[nums[i]] otherwise, b := 0 for j in range 0 to a, do b := b + integer of (nums[i] concatenate nums1[j]) memo[nums[i]] := b temp := temp + memo[nums[i]] return temp
讓我們看看下面的實現來更好地理解
示例
class Solution:
def solve(self, nums):
memo = {}
nums1 = nums
temp = 0
c = sum(nums1)
a = len(nums)
for i in range(a):
if nums[i] == 0:
temp += c
else:
if nums[i] in memo:
temp += memo[nums[i]]
else:
b = 0
for j in range(a):
b += int(str(nums[i]) + str(nums1[j]))
memo[nums[i]] = b
temp += memo[nums[i]]
return temp
ob = Solution()
nums = [5, 3]
print(ob.solve(nums))輸入
[5, 3]
輸出
176
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP