Combinatorics question from Google interviews. This article demonstrates the application of backtracking algorithms and list comprehensions through a name permutation generation problem. oavoservice helps you master combinatorial algorithms.
📋 Problem Scenario
Given a list of surnames and a list of first names, generate all possible name combinations.
Example:
surnames = ["Smith", "Johnson"]
first_names = ["John", "Jane"]
Output: ["John Smith", "John Johnson", "Jane Smith", "Jane Johnson"]
🎯 Solution Comparison
Method 1: Nested Loops
def generate_names_v1(surnames, first_names):
result = []
for first in first_names:
for last in surnames:
result.append(f"{first} {last}")
return result
Method 2: List Comprehension (Pythonic)
def generate_names_v2(surnames, first_names):
return [f"{first} {last}"
for first in first_names
for last in surnames]
Method 3: itertools (Most Elegant)
from itertools import product
def generate_names_v3(surnames, first_names):
return [f"{first} {last}"
for first, last in product(first_names, surnames)]
🚀 Extension: Middle Names
def generate_full_names(first, middle, last):
# Supports optional middle names
names = []
for f in first:
for l in last:
names.append(f"{f} {l}")
for m in middle:
names.append(f"{f} {m} {l}")
return names
💼 How oavoservice Helps
Python Skills - List comprehensions and generators Standard Library - Efficient use of itertools Code Style - Pythonic coding
Contact oavoservice for professional Python interview assistance!
Tags: #Google #Python #Combinatorics #ListComprehension #VOHelp #InterviewPrep #1point3acres
Need real interview questions? Contact WeChat Coding0201 immediately to get real questions.