
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Good Meals with Exactly Two Items in Python
Suppose we have an array deli where deli[i] is the deliciousness of the ith food, we have to find the number of different good meals we can make from this list. If the answer is too large, then return result modulo 10^9 + 7. Here a good meal means a meal that contains exactly two different food items with a sum of deliciousness which is a power of two. We can select any two different foods to make a good meal.
So, if the input is like deli = [1,7,3,6,5], then the output will be 3 because we can make pairs (1,3), (1,7) and (3,5) whose sum is power of 2.
To solve this, we will follow these steps −
- m := 10^9 + 7
- count := a map containing frequency of each deliciousness values
- ans := 0
- for each item i in count, do
- for n in range 0 to 21, do
- j:= (2^n) - i
- if j is in count, then
- if i is same as j, then
- ans := ans + count[i] *(count[i]-1)
- otherwise,
- ans := ans + count[i] * count[j]
- if i is same as j, then
- for n in range 0 to 21, do
- return quotient of (ans/2) mod m
Example
Let us see the following implementation to get better understanding −
from collections import Counter def solve(deli): m = 10**9 + 7 count = Counter(deli) ans = 0 for i in count: for n in range(22): j = (1<<n)-i if j in count: if i == j: ans += count[i] * (count[i]-1) else: ans += count[i] * count[j] return (ans // 2) % m deli = [1,7,3,6,5] print(solve(deli))
Input
[1,7,3,6,5]
Output
3
Advertisements