我如何打印这样的图案

时间:2017-10-28 04:28:44

标签: python for-loop

有一个问题。 我如何打印这样的图案

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循环来解决这个问题? 感谢...

9 个答案:

答案 0 :(得分: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  

答案 1 :(得分: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

答案 2 :(得分:1)

跟踪表示要打印的字符串片段的两个索引rs = '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

输出:

     <div class = "row"> 
          <div class = "col-md-4 col-md-offset-4">   
           <h2> Please sign in</h2> 

           <input type = "email" id = "usernameInput" 
              class = "form-control formgroup" placeholder = "Enter Name" 
              required = "" autofocus = "" title="please Enter name">
           <button id = "loginBtn" class = "btn btn-lg btn-primary btnblock">
              Sign in</button> 
        </div> 
     </div> 

  </div>

  <div id = "callPage" class = "call-page container">

     <div class = "row"> 
        <div class = "col-md-4 col-md-offset-4 text-center"> 
           <div class = "panel panel-primary"> 
              <div class = "panel-heading">Text chat</div> 
              <div id = "chatarea" class = "panel-body text-left"></div> 
           </div> 
        </div> 
     </div>


     <div class = "row text-center"> 
        <div class = "col-md-12"> 
           <input id = "msgInput" type = "text" placeholder = "Enter message" /> 
           <button id = "sendMsgBtn" class = "btn-success btn">Send</button> 
        </div> 
     </div>

  </div> 

  <script >


        var name; 
        var connectedUser; 

        var conn = new WebSocket('ws://localhost:8000'); 

        conn.onopen = function () { 

        console.log("Connected to the signaling server");
        };

        //when we got a message from a signaling server 
        conn.onmessage = function (msg) { 
        console.log("Got message", msg.data); 
        var data =JSON.parse( msg.data); 
        //    console.log(data.type);

        switch(data.type) { 
              case "login": 

              handleLogin(data.success);

              break; 
              //when somebody wants to call us 
              case "offer": 
              handleOffer(data.offer, data.name); 
              break; 
              case "answer": 
              handleAnswer(data.answer); 
              break; 
              //when a remote peer sends an ice candidate to us 
              case "candidate": 
              handleCandidate(data.candidate); 
              console.log('candidate');
              break; 
              case "leave": 
              handleLeave(); 
              break; 
              default: 
              break; 
        } 
        }; 

        conn.onerror = function (err) { 
        console.log("Got error", err); 
        }; 

        //alias for sending JSON encoded messages 
        function send(message) { 

        //attach the other peer username to our messages
        if (connectedUser) { 
              message.name = connectedUser; 
        } 

        conn.send(JSON.stringify(message)); 
        };


        var loginPage = document.querySelector('#loginPage'); 
        var usernameInput = document.querySelector('#usernameInput'); 
        var loginBtn = document.querySelector('#loginBtn'); 

        var callPage = document.querySelector('#callPage'); 
        var callToUsernameInput = document.querySelector('#callToUsernameInput');
        // var callBtn = document.querySelector('#callBtn'); 

        // var hangUpBtn = document.querySelector('#hangUpBtn'); 
        var msgInput = document.querySelector('#msgInput'); 
        var sendMsgBtn = document.querySelector('#sendMsgBtn'); 

        var chatArea = document.querySelector('#chatarea'); 
        var yourConn; 
        var dataChannel; 
        callPage.style.display = "none"; 

        // Login when the user clicks the button 
        loginBtn.addEventListener("click", function (event) { 
        name = usernameInput.value; 

        if (name.length > 0) { 
              send({ 
              type: "login", 
              name: name 
              }); 
        } 

        });

        function handleLogin(success) { 

        if (success === false) {
              alert("Ooops...try a different username"); 
        } else { 
              loginPage.style.display = "none"; 
              callPage.style.display = "block"; 


              //using Google public stun server 
              var configuration = { 
              "iceServers": [{ "url": "stun:stun2.1.google.com:19302" }] 
              }; 


              yourConn = new RTCPeerConnection(configuration,{optional: [{RtpDataChannels: true}]}); 

              // Setup ice handling 
              yourConn.onicecandidate = function (event) { 
                    console.log('enter into login');
              if (event.candidate) { 
                    send({ 
                    type: "candidate", 
                    candidate: event.candidate 
                    }); 
              } 
              }; 

              //creating data channel 
              dataChannel = yourConn.createDataChannel("channel",  {reliable:true}); 

              dataChannel.onerror = function (error) { 
              console.log("Ooops...error:", error); 
              }; 

              //when we receive a message from the other peer, display it on the screen 
              dataChannel.onmessage = function (event) { 
              chatArea.innerHTML += connectedUser + ": " + event.data + "<br />"; 
              }; 

              dataChannel.onclose = function () { 
              console.log("data channel is closed"); 
              };

        } 
        };

        //when we got an answer from a remote user 
        function handleAnswer(answer) { 
        yourConn.setRemoteDescription(new RTCSessionDescription(answer)); 
        };

        //when we got an ice candidate from a remote user 
        function handleCandidate(candidate) { 
        yourConn.addIceCandidate(new RTCIceCandidate(candidate)); 
        };


        //when user clicks the "send message" button 
        sendMsgBtn.addEventListener("click", function (event) { 

        var val = msgInput.value; 
        chatArea.innerHTML += name + ": " + val + "<br />"; 

        //sending a message to a connected peer 
        dataChannel.send(val); 
        msgInput.value = ""; 
        });
       </script>  

答案 3 :(得分:1)

你可以使用&#39; some_string&#39; .rjust(width,&#39;&#39;)其中width是一个整数值,第二个参数是我的例子中使用空格的字符串。您也可以使用&#39; some_string&#39; .ljust(width,&#39;&#39;)。有关详细信息,请访问此网站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)

答案 4 :(得分: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)

答案 5 :(得分: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

答案 6 :(得分: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  

答案 7 :(得分: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”)

答案 8 :(得分:0)

以下是使用递归函数 printline()的另一种方法。 For loop 不需要。

# 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