Skip to content

Commit 5472c61

Browse files
update solutions
1 parent c015422 commit 5472c61

File tree

7 files changed

+113
-18
lines changed

7 files changed

+113
-18
lines changed

part-06/solution/1-scrambled.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,11 @@
1212
# Hint: Use the random.choice() function to select a word from the list and try to come up with the rest of the code yourself!
1313

1414
import random
15-
import string
1615

1716
# List of words to choose from for the game
1817
words = ["python", "programming", "computer", "algorithm", "database"]
1918

2019
def scramble_word(word):
21-
# Convert the word to a list of characters, shuffle them, and join back into a string
2220
chars = list(word)
2321
random.shuffle(chars)
2422
return ''.join(chars)

part-06/solution/3-random-package.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
# - It should also ask the user if they want to play again
88
# Your code here
99

10-
#| eval: false
1110
import random
1211

1312
def play_game():

part-06/solution/5-password.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,21 +14,21 @@
1414
import re
1515

1616
def check_password_strength(password):
17-
if len(password) < 8:
18-
return "Weak"
19-
20-
criteria = [
21-
r'[A-Z]', # Uppercase letter
22-
r'[a-z]', # Lowercase letter
23-
r'\d', # Digit
24-
r'[!@#$%^&*]' # Special character
25-
]
26-
27-
strength = sum(bool(re.search(pattern, password)) for pattern in criteria)
28-
29-
if strength == 4:
17+
criteria = 0
18+
if len(password) >= 8:
19+
criteria += 1
20+
if re.search(r'[A-Z]', password):
21+
criteria += 1
22+
if re.search(r'[a-z]', password):
23+
criteria += 1
24+
if re.search(r'\d', password):
25+
criteria += 1
26+
if re.search(r'[!@#$%^&*]', password):
27+
criteria += 1
28+
29+
if criteria == 5:
3030
return "Strong"
31-
elif strength >= 2:
31+
elif criteria >= 3:
3232
return "Medium"
3333
else:
3434
return "Weak"
0 Bytes
Binary file not shown.
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#Imagine you're a climate scientist working on a project to analyze temperature data from weather stations across the country. You've been given a large dataset, and you need to use NumPy to process and analyze this data efficiently.
2+
3+
import numpy as np
4+
5+
# First, we simulate loading data from 100 weather stations over 365 days. Each row represents a station, each column a day.
6+
temp_data = np.random.randint(0, 40, size=(100, 365))
7+
8+
# a) Calculate the average temperature for each station and the overall average temperature.
9+
station_averages = np.mean(temp_data, axis=1)
10+
overall_average = np.mean(temp_data)
11+
print(f"Average temperature for each station:\n{station_averages}")
12+
print(f"Overall average temperature: {overall_average:.2f}°C")
13+
14+
# b) Find the highest and lowest temperature recorded and print a message with the corresponding stations.
15+
highest_temp = np.max(temp_data)
16+
lowest_temp = np.min(temp_data)
17+
highest_station, highest_day = np.where(temp_data == highest_temp)
18+
lowest_station, lowest_day = np.where(temp_data == lowest_temp)
19+
print(f"Highest temperature: {highest_temp}°C at station {highest_station[0]} on day {highest_day[0]}")
20+
print(f"Lowest temperature: {lowest_temp}°C at station {lowest_station[0]} on day {lowest_day[0]}")
21+
22+
# c) Identify heat waves. A heat wave is defined as 5 consecutive days with temperatures above 30°C. Print a message counting the number of heat waves.
23+
heat_waves = 0
24+
for station in temp_data:
25+
consecutive_hot_days = 0
26+
for temp in station:
27+
if temp > 30:
28+
consecutive_hot_days += 1
29+
if consecutive_hot_days == 5:
30+
heat_waves += 1
31+
consecutive_hot_days = 0 # Reset to avoid double-counting
32+
else:
33+
consecutive_hot_days = 0
34+
print(f"Total number of heat waves across all stations: {heat_waves}")
35+
36+
37+
# d) Calculate the temperature anomaly for each day (difference from each individual station's average temperature).
38+
temp_anomaly = temp_data - station_averages[:, None]
39+
print("Temperature anomaly shape:", temp_anomaly.shape)
40+
41+
# e) Find the hottest and coldest stations and determine the index of the station with the highest average temperature and the station with the lowest average temperature.
42+
hottest_station = np.argmax(station_averages)
43+
coldest_station = np.argmin(station_averages)
44+
print(f"Hottest station index: {hottest_station}, with average temperature: {station_averages[hottest_station]:.2f}°C")
45+
print(f"Coldest station index: {coldest_station}, with average temperature: {station_averages[coldest_station]:.2f}°C")

part-07/solution/02-gistemp.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# In this exercise, you'll use Pandas to analyze real global temperature anomaly data from NASA, helping to understand trends in climate change over time.
2+
3+
# The dataset is provided by the GISS Team, 2024: GISS Surface Temperature Analysis (GISTEMP), version 4. NASA Goddard Institute for Space Studies. Dataset at https://data.giss.nasa.gov/gistemp/.
4+
5+
import pandas as pd
6+
import matplotlib.pyplot as plt
7+
8+
# First, we load the NASA GISTEMP dataset for global temperature anomalies.
9+
url = "https://data.giss.nasa.gov/gistemp/tabledata_v4/GLB.Ts+dSST.csv"
10+
temp_anomaly_data = pd.read_csv(url, skiprows=1) # skiprows=1 ensures that the first column is not read as a row index
11+
# Convert 'Anomaly' column to float
12+
melted_data['Anomaly'] = melted_data['Anomaly'].astype(float)
13+
14+
15+
# a) Display the first 5 rows and keep only 'Year' and month columns
16+
temp_anomaly_data = temp_anomaly_data.drop(columns=['J-D', 'D-N','DJF','MAM','JJA','SON'])
17+
print(temp_anomaly_data.head())
18+
19+
# b) Calculate and print the average temperature anomaly for each year
20+
melted_data = pd.melt(temp_anomaly_data, id_vars=['Year'], var_name='Month')
21+
melted_data = melted_data.drop(columns=['Month'])
22+
print(melted_data.head())
23+
melted_data.groupby(['Year']).mean()
24+
print(melted_data.head())
25+
print("\nAverage temperature anomaly for each year:")
26+
print(melted_data.head())
27+
28+
# c) Find the year with the highest and lowest temperature anomaly
29+
max_year = yearly_avg.idxmax()
30+
min_year = yearly_avg.idxmin()
31+
print(f"\nYear with highest anomaly: {max_year} ({yearly_avg[max_year]:.2f})")
32+
print(f"Year with lowest anomaly: {min_year} ({yearly_avg[min_year]:.2f})")
33+
34+
# d) Create 'Anomaly_Category' column
35+
def categorize_anomaly(value):
36+
if value < -0.2:
37+
return 'Cool'
38+
elif value > 0.2:
39+
return 'Warm'
40+
else:
41+
return 'Neutral'
42+
43+
melted_data['Anomaly_Category'] = melted_data['Anomaly'].apply(categorize_anomaly)
44+
45+
# e) Calculate the percentage of 'Warm' months for each decade
46+
melted_data['Decade'] = (melted_data['Year'] // 10) * 10
47+
warm_percentage = melted_data.groupby('Decade')['Anomaly_Category'].apply(lambda x: (x == 'Warm').mean() * 100)
48+
print("\nPercentage of 'Warm' months for each decade:")
49+
print(warm_percentage)
50+
51+
# f) Save the DataFrame to Excel
52+
melted_data.to_excel('temp_anomaly_data.xlsx', index=False)
53+
print("\nData saved to 'temp_anomaly_data.xlsx'")

part-07/tutorial-scientific.qmd

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ temp_data = np.random.randint(0, 40, size=(100, 365))
3737
# TODO: b) Find the highest and lowest temperature recorded and print an message with the corresponding stations.
3838
# Your code here
3939

40-
# TODO: c) Identify heat waves. A heat wave is defined as 5 consecutive days with temperatures above 35°C. Print a message counting the number of heat waves.
40+
# TODO: c) Identify heat waves. A heat wave is defined as 5 consecutive days with temperatures above 30°C. Print a message counting the number of heat waves.
4141
# Your code here
4242

4343
# TODO: d) Calculate the temperature anomaly for each day (difference from each indidvual station's average temperature).

0 commit comments

Comments
 (0)