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]
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
176
广告