How to make this for loop in Python work?

后端 未结 3 624
予麋鹿
予麋鹿 2021-01-19 16:55

I want to spit out a list of palindromes until a certain letter I give.

It\'s about this part:

def pyramid_palindrome(last_letter):
    for letter in         


        
3条回答
  •  时光说笑
    2021-01-19 17:40

    Your code is more complicated than it needs to be, and does unnecessary work generating each string of letters from scratch.

    I'm not sure why you don't want to import the letter string from the string module, but you can easily generate the string of letters once and then slice it to get the substrings required to build each palindrome. The code below works on Python 2 or 3.

    def pyramid_palindrome(last_letter):
        letters = ''.join([chr(i) for i in range(97, last_letter)])
        for i in range(last_letter - 97):
            print(letters[:i] + letters[i::-1])
    
    pyramid_palindrome(102)
    

    output

    a
    aba
    abcba
    abcdcba
    abcdedcba
    

    Alternatively, keep letters as a list and use .join on the sliced lists:

    def pyramid_palindrome(last_letter):
        letters = [chr(i) for i in range(97, last_letter)]
        for i in range(last_letter - 97):
            print(''.join(letters[:i] + letters[i::-1]))
    

    It's theoretically faster to add two lists than two strings, although there are optimizations in CPython for small strings so you may not notice the difference unless the strings are longer than 1000 or so. OTOH, calling .join once on letters is probably better than calling it for each palindrome.


    Here's a minor variation of the first version. We save all the palindromes into a list of strings. Then the caller can join that list of strings into one string and print it with one print call.

    def pyramid_palindrome(last_letter):
        letters = [chr(i) for i in range(97, last_letter)]
        return [''.join(letters[:i] + letters[i::-1])
            for i in range(last_letter - 97)]
    
    print('\n'.join(pyramid_palindrome(102)))
    

提交回复
热议问题