他的要求是不要在函数里面打印,结果是用来返回的,不是用来打印的,这是这个题目唯一值得思考的地方
return结果比print难一些 SixPy 发表于 2017-6-10 01:12
str自带 center 方法,何必舍近求远~
{:9_239:}
这个厉害了,你这么一说我就想起来 ,str的确自带了居中的这个方法,
这都能想到,厉害了 def diamond(n):
m=1
a=[]
if n<0 or n%2==0:
return None
else:
while m<n:
a.append(''*((n-m)//2)+'*'*m+''*((n-m)//2))
m+=2
else:
while m>0:
a.append(''*((n-m)//2)+'*'*m+''*((n-m)//2))
m-=2
return '\n'.join(a,)
print(diamond(17))
利用 y=|x| 函数的特性,正是空格的规律
def diamond(n):
"""diamond(n) -> str, print diamond which sized n (integer)"""
if n<=0 or n%2==0:
return None
else:
result = ""
for i in range(-(n-1)//2,(n+1)//2): # 利用函数 y=abs(x)
result += " "*abs(i)+"*"*(n-abs(i)*2)+"\n" # 空格数+星号数
return result def diamond(x):
if x < 0 or x % 2 == 0:
return None
else:
for i in range(1, x//2+2):
print(' ' * (8-i) + '*' * (2*i-1))
for i in range(x//2+1, x+1):
print(' ' * abs(7-i) + '*' * (x - 2*(i-7)))
def func(num):
flag, status = 1, 2
while flag > 0:
print('{0:^{1}}'.format('*'*flag,num))
flag += status
if flag >= num: status = -2 n = int(input("please enter one number:"))
if n % 2 ==0 or n < 0:
print("please enter odd number")
else:
x = 1
z = int((n-1)/2)
y = 1
while True:
print(" "*z,"*"*x,end ="\n" )
x = x + 2
z = z - 1
if x > n:
break
while True:
print(" "*y,"*" * (n-2),end = "\n")
y = y + 1
n = n - 2
if n < 0:
break def diamond(n):
if n % 2 == 0 or n < 0:
return None
else:
s = ''
for i in range(n // 2 + 1):
s += (n // 2 - i) * ' ' + (2 * i + 1) * '*' + '\n'
for k in range(n // 2):
s += (k + 1) * ' ' + (n - 2 - 2 * k) * '*' + '\n'
return s
print(diamond(21)) 看看 def fun62(num):
str1 = ""
if not num%2 or num < 0:
return None
for each in range(1,num+3):
if each < (num+3)//2:
star = 2 * each - 1
else:
star = 2 * (num - each) + 1
str1 += " " * ((num-star)//2) + "*" * star + "\n"
return str1
print(fun62(15)) SixPy 发表于 2017-6-9 20:48
神仙语言{:10_285:} 看着简单,其实不简单。
def pstars(n):
if n < 0 or n % 2 == 0:
return None
for i in range(1, int((n+3)/2)):
print(' '*(n-i-2) + '*'*(2*i-1) + ' '*(n-i-2))
for j in range(int((n+3)/2), n+1):
print(' '*(j-3) + '*'*(2*n-2*j+1) + ' '*(j-3)) 不知道为啥是歪的def diamond(num):
if num%2 == 0 or num <0:
return None
result =[]
new_result = []
a = num // 2 + 1
max_num = 2*a +1
m_num = max_num//2
for each in range(1,max_num,2):
result.append(each)
for each in range(max_num,0,-2):
result.append(each)
for each in result:
print(' '*((max_num-each)//2),end='')
for i in range(each):
print('*',end='')
print()
diamond(15)
膜拜 import nummpy
def diamond(num):
pass
if n % 2 != 0 or n >= 0:
num = int(input('请输入奇数:'))
print(diamond(num))
else:
num = int(input('请重新输入奇数: '))
print(diamond(num)) 1
页:
1
[2]