【每日一题0622】打印正方形图案

题目:给你一个整数,返回一个和整数一样长和一样宽的形状。整数是介于1和50之间。
难度:简单
来源:codewars.com

示例:当n=3,打印的图形是:

 +++
 +++
 +++
def generate_shape(n):
    pass

assert generate_shape(3) == '+++\n+++\n+++'
assert generate_shape(8) == '++++++++\n++++++++\n++++++++\n++++++++\n++++++++\n++++++++\n++++++++\n++++++++'
def generate_shape(n):
	for i in range(n):
		for j in range(n-1):
			print("*",end='')
		print("*")
generate_shape(5)
	int i=4;
	for(int j=0;j<i;j++) {
		for(int f=0;f<i;f++) {
			System.out.print("*");
		}
		System.out.println("");
	}

def generate_shape(n):

if 1 < n < 50:
    return '\n'.join(['+' * n] * n)

assert generate_shape(3) == ‘+++\n+++\n+++’
assert generate_shape(8) == ‘++++++++\n++++++++\n++++++++\n++++++++\n++++++++\n++++++++\n++++++++\n++++++++’

def func123(n):
    str = ''
    if 1<n<50:
        for i in range(n):
            for i in range(n):
                str +='+'
            str += "\n"
    else:
        return '请输入1~50之间的数字'
    return str
print(func123(49))

import org.junit.jupiter.api.Test;

public class GenerateShape {
    public void generateShape(int num){
        if (num>0 && num<50){
            for (int i=0; i<num; i++){
                for (int n=0;n<num; n++){
                    System.out.print("*");
                }
                System.out.println("");
            }
        }else {
            System.out.println("Please enter an integer between 1 and 50");
        }

    }


    @Test
    void runTests(){
        generateShape(49);
    }
}
def generate_shape(n):
    for i in range(n):
        print('+'*n)
#coding=utf-8

def fun_a(num):
    for i in range(num):
        print("+"*num)
        # print("\n")


if __name__ == '__main__':
    a=int(input("请输入整数,范围为1-50"))
    fun_a(a)
输入或粘贴代码
def squre(a):
    for i in range(a+1):
        print(a * "+ ")

if __name__ == '__main__':
    a = int(input("请输入整数介于1和50之间。\n"))
    squre(a)

‘’’
题目:给你一个整数,返回一个和整数一样长和一样宽的形状。整数是介于1和50之间。
‘’’
def zhengFX():
a = 0
try:
a = int(input(‘请输入0-50的整数:’))
except :
print(‘请输入正整数’)
else:
if a <= 0:
print(‘请输入大于0的数’)
elif a > 50:
print(‘请输入小于等于50的数’)
else:
for i in range(0, a):
print(a*"+")
zhengFX()

题解

def generate_shape(n):
    return "\n".join(["+"*n]*n)

:partying_face: :partying_face: :partying_face: :partying_face: :partying_face: :partying_face:

image
考虑到性能方面没有使用两个for循环

def generate_shape(n):
    s=''
    for i in range(n):
        if i<n-1:
            s=s+'+'*n+'\n'
        if i ==n-1:
            s=s+'+'*n
    return  s
assert generate_shape(3)=='+++\n+++\n+++'
关闭