Advertisement
gruntfutuk

triangle

Jun 11th, 2018
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. ''' Beginner Python exercise to print an Isosceles triangle of asterisks with a user specified number of asterisks
  2.     in the base (reduced by one to odd number if an even number is supplied). There is a space between each asterisk.
  3. '''
  4.  
  5. ''' one liner - cryptic '''
  6. def triangle_in_one():
  7.     print(*(" " * i + " *" * j for j, i in enumerate(range(int((int(input('Base size: ')) + 1) / 2) * 2, 0, -1))), sep="\n")
  8.  
  9. def triangle(base: int) -> str:
  10.     ''' return print string of asterisk triangle of indicated base size '''
  11.     if not isinstance(base, int):
  12.         raise TypeError(f'{base} not valid - triangle function requires an integer parameter')
  13.     if base < 2:
  14.         raise ValueError(f'{base} not valid - triangle function requires a positive integer over 1 parameter')
  15.     apex = int((base + 1) / 2) * 2
  16.     triangle_str = ''
  17.     for asterisks, spaces in enumerate(range(apex, 0, -1)):
  18.         triangle_str += (f'{" " * spaces}{" *" * asterisks}\n')
  19.     return triangle_str
  20.  
  21. def triangle_one_better(rows):
  22.     return '\n'.join('{:^{width}}'.format(('* ' * row), width=rows * 2 + 1) for row in range(1, rows + 1))
  23.  
  24. if __name__ == "__main__":
  25.     triangle_in_one()
  26.     base = int(input('Base size for rest of solutions: '))
  27.     print(triangle(base))
  28.     print(triangle_one_better(base))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement