How to make this for loop in Python work?

后端 未结 3 650
予麋鹿
予麋鹿 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:37

    Your this entire logic could be simplified using string slicing along with string.ascii_lower as:

    import string
    alphs = string.ascii_lowercase   # returns string of lower case characters
    last_letter = 'f'
    
    for i in range(len(alphs)):
        print alphs[:i]+alphs[i::-1]
        if alphs[i] == last_letter:  # break the loop when `last_letter` is found
            break
    

    which will generate output as:

    a
    aba
    abcba
    abcdcba
    abcdedcba
    abcdefedcba    
    

    Edit: If you do not want to import string, you may get the string of lowercase characters via using:

    alphs = ''.join(chr(i) for i in range(97,123))
    

提交回复
热议问题