Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top Phrases Extraction Function

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Top Phrases Extraction Function. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Textio analyzes language patterns in writing. Given a text string and an integer k, return the k most frequent repeated phrases, where each phrase contains at least two words.

A phrase is a contiguous sequence of words within one sentence. Matching is case-insensitive, and punctuation separates sentences when it is ., !, or ?. Ignore other punctuation when identifying words. A shorter phrase is redundant when it appears inside a longer phrase with the same frequency. Do not return redundant phrases. This preserves the longest repeated wording rather than separately reporting all of its subphrases.

Return objects containing phrase and count. Sort results by decreasing frequency, then decreasing word count, then lexicographic phrase order. Return fewer than k results when fewer qualifying phrases exist.

Formal Specification

Implement top_phrases(text, k), where text is a string and k is a positive integer. Return a list of dictionaries in the form {"phrase": string, "count": integer}. Only phrases occurring at least twice qualify.

Constraints

  • 1 <= len(text) <= 100000
  • 1 <= k <= 1000
  • Words contain letters or digits, with an optional internal apostrophe
  • A sentence contains at most 500 words
  • Matching is case-insensitive

Function Signature

def top_phrases(text, k):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output