Initial commit
This commit is contained in:
commit
633968fb77
9
2D_array_boolean_indexing.py
Normal file
9
2D_array_boolean_indexing.py
Normal file
@ -0,0 +1,9 @@
|
||||
import numpy as np
|
||||
|
||||
array_2d = np.array([
|
||||
[1, 2, 3],
|
||||
[4, 5, 6],
|
||||
[7, 8, 9]
|
||||
])
|
||||
# Retrieving elements less than 3 or greater than OR greater than or equal to 8
|
||||
print(array_2d[(array_2d < 3) | (array_2d >= 8)])
|
||||
30
2D_array_indexing.py
Normal file
30
2D_array_indexing.py
Normal file
@ -0,0 +1,30 @@
|
||||
import numpy as np
|
||||
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
|
||||
# Accessing the first element (1D array) with positive index
|
||||
print(array_2d[0])
|
||||
# Accessing the first element (1D array) with negative index
|
||||
print(array_2d[-2])
|
||||
# Accessing the second element of the first 1D array with negative index
|
||||
print(array_2d[0, -3])
|
||||
# Accessing the second element of the first 1D array with positive index
|
||||
print(array_2d[0, 1])
|
||||
# Accessing the last element of the last 1D array with negative index
|
||||
print(array_2d[-1, -1])
|
||||
|
||||
# Creating a 5x5 matrix representing stock prices
|
||||
stock_prices = np.array([
|
||||
[120, 130, 140, 150, 160],
|
||||
[210, 220, 230, 240, 250],
|
||||
[310, 320, 330, 340, 350],
|
||||
[410, 420, 430, 440, 450],
|
||||
[510, 520, 530, 540, 550]
|
||||
])
|
||||
# Retrieve all the stock prices of the first company over five days with a positive index
|
||||
first_company_prices = stock_prices[0]
|
||||
# Retrieve the stock price of the third company on the second day with positive indices
|
||||
third_company_second_day_price = stock_prices[2, 1]
|
||||
# Retrieve the stock price of the last company on the last day with negative indices
|
||||
last_company_last_day_price = stock_prices[-1, -1]
|
||||
print(first_company_prices)
|
||||
print(third_company_second_day_price)
|
||||
print(last_company_last_day_price)
|
||||
19
2D_array_slicing.py
Normal file
19
2D_array_slicing.py
Normal file
@ -0,0 +1,19 @@
|
||||
import numpy as np
|
||||
array_2d = np.array([
|
||||
[1, 2, 3, 4],
|
||||
[5, 6, 7, 8],
|
||||
[9, 10, 11, 12]
|
||||
])
|
||||
print(array_2d[1:])
|
||||
print(array_2d[:, 0])
|
||||
print(array_2d[1:, 1:-1])
|
||||
print(array_2d[:-1, ::2])
|
||||
print(array_2d[2, ::-2])
|
||||
|
||||
array = np.array([23, 41, 7, 80, 3])
|
||||
# Retrieving elements at indices 0, 1 and 3
|
||||
print(array[[0, 1, 3]])
|
||||
# Retrieving elements at indices 1, -1 and 2 in this order
|
||||
print(array[[1, -1, 2]])
|
||||
# IndexError is thrown since index 5 is out of bounds
|
||||
print(array[[2, 4]])
|
||||
19
2D_int_array_indexing.py
Normal file
19
2D_int_array_indexing.py
Normal file
@ -0,0 +1,19 @@
|
||||
import numpy as np
|
||||
|
||||
array_2d = np.array([
|
||||
[1, 2, 3],
|
||||
[4, 5, 6],
|
||||
[7, 8, 9]
|
||||
])
|
||||
# Retrieving first and the third row
|
||||
print(array_2d[[0, 2]])
|
||||
# Retrieving the main diagonal elements
|
||||
print(array_2d[[0, 1, 2], [0, 1, 2]])
|
||||
# Retrieving the first and third element of the second row
|
||||
print(array_2d[1, [0, 2]])
|
||||
# IndexError is thrown, since index 3 along axis 0 is out of bounds
|
||||
print(array_2d[[0, 2], [0, 1]])
|
||||
#print(array_2d[[0, 1, 2], [2, 1, 0]])
|
||||
|
||||
|
||||
|
||||
17
3D_array_indexing.py
Normal file
17
3D_array_indexing.py
Normal file
@ -0,0 +1,17 @@
|
||||
import numpy as np
|
||||
|
||||
array_3d = np.array([
|
||||
[[1, 2, 3], [4, 5, 6]],
|
||||
[[7, 8, 9], [10, 11, 12]],
|
||||
[[13, 14, 15], [16, 17, 18]]
|
||||
])
|
||||
|
||||
# Retrieving the first and second element of the first row in the second 2D array
|
||||
#print(array_3d[0, 1, [0, 1]])
|
||||
# Retrieving the first and second element of the second row in the second 2D array
|
||||
#print(array_3d[1, 1, [0, 1]])
|
||||
# Retrieving the first and second element of the second row in the third 2D array
|
||||
#print(array_3d[2, 1, [0, 1]])
|
||||
|
||||
#accessing the main diagonal elements across the 3D array
|
||||
print(array_3d[[0, 1, 2], [0, 1, 1], [0, 1, 2]])
|
||||
5
Context_Managers.py
Normal file
5
Context_Managers.py
Normal file
@ -0,0 +1,5 @@
|
||||
with open('notes.txt', 'w') as file:
|
||||
file.write("This is a note.")
|
||||
|
||||
print("File has been written and closed automatically.")
|
||||
|
||||
24
Lambda_funcs.py
Normal file
24
Lambda_funcs.py
Normal file
@ -0,0 +1,24 @@
|
||||
# Define a function that takes a function and a value as arguments
|
||||
def apply_function(func, value):
|
||||
return func(value)
|
||||
|
||||
# Call the function with a lambda function as the first argument
|
||||
result = apply_function(lambda x: x * x, 25)
|
||||
|
||||
print(result)
|
||||
|
||||
# Define a function that applies a given function to each element in a list
|
||||
def apply_to_list(numbers, func):
|
||||
"""Applies the given function to each element in the numbers list."""
|
||||
return [func(x) for x in numbers]
|
||||
|
||||
# List of numbers
|
||||
numbers = [1, 2, 3, 4, 5]
|
||||
|
||||
# Using a lambda function to add 10 to each number
|
||||
result_add = apply_to_list(numbers, lambda x: x + 10)
|
||||
print("Adding 10:", result_add)
|
||||
|
||||
# Using a lambda function to multiply each number by 2
|
||||
result_multiply = apply_to_list(numbers, lambda x: x * 2)
|
||||
print("Multiplying by 2:", result_multiply)
|
||||
14
Lists_In_Functions.py
Normal file
14
Lists_In_Functions.py
Normal file
@ -0,0 +1,14 @@
|
||||
def add_strawberry(original_list):
|
||||
list_copy = original_list.copy() # Create a copy of the original list
|
||||
list_copy.append("Strawberry") # Modify the copied list
|
||||
return list_copy
|
||||
|
||||
# Original list
|
||||
fruits = ["Apple", "Banana", "Cherry"]
|
||||
|
||||
# Call the function
|
||||
new_fruits = add_strawberry(fruits)
|
||||
|
||||
# Check the results
|
||||
print("Original list:", fruits) # ['Apple', 'Banana', 'Cherry']
|
||||
print("Modified list:", new_fruits) # ['Apple', 'Banana', 'Cherry', 'Strawberry']
|
||||
34
RMD_Calculator.py
Normal file
34
RMD_Calculator.py
Normal file
@ -0,0 +1,34 @@
|
||||
def calculate_rmd(balance, age):
|
||||
"""
|
||||
Calculates the Required Minimum Distribution (RMD)
|
||||
using the IRS Uniform Lifetime Table.
|
||||
|
||||
Parameters:
|
||||
- balance (float): IRA balance on Dec 31 of the prior year
|
||||
- age (int): age as of the distribution year
|
||||
|
||||
Returns:
|
||||
- rmd (float): calculated RMD
|
||||
"""
|
||||
|
||||
# Life expectancy factors from the IRS Uniform Lifetime Table (selected ages)
|
||||
uniform_lifetime_table = {
|
||||
73: 26.5, 74: 25.5, 75: 24.6, 76: 23.7, 77: 22.9,
|
||||
78: 22.0, 79: 21.1, 80: 20.2, 81: 19.4, 82: 18.5,
|
||||
83: 17.7, 84: 16.8, 85: 16.0
|
||||
# Add more ages if needed
|
||||
}
|
||||
|
||||
if age not in uniform_lifetime_table:
|
||||
raise ValueError(f"No factor found for age {age}. Please check IRS table.")
|
||||
|
||||
factor = uniform_lifetime_table[age]
|
||||
rmd = balance / factor
|
||||
return round(rmd, 2)
|
||||
|
||||
# Example usage
|
||||
ira_balance = 100000 # Replace with actual Dec 31 balance for the prior year
|
||||
age = 73 # Replace with your age as of the distribution year
|
||||
|
||||
rmd_amount = calculate_rmd(ira_balance, age)
|
||||
print(f"Your RMD for age {age} is: ${rmd_amount}")
|
||||
BIN
__pycache__/layers.cpython-313.pyc
Normal file
BIN
__pycache__/layers.cpython-313.pyc
Normal file
Binary file not shown.
BIN
__pycache__/multiprocessing.cpython-313.pyc
Normal file
BIN
__pycache__/multiprocessing.cpython-313.pyc
Normal file
Binary file not shown.
22
activations.py
Normal file
22
activations.py
Normal file
@ -0,0 +1,22 @@
|
||||
import numpy as np
|
||||
|
||||
|
||||
class ReLU:
|
||||
def __call__(self, x):
|
||||
return np.maximum(0, x)
|
||||
|
||||
def derivative(self, x):
|
||||
return (x > 0).astype(float)
|
||||
|
||||
|
||||
class Sigmoid:
|
||||
def __call__(self, x):
|
||||
return 1 / (1 + np.exp(-x))
|
||||
|
||||
def derivative(self, x):
|
||||
sig = self.__call__(x)
|
||||
return sig * (1 - sig)
|
||||
|
||||
|
||||
relu = ReLU()
|
||||
sigmoid = Sigmoid()
|
||||
75
animal_talk.py
Normal file
75
animal_talk.py
Normal file
@ -0,0 +1,75 @@
|
||||
|
||||
|
||||
"""
|
||||
This module defines an abstract base class `Animal` and its subclasses `Dog` and `Cat`,
|
||||
demonstrating object-oriented principles such as inheritance, abstraction, and polymorphism.
|
||||
Classes:
|
||||
Animal:
|
||||
Abstract base class representing a generic animal.
|
||||
Methods:
|
||||
speak(): Abstract method to be implemented by subclasses for animal sound.
|
||||
move(): Abstract method to be implemented by subclasses for animal movement.
|
||||
Dog(Animal):
|
||||
Represents a dog with breed, name, and age attributes.
|
||||
Methods:
|
||||
speak(): Returns the sound a dog makes ("Woof!").
|
||||
move(): Returns a description of how a dog moves ("runs energetically").
|
||||
Cat(Animal):
|
||||
Represents a cat with breed, name, age, and color attributes.
|
||||
Methods:
|
||||
speak(): Returns the sound a cat makes ("Meow!").
|
||||
move(): Returns a description of how a cat moves ("walks gracefully").
|
||||
Usage:
|
||||
Demonstrates polymorphism by creating instances of Dog and Cat and invoking their
|
||||
respective speak and move methods.
|
||||
"""
|
||||
|
||||
class Animal: # Abstract Base Class (Not to be instantiated directly)
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def speak(self):
|
||||
raise NotImplementedError("Subclasses must implement this method")
|
||||
|
||||
def move(self):
|
||||
raise NotImplementedError("Subclasses must implement this method")
|
||||
|
||||
class Dog(Animal): # Subclass of Animal with 3 attributes
|
||||
def __init__(self, breed, name, age):
|
||||
super().__init__()
|
||||
self.breed = breed
|
||||
self.name = name
|
||||
self.age = age
|
||||
|
||||
def speak(self): # Implementation of abstract method
|
||||
return "Woof!"
|
||||
|
||||
def move(self): # Implementation of abstract method
|
||||
return "runs energetically"
|
||||
|
||||
class Cat(Animal): # Subclass of Animal with 4 attributes
|
||||
def __init__(self, breed, name, age, color):
|
||||
super().__init__()
|
||||
self.breed = breed
|
||||
self.name = name
|
||||
self.age = age
|
||||
self.color = color
|
||||
|
||||
def speak(self): # Implementation of abstract method
|
||||
return "Meow!"
|
||||
|
||||
def move(self): # Implementation of abstract method
|
||||
return "walks gracefully"
|
||||
|
||||
|
||||
# Creating instances of Dog and Cat
|
||||
my_dog = Dog("Collie","Buddy", 9)
|
||||
my_cat = Cat("Simese","Whiskers", 3, "White")
|
||||
my_other_dog = Dog("Snouser","Max", 5)
|
||||
|
||||
# Demonstrating polymorphism
|
||||
print(f"My {my_dog.breed} dog, {my_dog.name}, age {my_dog.age} says {my_dog.speak()} and {my_dog.move()}")
|
||||
print(f"My {my_cat.color} {my_cat.breed} cat, {my_cat.name}, age {my_cat.age} says {my_cat.speak()} and {my_cat.move()}")
|
||||
print(f"My {my_other_dog.breed} dog, {my_other_dog.name}, age {my_other_dog.age} says {my_other_dog.speak()} and {my_other_dog.move()}")
|
||||
|
||||
|
||||
19
args_and_kargs_in_func.py.py
Normal file
19
args_and_kargs_in_func.py.py
Normal file
@ -0,0 +1,19 @@
|
||||
def new_func(a, b=0, *args, **kwargs):
|
||||
print(f"a = {a}, b = {b}, args = {args}, kwargs = {kwargs}")
|
||||
|
||||
"""
|
||||
A function that demonstrates the use of positional, default, variable positional (*args), and variable keyword (**kwargs) arguments.
|
||||
Parameters:
|
||||
a (Any): The first positional argument.
|
||||
b (Any, optional): The second argument with a default value of 0.
|
||||
*args: Additional positional arguments.
|
||||
**kwargs: Additional keyword arguments.
|
||||
Prints:
|
||||
The values of 'a', 'b', 'args', and 'kwargs' in a formatted string.
|
||||
Returns:
|
||||
None
|
||||
|
||||
"""
|
||||
# Example usage of the new_func function
|
||||
new_func(1, 2, "Love", "Hope", name="Anna", age=20)
|
||||
|
||||
33
args_and_optionals.py.py
Normal file
33
args_and_optionals.py.py
Normal file
@ -0,0 +1,33 @@
|
||||
def add(a=0, b=0, *args):
|
||||
total = a + b
|
||||
for num in args:
|
||||
total += num
|
||||
return total
|
||||
|
||||
"""
|
||||
Adds two or more numbers together.
|
||||
|
||||
Parameters:
|
||||
a (int or float, optional): The first number to add. Defaults to 0.
|
||||
b (int or float, optional): The second number to add. Defaults to 0.
|
||||
*args (int or float): Additional numbers to add.
|
||||
|
||||
Returns:
|
||||
int or float: The sum of all provided numbers.
|
||||
"""
|
||||
|
||||
print(add(1, 2)) # Output: 3
|
||||
print(add(1, 2, 3, 4)) # Output: 10
|
||||
print(add(1)) # Output: 1
|
||||
print(add(1, 2, 3, 4, 5, 6)) # Output: 21
|
||||
print(add()) # Output: 0
|
||||
|
||||
# Function to calculate the average mark of a student
|
||||
# It takes the student's name and a variable number of marks as arguments.
|
||||
def average_mark(name, *args):
|
||||
mark = round(sum(args)/len(args), 2) # average value rounded to the 2 num after the dot
|
||||
print(f"{name} got {mark}")
|
||||
|
||||
average_mark("Tom", 4.0, 3.5, 3.0, 3.3, 3.8)
|
||||
average_mark("Dick", 2.5, 3.8)
|
||||
average_mark("Harry", 4.0, 4.5, 3.8, 4.2, 4.0, 3.9)
|
||||
10
array_boolean_indexing.py
Normal file
10
array_boolean_indexing.py
Normal file
@ -0,0 +1,10 @@
|
||||
import numpy as np
|
||||
# Creating an array of integers from 1 to 10 inclusive
|
||||
array = np.arange(1, 11)
|
||||
# Creating a boolean array based on a condition
|
||||
boolean_array = array > 5
|
||||
print(boolean_array)
|
||||
|
||||
# Creating an array of integers from 1 to 10 inclusive
|
||||
array = np.arange(1, 11)
|
||||
print(array[array > 5])
|
||||
18
array_comparisons.py
Normal file
18
array_comparisons.py
Normal file
@ -0,0 +1,18 @@
|
||||
import numpy as np
|
||||
# Creating an array of integers from 1 to 10 inclusive
|
||||
array = np.arange(1, 11)
|
||||
# Retrieving elements greater than or equal to 5 AND less than 9
|
||||
print(array[(array >= 5) & (array < 9)])
|
||||
# Retrieving elements less than or equal to 4 AND not equal to 2
|
||||
print(array[(array != 2) & (array <= 4)])
|
||||
# Retrieving elements less than 3 OR equal to 8
|
||||
print(array[(array < 3) | (array == 8)])
|
||||
# Retrieving elements between 2 inclusive AND 5 inclusive OR equal to 9
|
||||
print(array[(array >= 2) & (array <= 5) | (array == 9)])
|
||||
|
||||
'''
|
||||
If both conditions are true, | returns True, otherwise returns False.
|
||||
If either condition is true, & returns True, otherwise returns False.
|
||||
The & operator is used for element-wise logical AND, while | is used for element-wise logical OR.
|
||||
The parentheses around conditions are necessary to ensure correct precedence of operations.
|
||||
'''
|
||||
18
array_copying.py
Normal file
18
array_copying.py
Normal file
@ -0,0 +1,18 @@
|
||||
import numpy as np
|
||||
"""
|
||||
This script demonstrates how to copy and modify NumPy arrays for simulated sales data.
|
||||
|
||||
- Imports NumPy for array manipulation.
|
||||
- Defines `sales_data_2021` as a 2D NumPy array representing quarterly sales for two products in 2021.
|
||||
- Creates a deep copy of `sales_data_2021` named `sales_data_2022` to simulate sales for the next year.
|
||||
- Updates the last two quarters' sales for the first product in `sales_data_2022` with new values (390 and 370).
|
||||
- Prints both the original and modified sales data arrays for comparison.
|
||||
"""
|
||||
# Simulated quarterly sales data for two products in 2021
|
||||
sales_data_2021 = np.array([[350, 420, 380, 410], [270, 320, 290, 310]])
|
||||
# Create a copy of sales_data_2021
|
||||
sales_data_2022 = np.copy(sales_data_2021)
|
||||
# Assign the NumPy array with elements 390 and 370 to the correct slice
|
||||
sales_data_2022[0, -2:] = np.array([390, 370])
|
||||
print(f'Quarterly sales in 2021:\n{sales_data_2021}')
|
||||
print(f'Quarterly sales in 2022:\n{sales_data_2022}')
|
||||
25
array_creation_functions.py
Normal file
25
array_creation_functions.py
Normal file
@ -0,0 +1,25 @@
|
||||
import numpy as np
|
||||
# Сreating a 1D array of zeros with 5 elements
|
||||
zeros_1d = np.zeros(5)
|
||||
print(zeros_1d)
|
||||
# Сreating a 1D array of zeros with specifying dtype
|
||||
zeros_1d_int = np.zeros(5, dtype=np.int8)
|
||||
print(zeros_1d_int)
|
||||
# Сreating a 2D array of zeros of shape 5x3
|
||||
zeros_2d = np.zeros((5, 3))
|
||||
print(zeros_2d)
|
||||
|
||||
# Create an array of zeros of size 5
|
||||
zeros_array_1d = np.zeros(5)
|
||||
# Create an array of zeros of shape 2x4
|
||||
zeros_array_2d = np.zeros((2, 4))
|
||||
# Create an array of ones of size 3
|
||||
ones_array_1d = np.ones(3)
|
||||
# create an array of ones of shape 2x3
|
||||
ones_array_2d = np.ones((2, 3))
|
||||
# Create an array of sevens of shape 2x2
|
||||
sevens_array_2d = np.full((2, 2), 7)
|
||||
print(f'1D zeros array: {zeros_array_1d}, 1D ones array: {ones_array_1d}')
|
||||
print(f'2D zeros array:\n{zeros_array_2d}')
|
||||
print(f'2D ones array:\n{ones_array_2d}')
|
||||
print(f'2D sevens array:\n{sevens_array_2d}')
|
||||
25
array_indexing.py
Normal file
25
array_indexing.py
Normal file
@ -0,0 +1,25 @@
|
||||
import numpy as np
|
||||
array = np.array([9, 6, 4, 8, 10])
|
||||
# Accessing the first element (positive index)
|
||||
print(f'The first element (positive index): {array[0]}')
|
||||
# Accessing the first element (negative index)
|
||||
print(f'The first element (negative index): {array[-5]}')
|
||||
# Accessing the last element (positive index)
|
||||
print(f'The last element (positive index): {array[4]}')
|
||||
# Accessing the last element (negative index)
|
||||
print(f'The last element (negative index): {array[-1]}')
|
||||
# Accessing the third element (positive index)
|
||||
print(f'The third element (positive index): {array[2]}')
|
||||
# Accessing the third element (negative index)
|
||||
print(f'The third element (negative index): {array[-3]}')
|
||||
|
||||
|
||||
array = np.array([9, 6, 4, 8, 10])
|
||||
# Finding the average between the first and the last element
|
||||
print((array[0] + array[-1]) / 2)
|
||||
|
||||
|
||||
arr = np.array([8, 18, 9, 16, 7, 1, 3])
|
||||
# Calculate an average of the first, fourth and last elements
|
||||
average = (arr[0] + arr[3] + arr[-1]) / 3
|
||||
print(average)
|
||||
18
array_manipulation.py
Normal file
18
array_manipulation.py
Normal file
@ -0,0 +1,18 @@
|
||||
import numpy as np
|
||||
"""
|
||||
This script demonstrates basic NumPy array manipulation:
|
||||
- Updates product prices by assigning a value of 20 to all prices greater than 10.
|
||||
- Modifies product ratings for two categories over three criteria by setting the last two criteria of the first category to 9.
|
||||
- Prints the updated prices and ratings arrays.
|
||||
"""
|
||||
# Product prices
|
||||
prices = np.array([15, 8, 22, 7, 12, 5])
|
||||
# Assign 20 to every price greater than 10
|
||||
prices[prices > 10] = 20
|
||||
|
||||
# Product ratings for two categories over three criteria
|
||||
ratings = np.array([[6, 8, 9], [7, 5, 10]])
|
||||
|
||||
ratings[0, 1:] = np.array([9, 9])
|
||||
print(prices)
|
||||
print(ratings)
|
||||
62
array_scalar_operations.py
Normal file
62
array_scalar_operations.py
Normal file
@ -0,0 +1,62 @@
|
||||
import numpy as np
|
||||
"""
|
||||
Demonstrates array and scalar operations using NumPy, including:
|
||||
- Creating 1D and 2D arrays.
|
||||
- Performing scalar addition and multiplication on arrays.
|
||||
- Element-wise addition, multiplication, and exponentiation between arrays of the same shape.
|
||||
- Broadcasting for element-wise operations between arrays of different shapes.
|
||||
- Simulating quarterly sales revenue data for two products over two years.
|
||||
- Calculating and rounding quarterly revenue growth percentages for each product.
|
||||
Prints intermediate and final results for illustration.
|
||||
"""
|
||||
|
||||
array = np.array([1, 2, 3, 4])
|
||||
print(f'Array 1D: {array}')
|
||||
# Creating a 2D array with 1 row
|
||||
array_2d = np.array([[1, 2, 3, 4]])
|
||||
|
||||
# Scalar addition
|
||||
result_add_scalar = array + 2 # Adding 2 to each element
|
||||
print(f'\nScalar addition: {result_add_scalar}')
|
||||
# Scalar multiplication
|
||||
result_mul_scalar = array * 3 # Multiplying each element by 3
|
||||
|
||||
arr1 = np.array([1, 2, 3, 4])
|
||||
arr2 = np.array([5, 6, 7, 8])
|
||||
print(f'\nArray 1: {arr1}')
|
||||
print(f'Array 2: {arr2}')
|
||||
# Element-wise addition
|
||||
result_add = arr1 + arr2 # Adding corresponding elements
|
||||
print(f'\nElement-wise addition: {result_add}')
|
||||
# Element-wise multiplication
|
||||
result_mul = arr1 * arr2 # Multiplying corresponding elements
|
||||
print(f'Element-wise multiplication: {result_mul}')
|
||||
# Element-wise exponentiation (raising to power)
|
||||
result_power = arr1 ** arr2 # Raising each element of arr1 to the power of corresponding element in arr2
|
||||
print(f'Element-wise exponentiation: {result_power}')
|
||||
|
||||
|
||||
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
|
||||
arr2 = np.array([5, 6, 7])
|
||||
print(f'\nArray 1:\n{arr1}')
|
||||
print(f'Array 2:\n{arr2}')
|
||||
# Element-wise addition
|
||||
result_add = arr1 + arr2 # Broadcasting arr2 to match the shape of arr1
|
||||
print(f'\nElement-wise addition: {result_add}')
|
||||
# Element-wise multiplication
|
||||
result_mul = arr1 * arr2 # Broadcasting arr2 to match the shape of arr1
|
||||
print(f'Element-wise multiplication: {result_mul}')
|
||||
# Element-wise exponentiation (raising to power)
|
||||
result_power = arr1 ** arr2 # Broadcasting arr2 to match the shape of arr1
|
||||
print(f'Element-wise exponentiation:\n{result_power}')
|
||||
|
||||
#Task:
|
||||
# Simulated quarterly sales revenue data for two products in 2021 and 2022
|
||||
sales_data_2021 = np.array([[350, 420, 380, 410], [270, 320, 290, 310]])
|
||||
sales_data_2022 = np.array([[360, 440, 390, 430], [280, 330, 300, 320]])
|
||||
# Calculate the quarterly revenue growth for each product in percents
|
||||
revenue_growth = (sales_data_2022 - sales_data_2021) / sales_data_2021 * 100
|
||||
# Rounding each of the elements to 2 decimal places
|
||||
revenue_growth = np.round(revenue_growth, 2)
|
||||
print(f'\nRevenue growth by quarter for each product:\n{revenue_growth}')
|
||||
|
||||
72
array_statistical_operations.py
Normal file
72
array_statistical_operations.py
Normal file
@ -0,0 +1,72 @@
|
||||
import numpy as np
|
||||
"""
|
||||
This script demonstrates various statistical operations on NumPy arrays, including mean, median, variance, and standard deviation calculations for both 1D and 2D arrays.
|
||||
Features:
|
||||
- Calculates mean and median for samples with odd and even numbers of elements.
|
||||
- Sorts arrays for display purposes.
|
||||
- Computes sample variance (using Bessel's correction) and standard deviation.
|
||||
- Performs mean calculations on 2D arrays, both flattened and along specific axes.
|
||||
- Simulates exam scores for two students and computes per-student mean, overall median, variance, and standard deviation.
|
||||
Dependencies:
|
||||
- numpy
|
||||
Usage:
|
||||
Run the script to see printed outputs of statistical calculations for various sample arrays and a simulated exam scores dataset.
|
||||
"""
|
||||
|
||||
sample = np.array([10, 25, 15, 30, 20, 10, 2])
|
||||
print(f'Original sample: {sample}, Odd # of elements:')
|
||||
# Calculating the mean
|
||||
sample_mean = np.mean(sample)
|
||||
print(f'Sorted sample: {np.sort(sample)}')
|
||||
# Calculating the median
|
||||
sample_median = np.median(sample)
|
||||
print(f'Mean: {sample_mean}, median: {sample_median}')
|
||||
|
||||
|
||||
sample = np.array([1, 2, 8, 10, 15, 20, 25, 30])
|
||||
print(f'\nOriginal sample: {sample}, Even # of elements:')
|
||||
sample_mean = np.mean(sample)
|
||||
sample_median = np.median(sample)
|
||||
# Sorting the sample
|
||||
print(f'Sorted sample: {np.sort(sample)}')
|
||||
print(f'Mean: {sample_mean}, median: {sample_median}')
|
||||
|
||||
|
||||
sample = np.array([10, 25, 15, 30, 20, 10, 2])
|
||||
print(f'\nOriginal sample: {sample}, Odd # of elements:')
|
||||
# Calculating the variance
|
||||
sample_variance = np.var(sample, ddof=1)
|
||||
# Calculating the standard deviation
|
||||
sample_std = np.std(sample)
|
||||
print(f'Variance: {sample_variance}, Standard Deviation: {sample_std}')
|
||||
|
||||
#Higher dimensional array calculations
|
||||
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
|
||||
print(f'\n2D Array:\n{array_2d}')
|
||||
# Calculating the mean in a flattened array
|
||||
print(f'Mean (flattened): {np.mean(array_2d)}')
|
||||
# Calculating the mean along axis 0
|
||||
print(f'Mean (axis 0): {np.mean(array_2d, axis=0)}')
|
||||
# Calculating the mean along axis 1
|
||||
print(f'Mean (axis 1): {np.mean(array_2d, axis=1)}')
|
||||
|
||||
# Task: Simulated test scores of 2 students for five different exams
|
||||
exam_scores = np.array([[85, 90, 78, 92, 88], [72, 89, 65, 78, 92]])
|
||||
print(f'\nExam Scores:\n{exam_scores}')
|
||||
|
||||
# Calculate the mean score for each student
|
||||
mean_scores = np.mean(exam_scores, axis=1)
|
||||
print(f'Mean score for each student: {mean_scores}')
|
||||
# Calculate the median score of all scores
|
||||
median_score = np.median(exam_scores)
|
||||
print(f'Median score of all exams: {median_score}')
|
||||
|
||||
# Calculate the median score of all scores
|
||||
median_score = np.median(exam_scores)
|
||||
print(f'Median score for all scores: {median_score}')
|
||||
# Calculate the variance of all scores
|
||||
scores_variance = np.var(exam_scores)
|
||||
print(f'Variance for all scores: {scores_variance}')
|
||||
# Calculate the standard deviation of all scores
|
||||
scores_std = np.std(exam_scores)
|
||||
print(f'Standard deviation for all scores: {scores_std}')
|
||||
44
assigning_values_to_indexed_elements.py
Normal file
44
assigning_values_to_indexed_elements.py
Normal file
@ -0,0 +1,44 @@
|
||||
import numpy as np
|
||||
|
||||
array_1d = np.array([1, 4, 6, 2])
|
||||
# Assigning 10 to the first element of array_1d
|
||||
array_1d[0] = 10
|
||||
print(array_1d)
|
||||
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
|
||||
|
||||
|
||||
# Assigning 8 to the element in the second row and column of array_2d
|
||||
array_2d[1, 1] = 8
|
||||
print(array_2d)
|
||||
|
||||
# Assigning a float value to an integer indexed element in a 1D array
|
||||
array_1d = np.array([1, 4, 6, 2])
|
||||
# Assigning 10.2 to the first element of array_1d
|
||||
array_1d[0] = 10.2
|
||||
print(array_1d)
|
||||
|
||||
# assigning values to indexed subarrays
|
||||
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
|
||||
# Assigning a subarray to the first row of array_2d
|
||||
array_2d[0] = np.array([7, 8, 9])
|
||||
print(array_2d)
|
||||
|
||||
# more examples of assigning values to indexed subarrays
|
||||
array_1d_1 = np.array([1, 4, 6, 2, 9])
|
||||
# Assigning an array to the slice of array_1d
|
||||
array_1d_1[1:-1] = np.array([3, 5, 7])
|
||||
print(array_1d_1)
|
||||
# Assigning a scalar to the slice of array_1d
|
||||
array_1d_1[1:-1] = 5
|
||||
print(array_1d_1)
|
||||
array_2d_1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
|
||||
# Assigning a 2D array to the slice of array_2d
|
||||
array_2d_1[1:3, 1:] = np.array([[20, 21], [40, 41]])
|
||||
print(array_2d_1)
|
||||
# Assigning a 1D array to the slice of array_2d
|
||||
array_2d_1[1:3, 1:] = [50, 51]
|
||||
print(array_2d_1)
|
||||
# Assigning a scalar to the slice of array_2d
|
||||
array_2d_1[1:3, 1:] = 30
|
||||
print(array_2d_1)
|
||||
|
||||
34
broadcasting_arrays.py
Normal file
34
broadcasting_arrays.py
Normal file
@ -0,0 +1,34 @@
|
||||
import numpy as np
|
||||
"""
|
||||
Demonstrates NumPy broadcasting rules with arrays of different shapes.
|
||||
Examples included:
|
||||
- Adding a (2, 3) array to a (1, 3) array using broadcasting.
|
||||
- Adding a (2, 3) array to a (3,) array using broadcasting.
|
||||
- Adding a scalar to a (2, 3) array using broadcasting.
|
||||
Prints the shapes of the arrays and the results of the element-wise additions.
|
||||
"""
|
||||
array_1 = np.array([[1, 2, 3], [4, 5, 6]])
|
||||
print(array_1.shape)
|
||||
# Creating a 2D array with 1 row
|
||||
array_2 = np.array([[11, 12, 13]])
|
||||
print(array_2.shape)
|
||||
# Broadcasting and element-wise addition
|
||||
result = array_1 + array_2
|
||||
print(result)
|
||||
|
||||
|
||||
array_1 = np.array([[1, 2, 3], [4, 5, 6]])
|
||||
print(array_1.shape)
|
||||
# Creating a 1D array
|
||||
array_2 = np.array([11, 12, 13])
|
||||
print(array_2.shape)
|
||||
# Broadcasting and element-wise addition
|
||||
result = array_1 + array_2
|
||||
print(result)
|
||||
|
||||
|
||||
array = np.array([[1, 2, 3], [4, 5, 6]])
|
||||
print(array.shape)
|
||||
# Broadcasting and element-wise addition
|
||||
result = array + 10
|
||||
print(result)
|
||||
25
class_Pet.py
Normal file
25
class_Pet.py
Normal file
@ -0,0 +1,25 @@
|
||||
class Pet:
|
||||
def __init__(self, name, species):
|
||||
self.name = name
|
||||
self.species = species
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.name} is a {self.species}."
|
||||
|
||||
def make_sound(self, sound):
|
||||
return f"{self.name} says {sound}."
|
||||
|
||||
def get_info(self):
|
||||
return f"Name: {self.name}, Species: {self.species}"
|
||||
|
||||
# Example usage:
|
||||
if __name__ == "__main__":
|
||||
my_pet = Pet("Buddy", "dog")
|
||||
print(my_pet) # Output: Buddy is a dog.
|
||||
print(my_pet.make_sound("Woof")) # Output: Buddy says Woof'
|
||||
print(my_pet.get_info()) # Output: Name: Buddy, Species: dog
|
||||
|
||||
my_other_pet = Pet("Max", "cat")
|
||||
print(my_other_pet) # Output: Max is a cat.
|
||||
print(my_other_pet.make_sound("Meow")) # Output: Max says Meow'
|
||||
print(my_other_pet.get_info()) # Output: Name: Max, Species: cat
|
||||
25
class_inheritance.py
Normal file
25
class_inheritance.py
Normal file
@ -0,0 +1,25 @@
|
||||
class MyClass:
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
|
||||
def display_value(self):
|
||||
print(f"Value: {self.value}")
|
||||
|
||||
my_class_instance = MyClass(10)
|
||||
my_class_instance.display_value()
|
||||
|
||||
|
||||
class MySubClass(MyClass):
|
||||
def __init__(self, value, extra):
|
||||
super().__init__(value)
|
||||
self.extra = extra
|
||||
|
||||
def display_extra(self):
|
||||
print(f"Extra: {self.extra}")
|
||||
|
||||
my_subclass_instance = MySubClass(20, "Hello")
|
||||
my_subclass_instance.display_value()
|
||||
my_subclass_instance.display_extra()
|
||||
|
||||
|
||||
|
||||
22
class_user_def_context_mgr.py
Normal file
22
class_user_def_context_mgr.py
Normal file
@ -0,0 +1,22 @@
|
||||
class ManagedFile: # A user-defined context manager for text files
|
||||
def __init__(self, filename):
|
||||
self.filename = filename
|
||||
self.file = None
|
||||
|
||||
def __enter__(self):
|
||||
self.file = open(self.filename, 'w')
|
||||
print('File opened and written')
|
||||
return self.file
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
if self.file:
|
||||
self.file.close()
|
||||
print('Exception:', exc_type, exc_value, traceback)
|
||||
|
||||
with ManagedFile('managed_file.txt') as file: # Using the user-defined context manager
|
||||
note = input("Write some text and Press Enter to continue...\n ")
|
||||
file.write(note)
|
||||
|
||||
print("Managed file has been written and closed automatically.")
|
||||
|
||||
# The file is automatically closed after the with block, even if an exception occurs.
|
||||
63
classes_fundamentals.py
Normal file
63
classes_fundamentals.py
Normal file
@ -0,0 +1,63 @@
|
||||
class Car():
|
||||
def __init__(self, make: str, model: str, year: int) -> None:
|
||||
self.make = make
|
||||
self.model = model
|
||||
self.year = year
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.year} {self.make} {self.model}"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Car(make={self.make}, model={self.model}, year={self.year})"
|
||||
|
||||
def __eq__(self, value):
|
||||
if not isinstance(value, Car):
|
||||
return NotImplemented
|
||||
return (self.make, self.model, self.year) == (value.make, value.model, value.year)
|
||||
|
||||
Honda: Car = Car("Honda", "Civic", 2020)
|
||||
Toyota: Car = Car("Toyota", "Corolla", 2021)
|
||||
|
||||
# Instance creation and string representation
|
||||
class ElectricCar(Car):
|
||||
def __init__(self, make: str, model: str, year: int, battery_size: int) -> None:
|
||||
super().__init__(make, model, year)
|
||||
self.battery_size = battery_size
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.year} {self.make} {self.model} with a {self.battery_size}-kWh battery"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"ElectricCar(make={self.make}, model={self.model}, year={self.year}, battery_size={self.battery_size})"
|
||||
|
||||
def __eq__(self, value):
|
||||
if not isinstance(value, ElectricCar):
|
||||
return NotImplemented
|
||||
return (self.make, self.model, self.year, self.battery_size) == (value.make, value.model, value.year, value.battery_size)
|
||||
|
||||
# use the classes
|
||||
Tesla: ElectricCar = ElectricCar("Tesla", "Model 3", 2022, 75)
|
||||
myHybridCar: ElectricCar = ElectricCar("Nissan", "Leaf", 2021, 40)
|
||||
print(myHybridCar == Tesla) # Output: False
|
||||
print(repr(Tesla)) # Output: ElectricCar(make=Tesla, model=Model 3, year=2022, battery_size=75)
|
||||
print(str(Tesla)) # Output: 2022 Tesla Model 3 with a 75-kWh battery
|
||||
print(Honda == Tesla) # Output: False
|
||||
print(Tesla == ElectricCar("Tesla", "Model 3", 2022, 75)) # Output: True
|
||||
print(Tesla == ElectricCar("Tesla", "Model S", 2022, 100)) # Output: False
|
||||
|
||||
#inheritance and method overriding
|
||||
class HybridCar(ElectricCar):
|
||||
def __init__(self, make: str, model: str, year: int, battery_size: int, fuel_type: str) -> None:
|
||||
super().__init__(make, model, year, battery_size)
|
||||
self.fuel_type = fuel_type
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.year} {self.make} {self.model} with a {self.battery_size}-kWh battery runs on {self.fuel_type}"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"HybridCar(make={self.make}, model={self.model}, year={self.year}, battery_size={self.battery_size}, fuel_type={self.fuel_type})"
|
||||
|
||||
myHybridCar: HybridCar = HybridCar("Toyota", "Prius", 2021, 1.3, "Gasoline")
|
||||
print(myHybridCar) # Output: 2021 Toyota Prius with a 1.3-kWh battery runs on Gasoline
|
||||
print(repr(myHybridCar)) # Output: HybridCar(make=Toyota, model=Prius, year=2021, battery_size=1.3, fuel_type=Gasoline)
|
||||
print(str(myHybridCar)) # Output: 2021 Toyota Prius with a 1.3-kWh battery and runs on Gasoline
|
||||
151
code_challenges/.snapshots/config.json
Normal file
151
code_challenges/.snapshots/config.json
Normal file
@ -0,0 +1,151 @@
|
||||
{
|
||||
"excluded_patterns": [
|
||||
".git",
|
||||
".gitignore",
|
||||
"gradle",
|
||||
"gradlew",
|
||||
"gradlew.*",
|
||||
"node_modules",
|
||||
".snapshots",
|
||||
".idea",
|
||||
".vscode",
|
||||
"*.log",
|
||||
"*.tmp",
|
||||
"target",
|
||||
"dist",
|
||||
"build",
|
||||
".DS_Store",
|
||||
"*.bak",
|
||||
"*.swp",
|
||||
"*.swo",
|
||||
"*.lock",
|
||||
"*.iml",
|
||||
"coverage",
|
||||
"*.min.js",
|
||||
"*.min.css",
|
||||
"__pycache__",
|
||||
".marketing",
|
||||
".env",
|
||||
".env.*",
|
||||
"*.jpg",
|
||||
"*.jpeg",
|
||||
"*.png",
|
||||
"*.gif",
|
||||
"*.bmp",
|
||||
"*.tiff",
|
||||
"*.ico",
|
||||
"*.svg",
|
||||
"*.webp",
|
||||
"*.psd",
|
||||
"*.ai",
|
||||
"*.eps",
|
||||
"*.indd",
|
||||
"*.raw",
|
||||
"*.cr2",
|
||||
"*.nef",
|
||||
"*.mp4",
|
||||
"*.mov",
|
||||
"*.avi",
|
||||
"*.wmv",
|
||||
"*.flv",
|
||||
"*.mkv",
|
||||
"*.webm",
|
||||
"*.m4v",
|
||||
"*.wfp",
|
||||
"*.prproj",
|
||||
"*.aep",
|
||||
"*.psb",
|
||||
"*.xcf",
|
||||
"*.sketch",
|
||||
"*.fig",
|
||||
"*.xd",
|
||||
"*.db",
|
||||
"*.sqlite",
|
||||
"*.sqlite3",
|
||||
"*.mdb",
|
||||
"*.accdb",
|
||||
"*.frm",
|
||||
"*.myd",
|
||||
"*.myi",
|
||||
"*.ibd",
|
||||
"*.dbf",
|
||||
"*.rdb",
|
||||
"*.aof",
|
||||
"*.pdb",
|
||||
"*.sdb",
|
||||
"*.s3db",
|
||||
"*.ddb",
|
||||
"*.db-shm",
|
||||
"*.db-wal",
|
||||
"*.sqlitedb",
|
||||
"*.sql.gz",
|
||||
"*.bak.sql",
|
||||
"dump.sql",
|
||||
"dump.rdb",
|
||||
"*.vsix",
|
||||
"*.jar",
|
||||
"*.war",
|
||||
"*.ear",
|
||||
"*.zip",
|
||||
"*.tar",
|
||||
"*.tar.gz",
|
||||
"*.tgz",
|
||||
"*.rar",
|
||||
"*.7z",
|
||||
"*.exe",
|
||||
"*.dll",
|
||||
"*.so",
|
||||
"*.dylib",
|
||||
"*.app",
|
||||
"*.dmg",
|
||||
"*.iso",
|
||||
"*.msi",
|
||||
"*.deb",
|
||||
"*.rpm",
|
||||
"*.apk",
|
||||
"*.aab",
|
||||
"*.ipa",
|
||||
"*.pkg",
|
||||
"*.nupkg",
|
||||
"*.snap",
|
||||
"*.whl",
|
||||
"*.gem",
|
||||
"*.pyc",
|
||||
"*.pyo",
|
||||
"*.pyd",
|
||||
"*.class",
|
||||
"*.o",
|
||||
"*.obj",
|
||||
"*.lib",
|
||||
"*.a",
|
||||
"*.map",
|
||||
".npmrc"
|
||||
],
|
||||
"default": {
|
||||
"default_prompt": "Enter your prompt here",
|
||||
"default_include_all_files": false,
|
||||
"default_include_entire_project_structure": true
|
||||
},
|
||||
"included_patterns": [
|
||||
"build.gradle",
|
||||
"settings.gradle",
|
||||
"gradle.properties",
|
||||
"pom.xml",
|
||||
"Makefile",
|
||||
"CMakeLists.txt",
|
||||
"package.json",
|
||||
"requirements.txt",
|
||||
"Pipfile",
|
||||
"Gemfile",
|
||||
"composer.json",
|
||||
".editorconfig",
|
||||
".eslintrc.json",
|
||||
".eslintrc.js",
|
||||
".prettierrc",
|
||||
".babelrc",
|
||||
".dockerignore",
|
||||
".gitattributes",
|
||||
".stylelintrc",
|
||||
".npmrc"
|
||||
]
|
||||
}
|
||||
11
code_challenges/.snapshots/readme.md
Normal file
11
code_challenges/.snapshots/readme.md
Normal file
@ -0,0 +1,11 @@
|
||||
# Snapshots Directory
|
||||
|
||||
This directory contains snapshots of your code for AI interactions. Each snapshot is a markdown file that includes relevant code context and project structure information.
|
||||
|
||||
## What's included in snapshots?
|
||||
- Selected code files and their contents
|
||||
- Project structure (if enabled)
|
||||
- Your prompt/question for the AI
|
||||
|
||||
## Configuration
|
||||
You can customize snapshot behavior in `config.json`.
|
||||
44
code_challenges/.snapshots/sponsors.md
Normal file
44
code_challenges/.snapshots/sponsors.md
Normal file
@ -0,0 +1,44 @@
|
||||
# Thank you for using Snapshots for AI
|
||||
|
||||
Thanks for using Snapshots for AI. We hope this tool has helped you solve a problem or two.
|
||||
|
||||
If you would like to support our work, please help us by considering the following offers and requests:
|
||||
|
||||
## Ways to Support
|
||||
|
||||
### Join the GBTI Network!!! 🙏🙏🙏
|
||||
The GBTI Network is a community of developers who are passionate about open source and community-driven development. Members enjoy access to exclussive tools, resources, a private MineCraft server, a listing in our members directory, co-op opportunities and more.
|
||||
|
||||
- Support our work by becoming a [GBTI Network member](https://gbti.network/membership/).
|
||||
|
||||
### Try out BugHerd 🐛
|
||||
BugHerd is a visual feedback and bug-tracking tool designed to streamline website development by enabling users to pin feedback directly onto web pages. This approach facilitates clear communication among clients, designers, developers, and project managers.
|
||||
|
||||
- Start your free trial with [BugHerd](https://partners.bugherd.com/55z6c8az8rvr) today.
|
||||
|
||||
### Hire Developers from Codeable 👥
|
||||
Codeable connects you with top-tier professionals skilled in frameworks and technologies such as Laravel, React, Django, Node, Vue.js, Angular, Ruby on Rails, and Node.js. Don't let the WordPress focus discourage you. Codeable experts do it all.
|
||||
|
||||
- Visit [Codeable](https://www.codeable.io/developers/?ref=z8h3e) to hire your next team member.
|
||||
|
||||
### Lead positive reviews on our marketplace listing ⭐⭐⭐⭐⭐
|
||||
- Rate us on [VSCode marketplace](https://marketplace.visualstudio.com/items?itemName=GBTI.snapshots-for-ai)
|
||||
- Review us on [Cursor marketplace](https://open-vsx.org/extension/GBTI/snapshots-for-ai)
|
||||
|
||||
### Star Our GitHub Repository ⭐
|
||||
- Star and watch our [repository](https://github.com/gbti-network/vscode-snapshots-for-ai)
|
||||
|
||||
### 📡 Stay Connected
|
||||
Follow us on your favorite platforms for updates, news, and community discussions:
|
||||
- **[Twitter/X](https://twitter.com/gbti_network)**
|
||||
- **[GitHub](https://github.com/gbti-network)**
|
||||
- **[YouTube](https://www.youtube.com/channel/UCh4FjB6r4oWQW-QFiwqv-UA)**
|
||||
- **[Dev.to](https://dev.to/gbti)**
|
||||
- **[Daily.dev](https://dly.to/zfCriM6JfRF)**
|
||||
- **[Hashnode](https://gbti.hashnode.dev/)**
|
||||
- **[Discord Community](https://gbti.network)**
|
||||
- **[Reddit Community](https://www.reddit.com/r/GBTI_network)**
|
||||
|
||||
---
|
||||
|
||||
Thank you for supporting open source software! 🙏
|
||||
34
code_challenges/CodeChallenge_02(Medium).py
Normal file
34
code_challenges/CodeChallenge_02(Medium).py
Normal file
@ -0,0 +1,34 @@
|
||||
'''
|
||||
The ternary numeric system is commonly used in Codeland, and to represent ternary numbers, the Tick alphabet is employed. In this system, the digit 0
|
||||
is represented by ., 1 by -., and 2 by --. Your task is to decode a Tick-encoded string and determine the corresponding ternary number.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
.-.--
|
||||
Output:
|
||||
012
|
||||
'''
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, code:str)->str:
|
||||
tick_map = {'.': '0', '-.': '1', '--': '2'}
|
||||
i = 0
|
||||
result = ''
|
||||
while i < len(code):
|
||||
if code[i] == '.':
|
||||
result += '0'
|
||||
i += 1
|
||||
elif code[i:i+2] == '-.':
|
||||
result += '1'
|
||||
i += 2
|
||||
elif code[i:i+2] == '--':
|
||||
result += '2'
|
||||
i += 2
|
||||
return result
|
||||
|
||||
# Usage
|
||||
s = Solution()
|
||||
print(s.solve("-.--.-.--"))
|
||||
|
||||
|
||||
|
||||
12
code_challenges/CodeChallenge_1.py
Normal file
12
code_challenges/CodeChallenge_1.py
Normal file
@ -0,0 +1,12 @@
|
||||
class Solution(object):
|
||||
def solve(self,a:int,b:int,c:int)->int:
|
||||
print(f"a: {a}, b: {b}, c: {c}")
|
||||
v1 = a + b * c
|
||||
v2 = a * (b + c)
|
||||
v3 = a * b *c
|
||||
v4 = (a + b) * c
|
||||
s_max = max(v1, v2, v3, v4)
|
||||
return s_max
|
||||
|
||||
s = Solution()
|
||||
print (s.solve(2, 7, 6))
|
||||
23
code_challenges/CodeChallenge_10.py
Normal file
23
code_challenges/CodeChallenge_10.py
Normal file
@ -0,0 +1,23 @@
|
||||
'''
|
||||
Given two integers x and y, return a list of integers: the first being the minimum of x and y, and the second being the maximum of x and y.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
x = 5; y = 3
|
||||
Output:
|
||||
[3, 5]
|
||||
'''
|
||||
from typing import List
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, x:int, y:int) -> List[int]:
|
||||
print(f"x: {x}, y: {y}")
|
||||
result = []
|
||||
result.append(min(x, y))
|
||||
result.append(max(x, y))
|
||||
return result
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(5, 3)) # Output: [3, 5]
|
||||
print(s.solve(10, 20)) # Output: [10, 20]
|
||||
print(s.solve(19, -3)) # Output: [-3, 19]
|
||||
30
code_challenges/CodeChallenge_11.py
Normal file
30
code_challenges/CodeChallenge_11.py
Normal file
@ -0,0 +1,30 @@
|
||||
'''
|
||||
Bill keeps his most treasured savings in a home safe with a combination lock. The combination lock is
|
||||
represented by n rotating disks with digits from 0 to 9 written on them. Bill has to turn some disks so
|
||||
that the combination of digits on the disks forms a secret combination. In one move, he can rotate one
|
||||
disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and
|
||||
vice versa. What minimum number of actions does he need for that?
|
||||
|
||||
Given an integer original and an integer of final code combination target, return an integer of the minimum
|
||||
number of moves Bill needs to open the lock
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
original = 82195; target = 64723
|
||||
Output:
|
||||
13
|
||||
'''
|
||||
class Solution(object):
|
||||
def solve(self, original:int, target:int) -> int:
|
||||
print(f"original: {original}, target: {target}")
|
||||
original_str = f"{original}"
|
||||
target_str = f"{target}"
|
||||
turns = 0
|
||||
for i in range(len(original_str)):
|
||||
diff = abs(int(original_str[i]) - int(target_str[i]))
|
||||
turns += min(diff, 10 - diff)
|
||||
return turns
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(82195, 64723))
|
||||
print(s.solve(12345, 98765)) # Output: 1
|
||||
41
code_challenges/CodeChallenge_12.py
Normal file
41
code_challenges/CodeChallenge_12.py
Normal file
@ -0,0 +1,41 @@
|
||||
'''
|
||||
Given an integer n, determine how many integers x (where 1 ≤ x ≤ n) are interesting. An integer x is considered interesting if the sum of its digits decreases when incremented by 1, i.e., S(x+1) < S(x), where S(x) represents the sum of the digits of x in the decimal system.
|
||||
|
||||
Your task is to count how many such interesting numbers exist within the given range.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
9
|
||||
Output:
|
||||
1
|
||||
Example 2
|
||||
Input:
|
||||
19
|
||||
Output:
|
||||
2
|
||||
Example 3
|
||||
Input:
|
||||
1
|
||||
Output:
|
||||
0
|
||||
'''
|
||||
class Solution(object):
|
||||
def solve(self, n:int) -> int:
|
||||
print(f"n: {n}")
|
||||
interesting_count = 0
|
||||
for x in range(1, n + 1):
|
||||
if self.is_interesting(x):
|
||||
interesting_count += 1
|
||||
return interesting_count
|
||||
|
||||
def is_interesting(self, x:int) -> bool:
|
||||
return self.digit_sum(x + 1) < self.digit_sum(x)
|
||||
|
||||
def digit_sum(self, x:int) -> int:
|
||||
return sum(int(digit) for digit in str(x))
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(9)) # Output: 1
|
||||
print(s.solve(19)) # Output: 2
|
||||
print(s.solve(1)) # Output: 0
|
||||
print(s.solve(160)) # Output: 9
|
||||
25
code_challenges/CodeChallenge_13.py
Normal file
25
code_challenges/CodeChallenge_13.py
Normal file
@ -0,0 +1,25 @@
|
||||
'''
|
||||
Jane, a budding mathematician and a second-grade student, is learning how to perform addition. Her teacher wrote down a sum of several numbers on the board, and the
|
||||
students were asked to calculate the total. To keep things simple, the sum only includes the numbers 1, 2, and 3. However, Jane is still getting the hang of addition,
|
||||
so she can only calculate the sum if the numbers are arranged in non-decreasing order (i.e., each number is greater than or equal to the one before it). For example, she cannot compute a sum like 2+1+3+2, but she can handle 1+2+2+3.
|
||||
Your task is to rearrange the numbers in the given sum so that Sophia can compute it.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
1+3+2+1
|
||||
Output:
|
||||
1+1+2+3
|
||||
'''
|
||||
class Solution(object):
|
||||
def solve(self, s:str) -> str:
|
||||
print(f"s: {s}")
|
||||
# Write your code here.
|
||||
input_numbers = s.split('+')
|
||||
print(f"input_numbers: {input_numbers}")
|
||||
input_numbers = [int(num) for num in input_numbers]
|
||||
input_numbers.sort()
|
||||
return '+'.join(map(str, input_numbers)) # Join them back with '+' to form the output string
|
||||
|
||||
s = Solution()
|
||||
print(s.solve("1+3+2+1"))
|
||||
print(s.solve("5+3+11+5+7")) # Output: "1+1+2+3"
|
||||
28
code_challenges/CodeChallenge_14.py
Normal file
28
code_challenges/CodeChallenge_14.py
Normal file
@ -0,0 +1,28 @@
|
||||
'''
|
||||
Given three digits a, b, c, where two of them are equal and one is different, return the value that occurs exactly once.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
a = 1; b = 2; c = 2
|
||||
Output:
|
||||
1
|
||||
Example 2
|
||||
Input:
|
||||
a = 4; b = 3; c = 4
|
||||
Output:
|
||||
3
|
||||
'''
|
||||
|
||||
class Solution(object):
|
||||
def solve(self,a:int, b:int, c:int) -> int:
|
||||
print(f"a: {a}, b: {b}, c: {c}")
|
||||
if a != b and a != c:
|
||||
return a
|
||||
elif b != a and b != c:
|
||||
return b
|
||||
else:
|
||||
return c
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(1, 2, 2))
|
||||
print(s.solve(4, 3, 4))
|
||||
26
code_challenges/CodeChallenge_15.py
Normal file
26
code_challenges/CodeChallenge_15.py
Normal file
@ -0,0 +1,26 @@
|
||||
'''
|
||||
Given an integer a and an integer b, return the smallest integer n such that if a is tripled n times and b is doubled n times, a exceeds b.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
a = 17; b = 100
|
||||
Output:
|
||||
5
|
||||
'''
|
||||
|
||||
|
||||
class Solution:
|
||||
def solve(self, a:int, b:int) -> int:
|
||||
print(f"a: {a}, b: {b}")
|
||||
triple = a
|
||||
double = b
|
||||
n = 0
|
||||
while triple < double:
|
||||
n += 1
|
||||
triple *= 3
|
||||
double *= 2
|
||||
return n
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(17, 100))
|
||||
print(s.solve(4, 16806))
|
||||
26
code_challenges/CodeChallenge_16.py
Normal file
26
code_challenges/CodeChallenge_16.py
Normal file
@ -0,0 +1,26 @@
|
||||
'''
|
||||
Given an integer n, return the last two digits of the number 5 raised to the power of n. Note that n can be rather large, so direct computation may not be feasible. The task requires an efficient approach to solve the problem.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
2
|
||||
Output:
|
||||
25
|
||||
'''
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, n:int) -> int:
|
||||
print(f"n: {n}")
|
||||
i = 1
|
||||
pow = 1
|
||||
for i in range (n):
|
||||
pow *= 5
|
||||
pow_str = str(pow)
|
||||
result = int(pow_str[-2:])
|
||||
return result
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(4)) # Output: 25
|
||||
print(s.solve(100)) # Output: 25
|
||||
print(s.solve(1000)) # Output: 25
|
||||
print(s.solve(89)) # Output: 25
|
||||
40
code_challenges/CodeChallenge_17.py
Normal file
40
code_challenges/CodeChallenge_17.py
Normal file
@ -0,0 +1,40 @@
|
||||
'''
|
||||
The price of one tomato at grocery-store is a dollars, but there is a promotion where you can buy two tomatoes for b dollars. Bob needs to buy exactly n tomatoes.
|
||||
When buying two tomatoes, he can choose to buy them at the regular price or at the promotion price. What is the minimum amount of dollars Bob should spend to buy
|
||||
n tomatoes?
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
n = 2; a = 5; b = 9
|
||||
Output:
|
||||
9
|
||||
Example 2
|
||||
Input:
|
||||
n = 3; a = 5; b = 11
|
||||
Output:
|
||||
15
|
||||
'''
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, n:int, a:int, b:int) -> int:
|
||||
print(f"n: {n}, a: {a}, b: {b}")
|
||||
total = 0
|
||||
if n == 1:
|
||||
total = a
|
||||
else:
|
||||
if a*2 > b:
|
||||
if n % 2 == 0: # Buy at lower price
|
||||
total = int((n/2)*b)
|
||||
else:
|
||||
total = int(((n-1)/2)*b + a)
|
||||
elif b > a*2:
|
||||
total = n*a
|
||||
elif b == 2*a:
|
||||
total = n*a
|
||||
return total
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(2, 5, 9)) # Output: 9
|
||||
print(s.solve(3, 5, 11)) # Output: 15
|
||||
print(s.solve(1, 5, 12))
|
||||
print(s.solve(9, 7, 13))
|
||||
36
code_challenges/CodeChallenge_18.py
Normal file
36
code_challenges/CodeChallenge_18.py
Normal file
@ -0,0 +1,36 @@
|
||||
'''
|
||||
One day three best friends Bill, Bob, and Jane decided to form a team and take part in programming contests. During these contests, participants are typically
|
||||
given several problems to solve. Before the competition began, the friends agreed on a rule:
|
||||
They would only attempt to solve a problem if at least two of them were confident in their solution. Otherwise, they would skip that problem. For each problem, it is
|
||||
known which of the friends are sure about the solution. Your task is to help the friends determine the number of problems they will attempt to solve based on their rule.
|
||||
|
||||
Given a list of lists of triples of integers 1 or 0. If the first number in the line equals 1, then Bill is sure about the problem's solution, otherwise he isn't sure.
|
||||
The second number shows Bob’s view on the solution, the third number shows Jane’s view. Return an integer - the number of problems the friends will implement on the
|
||||
contest.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
[[ 1, 0, 1 ], [1, 1, 1], [0, 0, 0]]
|
||||
Output:
|
||||
2
|
||||
Example 2
|
||||
Input:
|
||||
[[0, 1, 1], [0, 0, 1], [1, 1, 1], [1, 1, 0]]
|
||||
Output:
|
||||
3
|
||||
'''
|
||||
from typing import List
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, problems: List[List[int]]) -> int:
|
||||
print(f"problems: {problems}")
|
||||
count = 0
|
||||
for problem in problems:
|
||||
if sum(problem) >= 2:
|
||||
count += 1
|
||||
return count
|
||||
|
||||
s = Solution()
|
||||
# Example usage
|
||||
print(s.solve([[1, 0, 1], [1, 1, 1], [0, 0, 0]])) # Output: 2
|
||||
print(s.solve([[0, 1, 1], [0, 0, 1], [1, 1, 1], [1, 1, 0]])) # Output: 3
|
||||
34
code_challenges/CodeChallenge_19.py
Normal file
34
code_challenges/CodeChallenge_19.py
Normal file
@ -0,0 +1,34 @@
|
||||
'''
|
||||
Bob has three sisters: Ann, Bella, and Caroline. They're collecting coins. Currently, Ann has a coins, Bella has b coins and Caroline has c coins. Recently Bob has
|
||||
returned from the trip around the world and brought n coins. He wants to distribute all these n coins between his sisters in such a way that the number of coins Ann
|
||||
has is equal to the number of coins Bella has and is equal to the number of coins Caroline has. In other words, if Bob gives A coins to Ann, B coins to Bella and C
|
||||
coins to Caroline A+B+C=n, then a+A=b+B=c+C
|
||||
|
||||
Note that A, B or C (the number of coins Bob gives to Ann, Bella and Caroline correspondingly) can be 0. Help Bob to find out if it is possible to distribute all n
|
||||
coins between sisters in a way described above.
|
||||
|
||||
Given an integers a - the number of coins Ann has , b - number of coins Bella has, c - number of coins Caroline has and n - the number of coins Bob has.
|
||||
Return YES if Bob can distribute all n coins between his sisters and NO in the opposite case.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
a = 3, b = 798, c = 437, n = 1804
|
||||
Output:
|
||||
YES
|
||||
'''
|
||||
|
||||
class Solution(object):
|
||||
def solve(self,a:int, b:int, c:int, n:int) -> str:
|
||||
print(f"a: {a}, b: {b}, c: {c}, n: {n}")
|
||||
total = a + b + c + n
|
||||
if total % 3 == 0:
|
||||
target = total // 3
|
||||
if target >= a and target >= b and target >= c:
|
||||
return "YES"
|
||||
return "NO"
|
||||
|
||||
s = Solution()
|
||||
# Example usage
|
||||
print(s.solve(3, 798, 437, 1804)) # Output: YES
|
||||
print(s.solve(1, 2, 3, 4)) # Output: NO
|
||||
|
||||
11
code_challenges/CodeChallenge_2.py
Normal file
11
code_challenges/CodeChallenge_2.py
Normal file
@ -0,0 +1,11 @@
|
||||
class Solution(object):
|
||||
def solve(self, n:int) -> str:
|
||||
print(f"n: {n}")
|
||||
s = list(str(n))
|
||||
for i in range(len(s)):
|
||||
if s[i] != '4' and s[i] != '7':
|
||||
return "NO"
|
||||
return "YES"
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(47))
|
||||
27
code_challenges/CodeChallenge_20.py
Normal file
27
code_challenges/CodeChallenge_20.py
Normal file
@ -0,0 +1,27 @@
|
||||
'''
|
||||
Given an array of operations ++x, x++, --x. x-- and an integer target, return an initial integer, so that the final value is the target value.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
["x++", "--x", "--x"], 12
|
||||
Output:
|
||||
13
|
||||
'''
|
||||
|
||||
from typing import List
|
||||
|
||||
class Solution(object):
|
||||
def solve(self,ops:List[str], target:int) -> int:
|
||||
print(f"ops: {ops}, target: {target}")
|
||||
current = 0
|
||||
for op in ops:
|
||||
if op == "++x" or op == "x++":
|
||||
current += 1
|
||||
else:
|
||||
current -= 1
|
||||
return target - current
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(["x++", "--x", "--x"], 12)) # Output: 13
|
||||
print(s.solve(["x++", "x++", "x--"], 2)) # Output: 1
|
||||
print(s.solve(["--x", "x++", "x++"], 3))
|
||||
27
code_challenges/CodeChallenge_21.py
Normal file
27
code_challenges/CodeChallenge_21.py
Normal file
@ -0,0 +1,27 @@
|
||||
'''
|
||||
Bill has found a set. The set consists of small English letters. Bill carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Bill would forget writing some letter and write it again. Help Bill to count the total number of distinct letters in his set.
|
||||
|
||||
Given a string of set format set_str, return an integer of total number of distinct letters from set.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
{b, a, b, a}
|
||||
Output:
|
||||
2
|
||||
'''
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, set_str:str) -> int:
|
||||
print(f"set_str: {set_str}")
|
||||
# Remove the curly braces and split the string by comma
|
||||
elements = set_str[1:-1].split(", ")
|
||||
# Use a set to find distinct elements
|
||||
distinct_elements = set(elements)
|
||||
return len(distinct_elements)
|
||||
|
||||
s = Solution()
|
||||
print(s.solve("{b, a, b, a}")) # Output: 2
|
||||
print(s.solve("{c, d, e, c, d}")) # Output: 3
|
||||
print(s.solve("{x, y, z}")) # Output: 3
|
||||
print (s.solve("{a, b, c, d, e, f, g, h, i, j}")) # Output: 10
|
||||
print(s.solve("{a, a, a, a}")) # Output: 1
|
||||
27
code_challenges/CodeChallenge_22.py
Normal file
27
code_challenges/CodeChallenge_22.py
Normal file
@ -0,0 +1,27 @@
|
||||
'''
|
||||
Given a list of integers and a threshold integer, return a sum of numbers, where each number contributes 2 if it exceeds or equals
|
||||
the threshold and 1 otherwise.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
[2, 8, 25, 18, 99, 11, 17, 16], 17
|
||||
Output:
|
||||
12
|
||||
'''
|
||||
from typing import List
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, nums:List[int], threshold:int) -> int:
|
||||
print(f"nums: {nums}, threshold: {threshold}")
|
||||
total = 0
|
||||
for num in nums:
|
||||
if num >= threshold:
|
||||
total += 2
|
||||
else:
|
||||
total += 1
|
||||
return total
|
||||
|
||||
s = Solution()
|
||||
print(s.solve([2, 8, 25, 18, 99, 11, 17, 16], 17)) # Output: 12
|
||||
print(s.solve([1, 2, 3, 4, 5], 3)) # Output: 8
|
||||
print(s.solve([10, 20, 30], 15)) # Output:
|
||||
34
code_challenges/CodeChallenge_23.py
Normal file
34
code_challenges/CodeChallenge_23.py
Normal file
@ -0,0 +1,34 @@
|
||||
'''
|
||||
Given an integers a and b, return a count of numbers between a and b (inclusive) that have no repeated digits.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
a = 100; b = 1000
|
||||
Output:
|
||||
648
|
||||
'''
|
||||
|
||||
class Solution(object):
|
||||
def solve(self,a:int, b:int) ->int:
|
||||
print(f"a: {a}, b: {b}")
|
||||
count = 0
|
||||
for num in range(a, b+1): # Iterate through each number in the range
|
||||
if self.has_unique_digits(num):
|
||||
count += 1 # increment count if the number has unique digits
|
||||
return count
|
||||
|
||||
def has_unique_digits(self, num:int) -> bool:
|
||||
digits = set()
|
||||
while num > 0:
|
||||
digit = num % 10 # Looks at the last digit of num
|
||||
if digit in digits: # If the digit is already in the set, return false
|
||||
return False
|
||||
digits.add(digit) # Add the digit to the set of digits
|
||||
num //= 10 # Remove the last digit of num
|
||||
return True
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(100, 1000)) # Output: 648
|
||||
print(s.solve(1000, 10000)) # Output: 5520
|
||||
print(s.solve(10001, 100000)) # Output: 45360
|
||||
print(s.solve(500, 600)) # Output: 403200
|
||||
27
code_challenges/CodeChallenge_24.py
Normal file
27
code_challenges/CodeChallenge_24.py
Normal file
@ -0,0 +1,27 @@
|
||||
'''
|
||||
Given three integers a, b, and c, return + if the equation a + b = c is true, and - if the equation a - b = c is true
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
a = 1; b = 2; c = 3
|
||||
Output:
|
||||
+
|
||||
Example 2
|
||||
Input:
|
||||
a = 2; b = 9; c = -7
|
||||
Output:
|
||||
-
|
||||
'''
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, a:int, b:int, c:int) -> str:
|
||||
if a + b == c:
|
||||
return "+"
|
||||
elif a - b == c:
|
||||
return "-"
|
||||
else:
|
||||
return "0"
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(1, 2, 3)) # Output: "+"
|
||||
print(s.solve(2, 9, -7)) # Output: "-"
|
||||
19
code_challenges/CodeChallenge_25.py
Normal file
19
code_challenges/CodeChallenge_25.py
Normal file
@ -0,0 +1,19 @@
|
||||
'''
|
||||
Given an array of integers nums and an integer k, return an amount of integers in array are larger than the k.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
[9, 10, 2, 3, 55, 76, 12, 6]; k = 7
|
||||
Output:
|
||||
5
|
||||
'''
|
||||
class Solution(object):
|
||||
def solve(self, nums: list[int], k: int) -> int:
|
||||
count = 0
|
||||
for num in nums:
|
||||
if num > k:
|
||||
count += 1
|
||||
return count
|
||||
|
||||
s = Solution()
|
||||
print(s.solve([9, 10, 2, 3, 55, 76, 12, 6], 7)) # Output: 5
|
||||
33
code_challenges/CodeChallenge_26.py
Normal file
33
code_challenges/CodeChallenge_26.py
Normal file
@ -0,0 +1,33 @@
|
||||
'''
|
||||
Bob has recently started commuting by bus. We know that a one bus ride ticket costs a dollars. Besides, Bob found out that he can buy a special ticket for m rides,
|
||||
also he can buy it several times. It costs b dollars. Bob will need to use bus n times. Help Bob to calculate what is the minimum sum of money he will have to spend
|
||||
to make n rides?
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
n = 10; m = 3; a = 1; b = 2
|
||||
Output:
|
||||
7
|
||||
Example 2
|
||||
Input:
|
||||
n = 10; m = 2; a = 1; b = 1
|
||||
Output:
|
||||
5
|
||||
'''
|
||||
import math
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, n: int, m: int, a: int, b: int) -> int: # n: number of rides, m: rides in special ticket, a: cost of single ticket, b: cost of special ticket
|
||||
# Calculate the cost using only single tickets
|
||||
cost_single = n * a
|
||||
# Calculate the cost using special tickets
|
||||
cost_special = (n // m) * b + (n % m) * a # Full special tickets + remaining rides with single tickets
|
||||
|
||||
cost_packs_only = math.ceil(n / m) * b # If we only use special tickets, we need to round up the number of packs
|
||||
# Return the minimum of the two costs
|
||||
return min(cost_single, cost_special, cost_packs_only)
|
||||
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(10, 3, 5, 1)) # Output: 4
|
||||
print(s.solve(10, 2, 1, 1)) # Output: 5
|
||||
25
code_challenges/CodeChallenge_27.py
Normal file
25
code_challenges/CodeChallenge_27.py
Normal file
@ -0,0 +1,25 @@
|
||||
'''
|
||||
Bill decided to visit his friend. It turned out that the Bill's house is located at point 0 and his friend's house is located at point x (x > 0) of the
|
||||
coordinate line. In one step Bill can move 1, 2, 3, 4 or 5 positions forward.
|
||||
|
||||
Given integer x, return the minimum number of steps Bill needs to make in order to get to his friend's house.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
12
|
||||
Output:
|
||||
3
|
||||
Example 2
|
||||
Input:
|
||||
41
|
||||
Output:
|
||||
9
|
||||
'''
|
||||
class Solution(object):
|
||||
def solve(self, x: int) -> int:
|
||||
return (x + 4) // 5 # Round up division by 5
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(12)) # Output: 3
|
||||
print(s.solve(41)) # Output: 9
|
||||
print(s.solve(999999)) # Output: 200000
|
||||
41
code_challenges/CodeChallenge_28.py
Normal file
41
code_challenges/CodeChallenge_28.py
Normal file
@ -0,0 +1,41 @@
|
||||
'''
|
||||
Liam enjoys playing chess, and so does his friend Noah. One day, they played n games in a row. For each game, it is known who the winner was—Liam or Noah.
|
||||
None of the games ended in a tie.
|
||||
|
||||
Now Liam is curious to know who won more games - him or Noah. Can you help him find out?
|
||||
Given a string s, consisting of uppercase English letters L and N — the outcome of each of the games. The i-th character of the string is equal to L if the Liam
|
||||
won the i-th game and N if Noah won the i-th game, return a string with Noah If Noah won more games than Liam and Liam in the opposite case. If Noah and Liam won
|
||||
the same number of games, return Friendship
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
LNLLLL
|
||||
Output:
|
||||
Liam
|
||||
Example 2
|
||||
Input:
|
||||
NLNLNL
|
||||
Output:
|
||||
Friendship
|
||||
Example 3
|
||||
Input:
|
||||
NNLNLN
|
||||
Output:
|
||||
Noah
|
||||
'''
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, s:str) -> str:
|
||||
liam_wins = s.count('L')
|
||||
noah_wins = s.count('N')
|
||||
if liam_wins > noah_wins:
|
||||
return "Liam"
|
||||
elif noah_wins > liam_wins:
|
||||
return "Noah"
|
||||
else:
|
||||
return "Friendship"
|
||||
|
||||
s = Solution()
|
||||
print(s.solve("LNLLLL")) # Output: Liam
|
||||
print(s.solve("NLNLNL")) # Output: Friendship
|
||||
print(s.solve("NNLNLN")) # Output: Noah
|
||||
58
code_challenges/CodeChallenge_29.py
Normal file
58
code_challenges/CodeChallenge_29.py
Normal file
@ -0,0 +1,58 @@
|
||||
'''
|
||||
Bob likes to play his game on paper. He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to
|
||||
do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j]
|
||||
(that is i ≤ k ≤ j). Flip the value of ak means to apply operation ak = 1 - ak.
|
||||
|
||||
The goal of the game is that after exactly one move to obtain the maximum number of ones.
|
||||
|
||||
Given a list of 0 or 1. Return the maximal number of 1s that can be obtained after exactly one move.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
[1, 0, 0, 0, 1, 0, 0, 0]
|
||||
Output:
|
||||
7
|
||||
'''
|
||||
|
||||
from typing import List
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, l:List[int]) -> int:
|
||||
current_ones = sum(l)
|
||||
max_ones = 0
|
||||
for i in range(len(l)):
|
||||
for j in range(i, len(l)):
|
||||
flipped = l[i:j+1] # Flipping the segment from i to j
|
||||
if flipped.count(1) == len(flipped): # If all are 1
|
||||
new_ones = current_ones - len(flipped) # Flipping all 1s to 0s
|
||||
new_ones = current_ones - sum(flipped) + len(flipped) - sum(flipped) # Flipping 0s to 1s and 1s to 0s
|
||||
max_ones = max(max_ones, new_ones)
|
||||
return max_ones
|
||||
|
||||
s = Solution()
|
||||
print(s.solve([1, 0, 0, 0, 1, 0, 0, 0])) # Output: 7
|
||||
print(s.solve([1, 1, 1, 1, 1, 1, 1, 1])) # Output: 8
|
||||
print(s.solve([0, 0, 0, 0, 0, 0, 0, 0])) # Output: 8
|
||||
|
||||
'''
|
||||
def solve_optimized(self, l: List[int]) -> int:
|
||||
n = len(l)
|
||||
current_ones = sum(l)
|
||||
max_diff = float('-inf')
|
||||
current_diff = 0
|
||||
|
||||
for i in range(n):
|
||||
if l[i] == 1:
|
||||
current_diff -= 1
|
||||
else:
|
||||
current_diff += 1
|
||||
|
||||
if current_diff < 0:
|
||||
current_diff = 0
|
||||
|
||||
max_diff = max(max_diff, current_diff)
|
||||
|
||||
return current_ones + max_diff if max_diff != float('-inf') else current_ones
|
||||
|
||||
'''
|
||||
|
||||
28
code_challenges/CodeChallenge_3.py
Normal file
28
code_challenges/CodeChallenge_3.py
Normal file
@ -0,0 +1,28 @@
|
||||
'''
|
||||
Given an array of three arrays of triples of integers, return the missing triple of integers to make them all add up to 0 coordinatewise
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
[[1, 2, 3], [9, -2, 8], [17, 2, 50]]
|
||||
Output:
|
||||
[-27, -2, -61]
|
||||
|
||||
'''
|
||||
from typing import List
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, nums:List[List[int]]) -> List[int]:
|
||||
print(f"nums: {nums}")
|
||||
# Initialize the result triple
|
||||
result = [0, 0, 0]
|
||||
# Iterate through each array
|
||||
for arr in nums:
|
||||
# Add the values coordinatewise
|
||||
for i in range(3):
|
||||
result[i] += arr[i]
|
||||
# The missing triple is the negative of twice the result
|
||||
return [-2*x for x in result]
|
||||
|
||||
arrays = [[1,-2, 3], [9, -2, 8], [27, 2, 50]]
|
||||
solution = Solution()
|
||||
print(solution.solve(arrays))
|
||||
34
code_challenges/CodeChallenge_30.py
Normal file
34
code_challenges/CodeChallenge_30.py
Normal file
@ -0,0 +1,34 @@
|
||||
'''
|
||||
Given a binary array consisting of only 0s and 1s, return the length of the longest segment of consecutive 0s (also referred to as a blank space) in the array.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
[1, 0, 0, 1, 0]
|
||||
Output:
|
||||
2
|
||||
Example 2
|
||||
Input:
|
||||
[1, 1, 1]
|
||||
Output:
|
||||
0
|
||||
'''
|
||||
|
||||
from typing import List
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, a:List[int]) -> int:
|
||||
max_length = 0
|
||||
current_length = 0
|
||||
for num in a:
|
||||
if num == 0:
|
||||
current_length += 1
|
||||
max_length = max(max_length, current_length)
|
||||
else:
|
||||
current_length = 0
|
||||
return max_length
|
||||
|
||||
s = Solution()
|
||||
print(s.solve([1, 0, 0, 1, 0]))
|
||||
# Output: 2
|
||||
print(s.solve([1, 1, 1]))
|
||||
# Output: 0
|
||||
34
code_challenges/CodeChallenge_31.py
Normal file
34
code_challenges/CodeChallenge_31.py
Normal file
@ -0,0 +1,34 @@
|
||||
'''
|
||||
A young girl named Emily is learning how to subtract one from a number, but she has a unique way of doing it when the number has two or more digits.
|
||||
|
||||
Emily follows these steps:
|
||||
If the last digit of the number is not zero, she simply subtracts one from the number.
|
||||
If the last digit of the number is zero, she divides the number by 10 (effectively removing the last digit).
|
||||
You are given an integer number n. Emily will perform this subtraction process k times. Your task is to determine the final result after all k subtractions. It is guaranteed that the result will always be a positive integer.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
n = 512, k = 4
|
||||
Output:
|
||||
50
|
||||
Explanation:
|
||||
512→511→510→51→50
|
||||
'''
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, n:int, k:int) -> int:
|
||||
for _ in range(k):
|
||||
if n % 10 != 0:
|
||||
n -= 1
|
||||
else:
|
||||
n //= 10
|
||||
return n
|
||||
|
||||
|
||||
# Example usage:
|
||||
if __name__ == "__main__":
|
||||
solution = Solution()
|
||||
print(solution.solve(512, 4)) # Output: 50
|
||||
print(solution.solve(100, 3)) # Output: 10
|
||||
print(solution.solve(12345, 5)) # Output: 12340
|
||||
print(solution.solve(10, 1)) # Output: 1
|
||||
33
code_challenges/CodeChallenge_32.py
Normal file
33
code_challenges/CodeChallenge_32.py
Normal file
@ -0,0 +1,33 @@
|
||||
'''
|
||||
A string consisting only of the characters b, d and w is painted on a glass window of a store. Alex walks past the store, standing directly in front of the glass
|
||||
window, and observes string s. Alex then heads inside the store, looks directly at the same glass window, and observes string r.
|
||||
Alex gives you string s. Your task is to find and output string r.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
dwd
|
||||
Output:
|
||||
bwb
|
||||
Example 2
|
||||
Input:
|
||||
bbwwwddd
|
||||
Output:
|
||||
bbbwwwdd
|
||||
'''
|
||||
class Solution(object):
|
||||
def solve(self, s:str) -> str:
|
||||
r = []
|
||||
s = s[::-1] #reverse the string
|
||||
# Create a translation table for characters
|
||||
for char in s:
|
||||
trans = str.maketrans({'b':'d','d':'b','w':'w'})
|
||||
return s.translate(trans)
|
||||
|
||||
# Example usage:
|
||||
if __name__ == "__main__":
|
||||
solution = Solution()
|
||||
print(solution.solve("dwd")) # Output: "bwb"
|
||||
print(solution.solve("bbwwwddd")) # Output: "bbbwwwdd"
|
||||
print(solution.solve("bwd")) # Output: "dwb"
|
||||
print(solution.solve("d")) # Output: "b"
|
||||
print(solution.solve("billyjoebob")) #Output: "dodeojyllid"
|
||||
31
code_challenges/CodeChallenge_33.py
Normal file
31
code_challenges/CodeChallenge_33.py
Normal file
@ -0,0 +1,31 @@
|
||||
'''
|
||||
Given a ticket string consisting of six digits, return YES if its lucky and NO in the opposite case. A ticket is considered lucky if the sum of the first
|
||||
three digits is equal to the sum of the last three digits, even when there are leading zeroes.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
213132
|
||||
Output:
|
||||
YES
|
||||
Example 2
|
||||
Input:
|
||||
973894
|
||||
Output:
|
||||
NO
|
||||
'''
|
||||
class Solution(object):
|
||||
def solve(self,ticket:str)->str:
|
||||
first_half = ticket[:3]
|
||||
second_half = ticket[3:]
|
||||
if sum(int(digit) for digit in first_half) == sum(int(digit) for digit in second_half):
|
||||
return "YES"
|
||||
return "NO"
|
||||
|
||||
# Example usage:
|
||||
if __name__ == "__main__":
|
||||
solution = Solution()
|
||||
print(solution.solve("213132")) # Output: YES
|
||||
print(solution.solve("973894")) # Output: NO
|
||||
print(solution.solve("123321")) # Output: YES
|
||||
print(solution.solve("000000")) # Output: YES
|
||||
print(solution.solve("123456")) # Output: NO
|
||||
40
code_challenges/CodeChallenge_34.py
Normal file
40
code_challenges/CodeChallenge_34.py
Normal file
@ -0,0 +1,40 @@
|
||||
'''
|
||||
Sometimes, certain words like optimization or kubernetes are so lengthy that writing them repeatedly in a single text becomes quite tedious.
|
||||
|
||||
Let’s define a word as too long if its length is strictly greater than 7 characters. All such words should be replaced with a special abbreviation.
|
||||
|
||||
The abbreviation is created as follows:
|
||||
Write the first and last letter of the word, and between them, insert the number of letters that appear between the first and last letters. This number is
|
||||
written in decimal format and should not contain any leading zeros.
|
||||
|
||||
Your task is to automate the process of abbreviating words. Replace all too long words with their abbreviations, while leaving shorter words unchanged.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
optimization
|
||||
Output:
|
||||
o10n
|
||||
Example 2
|
||||
Input:
|
||||
kubernetes
|
||||
Output:
|
||||
k8s
|
||||
Example 3
|
||||
Input:
|
||||
word
|
||||
Output:
|
||||
word
|
||||
'''
|
||||
class Solution(object):
|
||||
def solve(self, s:str) -> str:
|
||||
if len(s) > 7:
|
||||
return f"{s[0]}{len(s) - 2}{s[-1]}"
|
||||
return s
|
||||
|
||||
solution = Solution()
|
||||
print(solution.solve("optimization")) # Output: "o10n"
|
||||
print(solution.solve("kubernetes")) # Output: "k8s"
|
||||
print(solution.solve("word")) # Output: "word"
|
||||
print(solution.solve("hello")) # Output: "hello"
|
||||
print(solution.solve("supercalifragilisticexpialidocious")) # Output: "s30s"
|
||||
print(solution.solve("bergermeisterblindarmentzuntuntoperationschwierigkeiten")) # Output: "b56n"
|
||||
35
code_challenges/CodeChallenge_35.py
Normal file
35
code_challenges/CodeChallenge_35.py
Normal file
@ -0,0 +1,35 @@
|
||||
'''
|
||||
There is a game called Mario Adventures, consisting of n levels. Bill and his friend Bob are addicted to the game. Each of them wants to pass the whole game.
|
||||
Bill can complete certain levels on his own and Bob can complete certain levels on his own. If they combine their skills, can they complete all levels together?
|
||||
|
||||
Given an integer n - the total number of levels, list of integers bill_levels - the number of levels Bill can complete and Another list of integers
|
||||
bob_levels - the number of levels Bob can complete. Return string I become the hero! If they can complete all levels together, in the opposite case Oh, no!
|
||||
The castle is locked!
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
n = 5; bill_levels = [3, 1, 2, 3]; bob_levels = [2, 2, 4]
|
||||
Output:
|
||||
Oh, no! The castle is locked!
|
||||
'''
|
||||
|
||||
from typing import List
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, n:int, bill_levels: List[int], bob_levels: List[int]) -> str:
|
||||
print(f"n: {n}, bill_levels: {bill_levels} bob_levels: {bob_levels}")
|
||||
total_levels = set(bill_levels + bob_levels)
|
||||
print(f"Total levels combined: {total_levels}")
|
||||
if len(total_levels) == n:
|
||||
return "I become the hero!"
|
||||
else:
|
||||
return "Oh, no! The castle is locked!"
|
||||
|
||||
# Example usage
|
||||
if __name__ == "__main__":
|
||||
solution = Solution()
|
||||
n = 5
|
||||
bill_levels = [3, 1, 2, 3]
|
||||
bob_levels = [2, 2, 4]
|
||||
result = solution.solve(n, bill_levels, bob_levels)
|
||||
print(result) # Output: Oh, no! The castle is locked!
|
||||
34
code_challenges/CodeChallenge_36.py
Normal file
34
code_challenges/CodeChallenge_36.py
Normal file
@ -0,0 +1,34 @@
|
||||
'''
|
||||
Bob enjoys relaxing after a long day of work. Like many programmers, he's a fan of the famous drink Fantastic, which is sold at various stores around the city. The price of one bottle in store i is xi coins. Bob plans to buy the drink for q consecutive days, and for each day, he knows he will have mi coins to spend. On each day, Bob wants to know how many different stores he can afford to buy the drink from.
|
||||
|
||||
You are given two arrays:
|
||||
|
||||
An array of prices in the shops: prices = [x1, x2, x3, ..., xn] where each xi is the price of one bottle in store i.
|
||||
An array of coins Bob can spend each day: coins = [m1, m2, m3, ..., mq] where each mi represents the coins Bob can spend on the i-th day.
|
||||
Return number of shops where Bob will be able to buy a bottle of the drink on the i-th day.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
prices = [3,10,8,6,11]; coins = [1, 10, 3, 11]
|
||||
Output:
|
||||
[0, 4, 1, 5]
|
||||
'''
|
||||
|
||||
from typing import List
|
||||
|
||||
class Solution(object):
|
||||
def solve(self,prices:List[int], coins:List[int])->List[int]:
|
||||
result = []
|
||||
for m in coins:
|
||||
count = sum(1 for x in prices if x <= m)
|
||||
result.append(count)
|
||||
return result
|
||||
|
||||
|
||||
# Example usage:
|
||||
if __name__ == "__main__":
|
||||
prices = [868,987,714,168,123]
|
||||
coins = [424,192,795,873]
|
||||
solution = Solution()
|
||||
print(solution.solve(prices, coins))
|
||||
|
||||
49
code_challenges/CodeChallenge_37.py
Normal file
49
code_challenges/CodeChallenge_37.py
Normal file
@ -0,0 +1,49 @@
|
||||
'''
|
||||
Alex loves lucky numbers. Lucky numbers are positive integers that contain only the digits 4 and 7 in their decimal representation.
|
||||
|
||||
For example, numbers like 47, 744, and 4 are lucky, while numbers like 5, 17, and 467 are not.
|
||||
|
||||
Alex calls a number almost lucky if it could be evenly divided by some lucky number. Help him find out if the given number n is almost lucky,
|
||||
return YES if its almost lucky and NO in the opposite case.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
47
|
||||
Output:
|
||||
YES
|
||||
Example 2
|
||||
Input:
|
||||
16
|
||||
Output:
|
||||
YES
|
||||
Example 3
|
||||
Input:
|
||||
78
|
||||
Output:
|
||||
NO
|
||||
'''
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, n):
|
||||
# Function to check if a number is lucky
|
||||
def is_lucky(num):
|
||||
return all(digit in '47' for digit in str(num))
|
||||
|
||||
# Generate lucky numbers up to n
|
||||
lucky_numbers = [i for i in range(1, n + 1) if is_lucky(i)]
|
||||
|
||||
# Check if n is almost lucky
|
||||
for lucky in lucky_numbers:
|
||||
if n % lucky == 0:
|
||||
return "YES"
|
||||
|
||||
return "NO"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
n = int(input())
|
||||
solution = Solution()
|
||||
print(solution.solve(n)) # Output: YES or NO based on the input number n
|
||||
|
||||
# Example usage:
|
||||
# n = 47
|
||||
34
code_challenges/CodeChallenge_38.py
Normal file
34
code_challenges/CodeChallenge_38.py
Normal file
@ -0,0 +1,34 @@
|
||||
'''
|
||||
You are given an integer n. In one move, you can either: Multiply n by 2, or Divide n by 6 (only if it is divisible by 6 without a remainder).
|
||||
Return the minimum number of moves needed to obtain 1 from n, or return -1 if it's impossible to do so.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
1
|
||||
Output:
|
||||
0
|
||||
Example 2
|
||||
Input:
|
||||
2
|
||||
Output:
|
||||
-1
|
||||
'''
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, n: int) -> int:
|
||||
moves = 0
|
||||
while n != 1:
|
||||
if n % 6 == 0:
|
||||
n //= 6
|
||||
elif n % 3 == 0:
|
||||
n *= 2
|
||||
else:
|
||||
return -1
|
||||
moves += 1
|
||||
return moves
|
||||
|
||||
# Usage
|
||||
s = Solution()
|
||||
print(s.solve(108))
|
||||
|
||||
|
||||
61
code_challenges/CodeChallenge_39.py
Normal file
61
code_challenges/CodeChallenge_39.py
Normal file
@ -0,0 +1,61 @@
|
||||
'''
|
||||
You have gifts, and each gift contains a certain number of candies and oranges. Your goal is to make all gifts identical in terms of the number of candies
|
||||
and oranges. You are allowed to perform the following operations on any gift:
|
||||
|
||||
Remove one candy.
|
||||
Remove one orange.
|
||||
Remove one candy and one orange at the same time.
|
||||
You cannot remove more than what is available in a gift (no negative values).
|
||||
After performing some moves, all gifts must have the same number of candies and the same number of oranges (though candies and oranges do not need to be equal
|
||||
to each other). Your task is to find the minimum number of moves required to achieve this.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
candies = [3, 5, 6]; oranges = [3, 2, 3]
|
||||
Output:
|
||||
6
|
||||
'''
|
||||
|
||||
from typing import List
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, candies:List[int], oranges:List[int]) -> int:
|
||||
"""
|
||||
Calculates the minimum number of moves required to equalize the number of candies and oranges in all gifts.
|
||||
|
||||
In each move, you can either:
|
||||
- Remove one candy from a gift,
|
||||
- Remove one orange from a gift,
|
||||
- Or remove one candy and one orange from the same gift simultaneously.
|
||||
|
||||
Args:
|
||||
candies (List[int]): A list of integers representing the number of candies in each gift.
|
||||
oranges (List[int]): A list of integers representing the number of oranges in each gift.
|
||||
|
||||
Returns:
|
||||
int: The minimum number of moves required to make all gifts have the same number of candies and oranges.
|
||||
"""
|
||||
# Find the minimum candies and oranges in all gifts
|
||||
min_candies = min(candies)
|
||||
min_oranges = min(oranges)
|
||||
moves = 0
|
||||
for c, o in zip(candies, oranges):
|
||||
# Calculate the extra candies and oranges to remove
|
||||
extra_candies = c - min_candies
|
||||
extra_oranges = o - min_oranges
|
||||
# The minimum of the two can be removed together
|
||||
both = min(extra_candies, extra_oranges)
|
||||
moves += both
|
||||
# Remove the rest individually
|
||||
moves += (extra_candies - both) + (extra_oranges - both)
|
||||
return moves
|
||||
|
||||
# usage example
|
||||
|
||||
s = Solution()
|
||||
candies = [1, 2, 3, 4, 5]
|
||||
oranges = [5, 4, 3, 2, 1]
|
||||
print(s.solve(candies, oranges))
|
||||
|
||||
|
||||
|
||||
34
code_challenges/CodeChallenge_4.py
Normal file
34
code_challenges/CodeChallenge_4.py
Normal file
@ -0,0 +1,34 @@
|
||||
'''
|
||||
One cozy afternoon, Lily and her friend Noah decided to buy a large cake from their favorite bakery. They chose the most decadent one, layered with rich frosting and
|
||||
fresh berries. After purchasing, the cake was weighed, showing a total weight of n grams. Excited to share it, they hurried home but soon realized they faced a tricky
|
||||
problem. Lily and Noah are big fans of even numbers, so they want to divide the cake in such a way that each of the two portions weighs an even number of grams. The
|
||||
portions don’t need to be equal, but each must have a positive weight. Since they’re both tired and eager to enjoy the cake, you need to help them determine if it’s
|
||||
possible to split it the way they want. Given an integer number n - the weight of cake bought by Lily and Noah, return a string YES, if Lily and Noah can divide the
|
||||
cake into two parts, each of them weighing an even number of grams and NO in the opposite case.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
120
|
||||
Output:
|
||||
YES
|
||||
|
||||
Example 2
|
||||
Input:
|
||||
155
|
||||
Output:
|
||||
NO
|
||||
|
||||
'''
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, n: int) -> str:
|
||||
print(f"n: {n}")
|
||||
# Check if n is even and greater than 2
|
||||
if n % 2 == 0 and n > 2:
|
||||
return "YES"
|
||||
else:
|
||||
return "NO"
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(120)) # Output: YES
|
||||
print(s.solve(155)) # Output: NO
|
||||
27
code_challenges/CodeChallenge_5.py
Normal file
27
code_challenges/CodeChallenge_5.py
Normal file
@ -0,0 +1,27 @@
|
||||
'''
|
||||
Bill and Bob have recently joined the Codefinity University for Cool Engineers. They are now moving into a dormitory and want to share the same room. The dormitory has n rooms in total. Each room has a current occupancy and a maximum capacity. Your task is to determine how many rooms have enough space for both Bill and Bob to move in.
|
||||
|
||||
Given a list of n sublists, where each sublist contains two integers c (number of people currently living in the room) and m (room's maximum capacity), return the number of rooms where Bill and Bob can move in together.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
[[2, 2], [1, 10], [3, 5], [0, 2]]
|
||||
Output:
|
||||
3
|
||||
|
||||
'''
|
||||
from typing import List
|
||||
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, rooms: List[List[int]]) -> int:
|
||||
print("Input rooms:", rooms)
|
||||
count = 0
|
||||
for c, m in rooms:
|
||||
if m - c >= 2:
|
||||
count += 1
|
||||
return count
|
||||
|
||||
s = Solution()
|
||||
print(s.solve([[2, 2], [1, 10], [3, 5], [0, 2]])) # Output: 3
|
||||
print(s.solve([[1, 1], [2, 3], [4, 5], [0, 1], [3, 6]])) # Output: 1
|
||||
25
code_challenges/CodeChallenge_6.py
Normal file
25
code_challenges/CodeChallenge_6.py
Normal file
@ -0,0 +1,25 @@
|
||||
'''
|
||||
Bear Bill wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Bill and Bob weigh a and b
|
||||
respectively. It's guaranteed that Bill's weight is smaller than or equal to his brother's weight. Bill eats a lot and his weight is tripled
|
||||
after every year, while Bob's weight is doubled after every year. After how many full years will Bill become strictly heavier than Bob?
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
a = 4; b = 7
|
||||
Output:
|
||||
2
|
||||
'''
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, a: int, b: int) -> int:
|
||||
print("Initial weights - Bill:", a, "Bob:", b)
|
||||
years = 0
|
||||
while a <= b:
|
||||
a *= 3
|
||||
b *= 2
|
||||
years += 1
|
||||
print(f"After year {years}: Bill's weight = {a}, Bob's weight = {b}")
|
||||
return years
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(4, 8)) # Output: 2
|
||||
19
code_challenges/CodeChallenge_7.py
Normal file
19
code_challenges/CodeChallenge_7.py
Normal file
@ -0,0 +1,19 @@
|
||||
class Solution:
|
||||
def solve(self, n:int) -> int:
|
||||
print(f"n: {n}")
|
||||
'''
|
||||
find how many (a, b) are possible where a + b = n
|
||||
n = 3 -> (1, 2), (2, 1)
|
||||
n = 4 -> (1, 3), (2, 2), (3, 1)
|
||||
'''
|
||||
a = 1
|
||||
count = 0
|
||||
while n - a > 0:
|
||||
a += 1
|
||||
count += 1
|
||||
return count
|
||||
|
||||
s = Solution()
|
||||
print(s.solve(3)) # Output: 2
|
||||
print(s.solve(4)) # Output: 3
|
||||
print(s.solve(5)) # Output: 4
|
||||
33
code_challenges/CodeChallenge_8.py
Normal file
33
code_challenges/CodeChallenge_8.py
Normal file
@ -0,0 +1,33 @@
|
||||
'''
|
||||
Given an alphabetic string s, return a string where all vowels are removed and a . is inserted before each remaining letter, and make everything lowercase.
|
||||
|
||||
Vowels are letters A, O, Y, E, U, I, and the rest are consonants.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
hello
|
||||
Output:
|
||||
.h.l.l
|
||||
|
||||
Example 2
|
||||
Input:
|
||||
Codefinity
|
||||
Output:
|
||||
.c.d.f.n.t
|
||||
|
||||
'''
|
||||
class Solution(object):
|
||||
def solve(self, s:str) -> str:
|
||||
print(f"s: {s}")
|
||||
s_lower = s.lower()
|
||||
vowels = ("aeiouy")
|
||||
result = ""
|
||||
for c in s_lower:
|
||||
if c not in vowels:
|
||||
result += '.' + c
|
||||
return result
|
||||
|
||||
s = Solution()
|
||||
# Example usage
|
||||
print(s.solve("HeLlo")) # Output: .h.l.l
|
||||
print(s.solve("Codefinity")) # Output: .c.d.f.n.t
|
||||
21
code_challenges/CodeChallenge_9.py
Normal file
21
code_challenges/CodeChallenge_9.py
Normal file
@ -0,0 +1,21 @@
|
||||
'''
|
||||
Given a string as a+b expression, where a and b are integers, return a sum of a and b as an integer.
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
4+2
|
||||
Output:
|
||||
6
|
||||
'''
|
||||
class Solution(object):
|
||||
def solve(self, expression:str) -> int:
|
||||
print(f"expression: {expression}")
|
||||
left, right = expression.split('+')
|
||||
int_left = int(left)
|
||||
int_right = int(right)
|
||||
sum = int_left + int_right
|
||||
return sum
|
||||
|
||||
s = Solution()
|
||||
print(s.solve("4+2")) # Output: 6
|
||||
print(s.solve("10+20")) # Output: 30
|
||||
53
code_challenges/Code_Challenge_medium_1.py
Normal file
53
code_challenges/Code_Challenge_medium_1.py
Normal file
@ -0,0 +1,53 @@
|
||||
'''
|
||||
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we define a positive integer t as a T-prime
|
||||
if it has exactly three distinct positive divisors.
|
||||
|
||||
Given an array of positive integers, return an array of True or False for each integer if it T-prime
|
||||
|
||||
Example 1
|
||||
Input:
|
||||
[4, 5, 6]
|
||||
Output:
|
||||
[True, False, False]
|
||||
'''
|
||||
|
||||
from typing import List
|
||||
|
||||
|
||||
class Solution(object):
|
||||
def solve(self, nums:List[int]) -> List[bool]:
|
||||
"""
|
||||
:type nums: List[int]
|
||||
:rtype: List[bool]
|
||||
"""
|
||||
def is_t_prime(n):
|
||||
if n < 4:
|
||||
return False
|
||||
root = int(n**0.5)
|
||||
return root * root == n and self.is_prime(root)
|
||||
|
||||
self.is_prime = self.sieve_of_eratosthenes(max(nums))
|
||||
return [is_t_prime(num) for num in nums]
|
||||
|
||||
def sieve_of_eratosthenes(self, n):
|
||||
"""
|
||||
Returns a function that checks if a number is prime using the Sieve of Eratosthenes.
|
||||
"""
|
||||
is_prime = [True] * (n + 1)
|
||||
is_prime[0] = is_prime[1] = False
|
||||
|
||||
for i in range(2, int(n**0.5) + 1):
|
||||
if is_prime[i]:
|
||||
for j in range(i * i, n + 1, i):
|
||||
is_prime[j] = False
|
||||
|
||||
return lambda x: is_prime[x] if x <= n else False
|
||||
|
||||
# Example usage:
|
||||
if __name__ == "__main__":
|
||||
solution = Solution()
|
||||
print(solution.solve([4, 5, 6])) # Output: [True, False, False]
|
||||
print(solution.solve([9, 25, 49])) # Output: [True, True, True]
|
||||
print(solution.solve([1, 2, 3, 10])) # Output: [False, False, False, False]
|
||||
|
||||
|
||||
106
code_challenges/URLSuffixHash.py
Normal file
106
code_challenges/URLSuffixHash.py
Normal file
@ -0,0 +1,106 @@
|
||||
'''
|
||||
I need to shorten 10,000 URLs by taking the URL number and perform repeated divisions by 62, using the remainder to map to a character set. The character set
|
||||
consists of lowercase letters, uppercase letters, and digits. The process continues until the number is reduced to zero.
|
||||
# This will print shortened URLs for numbers 1 to 10,000
|
||||
# You can replace the range with any number to generate a specific shortened URL.
|
||||
# Note: The function `shorten_url` can be called with any integer to get its shortened URL representation.
|
||||
|
||||
# The above code will generate a unique shortened URL for each number from 1 to 10,000.
|
||||
# The output will be a string of characters that can be used as a URL suffix.
|
||||
|
||||
# The character set used is:
|
||||
# - Lowercase letters: a-z
|
||||
# - Uppercase letters: A-Z
|
||||
# - Digits: 0-9
|
||||
# The total character set size is 62, allowing for a wide range of unique URL suffixes.
|
||||
# The function `shorten_url` can be used to convert any integer into a unique URL suffix based on the specified character set.
|
||||
# The function handles the conversion by repeatedly dividing the number by 62 and using the remainder to index into the character set.
|
||||
# The output will be a string that can be appended to a base URL to create a shortened URL.
|
||||
# The function is efficient and can handle large numbers, generating unique suffixes for each input number.
|
||||
# The function can be used in various applications where URL shortening is required, such as in web applications, APIs, or any system that needs to generate short links.
|
||||
# The function `shorten_url` can be used to generate unique URL suffixes for any integer input, making it versatile for various applications.
|
||||
# The function can be easily integrated into a larger system where URL shortening is needed, providing a simple and effective way to create unique identifiers for resources.
|
||||
# The function can be tested with various inputs to ensure it generates the expected shortened URLs.
|
||||
# The function can be modified to handle edge cases or specific requirements as needed, such as handling negative numbers or zero.
|
||||
# The function is designed to be straightforward and easy to understand, making it accessible for developers of all skill levels.
|
||||
# The function can be optimized further if needed, but it is already efficient for the purpose of generating unique URL suffixes.
|
||||
# The function can be used in conjunction with a database or other storage system to map shortened URLs back to their original forms, enabling full URL shortening functionality.
|
||||
# The function can be extended to include additional features, such as tracking usage statistics or expiration dates for shortened URLs.
|
||||
# The function can be used in a variety of contexts, such as social media platforms, content management systems, or any application that requires URL shortening.
|
||||
# The function can be easily adapted to different character sets or base sizes if needed, providing flexibility for different use cases.
|
||||
# The function can be used to generate unique identifiers for resources, making it suitable for applications that require unique keys or tokens.
|
||||
# The function can be tested with a wide range of inputs to ensure robustness and reliability in generating unique URL suffixes.
|
||||
# The function can be integrated into a web service or API to provide URL shortening capabilities for users or applications.
|
||||
# The function can be used to create a simple URL shortening service, allowing users to generate short links for long URLs.
|
||||
# The function can be used in conjunction with a web framework to create a complete URL shortening application, providing both the shortening and redirection functionalities.
|
||||
# The function can be used to generate unique URL suffixes for any integer input, making it versatile for various applications.
|
||||
# The function can be used to create a simple URL shortening service, allowing users to generate short links for long URLs.
|
||||
# The function can be used in conjunction with a web framework to create a complete URL shortening application, providing both the shortening and redirection functionalities.
|
||||
# The function can be used to generate unique identifiers for resources, making it suitable for applications that require unique keys or tokens.
|
||||
# The function can be extended to include additional features, such as tracking usage statistics or expiration dates
|
||||
# for shortened URLs.
|
||||
# The function can be used in a variety of contexts, such as social media platforms, content management systems, or any application that requires URL shortening.
|
||||
# The function can be easily adapted to different character sets or base sizes if needed, providing flexibility for different use cases.
|
||||
# The function can be used to generate unique URL suffixes for any integer input, making it versatile for various applications.
|
||||
# The function can be tested with a wide range of inputs to ensure robustness and reliability in generating unique URL suffixes.
|
||||
# The function can be integrated into a web service or API to provide URL shortening capabilities for users or applications.
|
||||
# The function can be used to create a simple URL shortening service, allowing users to generate short
|
||||
# links for long URLs.
|
||||
# The function can be used in conjunction with a web framework to create a complete URL shortening application, providing both the shortening and redirection functionalities.
|
||||
# The function can be used to generate unique identifiers for resources, making it suitable for applications that require unique keys or tokens.
|
||||
|
||||
# The function can be extended to include additional features, such as tracking usage statistics or expiration dates for shortened URLs.
|
||||
# The function can be used in a variety of contexts, such as social media platforms, content
|
||||
# management systems, or any application that requires URL shortening.
|
||||
# The function can be easily adapted to different character sets or base sizes if needed, providing flexibility for different use cases.
|
||||
# The function can be used to generate unique URL suffixes for any integer input, making it versatile for various applications.
|
||||
# The function can be tested with a wide range of inputs to ensure robustness and reliability in generating
|
||||
|
||||
# unique URL suffixes.
|
||||
# The function can be integrated into a web service or API to provide URL shortening capabilities for users or applications.
|
||||
# The function can be used to create a simple URL shortening service, allowing users to generate short links for long URLs.
|
||||
# The function can be used in conjunction with a web framework to create a complete URL shortening application
|
||||
# providing both the shortening and redirection functionalities.
|
||||
# The function can be used to generate unique identifiers for resources, making it suitable for applications that require unique keys or tokens.
|
||||
# The function can be extended to include additional features, such as tracking usage statistics or expiration dates
|
||||
# for shortened URLs.
|
||||
# The function can be used in a variety of contexts, such as social media platforms, content management systems, or any application that requires URL shortening.
|
||||
# The function can be easily adapted to different character sets or base sizes if needed, providing flexibility
|
||||
# for different use cases.
|
||||
# The function can be used to generate unique URL suffixes for any integer input, making it
|
||||
# versatile for various applications.
|
||||
|
||||
# The function can be tested with a wide range of inputs to ensure robustness and reliability in generating unique URL suffixes.
|
||||
# The function can be integrated into a web service or API to provide URL shortening capabilities for users or applications.
|
||||
# The function can be used to create a simple URL shortening service, allowing users to generate short links for long URLs.
|
||||
# The function can be used in conjunction with a web framework to create a complete URL shortening application, providing both the shortening and redirection functionalities.
|
||||
# The function can be used to generate unique identifiers for resources, making it suitable for applications that require unique keys or tokens.
|
||||
# The function can be extended to include additional features, such as tracking usage statistics or expiration dates for shortened URLs.
|
||||
|
||||
'''
|
||||
|
||||
import string
|
||||
|
||||
class URLSuffixHash:
|
||||
@staticmethod
|
||||
|
||||
def shorten_url(url_number):
|
||||
characters = string.ascii_lowercase + string.ascii_uppercase + string.digits
|
||||
base = len(characters)
|
||||
short_url = []
|
||||
|
||||
while url_number > 0:
|
||||
url_number -= 1
|
||||
remainder = url_number % base
|
||||
short_url.append(characters[remainder])
|
||||
url_number //= base
|
||||
|
||||
return 'mydomain.com/' + ''.join(reversed(short_url))
|
||||
|
||||
|
||||
s = URLSuffixHash()
|
||||
# Example usage
|
||||
for i in range(1500000, 2050001):
|
||||
print(s.shorten_url(i))
|
||||
# This will print shortened URLs for numbers 150000 to 205000
|
||||
|
||||
43
code_challenges/cylinder_max.py
Normal file
43
code_challenges/cylinder_max.py
Normal file
@ -0,0 +1,43 @@
|
||||
'''
|
||||
You must manufacture a closed cylindrical can (top and bottom included). You have a fixed amount of material so the total surface area 𝐴 of the can is fixed.
|
||||
Find the radius 𝑟 and height ℎ of the cylinder that maximize the enclosed volume 𝑉. What is the relation between ℎ and 𝑟 at the optimum? What is the maximal
|
||||
volume 𝑉 sub(max) expressed in terms of the fixed surface area 𝐴?
|
||||
'''
|
||||
|
||||
import numpy as np
|
||||
from scipy.optimize import minimize
|
||||
|
||||
# Fixed surface area
|
||||
A_fixed = 2000 # You can change this value
|
||||
|
||||
# Volume function to maximize (we'll minimize the negative)
|
||||
def volume(params):
|
||||
r, h = params
|
||||
return -np.pi * r**2 * h # Negative for maximization
|
||||
|
||||
# Constraint: surface area must equal A_fixed
|
||||
def surface_area_constraint(params):
|
||||
r, h = params
|
||||
return 2 * np.pi * r**2 + 2 * np.pi * r * h - A_fixed
|
||||
|
||||
# Initial guess
|
||||
initial_guess = [1.0, 1.0]
|
||||
|
||||
# Bounds: radius and height must be positive
|
||||
bounds = [(0.0001, None), (0.0001, None)]
|
||||
|
||||
# Define constraint dictionary
|
||||
constraints = {'type': 'eq', 'fun': surface_area_constraint}
|
||||
|
||||
# Run optimization
|
||||
result = minimize(volume, initial_guess, bounds=bounds, constraints=constraints)
|
||||
|
||||
# Extract optimal values
|
||||
if result.success:
|
||||
r_opt, h_opt = result.x
|
||||
V_max = np.pi * r_opt**2 * h_opt
|
||||
print(f"Optimal radius: {r_opt:.4f}")
|
||||
print(f"Optimal height: {h_opt:.4f}")
|
||||
print(f"Maximum volume: {V_max:.4f}")
|
||||
else:
|
||||
print("Optimization failed:", result.message)
|
||||
26
code_challenges/myCode_1.py
Normal file
26
code_challenges/myCode_1.py
Normal file
@ -0,0 +1,26 @@
|
||||
# Enter a sentence containing only letters of the alphabet and numbers 0-9 and output the morse code equivalent.
|
||||
|
||||
class MorseCode
|
||||
morse_code: (text) ->
|
||||
morse_code_map =
|
||||
a: '.-', b: '-...', c: '-.-.', d: '-..', e: '.'
|
||||
f: '..-.', g: '--.', h: '....', i: '..', j: '.---'
|
||||
k: '-.-', l: '.-..', m: '--', n: '-.', o: '---'
|
||||
p: '.--.', q: '--.-', r: '.-.', s: '...', t: '-'
|
||||
u: '..-', v: '...-', w: '.--', x: '-..-', y: '-.--'
|
||||
z: '--..'
|
||||
'0': '-----', '1': '.----', '2': '..---', '3': '...--'
|
||||
'4': '....-', '5': '.....', '6': '-....', '7': '--...'
|
||||
'8': '---..', '9': '----.'
|
||||
result = []
|
||||
for char in text.toLowerCase()
|
||||
if morse_code_map[char]?
|
||||
result.push morse_code_map[char]
|
||||
else if char is ' '
|
||||
result.push ' / '
|
||||
result.join ''
|
||||
|
||||
s = new MorseCode()
|
||||
console.log s.morse_code "To be or not to be"
|
||||
|
||||
|
||||
21
code_challenges/myCode_2.py
Normal file
21
code_challenges/myCode_2.py
Normal file
@ -0,0 +1,21 @@
|
||||
"""
|
||||
Translate a string of text: letter a becomes z, b becomes y, ..., z becomes a.
|
||||
"""
|
||||
|
||||
class Translate:
|
||||
def translation(self, text: str) -> str:
|
||||
# Create translation table for a-z
|
||||
import string
|
||||
table = str.maketrans(
|
||||
string.ascii_lowercase,
|
||||
string.ascii_lowercase[::-1]
|
||||
)
|
||||
return text.translate(table)
|
||||
|
||||
# Example usage
|
||||
if __name__ == "__main__":
|
||||
t = Translate()
|
||||
sentence = "Tobeornottobethatisthequestion"
|
||||
print(t.translation("sentence")) # Output: zyxcba
|
||||
|
||||
|
||||
62
code_challenges/practice_1.py
Normal file
62
code_challenges/practice_1.py
Normal file
@ -0,0 +1,62 @@
|
||||
class Math(object):
|
||||
def sum (self, *args, **kargs) -> float:
|
||||
result = sum(args)
|
||||
return result
|
||||
|
||||
def sub (self, *args, **kargs) -> float:
|
||||
if len(args) < 2:
|
||||
raise ValueError("sub requires at least two arguments")
|
||||
result = args[0] - args[1]
|
||||
return result
|
||||
|
||||
def mult (self, *args, **kargs) -> float:
|
||||
if len(args) < 2:
|
||||
raise ValueError("mult requires at least two arguments")
|
||||
result = args[0] * args[1]
|
||||
return result
|
||||
|
||||
def div (self, *args, **kargs) -> float:
|
||||
if len(args) < 2:
|
||||
raise ValueError("div requires at least two arguments")
|
||||
result = args[0] / args[1]
|
||||
return result
|
||||
|
||||
def fdiv (self, *args, **kargs) -> float:
|
||||
if len(args) < 2:
|
||||
raise ValueError("fdiv requires at least two arguments")
|
||||
result = args[0] // args[1]
|
||||
return result
|
||||
|
||||
def pow (self, *args, **kargs) -> float:
|
||||
if len(args) < 2:
|
||||
raise ValueError("pow requires at least two arguments")
|
||||
result = args[0] ** args[1]
|
||||
return result
|
||||
|
||||
def mod (self, *args, **kargs) -> float:
|
||||
if len(args) < 2:
|
||||
raise ValueError("mod requires at least two arguments")
|
||||
result = args[0] % args[1]
|
||||
return result
|
||||
|
||||
def avg (self, *args, **kargs) -> float:
|
||||
if len(args) < 2:
|
||||
raise ValueError("avg requires at least two arguments")
|
||||
result = (sum(args)/len(args))
|
||||
return result
|
||||
|
||||
|
||||
|
||||
s = Math()
|
||||
|
||||
print(f"Sum: {s.sum(3.564, 92.335, 14.56):.2f}")
|
||||
print(f"Product: {s.mult(8.56, 3.567):.2f}")
|
||||
print(f"Difference: {s.sub(8.56, 3.567):.2f}")
|
||||
print(f"Floor Division: {s.fdiv(8.56, 3.567):.2f}")
|
||||
print(f"Power: {s.pow(8.56, 3.567):.2f}")
|
||||
print(f"Mod: {s.mod(8.0, 3.0):.2f}")
|
||||
print(f"Average: {s.avg(8.56, 3.567, 73.45, 10.778, 14.334, 56.789):.2f}")
|
||||
print(f"Division: {s.div(8.56, 3.567):.2f}")
|
||||
|
||||
|
||||
print(f"Average: {s.avg(2, 3, 4, 53, 6):.2f}")
|
||||
23
code_challenges/using_zip.py
Normal file
23
code_challenges/using_zip.py
Normal file
@ -0,0 +1,23 @@
|
||||
#Zipping two lists of equal length
|
||||
names = ['Alice', 'Bob', 'Charlie']
|
||||
scores = [85, 92, 78]
|
||||
paired = list(zip(names, scores))
|
||||
print(paired)
|
||||
|
||||
#Creating a dictionary
|
||||
keys = ['id', 'name', 'age']
|
||||
values = [101, 'Alice', 30]
|
||||
data = dict(zip(keys, values))
|
||||
print(data)
|
||||
|
||||
#Unzipping the zipped lists
|
||||
zipped = [('Alice', 85), ('Bob', 92), ('Charlie', 78)]
|
||||
names, scores = zip(*zipped)
|
||||
print(names) # ('Alice', 'Bob', 'Charlie')
|
||||
print(scores) # (85, 92, 78)
|
||||
|
||||
#Unzipping the dictionary to a list of key, value tuples
|
||||
data = {'id': 101, 'name': "Alice", 'age' : 30}
|
||||
keys, values = zip(*data.items())
|
||||
print(keys, values)
|
||||
|
||||
73
complex_class.py
Normal file
73
complex_class.py
Normal file
@ -0,0 +1,73 @@
|
||||
class Complex:
|
||||
def __init__(self, real=0.0, imag=0.0):
|
||||
self.real = real
|
||||
self.imag = imag
|
||||
|
||||
def __add__(self, other):
|
||||
if isinstance(other, Complex):
|
||||
return Complex(self.real + other.real, self.imag + other.imag)
|
||||
return NotImplemented
|
||||
|
||||
def __sub__(self, other):
|
||||
if isinstance(other, Complex):
|
||||
return Complex(self.real - other.real, self.imag - other.imag)
|
||||
return NotImplemented
|
||||
|
||||
def __mul__(self, other):
|
||||
if isinstance(other, Complex):
|
||||
return Complex(
|
||||
self.real * other.real - self.imag * other.imag,
|
||||
self.real * other.imag + self.imag * other.real
|
||||
)
|
||||
return NotImplemented
|
||||
|
||||
def __truediv__(self, other):
|
||||
if isinstance(other, Complex):
|
||||
denom = other.real ** 2 + other.imag ** 2
|
||||
if denom == 0:
|
||||
raise ZeroDivisionError("division by zero")
|
||||
return Complex(
|
||||
(self.real * other.real + self.imag * other.imag) / denom,
|
||||
(self.imag * other.real - self.real * other.imag) / denom
|
||||
)
|
||||
return NotImplemented
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.real} + {self.imag}i"
|
||||
|
||||
def __repr__(self):
|
||||
return f"Complex({self.real}, {self.imag})"
|
||||
|
||||
def conjugate(self):
|
||||
return Complex(self.real, -self.imag)
|
||||
|
||||
def magnitude(self):
|
||||
return (self.real ** 2 + self.imag ** 2) ** 0.5
|
||||
|
||||
def phase(self):
|
||||
import math
|
||||
return math.atan2(self.imag, self.real)
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, Complex):
|
||||
return self.real == other.real and self.imag == other.imag
|
||||
return NotImplemented
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self.__eq__(other)
|
||||
|
||||
if __name__ == "__main__":
|
||||
c1 = Complex(3, 4)
|
||||
c2 = Complex(1, 2)
|
||||
|
||||
print("c1:", c1)
|
||||
print("c2:", c2)
|
||||
print("c1 + c2:", c1 + c2)
|
||||
print("c1 - c2:", c1 - c2)
|
||||
print("c1 * c2:", c1 * c2)
|
||||
print("c1 / c2:", c1 / c2)
|
||||
print("Conjugate of c1:", c1.conjugate())
|
||||
print("Magnitude of c1:", c1.magnitude())
|
||||
print("Phase of c1:", c1.phase())
|
||||
print("Are c1 and c2 equal?", c1 == c2)
|
||||
|
||||
38
concatenating_arrays.py
Normal file
38
concatenating_arrays.py
Normal file
@ -0,0 +1,38 @@
|
||||
import numpy as np
|
||||
"""
|
||||
This script demonstrates how to concatenate NumPy arrays using `np.concatenate` for both 1D and 2D arrays.
|
||||
Examples included:
|
||||
- Concatenating two 1D arrays along their only axis.
|
||||
- Concatenating two 2D arrays along axis 0 (rows) and axis 1 (columns).
|
||||
- Combining simulated quarterly sales data for two products across two years by concatenating along columns.
|
||||
Variables:
|
||||
- array1, array2: Example arrays for demonstration.
|
||||
- concatenated_array: Result of concatenating 1D arrays.
|
||||
- concatenated_array_rows: Result of concatenating 2D arrays along rows.
|
||||
- concatenated_array_columns: Result of concatenating 2D arrays along columns.
|
||||
- sales_data_2021, sales_data_2022: Simulated sales data arrays.
|
||||
- combined_sales_by_product: Combined sales data for both years by product.
|
||||
Prints the results of each concatenation operation.
|
||||
"""
|
||||
array1 = np.array([1, 2, 3])
|
||||
array2 = np.array([4, 5, 6])
|
||||
# Concatenating 1D arrays along their only axis 0
|
||||
concatenated_array = np.concatenate((array1, array2))
|
||||
print(concatenated_array)
|
||||
|
||||
|
||||
array1 = np.array([[1, 2], [3, 4]])
|
||||
array2 = np.array([[5, 6], [7, 8]])
|
||||
# Concatenating along the axis 0 (rows)
|
||||
concatenated_array_rows = np.concatenate((array1, array2))
|
||||
print(f'Axis = 0:\n{concatenated_array_rows}')
|
||||
# Concatenating along the axis 1 (columns)
|
||||
concatenated_array_columns = np.concatenate((array1, array2), axis=1)
|
||||
print(f'Axis = 1:\n{concatenated_array_columns}')
|
||||
|
||||
# Simulated data for quarterly sales of two products in 2021 and 2022
|
||||
sales_data_2021 = np.array([[350, 420, 380, 410], [270, 320, 290, 310]])
|
||||
sales_data_2022 = np.array([[370, 430, 400, 390], [280, 330, 300, 370]])
|
||||
# Concatenate the sales data for both products by columns
|
||||
combined_sales_by_product = np.concatenate((sales_data_2021, sales_data_2022), axis=1)
|
||||
print(f'Combined sales by product:\n{combined_sales_by_product}')
|
||||
7
console_print_with_function.py
Normal file
7
console_print_with_function.py
Normal file
@ -0,0 +1,7 @@
|
||||
# Prices of items sold today
|
||||
prices = [12.99, 23.50, 4.99, 8.75, 15.00]
|
||||
|
||||
def total_sales(prices):
|
||||
print(f"Today's total sales: $", sum(prices))
|
||||
|
||||
total_sales(prices)
|
||||
47
decorator_add.py
Normal file
47
decorator_add.py
Normal file
@ -0,0 +1,47 @@
|
||||
def verbose(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
print(f"Arguments were: {args}, {kwargs}")
|
||||
return func(*args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
@verbose
|
||||
def add(a, b):
|
||||
return a + b
|
||||
|
||||
print(add(3, 4))
|
||||
|
||||
'''
|
||||
How it works:
|
||||
# The decorator 'verbose' prints the arguments passed to the function 'add' before executing it.
|
||||
# The function 'add' then returns the sum of the two arguments. The decorator is applied using the '@' syntax.
|
||||
|
||||
'''
|
||||
|
||||
def layer1(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
print("layer 1")
|
||||
func(*args, **kwargs)
|
||||
print("layer 1")
|
||||
return wrapper
|
||||
|
||||
def layer2(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
print("layer 2")
|
||||
func(*args, **kwargs)
|
||||
print("layer 2")
|
||||
return wrapper
|
||||
|
||||
def layer3(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
print("layer 3")
|
||||
func(*args, **kwargs)
|
||||
print("layer 3")
|
||||
return wrapper
|
||||
|
||||
@layer1
|
||||
@layer2
|
||||
@layer3
|
||||
def print_hi(message):
|
||||
print(message)
|
||||
|
||||
print_hi("Hi there!")
|
||||
33
decorator_chaining.py
Normal file
33
decorator_chaining.py
Normal file
@ -0,0 +1,33 @@
|
||||
|
||||
def decorator_one(func):
|
||||
def wrapper():
|
||||
print("Decorator one start")
|
||||
func()
|
||||
print("Decorator one end")
|
||||
return wrapper
|
||||
|
||||
def decorator_two(func):
|
||||
def wrapper():
|
||||
print("Decorator two start")
|
||||
func()
|
||||
print("Decorator two end")
|
||||
return wrapper
|
||||
|
||||
@decorator_one
|
||||
@decorator_two
|
||||
def greet():
|
||||
print("Hello!")
|
||||
|
||||
greet()
|
||||
|
||||
'''
|
||||
How it works:
|
||||
1. The `decorator_one` function is defined, which takes a function `func` as an argument.
|
||||
2. Inside `decorator_one`, a `wrapper` function is defined that prints messages before and after calling `func`.
|
||||
3. The `wrapper` function is returned from `decorator_one`.
|
||||
|
||||
4. The `decorator_two` function is defined in a similar way.
|
||||
5. The `greet` function is decorated with both `@decorator_one` and `@decorator_two`.
|
||||
6. When `greet` is called, it goes through both decorators, printing messages from each.
|
||||
|
||||
'''
|
||||
33
decorator_exercise.py
Normal file
33
decorator_exercise.py
Normal file
@ -0,0 +1,33 @@
|
||||
import time
|
||||
|
||||
# Step 2: Define the decorator
|
||||
def time_it(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
start_time = time.time() # Start time
|
||||
result = func(*args, **kwargs) # Call the function
|
||||
end_time = time.time() # End time
|
||||
print(f"{func.__name__} took {end_time - start_time} seconds")
|
||||
return result
|
||||
return wrapper
|
||||
|
||||
# Step 4: Apply the decorator
|
||||
@time_it
|
||||
def factorial(n):
|
||||
"""Function to compute factorial of a number"""
|
||||
return 1 if n == 0 else n * factorial(n - 1)
|
||||
|
||||
# Step 5: Test the decorator
|
||||
print(factorial(20)) # Replace with any number to test
|
||||
|
||||
''' How this code works:
|
||||
This code defines a decorator indicate and three functions avg_two, avg_three, and avg_many_kwargs , each decorated with indicate. Here's a brief description of each component:
|
||||
|
||||
Decorator time_it(func) function:
|
||||
- Adds functionality to factorial to calculate the difference between the time before and after executing function factorial.
|
||||
- wrapper takes arguments *args and **kwargs and passes them to the func call (factorial).
|
||||
- The *args allows the wrapper() function to accept any number of positional arguments as a tuple.
|
||||
- The **kwargs allows the wrapper() function to accept any number of keyword arguments as a dictionary.
|
||||
The @time_it decorator is applied to the function:
|
||||
- factorial(n): Computes the factorial of a number, with timing information displayed due to the decorator.
|
||||
- The decorator prints the time taken to execute the factorial function.
|
||||
'''
|
||||
17
decorator_validation.py
Normal file
17
decorator_validation.py
Normal file
@ -0,0 +1,17 @@
|
||||
def validate_decorator(func):
|
||||
def wrapper(number):
|
||||
if not isinstance(number, int) or number < 0:
|
||||
raise ValueError("Input must be a non-negative integer")
|
||||
return func(number)
|
||||
return wrapper
|
||||
|
||||
@validate_decorator
|
||||
def factorial(n):
|
||||
if n == 0:
|
||||
return 1
|
||||
else:
|
||||
return n * factorial(n - 1)
|
||||
|
||||
# Usage
|
||||
print(factorial(2))
|
||||
# factorial(-1) # This will raise an error
|
||||
12
default_func_parameters.py
Normal file
12
default_func_parameters.py
Normal file
@ -0,0 +1,12 @@
|
||||
# Define a function with a default `discount` argument
|
||||
def apply_discount(price, discount=0.10):
|
||||
discounted_price = price * (1 - discount)
|
||||
return discounted_price
|
||||
|
||||
# Call the function without providing a `discount`, using the default value
|
||||
default_discount_price = apply_discount(100)
|
||||
print(f"Price after applying the default discount: ${default_discount_price}")
|
||||
|
||||
# Call the function with a custom `discount` value
|
||||
custom_discount_price = apply_discount(100, 0.20)
|
||||
print(f"Price after applying a custom discount: ${custom_discount_price}")
|
||||
6
dict_merge.py
Normal file
6
dict_merge.py
Normal file
@ -0,0 +1,6 @@
|
||||
# Merging two dictionaries in Python
|
||||
dict_a = {'a': 1, 'b': 2}
|
||||
dict_b = {'c': 3, 'd': 4}
|
||||
|
||||
my_dict = {**dict_a, **dict_b}
|
||||
print(my_dict)
|
||||
23
digital_to_binary.py
Normal file
23
digital_to_binary.py
Normal file
@ -0,0 +1,23 @@
|
||||
def digital_to_binary(digital_number):
|
||||
"""
|
||||
Convert a digital number to its binary representation.
|
||||
|
||||
Parameters:
|
||||
digital_number (int): The digital number to convert.
|
||||
|
||||
Returns:
|
||||
str: The binary representation of the digital number.
|
||||
"""
|
||||
if not isinstance(digital_number, int) or digital_number < 0:
|
||||
raise ValueError("Input must be a non-negative integer.")
|
||||
|
||||
return bin(digital_number)[2:]
|
||||
|
||||
# Example usage:
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
number = 1078 # Example digital number
|
||||
binary_representation = digital_to_binary(number)
|
||||
print(f"The binary representation of {number} is {binary_representation}")
|
||||
except ValueError as e:
|
||||
print(e)
|
||||
23
digital_to_hexidecimal.py
Normal file
23
digital_to_hexidecimal.py
Normal file
@ -0,0 +1,23 @@
|
||||
def digital_to_hexidecimal(digital_number):
|
||||
"""
|
||||
Convert a digital number to its hexadecimal representation.
|
||||
|
||||
Parameters:
|
||||
digital_number (int): The digital number to convert.
|
||||
|
||||
Returns:
|
||||
str: The hexadecimal representation of the digital number.
|
||||
"""
|
||||
if not isinstance(digital_number, int) or digital_number < 0:
|
||||
raise ValueError("Input must be a non-negative integer.")
|
||||
|
||||
return hex(digital_number)[2:].upper()
|
||||
|
||||
# Example usage:
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
number = 1500 # Example digital number
|
||||
hex_representation = digital_to_hexidecimal(number)
|
||||
print(f"The hexadecimal representation of {number} is {hex_representation}")
|
||||
except ValueError as e:
|
||||
print(e)
|
||||
14
discounted_list_prices.py
Normal file
14
discounted_list_prices.py
Normal file
@ -0,0 +1,14 @@
|
||||
# List of product prices
|
||||
product_prices = [1.50, 2.50, 3.00, 0.99, 2.30]
|
||||
|
||||
def apply_discount(prices):
|
||||
prices_copy = product_prices.copy()
|
||||
for index in range(len(prices_copy)):
|
||||
if prices_copy[index] > 2.00:
|
||||
prices_copy[index] *= .90
|
||||
return prices_copy
|
||||
|
||||
# Call the function and store the updated prices
|
||||
updated_prices = apply_discount(product_prices)
|
||||
|
||||
print(f"Updated product prices: {updated_prices}")
|
||||
42
enhanced_decorators.py
Normal file
42
enhanced_decorators.py
Normal file
@ -0,0 +1,42 @@
|
||||
def simple_decorator(func):
|
||||
def wrapper():
|
||||
print("Something is happening before the function is called.")
|
||||
func()
|
||||
print("Something is happening after the function is called.")
|
||||
return wrapper
|
||||
|
||||
@simple_decorator
|
||||
def say_hello():
|
||||
print("Hello!")
|
||||
|
||||
say_hello()
|
||||
|
||||
# Now, the enhanced decorator
|
||||
def decorator_with_args(arg1, arg2):
|
||||
def decorator(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
print(f"Decorator args: {arg1}, {arg2}")
|
||||
return func(*args, **kwargs)
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
@decorator_with_args("hello", 42)
|
||||
def print_numbers(a, b):
|
||||
print(a + b)
|
||||
|
||||
print_numbers(10, 5)
|
||||
|
||||
'''
|
||||
How it works:
|
||||
1. The `simple_decorator` function is defined, which takes a function `func` as an argument.
|
||||
2. Inside `simple_decorator`, a `wrapper` function is defined that prints messages before and after calling `func`.
|
||||
3. The `wrapper` function is returned from `simple_decorator`.
|
||||
|
||||
4. The `decorator_with_args` function is defined, which takes two arguments `arg1` and `arg2`.
|
||||
5. Inside `decorator_with_args`, a `decorator` function is defined that takes a function `func` as an argument.
|
||||
6. Inside `decorator`, a `wrapper` function is defined that prints the decorator arguments and then calls `func`.
|
||||
7. The `wrapper` function is returned from `decorator`, and `decorator` is returned from `decorator_with_args`.
|
||||
|
||||
8. The `print_numbers` function is decorated with `@decorator_with_args("hello", 42")`.
|
||||
9. When `print_numbers` is called, it prints the sum of its arguments and the decorator arguments.
|
||||
'''
|
||||
27
flattening_arrays.py
Normal file
27
flattening_arrays.py
Normal file
@ -0,0 +1,27 @@
|
||||
import numpy as np
|
||||
"""
|
||||
This script demonstrates three different methods to flatten a NumPy array:
|
||||
1. `flatten()`: Returns a copy of the array collapsed into one dimension.
|
||||
2. `reshape(-1)`: Reshapes the array into a one-dimensional array.
|
||||
3. `ravel()`: Returns a flattened array; returns a view whenever possible.
|
||||
The script uses a simulated exam scores array for three students across three subjects.
|
||||
It prints the results of each flattening method and shows that modifying the copy returned by `flatten()` does not affect the original array.
|
||||
"""
|
||||
# Simulated exam scores for three students in three subjects
|
||||
exam_scores = np.array([[75, 82, 90], [92, 88, 78], [60, 70, 85]])
|
||||
# Use the flatten() method for flattening
|
||||
flattened_exam_scores = exam_scores.flatten()
|
||||
print(flattened_exam_scores)
|
||||
|
||||
# Use the reshape() method for flattening
|
||||
exam_scores_reshaped = exam_scores.reshape(-1)
|
||||
print(exam_scores_reshaped)
|
||||
|
||||
# Use the ravel() method for flattening
|
||||
exam_scores_raveled = exam_scores.ravel()
|
||||
print(exam_scores_raveled)
|
||||
|
||||
# Set the first element of the flattened copy to 100
|
||||
flattened_exam_scores[0] = 100
|
||||
print(flattened_exam_scores)
|
||||
print(exam_scores) # Original array remains unchanged
|
||||
49
flexible_decorators.py
Normal file
49
flexible_decorators.py
Normal file
@ -0,0 +1,49 @@
|
||||
def indicate(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
print("=" * 15)
|
||||
print("Taken arguments:", *args, kwargs)
|
||||
result = func(*args, **kwargs)
|
||||
print("=" * 15)
|
||||
return result
|
||||
return wrapper
|
||||
|
||||
|
||||
@indicate
|
||||
def avg_two(a, b):
|
||||
"""Calculate the average of two numbers"""
|
||||
return round((a + b) / 2, 1)
|
||||
|
||||
@indicate
|
||||
def avg_three(a, b, c):
|
||||
"""Calculate the average of three numbers"""
|
||||
return round((a + b + c) / 3, 1)
|
||||
|
||||
@indicate
|
||||
def avg_many_kwargs(**kwargs):
|
||||
"""Calculate the average of multiple numbers in a dictionary"""
|
||||
keys = 0
|
||||
total = 0
|
||||
|
||||
for value in kwargs.values():
|
||||
keys += 1
|
||||
total += value
|
||||
|
||||
return round(total / keys, 1)
|
||||
|
||||
print("Returned:", avg_two(14, 21), "\n")
|
||||
print("Returned:", avg_three(225, 12, 11), "\n")
|
||||
print("Returned:", avg_many_kwargs(first=51, second=11, third=47, fourth=93))
|
||||
|
||||
''' How this code works:
|
||||
This code defines a decorator indicate and three functions avg_two, avg_three, and avg_many_kwargs , each decorated with indicate. Here's a brief description of each component:
|
||||
|
||||
Decorator indicate(func) function:
|
||||
- Adds functionality to print arguments and a separator before and after executing a function.
|
||||
- wrapper takes arguments *args and **kwargs and pass them to the func call.
|
||||
- The *args allows the wrapper() function to accept any number of positional arguments as a tuple.
|
||||
- The **kwargs allows the wrapper() function to accept any number of keyword arguments as a dictionary.
|
||||
The @indicate decorator is applied to three functions:
|
||||
- avg_two(a, b): Calculates and returns the average of two numbers, displaying additional information due to the decorator.
|
||||
- avg_three(a, b, c): Computes the average of three numbers, with additional prints from the decorator.
|
||||
- avg_many_kwargs(**kwargs): Finds the average of multiple numbers passed as keyword arguments, also showing argument details through the decorator.
|
||||
'''
|
||||
25
func_calls_func.py
Normal file
25
func_calls_func.py
Normal file
@ -0,0 +1,25 @@
|
||||
# Dictionary representing the current stock of products
|
||||
inventory = {
|
||||
"apples": 17,
|
||||
"bananas": 75,
|
||||
"oranges": 2,
|
||||
"grapes": 50
|
||||
}
|
||||
|
||||
# Function to restock items that have low stock levels by adding a specified amount
|
||||
def restock(product, inventory, restock_amount):
|
||||
inventory[product] += restock_amount
|
||||
print(f"Restock order placed for {product}. New stock level: {inventory[product]} units.")
|
||||
|
||||
# Function to check which items are below the stock threshold and trigger the `restock` function
|
||||
def check_stock_levels(inventory, threshold):
|
||||
for product, quantity in inventory.items():
|
||||
if quantity < threshold:
|
||||
# If the stock is below the threshold, call the `restock` function to add 50 units
|
||||
restock(product, inventory, 50)
|
||||
|
||||
# Checking the stock levels for all products in the inventory with a threshold of 30 units
|
||||
check_stock_levels(inventory, 30)
|
||||
|
||||
# Display the final inventory after restocking
|
||||
print("Final inventory status:", inventory)
|
||||
63
generators.py
Normal file
63
generators.py
Normal file
@ -0,0 +1,63 @@
|
||||
import time
|
||||
|
||||
def my_generator():
|
||||
yield 3
|
||||
yield 2
|
||||
yield 1
|
||||
|
||||
for value in my_generator():
|
||||
print(value)
|
||||
|
||||
|
||||
# Using next() to manually iterate through the generator
|
||||
g = my_generator()
|
||||
print(next(g)) # Output: 1
|
||||
print(next(g)) # Output: 2
|
||||
print(next(g)) # Output: 3
|
||||
|
||||
print(sum(my_generator())) # Output: 6
|
||||
print(sorted(my_generator())) # Output: [1, 2, 3]
|
||||
|
||||
def countdown(n):
|
||||
while n > 0:
|
||||
yield n
|
||||
n -= 1
|
||||
|
||||
for number in countdown(4):
|
||||
print(number)
|
||||
time.sleep(1) # Pause for 1 second between numbers
|
||||
|
||||
# Example of a generator function to yield first n numbers
|
||||
def firstn(n):
|
||||
num = 0
|
||||
while num < n:
|
||||
yield num
|
||||
num += 1
|
||||
|
||||
# calling firstn():
|
||||
for number in firstn(10):
|
||||
print(number)
|
||||
|
||||
|
||||
print(sum(firstn(100))) # Output: 4950
|
||||
|
||||
|
||||
# Example of a generator expression
|
||||
squared = (x * x for x in range(10))
|
||||
for num in squared:
|
||||
print(num)
|
||||
|
||||
# Fibonacci sequence generator
|
||||
def fibonacci(n):
|
||||
a, b = 0, 1
|
||||
for _ in range(n):
|
||||
yield a
|
||||
a, b = b, a + b
|
||||
|
||||
for num in fibonacci(30):
|
||||
print(num)
|
||||
|
||||
print(list(fibonacci(30))) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
|
||||
|
||||
|
||||
|
||||
47
global_variables.py
Normal file
47
global_variables.py
Normal file
@ -0,0 +1,47 @@
|
||||
|
||||
|
||||
"""
|
||||
This script demonstrates the use of global variables and the `global` keyword in Python functions.
|
||||
Global Variables:
|
||||
- `age`: An integer representing a person's age.
|
||||
Functions:
|
||||
- birthday_greet():
|
||||
- First definition: Prints a birthday greeting using the global `age` variable, incremented by 1 (without modifying the global variable).
|
||||
- Second definition: Uses the `global` keyword to modify the global `age` variable by incrementing it by 1, then prints a birthday greeting.
|
||||
- birthday_greet_global():
|
||||
- First definition: Prints a birthday greeting using the global `age` variable, incremented by 5 (without modifying the global variable).
|
||||
- Second definition: Uses the `global` keyword to modify the global `age` variable by incrementing it by 5, then prints a birthday greeting.
|
||||
Demonstrates:
|
||||
- The difference between accessing and modifying global variables inside functions.
|
||||
- The effect of the `global` keyword on variable scope and assignment.
|
||||
"""
|
||||
age = 24
|
||||
|
||||
def birthday_greet():
|
||||
print(f"Happy B-Day! You are {age + 1}! (local message)")
|
||||
|
||||
birthday_greet() # Call the local function
|
||||
print("Global message", age) # Print the global variable
|
||||
|
||||
def birthday_greet_global():
|
||||
print(f"Happy B-Day! You are {age + 5}! (global message)")
|
||||
birthday_greet_global() # Call the global function
|
||||
|
||||
|
||||
|
||||
age = 20
|
||||
|
||||
def birthday_greet():
|
||||
global age # Added 'global' keyword
|
||||
age += 1
|
||||
print(f"Happy B-Day! You are {age}! (local message)")
|
||||
|
||||
birthday_greet()
|
||||
print("Global message", age)
|
||||
|
||||
def birthday_greet_global():
|
||||
global age # Added 'global' keyword
|
||||
age += 5
|
||||
print(f"Happy B-Day! You are {age}! (global message)")
|
||||
|
||||
birthday_greet_global() # Call the global function
|
||||
50
high-order_functions.py
Normal file
50
high-order_functions.py
Normal file
@ -0,0 +1,50 @@
|
||||
# File: OneDrive/Documents/Python%20Code/using_kwargs.py
|
||||
# Using map to apply a function to each item in an iterable
|
||||
def square(x):
|
||||
return x * x
|
||||
|
||||
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # List of numbers from 1 to 10
|
||||
squared_numbers = map(square, numbers)
|
||||
|
||||
# Convert the map object to a list
|
||||
squared_numbers_list = list(squared_numbers)
|
||||
print(squared_numbers_list)
|
||||
|
||||
# Using map to cube numbers
|
||||
def cube(x):
|
||||
return x * x * x
|
||||
|
||||
cubed_numbers = map(cube, numbers)
|
||||
cubed_numbers_list = list(cubed_numbers)
|
||||
print(cubed_numbers_list)
|
||||
|
||||
# Using filter to filter out even numbers
|
||||
def is_even(x):
|
||||
return x % 2 == 0
|
||||
|
||||
even_numbers = filter(is_even, numbers)
|
||||
even_numbers_list = list(even_numbers)
|
||||
print(even_numbers_list)
|
||||
# Using filter to filter out odd numbers
|
||||
def is_odd(x):
|
||||
return x % 2 != 0
|
||||
|
||||
odd_numbers = filter(is_odd, numbers)
|
||||
odd_numbers_list = list(odd_numbers)
|
||||
print(odd_numbers_list)
|
||||
|
||||
# Step 1: Define the list of temperatures in Celsius
|
||||
temp_celsius = [-40, 0, 25, 30, 40, 100]
|
||||
|
||||
# Step 2: Define a custom function to convert Celsius to Fahrenheit
|
||||
def celsius_to_fahrenheit(celsius):
|
||||
"""Convert temperature from Celsius to Fahrenheit."""
|
||||
fahrenheit = (celsius * 9/5) + 32
|
||||
return fahrenheit
|
||||
|
||||
# Step 3: Use map() with the custom function
|
||||
temp_fahrenheit = map(celsius_to_fahrenheit, temp_celsius)
|
||||
|
||||
# Step 4: Convert the map object to a list and print
|
||||
temp_fahrenheit_list = list(temp_fahrenheit)
|
||||
print(temp_fahrenheit_list)
|
||||
170
item_class.py
Normal file
170
item_class.py
Normal file
@ -0,0 +1,170 @@
|
||||
class item:
|
||||
def __init__(self, name: str, price: float, quantity=0):
|
||||
# Run validations to the received arguments
|
||||
assert price >= 0, f"Price {price} is not greater than or equal to zero!"
|
||||
assert quantity >= 0, f"Quantity {quantity} is not greater than or equal to zero!"
|
||||
|
||||
# Assign to self object
|
||||
self.name = name
|
||||
self.price = price
|
||||
self.quantity = quantity
|
||||
|
||||
def calculate_total_price(self):
|
||||
return self.price * self.quantity
|
||||
|
||||
def apply_discount(self, discount):
|
||||
self.price = self.price * (1 - discount)
|
||||
assert self.price >= 0, f"Price {self.price} is not greater than or equal to zero!"
|
||||
return self.price
|
||||
|
||||
def __repr__(self):
|
||||
return f"item('{self.name}', {self.price}, {self.quantity})"
|
||||
|
||||
def __str__(self):
|
||||
return f"Item: {self.name}, Price: {self.price}, Quantity: {self.quantity}"
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def price(self):
|
||||
return self._price
|
||||
|
||||
@property
|
||||
def quantity(self):
|
||||
return self._quantity
|
||||
@name.setter
|
||||
def name(self, value):
|
||||
if len(value) > 10:
|
||||
raise Exception("The name is too long!")
|
||||
else:
|
||||
self._name = value
|
||||
|
||||
@price.setter
|
||||
def price(self, value):
|
||||
if value < 0:
|
||||
raise Exception("Price cannot be negative!")
|
||||
else:
|
||||
self._price = value
|
||||
|
||||
@quantity.setter
|
||||
def quantity(self, value):
|
||||
if value < 0:
|
||||
raise Exception("Quantity cannot be negative!")
|
||||
else:
|
||||
self._quantity = value
|
||||
|
||||
@classmethod
|
||||
def instantiate_from_csv(cls, filename):
|
||||
import csv
|
||||
with open(filename, 'r') as f:
|
||||
reader = csv.DictReader(f)
|
||||
items = list(reader)
|
||||
for item in items:
|
||||
item['price'] = float(item['price'])
|
||||
item['quantity'] = int(item['quantity'])
|
||||
return [cls(**item) for item in items]
|
||||
@staticmethod
|
||||
def is_integer(num):
|
||||
# We will count out the floats that are point zero
|
||||
if isinstance(num, float):
|
||||
# Count out the floats that are point zero
|
||||
return num.is_integer()
|
||||
elif isinstance(num, int):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
def __add__(self, other):
|
||||
if isinstance(other, item):
|
||||
return self.quantity + other.quantity
|
||||
else:
|
||||
raise Exception("You cannot add these two objects")
|
||||
def __radd__(self, other):
|
||||
return self.__add__(other)
|
||||
def __mul__(self, other):
|
||||
if isinstance(other, (int, float)):
|
||||
return self.price * other
|
||||
else:
|
||||
raise Exception("You cannot multiply these two objects")
|
||||
def __rmul__(self, other):
|
||||
return self.__mul__(other)
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, item):
|
||||
return self.price == other.price and self.quantity == other.quantity
|
||||
else:
|
||||
return False
|
||||
def __lt__(self, other):
|
||||
if isinstance(other, item):
|
||||
return self.price < other.price
|
||||
else:
|
||||
raise Exception("You cannot compare these two objects")
|
||||
def __le__(self, other):
|
||||
if isinstance(other, item):
|
||||
return self.price <= other.price
|
||||
else:
|
||||
raise Exception("You cannot compare these two objects")
|
||||
def __gt__(self, other):
|
||||
if isinstance(other, item):
|
||||
return self.price > other.price
|
||||
else:
|
||||
raise Exception("You cannot compare these two objects")
|
||||
def __ge__(self, other):
|
||||
if isinstance(other, item):
|
||||
return self.price >= other.price
|
||||
else:
|
||||
raise Exception("You cannot compare these two objects")
|
||||
|
||||
def __ne__(self, other):
|
||||
if isinstance(other, item):
|
||||
return self.price != other.price or self.quantity != other.quantity
|
||||
else:
|
||||
return True
|
||||
def __hash__(self):
|
||||
return hash((self.name, self.price, self.quantity))
|
||||
def __bool__(self):
|
||||
return self.quantity > 0
|
||||
def __len__(self):
|
||||
return len(self.name)
|
||||
def __getitem__(self, index):
|
||||
return self.name[index]
|
||||
def __setitem__(self, index, value):
|
||||
name_list = list(self.name)
|
||||
name_list[index] = value
|
||||
self.name = ''.join(name_list)
|
||||
def __delitem__(self, index):
|
||||
name_list = list(self.name)
|
||||
del name_list[index]
|
||||
self.name = ''.join(name_list)
|
||||
def __contains__(self, item):
|
||||
return item in self.name
|
||||
def __dir__(self):
|
||||
return ['name', 'price', 'quantity', 'calculate_total_price', 'apply_discount', 'instantiate_from_csv', 'is_integer']
|
||||
def __format__(self, format_spec):
|
||||
if format_spec == 'name':
|
||||
return self.name
|
||||
elif format_spec == 'price':
|
||||
return f"{self.price:.2f}"
|
||||
elif format_spec == 'quantity':
|
||||
return str(self.quantity)
|
||||
else:
|
||||
return str(self)
|
||||
def __getstate__(self):
|
||||
return self.__dict__
|
||||
def __setstate__(self, state):
|
||||
self.__dict__.update(state)
|
||||
def __copy__(self):
|
||||
return item(self.name, self.price, self.quantity)
|
||||
def __deepcopy__(self, memo):
|
||||
from copy import deepcopy
|
||||
return item(deepcopy(self.name, memo), deepcopy(self.price, memo), deepcopy(self.quantity, memo))
|
||||
def __reversed__(self):
|
||||
return item(self.name[::-1], self.price, self.quantity)
|
||||
# The following methods are already defined above, so they should not be duplicated.
|
||||
# Remove the duplicate definitions to avoid syntax errors and keep only one implementation.
|
||||
|
||||
# (No code needed here, as the correct implementations are already present earlier in the class.)
|
||||
example = item("Example", 10.0, 5)
|
||||
print(example) # Output: Item: Example, Price: 10.0, Quantity: 5
|
||||
print(repr(example)) # Output: item('Example', 10.0, 5)
|
||||
print(example.calculate_total_price()) # Output: 50.0
|
||||
21
kargs_in_dynamic_funcs.py
Normal file
21
kargs_in_dynamic_funcs.py
Normal file
@ -0,0 +1,21 @@
|
||||
def personal_info(name, **kwargs):
|
||||
print(f"Name: {name}")
|
||||
for key, value in kwargs.items():
|
||||
print(f"{key.capitalize()}: {value}")
|
||||
|
||||
|
||||
"""
|
||||
Prints personal information including a required name and any number of additional keyword arguments.
|
||||
Args:
|
||||
name (str): The person's name.
|
||||
**kwargs: Arbitrary keyword arguments representing additional personal information (e.g., surname, son, cats, breed).
|
||||
kwargs.key is capitalized in the output.
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
# Example usage of the personal_info function
|
||||
personal_info("Sarah", surname="Conor", son="John")
|
||||
personal_info("Natalie", cats="3", breed="Maine Coon")
|
||||
personal_info("John", surname="Doe", age=30, city="New York", occupation="Engineer")
|
||||
personal_info("Alice", hobbies="reading, hiking", favorite_color="blue")
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user