initial commit of files

This commit is contained in:
Dan Calloway 2025-09-15 16:02:00 -04:00
parent 160b474d15
commit 1f304523ad
214 changed files with 5493 additions and 0 deletions

View 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
View 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
View 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
View 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
View 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]])

View 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
CodeChallenge_1.py Normal file
View 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
CodeChallenge_10.py Normal file
View 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
CodeChallenge_11.py Normal file
View 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
CodeChallenge_12.py Normal file
View 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
CodeChallenge_13.py Normal file
View 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
CodeChallenge_14.py Normal file
View 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
CodeChallenge_15.py Normal file
View 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
CodeChallenge_16.py Normal file
View 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
CodeChallenge_17.py Normal file
View 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
CodeChallenge_18.py Normal file
View 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 Bobs view on the solution, the third number shows Janes 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
CodeChallenge_19.py Normal file
View 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
CodeChallenge_2.py Normal file
View 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
CodeChallenge_20.py Normal file
View 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
CodeChallenge_21.py Normal file
View 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
CodeChallenge_22.py Normal file
View 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
CodeChallenge_23.py Normal file
View 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
CodeChallenge_24.py Normal file
View 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
CodeChallenge_25.py Normal file
View 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
CodeChallenge_26.py Normal file
View 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
CodeChallenge_27.py Normal file
View 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
CodeChallenge_28.py Normal file
View 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 wasLiam 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
CodeChallenge_29.py Normal file
View 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
CodeChallenge_3.py Normal file
View 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
CodeChallenge_30.py Normal file
View 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
CodeChallenge_31.py Normal file
View 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:
5125115105150
'''
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
CodeChallenge_32.py Normal file
View 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
CodeChallenge_33.py Normal file
View 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
CodeChallenge_34.py Normal file
View 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.
Lets 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
CodeChallenge_35.py Normal file
View 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
CodeChallenge_36.py Normal file
View 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
CodeChallenge_37.py Normal file
View 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
CodeChallenge_38.py Normal file
View 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
CodeChallenge_39.py Normal file
View 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
CodeChallenge_4.py Normal file
View 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 dont need to be equal, but each must have a positive weight. Since theyre both tired and eager to enjoy the cake, you need to help them determine if its
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
CodeChallenge_5.py Normal file
View 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
CodeChallenge_6.py Normal file
View 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
CodeChallenge_7.py Normal file
View 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
CodeChallenge_8.py Normal file
View 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
CodeChallenge_9.py Normal file
View 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

View 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]

5
Context_Managers.py Normal file
View 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.")

1
Hello_Python_World.py Normal file
View File

@ -0,0 +1 @@
print("Hello Python World")

View File

@ -0,0 +1,5 @@
message = "Hello Python World"
print(message)
message = "Hello Python Crash Course World. What's next for us in Python Programming?"
print(message)

24
Lambda_funcs.py Normal file
View 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
View 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']

15
Projects.code-workspace Normal file
View File

@ -0,0 +1,15 @@
{
"folders": [
{
"path": "../../../home/datapioneer/Projects"
},
{
"path": "."
}
],
"settings": {
"files.exclude": {
"**/.git": false
}
}
}

0
README.txt Normal file
View File

90
README_GITEA_PUSH.md Normal file
View File

@ -0,0 +1,90 @@
# Quick Start: Push Local Repo to Gitea
## 1. Create repo on Gitea
- Log in → **`+` → New Repository**
- Enter repo name → click **Create Repository**
---
## 2. Initialize your local repo
```bash
cd ~/projects/myproject
git init
git add .
git commit -m "Initial commit"
```
---
## 3. Add the remote
Copy the HTTPS or SSH URL from Gitea:
```bash
git remote add origin https://gitcenter.dancalloway.com/dancalloway/Python_Projects.git
```
(or SSH: `git@gitcenter.dancalloway.com:dancalloway/Python_Projects.git`)
---
## 4. Push your branch
If your branch is `main`:
```bash
git push -u origin main
```
If your branch is `Main`: [Our branch is Main -uppercase M]
```bash
git push -u origin Main
```
---
## 5. Done
- `git push` → send changes up
- `git pull` → fetch changes down
- Repeat `add` + `commit` + `push` as you work
---
⚠️ **Important**:
- Repos **must be created on Gitea first**. Pushing to a non-existent repo wont work (push-to-create is disabled).
- Branch names are **case-sensitive** (`main` ≠ `Main`).
---
# 🛠️ Troubleshooting Common Git Errors
**1. Error: `fatal: remote origin already exists`**
👉 You already added a remote. Fix with:
```bash
git remote set-url origin https://gitcenter.dancalloway.com/dancalloway/Python_Projects.git
```
---
**2. Error: `non-fast-forward` (push rejected)**
👉 Your local branch is behind the remote. Update first:
```bash
git pull --rebase origin main
git push
```
---
**3. Error: `push to create not enabled`**
👉 You tried pushing to a repo that doesnt exist. Create it on Gitea first, then retry.
---
**4. Error: `authentication failed`**
👉 Check your username/password or SSH key.
- For HTTPS: use your **Gitea username + password (or token)**.
- For SSH: ensure your public key is added under **Profile → Settings → SSH / GPG Keys**.
---
**5. Wrong branch pushed (e.g. `Main` vs `main`)**
👉 Branch names are case-sensitive. Rename if needed:
```bash
git branch -m Main main
git push -u origin main
```

34
RMD_Calculator.py Normal file
View 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}")

106
URLSuffixHash.py Normal file
View 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

22
activations.py Normal file
View 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()

7
alien.py Normal file
View File

@ -0,0 +1,7 @@
alien_0 = {'color': 'green', 'points': 5 }
#print(f" The color of the alien is: {alien_0 ['color']}")
#print(f" The number of points on the alien is: {alien_0 ['points']}")
print(alien_0)
alien_0['x-position'] = 0
alien_0['y-position'] = 25
print(alien_0)

4
alien1.py Normal file
View File

@ -0,0 +1,4 @@
alien_1 = {}
alien_1['color'] = 'green'
alien_1['points'] = 5
print(alien_1)

4
alien2.py Normal file
View File

@ -0,0 +1,4 @@
alien_2 = {'color': 'green'}
print(f"The alien is {alien_2['color']}")
alien_2 = {'color': 'yellow'}
print(f"The alien is now {alien_2['color']}")

14
alien3.py Normal file
View File

@ -0,0 +1,14 @@
alien_3 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print(f"Original position {alien_3['x_position']}")
# Determine how far to move the alien based on its current speed
if alien_3['speed'] == 'slow':
x_increment = 1
elif alien_3['speed'] == 'medium':
x_increment = 2
else:
# This must be a fast alien
x_increment = 3
# The new position is the old position plus the increment
alien_3['x_position'] = alien_3['x_position'] + x_increment
print(f"New position: {alien_3['x_position']}")

6
alien4.py Normal file
View File

@ -0,0 +1,6 @@
alien_4 = {'color': 'green', 'points': 5}
print(alien_4)
# Delete the second key:value pair from alien_4
del(alien_4['points'])
print(alien_4)

7
alien5.py Normal file
View File

@ -0,0 +1,7 @@
alien_0 = {'color': 'green', 'points': 5 }
#print(f" The color of the alien is: {alien_0 ['color']}")
#print(f" The number of points on the alien is: {alien_0 ['points']}")
print(alien_0)
alien_0['x-position'] = 0
alien_0['y-position'] = 25
print(alien_0)

3
alien5a.py Normal file
View File

@ -0,0 +1,3 @@
alien_5 = {'color': 'green', 'speed': 'slow'}
point_value = alien_5.get('points', 'No point value assigned.')
print(point_value)

3
alien5get_method.py Normal file
View File

@ -0,0 +1,3 @@
alien_5 = {'color': 'green', 'speed': 'slow'}
point_value = alien_5.get('points', 'No point value assigned.')
print(point_value)

7
aliens.py Normal file
View File

@ -0,0 +1,7 @@
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)

9
amusement_park.py Normal file
View File

@ -0,0 +1,9 @@
age = 12
if age < 4:
print('Your admission price is $0.')
elif age < 18:
print('Your admission price is $25.')
else:
print('Your admission price is $40.')

View File

@ -0,0 +1,11 @@
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
else:
price = 40
print(f"Your admission price is ${price}")

75
animal_talk.py Normal file
View 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()}")

2
apostrophe.py Normal file
View File

@ -0,0 +1,2 @@
message = "One of python's strengths is its diverse community."
print(message)

16
areaOfTriangle.py Normal file
View File

@ -0,0 +1,16 @@
# Python Program to find the area of triangle
A = 5
B = 6
C = 7
"""Uncomment below to take inputs from the user"""
# A = float(input('Enter first side: '))
# B = float(input('Enter second side: '))
# C = float(input('Enter third side: '))
"""calculate the semi-perimeter"""
S = (A + B + C) / 2
"""Calculating the area"""
AREA = (S*(S-A)*(S-B)*(S-C)) ** 0.5
print('The area of the triangle is %0.2f' %AREA)

19
args_and_kargs_in_func.py Normal file
View 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 Normal file
View 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
View 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
View 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
View 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}')

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

View 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}')

View 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}')

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

5
banned_users.py Normal file
View File

@ -0,0 +1,5 @@
banned_users = ['carolina', 'andrew', 'david']
user = 'marie'
if user not in banned_users:
print(f"{user.title()}, you can post a response if you wish.")

10
bicycles.py Normal file
View File

@ -0,0 +1,10 @@
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
#print(bicycles)
#print(bicycles[0])
#print(bicycles[0].title())
#print(bicycles[-1].title())
print(f"My first bicycle was a {bicycles[0].title()}")

34
broadcasting_arrays.py Normal file
View 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
cars.py Normal file
View File

@ -0,0 +1,25 @@
# sorting a list alphabetically; original list is permanently changed
#cars = ['bmw', 'audi', 'toyota', 'subaru']
#print(cars)
#cars.sort()
#print(cars)
#print("\n")
# sorting a list in reverse-alphabetical order; original list is permanently
# changed
#cars = ['bmw', 'audi', 'toyota', 'subaru']
#print(cars)
#cars.sort(reverse=True)
#print(cars)
# sorting a list but maintaining the original list
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\n Here is the sorted list:")
print(sorted(cars))
print("\n Here is the original list again:")
print(cars)

7
cars2.py Normal file
View File

@ -0,0 +1,7 @@
cars = ['audi', 'bmw', 'suburu', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())

25
class_Pet.py Normal file
View 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
View 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()

View 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
View 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

73
complex_class.py Normal file
View 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
View 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}')

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

43
cylinder_max.py Normal file
View 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)

47
decorator_add.py Normal file
View 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
View 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
View 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
View 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

View File

@ -0,0 +1,47 @@
def decode_permissions(permissions):
if len(permissions) != 10:
return "Invalid permissions string."
file_type = permissions[0]
owner_permissions = permissions[1:4]
group_permissions = permissions[4:7]
others_permissions = permissions[7:10]
file_type_dict = {
'd': "Directory",
'-': "File"
}
owner_permissions_dict = {
'r': "Read",
'w': "Write",
'x': "Execute",
'-': "No permission"
}
owner_permissions_str = " ".join(owner_permissions_dict[p] for p in owner_permissions)
group_permissions_dict = {
'r': "Read",
'w': "Write",
'x': "Execute",
's': "Set Group ID (SGID) bit set",
'-': "No permission"
}
group_permissions_str = " ".join(group_permissions_dict[p] for p in group_permissions)
others_permissions_dict = {
'r': "Read",
'w': "Write",
'x': "Execute",
's': "Set Group ID (SGID) bit set for others",
'-': "No permission"
}
others_permissions_str = " ".join(others_permissions_dict[p] for p in others_permissions)
return f"{file_type_dict[file_type]} - Owner: {owner_permissions_str}, Group: {group_permissions_str}, Others: {others_permissions_str}"
file_permissions = "drwxrwsrwx+"
print(decode_permissions(file_permissions)) # Output: Directory - Owner: Read Write Execute, Group: Read Write Set Group ID (SGID) bit set, Others: Read Write Execute

Some files were not shown because too many files have changed in this diff Show More