Quizzes Panda

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

Using the Python calendar library and given a weekday, integer (0-6), set that day as the first

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):

# Set the first day of the week

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

print(f"First day of the week: {new_first_day}")

# Input from the user

user_input = int(input("Day of the week (0-6):"))

# Setting the first day of the week based on user input

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".

from datetime import datetime

# Input date string

date_string = input("Date:")

# Parse the input date string into a datetime object

date_object = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")


# Format the datetime object into the desired output format

output_format = date_object.strftime("%d/%m/%Y %Hh %Mmin %Ss")

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).

from datetime import datetime

# Input the number of seconds since the epoch for the first date

seconds_since_epoch_1 = int(input("Number of seconds since the epoch of the first date:"))

# Input the number of seconds since the epoch for the second date

seconds_since_epoch_2 = int(input("Number of seconds since the epoch of the second date:"))

# Convert the number of seconds to datetime objects

date_1 = datetime.fromtimestamp(seconds_since_epoch_1)

date_2 = datetime.fromtimestamp(seconds_since_epoch_2)

# Calculate the difference in years

years_diff = date_2.year - date_1.year

# Adjust the difference if the second date's month and day are before the first date's month
and day

if (date_2.month, date_2.day) < (date_1.month, date_1.day):

years_diff -= 1

print(f"Number of years between {date_1.strftime('%Y-%m-%d')} and {date_2.strftime('%Y-%m-


%d')} = {years_diff}")

ddhgsdhsdhbc

from datetime import datetime


from dateutil import tz

def sort_dates_with_timezone(num_dates, date_list):

# Create a list to store datetime objects with timezone information

datetime_with_tz = []

# Iterate over the date strings and parse them into datetime objects

for date_str, timezone_str in date_list:

# Parse the date string into a datetime object

dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")

# Get the timezone object corresponding to the given timezone string

timezone = tz.gettz(timezone_str)

# Attach the timezone information to the datetime object

dt = dt.replace(tzinfo=timezone)

# Append the datetime object to the list

datetime_with_tz.append((dt, timezone_str))

# Sort the datetime objects

sorted_dates = sorted(datetime_with_tz, key=lambda x: x[0])

# Print the sorted dates and timezone names

for dt, timezone_str in sorted_dates:

# Get the UTC offset in ISO 8601 format (+/-HH:MM)

utc_offset = dt.strftime('%z')

# Convert UTC offset to the desired format (e.g., +03:00 or -08:00)

formatted_utc_offset = f"{utc_offset[:3]}:{utc_offset[3:]}"

# Get the abbreviated timezone name

tz_abbr = dt.strftime('%Z')

# Format the output

print(f"{dt.strftime('%Y-%m-%d %H:%M:%S')}{formatted_utc_offset}, {tz_abbr}")


# Accept user input

num_dates = int(input("Number of dates:"))

date_list = []

for i in range(num_dates):

date_str, timezone_str = input("").split(", ")

date_list.append((date_str, timezone_str))

# Call the function with user input

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

# Input year and month

year = int(input("Year:"))

month = int(input("Month:"))

# Get the calendar matrix for the given year and month

cal = calendar.monthcalendar(year, month)

# Iterate over the rows of the matrix

for week in cal:

# Check if Monday exists in the week

if week[calendar.MONDAY] != 0:

# Print the day of the month for Monday

print(week[calendar.MONDAY])

Using the Python time library convert a given floating number of seconds since the epoch to
a string.

import time

# Accept user input


seconds_since_epoch = float(input("Number of seconds:"))

# Convert seconds to string format

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)

from datetime import datetime

# Input date string

date_str = input("Date:")

# Parse the date string into a datetime object

date_obj = datetime.strptime(date_str, "%d/%m/%Y")

# Get the weekday (1 is Monday)

weekday = date_obj.weekday() + 1

# Get the ISO week number

iso_week = date_obj.isocalendar()[1]

print(f"weekday = {weekday}, week = {iso_week}")

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)

from datetime import datetime

from dateutil import tz

def convert_timezone(date_str, timezone_str):

# 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)

# Convert the datetime object to the new timezone

dt_new_timezone = dt_utc.astimezone(timezone_new)

# Get the timezone abbreviation

tz_abbr = dt_new_timezone.strftime('%Z')

# Print the new date in ISO format with the timezone name

print(f"New date: {dt_new_timezone.isoformat()}")

print(f"Timezone: {tz_abbr}")

# Example usage

date_str = input("Date:")

timezone_str = input("Timezone:")

convert_timezone(date_str, timezone_str) campeoes caralho


trincao goat
Given a date string in the following format "2022-03-20 18:45:23" and using the Python time
and calendar libraries print the weekday name for that date.

from datetime import datetime

import calendar

# Input date string

date_str = input("Date:")

# Parse the date string into a datetime object

date_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")


# Get the weekday name

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)

from datetime import datetime, timedelta

def add_time(original_date_str, weeks, days, hours, seconds):

# Define the format of the input date string

date_format = "%d/%m/%Y %H:%M:%S"

# Parse the original date string into a datetime object

original_date = datetime.strptime(original_date_str, date_format)

# Create a timedelta object with the specified number of weeks, days, hours, and seconds

delta = timedelta(weeks=weeks, days=days, hours=hours, seconds=seconds)

# Add the timedelta to the original date to get the new date

new_date = original_date + delta

# 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

# Accept user input

original_date_str = input("Date:")
weeks = int(input("Weeks:"))

days = int(input("Days:"))

hours = int(input("Hours:"))

seconds = int(input("Seconds:"))

# Calculate and print the new date

new_date_str = add_time(original_date_str, weeks, days, hours, 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)

from datetime import datetime

from dateutil.relativedelta import relativedelta

def add_relative_delta(date_str, relative_deltas):

# Define the formats of the input date string

date_formats = ["%d/%m/%Y %H:%M:%S", "%m-%d-%Y %H:%M:%S"]

# Try parsing the date string using each format until successful

for date_format in date_formats:

try:

# Parse the date string into a datetime object

date_obj = datetime.strptime(date_str, date_format)

break

except ValueError:

pass

else:

raise ValueError("Invalid date format")

# Apply the relative deltas to the date


for delta_type, delta_value in relative_deltas:

if delta_type == 'months':

date_obj += relativedelta(months=delta_value)

elif delta_type == 'days':

date_obj += relativedelta(days=delta_value)

elif delta_type == 'hours':

date_obj += relativedelta(hours=delta_value)

# Format the new date using the ISO format

new_date_str = date_obj.isoformat()

return new_date_str

# Accept user input

date_str = input("Date:")

relativedelta_params = input("Relativedelta parameters:")

# Parse relativedelta parameters

relative_deltas = []

for param in relativedelta_params.split(','):

delta_type, delta_value = param.split('=')

relative_deltas.append((delta_type, int(delta_value)))

# Calculate and print the new date

new_date_str = add_relative_delta(date_str, relative_deltas)

print("New date:", new_date_str)

Calculate the scalar product of two vectors using NumPy library.

import numpy as np

def scalar_product(vector1, vector2):

# Calculate the scalar product of the two vectors


result = np.dot(vector1, vector2)

return result

# Accept user input for the number of elements in the vectors

num_elements = int(input("Number of elements:"))

# Initialize empty arrays for the vectors

vector1 = np.zeros(num_elements)

vector2 = np.zeros(num_elements)

# Accept user input for each element of the vectors

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}]:"))

# Calculate the scalar product

scalar_result = scalar_product(vector1, vector2)

# Print the scalar product with one decimal place

print("Scalar product = {:.1f}".format(scalar_result))

Given a matrix a (NxN) and a vector b (N) solve the linear system ax = b using NumPy library.

import numpy as np

# Input elements of matrix A

#print("Enter the elements of matrix A:")

matrix_A = []

input_data = list(map(float, input().split(",")))

N = len(input_data)

matrix_A.append(input_data)

for _ in range(N - 1):


input_data = list(map(float, input().split(",")))

matrix_A.append(input_data)

# Input elements of vector b

#print("Enter the elements of vector b:")

vector_b = list(map(float, input().split(",")))

# Convert lists to NumPy arrays

matrix_A = np.array(matrix_A)

vector_b = np.array(vector_b)

# Solve the linear system

solution = np.linalg.solve(matrix_A, vector_b)

# Print the solution

print("solution:")

print(solution)

Compute the product of two matrices A (NxM) and B (MxP) using NumPy library.

Input order (one per line): N, M, P, A[0][...], A[1][...], ..., B[0][...],B[1][...]

import numpy as np

# Input sizes of matrices A and B

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)

# Input elements of matrices B

#print("Enter the elements of matrix B:")

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)

# Convert lists to NumPy arrays

matrix_A = np.array(matrix_A)

matrix_B = np.array(matrix_B)

# Compute the product of matrices A and B

product = np.dot(matrix_A, matrix_B)

# Print the product

for row in product:

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)

# Input matrix dimensions

rows = int(input("Rows:"))

cols = int(input("Columns:"))

# Generate matrix with random samples from a normal distribution

matrix = np.random.normal(0, 1, (rows, cols))

# Calculate the mean and standard deviation of the matrix elements

mean = np.mean(matrix)

std_dev = np.std(matrix)

# Round mean and standard deviation to two decimal places

mean = "{:.2f}".format(mean)

std_dev = "{:.2f}".format(std_dev)

# Print the mean and standard deviation

print("Mean: {}, Std: {}".format(mean, 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

# Input initial, final, and number of values

initial = float(input("Initial value:"))

final = float(input("Final value:"))

n = int(input("Number of values:"))

# Generate array with n elements equally spaced between initial and final values
values = np.linspace(initial, final, n)

# Square the values

squared_values = np.square(values)

# Calculate the sum of squared values

sum_squared = np.sum(squared_values)

# Round the sum to two decimal places

sum_squared_rounded = round(sum_squared, 2)

# Print the rounded sum

print("Sum of the array:", sum_squared_rounded)

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):

while filename.strip() != filename:

filename = filename.strip()

return filename

# Input filename

filename = input("Filename:").strip()

original_filename = filename

# Filename after stripping leading and trailing whitespace

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():

#global df # Access the global DataFrame variable

# Filter the DataFrame to include only single men

single_men = df[(df['status'] == 'single') & (df['sex'] == 'M')]

# Count the number of single men

count_single_men = len(single_men)

# Print the count of 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():

# Count the total number of customers

total_customers = len(df)

# Count the number of female customers

female_customers = len(df[df['sex'] == 'F'])

# Calculate the percentage of female customers

percentage_female_customers = (female_customers / total_customers) * 100


# Round the percentage to two decimal places

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 the result

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

filtered_df = df[(df['hours'] >= 3) & (df['hours'] <= 4)]

# Calculate the average height of the selected people


average_height = filtered_df['height'].mean()

# Print the average height rounded to two decimal places

print( round(average_height, 2))

Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:

How many male customers are on the list.

import pandas as pd

def solve():

# Count the number of male customers

male_customers = len(df[df['sex'] == 'M'])

print(male_customers)

Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:

Print the first 3 rows from df.

import pandas as pd

def solve():

# Print the first 3 rows from df

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

more_than_5_hours = df[df['hours'] > 5]

# Calculate the average age of people who train more than 5 hours a week

average_age = more_than_5_hours['age'].mean()

# Round the average age to two decimal places

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['weight'] / ((df['height'] / 100) ** 2) # Convert height to meters

# Round bmi to two decimal places

df['bmi'] = df['bmi'].round(2)

# Print the id, name, weight, height, and bmi of the first three rows

print(df[['id', 'name', 'weight', 'height', 'bmi']].head(3))

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():

df['year'] = df['id'] % 100

applicants_2013_over_50 = df[(df['year'] == 13) & (df['age'] >= 50)]

result = applicants_2013_over_50[['id', 'name', 'weight', 'height', 'age']]

print(result)

Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:

How many married people go to the gym.

import pandas as pd

def solve():

# Filter the DataFrame to include only married people

married_people = df[df['status'] == 'married']

# Count the number of married people

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():

filtered_df = df[(df['hours'] >= 3) & (df['hours'] <= 4)]

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:

How old is the youngest person.

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

filtered_df = df[(df['height'] < 150) | (df['height'] > 177)]

# View Name, Weight, and Number of Children of the filtered people

result = filtered_df[['name', 'weight', 'children']]

print(result)

Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:

What is the total number of children of customers over 55 years of age.

import pandas as pd

def solve():

# Filter the DataFrame to include only customers over 55 years of age

customers_over_55 = df[df['age'] > 55]

# Calculate the total number of children for these customers

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:

How much does the heaviest customer weigh.

import pandas as pd

def solve():

# Read the CSV file

# Find the maximum weight in the DataFrame

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:

weight <= 50 'underweight'

weight > 50 weight <= 80 'normal weight'

weight > 80 'overweight'

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):

if weight <= 50:

return 'underweight'

elif weight <= 80:

return 'normal weight'


else:

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

result = df[['id', 'name', 'weight', 'observation']].head()

print(result)

Given the dataframe df and using the Pandas library create a function 'solve()' to answer the
following:

How many customers have a maximum of 1 child.

import pandas as pd

def solve():

# Read the CSV file

# Count the number of customers with a maximum of 1 child

num_customers_max_1_child = df[df['children'] <= 1]['id'].count()

print(num_customers_max_1_child)

You might also like