Advertisement
CodingComputing

Asterisk pattern solution

Apr 4th, 2024
793
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. # *Asterisk Pattern* solution by @CodingComputing
  2. size = 7  # given parameter, expected to be ODD
  3. center_idx = size // 2  # get the index of the central row/column
  4. for row_idx in range(size):  # to construct each row and print
  5.     if row_idx == center_idx:  # if the row is the central row...
  6.         row_chars = ["*"] * size  # print all *s for the central row
  7.     else:  # for a non-centre row...
  8.         row_chars = [" "] * size  # initialization, we'll fill * where needed
  9.         for col_idx in range(size):  # for columns within the current row...
  10.             # check if we are on any of the diagnoals
  11.             is_on_descending_diagonal = col_idx==row_idx
  12.             is_on_ascending_diagonal = col_idx==(size-1-row_idx)
  13.             # -1 is needed because row_idx and col_idx are zero indexed
  14.             is_on_centre_col = col_idx==center_idx  # check if on the central column
  15.             if (
  16.                 is_on_ascending_diagonal or
  17.                 is_on_descending_diagonal or
  18.                 is_on_centre_col
  19.             ):  # Any of these conditions
  20.                 row_chars[col_idx] = '*'  # change the initialized space to *
  21.     print(" ".join(row_chars))  # join on a space to get separation
  22.    
  23. # Output:
  24. #
  25. # *     *     *
  26. #   *   *   *  
  27. #     * * *    
  28. # * * * * * * *
  29. #     * * *    
  30. #   *   *   *  
  31. # *     *     *
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement