【Python 小学低段竞赛数学题】数字5在书本页码中出现16次,这本书最多有多少页

书的页码编号是按1 2 3 4 5一直这样下去的,数字5恰好出现了16次,请问这本书最多可以有多少页?

包含5的页码: 5 15 25 35 45 50 51 52 53 54 55 56 57 58 59 65

需要注意页码55,出现了两次5。因此到59页就满足数字5出现了16次。且59页是书本最少总页数。最多总页数要往17次算出页数65,65页刚好第一次满足出现17次数字5,所在64页就是数字5出现16次的书本最多总页数。

python 复制代码
def page_num_count(specify_number: int, set_times: int) -> tuple[int, int, list[int]]:
    page_num = 1
    num_count = 0  # 记录5出现的总次数
    list_specify_number = []  # 包含指定数字的页码,组成列表。
    while True:
        count = str(page_num).count(str(specify_number))  # 统计5在当前页码中出现的次数
        if count > 0:
            num_count += count  # 当前页码有5,将次数累加进总次数中
            list_specify_number.append(page_num)
        if num_count == set_times:
            break
        page_num += 1
    return page_num, num_count,list_specify_number


page_num, num_count, list_specify_number = page_num_count(5, 16)

print(f"5出现的总次数:{num_count}")  # 5出现的总次数:16
print(f"最少:{page_num}页。")  # 最少:59页。
print(f"包含5的页码:", *list_specify_number)  # 包含5的页码: 5 15 25 35 45 50 51 52 53 54 55 56 57 58 59


page_num, num_count, list_specify_number = page_num_count(5, 17)  # 共出现16次,可能的最多页数,要按17次算,将刚满足17次的页码减1,即是16次最多页数。

print(f"按17次算,包含5的页码:", *list_specify_number)  # 按17次算,包含5的页码: 5 15 25 35 45 50 51 52 53 54 55 56 57 58 59 65
print(f"最多:{page_num-1}页。")  # 最多:64页。
相关推荐
bug总结几秒前
新学一个JavaScript 的 classList API
开发语言·javascript·ecmascript
Nicole Potter7 分钟前
请说明C#中的List是如何扩容的?
开发语言·面试·c#
liuyuzhongcc9 分钟前
List 接口中的 sort 和 forEach 方法
java·数据结构·python·list
鸟哥大大18 分钟前
【Python】pypinyin-汉字拼音转换工具
python·自然语言处理
jiugie26 分钟前
MongoDB学习
数据库·python·mongodb
靡不有初11134 分钟前
CCF-CSP第18次认证第一题——报数【两个与string相关的函数的使用】
c++·学习·ccfcsp
十八朵郁金香1 小时前
通俗易懂的DOM1级标准介绍
开发语言·前端·javascript
阿尔法波1 小时前
python与pycharm如何设置文件夹为源代码根目录
开发语言·python·pycharm
xing25161 小时前
pytest下allure
开发语言·python·pytest
眸笑丶1 小时前
使用 Python 调用 Ollama API 并调用 deepseek-r1:8b 模型
开发语言·python