简体   繁体   中英

How to print a pattern with 0 and * in python3

I need to create a program that asks the user for an integer and depending on what the integer is, I need to return this output:

0000*
000*0
00*00
0*000
*0000

This output would be an example if the user put in 5.

If the user put 3 then it would be:

00*
0*0
*00

So far all I have is:

def pattern(x):
    for i in range(x):
        print('0' * x)

x = int(input('Enter an integer:'))
pattern(x)

No need for any imports:

def pattern(x):
    for i in reversed(range(x)):  # This just says start counting from the top, so x is 5, it'll start at 5 and go down to 1.
        res = ['0'] * x  # here we create a list containing x '0', so if x is 5 we will get the following ['0', '0', '0', '0', '0']
        res[i] = '*'  # Here we say replace the item at position i with *, so on the first iteration, if x is 5, we're saying replace item 5 with *, on the next run we replace 4, then 3 and so on.
        res = ''.join(res) # Join the list back to a string.
        print(res)
x = int(input('Enter an integer:'))
pattern(x)

For each row you can create a list with '0' . Then switch the value to 'X' at the correct position. Now join everything together to a string an print the string.

def pattern(x):
    for i in range(x):
        v = ['0'] * x
        v[x - i - 1] = '*'
        print(''.join(v))

Combining this idea with the ideas of some other answers:

def pattern(x):
    for i in range(x):
        print(''.join('0' if i != j else '*' for j in reversed(range(x))))

You may find it easier to use a just create an initial list (or deque) and shift/rotate it every iteration:

from collections import deque
size = int(input('Enter an integer: '))
items = deque(['0' for _ in range(size - 1)] + ['*'])
for _ in range(size):
    print(''.join(items))
    items.rotate(-1) # rotate left once

Output:

>>> Enter an integer: 5
0000*
000*0
00*00
0*000
*0000

Just simple logic, might not be the most pythonic.

def pattern(x):
    for i in range(x):
        for j in range(x):
            if i + j == x - 1:
                print('*', end='')
            else:
                print('0', end='')
        print()


x = int(input('Enter number\n'))
pattern(x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM