PracticeStrings

The Initial Segment Test

BeginnerStringstraversalcomparisonprefix reasoning Time not estimated Not started

Context

Let two finite strings be given: a source word and a nonempty leading token. Decide whether the token is exactly the initial segment of the source word. The comparison concerns only the beginning of the source; an identical sequence appearing later does not count.

Problem

Write a function that classifies whether source begins with prefix. Return true exactly when every character of prefix matches the corresponding character of source starting at index 0. The source must remain unchanged. If the source is shorter than prefix, return false. Matching characters later in source do not qualify, and repeated characters must still be compared in their original order.

Examples

Example 1
Input: prefix = "sun"source = "sunflower"
Output: True
Explanation: For source "sunflower" and prefix "sun", the executed call returns true; its final position is 3 and is_match is true.
Example 2
Input: prefix = "bow"source = "rainbow"
Output: False
Explanation: For source "rainbow" and prefix "bow", the executed call returns false; its final position is 0 and is_match is false.
Example 3
Input: prefix = "banan"source = "banana"
Output: True
Explanation: For source "banana" and prefix "banan", the executed call returns true; its final position is 5 and is_match is true.

Constraints

  • 1 <= len(source) <= 100
  • source: non empty
  • source: alphabet lowercase
  • 1 <= len(prefix) <= 100
  • prefix: non empty
  • prefix: alphabet lowercase
  • source and prefix contain only lowercase letters.
  • Types: source is str, prefix is str; result is bool

Function signature

def begins_with_prefix(source: str, prefix: str) -> bool
source str
The source string to inspect.
prefix str
The nonempty string that must occupy the beginning of source.
returns bool
Return true if and only if source starts with prefix at index 0; otherwise return false.

Adapted from MBPP problem task_900 (CC BY 4.0). Rewritten, extended and verified by Iksha.

Notes

  • The source and prefix are separate strings; do not modify either input.
  • The comparison is case-sensitive because all characters are lowercase.
Approved · cb040-abs_300_v114 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1