![]() |
Given a dictionary in python, write a program to find the XOR of all the key-value pairs in the dictionary and return in the form of an array. Note: All the keys and values in the dictionary are integers. Examples: Input : dic={1:3, 4:5, 6:7, 3 :8} Output : [2, 1, 1, 11] Explanation: XOR of all the key-value pairs in the dictionary are [1^3, 4^5, 6^7, 3^8] Thus, [2, 1, 1, 11] Note: Order may change as the dictionary is unordered. Method 1:
Below is the implementation of the above approach Python3
Output
[13, 3, 7, 15] Time complexity: O(n) Method 2:Using items() function Python3
Output
[13, 3, 7, 15] Time complexity: where n is the number of items in the dictionary, because it has to traverse the dictionary once to calculate the XOR of each key-value pair. Method #3 : Using keys() and values() methods Python3
Output
[13, 3, 7, 15] Time complexity: O(n) Method 4: Using a list comprehension Python3
Output
[13, 3, 7, 15] Time complexity: O(n) Method 5:Using the map() function and a lambda function
Code uses the map() function with a lambda function to perform the XOR operation on each key-value pair in the dictionary and store the result in a list. Python3
Output
[13, 3, 7, 15] The items() method is used by the map() function to extract the key-value pairs for each item in the dictionary. The list() method is used to turn iterable that the map() function returns into a list. The list of XOR results is printed last. Time complexity: O(N) as the map() function and the lambda function are both applied to each key-value pair once, which takes O(1) time and there are a total of N key-value pairs. So time complexity is O(N). |
Reffered: https://www.geeksforgeeks.org
Data Structures |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |