一道简单的笔试题:打印一个菱形

这是一道简单的笔试题,然而还是花了我一些时间。 暂时是这个粗糙的样子:

#!/usr/bin/env python2

__author__ = "zhangkaizhao <zhangkaizhao@gmail.com>"

def print_lozenge(xnum):
    alen = xnum * 2 - 1
    for i in range(alen):
        if i % 2:
            print " "
        else:
            start = (i < xnum) and (xnum - 1 - i) or (i - xnum + 1)
            end = alen - 1 - start
            xjs = range(start, end + 2, 2)
            print "".join([i in xjs and "X" or " " for i in range(alen)])

if __name__ == "__main__":
    import sys
    args = sys.argv
    if len(args) != 2:
        print "Usage: python print_lozenge.py number"
        sys.exit(1)
    xnum = args[1]
    try:
        xnum = int(xnum)
    except:
        print "number must be an odd number"
        sys.exit(1)
    if not xnum % 2:
        print "number must be an odd number"
        sys.exit(1)
    print_lozenge(xnum)

Comments

Comment is disabled by administrator.