Program to count how many times we can find "pizza" with given string characters in Python

When we need to count how many times we can form the word "pizza" from available characters in a string, we need to check the frequency of each required character. Since "pizza" contains 'p', 'i', 'z', 'z', 'a', we need at least 1 'p', 1 'i', 2 'z', and 1 'a' to form one complete word.

So, if the input is like "ihzapezlzzilaop", then the output will be 2.

Algorithm

To solve this problem, we follow these steps ?

  • Count frequency of 'p' in the string
  • Count frequency of 'i' in the string
  • Count frequency of 'z' in the string (divide by 2 since we need 2 'z' per pizza)
  • Count frequency of 'a' in the string
  • Return the minimum of all these counts

Example

class Solution:
    def solve(self, s):
        p_freq = s.count('p')
        i_freq = s.count('i')
        z_freq = s.count('z')
        a_freq = s.count('a')
        return min(p_freq, i_freq, z_freq // 2, a_freq)

ob = Solution()
print(ob.solve("ihzapezlzzilaop"))
2

How It Works

In the string "ihzapezlzzilaop", let's count each character ?

s = "ihzapezlzzilaop"

p_count = s.count('p')
i_count = s.count('i')
z_count = s.count('z')
a_count = s.count('a')

print(f"p: {p_count}, i: {i_count}, z: {z_count}, a: {a_count}")
print(f"Possible pizzas: {min(p_count, i_count, z_count // 2, a_count)}")
p: 2, i: 2, z: 4, a: 2
Possible pizzas: 2

Alternative Implementation

Using Counter from collections module ?

from collections import Counter

def count_pizzas(s):
    freq = Counter(s)
    return min(freq['p'], freq['i'], freq['z'] // 2, freq['a'])

result = count_pizzas("ihzapezlzzilaop")
print(result)
2

Conclusion

To count possible "pizza" formations, find the minimum of individual character frequencies, remembering that 'z' needs to be divided by 2 since "pizza" requires two 'z' characters. The bottleneck character determines the maximum number of complete words we can form.

Updated on: 2026-03-25T10:51:58+05:30

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements