problem
string
| solution
string
|
---|---|
"def calculate_average_price(prices):
"""
Calculate the average price of a list of fashion items.
Args:
prices (list): A list of prices of fashion items.
Returns:
float: The average price of the fashion items.
"""" | "
total = 0
while prices:
# Slices the prices list to get the first item and remove it from the original list
price = prices.pop(0)
# Complete the missing code to update the total variable by adding the current price
# Calculate the average price by dividing the total by the number of fashion items
average_price = total / len(prices)
return average_price" |
"def find_gene(sequence, target_gene):
"""
Given a DNA sequence and a target gene, this function should return the starting index of the target gene in the given sequence, using a while loop and boolean expressions.
Note: The target gene is represented as a string of characters, and we assume that it only occurs once in the sequence.
Args:
- sequence: a string representing the DNA sequence to search in
- target_gene: a string representing the target gene to find
Returns:
- The starting index (integer) of the target gene in the sequence, or -1 if the target gene is not found.
"""" | "
index = 0
gene_len = len(target_gene)
while index <= len(sequence) - gene_len:
# Check if current substring matches the target gene
if sequence[index:index+gene_len] == target_gene:
return index
index += 1
return -1 # Target gene not found in the given sequence" |
"def get_common_words(string1, string2):
"""
This function takes in two strings and returns a set of common words found in both strings.
Args:
string1 (str): The first string.
string2 (str): The second string.
Returns:
set: A set of common words found in both strings.
Raises:
ValueError: If either string1 or string2 is empty.
"""" | "
if not string1 or not string2:
raise ValueError("Both strings must not be empty")
words1 = string1.split()
words2 = string2.split()
common_words = set()
for word1 in words1:
for word2 in words2:
if word1 == word2:
common_words.add(word1)
return common_words
" |
"def advantages_equal(musician_1, musician_2):
"""This exercise will determine the intersection of advantages between two musicians and check if they are equal."""" | "
# Find the advantages of musician_1
musician_1_advantages = set(musician_1['advantages'])
# Find the advantages of musician_2
musician_2_advantages = set(musician_2['advantages'])
# Find the common advantages between musician_1 and musician_2
common_advantages = musician_1_advantages.intersection(musician_2_advantages)
# Check if the advantages are equal in count
advantages_equal = len(musician_1_advantages) == len(musician_2_advantages)
return common_advantages, advantages_equal
" |
"def create_tuple(n):
"""
Given an integer n, create a nested tuple using ternary operators.
Args:
n (int): The length of the nested tuple.
Returns:
tuple: Nested tuple of length n, where each element is either a tuple or a string 'Done'.
Example:
Input:
create_tuple(2)
Output:
(('Done', 'Done'),)
Explanation:
The nested tuple has length 2 and each element is 'Done'. Therefore, it returns (('Done', 'Done'),).
"""" | "
return (('Done',) * n,) if n else 'Done'
" |
"def create_tuple(graphic_designer_name, graphic_designer_age, graphic_designer_skill_level, graphic_designer_experience):
"""
This exercise focuses on creating a tuple to store information about a graphic designer.
The tuple should include the designer's name, age, skill level, and experience.
Your task is to complete the code by creating a tuple with the provided information. Please make sure to follow the given order.
Args:
- graphic_designer_name (str): The name of the graphic designer.
- graphic_designer_age (int): The age of the graphic designer.
- graphic_designer_skill_level (str): The skill level of the graphic designer (e.g., Beginner, Intermediate, Advanced).
- graphic_designer_experience (int): The years of experience of the graphic designer.
Returns:
- tuple: A tuple containing the provided information about the graphic designer.
"""" | "
# Create a tuple with the given information **in the correct order**
graphic_designer_tuple = (graphic_designer_name, graphic_designer_age, graphic_designer_skill_level, graphic_designer_experience)
return graphic_designer_tuple
# Example usage
designer_info = create_tuple("John" |
"def intersection_sets(s1, s2):
"""
This exercise requires you to complete the code to find the intersection of two sets using list comprehension and iterating through sets.
You are given two sets, s1 and s2, and you need to find the common elements between them. You should use list comprehension
to create a new list containing the common elements found in both sets. Finally, return the list with the common elements.
Remember to use list comprehension and iterate through sets to solve this exercise. Good luck!
"""" | "
intersection = [x for x in s1 if x in s2] # Use list comprehension to iterate through s1 and check if each element exists in s2
return intersection" |
"def find_common_elements(set1, set2):
"""
This function takes two sets as input and returns a new set with only the elements that are
greater than or equal to the smallest element in the first set.
Args:
set1 (set): First input set
set2 (set): Second input set
Returns:
set: A new set containing the common elements from both sets
"""" | "
min_element = min(set1) # Find the smallest element in set1
return {element for element in set2 if element >= min_element}
" |
"def find_common_elements(list1, list2):
"""
Given two lists, find the common elements between them.
Parameters:
list1 (list): First list to check for common elements
list2 (list): Second list to check for common elements
Returns:
common_elements (list): List of common elements between list1 and list2
"""" | "
# Initialize an empty list to store the common elements
common_elements = []
# Iterate over each element in list1
for element in list1:
# Check if the element is not equal to any elements in list2
if element not in list2:
# Add the element to the common_elements list
common_elements.append(element)
return common_elements" |
"def find_sum(nums):
"""
Takes a list of numbers as input and returns the sum of all the numbers greater than 10.
Args:
nums (list): A list of numbers
Returns:
int: The sum of all the numbers greater than 10
"""" | "
total = 0
# Iterate over each number in the input list
for num in nums:
# Check if the number is greater than 10
if num > 10:
# Add the number to the total
total += num
return total
" |
"def find_criminals(criminals: tuple, search_terms: tuple) -> list:
"""
This function takes a tuple of criminals and a tuple of search terms
and returns a list of criminals that match the search terms.
Args:
criminals (tuple): A tuple of all the criminals' information
search_terms (tuple): A tuple of search terms for finding specific criminals
Returns:
list: A list of criminals that match the search terms
Example:
criminals = (("John Doe", 35, "Male"), ("Jane Smith", 28, "Female"), ("Michael Johnson", 42, "Male"))
search_terms = ("Male",)
find_criminals(criminals, search_terms) => [("John Doe", 35, "Male"), ("Michael Johnson", 42, "Male")]
"""" | "
matching_criminals = []
for criminal in criminals:
if all(term in criminal for term in search_terms):
matching_criminals.append(criminal)
return matching_criminals
criminals = (("John Doe", 35, "Male"), ("Jane Smith", 28, "Female"), ("Michael Johnson", 42, "Male" |
"def intersection_of_sequence_and_addition_assignment(sequence: list, number: int):
"""Given a sequence and a number, find the intersection of the sequence after adding the number to each element.
Args:
sequence (list): A list of integers.
number (int): An integer to be added to each element of the sequence.
Returns:
list: A list with the intersection of elements after adding the number.
"""" | "
result = set(sequence[0] + number)
for i in range(1, len(sequence)):
current_set = set()
for j in result:
current_set.add(j + sequence[i])
result = result.intersection(current_set)
return list(result)
" |
"def find_special_chars(string: str) -> list:
"""
Given a string, find and return a list of all special characters that are surrounded by uppercase letters.
Args:
string (str): The input string to search for special characters.
Returns:
list: A list of special characters that satisfy the given condition.
Example:
>>> find_special_chars('Ab#cD*efG')
['#', '*']
"""" | "
special_chars = []
for i in range(len(string)):
if string[i].isupper() and i > 0 and i < len(string)-1:
if not string[i-1].isalpha() and not string[i+1].isalpha():
special_chars.append(string[i])
return special_chars
missing_code = "Ab#cD*efG"
result = find_special_chars(missing_code)
print(result)" |
"def calculate_factorial(n):
"""
This function calculates the factorial of a given number using nested ternary operators within a basic while loop.
Args:
n (int): The number for which factorial needs to be calculated.
Returns:
int: The factorial of the input number.
"""" | "
# Initialize the factorial variable
factorial = 1
# Use a while loop to calculate factorial
while n > 1:
# Nested ternary operators to calculate factorial
factorial *= n if n > 1 else 1
n -= 1
return factorial
# Example usage
print(calculate_factorial(5)) # Output: 120" |
"def while_subtraction(base_number, subtract_value):
"""
This exercise requires you to write a basic while loop syntax to perform a subtraction operation.
Given a base number, your task is to subtract the subtract_value from the base_number using a while loop
and return the final result.
Args:
- base_number: an integer representing the base number
- subtract_value: an integer representing the value to subtract from the base number
Returns:
- The final result after subtracting the subtract_value from the base_number
Example:
- If base_number = 10 and subtract_value = 3
The output should be 7, as 10 - 3 = 7
Instructions:
1. Initialize a variable 'result' with the value of 'base_number'
2. Write a while loop that continues as long as 'result' is greater than or equal to 'subtract_value'
3. Inside the loop, subtract 'subtract_value' from 'result'
4. Finally, return 'result'
"""" | "
result = base_number
# Write your code here
" |
"def calculate_total_sales(revenue_list):
"""
Given a list of revenues for different products, this function calculates the total sales in floating-point
format.
Args:
revenue_list (list): A list of revenue values for different products.
Returns:
float: The total sales calculated from the revenue list.
"""" | "
# Initialize the cumulative sales as 0.0
total_sales = 0.0
# Iterate over each revenue value in the list
for revenue in revenue_list:
# Convert the revenue to floating-point number if necessary
revenue = float(revenue)
# Add the revenue to the total sales
total_sales += revenue
return total_sales
" |
"def find_affordable_items(budget, items):
"""
Given a budget and a dictionary of items with their prices,
find the items that are less expensive than the budget.
Args:
- budget: The maximum amount of money the interior designer can spend.
- items: A dictionary mapping item names to their prices.
Returns:
- A list of item names that are less expensive than the budget.
"""" | "
affordable_items = [] # Stores the names of affordable items
# Loop through the dictionary using items.items()
for item, price in items.items():
if price < budget: # Check if the price of the item is less than the budget
affordable_items.append(item) # Add the name of the affordable item to the list
return affordable_items
" |
"def musician_dict(musician_list):
"""
This exercise is to create a dictionary for a musician, where the keys are the genres of music they play and the values are the number of albums they have released in that genre.
Write a function that takes in a list of genres for a musician and returns a dictionary containing the count of albums released in each genre. If a genre is repeated in the list, it should only be counted once in the dictionary.
Example:
Input:
musician_list = ['Rock', 'Pop', 'Rock', 'Hip Hop', 'Jazz', 'Rock', 'Pop']
Output:
{'Rock': 2, 'Pop': 1, 'Hip Hop': 1, 'Jazz': 1}
"""" | "
genre_dict = {}
i = 0
while i < len(musician_list):
genre = musician_list[i]
if genre not in genre_dict:
genre_dict[genre] = 1
else:
genre_dict[genre] += 1
# Complete the code to increment the value for the genre in the dictionary
i += 1
return genre" |
"def nurse_schedule(schedule, nurse_name):
"""A nurse's schedule is given as a list of tuples, where each tuple represents a shift with start and end time.
Loop through the schedule and find the shifts where the nurse named "nurse_name" is not available. Print the number of such shifts.
Args:
schedule (list): A list of tuples representing shifts in the format (start_time, end_time)
nurse_name (str): The name of the nurse
Returns:
None
"""" | "
unavailable_shifts = 0
for shift in schedule:
start_time, end_time = shift
if not nurse_name_available(nurse_name, shift):
unavailable_shifts += 1
print("Number of shifts where", nurse_name, "is not available:", unavailable_shifts)
" |
"def find_highest_peak(elevations):
"""
Given a list of elevations representing a geographic region,
find the highest peak.
:param elevations: A list of integers representing elevations.
:return: The highest peak (an integer).
"""" | "
if not elevations:
return None
highest_peak = elevations[0]
for elevation in elevations:
if elevation > highest_peak:
highest_peak = elevation
# Write code below to break out of the loop
# if the current elevation is greater than 5000.
return highest_peak" |
"def calculate_volumes(spheres):
"""This function calculates the volumes of spheres given their radii."""" | "
volumes = []
for radius in spheres:
# Complete the code to calculate the volume of a sphere using the formula (4/3) * pi * radius^3
volume = (4 / 3) * 3.14159 * (radius ** 3)
volumes.append(volume)
return volumes
radii = [2, 3, 4, 5]
sphere_volumes = calculate_volumes(radii)
print(sphere_volumes)
# Output: [33.51029333333333, 113.09722666666666, 268.08234666666664, 523.5983333333332]" |
"def count_common_characters(therapist_notes, patient_notes):
"""
This function takes in two strings, therapist_notes and patient_notes,
and returns the count of common characters between the two strings.
"""" | "
common_characters = []
for char1 in therapist_notes:
for char2 in patient_notes:
# Check if character is common
if char1 == char2 and char1 not in common_characters:
common_characters.append(char1)
return len(common_characters)
" |
"def replace_common_characters(therapist_notes, patient_notes):
"""
This function takes in two strings, therapist_notes and patient_notes,
and replaces any common characters between the two strings with '#'.
It returns the modified therapist_notes string.
"""" | "
modified_notes = ''
for char1 in therapist_notes:
is_common = False
for char2 in patient_notes:
# If character is common, replace it with '#'
if char1 == char2:
modified_notes += '#'
is_common = True
break
if not is_common:
modified_notes += char1
return modified_notes
" |
"def find_common_elements(data1, data2):
"""
Write a function that takes in two tuples, `data1` and `data2`, which contains data related to biological studies.
The function should return a tuple containing only the elements that exist in both `data1` and `data2`, preserving the order.
Example:
data1 = ('AGT', 'CTG', 'GGA', 'AAC')
data2 = ('AAG', 'CTG', 'TGC', 'ATC')
find_common_elements(data1, data2) # Output: ('CTG',)
"""" | "
common_elements = ()
# Iterate through each element of data1
for elem in data1:
# Check if the element exists in data2
if elem in data2:
# Add the element to the common_elements tuple
common_elements += (elem,)
return common_elements" |
"def update_actor_details(actor_data):
"""
This function takes a list of dictionaries containing actor/actress details. It updates the salary of each actor
based on their experience and returns the updated list.
Args:
- actor_data (list of dictionaries): A list containing actor/actress details. Each dictionary contains 'name',
'experience', and 'salary' keys.
Returns:
- updated_actor_data (list of dictionaries): The updated list of actor/actress details with their updated salary.
"""" | "
# Iterate over the actor_data list using enumerate to get the index and dictionary at each iteration
for index, actor in enumerate(actor_data):
# Update the salary based on the actor's experience
if actor['experience'] < 5:
actor['salary'] = actor['salary'] * 1.1
elif actor['experience'] >= 5 and actor['experience'] < 10:
actor['salary'] = actor['salary'] * 1.2
else:
actor['salary'] = actor['salary'] * 1.3
return actor_data
" |
"def find_common_letters(artist1, artist2):
"""
This function takes in two artist names as arguments and returns a string containing all the common letters
between the two names, using a while loop and tuple slicing.
Args:
artist1 (str): The name of the first artist.
artist2 (str): The name of the second artist.
Returns:
str: A string containing all the common letters between the two artists' names.
Raises:
ValueError: If either artist's name is an empty string.
"""" | "
if not artist1 or not artist2:
raise ValueError("Artist name cannot be empty")
common_letters = ""
i = 0
while i < len(artist1):
j = 0
while j < len(artist2):
if artist1[i] == artist2[j]:
common_letters += artist1[i]
break
j += 1
i += 1
return common_letters
" |
"def nurse_is_busy(schedule):
"""
A nurse is busy for half of the day and must take a break for 30 minutes every hour.
Given a schedule that represents the nurse's availability during the day,
write a function that determines if there is a gap long enough for the nurse to take a break.
Args:
schedule (tuple): A tuple of integers representing the nurse's schedule, where 1 represents patient
appointments and 0 represents an available time slot.
Returns:
bool: True if the nurse can take a break, False otherwise.
Example:
nurse_is_busy((0, 1, 0, 0, 0, 1, 0, 1, 1, 0))
Output: True
Explanation: The nurse can take a break during the gap from index 4 to 5
as there are at least 30 consecutive minutes available.
"""" | "
break_length = 30 # minutes
gap_length = 0
for slot in schedule:
if slot == 0:
gap_length += 1
else:
if gap_length >= break_length:
return True
" |
"def create_animal_tuple(name, species, size, weight, age):
"""
This exercise requires you to create a tuple containing information about an animal.
The tuple should include the name, species, size, weight, and age of the animal.
Your task is to write the code to create the tuple and use if statements to perform additional actions.
Args:
- name (str): The name of the animal.
- species (str): The species of the animal.
- size (str): The size of the animal.
- weight (float): The weight of the animal.
- age (int): The age of the animal.
Returns:
- animal_tuple (tuple): A tuple containing the information about the animal.
"""" | "
animal_tuple = tuple()
if isinstance(name, str) and isinstance(species, str) and isinstance(size, str) and \
isinstance(weight, float) and isinstance(age, int):
animal_tuple = (name, species, size, weight, age)
if weight > 100:
print("Warning: This animal is significantly heavier than average.")
if age < 1:
print("This animal is very young" |
"def intersect_slicing_conjugate_abs(x):
"""
This exercise involves applying slicing to a complex number, then computing its conjugate and absolute value.
"""" | "
# Creating a complex number
complex_num = complex(x)
# Slicing the real and imaginary parts
real_part = complex_num.real
imag_part = complex_num.imag
# Computing the conjugate of the complex number
conjugate = complex(real_part, -imag_part)
# Computing the absolute value of the complex number
absolute_value = abs(complex_num)
# Return the conjugate and absolute value
return conjugate, absolute_value
" |
"def search_photos(tags: list, locations: list, photodatabase: dict) -> list:
"""
Given a list of tags, a list of locations, and a photo database,
this function returns a list of photos that have at least one tag
from the tags list and are taken at a location specified in the
locations list.
Args:
tags (list): A list of tags.
locations (list): A list of locations.
photodatabase (dict): A dictionary representing the photo database.
Returns:
list: A list of matching photos.
"""" | "
result = []
for location in locations:
if location in photodatabase:
for photo in photodatabase[location]:
if any(tag in photo['tags'] for tag in tags):
result.append(photo)
return result" |
"def get_photo_location(photo):
"""
Given a photo object, this function returns the location of the photo.
Args:
photo (dict): A dictionary representing a photo object with 'location' key.
Returns:
str: The location of the photo.
"""" | "
if 'location' in photo and isinstance(photo['location'], str):
return photo['location']
else:
return "Unknown"
" |
"def get_special_photos(photos):
"""
Given a list of photo objects, this function returns a list of photos taken at special locations.
A location is considered special if it starts with the keyword 'Special:'.
Args:
photos (list): A list of dictionaries representing photo objects with 'location' key.
Returns:
list: A list of dictionaries representing special photos.
"""" | "
special_photos = []
for photo in photos:
location = get_photo_location(photo)
if isinstance(location, str) and location.startswith('Special:'):
special_photos.append(photo)
return special_photos
" |
"def find_negative_index(vet_records):
"""
Given a dictionary of veterinary records, find the negative index of the animal's name.
Args:
vet_records (dict): A dictionary containing the animal name as the key and the number of visits as the value.
Returns:
int: The negative index of the animal's name.
"""" | "
animal_names = list(vet_records.keys())
# Loop through the dictionary to find the animal with the maximum number of visits
max_visits = 0
for animal_name in vet_records:
visits = vet_records[animal_name]
if visits > max_visits:
max_visits = visits
# Find the negative index of the animal with maximum visits
for i in range(len(animal_names)):
if vet_records[animal_names[i]] == max_visits:
return -1 * (len(animal_names) - i - 1)
" |
"def replace_missing_vowels(text):
"""
Given a text as input, the function replaces all the missing vowels with the letter 'x'.
"""" | "
# Define a list of vowels
vowels = ['a', 'e', 'i', 'o', 'u']
# Convert the input text to lowercase
text = text.lower()
# Loop through each character in the text
for char in text:
# Check if the character is a letter and not already a vowel
if char.isalpha() and char not in vowels:
# Replace the character with 'x'
text = text.replace(char, 'x')
return text
# Now, let's test the function with an example
input_text = "Hello, how are you today?"
print(replace_missing_vowels(input_text))
" |
"def physician_code_completion(patients):
"""
Given a dictionary of patients with their corresponding medical conditions,
modify the list of medical conditions for each patient based on certain conditions.
- If a patient's age is less than 18, add 'CHILD' to their medical conditions.
- If a patient's age is greater than or equal to 65, add 'ELDERLY' to their medical conditions.
- If a patient's age is between 18 and 65 (inclusive), add 'ADULT' to their medical conditions.
Args:
patients (dict): A dictionary mapping patient names (keys) to their ages (values).
Returns:
dict: The same dictionary with modified medical conditions for each patient.
"""" | "
for patient, age in patients.items():
if age < 18:
patients[patient].append('CHILD')
elif 18 <= age <= 65:
patients[patient].append('ADULT')
elif age >= 65:
patients[patient].append('ELDERLY')
return patients
# Example usage:
patients = {
'John': 22,
'Emily': 8,
'David': 45,
" |
"def find_average_income(data):
"""Calculate the average income for each city"""" | "
average_incomes = []
for city_data in data:
total_income = 0
num_households = 0
for household in city_data:
for income in household["incomes"]:
total_income += income
num_households += 1
if num_households > 0:
average_income = total_income / num_households
average_incomes.append(average_income)
return average_incomes
city_data = [
[
{"incomes": [45000, 60000, 75000]},
{"incomes": [35000, 48000]},
{"incomes": [52000, 68000, 75000, 82000]}
],
[
{"incomes": [58000, 62000, 69000]},
{"incomes": [42000, 55000, 72000]},
{"incomes": [48000, 55000]}
],
[
{"incomes": [45000, 51000, 66000]},
{"incomes": [33000, 42000" |
"def intersection_of_not_operator_and_repetition(data):
"""
This function takes a list of integers as input and returns the intersection
of numbers that are NOT divisible by 3 and are repeated at least twice.
Args:
data (list): A list of integers.
Returns:
list: A list of integers representing the intersection of numbers that are NOT
divisible by 3 and are repeated at least twice.
"""" | "
unique_nums = set()
repeated_nums = set()
result = []
for num in data:
if num % 3 != 0:
if num in unique_nums:
repeated_nums.add(num)
else:
unique_nums.add(num)
for num in repeated_nums:
if data.count(num) > 1:
result.append(num)
return result
" |
"def validate_input(choice):
"""Check if the choice is valid. Return True if valid, False otherwise."""" | "
# Implement the code to check if the choice is valid.
# Returns True if the choice is between 1 and 10, inclusive.
# Otherwise, returns False.
" |
"def process_choice(choice):
"""Implement the main logic for processing the choice given by the player."""" | "
# Implement the code to process the choice based on game rules.
# If the choice is even, print "Even choice!" and continue to next iteration.
# If the choice is prime, print "Prime choice!" and break out of the loop.
# If the choice is divisible by 5, print "Divisible by 5!" and return True.
# Otherwise, return False.
" |
"def game():
"""Simulate a game with choices made by the player."""" | "
while True:
choice = int(input("Enter a number between 1 and 10: "))
valid = validate_input(choice)
if not valid:
print("Invalid input. Try again.")
continue
even = choice % 2 == 0
prime = choice > 1" |
"def calculate_fuel_usage(fuel_capacity, distance_traveled):
"""
Calculate the fuel usage of an aircraft based on its fuel capacity and the distance traveled.
The fuel usage is determined by dividing the distance traveled by the fuel capacity.
Return the result as a floating-point number.
Example:
fuel_capacity: 12000 distance_traveled: 5000
fuel usage = 5000 / 12000 = 0.4166666666666667
Return 0.4166666666666667
"""" | "
fuel_usage = float(distance_traveled) / fuel_capacity
return fuel_usage
" |
"def determine_speed_ratio(speed, reference_speed):
"""
Determine the speed ratio between an aircraft's speed and a reference speed.
The speed ratio is calculated by dividing the speed by the reference speed.
Return the result as a floating-point number.
Example:
speed: 500 reference_speed: 250
speed ratio = 500 / 250 = 2.0
Return 2.0
"""" | "
speed_ratio = float(speed) / reference_speed
return speed_ratio
" |
"def modify_expenses(accountant_data):
"""
Given a list of accountant's expenses, modify the amounts of the expenses by adding a bonus to each amount.
Args:
accountant_data (list of tuples): A list of tuples representing the accountant's expenses with their corresponding amounts.
Returns:
list: A list of modified expenses with the bonus added to each amount.
Example:
modify_expenses([(1, 100), (2, 200), (3, 300)]) -> [101, 202, 303]
"""" | "
modified_expenses = []
# Iterate over each expense tuple and unpack the amount
for _, amount in accountant_data:
# Modify the amount by adding a bonus and append it to the modified_expenses list
modified_expenses.append(amount + 1_000_000)
return modified_expenses
" |
"def adjust_exposure(photo_exposure, target_exposure):
"""
This function takes in the current exposure level of a photo and the target exposure level desired by a photographer.
It adjusts the exposure by iteratively increasing or decreasing the exposure level until it matches the target exposure level.
The adjustment is done using a while loop and additional conditions within if statements to ensure the exposure level converges accurately.
"""" | "
# Iteratively adjust the exposure level until it reaches the target exposure
while abs(photo_exposure - target_exposure) > 0.01:
if photo_exposure < target_exposure:
photo_exposure += 0.1 # Increase exposure level by 0.1
if photo_exposure > 1.0:
photo_exposure = 1.0 # Limit maximum exposure level to 1.0
else:
photo_exposure -= 0.1 # Decrease exposure level by 0.1
if photo_exposure < 0.0:
photo_exposure = 0.0 # Limit minimum exposure level to 0.0
return photo_exposure
# Adjust the exposure of a photo from 0" |
"def calculate_average_depth(rock_layers, num_shifts):
"""
This function takes a list of rock layers and the number of times the shift operators should be applied. It calculates the average depth of the rock layers after applying the shift operators.
Args:
- rock_layers: a list containing the depths of rock layers
- num_shifts: an integer representing the number of times the shift operators should be applied
Returns:
- average_depth: a float representing the average depth of the rock layers
Example:
calculate_average_depth([10, 20, 30, 40, 50], 3)
Output: 25.0
"""" | "
shifted_layers = rock_layers.copy()
for shift in range(num_shifts):
for i in range(len(shifted_layers)):
if i == 0:
shifted_layers[i] = shifted_layers[i] << 1
else:
shifted_layers[i] = shifted_layers[i] >> 1
total_depth = sum(shifted_layers)
average_depth = total_depth / len(shifted_layers)
return average_depth
rock_layers = [10, 20, 30, 40, 50]
" |
"def create_tuple_from_string_math(text):
"""
Given a string containing mathematical expressions separated by commas, create a tuple of the evaluated expressions.
Args:
text (str): A string containing mathematical expressions.
Returns:
tuple: A tuple of the evaluated expressions.
Example:
>>> create_tuple_from_string_math("2+3, 4*5, 6-1")
(5, 20, 5)
>>> create_tuple_from_string_math("sqrt(16), sin(pi/2), log10(1000)")
(4.0, 1.0, 3.0)
"""" | "
# Initialize an empty list to store the evaluated expressions
result = []
# Remove any whitespaces from the text
text = text.replace(" ", "")
# Split the string into individual expressions using ',' as delimiter
expressions = text.split(",")
# Iterate over each expression and evaluate it
for expr in expressions:
# Evaluate the expression and append the result to the result list
result.append(eval(expr))
# Return the result list as a tuple
return tuple(result)" |
"def find_common_elements(lst1, lst2):
"""
Given two lists, return a new list containing the common elements between them.
Use slicing and None as a placeholder.
Args:
lst1 -- the first list
lst2 -- the second list
Returns:
A new list containing the common elements between lst1 and lst2.
"""" | "
common_elements = []
# TODO: Use slicing and None as a placeholder to find the common elements between lst1 and lst2
# HINT: You can iterate through one list and compare each element with the corresponding element in the other list using slicing and None as a placeholder.
# HINT: If an element in the first list is equal to the corresponding element or None in the second list, add it to common_elements.
for i in range(len(lst1)):
if lst1[i] == lst2[i] or lst2[i] is None:
common_elements.append(lst1[i])
return common_elements
" |
"def find_missing_items(items: list) -> list:
"""
This exercise requires the archaeologist to find the missing items in a given list of findings.
Args:
- items: A list containing the items found by the archaeologist.
Returns:
- A list of the missing items that the archaeologist needs to find.
Example:
find_missing_items([1, 2, 3, 5, 9]) -> [4, 6, 7, 8]
"""" | "
# Determine the minimum and maximum values in the given list
min_item = min(items)
max_item = max(items)
# Generate a range of numbers from the minimum to the maximum item, inclusive
complete_range = list(range(min_item, max_item + 1))
# Initialize an empty list to store the missing items
missing_items = []
# Iterate through the complete range
for num in complete_range:
# Check if the current number from the complete range is not in the given items list
if num not in items:
# Append the missing number to the missing_items list
missing_items.append(num)
return missing_items
" |
"def animal_times_two(animal_1, animal_2):
"""
This function takes in two animals and returns the result of multiplying their values.
However, one of the animals needs to be either a land animal or a water animal.
Your task is to complete the code by using the AND and XOR operators to check the following conditions:
- If both animals are land animals, return 0.
- If both animals are water animals, return 0.
- If one animal is a land animal and the other is a water animal, return the product of the animals' values.
Args:
animal_1 (int): The value of the first animal.
animal_2 (int): The value of the second animal.
Returns:
int: The result of multiplying the animals' values based on the given conditions.
"""" | "
if (animal_1 == 0 and animal_2 != 0) or (animal_1 != 0 and animal_2 == 0): # Check if one animal is a land animal and the other is a water animal
return animal_1 * animal_2
elif animal_1 == 0 and animal_" |
"def tuples_and_infinite_loops(aerospace_element: str) -> tuple:
"""This exercise explores the concepts of tuples and infinite loops in the context
of aerospace engineering. Your task is to complete the code by implementing the
missing parts and ensuring an infinite loop that manipulates the given aerospace
element as a tuple.
Args:
- aerospace_element (str): The aerospace element to be manipulated.
Returns:
- tuple: The modified aerospace element.
"""" | "
# Initialize an empty tuple to store the modified aerospace element
modified_element = ()
# Enable infinite loop to manipulate the element as a tuple
while True:
# Prompt the user to choose an option
print("Please select an option:")
print("1. Remove duplicate characters in the aerospace element.")
print("2. Reverse the order of characters in the aerospace element.")
print("3. Count the occurrence of a specific character in the aerospace element.")
print("4. Exit the program.")
# Get user's choice
choice = input("Enter your choice (1/2/3/4): ")
# Option 1: Remove duplicate characters
if choice == "1":
" |
"def unique_pairs(membership_list):
"""
Given a list of names representing the members in a biomedical engineering team,
this function returns a list of all unique pairs of team members.
Example:
>>> unique_pairs(["Alice", "Bob", "Charlie"])
[("Alice", "Bob"), ("Alice", "Charlie"), ("Bob", "Charlie")]
Args:
- membership_list: A list of strings representing the names of the team members
Returns:
- A list of tuples representing all unique pairs of team members
"""" | "
pairs = []
n = len(membership_list)
# Iterate over each member in the membership_list
for i in range(n):
# Iterate over the remaining members in the membership_list
for j in range(i+1, n):
# Append the unique pair of members to the pairs list
pairs.append((membership_list[i], membership_list[j]))
return pairs" |
"def unconditioned_ternary_operator_or_operator(input1, input2, input3):
"""
Given three inputs (input1, input2, input3), the function should return the value of input1 if it is True, otherwise it should return the value of input2 if it is True, otherwise it should return the value of input3.
"""" | "
return input1 if input1 or input2 or input3 else input2
" |
"def intersection_of_loops(list_1, list_2):
"""
This exercise focuses on list comprehension and executing nested loops.
Given two lists, list_1 and list_2, your task is to find the common elements between them using list comprehension.
"""" | "
common_elements = []
# Iterate through each element in list_1
for element_1 in list_1:
# Iterate through each element in list_2
for element_2 in list_2:
# Check if the elements are equal
if element_1 == element_2:
# Append the common element to the common_elements list
common_elements.append(element_1)
return common_elements
" |
"def dancer_moves(dancers: set[str]) -> set[str]:
"""
Given a set of dancers, the function takes two nested loops to generate all possible dance moves
by pairing each dancer with every other unique dancer in the set. Each dance move is formed by
combining the names of the two dancers with a "+" sign in between.
Args:
- dancers: A set of strings representing the names of dancers.
Returns:
- A set of strings representing all possible dance moves generated from the pairs of dancers.
"""" | "
dance_moves = set() # Initialize an empty set to store dance moves
for dancer1 in dancers:
for dancer2 in dancers:
if dancer1 != dancer2: # Avoid pairing a dancer with themselves
dance_move = dancer1 + "+" + dancer2 # Combine dancer names with "+"
dance_moves.add(dance_move) # Add dance move to the set of dance moves
return dance_moves
# Example usage
dancers = {"Alice", "Bob", "Charlie"}
dance_moves = dancer_moves(dancers)
print(dance_moves)
# Output: {'Alice+Charlie', 'Charlie+Bob', 'Bob+" |
"def modify_tuples(architects: List[Tuple[str, int]]) -> List[Tuple[str, int]]:
"""
Given a list of tuples containing architects' names and their ages,
modify the ages of the architects which are above 30 to their square root.
Example:
Input: [('John', 25), ('Emily', 33), ('Oliver', 42)]
Output: [('John', 5), ('Emily', 33), ('Oliver', 6)]
Args:
- architects: List of tuples containing architects' names (str) and ages (int)
Returns:
- List of tuples with modified ages
"""" | "
return [(name, age**0.5 if age > 30 else age) for name, age in architects]
" |
"def calculate_animal_population(target_population: int, current_population: int) -> int:
"""A zoologist wants to determine how many more animals need to be removed
from a specific area to achieve the target population.
Complete the function by subtracting the current population from the target population
and return the result.
Args:
target_population (int): The desired population of animals in the area.
current_population (int): The current population of animals in the area.
Returns:
int: The number of additional animals that need to be removed.
"""" | "
# Subtract the current population from the target population
remaining_population = target_population - current_population
return remaining_population
" |
"def concatenate_and_check(actor1, actor2):
"""
This exercise requires concatenating two strings and then using the 'is' operator
to check if the resulting string is equal to a specific value.
Given an actor's first and last name, concatenate them by adding a space in between.
Then, using the 'is' operator, check if the resulting string is equal to 'Leonardo DiCaprio'.
Return True if they are equal, False otherwise.
Args:
actor1 (str): The actor's first name.
actor2 (str): The actor's last name.
Returns:
bool: True if the concatenated string is equal to 'Leonardo DiCaprio', False otherwise.
Example:
>>> concatenate_and_check('Leonardo', 'DiCaprio')
True
>>> concatenate_and_check('Brad', 'Pitt')
False
"""" | "
full_name = actor1 + " " + actor2
return full_name is 'Leonardo DiCaprio'" |
"def combine_strings_with_loop(strings_list: List[str]) -> str:
"""
Takes a list of strings and combines them into a single string using a loop.
Args:
strings_list: A list of strings.
Returns:
The combined string.
"""" | "
result = ''
for string in strings_list:
result += string
return result
" |
"def intersection_of_lists(list1: List[int], list2: List[int]) -> List[int]:
"""
Takes two lists of integers and returns their intersection using a loop.
Args:
list1: A list of integers.
list2: A list of integers.
Returns:
A list containing the common elements between list1 and list2.
"""" | "
intersection = []
for num1 in list1:
for num2 in list2:
if num1 == num2:
intersection.append(num1)
return intersection
" |
"def nested_loop_exercise(sequence):
"""
This exercise requires you to iterate over a sequence using nested loops.
Given a sequence of numbers, you need to find all the pairs of numbers that sum up to a given target value.
Your task is to complete the code to find and return a list of tuples, where each tuple represents a pair of numbers
that sum up to the target value.
Args:
- sequence (list): The sequence of numbers to iterate over.
Returns:
- list: List of tuples representing pairs of numbers that sum up to the target value.
"""" | "
# Define the target value
target = 10
# List to store the pairs
pairs = []
# TODO: Complete the nested loops to find the pairs of numbers that sum up to the target value
for i in range(len(sequence)):
for j in range(i + 1, len(sequence)):
if sequence[i] + sequence[j] == target:
# Add the pair of numbers to the list
pairs.append((sequence[i], sequence[j]))
return pairs
" |
"def dance_routine(dancer, routine):
"""
Dancer performs a dance routine by modifying the elements using indexing.
Args:
dancer: A list of dance moves performed by the dancer.
routine: A list of elements that need to be modified using indexing.
Returns:
None
"""" | "
# Iterate over each element in the routine
for element in routine:
# Extract the necessary information from the element
move, start_index, end_index = element
# Ensure the start_index is within the range of the dancer's moves
if start_index >= 0 and start_index < len(dancer):
# Modify the dancer's moves based on the given start_index and end_index
dancer[start_index] = move * (end_index - start_index + 1)
# Print the final dance routine of the dancer
print("Final Dance Routine:")
for move in dancer:
print(move)
# Example usage
dancer_moves = ["Jump", "Spin", "Twirl", "Slide", "Kick"]
routine_elements = [("Shake", 0, 2), ("Clap", 1, 3), ("Jump", 3, 4" |
"def remove_and_concatenate(lst1, lst2):
"""
The function takes two lists as input and performs the following operations:
1. Removes all elements from lst1 that are present in lst2.
2. Concatenates the remaining elements in lst1 and lst2, ensuring no duplicates.
Finally, it returns the concatenated list.
Args:
lst1 (list): First list of elements
lst2 (list): Second list of elements
Returns:
list: Concatenated list with elements from both input lists
"""" | "
# Remove elements from lst1 that are present in lst2
for element in lst2:
if element in lst1:
lst1.remove(element)
# Concatenate the remaining elements from lst1 and lst2 without duplicates
concatenated_list = lst1 + lst2
# Remove duplicate elements from the concatenated list
concatenated_list = list(set(concatenated_list))
return concatenated_list
" |
"def dancer_matrix_multiplication(matrix1, matrix2):
"""
This function performs matrix multiplication using nested loops for a dancer routine.
Args:
matrix1 (list): The first matrix to be multiplied
matrix2 (list): The second matrix to be multiplied
Returns:
list: The resulting matrix after matrix multiplication
"""" | "
# Check if multiplication is possible
if len(matrix1[0]) != len(matrix2):
raise ValueError("The number of columns in matrix1 must match the number of rows in matrix2")
# Initialize the resulting matrix with zeros
result_matrix = [[0 for _ in range(len(matrix2[0]))] for _ in range(len(matrix1))]
# Multiply the matrices
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
result_matrix[i][j] += matrix1[i][k] * matrix2[k][j]
# Return the resulting matrix
return result_matrix" |
"def calculate_distance(points):
"""
This function takes a list of points and calculates the total distance between each consecutive pair of points.
Args:
- points: a list of points represented as tuples (x, y)
Returns:
- distance: the total distance between all pairs of points
"""" | "
distance = 0
for i in range(len(points) - 1):
# Calculate the Euclidean distance between two consecutive points
x1, y1 = points[i]
x2, y2 = points[i + 1]
pair_distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
# Update the total distance by adding the pair distance
# Fill in the code below to complete the statement
distance += pair_distance
return distance
" |
"def find_common_crops(farmer1_crops, farmer2_crops):
"""
This function finds the common crops between two farmers.
Args:
farmer1_crops (list): List of crops grown by farmer 1
farmer2_crops (list): List of crops grown by farmer 2
Returns:
common_crops (list): List of common crops grown by both farmers
"""" | "
common_crops = []
for crop in farmer1_crops:
if crop not in farmer2_crops:
continue # Skip to the next iteration if crop not in farmer2_crops
common_crops.append(crop)
return common_crops
" |
"def identify_architect(age, experience, skills):
"""
This function determines whether a person qualifies as an architect based on their age, experience, and skills.
Args:
age (int): The age of the person.
experience (int): The experience (in years) of the person.
skills (list): A list of skills possessed by the person.
Returns:
str: A message indicating whether the person qualifies as an architect or not.
"""" | "
if age < 25:
return "Sorry, you must be at least 25 years old to be considered as an architect."
if experience < 5:
return "Sorry, you must have at least 5 years of experience to be considered as an architect."
if "design" not in skills or "planning" not in skills or "construction" not in skills:
return "Sorry, you must possess design, planning, and construction skills to be considered as an architect."
return "Congratulations! You qualify as an architect."
" |
"def find_intersection(coordinates1, coordinates2):
"""
This function finds the intersection of two sets of coordinates.
Args:
coordinates1 (list): The first set of coordinates as a list of tuples.
coordinates2 (list): The second set of coordinates as a list of tuples.
Returns:
list: The intersection of the two sets of coordinates.
"""" | "
intersection = []
for coord1 in coordinates1:
for coord2 in coordinates2:
if coord1 == coord2:
intersection.append(coord1)
break
return intersection
" |
"def calculate_land_area(geographical_data):
"""
This function calculates the total land area of a given region based on the geographical data.
Args:
geographical_data (list): A list of geographical features including the name and area of each feature.
Returns:
float: The total land area of the region.
"""" | "
land_area = 0
for feature in geographical_data:
if feature['type'] == 'land':
land_area += feature['area']
return land_area
" |
"def calculate_max_load(design_limit, material_strength, safety_factor):
"""
Calculates the maximum load that a structure can handle.
Args:
- design_limit (float): The maximum allowable load specified in the design code.
- material_strength (float): The ultimate strength of the material used in the structure.
- safety_factor (float): The safety factor used to account for uncertainties in loads and materials.
Returns:
- max_load (float): The maximum load that the structure can handle.
"""" | "
max_load = 0
for i in range(int(design_limit+1)):
load = i * material_strength
if load >= (design_limit * safety_factor):
break
max_load = load
return max_load
" |
"def find_intersection(athletes):
"""
This function takes a list of athletes' names and returns a list
of the athletes who participate in all the sports given.
Args:
athletes (list): A list of athletes' names.
Returns:
list: A list of athletes who participate in all sports.
"""" | "
# Initialize the common_athletes list with the first athlete's sports
common_athletes = athletes[0]
# Iterate over the remaining athletes
for athlete in athletes[1:]:
# Temporary list to store common sports for current athlete
temp_common_sports = []
# Iterate over the sports of each athlete
for sport in athlete:
# Check if the sport is in common_athletes list
if sport in common_athletes:
# If sport exists in common_athletes list, append it to temp_common_sports
temp_common_sports.append(sport)
# Update the common_athletes list with the intersection of sports
common_athletes = temp_common_sports
# Return the final list of athletes participating in all sports
return common_athletes" |
"def copy_and_loop(list1, list2):
"""
Given two lists of integers, copy the common elements from both lists into a new list.
Iterate over each element of both lists using a loop and add the common elements to a new list.
Return the new list containing the common elements.
"""" | "
common_elements = []
# Your code here
for num1 in list1:
for num2 in list2:
if num1 == num2:
if num1 not in common_elements:
common_elements.append(num1)
return common_elements
" |
"def create_tuple_from_string_and_subtraction(string: str, subtract: bool) -> tuple:
"""
This function takes a string as input and subtracts the ASCII value of each character
from its corresponding index in the string. It returns a tuple of the calculated results.
Args:
- string: A string representing the input text.
- subtract: A boolean indicating whether subtraction should be performed.
Returns:
- A tuple containing the calculated results.
Example:
>>> create_tuple_from_string_and_subtraction("Code", True)
(-2, 100, 101, 97)
"""" | "
result = ()
for i, char in enumerate(string):
if subtract:
result += (ord(char) - i,)
else:
result += (ord(char) + i,)
return result
" |
"def get_common_elements(list1, list2):
"""
Given two lists, find the common elements between them.
Args:
list1: A list of elements.
list2: Another list of elements.
Returns:
A list containing the common elements found between list1 and list2.
Example:
>> get_common_elements([1, 2, 3, 4, 5], [4, 5, 6, 7, 8])
Output: [4, 5]
"""" | "
common_elements = []
# Loop through every element in list1
for element in list1:
# Check if the element is in list2 and not already in common_elements
if element in list2 and element not in common_elements:
common_elements.append(element)
return common_elements" |
"def count_vowels(name):
"""
This exercise requires you to manipulate strings and understand the concept of short-circuiting with if-else.
Write a function that takes a string as input and returns the count of vowels in that string.
You must use a loop to iterate through each character of the string and an if-else statement to check if the character is a vowel.
However, you should express the if-else statement in a way that utilizes short-circuiting to improve performance.
Note: Consider both uppercase and lowercase vowels.
Example:
count_vowels("Astronomer") -> 4
Explanation:
The string "Astronomer" has 4 vowels: 'A', 'o', 'e', 'e'.
"""" | "
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
count = 0
for char in name:
if char in vowels:
count += 1
return count" |
"def can_dance(dancer, dancers):
"""Given a list of dancers, return True if the given dancer is present in the first half and also if the given dancer is taller than all the other dancers in the second half of the list. Otherwise, return False."""" | "
# Extract the first half of the given dancers list and assign it to a variable named first_half
first_half = dancers[:len(dancers)//2]
# Extract the second half of the given dancers list and assign it to a variable named second_half
second_half = dancers[len(dancers)//2:]
# Check if the given dancer is present in the first half and if the given dancer is taller than all the other dancers in the second half
if dancer in first_half and all(dancer > other_dancer for other_dancer in second_half):
return True
else:
return False" |
"def create_typed_tuple(selection: str) -> tuple:
"""
Given a selection of historical events, create a tuple of tuples using the tuple() function.
Args:
- selection (str): A string representing historical events, separated by semicolons.
Returns:
- tuple: A tuple of tuples, where each inner tuple contains the event name and its year.
"""" | "
events = selection.split(";") # Split the selection by semicolons
event_tuples = [] # Store each event as a tuple
for event in events:
event_year = "" # Variable to store the year of the event
event_name = "" # Variable to store the name of the event
# Extract the event name and year from the selection
for char in event:
if char.isdigit():
event_year += char
else:
event_name += char
# Ignore events without year information
if event_year != "":
event_tuple = (event_name.strip(), int(event_year.strip())) # Create the tuple containing the event name and year
event_tuples.append(event_tuple) # Add the tuple to the list of event tuples
return tuple(event" |
"def farmer_cows_tuple():
"""
A farmer wants to keep track of the number of cows she owns.
You need to write a function that takes an integer argument 'num_cows' and returns a tuple
consisting of consecutive numbers starting from 1 up to the given 'num_cows'.
For example, if the input is 4, the function should return (1, 2, 3, 4).
Complete the code to solve the exercise.
"""" | "
num_cows = int(input("Enter the number of cows: ")) # Get the number of cows from the user
cows = () # Initialize an empty tuple
# Write a while loop to populate the 'cows' tuple with consecutive numbers from 1 to 'num_cows'
i = 1 # Start the counter at 1
while i <= num_cows:
# Add the current number to the tuple
cows += (i,) # Note the use of parentheses inside the parentheses to create a singleton tuple
i += 1 # Increment the counter
return cows
" |
"def precedence_of_logical_operators_and_creating_a_set():
"""
Given a list of logical expressions, prioritize the evaluation of the logical operators
and create a set with the results of each expression.
Logical expressions:
- expr1: result of (True and False) or True or False
- expr2: result of not (True and False) or (not (True or False))
Returns:
A set containing the results of each logical expression.
Example:
Input:
No input required.
Output:
{False, True}
"""" | "
# Precedence of logical operators:
# not -> and -> or
result1 = (True and False) or True or False
result2 = not (True and False) or (not (True or False))
# Creating a set with the results
results = {result1, result2}
return results" |
"def calculate_average_income(data):
"""
Given a list of dictionaries containing information on income and population,
calculate the average income per person.
Args:
- data (list): List of dictionaries, where each dictionary contains 'income'
and 'population' keys.
Return:
- average_income (float): Average income per person.
Example:
calculate_average_income([{'income': 50000, 'population': 1000},
{'income': 60000, 'population': 2000},
{'income': 40000, 'population': 1500}])
Output: 44.444 (rounded to 3 decimal places)
"""" | "
total_income = 0.0
total_population = 0
for entry in data:
# Access the income and population values from each dictionary
income = entry['income']
population = entry['population']
# Calculate the total income and population
total_income += income
total_population += population
# Calculate the average income per person
average_income = total_income / total_population
return round(average_income, 3)
" |
"def calculate_mean(numbers):
"""
This function takes a list of integers as input and calculates the mean (average) of the numbers.
"""" | "
# Check if the input is empty
if len(numbers) == 0:
return None
# Calculate the sum of all numbers
sum_of_numbers = sum(numbers)
# Calculate the mean by dividing the sum by the number of elements
mean = sum_of_numbers / len(numbers)
return mean
" |
"def calculate_median(numbers):
"""
This function takes a list of integers as input and calculates the median (middle value) of the numbers.
In case of an even number of elements, the average of the two middle values is returned.
"""" | "
# Sort the numbers in ascending order
sorted_numbers = sorted(numbers)
# Check if the input is empty
if len(sorted_numbers) == 0:
return None
# Calculate the index of the middle element
mid_index = len(sorted_numbers) // 2
# Check if the number of elements is odd
if len(sorted_numbers) % 2 == 1:
median = sorted_numbers[mid_index]
else:
# Calculate the" |
"def calculate_strength_diff(selection, intensity):
"""
This exercise aims to simulate a physical therapy session for calculating the difference in strength of the selected muscles.
Args:
selection (list): A list of muscle groups selected for evaluation.
intensity (float): The intensity level applied during the evaluation.
Returns:
dict: A dictionary containing the complex conjugate and absolute value of the difference in strength for each selected muscle group.
"""" | "
results = {}
for muscle in selection:
# Simulating strength evaluation process
measured_strength = some_physical_therapy_method(muscle, intensity)
# Perform complex conjugate and absolute calculation
conjugate = measured_strength.conjugate()
absolute_value = abs(measured_strength)
results[muscle] = {'Conjugate': conjugate, 'Absolute Value': absolute_value}
return results
# Example usage:
selected_muscles = ['Quadriceps', 'Hamstrings', 'Gluteus Maximus']
intensity_level = 0.8
strength_differences = calculate_strength_diff(selected_muscles, intensity_level)
print(strength_differences)
# Output:
# {
# 'Quadr" |
"def calculate_client_bill(hourly_rate, hours_worked, additional_charges):
"""
This function calculates the total bill for a graphic designer based on their hourly rate, hours worked, and any additional charges.
Parameters:
hourly_rate (float): The hourly rate of the graphic designer.
hours_worked (float): The number of hours worked by the graphic designer.
additional_charges (float): Any additional charges applied to the bill.
Returns:
float: The total bill for the graphic designer.
"""" | "
total_bill = 0.0
if hourly_rate > 0 and hours_worked > 0:
total_bill = hourly_rate * hours_worked
if additional_charges > 0:
total_bill += additional_charges
return total_bill
" |
"def calculate_harvest(farm):
"""
Calculates the total harvest count for a farmer's crops.
Args:
- farm (list of lists): Represents the layout of the farm, where each sublist
represents a row and the elements within each sublist represent the number of
crops in that location.
Returns:
- total_harvest (int): The total number of crops harvested from the farm.
"""" | "
total_harvest = 0
i = 0
while i < len(farm):
j = 0
while j < len(farm[i]):
if farm[i][j] > 0:
total_harvest += farm[i][j]
j += 1
i += 1
return total_harvest
# Example Usage:
farm = [[0, 5, 3, 0], [1, 0, 2, 4], [0, 0, 0, 0], [8, 2, 6, 0]]
total_harvest = calculate_harvest(farm)
print(total_harvest) # Output: 31" |
"def find_patient_with_condition(patients, condition):
"""
Given a list of patients and a specific condition,
this function should return the first patient who has that condition.
Args:
- patients (list): A list of patient names (strings).
- condition (str): The condition to be searched for.
Returns:
- str: The name of the patient with the given condition or None if no patient has it.
Example:
>>> patients = ["John Doe", "Alice Smith", "Jack Johnson", "Jane Brown"]
>>> find_patient_with_condition(patients, "flu")
'John Doe'
>>> find_patient_with_condition(patients, "covid")
'Jack Johnson'
>>> find_patient_with_condition(patients, "migraine")
None
"""" | "
index = 0
while index < len(patients):
patient = patients[index]
if condition in patient:
return patient
index += 1
return None" |
"def find_common_chars(str1, str2):
"""
This exercise is to help the Marketing Manager to find the common characters between two strings using an unconditioned ternary operator and a while loop.
The function takes two strings as arguments and returns a list of common characters found in both strings.
Example:
find_common_chars("hello", "world") should return ['l', 'o'].
Your task is to complete the code below by using an unconditioned ternary operator and a while loop to solve the exercise.
"""" | "
common_chars = []
i = 0
while i < len(str1):
common_chars.append(str1[i]) if str1[i] in str2 else None
i += 1
return common_chars" |
"def find_common_elements(rock1, rock2):
"""A geologist wants to find the common elements between two rocks.
The function takes in two lists, rock1 and rock2, which represent the composition of the rocks.
It returns a new list with the common elements found in both rocks.
Use the 'not in' operator to check if an element from rock1 exists in rock2.
Difficulty: Difficult"""" | "
common_elements = []
for element in rock1:
if element not in rock2:
continue
else:
common_elements.append(element)
return common_elements
" |
"def create_tuple_with_or_operator(books: list, movies: list) -> tuple:
"""
This function takes two lists of items and returns a tuple containing all the items that are present in at least one of the lists.
Args:
- books: A list of books.
- movies: A list of movies.
Returns:
- A tuple containing all the items that are present in at least one of the lists.
Example:
create_tuple_with_or_operator(['Harry Potter', 'Lord of the Rings'], ['The Godfather', 'Lord of the Rings'])
Output: ('Harry Potter', 'Lord of the Rings', 'The Godfather')
"""" | "
combined_list = books + movies # Combine both lists
unique_items = list(set(combined_list)) # Remove duplicates
unique_items.sort() # Sort the items alphabetically
result_tuple = tuple(unique_items) # Convert list to tuple
return result_tuple
" |
"def librarian_check_book_returned(book_is_borrowed: bool, book_is_overdue: bool) -> bool:
"""
A librarian wants to check if a book has been returned and if it is overdue.
Complete the function 'librarian_check_book_returned' that takes in two boolean arguments:
- book_is_borrowed: indicating whether the book has been borrowed or not (True/False)
- book_is_overdue: indicating whether the book is overdue or not (True/False)
The function should return a boolean value:
- True if the book has been returned and is overdue
- False if the book has not been returned or is not overdue
For example:
- librarian_check_book_returned(True, True) should return True
- librarian_check_book_returned(True, False) should return False
- librarian_check_book_returned(False, True) should return False
- librarian_check_book_returned(False, False) should return False
"""" | "
return book_is_borrowed and book_is_overdue" |
"def compare_lists(list1, list2):
"""
Given two lists, return a new list containing the elements that appear in both lists.
Example:
compare_lists([1, 2, 3, 4], [3, 4, 5, 6]) -> [3, 4]
Required knowledge: booleans, identity comparison, list iteration.
"""" | "
# Initialize an empty list to store the common elements
common_elements = []
# Loop through the first list
for element in list1:
# Check if the element is also present in the second list using identity comparison
if element in list2 and element not in common_elements: # INCOMPLETE
# Append the common element to the list
common_elements.append(element)
return common_elements" |
"def calculate_total_income(income, expenses):
"""
Given two tuples containing income and expenses, return the total income after deducting expenses.
Args:
income (tuple): A tuple containing different sources of income.
expenses (tuple): A tuple containing different expenses.
Returns:
float: Total income after deducting expenses.
"""" | "
total_income = sum(income)
for expense in expenses:
total_income -= expense
return total_income
" |
"def calculate_net_profit(income, expenses):
"""
Given two tuples containing income and expenses, return the net profit after deducting expenses.
Args:
income (tuple): A tuple containing different sources of income.
expenses (tuple): A tuple containing different expenses.
Returns:
float: Net profit after deducting expenses.
"""" | "
net_profit = calculate_total_income(income, expenses)
if net_profit < 0:
return 0
else:
return net_profit
" |
"def modify_element_coordinates(coordinates):
"""
This exercise focuses on a game developer's skill to modify the coordinates of game elements using a for loop.
The 'coordinates' parameter is a list containing the coordinates (x, y) of several game elements. Your task is to modify the second element's x-coordinate by adding 10 to its current value.
Complete the code below to solve the exercise.
"""" | "
for index, coord in enumerate(coordinates):
if index == 1:
coordinates[index] = (coord[0] + 10, coord[1])
return coordinates
" |
"def update_tuple(tuple1, tuple2):
"""
This function takes two tuples, tuple1 and tuple2, and updates tuple1 with the elements from tuple2.
The updated tuple1 is returned.
"""" | "
# Convert the tuples to lists for easier manipulation
list1 = list(tuple1)
list2 = list(tuple2)
# Iterate through the elements of tuple2
for element in list2:
# Check if the element is already in tuple1
if element not in list1:
# Append the element to tuple1
list1.append(element)
# Convert the updated list1 back to a tuple
updated_tuple = tuple(list1)
# Return the updated tuple1
return updated_tuple
" |
"def diagnose_animal(sick_animals):
"""
Given a list of sick animals, this function diagnoses each animal
and determines the treatment needed. The function utilizes conditional
statements and nested loops to control the flow of the diagnosis
process.
Args:
sick_animals (list): A list of sick animals.
Returns:
list: A list of tuples, where each tuple contains the diagnosed animal
and the recommended treatment.
"""" | "
diagnoses = []
for animal in sick_animals:
print(f"Diagnosing {animal}...")
if animal == "dog" or animal == "cat":
symptoms = input("Please enter the symptoms: ").split(", ")
if "coughing" in symptoms or "sneezing" in symptoms:
treatment = "antibiotics"
elif "itching" in symptoms or "hair loss" in symptoms:
treatment = "antiparasitic medication"
elif "vomiting" in symptoms or "diarrhea" in symptoms:
treatment = "antiemetics"
else:
treatment = "unknown"
elif animal == "bird":
print("Birds have respiratory symptoms" |
"def replace_elements(lst1, lst2, idx1, idx2):
"""
Given two lists lst1 and lst2, and two indices idx1 and idx2, this function returns a new list in which the elements
from idx1 to idx2 (inclusive) in lst1 are replaced by the elements in lst2.
Args:
- lst1: A list of elements (e.g., integers, strings).
- lst2: A list of elements (e.g., integers, strings).
- idx1: An integer representing the starting index.
- idx2: An integer representing the ending index.
Returns:
- A new list with replaced elements.
Example:
replace_elements([1, 2, 3, 4, 5], ['a', 'b', 'c'], 1, 3)
Output: [1, 'a', 'b', 'c', 5]
"""" | "
return lst1[:idx1] + lst2 + lst1[idx2+1:]
" |
"def calculate_distance(point1, point2):
"""Function to calculate the distance between two points"""" | "
# Check if the points are valid representations of complex numbers
if (not isinstance(point1, complex)) or (not isinstance(point2, complex)):
return "Invalid input!"
# Extract the real and imaginary parts of the complex numbers
x1 = point1.real
y1 = point1.imag
x2 = point2.real
y2 = point2.imag
# Calculate the distance using Euclidean distance formula
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
return distance
" |
"def find_nearest_point(point, points):
"""Function to find the nearest point to a given point"""" | "
# Check if the given point is a valid representation of a complex number
if not isinstance(point, complex):
return "Invalid input!"
# Initialize variables for storing the nearest point and its distance
nearest_point = None
min_distance = float('inf')
# Iterate through all the points
for p in points:
# Check" |
"def find_excluded_cases(cases: set, valid_cases: set) -> set:
"""
This function takes a set of cases and a set of valid cases as input, and returns a set of excluded cases.
Excluded cases refer to the cases that are not valid according to the given set of valid cases.
Args:
- cases: A set of cases (strings)
- valid_cases: A set of valid cases (strings)
Returns:
- A set of excluded cases (strings)
"""" | "
excluded_cases = set()
for case in cases:
is_excluded = True
for valid_case in valid_cases:
if valid_case == case:
is_excluded = False
break
if is_excluded:
excluded_cases.add(case)
return excluded_cases" |
"def add_complex_numbers(complex_1, complex_2):
"""
Write a function that takes two complex numbers represented as pairs of floats (real, imag) and returns their sum.
Args:
complex_1 (tuple): A pair of floats representing the real and imaginary part of the first complex number.
complex_2 (tuple): A pair of floats representing the real and imaginary part of the second complex number.
Returns:
tuple: A pair of floats representing the real and imaginary part of the sum of the two complex numbers.
Example:
>>> add_complex_numbers((2, 3), (-1, 5))
(1, 8)
"""" | "
real_part = complex_1[0] + complex_2[0]
imag_part = complex_1[1] + complex_2[1]
return real_part, imag_part
" |
Dataset Card for "code_exercises"
Code exercise
This dataset is composed of a diverse set of ~120k Python code exercises (~120m total tokens) generated by ChatGPT 3.5. It is designed to distill ChatGPT 3.5 knowledge about Python coding tasks into other (potentially smaller) models. The exercises have been generated by following the steps described in the related GitHub repository.
The generated exercises follow the format of the Human Eval benchmark. Each training sample is split into a Python function signature with a descriptive docstring, and a solution to the exercise.
This approach is inspired by several works on synthetic dataset generation, especially by Textbooks Are All You Need (Gunasekar et al. 2023).
Disclaimer
This dataset has been generated using ChatGPT 3.5, and you should check the legal status of AI-generated content in your jurisdiction before use. We cannot guarantee that it is free of IP restrictions. You should also make sure that your usage complies with the OpenAI Terms of Use, in so far as legally applicable.
This dataset focuses narrowly on improving performance on the kinds of tasks described in the Human Eval benchmark. The Human Eval benchmark has limitations and does not necessarily fully represent the coding abilities of a large language model, and there is no way to guarantee that an improvement on this benchmark represents an overall improvement in programming performance. We present this data as is, without any guarantee of its usefulness in any specific context, to encourage research that might be inspired by our method.
Synthetic exercise creation
Model distillation is the process of transferring some of the skilled performance of large models on specific classes of tasks to significantly smaller models. The purpose is to get performance comparable to the larger model, but at a fraction of the cost and at vastly quicker speed. The general outline of this strategy is described (without technical implementation details) in Textbooks Are All You Need.
Key to the distillation process is the creation of synthetic data, generated by the larger AI model, to train the smaller model. We have applied this approach to Python programming tasks and are publishing a summary of our methods here along with the synthetic dataset.
For fuller details and implementation code, see the related GitHub repository.
Diversity
The main problem with model-generated synthetic data is its diversity. If we had constructed this dataset by giving ChatGPT 3.5 the same prompt several hundred thousand times, we would get many very similar, if not functionally identical, results. This would reduce the usefulness of the dataset for training. In principle, one might solve the problem by filtering the results for near duplicates, but this is a non-trivial problem, and even if it could be solved, it would be a wasteful and potentially expensive use of the larger model.
And even then, we could not be sure the examples adequately covered the topic. To solve this problem, we introduced a novel scheme for systematically prompting large language models to produce diverse examples.
Using a topic tree to build diverse prompts
We constructed a hierarchical model of subjects in Python programming, i.e. a topic tree. First, we manually identified 42 general topic areas in Python knowledge, for example, data structures and sorting algorithms. We asked an LLM to propose 10 subtopics for each, and then for each of those 420 fine-grained topics, we asked the LLM to generate 5 even more fine-grained sub-subtopics. This resulted in roughly 2000 very fine-grained topics.
We generated prompts by randomly selecting two of those roughly two thousand topics and combining them:
Create a code completion exercise on the intersection of {topic 1} and {topic 2}.
To increase randomness and diversity in the results, we also constructed a list of 40 professions, like economist, engineer, and social worker, and added them to the prompt:
Create a code completion exercise on the intersection of {topic 1} and {topic 2}.
Write it for a {profession}.
In principle, there are approximately two million possible pairs of topics, and with 40 possible professions, this yields 80 million unique prompts. If the response to each prompt averages 100 tokens, this means our method can generate an 8 billion token synthetic dataset while maintaining a high degree of diversity. The roughly 120,000 published here is a small random subset of what is possible.
Credits
This dataset was developed at Jina.ai
- Downloads last month
- 27