Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i print a pattern like this

There is a question. How do i print a pattern like this

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

I have tried to use for loops but failed...

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

And I don't know how to use for loops to finish it Are there any ways without using for loops to address this problem? Thanks...

like image 947
iamyourmother Avatar asked Apr 12 '26 03:04

iamyourmother


1 Answers

Another possible solution is

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

which gives output

stackoverflow
 tackoverflow
 tackoverflo 
  ackoverflo 
  ackoverfl  
   ckoverfl  
   ckoverf   
    koverf   
    kover    
     over    
     ove     
      ve     
      v  
like image 76
kgf3JfUtW Avatar answered Apr 13 '26 17:04

kgf3JfUtW