E04 - Pyramide⚓︎
Le problème
Solution⚓︎
🐍 Script Python
"""
author: Franck CHAMBON
problem: https://prologin.org/train/2011/semifinal/pyramide
"""
# 0. Cœur du problème
def affiche_pyramide(hauteur: int) -> None:
"""Affiche une pyramide de `hauteur` donnée.
>>> affiche_pyramide(1)
*
>>> affiche_pyramide(3)
*
**
***
"""
return print("\n".join("*" * h for h in range(1, hauteur + 1)))
import doctest
doctest.testmod()
# 1. Entrée
hauteur = int(input())
# 2. Sortie
affiche_pyramide(hauteur)
Variante simple⚓︎
🐍 Script Python
def affiche_pyramide(hauteur: int) -> None:
for h in range(1, hauteur + 1):
print("*" * h)
Variante sans sucre⚓︎
Une version sans la multiplication str * int
serait :
🐍 Script Python
def affiche_pyramide(hauteur: int) -> None:
for h in range(1, hauteur + 1):
# Affiche une ligne de `h` étoiles
for i in range(h):
print("*", end="")
print()
Cette dernière variante peut facilement s'écrire en C.
Variante sans print
dans la fonction⚓︎
On utilise cependant le print
dans le doctest, afin qu'il reste simple.
🐍 Script Python
"""
author: Franck CHAMBON
problem: https://prologin.org/train/2011/semifinal/pyramide
"""
# 0. Cœur du problème
def pyramide(hauteur: int) -> None:
"""Renvoie une pyramide de `hauteur` donnée.
>>> print(pyramide(1))
*
>>> print(pyramide(3))
*
**
***
"""
return "\n".join("*" * h for h in range(1, hauteur + 1))
import doctest
doctest.testmod()
# 1. Entrée
hauteur = int(input())
# 2. Sortie
print(pyramide(hauteur))
Variante récursive⚓︎
🐍 Script Python
def affiche_pyramide(hauteur: int) -> None:
if hauteur > 0:
affiche_pyramide(hauteur - 1) # le début, sauf la dernière ligne
print("*" * hauteur) # la dernière ligne