fork download
  1. def diamond(n):
  2. """
  3. print a diamond pattern with asterisks of given size (must be odd)
  4. if not odd, return ""
  5.  
  6. example:
  7. diamond(3)
  8. # *
  9. # ***
  10. # *
  11. """
  12. # TODO: Implement this function
  13. if n % 2 == 0:
  14. return ""
  15.  
  16. for i in range(1, n + 1, 2):
  17. spaces = (n - i) // 2
  18. print(" " * spaces + "*" * i + " " * spaces)
  19.  
  20. for i in range(n-2, 0, -2):
  21. spaces = (n - i) // 2
  22. print(" " * spaces + "*" * i + " " * spaces)
  23.  
  24.  
  25. # ===== Provided by the TA. Do not modify. =====
  26. import io
  27. import sys
  28.  
  29.  
  30. def main() -> None:
  31. n = int(input())
  32. captured = io.StringIO()
  33. real_stdout = sys.stdout
  34. sys.stdout = captured # everything diamond() prints is collected here
  35. try:
  36. diamond(n)
  37. finally:
  38. sys.stdout = real_stdout
  39. for line in captured.getvalue().splitlines():
  40. print(line.rstrip()) # spaces at the end of a line are ignored
  41.  
  42.  
  43. main()
  44.  
Success #stdin #stdout 0.07s 14192KB
stdin
7
stdout
   *
  ***
 *****
*******
 *****
  ***
   *