Python Forum
Could you explain each part of the code? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Could you explain each part of the code? (/thread-36697.html)



Could you explain each part of the code? - Tsushida - Mar-19-2022

Hello! Could you guys explain to me each part of this code right here:

n = int(input())
alpha = 'abcdefghijklmnopqrstuvwxyz'
print(*[''.join([alpha[min(abs(i-j), abs(n - i - j - 1) % len(alpha))] for j in range(n)]) for i in range(n)], sep='\n')



RE: Could you explain each part of the code? - deanhystad - Mar-20-2022

Ask specific questions. You must understand some of it. If not, trying to explain it to you is a waste of everybody's time. You wont understand the explanations.

I appears to be a palindrome generator.
i is start of the palindrome (alpha[i]).
Two sequences are calculated. One counts down from i to zero and then back up, the other counts down from (n-j-1) to zero and back up.
The two sequences cross at the center.
The lesser value from the two sequences is used for the palindrome.
Each sequence is responsible for producing half of the palindrome.

Assume n == 5
Look at what abs(i-j) produces: (0, 1, 2, 3, 4), (1, 0, 1, 2, 3), (2, 1, 0, 1, 2), (3, 2, 1, 0, 1), (4, 3, 2, 1, 0).
Look at what abs(n - i - j - 1) % len(alpha)) produces: (4, 3, 2, 1, 0), (3, 2, 1, 0, 1), (2, 1, 0, 1, 2), (1, 0, 1, 2, 3), (0, 1, 2, 3, 4)


RE: Could you explain each part of the code? - Larz60+ - Mar-20-2022

Expecting n = int(input()) to always return a number would be naive.
Someone will type text, so line 1 should be expanded to something like:
def get_num():
    n = None

    while(not isinstance(n, int)):
        n = input("Please enter a number: ")
        try:
            n = int(n)
        except ValueError:
            print(f"{n} is not numeric, try again")
    return n

n = get_num()
also, there is a builtin for line 2 in string:
# at top of script:
import string
# ...
alpha = string.ascii_lowercase