Python 从命令行参数打印平铺
我需要根据命令行参数打印分幅,其中第一个参数是宽度,第二个是名称。 例如:Python 从命令行参数打印平铺,python,arguments,command,line,tiles,Python,Arguments,Command,Line,Tiles,我需要根据命令行参数打印分幅,其中第一个参数是宽度,第二个是名称。 例如: $ python tile.py 5 tommy ------+|+------ ---+|++|++|+--- -----TOMMY----- ---+|++|++|+--- ------+|+------ 或 因为有一些限制:宽度只能是奇数,名称的长度不能超过3*width 我不知道如何做垂直部分,因为它可以是5层、7层或更多层 import sys a = int(sys.argv[1]) if a%2==0:
$ python tile.py 5 tommy
------+|+------
---+|++|++|+---
-----TOMMY-----
---+|++|++|+---
------+|+------
或
因为有一些限制:宽度只能是奇数,名称的长度不能超过3*width
我不知道如何做垂直部分,因为它可以是5层、7层或更多层
import sys
a = int(sys.argv[1])
if a%2==0:
print('Error: tile height must be an odd number')
else:
if len(sys.argv[2])>(3*a):
print('Error: name must fit within {} characters'.format(3*a))
else:
print('-'*((3*a-3)/2)+'+-+'+'-'*((3*a-3)/2))
print('-'*((3*a-9)/2))
可以使用string函数简化填充。除此之外,您只需使用循环向上计数,然后向下计数,利用python和列表上的
*
运算符:
# Growing width Name Shrinking width
widths = list(range(a//2)) + [-1] + list(reversed(range(a//2)))
for k in widths:
# Print name if we're halfway there
if k == -1:
# Print name in uppercase, centered over 3*a characters, padded with '-'
print(name.upper().center(3*a,'-'))
else:
# Repeat '+|+' 1+2k number of times,
# join with nothing in between and center, padding with '-'
print("".join(["+|+"]*(1+2*k)).center(3*a,'-'))
可以使用string函数简化填充。除此之外,您只需使用循环向上计数,然后向下计数,利用python和列表上的
*
运算符:
# Growing width Name Shrinking width
widths = list(range(a//2)) + [-1] + list(reversed(range(a//2)))
for k in widths:
# Print name if we're halfway there
if k == -1:
# Print name in uppercase, centered over 3*a characters, padded with '-'
print(name.upper().center(3*a,'-'))
else:
# Repeat '+|+' 1+2k number of times,
# join with nothing in between and center, padding with '-'
print("".join(["+|+"]*(1+2*k)).center(3*a,'-'))
在我看来,宽度和高度总是一样的,因为你总是把'-'的数量减少2,直到剩下3分钟,所以对于宽度=9,一行有9'-'一行有7行,然后是5行,然后是3行,这是4行,然后一行代表名字,再反过来是4行,所以总共是9,在我看来,宽度和高度总是一样的,因为你总是把“-”的数量减少2,直到剩下3分钟,所以对于宽度=9,一行有9“-”,一行有7行,然后是5行,然后是3行,这是4行,然后是一行代表名字,再反过来是4行,所以总共是9行