I went a step further and made it so the user can actually decide how many rows they want generated. And it gives the user a chance to run the program again and choose how many rows again.
That's all for now, thanks for reading!
Here is my code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# PascalsTriangle.py | |
# Christian Munoz | |
# 04/15/2015 | |
import math | |
import sys | |
import time | |
def combination(n, r): | |
"""Calculates the combinations for the numbers entered.""" | |
return int((math.factorial(n)) / ((math.factorial(r)) * math.factorial(n - r))) | |
def pascals_triangle(rows): | |
"""This is the actual Pascal's Triangle function that will generate the amount of rows passed in.""" | |
result = [] | |
for count in range(rows): | |
row = [] | |
for element in range(count + 1): | |
row.append(combination(count, element)) | |
result.append(row) | |
return result | |
def delay(): | |
"""This function suspend the thread for around 1 second and gives the illusion of loading.""" | |
time.sleep(1.0) | |
def run_again(): | |
"""This function will run the next game if the player wants to start again.""" | |
decision = input("\nWould you like to run the program again? Y/N ") | |
print(" ") | |
decision = decision.lower() | |
if decision == "yes" or decision == "y": | |
main() | |
else: | |
print("See you later!") | |
delay() | |
sys.exit() | |
def main(): | |
"""This function will first ask how many lines of the triangle they want to see.""" | |
user_choice = eval(input("How many rows of Pascal's Triangle do you want? ")) | |
print(" ") | |
# This makes sure that the number will always be an integer. | |
user_choice = math.floor(user_choice) | |
# This checks to make sure the entry is a valid entry. | |
if user_choice < 1: | |
print("That is not a valid entry!\n") | |
main() | |
# If the entry was valid, then execute code. | |
else: | |
for row in pascals_triangle(user_choice): | |
print(row) | |
run_again() | |
if __name__ == "__main__": | |
main() | |
sys.exit() |
No comments:
Post a Comment