Python代写:COMP1001-MoreTextProcessing

Introduction

用Python的一个优势便是十分适合Text processing,由于Python内建了许多函数,对于文字、字符的处理十分便捷,如字符串连接、字符串截取、字符串查找、字符串替换、字符串比较、字符串分割、字符串翻转、字符串编码等,都有对应的函数进行处理。相比C语言,节省了很多开发工作量。

Requirement

This question prints the leaves of a symmetric tree. A user will be prompted for a symbol and a positive position for the tip of the leaves. Starting from the tip, the tree will fan out on both sides symmetrically until left side of the leaves reaches the left edge, assuming that the right edge has no limit. For example

1
2
3
4
5
6
7
8
9
10
11
12
13
Please enter a symbol: *
Please enter a positive position
of the symbol on the first line: 10
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************

Analysis

本题就是一个简单的字符串处理,注意逻辑处理就好,难度不大,直接上代码。

不过越是容易的题目,越不容易写出精简的代码,本题打印最简单的方法可由一行代码实现。

Tips

1
2
3
4
5
6
7
8
9
10
def main():
# user input
symbol = input("Please enter a symbol: ")
pos = eval(input("Please enter a positive position \nof the symbol on the first line: "))

# print the leaves
for i in range(pos):
print((pos - 1 - i) * " " + (2 * i + 1) * symbol)

main()