Quick Overview

This question evaluates proficiency in Python programming, particularly list comprehension, string tokenization, and sequence manipulation for generating consecutive word bigrams.

Generate Bigrams Using Python List Comprehension and Zip

Company: PayPal

Role: Data Scientist

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

##### Scenario Live Python exercise: generate all bigrams from an input string and iteratively optimize the solution. ##### Question Write a Python function that takes a sentence and returns a list of all consecutive word bigrams. Refactor the solution with list comprehension for conciseness. Can you further compress it into a single line? (Hint: consider using zip.) ##### Hints Think of zip(s.split()[:-1], s.split()[1:]) and join/format as needed.

Quick Answer: This question evaluates proficiency in Python programming, particularly list comprehension, string tokenization, and sequence manipulation for generating consecutive word bigrams.

Write a function that takes a sentence (string) and returns a list of all consecutive word bigrams. A bigram is a pair of adjacent words joined by a single space, in order. Split the sentence on whitespace (collapsing any runs of whitespace) before pairing. For example, given "the quick brown fox", return ["the quick", "quick brown", "brown fox"]. A sentence with fewer than two words yields an empty list. This mirrors the classic zip-based idiom: pairing words[:-1] with words[1:]. Try a loop first, then refactor into a one-line list comprehension over zip(words[:-1], words[1:]).

Constraints

  • The input is a single string that may contain leading, trailing, or repeated whitespace.
  • Words are maximal non-whitespace runs; splitting collapses any whitespace.
  • A sentence with zero or one word returns an empty list.
  • Each bigram is the two adjacent words joined by exactly one space.

Examples

Input: ("the quick brown fox",)

Expected Output: ["the quick", "quick brown", "brown fox"]

Explanation: Four words produce three consecutive bigrams.

Input: ("hello world",)

Expected Output: ["hello world"]

Explanation: Two words produce exactly one bigram.

Hints

  1. Split the sentence into a list of words first using whitespace splitting (which collapses repeated spaces).
  2. Pair each word with the one that follows it: index i with index i+1, for i from 0 to len(words)-2.
  3. The one-line idiom is [a + ' ' + b for a, b in zip(words[:-1], words[1:])] — zip naturally stops at the shorter sequence, so it produces exactly len(words)-1 pairs.

Loading coding console...