Assign Cookies using Python

The problem of assigning cookies is a popular coding interview question. Here you will be given a list of children with their greed factors and a list of cookies with their sizes. To solve this problem, you need to assign each child a cookie such that the child’s greed factor is less than or equal to the size of the cookie. So, if you want to know how to solve this problem, this article is for you. This article will take you through how to assign cookies using Python.

Assign Cookies Problem

In the assign cookies problem, you will be given a list of children with their greed factors and a list of cookies with their sizes. To solve this problem, you need to assign each child a cookie such that the child’s greed factor is less than or equal to the size of the cookie. For example, look at the input and output of this problem shown below:

  • Number of children with greed factors (g): [1, 2, 3], Number of cookies with their sizes (s): [1, 1] | Output: 1

In this example, there are two cookies with size 1, but only one child with a desired cookie size of 1. So, even though there are two cookies, only one child can be satisfied. That is why the output returns 1, as only one cookie is needed to satisfy the one child with a desired size of 1.

Assign Cookies using Python

I hope you have understood what the problem of assigning cookies means. Below is how you can assign cookies using the Python programming language:

def findContentChildren(g, s):
    i = 0
    j = 0
    g = sorted(g)
    s = sorted(s)

    while i < len(g) and j < len(s):
        i += g[i] <= s[i]
        j = j + 1
    return i

g = [1,2,3]
s = [1,1]
print(findContentChildren(g, s))
Output: 1

So this is how you can assign cookies using Python. You can find many more practice questions for coding interviews solved and explained using Python here.

Summary

In the assign cookies problem, you will be given a list of children with their greed factors and a list of cookies with their sizes. To solve this problem, you need to assign each child a cookie such that the child’s greed factor is less than or equal to the size of the cookie. I hope you liked this article on how to assign cookies using Python. Feel free to ask valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1397

Leave a Reply