当前位置:网站首页>Print out the "hourglass" and the remaining number according to the given number of characters and characters
Print out the "hourglass" and the remaining number according to the given number of characters and characters
2022-07-29 10:01:00 【Fantasy elves_ cq】
Python Official website :https://www.python.org/
Free: Big coffee free “ Bible ” course 《 python Complete self study course 》, It's not just the basics ……
- My CSDN Home page 、My HOT Bo 、My Python Study personal memos
- A good writer recommends 、 Laoqi classroom
Self study is not a mysterious thing , A person's self-study time is always longer than that in school , There are always more times when there are no teachers than when there are teachers .
—— Hua Luogeng

- 1、 subject
- 2、 Lonely and cold people solve —— Insert a space before each line to achieve
- 3、 My solution —— First find out half “ hourglass ”
- 4、Math Big brother —— Formula method

One 、 Insert a space before each line to achieve
Cold guy The blog has detailed interpretation and source code , You can click the blue text to move Cold guy Blog appreciation .
Cold guy Blog links :http://t.csdn.cn/7a7hu
Two 、 My solution
Analytical thinking : Get inspiration from Han Lao's blog , Think of it first “ hourglass ” Lower half of . be based on “ hourglass ” Graphic symmetry , Print the lower half of the list in reverse , You can complete the upper half of the output .
Code :
#!/sur/bin/env python
# coding: utf-8
''' filename: /sdcard/qpython/tem.py The dream spirit _cq Code yard '''
num, ch = input(f"\n{
' Numbers Symbol ( Such as :19 *):':>12}").strip().split()
try: # Block illegal input .
n = (num := int(num) - 1)//2 # Do not calculate the middle line , So subtract one .
except Exception as e:
print(f"\n{
' Input error !':-^45}\nErrorType:{
e}\n{
'~'*50}\n")
exit() # Exit after printing the error prompt .
if num < 0: # Block illegal input .
print(f"\n{
' Please enter a positive integer !':~^43}\n")
exit() # Exit after printing the error prompt .
hourglass = [] # Initial value of hourglass list .
for k in range(3, n, 2): # Get the bottom half row of the hourglass ( list ). The number of symbols per line is the difference of 2 Equal difference sequence of .
hourglass.append(chr*k) # Record current line .
n -= k
if n < k + 2: break # The number of remaining available symbols is insufficient to line up another line , sign out “ Fixed line ” loop .
remaining = num - ''.join(hourglass).count(ch)*2 # Calculate surplus
print(f"\n{
' The bottom half of the hourglass list :'}{
hourglass}\n\n{
' Hourglass graphics ':~^46}\n")
for i in range(-1, -len(hourglass)-1, -1): # Print the upper layer
print(hourglass[i].center(50))
print(ch.center(50)) # Print middle
for i in hourglass: # Print lower layer
print(i.center(50))
print(f"{
remaining:^50}\n") # Print remainder .
input(' Wait a moment ... '.center(50, '~'))


It can also be recorded with an integer list of the number of symbols per line “ hourglass ” The second half , Just modify the corresponding code .
remaining = num - sum(hourglass)*2 # Calculate surplus
print(f"\n{
' The bottom half of the hourglass list :'}{
hourglass}\n\n{
' Hourglass graphics ':~^46}\n")
for i in range(-1, -len(hourglass)-1, -1): # Print the upper layer
print((hourglass[i]*ch).center(50))
print(chr.center(50)) # Print middle
for i in hourglass: # Print lower layer
print((i*chr).center(50))


3、 ... and 、 Boss senior “ mathematics ” solution
Its code is what I think at present “ best ” Code .
I recited “ Better ” Code :
num, ch = input(f"\n{
' Numbers Symbol ( Such as :19 *):':>16}").strip().split() # Use string split Method to split numbers and symbols .
h = int((((n := int(num)) + 1)/2)**(1/2)) # The half story height of the hourglass ,n Is the total number of characters , Assign values with walrus operators (Python3.x The following versions , Please modify this statement ).
for i in range(1-h, h): print(((2 * abs(i) + 1) * ch).center(50)) # String method center Print each line of symbols in the center . Floor height h Print the entire hourglass .
“ Better ” Code explanation and source code blog link :http://t.csdn.cn/g8yeN

my “ hourglass ” Graphic output , It can be used “ Better ” Code optimization
num, ch = input(f"\n{
' Numbers Symbol ( Such as :19 *):':>12}").strip().split()
try: # Block illegal input .
n = (num := int(num) - 1)//2 # Do not calculate the middle line , So subtract one .
except Exception as e:
print(f"\n{
' Input error !':-^45}\nErrorType:{
e}\n{
'~'*50}\n")
exit() # Exit after printing the error prompt .
if num < 0: # Block illegal input .
print(f"\n{
' Please enter a positive integer !':~^43}\n")
exit() # Exit after printing the error prompt .
hourglass = [] # Initial value of hourglass list .
for k in range(3, n, 2): # Get the bottom half row of the hourglass ( list ). The number of symbols per line is the difference of 2 Equal difference sequence of .
hourglass.append(k) # Record current line .
n -= k
if n < k + 2: break # The number of remaining available symbols is insufficient to line up another line , sign out “ Fixed line ” loop .
h = len(hourglass) + 1 # The hourglass is half high h That is, half of the lines + Middle row .
remaining = num - sum(hourglass)*2 # Calculate surplus
print(f"\n{
' The bottom half of the hourglass list :'}{
hourglass}\n\n{
' Hourglass graphics ':~^46}\n")
for i in range(1-h, h): print(((2 * abs(i) + 1) * ch).center(50)) # String method center Print each line of symbols in the center . Floor height h Print the entire hourglass .
print(f"{
remaining:^50}\n") # Print remainder .
input(' Wait a moment ... '.center(50, '~'))
Two for loop , Replaced by a statement .
This exercise gives insights : Code , Generally, it can be optimized .
__ Last one :__ Rebuild my color Tools ——( Use chutong Python And class New repair )
__ Next :__
my HOT Bo :
- Hot: Chat message sensitive word shielding system ( String substitution str.replace(str1, *) )(1011 read )
- practice : Calculation of bank compound interest ( use for Solve a junior high school problem in a circular way )(1082 read )
- pandas Data type DataFrame(1514 read )
- Is it difficult for someone in the class to have the same birthday as me ?( probability probability、 Monte Carlo stochastic simulation method )(2116 read )
- Python The string is centered (1624 read )
- practice : Even sum 、 Threshold segmentation and subtraction ( list Two basic questions of the object )(1656 read )
- use pandas Solve a small problem (1981 read )
- Iteratable object and four functions (1074 read )
- “ Happy number ” Judge (1234 read )
- Roman digital converter ( Construct element module )(1950 read )
- Hot: Rome digital ( converter | Luo )(4012 read )
- Hot: Give Way QQ Group nickname color change code (30059 read )
- Hot: Fibonacci sequence ( recursive | for )(4053 read )
- The largest rectangle in the histogram (1658 read )
- Repeat start and end of sorting array elements (1247 read )
- Telephone dialing keyboard letter combination (1363 read )
- Password strength detector (1829 read )
- Find the balance point of the list (1823 read )
- Hot: String statistics (4293 read )
- Hot: Nim game ( Smart version starts )(3441 read ) Nim game ( Optimized version )(1052 read )
Recommended conditions Click to read a thousand

Excellent articles :
- A good writer recommends :《python Complete self study course 》 Qi Wei manuscript free Serial
- OPP The three major characteristics : In the package property
- Understand through built-in objects python'
- Regular expressions
- python in “*” The role of
- Python A complete self-study manual
- Walrus operators
- Python Medium `!=` And `is not` Different
- The right way to learn programming
source : Laoqi classroom
Python Getting started 【Python 3.6.3】
A good writer recommends :
High quality creators in the whole stack field —— Cold guy ( Or a domestic college student ) Good writing :《 Non technical paper — About English and how to ask questions correctly 》,“ English ” and “ I will ask questions ” Are two sharp tools for learning .
CSDN Practical skills blog :
- 8 A good one Python Practical skills
- python Ignore the warning
- Python Code specification
- Python Of docstring standard ( Describe the standard writing of the document )
边栏推荐
- English grammar_ Indefinite pronouns - Common Phrases
- Sublime Text3 设置不同文件不同缩进
- Summary of JD internship written examination questions
- A Zuo's realm
- 一文读懂Plato Farm的ePLATO,以及其高溢价缘由
- Some suggestions for programmers to leave single
- A little knowledge ~ miscellaneous notes on topics ~ a polymorphic problem
- 【C语言】扫雷(递归展开 + 标记功能)
- leetcode刷题——排序
- System architect learning
猜你喜欢

vector实现

i. Mx6ull driver development | 32 - manually write a virtual network card device

Window系统操作技巧汇总

Source code analysis of senparc.weixin.sample.mp
![[wechat applet] interface generates customized homepage QR code](/img/9b/cccdb8ff6db61518402a27b94d0196.png)
[wechat applet] interface generates customized homepage QR code

Behind 100000 visits...

HarmonyOS 3.0 发布!

这是一份不完整的数据竞赛年鉴!

node(二)

Senparc.Weixin.Sample.MP源码剖析
随机推荐
综合设计一个OPPE主页--页面的底部
【微信小程序】接口生成自定义首页二维码
Where are those test / development programmers in their 30s? a man should be independent at the age of thirty......
上海交大牵手淘宝成立媒体计算实验室:推动视频超分等关键技术发展
i. Mx6ull driver development | 32 - manually write a virtual network card device
阿左的境界
[AAAI] attention based spatiotemporal graph convolution network for traffic flow prediction
On memory computing integrated chip technology
Vector implementation
QoS quality of service five traffic shaping of QoS boundary behavior
A little knowledge ~ miscellaneous notes on topics ~ a polymorphic problem
读博后降维打击数学建模!
Virtual machines use host graphics cards (Hyper-V and wsl2)
Senparc.Weixin.Sample.MP源码剖析
What kind of framework is friendly to developers?
[ts]typescript learning record pit collection
A Zuo's realm
Implementation and verification logic of complex expression input component
英特尔联合Datawhale,发布学习项目!
Yin Yi: my learning and growth path