Nested Triangle in Python

青春壹個敷衍的年華 提交于 2019-12-13 09:36:53

问题


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,

Example output for 5 value

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]))


回答1:


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])


来源:https://stackoverflow.com/questions/47265894/nested-triangle-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!