给定一个包含N个项的字典arr ,其中key和value均为整数类型,任务是查找字典中所有键值对的总和。
例子:
Input: arr = {1: 10, 2: 20, 3: 30}
Output: 11 22 33
Explanation:
Sum of key and value of the first item in the dictionary = 1 + 10 = 11.
Sum of key and value of the second item in the dictionary = 2 + 20 = 22.
Sum of key and value of the third item in the dictionary = 3 + 30 = 33.
Input: arr = {10 : -5, 5 : -10, 100 : -50}
Output: 5 -5 50
使用字典遍历技术的方法:想法是使用for循环遍历字典的键。请按照以下步骤解决问题:
- 初始化一个列表,例如l ,以存储结果。
- 遍历字典arr ,然后将i + arr [i]附加到列表l中。
- 完成上述步骤后,将列表l打印为所需答案。
下面是上述方法的实现:
Python3
# Python3 implementation of
# the above approach
# Function to print the list containing
# the sum of key and value pairs of
# each item of a dictionary
def FindSum(arr):
# Stores the list containing the
# sum of keys and values of each item
l = []
# Traverse the dictionary
for i in arr:
l.append(i + arr[i])
# Print the list l
print(*l)
# Driver Code
arr = {1: 10, 2: 20, 3: 30}
FindSum(arr)
Python3
# Python3 implementation of the above approach
# Function to print the list
# containing the sum of key and
# value pairs from a dictionary
def FindSum(arr):
# Stores the list containing the
# sum of keys and values of each item
l = []
# Traverse the list of keys of arr
for i in arr.keys():
l.append(i + arr[i])
# Print the list l
print(*l)
# Driver Code
arr = {1: 10, 2: 20, 3: 30}
FindSum(arr)
输出:
11 22 33
时间复杂度: O(N)
辅助空间: O(N)
使用keys()方法的方法:解决该问题的另一种方法是使用keys()方法。请按照以下步骤解决问题:
- 初始化一个列表,例如l ,以存储结果。
- 遍历字典arr的键列表,然后追加。
- 完成上述步骤后,将列表l打印为答案。
下面是上述方法的实现:
Python3
# Python3 implementation of the above approach
# Function to print the list
# containing the sum of key and
# value pairs from a dictionary
def FindSum(arr):
# Stores the list containing the
# sum of keys and values of each item
l = []
# Traverse the list of keys of arr
for i in arr.keys():
l.append(i + arr[i])
# Print the list l
print(*l)
# Driver Code
arr = {1: 10, 2: 20, 3: 30}
FindSum(arr)
输出:
11 22 33
时间复杂度: O(N)
辅助空间: O(N)