当前位置:网站首页>根据给定字符数和字符,打印输出“沙漏”和剩余数
根据给定字符数和字符,打印输出“沙漏”和剩余数
2022-07-29 10:00:00 【梦幻精灵_cq】
Python 官网:https://www.python.org/
Free:大咖免费“圣经”教程《 python 完全自学教程》,不仅仅是基础那么简单……
自学并不是什么神秘的东西,一个人一辈子自学的时间总是比在学校学习的时间长,没有老师的时候总是比有老师的时候多。
—— 华罗庚


一、每行前插空格实现
寒佬博文有详尽解读和源码,可以点击蓝色文字移步寒佬博文赏析。
二、我的解决方案
解析思路:从寒佬的博文中得到启发,想到先求出“沙漏”的下半部。基于“沙漏”图形对称,反向打印下半部列表,即可完成上半部输出。
代码:
#!/sur/bin/env python
# coding: utf-8
''' filename: /sdcard/qpython/tem.py 梦幻精灵_cq的炼码场 '''
num, ch = input(f"\n{
'数字 符号(如:19 *):':>12}").strip().split()
try: # 拦截非法输入。
n = (num := int(num) - 1)//2 # 不计算中间行一行,所以减一。
except Exception as e:
print(f"\n{
' 输入错误!':-^45}\nErrorType:{
e}\n{
'~'*50}\n")
exit() # 打印错误提示后退出。
if num < 0: # 拦截非法输入。
print(f"\n{
' 请输入正整数!':~^43}\n")
exit() # 打印错误提示后退出。
hourglass = [] # 沙漏列表初值。
for k in range(3, n, 2): # 获取沙漏下半幅行(列表)。每行符号数量是差值为2的等差数列。
hourglass.append(chr*k) # 记录当前行。
n -= k
if n < k + 2: break # 剩余可用符号数量不足再排一行,退出“定行”循环。
remaining = num - ''.join(hourglass).count(ch)*2 # 计算剩余
print(f"\n{
' 沙漏下半部列表:'}{
hourglass}\n\n{
' 沙漏图形 ':~^46}\n")
for i in range(-1, -len(hourglass)-1, -1): # 打印上层
print(hourglass[i].center(50))
print(ch.center(50)) # 打印中间
for i in hourglass: # 打印下层
print(i.center(50))
print(f"{
remaining:^50}\n") # 打印余数。
input(' Wait a moment ... '.center(50, '~'))


也可以用每行符号数量的整数列表来记录“沙漏”下半部,修改相应代码就好。
remaining = num - sum(hourglass)*2 # 计算剩余
print(f"\n{
' 沙漏下半部列表:'}{
hourglass}\n\n{
' 沙漏图形 ':~^46}\n")
for i in range(-1, -len(hourglass)-1, -1): # 打印上层
print((hourglass[i]*ch).center(50))
print(chr.center(50)) # 打印中间
for i in hourglass: # 打印下层
print((i*chr).center(50))


三、大佬高级“数学”解法
其代码是目前我认为的“最好”代码。
我背下的“较好的”代码:
num, ch = input(f"\n{
'数字 符号(如:19 *):':>16}").strip().split() # 用字符串split方法分割数字和符号。
h = int((((n := int(num)) + 1)/2)**(1/2)) # 沙漏半部层高,n为总字符数量,用海象运算符赋值(Python3.x以下版本,请修改此条语句)。
for i in range(1-h, h): print(((2 * abs(i) + 1) * ch).center(50)) # 字符串方法center居中打印每行符号。用层高h打印整个沙漏。
“较好的”代码详解及源码博文链接:http://t.csdn.cn/g8yeN

我的“沙漏”图形输出,出可以用“较好的”代码优化
num, ch = input(f"\n{
'数字 符号(如:19 *):':>12}").strip().split()
try: # 拦截非法输入。
n = (num := int(num) - 1)//2 # 不计算中间行一行,所以减一。
except Exception as e:
print(f"\n{
' 输入错误!':-^45}\nErrorType:{
e}\n{
'~'*50}\n")
exit() # 打印错误提示后退出。
if num < 0: # 拦截非法输入。
print(f"\n{
' 请输入正整数!':~^43}\n")
exit() # 打印错误提示后退出。
hourglass = [] # 沙漏列表初值。
for k in range(3, n, 2): # 获取沙漏下半幅行(列表)。每行符号数量是差值为2的等差数列。
hourglass.append(k) # 记录当前行。
n -= k
if n < k + 2: break # 剩余可用符号数量不足再排一行,退出“定行”循环。
h = len(hourglass) + 1 # 沙漏半部高h即半部行数+中间行。
remaining = num - sum(hourglass)*2 # 计算剩余
print(f"\n{
' 沙漏下半部列表:'}{
hourglass}\n\n{
' 沙漏图形 ':~^46}\n")
for i in range(1-h, h): print(((2 * abs(i) + 1) * ch).center(50)) # 字符串方法center居中打印每行符号。用层高h打印整个沙漏。
print(f"{
remaining:^50}\n") # 打印余数。
input(' Wait a moment ... '.center(50, '~'))
两个for循环,被一条语句替代。
本练习感悟:代码,一般都是可以优化的。
__上一篇:__ 重建我的color工具——(用初通Python之class全新修葺)
__下一篇:__
我的HOT博:
- Hot:聊天消息敏感词屏蔽系统(字符串替换 str.replace(str1, *) )(1011阅读)
- 练习:银行复利计算(用 for 循环解一道初中小题)(1082阅读)
- pandas 数据类型之 DataFrame(1514阅读)
- 班里有人和我同生日难吗?(概率probability、蒙特卡洛随机模拟法)(2116阅读)
- Python字符串居中显示(1624阅读)
- 练习:求偶数和、阈值分割和求差( list 对象的两个基础小题)(1656阅读)
- 用 pandas 解一道小题(1981阅读)
- 可迭代对象和四个函数(1074阅读)
- “快乐数”判断(1234阅读)
- 罗马数字转换器(构造元素取模)(1950阅读)
- Hot:罗马数字(转换器|罗生成器)(4012阅读)
- Hot:让QQ群昵称色变的代码(30059阅读)
- Hot:斐波那契数列(递归| for )(4053阅读)
- 柱状图中最大矩形(1658阅读)
- 排序数组元素的重复起止(1247阅读)
- 电话拨号键盘字母组合(1363阅读)
- 密码强度检测器(1829阅读)
- 求列表平衡点(1823阅读)
- Hot: 字符串统计(4293阅读)
- Hot:尼姆游戏(聪明版首发)(3441阅读)尼姆游戏(优化版)(1052阅读)
推荐条件点阅破千

精品文章:
- 好文力荐:《python 完全自学教程》齐伟书稿免费连载
- OPP三大特性:封装中的property
- 通过内置对象理解python'
- 正则表达式
- python中“*”的作用
- Python 完全自学手册
- 海象运算符
- Python中的 `!=`与`is not`不同
- 学习编程的正确方法
来源:老齐教室
Python 入门指南【Python 3.6.3】
好文力荐:
全栈领域优质创作者——寒佬(还是国内某高校学生)好文:《非技术文—关于英语和如何正确的提问》,“英语”和“会提问”是学习的两大利器。
CSDN实用技巧博文:
边栏推荐
- 数据可视化的利器-Seaborn简易入门
- What kind of framework is friendly to developers?
- Talk about multithreaded concurrent programming from a different perspective without heap concept
- Leetcode question brushing - sorting
- 一知半解 ~题目杂记 ~ 一个多态问题
- Sed, regular expression of shell programming
- C语言的传参方式(int x)(int *x)(int &x)
- Manually build ABP framework from 0 -abp official complete solution and manually build simplified solution practice
- Summary of window system operation skills
- Linear regression of machine learning (least square handwriting +sklearn Implementation)
猜你喜欢

开放原子开源基金会黄金捐赠人优博讯携手合作伙伴,助力OpenHarmony破圈!

A little knowledge ~ miscellaneous notes on topics ~ a polymorphic problem

Shell notes (super complete)

【C语言】三子棋(智能下棋 + 阻拦玩家)

What kind of framework is friendly to developers?

mysql 数据库 期末复习题库

Comprehensively design an oppe home page -- the bottom of the page
![[ts]Typescript学习记录坑点合集](/img/4c/14991ea612de8d5c94b758174a1c26.png)
[ts]Typescript学习记录坑点合集

《LOL》从代码上来说最难的是哪个英雄?

函数——(C游记)
随机推荐
The purpose of DDD to divide domains, sub domains, core domains, and support domains
【C语言】三子棋(智能下棋 + 阻拦玩家)
Sed, regular expression of shell programming
JS temporary dead zone_ Temporary
Correct posture and landing practice of R & D efficiency measurement (speech ppt sharing version)
div 水平排列
JS to achieve full screen effect
Comprehensively design an oppe home page -- the bottom of the page
Why does the system we developed have concurrent bugs? What is the root cause of concurrent bugs?
Sample is new and supported from API 8! Come and take it
Tips of Day1 practice in 2022cuda summer training camp
English grammar_ Indefinite pronouns - Common Phrases
Shutter -- use camera (continuously updating)
Google Earth engine (GEE) -- calculate the location of the center point, the external boundary, the external polygon, fuse and simplify the boundary and return it to the vector set
Reasons for the rise of DDD and its relationship with microservices
Function - (C travel notes)
[wechat applet] interface generates customized homepage QR code
Read Plato farm's eplato and the reason for its high premium
函数——(C游记)
In simple terms, dependency injection and its application in Tiktok live broadcast