0

简单地说,当用户输入为 6 时,我希望使用 for 或 while 循环实现以下目标。

z....z
.z..z.
..zz..
..zz..
.z..z.
z....z

zz....
..z..z
...zz.
...zz.
..z..z
zz....

.zz...
z..z..
....zz
....zz
z..z..
.zz...
4

1 回答 1

0
#!/usr/bin/env python3

def create_pattern(pattern_size):
    # Create our list that'll be storing this info
    pattern = []

    # first_x and last_x are "memory" so we know where to place the Xes.
    first_x = 0
    last_x = pattern_size - 1

    # Next, create an inner list for each line
    for level in range(0, pattern_size):

        # start our new line
        pattern.append([])

        # Now place the Xes where they belong
        for x in range(0, pattern_size):
            if x == first_x or x == last_x:
                pattern[level].append("x")
            else:
                pattern[level].append(".")

        # Move the Xes to the new positions
        first_x += 1
        last_x -= 1
    return pattern

# see 'help(list.pop)' and 'help(list.insert)' for more details
def right_shift(line):
    buf = line.pop()
    line.insert(0, buf)
    return line

# This function just acts upon each line of a pattern
def shift_pattern(pattern):
    for line in range(0, len(pattern)):
        line = right_shift(pattern[line])
    return pattern

if __name__ == "__main__":
    original = create_pattern(7)
    for j in range(len(original)):
        if j != 0:
            original = shift_pattern(original)
        for i in range(len(original)):
            print("".join(original[i]))

        print()

这个问题很巧妙。你需要的是右移。所以我所做的是使用列表将模式分解为行和字符。可能有一种更有效的方法来做到这一点,但它似乎是最直接的方法,因为 Python 字符串是不可变的,而列表是可变的。

create_pattern()只需设置我们的“输入模式”,它会print()在第一次编辑后被操纵。

对我来说最有趣(也是最重要)的部分是right_shift(). 我的第一次尝试是在程序上设置列表索引。该方法成功了一半,但容易出错。然后我想起来了pop()。快速help(list)向我透露,我可以简单地从列表中弹出最后一个元素并将其放在开头以“伪造”右移。结果?

x.....x
.x...x.
..x.x..
...x...
..x.x..
.x...x.
x.....x

xx.....
..x...x
...x.x.
....x..
...x.x.
..x...x
xx.....

.xx....
x..x...
....x.x
.....x.
....x.x
x..x...
.xx....

..xx...
.x..x..
x....x.
......x
x....x.
.x..x..
..xx...

...xx..
..x..x.
.x....x
x......
.x....x
..x..x.
...xx..

....xx.
...x..x
x.x....
.x.....
x.x....
...x..x
....xx.

.....xx
x...x..
.x.x...
..x....
.x.x...
x...x..
.....xx

这是一个有趣而有趣的问题。享受。:)

注意:将 7 in 更改create_pattern()为另一个数字以产生其他模式。

于 2012-09-30T16:12:07.530 回答