编写代码根据p

问题描述 投票:0回答:1

我正在用 python 编写一个类似打印机的程序,问题是编写一个函数“count_pages(p),它根据字符串 p 返回将打印多少页

我尝试执行 count_pages 函数来返回有多少页。参数和返回值是

“5-7, 2”4

“12-18、20-20”8

“18-12、20-20、5-6”

我遇到了以下错误:

Traceback (most recent call last):
  File "C:/Users/19013/Desktop/1900/printer_party.py", line 19, in <module>
    print(count_pages('5-7, 2'))  # Expected output: 4
  File "C:/Users/19013/Desktop/1900/printer_party.py", line 11, in count_pages
    start, end = map(int, r.split('-'))
ValueError: not enough values to unpack (expected 2, got 1)


def count_pages(p):
    # Split the input string by commas
    ranges = p.split(', ')
    
    # Initialize the total page count
    total_pages = 0
    
    # Iterate through each range
    for r in ranges:
        # Split the range by hyphen
        start, end = map(int, r.split('-'))
        
        # Add the number of pages in this range to the total
        total_pages += end - start + 1
    
    return total_pages

# Example usage
print(count_pages('5-7, 2'))  # Expected output: 4
print(count_pages('12-18, 20-20'))  # Expected output: 8
print(count_pages('18-12, 20-20, 5-6'))  # Expected output: 10
python string
1个回答
0
投票

我会使用

re
进行字符串解析,例如:

import re


def count_pages(s):
    out = 0
    for a, b in re.findall(r"(\d+)(?:-(\d+))?", s):
        if b == "":
            b = a
        a, b = sorted((int(a), int(b)))
        out += b - a + 1
    return out


print(count_pages("5-7, 2"))  # Expected output: 4
print(count_pages("12-18, 20-20"))  # Expected output: 8
print(count_pages("18-12, 20-20, 5-6"))  # Expected output: 10

打印:

4
8
10
© www.soinside.com 2019 - 2024. All rights reserved.