To solve this problem, we need to calculate the byte length of a string where each ASCII character takes up 1 byte and non-ASCII characters (like Chinese characters) take up 2 bytes.
Approach
The approach to solve this problem involves the following steps:
- Initialize a total byte counter: Start with a counter set to 0.
- Iterate over each character: For each character in the input string:
- If the character is an ASCII character (using
isascii()method), add 1 to the counter. - If the character is non-ASCII, add 2 to the counter.
- If the character is an ASCII character (using
- Return the total: After processing all characters, return the total byte count.
Solution Code
def calculate_byte_length(s):
total = 0
for char in s:
total += 1 if char.isascii() else 2
return total
Explanation
- ASCII Check: The
isascii()method (available in Python 3.7+) checks if a character is an ASCII character (values 0-127). This helps us determine if the character takes up 1 byte. - Non-ASCII Handling: Any character that is not ASCII (like Chinese, accented characters, etc.) is assumed to take up 2 bytes as per the problem statement.
- Efficiency: The function runs in O(n) time complexity where n is the length of the string, as it processes each character exactly once.
Example Usage
Let’s test the function with some examples:
calculate_byte_length("abc")→ 3 (all ASCII characters).calculate_byte_length("你好abc")→ 22 +31 =7 (2 Chinese characters +3 ASCII).calculate_byte_length("Hello世界")→51 +22=9 (5 ASCII +2 Chinese).
This function correctly computes the byte length as required.
Answer:
def calculate_byte_length(s):
total = 0
for char in s:
total += 1 if char.isascii() else 2
return total


作者声明:本文包含人工智能生成内容。