Professional Documents
Culture Documents
Quizzes Panda
Quizzes Panda
Quizzes Panda
day of the week and confirm the change by printing the name of the default first day of the
week.
import calendar
def set_first_day_of_week(weekday):
calendar.setfirstweekday(weekday)
# Get the name of the first day of the week after the change
new_first_day = calendar.day_name[calendar.firstweekday()]
# Print confirmation
set_first_day_of_week(user_input)
Given a date string in the following format "2022-03-20 18:45:23" and using the Python time
library print the date in the following format "20/3/2022 18h 45min 23s".
date_string = input("Date:")
print(output_format)
Given two integers representing the number of seconds since the epoch calculate the
difference in full years of the two corresponding dates. (using the Python datetime library)
(note: you should take into account the day and month of the two dates).
# Input the number of seconds since the epoch for the first date
# Input the number of seconds since the epoch for the second date
date_1 = datetime.fromtimestamp(seconds_since_epoch_1)
date_2 = datetime.fromtimestamp(seconds_since_epoch_2)
# Adjust the difference if the second date's month and day are before the first date's month
and day
years_diff -= 1
ddhgsdhsdhbc
datetime_with_tz = []
# Iterate over the date strings and parse them into datetime objects
timezone = tz.gettz(timezone_str)
dt = dt.replace(tzinfo=timezone)
datetime_with_tz.append((dt, timezone_str))
utc_offset = dt.strftime('%z')
formatted_utc_offset = f"{utc_offset[:3]}:{utc_offset[3:]}"
tz_abbr = dt.strftime('%Z')
date_list = []
for i in range(num_dates):
date_list.append((date_str, timezone_str))
sort_dates_with_timezone(num_dates, date_list)
Using the Python calendar library and given a year and a month print the day of the month
for each Monday of the given month.
import calendar
year = int(input("Year:"))
month = int(input("Month:"))
# Get the calendar matrix for the given year and month
if week[calendar.MONDAY] != 0:
print(week[calendar.MONDAY])
Using the Python time library convert a given floating number of seconds since the epoch to
a string.
import time
time_string = time.ctime(seconds_since_epoch)
print(time_string)
Given a date string in the following format ("17/02/2022") print the corresponding iso
weekday (1 is Monday) and week (the first week of the year is the first week containing a
Thursday). (using the Python datetime library)
date_str = input("Date:")
weekday = date_obj.weekday() + 1
iso_week = date_obj.isocalendar()[1]
Given a date string in iso format and a timezone, assume that the date is in UTC and convert
the date to the new timezone. Print the new date using the iso format and the date timezone
name. (Using datetime and dateutil libraries)
# Parse the date string into a datetime object assuming it's in UTC
dt_utc = datetime.fromisoformat(date_str)
# Get the timezone object corresponding to the new timezone
timezone_new = tz.gettz(timezone_str)
dt_new_timezone = dt_utc.astimezone(timezone_new)
tz_abbr = dt_new_timezone.strftime('%Z')
# Print the new date in ISO format with the timezone name
print(f"Timezone: {tz_abbr}")
# Example usage
date_str = input("Date:")
timezone_str = input("Timezone:")
import calendar
date_str = input("Date:")
weekday_name = calendar.day_name[date_obj.weekday()]
print(weekday_name)
Given a date string in the following format ("17/02/2022 14:30:45") add a given number of
weeks, days, hours and seconds (all integer values) and print the new date using the same
format. (using the Python datetime library)
# Create a timedelta object with the specified number of weeks, days, hours, and seconds
# Add the timedelta to the original date to get the new date
# Format the new date string using the same format as the original date string
new_date_str = new_date.strftime(date_format)
return new_date_str
original_date_str = input("Date:")
weeks = int(input("Weeks:"))
days = int(input("Days:"))
hours = int(input("Hours:"))
seconds = int(input("Seconds:"))
print(new_date_str)
Given a date string in a free format and a list of relativedelta parameters (months, days or
hours) add those parameters to the date and print the new date using the iso format. (Using
datetime and dateutil libraries)
# Try parsing the date string using each format until successful
try:
break
except ValueError:
pass
else:
if delta_type == 'months':
date_obj += relativedelta(months=delta_value)
date_obj += relativedelta(days=delta_value)
date_obj += relativedelta(hours=delta_value)
new_date_str = date_obj.isoformat()
return new_date_str
date_str = input("Date:")
relative_deltas = []
relative_deltas.append((delta_type, int(delta_value)))
import numpy as np
return result
vector1 = np.zeros(num_elements)
vector2 = np.zeros(num_elements)
for i in range(num_elements):
vector1[i] = int(input(f"a[{i}]:"))
for i in range(num_elements):
vector2[i] = int(input(f"b[{i}]:"))
Given a matrix a (NxN) and a vector b (N) solve the linear system ax = b using NumPy library.
import numpy as np
matrix_A = []
N = len(input_data)
matrix_A.append(input_data)
matrix_A.append(input_data)
matrix_A = np.array(matrix_A)
vector_b = np.array(vector_b)
print("solution:")
print(solution)
Compute the product of two matrices A (NxM) and B (MxP) using NumPy library.
import numpy as np
N = int(input())
M = int(input())
P = int(input())
matrix_A = []
for _ in range(N):
row = []
#print(f"Row {_ + 1}:")
for _ in range(M):
element = float(input())
row.append(element)
matrix_A.append(row)
matrix_B = []
for _ in range(M):
row = []
#print(f"Row {_ + 1}:")
for _ in range(P):
element = float(input())
row.append(element)
matrix_B.append(row)
matrix_A = np.array(matrix_A)
matrix_B = np.array(matrix_B)
print(row)
Given the seed for the random number generator and the number of rows and columns,
generate a matrix drawing samples from a normal distribution with mean 0 and standard
deviation 1 and calculate the mean and the standard deviation (rounded to two decimal
places) of the matrix elements, using NumPy library.
import numpy as np
# Set the seed for the random number generator
seed = int(input("Seed:"))
np.random.seed(seed)
rows = int(input("Rows:"))
cols = int(input("Columns:"))
mean = np.mean(matrix)
std_dev = np.std(matrix)
mean = "{:.2f}".format(mean)
std_dev = "{:.2f}".format(std_dev)
Given the initial, final, and the number of values (all floats) generate an array with n
elements between initial and final values equally spaced, square the values and calculate the
sum (rounded to two decimal places), using NumPy library.
import numpy as np
n = int(input("Number of values:"))
# Generate array with n elements equally spaced between initial and final values
values = np.linspace(initial, final, n)
squared_values = np.square(values)
sum_squared = np.sum(squared_values)
sum_squared_rounded = round(sum_squared, 2)
Given the name of a .csv file (delimiter ";") with a matrix, find the maximum and minimum of
the matrix elements and the corresponding positions (row,colum), using NumPy library.
import numpy as np
def strip_filename(filename):
filename = filename.strip()
return filename
# Input filename
filename = input("Filename:").strip()
original_filename = filename
filename = strip_filename(filename)
#print("Filename:", original_filename)
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
How many single men go to the gym.
import pandas as pd
def solve():
count_single_men = len(single_men)
print(count_single_men)
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
What percentage of female customers are on the list (rounded to two decimal places).
import pandas as pd
def solve():
total_customers = len(df)
percentage_female_customers = round(percentage_female_customers, 2)
print(f"{percentage_female_customers:.2f}")
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
List of people who are over 175 cm tall and have children. View name, height and children.
import pandas as pd
def solve():
# Filter the DataFrame to select people who are over 175 cm tall and have children
result = df[(df['height'] > 175) & (df['children'] > 0)][['name', 'height', 'children']]
print(result)
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
What is the average height of people who train between 3 and 4 hours a week (rounded to
two decimal places).
import pandas as pd
def solve():
# Filter the DataFrame to select people who train between 3 and 4 hours a week
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
import pandas as pd
def solve():
print(male_customers)
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
import pandas as pd
def solve():
print(df.head(3))
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
What is the average age of people who train more than 5 hours a week (rounded to two
decimal places).
import pandas as pd
def solve():
# Filter the DataFrame to include only people who train more than 5 hours a week
# Calculate the average age of people who train more than 5 hours a week
average_age = more_than_5_hours['age'].mean()
average_age = round(average_age, 2)
print(f"{average_age:.2f}")
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
The Body Mass Index (BMI) is obtained by the formula: BMI = Weight /(Height)^2 (Height
must be expressed in meters). Create a new column 'bmi' (rounded to two decimal places)
with the corresponding value and print the id, name, weight, height and bmi of the first
three rows of the dataframe.
import pandas as pd
def solve():
#global df
# Calculate BMI
df['bmi'] = df['bmi'].round(2)
# Print the id, name, weight, height, and bmi of the first three rows
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
Knowing that the last two digits of the registration number represent the last two digits of
the year of registration, build the list of applicants in 2013 aged 50 years or over. View id,
name, weight, height and age.
import pandas as pd
def solve():
print(result)
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
import pandas as pd
def solve():
count_married_people = len(married_people)
print(count_married_people)
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
What is the average height of people who train between 3 and 4 hours a week (rounded to
two decimal places).
import pandas as pd
def solve():
average_height = filtered_df['height'].mean()
average_height = round(average_height, 2)
print(average_height)
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
What is the standard deviation of customer ages (rounded to two decimal places).
import pandas as pd
def solve():
std_dev_age = df['age'].std()
std_dev_age = round(std_dev_age, 2)
print(std_dev_age)
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
import pandas as pd
def solve():
youngest_age = df['age'].min()
print(youngest_age)
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
List of people under 150 cm or over 177 cm. View Name, Weight and Number of Children.
import pandas as pd
def solve():
# Filter the DataFrame to include only people under 150 cm or over 177 cm
print(result)
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
import pandas as pd
def solve():
total_children_over_55 = customers_over_55['children'].sum()
print(total_children_over_55)
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
import pandas as pd
def solve():
heaviest_weight = df['weight'].max()
print(heaviest_weight)
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
Create a Python function 'get_obs' which given the value of the weight returns the following
string:
Create a new 'observation' column with the result obtained by applying the 'get_obs'
function to the 'weight' column and print the id, name, weight and observation for the first
five rows of the dataframe.
import pandas as pd
def get_obs(weight):
return 'underweight'
return 'overweight'
def solve():
# Apply the 'get_obs' function to the 'weight' column to create the 'observation' column
df['observation'] = df['weight'].apply(get_obs)
# Print id, name, weight, and observation for the first five rows
print(result)
Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:
import pandas as pd
def solve():
print(num_customers_max_1_child)