python循环嵌套三角形_Python中的嵌套三角形

1586010002-jmsa.png

My assingment

At each level the complete triangle for the previous level is placed into an extra outer triangle. The user should be asked to input the two characters to be used and the width of the innermost triangle, which must be odd. In addition to the test for negative input the function should test whether the supplied number is odd and display an appropriate message if it is not.

I need to print 3 triangles but every one of them includes other. It needs to get printed with two different character(like *-) and the user have to specify the length of innermost triangle and which has to be an odd number. Example,

Ok, let me explain my way,

Every triangle should be in dictionary.

tri1 = {1:"*****", 2:"***", 3:"*"}

tri2 = {1:"..........", ...}

And couldn't find how I can deal with user input?

If enter 5,

length - 5 unit, height 3 unit

length - 11 unit, height 6 unit

length - 23 unit, height 12 unit.

How can i know? What is the logic?

Ok lets say if I did. I understand I should put a tringle in another triangle with nested loop, can simply iterate it another dictionary but, I need to check second character's position.

Thanks in advance.

My code,

ch1, ch2 = input("Please enter the characters you want to use: ")

num = int(input("Please specify the length of innermost triangle(only odd number): "))

if (num % 2 == 0) or (num < 3):

print("Number can not be even, less then 3 and negative")

num2 = (2 * num) + 1

num3 = (2 * num2) +1

tri1 = {}

tri2 = {}

tri3 = {}

for i in range(3):

tri1[i] = ch1*num

num -= 2

check = 1

cont = 0

var = 1

for ii in range(6):

tri2[ii] = ch2*check

check += 2

if (ii >= 3):

tri2[ii] = ch2*var + tri1[cont] + ch2*var

cont += 1

var += 2

for i in tri1:

print('{:^5}'.format(tri1[i]))

for i in tri2:

print('{:^11}'.format(tri2[i]))

解决方案

The dictionary can be created using a simple function:

def create_tri_dict(tri_chars, tri_height):

level_str = {0:tri_chars[0]}

for i in range(1,tri_height):

level_length = i *2 +1

tri_char = tri_chars[i%2]

level_str[i] = level_str[i-1] + '\n' + tri_char * level_length

return level_str

Then the main logic of your program could be:

tri_chars = input('Input triangle characters: ')

tri_length = int(input('Input triangle base length: '))

tri_height = (tri_length + 1)//2

if tri_length %2 == 0:

raise Exception('Triangle base length not odd')

tri_dict = create_tri_dict(tri_chars, tri_length)

Then to print the final 3(?) triangles:

print(tri_dict[tri_height-2])

print(tri_dict[tri_height-1])

print(tri_dict[tri_height])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值