Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commite775089

Browse files
committed
Merge branch 'rename-challenges'
2 parentsbb69aab +e7cefbf commite775089

File tree

23 files changed

+1155
-0
lines changed

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+
defconvert_cel_to_far(temp_cel):
6+
"""Return the Celsius temperature temp_cel converted to Fahrenheit."""
7+
temp_far=temp_cel* (9/5)+32
8+
returntemp_far
9+
10+
11+
defconvert_far_to_cel(temp_far):
12+
"""Return the Fahrenheit temperature temp_far converted to Celsius."""
13+
temp_cel= (temp_far-32)* (5/9)
14+
returntemp_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+
definvest(amount,rate,years):
9+
foryearinrange(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+
fordivisorinrange(1,num+1):
9+
ifnum%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+
importrandom
16+
17+
18+
defcoin_flip():
19+
"""Randomly return 'heads' or 'tails'."""
20+
ifrandom.randint(0,1)==0:
21+
return"heads"
22+
else:
23+
return"tails"
24+
25+
26+
flips=0
27+
num_trials=10_000
28+
29+
fortrialinrange(num_trials):
30+
ifcoin_flip()=="heads":
31+
# Increment the number of flips by 1
32+
flips=flips+1
33+
whilecoin_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+
whilecoin_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+
importrandom
16+
17+
18+
defcoin_flip():
19+
"""Randomly return 'heads' or 'tails'."""
20+
ifrandom.randint(0,1)==0:
21+
return"heads"
22+
else:
23+
return"tails"
24+
25+
26+
flips=0
27+
num_trials=10_000
28+
29+
fortrialinrange(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+
whilecoin_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+
fromrandomimportrandint
16+
17+
18+
defsingle_trial():
19+
toss=randint(0,1)
20+
total_flips=1
21+
22+
whiletoss==randint(0,1):
23+
total_flips+=1
24+
toss=randint(0,1)
25+
26+
total_flips+=1
27+
returntotal_flips
28+
29+
30+
defflip_trial_avg(num_trials):
31+
total=0
32+
fortrialinrange(num_trials):
33+
total+=single_trial()
34+
returntotal/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+
fromrandomimportrandom
8+
9+
total_A_wins=0
10+
total_B_wins=0
11+
12+
trials=10_000
13+
fortrialinrange(0,trials):
14+
A_win=0
15+
B_win=0
16+
ifrandom()<0.87:# 1st region
17+
A_win+=1
18+
else:
19+
B_win+=1
20+
ifrandom()<0.65:# 2nd region
21+
A_win+=1
22+
else:
23+
B_win+=1
24+
ifrandom()<0.17:# 3rd region
25+
A_win+=1
26+
else:
27+
B_win+=1
28+
# Determine overall election outcome
29+
ifA_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+
defenrollment_stats(list_of_universities):
6+
7+
# Variables
8+
total_students= []
9+
total_tuition= []
10+
11+
# Iterate through lists, adding values
12+
foruniversityinlist_of_universities:
13+
total_students.append(university[1])
14+
total_tuition.append(university[2])
15+
16+
# Return variables
17+
returntotal_students,total_tuition
18+
19+
20+
defmean(my_list):
21+
iflen(my_list)==0:
22+
return"The list is empty"
23+
list_sum=0
24+
foriinrange(len(my_list)):
25+
list_sum+=float(my_list[i])
26+
returnint(list_sum/len(my_list))
27+
28+
29+
defmedian(my_list):
30+
sorts=sorted(my_list)
31+
length=len(sorts)
32+
ifnotlength%2:
33+
return (sorts[int(length/2)]+sorts[int(length/2-1)])/2.0
34+
returnsorts[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)

[8]ページ先頭

©2009-2025 Movatter.jp