从用户输入创建字符三角形

时间:2016-10-04 01:49:29

标签: python

对于作业,如果字符等于偶数,我假设使用用户输入制作三角形。三角形的高度最多可打印5行,左侧应为字符串的左半部分,三角形的右侧应为字符串的右侧。

Example of what the triangle is suppose to look like

问题是我无法弄清楚如何在不进行硬编码的情况下将三角形分成两半,或者如何在没有循环的情况下正确显示空白区域(不允许在分配中)。现在,如果我要投入" ab"它会回来:

     aabb
    aabbaabb
   aabbaabbaabb
  aabbaabbaabbaabb
 aabbaabbaabbaabbaabb

而不是:

         aabb
       aaaabbbb
     aaaaaabbbbbb
   aaaaaaaabbbbbbbb
 aaaaaaaaaabbbbbbbbbb

这是我的代码:

#GET Users String
userString = input("Please enter a string with a value of 7 or less characters: ")

#CALCULATE IF userString is less than or equal to 7 and is even 
if len(userString) <= 7 and len(userString) % 2 == 0:
    print (" " * 5 + userString)
    print(" " * 4 + userString * 2)
    print(" " * 3 + userString * 3)
    print(" " * 2 + userString * 4)
    print(" " + userString * 5)

#CALCULATE IF userString is less than 7 but and off 
elif len(userString) <=7 and len(userString) % 2 == 1:
    print("You are odd")

#CALCULATE IF userString is over 7 characters
else:
    print ('The string is too long. \nGood-bye!')

2 个答案:

答案 0 :(得分:2)

以下是您可以这样做的方法:

def print_next(st, index):
   if index < 6:    # have not reached 5 - print offset and string
      offset = 6-index
      print '  '*offset+st
      index=index+1   # increase counter
      print_next((st[0:2]+st[-2:len(st)])*index,index) # recursively go next


print_next('aabb',1) # initial call with index set to 1

答案 1 :(得分:0)

我认为您可以使用堆栈来保存每一行,这样您就可以轻松获得类似三角形的输出。另外因为你不能使用循环所以我的建议是递归的。

public_stack = []

def my_func(original_str, line_count, space_num):
    if(line_count == 0):
        return
    times = line_count * 2
    half_length = len(original_str) / 2
    left_str = original_str[:half_length] * times
    right_str = original_str[half_length:] * times
    space_str = ' ' * space_num
    complete_str = space_str + left_str + right_str
    global public_stack
    public_stack.append(complete_str)
    space_num += len(original_str)
    line_count -= 1
    return my_func(original_str,line_count,space_num)

if __name__ == '__main__':
    original_str = 'ab'
    line_count = 5
    space_num = 0
    my_func(original_str,line_count,space_num)

    global public_stack
    for i in range(len(public_stack)):
        line = public_stack.pop()
        print line