Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Python Function for a Basic Gen Model

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

Your question is Python Function for a Basic Gen Model. 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

JPMorganChase is evaluating lightweight text-generation components for internal AI assistants. Implement a token-level generative model without external machine learning libraries.

Given a training corpus, build an interpolated n-gram model that predicts the next token from the longest available context. Apply additive smoothing so every vocabulary token remains possible, back off to shorter contexts when a context was not observed, and generate a reproducible continuation using a seeded random number generator.

Formal Specification

Implement generate_text(corpus, prompt, order, max_tokens, temperature, seed).

  • corpus and prompt are non-empty whitespace-separated strings.
  • order is the maximum context length.
  • max_tokens is the number of tokens to generate, excluding the prompt.
  • temperature controls randomness. A value of 0 selects the highest-probability token; positive values sample from temperature-adjusted probabilities.
  • seed initializes Python's pseudorandom generator.
  • Return a string containing exactly the generated tokens separated by single spaces. Return an empty string when max_tokens is zero.

Use additive smoothing with a fixed alpha of 0.1. If several tokens have the same highest probability at temperature 0, choose the lexicographically smallest token.

Constraints

  • 1 <= len(corpus.split()) <= 10^4
  • 0 <= max_tokens <= 100
  • 1 <= order <= 5
  • 0 <= temperature <= 2
  • seed is an integer
  • The vocabulary contains at most 2,000 distinct tokens

Function Signature

def generate_text(corpus, prompt, order, max_tokens, temperature, seed):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output