PracticeStrings
The Initial Segment Test
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:
TrueExplanation: 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:
FalseExplanation: 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:
TrueExplanation: 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) <= 100source: non emptysource: alphabet lowercase1 <= len(prefix) <= 100prefix: non emptyprefix: alphabet lowercasesource and prefix contain only lowercase letters.- Types:
sourceis str,prefixis str; result is bool
Function signature
def begins_with_prefix(source: str, prefix: str) -> bool
sourcestr- The source string to inspect.
prefixstr- 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.
Code
Saved