In: Computer Science
Python...Count the number of times a element of list1
occurs in in list2
list1 = ['a', 'b', 'c','e','j'];
list2 = ['a', 'c', 'd', 'b','e','z'];
{'a': 1, 'c': 1, 'b': 1, 'e': 1, 'j': 0}
How do I get to this to work without the Collections counter?
Code Explanation:
1. Define two list list1 and list2
2. Create an empty dictionary res = {}
3. run a for loop i = 0 to length of list1
4. initialize count = 0
5. run a for loop from j = 0 to length of list2
6. Check whether the element of list1 is equal to list2. If yes increment count
7. After every element in list2 is checked inner loop exists. Then add that key and
count to dictionary res
8. The loop will check similarly for all elements in list1. and adds the keys and count to res
9. print the res.
Code:
list1 = ['a', 'b','c','e','j']
list2 = ['a','c','d','b','e','z']
res ={}
for i in range(len(list1)):
count = 0
for j in range(len(list2)):
if(list1[i] == list2[j]):
count = count+1
res[list1[i]] = count
print(res)
O/P:
{'a': 1, 'b': 1, 'c': 1, 'e': 1, 'j': 0}
Execution screenshot for the above code:
Sample O/P when
list1 = ['a', 'b','c','e','j']
list2 = ['a','c','a','d','e','b','e','z']
(If you still have any doubts regarding this answer please comment I will definitely help)