8000 Merge branch 'rename-challenges' · rakash/python-basics-exercises@e775089 · GitHub
[go: up one dir, main page]

Skip to content

Commit e775089

Browse files
committed
Merge branch 'rename-challenges'
2 parents bb69aab + e7cefbf commit e775089

23 files changed

+1155
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# 4.5 - Challenge: Pick Apart Your User's Input
2+
# Solution to code challenge
3+
4+
5+
# Return the upper-case first letter entered by the user
6+
7+
user_input = input("Tell me your password: ")
8+
first_letter = user_input[0]
9+
print("The first letter you entered was:", first_letter.upper())
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# 4.9 - Challenge: Turn Your User Into a L33t H4x0r
2+
# Solution to challenge
3+
4+
5+
# Turn a user's input into leetspeak
6+
7+
my_text = input("Enter some text: ")
8+
9+
my_text = my_text.replace("a", "4")
10+
my_text = my_text.replace("b", "8")
11+
my_text = my_text.replace("e", "3")
12+
my_text = my_text.replace("l", "1")
13+
my_text = my_text.replace("o", "0")
14+
my_text = my_text.replace("s", "5")
15+
my_text = my_text.replace("t", "7")
16+
17+
print(my_text)
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# 5.3 - Challenge: Perform Calculations on User Input
2+
# Solution to challenge
3+
4+
5+
# Receive two input numbers and calculate their power
6+
7+
base = input("Enter a base: ")
8+
exponent = input("Enter an exponent: ")
9+
result = float(base) ** float(exponent)
10+
print(f"{base} to the power of {exponent} = {result}")
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# 6.3 - Challenge: Convert temperatures
2+
# Solution to challenge
3+
4+
5+
def convert_cel_to_far(temp_cel):
6+
"""Return the Celsius temperature temp_cel converted to Fahrenheit."""
7+
temp_far = temp_cel * (9 / 5) + 32
8+
return temp_far
9+
10+
11+
def convert_far_to_cel(temp_far):
12+
"""Return the Fahrenheit temperature temp_far converted to Celsius."""
13+
temp_cel = (temp_far - 32) * (5 / 9)
14+
return temp_cel
15+
16+
17+
# Prompt the user to input a Fahrenheit temperature.
18+
temp_far = input("Enter a temperature in degrees F: ")
19+
20+
# Convert the temperature to Celsius.
21+
# Note that `temp_far` must be converted to a `float`
22+
# since `input()` returns a string.
23+
temp_cel = convert_far_to_cel(float(temp_far))
24+
25+
# Display the converted temperature
26+
print(f"{temp_far} degrees F = {temp_cel:.2f} degrees C")
27+
28+
# You could also use `round()` instead of the formatting mini-language:
29+
# print(f"{temp_far} degrees F = {round(temp_cel, 2)} degrees C"")
30+
31+
# Prompt the user to input a Celsius temperature.
32+
temp_cel = input("\nEnter a temperature in degrees C: ")
33+
34+
# Convert the temperature to Fahrenheit.
35+
temp_far = convert_cel_to_far(float(temp_cel))
36+
37+
# Display the converted temperature
38+
print(f"{temp_cel} degrees C = {temp_far:.2f} degrees F")
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# 6.5 - Challenge: Track Your Investments
2+
# Solution to challenge
3+
4+
5+
# Calculate compound interest to track the growth of an investment
6+
7+
8+
def invest(amount, rate, years):
9+
for year in range(1, years + 1):
10+
amount = amount * (1 + rate)
11+
print(f"year {year}: ${amount:,.2f}")
12+
13+
14+
amount = float(input("Enter a principal amount: "))
15+
rate = float(input("Enter an anual rate of return: "))
16+
years = int(input("Enter a number of years: "))
17+
18+
invest(amount, rate, years)
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# 8.4 - Challenge: Find the Factors of a Number
2+
# Solution to challenge
3+
4+
5+
# Display all the factors of a number chosen by the user
6+
7+
num = int(input("Enter a positive integer: "))
8+
for divisor in range(1, num + 1):
9+
if num % divisor == 0:
10+
print(f"{divisor} is a factor of {num}")
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# 8.8 - Challenge: Simulate a Coin Toss Experiment
2+
# Solution to challenge
3+
4+
5+
# Simulate the results of a series of coin tosses and track the results
6+
7+
# This one is tricky to structure correctly. Try writing out the logic before
8+
# you start coding. Some additional pointers if you're stuck:
9+
# 1. You will need to use a `for` loop over a range of trials.
10+
# 2. For each trial, first you should check the outcome of the first flip.
11+
# 3. Make sure you add the first flip to the total number of flips.
12+
# 4. After the first toss, you'll need another loop to keep flipping while you
13+
# get the same result as the first flip.
14+
15+
import random
16+
17+
18+
def coin_flip():
19+
"""Randomly return 'heads' or 'tails'."""
20+
if random.randint(0, 1) == 0:
21+
return "heads"
22+
else:
23+
return "tails"
24+
25+
26+
flips = 0
27+
num_trials = 10_000
28+
29+
for trial in range(num_trials):
30+
if coin_flip() == "heads":
31+
# Increment the number of flips by 1
32+
flips = flips + 1
33+
while coin_flip() == "heads":
34+
# Keep incrementing the total number of flips
35+
# until "tails" is returned by coin_flip()
36+
flips = flips + 1
37+
# Once coin_flip() return "tails", the loop will exit,
38+
# but we need to add one more to flips to track the
39+
# last flip that generated "tails"
40+
flips = flips + 1
41+
else:
42+
# coin_flip() returned "tails" on the first flip.
43+
# Increment the number of flips by 1
44+
flips = flips + 1
45+
while coin_flip == "tails":
46+
# Keep incrementing the total number of flips
47+
# until "heads" is returned by coin_flip()
48+
flips = flips + 1
49+
# Once coin_flip() returns "heads", the loop will exit,
50+
# but we need to add one more to flips to track the
51+
# last flip that generated "heads"
52+
flips = flips + 1
53+
54+
avg_flips_per_trial = flips / num_trials
55+
print(f"The average number of flips per trial is {avg_flips_per_trial}.")
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# 8.8 - Challenge: Simulate a Coin Toss Experiement
2+
# Alternative solution to challenge
3+
4+
5+
# Simulate the results of a series of coin tosses and track the results
6+
7+
# This one is tricky to structure correctly. Try writing out the logic before
8+
# you start coding. Some additional pointers if you're stuck:
9+
# 1. You will need to use a `for` loop over a range of trials.
10+
# 2. For each trial, first you should check the outcome of the first flip.
11+
# 3. Make sure you add the first flip to the total number of flips.
12+
# 4. After the first toss, you'll need another loop to keep flipping while you
13+
# get the same result as the first flip.
14+
15+
import random
16+
17+
18+
def coin_flip():
19+
"""Randomly return 'heads' or 'tails'."""
20+
if random.randint(0, 1) == 0:
21+
return "heads"
22+
else:
23+
return "tails"
24+
25+
26+
flips = 0
27+
num_trials = 10_000
28+
29+
for trial in range(num_trials):
30+
# Flip the coin once and increment the flips tally by 1
31+
first_flip = coin_flip()
32+
flips = flips + 1
33+
# Continue flipping the coin and updating the tally until
34+
# a different result is returned by coin_flips()
35+
while coin_flip() == first_flip:
36+
flips = flips + 1
37+
# Increment the flip tally once more to account for the
38+
# final flip with a different result
39+
flips = flips + 1
40+
41+
avg_flips_per_trial = flips / num_trials
42+
print(f"The average number of flips per trial is {avg_flips_per_trial}.")
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# 8.8 - Challenge: Simulate a Coin Toss Experiement
2+
# Alternative solution to challenge using functions
3+
4+
5+
# Simulate the results of a series of coin tosses and track the results
6+
7+
# This one is tricky to structure correctly. Try writing out the logic before
8+
# you start coding. Some additional pointers if you're stuck:
9+
# 1. You will need to use a `for` loop over a range of trials.
10+
# 2. For each trial, first you should check the outcome of the first flip.
11+
# 3. Make sure you add the first flip to the total number of flips.
12+
# 4. After the first toss, you'll need another loop to keep flipping while you
13+
# get the same result as the first flip.
14+
15+
from random import randint
16+
17+
18+
def single_trial():
19+
toss = randint(0, 1)
20+
total_flips = 1
21+
22+
while toss == randint(0, 1):
23+
total_flips += 1
24+
toss = randint(0, 1)
25+
26+
total_flips += 1
27+
return total_flips
28+
29+
30+
def flip_trial_avg(num_trials):
31+
total = 0
32+
for trial in range(num_trials):
33+
total += single_trial()
34+
return total / num_trials
35+
36+
37+
print(f"The average number of coin flips was {flip_trial_avg(10000)}")
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# 8.9 - Challenge: Simulate an Election
2+
# Solution to challenge
3+
4+
5+
# Simulate the results of an election using a Monte Carlo simulation
6+
7+
from random import random
8+
9+
total_A_wins = 0
10+
total_B_wins = 0
11+
12+
trials = 10_000
13+
for trial in range(0, trials):
14+
A_win = 0
15+
B_win = 0
16+
if random() < 0.87: # 1st region
17+
A_win += 1
18+
else:
19+
B_win += 1
20+
if random() < 0.65: # 2nd region
21+
A_win += 1
22+
else:
23+
B_win += 1
24+
if random() < 0.17: # 3rd region
25+
A_win += 1
26+
else:
27+
B_win += 1
28+
# Determine overall election outcome
29+
if A_win > B_win:
30+
total_A_wins += 1
31+
else:
32+
total_B_wins += 1
33+
34+
print(f"Probability A wins: {total_A_wins / trials}")
35+
print(f"Probability B wins: {total_B_wins / trials}")
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# 9.2 - Challenge: List of Lists
2+
# Solution to challenge
3+
4+
5+
def enrollment_stats(list_of_universities):
6+
7+
# Variables
8+
total_students = []
9+
total_tuition = []
10+
11+
# Iterate through lists, adding values
12+
for university in list_of_universities:
13+
total_students.append(university[1])
14+
total_tuition.append(university[2])
15+
16+
# Return variables
17+
return total_students, total_tuition
18+
19+
20+
def mean(my_list):
21+
if len(my_list) == 0:
22+
return "The list is empty"
23+
list_sum = 0
24+
for i in range(len(my_list)):
25+
list_sum += float(my_list[i])
26+
return int(list_sum / len(my_list))
27+
28+
29+
def median(my_list):
30+
sorts = sorted(my_list)
31+
length = len(sorts)
32+
if not length % 2:
33+
return (sorts[int(length / 2)] + sorts[int(length / 2 - 1)]) / 2.0
34+
return sorts[int(length / 2)]
35+
36+
37+
universities = [
38+
["California Institute of Technology", 2175, 37704],
39+
["Harvard", 19627, 39849],
40+
["Massachusetts Institute of Technology", 10566, 40732],
41+
["Princeton", 7802, 37000],
42+
["Rice", 5879, 35551],
43+
["Stanford", 19535, 40569],
44+
["Yale", 11701, 40500],
45+
]
46+
47+
totals = enrollment_stats(universities)
48+
49+
print("\n")
50+
print("*****" * 5)
51+
print(f"Total students: {sum(totals[0])}")
52+
print(f"Total tuition: $ {sum(totals[1])}")
53+
print(f"\nStudent mean: {mean(totals[0])}")
54+
print(f"Student median: {median(totals[0])}")
55+
print(f"\nTuition mean: $ {mean(totals[1])}")
56+
print(f"Tuition median: $ {median(totals[1])}")
57+
print("*****" * 5)
58+
print("\n")

0 commit comments

Comments
 (0)
0