SECTION 13 / 31

Store the IDs who share each birthday

1 min read
The same date key can remember existence, a count, an ID list or an inner ID dictionary. Choose the representation for the question.
The same date key can remember existence, a count, an ID list or an inner ID dictionary. Choose the representation for the question.
birthdays = {}
duplicates = {}
foreach X in scores {
    dob = normalizedDayMonth(X.DateOfBirth)
    id = X.CardNo
    if (isKey(birthdays,dob)) {
        duplicates[dob] = True
        birthdays[dob] = birthdays[dob] ++ [id]
    }
    else {
        birthdays[dob] = [id]
    }
}
foreach dob in keys(duplicates) {
    sharedIDs = birthdays[dob]
}

On Aditya’s card, birthdays[15 Mar] becomes [7]. On Monika’s card it becomes [7,21]. Here length(birthdays[15 Mar]) is 2, while length(keys(birthdays)) is 29 after the full scan. One counts students at a chosen date; the other counts observed dates.

Try it yourself

Why append [id] rather than id?

Show explained answer

++ concatenates lists, so wrap the new ID in a one-element list.

Try it yourself

Does birthdays[dob]=[id] on every card retain all students?

Show explained answer

No. It replaces earlier lists. Append on existing keys.

Try it yourself

What does birthdays[15 Mar] return here?

Show explained answer

The whole ID list [7,21], not one ID and not just a Boolean flag.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑