Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Print an asterisk triangle without for-loops
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import logging
import os
import sys
def parse_args() -> argparse.Namespace:
parser: argparse.ArgumentParser = argparse.ArgumentParser()
parser.add_argument('n', metavar='N', type=int)
return parser.parse_args()
def asterisk_triangle(remaining_level: int, _current_level: int = 1) -> str:
res: str = ""
if remaining_level == 0:
return res
if remaining_level < 0:
raise ValueError('remaining level cannot be less than 0')
asterisk: str = '*' * (_current_level * 2 - 1)
space: str = ' ' * (remaining_level - 1)
res = f'{space}{asterisk}{os.linesep if remaining_level > 1 else ""}'
return res + asterisk_triangle(remaining_level - 1, _current_level=_current_level + 1)
def main() -> int:
logging.basicConfig()
args: argparse.Namespace = parse_args()
try:
print(asterisk_triangle(args.n))
except ValueError as e:
logging.exception(e)
return os.EX_OK
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment