我必须制作一颗钻石,它必须具有用户所需的完全相同的线条数量。我被困了,我已经思考了很长时间,但没有到达任何地方。我的钻石需要如下图所示:
答案 0 :(得分:1)
这也应该有效:
nl = 5
for line in range(nl):
if line < nl/2:
spc = (int(nl/2-line))*' '
dsh = (line*2+1)*'_'
print(spc, dsh)
else:
spc = (int(line-nl/2+1))*' '
dsh = ((nl-line)*2-1)*'_'
print(spc, dsh)
它会产生:
_
___
_____
___
_
答案 1 :(得分:0)
如果以文本形式打印出来,请尝试使用for循环,'_'字符和空格
编辑: 这是一些伪代码,
For i in range(totalLines/2):
For j in range(totalLines/2 - i):
Print(" ")
For j in range(i):
Print("_")
For i in range(totalLines/2):
For j in range(totalLines/2 - i):
Print("_")
For j in range(i):
Print(" ")
答案 2 :(得分:0)
标题说它需要在Python Turtle中完成。但是哦,好吧。我想出了一个能够满足我要求的代码,唯一的问题是上半部分和下半部分之间存在差距。
这是我的代码:
import turtle
clyde = turtle.Turtle()
P.S.: I speak spanish, but you should understand my code easily.
while True:
try:
lineas = int(raw_input('Cuantas lineas quieres que tenga tu rombo?(Numero Impar): '))
assert lineas > 2 and lineas < 646 and lineas % 2 != 0
break
except AssertionError:
if lineas > 646 or lineas < 2:
print "El numero de lineas debe ser entre de 3 a 645."
print
else:
print 'El numero deber ser un impar positivo.'
print
except:
print 'Ingresa un numero valido'
print
if lineas <= 21:
clyde.speed(8)
elif lineas <= 41:
clyde.speed(5)
else:
clyde.speed(0)
canvas = 200
if lineas > canvas:
canvas = lineas + 1
def trasPunta(punta):
clyde.pu()
clyde.goto(0, punta)
clyde.pd()
clyde.fd(1)
clyde.pu()
clyde.back(1)
def drawLine(inc):
clyde.pd()
clyde.fd(inc * (canvas / float(lineas)))
clyde.pu()
clyde.bk(inc * (canvas / float(lineas)))
trasPunta(canvas / 2.0)
a = 2
for i in range(lineas / 2):
clyde.right(90)
clyde.fd(canvas / float(lineas))
clyde.right(90)
clyde.fd(canvas / float(lineas))
clyde.right(180)
drawLine(a)
a += 2
trasPunta((-canvas / 2.0) + (canvas / float(lineas)))
b = 2
for i in range((lineas / 2) - 1):
clyde.left(90)
clyde.fd(canvas / float(lineas))
clyde.left(90)
clyde.fd(canvas / float(lineas))
clyde.left(180)
drawLine(b)
b += 2
答案 3 :(得分:0)
虽然您已经接受了自己的解决方案,但看着它的吸引力却很痛苦。你总是偏向于思考,总是从左到右工作,把问题分成两半。让我们绘制一个单一的形状,在双向思考的同时解决问题:
import turtle
lines = int(raw_input('How many lines do you wish your diamond to have? (Odd number only): '))
half = lines // 2
canvas = max(200, lines + 1)
shrinkage = canvas / float(lines)
clyde = turtle.Turtle()
clyde.speed('fastest') # because I have no patience
clyde.forward(canvas)
clyde.penup()
clyde.left(90)
clyde.forward(shrinkage)
clyde.left(90)
for i in range(1, half + 1):
clyde.forward(shrinkage)
for j in range(2):
clyde.pendown()
clyde.forward(canvas - i * shrinkage * 2) # visible horizontal lines
clyde.penup()
clyde.left(90)
clyde.forward(((i * 2) + j) * shrinkage) # invisible vertical lines
clyde.left(90)
clyde.hideturtle()
turtle.mainloop()
在这个例子中,我故意忽略输入错误检查以及将端点强制转换为单个像素。您可以稍后再添加:
观看您的解决方案如何绘制然后观看这个。请注意,浪费的动作较少。它从左到右和从右到左绘制。它将图案绘制为一系列变得更窄更高的矩形:
但保留关键线不可见。如果你用鼠标跟着它,你可以看到它实际上是一个spriral。