如何打印出如下图案

3
有一个问题。 如何打印出这样的图案
stackoverflow
stackoverflo
 tackoverflo
 tackoverfl
  ackoverfl
  ackoverf
   ckoverf
   ckover
    kover
    kove
     ove
     ov
      v

我曾尝试使用for循环,但失败了...


str = "stackoverflow"
k = len(str)
print(str)
print(str[:(k-1)])

我不知道如何使用for循环来完成它。 有没有不使用for循环来解决这个问题的方法呢? 谢谢...


2
你为什么避免使用for循环?使用for或while循环似乎是自然的方法。是的,可能有不用循环就能完成的方法,但这些方法可能会让你更加困惑。 - kgf3JfUtW
那么你将不得不使用一个 while 循环。 - whackamadoodle3000
9个回答

4
另一个可能的解决方案是:
s = "stackoverflow"
toggle = True # If true, remove first char. Else, cut last char.
left = 0 # number of spaces to prepend
right = 0 # number of spaces to append

while s: # while s is not empty
    print(' '*left + s + ' '*right)
    if toggle:
        s = s[1:] # remove first char
        left += 1
    else:
        s = s[:-1] # remove last char
        right += 1
    toggle = not toggle

输出结果

stackoverflow
 tackoverflow
 tackoverflo 
  ackoverflo 
  ackoverfl  
   ckoverfl  
   ckoverf   
    koverf   
    kover    
     over    
     ove     
      ve     
      v  

2

我建议使用 for 循环。一旦你习惯了它们,它们就非常容易使用。这里是一个使用 for 循环的解决方案:

def show(s):
    n = len(s)
    for i in range(n):
        n1 = i // 2
        n2 = i - n1
        print(" " * n1 + s[n1:n-n2])

s = "stackoverflow"
show(s)

输出结果如下:
stackoverflow
stackoverflo
 tackoverflo
 tackoverfl
  ackoverfl
  ackoverf
   ckoverf
   ckover
    kover
    kove
     ove
     ov
      v

如果您真的不想使用 for 循环,可以将其替换为以下方式的 while 循环:

i = 0
while i < n:
    ...
    i += 1

1
保持两个索引lr,它们表示要打印的字符串片段。然后在每次迭代中缩短该片段。
s = 'stackoverflow'

l, r = 0, len(s)      # range of string to print
remove_left = True    # which side of the string to remove
space = 0             # how much space to print to the left

while l < r:
    print('%s%s' % (' ' * int(space/2), s[l:r]))

    if remove_left:
        r-= 1
    else:
        l+= 1

    remove_left = not remove_left
    space += 1

输出:

stackoverflow
stackoverflo
 tackoverflo
 tackoverfl
  ackoverfl
  ackoverf
   ckoverf
   ckover
    kover
    kove
     ove
     ov
      v

1

你可以使用'some_string'.rjust(width, ' '),其中width是一个整数值,第二个参数是一个字符串,在我的例子中使用了一个空格。另外,你也可以使用'some_string'.ljust(width, ' ')。想要了解更多信息,请查看这个网站https://www.programiz.com/python-programming/methods/string/rjust

例如:

def word_reduce(word):
   n = word.__len__()
   for i in range(n):
       left = i // 2 
       right = i - left
       result = word[left:n-right]
       print((' ').rjust(left + 1) + result)

s = 'stackoverflow'
word_reduce(s)

编写一些代码,以便您可以给出答案,而不是指向参考资料。 - skrubber

1
您可以使用递归的概念。
def stackoverflow(pattern,alternate=0):
    if len(pattern) == 1:
        #base condition for recursion
        return 
    elif alternate == 0:
        #first time execution
        print(pattern)
        alternate = alternate + 1
        stackoverflow(pattern, alternate)
    elif alternate % 2 != 0:
        # truncate from right side
        pattern = pattern[:-1]
        print(pattern)
        alternate = alternate + 1
        stackoverflow(pattern, alternate)
    else:
        #truncate from left side
        pattern = pattern[1:]
        print(pattern)
        alternate = alternate + 1
        stackoverflow(pattern,alternate)

0
你可以尝试只使用一个计数器来实现这个功能。
string = "stackoverflow"
loop=0
while string.replace(' ','')!='':
   print(' '*(loop//2)+string+' '*(loop//2))
   if loop%2==0:
       string=string[:-1]
   else:
       string=string[1:]
   loop=loop+1

0

你可以使用简单的切片操作符:

a='stackoverflow'
print(a)

    #printing first whole string
    for i in range(len(a)):
        #loop range of the string

        if i%2==0:
            #here the logic see the problem you will find a pattern that it removing
            #last character when loop number is even and update the string with current
            #sliced string
            #print(i)
            # if you want use this print for understanding track of slicing
            print('{:^12s}'.format(a[:-1]))

            #Removing last character if loop index is even
            a=a[:-1]
            #update the string with current sliced string
        else:
            #print(i)
            #use this print for tracking of sliced string
            print('{:^14s}'.format(a[1:]))
            #remove first character if loop index is not even or loop index is odd.

            a=a[1:]
            #update the current string with sliced string

输出:

stackoverflow
stackoverflo
 tackoverflo  
 tackoverfl 
  ackoverfl   
  ackoverf  
   ckoverf    
   ckover   
    kover     
    kove    
     ove      
     ov     
      v  

0

正如 OP 所述,不能使用循环。硬编码算作有效答案吗?

print(“stackoverflow”)
print(“stackoverflo”)
print(“ tackoverflo”)
print(“ tackoverfl”)
print(“  ackoverfl”)
print(“  ackoverf”)
print(“   ckoverf”)
print(“   ckover”)
print(“    kover)
print(“    kove”)
print(“     ove”)
print(“     ov”)
print(“      v”)

0

这里有另一种使用递归函数printline()的方法。不需要for循环

# Recursive function
def printline(string, cutleft, padindex):
    # Print out the required line
    print(string.rjust(padindex+len(string)))

    # Last character to print out
    if len(string) == 1:
        return

    # Deciding to trim the left or right part of the string
    if cutleft:
        printline(string[1:], 0, padindex + 1)
    else:
        printline(string[:-1], 1, padindex)

# Calling the recursive function with initial value
printline('stackoverflow', 0, 0)

这是输出结果。

stackoverflow
stackoverflo
 tackoverflo
 tackoverfl
  ackoverfl
  ackoverf
   ckoverf
   ckover
    kover
    kove
     ove
     ov
      v

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接