
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to 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
- Related Articles
- Count Good Meals in Python
- Program to count number of sublists with exactly k unique elements in Python
- Program to count items matching a rule using Python
- How to count items in array with MongoDB?
- Program to count number of overlapping islands in two maps in Python
- Program to count pairs with XOR in a range in Python
- Program to check two trees are exactly same based on their structure and values in Python
- Program to count number of common divisors of two numbers in Python
- Program to count submatrices with all ones using Python
- Python Program to Count of Words with specific letter
- Program to find which element occurs exactly once in Python
- Program to count number of BST with n nodes in Python
- Count number of substrings with exactly k distinct characters in C++
- Program to count substrings with all 1s in binary string in Python
- Program to count average of all special values for all permutations of a list of items in Python

Advertisements