diff --git a/2D_array_boolean_indexing.py b/2D_array_boolean_indexing.py new file mode 100644 index 0000000..ac4107b --- /dev/null +++ b/2D_array_boolean_indexing.py @@ -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)]) \ No newline at end of file diff --git a/2D_array_indexing.py b/2D_array_indexing.py new file mode 100644 index 0000000..17d3dc2 --- /dev/null +++ b/2D_array_indexing.py @@ -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) \ No newline at end of file diff --git a/2D_array_slicing.py b/2D_array_slicing.py new file mode 100644 index 0000000..c0a5275 --- /dev/null +++ b/2D_array_slicing.py @@ -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]]) \ No newline at end of file diff --git a/2D_int_array_indexing.py b/2D_int_array_indexing.py new file mode 100644 index 0000000..6142a13 --- /dev/null +++ b/2D_int_array_indexing.py @@ -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]]) + + + diff --git a/3D_array_indexing.py b/3D_array_indexing.py new file mode 100644 index 0000000..9f9e89e --- /dev/null +++ b/3D_array_indexing.py @@ -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]]) \ No newline at end of file diff --git a/CodeChallenge_02(Medium).py b/CodeChallenge_02(Medium).py new file mode 100644 index 0000000..f368ab8 --- /dev/null +++ b/CodeChallenge_02(Medium).py @@ -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("-.--.-.--")) + + + \ No newline at end of file diff --git a/CodeChallenge_1.py b/CodeChallenge_1.py new file mode 100644 index 0000000..a034169 --- /dev/null +++ b/CodeChallenge_1.py @@ -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)) \ No newline at end of file diff --git a/CodeChallenge_10.py b/CodeChallenge_10.py new file mode 100644 index 0000000..24cfa57 --- /dev/null +++ b/CodeChallenge_10.py @@ -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] \ No newline at end of file diff --git a/CodeChallenge_11.py b/CodeChallenge_11.py new file mode 100644 index 0000000..7e6b027 --- /dev/null +++ b/CodeChallenge_11.py @@ -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 \ No newline at end of file diff --git a/CodeChallenge_12.py b/CodeChallenge_12.py new file mode 100644 index 0000000..28c1129 --- /dev/null +++ b/CodeChallenge_12.py @@ -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 \ No newline at end of file diff --git a/CodeChallenge_13.py b/CodeChallenge_13.py new file mode 100644 index 0000000..0948989 --- /dev/null +++ b/CodeChallenge_13.py @@ -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" \ No newline at end of file diff --git a/CodeChallenge_14.py b/CodeChallenge_14.py new file mode 100644 index 0000000..d310b61 --- /dev/null +++ b/CodeChallenge_14.py @@ -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)) \ No newline at end of file diff --git a/CodeChallenge_15.py b/CodeChallenge_15.py new file mode 100644 index 0000000..a9a084e --- /dev/null +++ b/CodeChallenge_15.py @@ -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)) \ No newline at end of file diff --git a/CodeChallenge_16.py b/CodeChallenge_16.py new file mode 100644 index 0000000..f8405a8 --- /dev/null +++ b/CodeChallenge_16.py @@ -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 \ No newline at end of file diff --git a/CodeChallenge_17.py b/CodeChallenge_17.py new file mode 100644 index 0000000..e0abd3d --- /dev/null +++ b/CodeChallenge_17.py @@ -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)) \ No newline at end of file diff --git a/CodeChallenge_18.py b/CodeChallenge_18.py new file mode 100644 index 0000000..21a993c --- /dev/null +++ b/CodeChallenge_18.py @@ -0,0 +1,36 @@ +''' +One day three best friends Bill, Bob, and Jane decided to form a team and take part in programming contests. During these contests, participants are typically +given several problems to solve. Before the competition began, the friends agreed on a rule: +They would only attempt to solve a problem if at least two of them were confident in their solution. Otherwise, they would skip that problem. For each problem, it is +known which of the friends are sure about the solution. Your task is to help the friends determine the number of problems they will attempt to solve based on their rule. + +Given a list of lists of triples of integers 1 or 0. If the first number in the line equals 1, then Bill is sure about the problem's solution, otherwise he isn't sure. +The second number shows Bob’s view on the solution, the third number shows Jane’s view. Return an integer - the number of problems the friends will implement on the +contest. + +Example 1 +Input: +[[ 1, 0, 1 ], [1, 1, 1], [0, 0, 0]] +Output: +2 +Example 2 +Input: +[[0, 1, 1], [0, 0, 1], [1, 1, 1], [1, 1, 0]] +Output: +3 +''' +from typing import List + +class Solution(object): + def solve(self, problems: List[List[int]]) -> int: + print(f"problems: {problems}") + count = 0 + for problem in problems: + if sum(problem) >= 2: + count += 1 + return count + +s = Solution() +# Example usage +print(s.solve([[1, 0, 1], [1, 1, 1], [0, 0, 0]])) # Output: 2 +print(s.solve([[0, 1, 1], [0, 0, 1], [1, 1, 1], [1, 1, 0]])) # Output: 3 \ No newline at end of file diff --git a/CodeChallenge_19.py b/CodeChallenge_19.py new file mode 100644 index 0000000..12e4d65 --- /dev/null +++ b/CodeChallenge_19.py @@ -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 + \ No newline at end of file diff --git a/CodeChallenge_2.py b/CodeChallenge_2.py new file mode 100644 index 0000000..84e8150 --- /dev/null +++ b/CodeChallenge_2.py @@ -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)) \ No newline at end of file diff --git a/CodeChallenge_20.py b/CodeChallenge_20.py new file mode 100644 index 0000000..cc343e0 --- /dev/null +++ b/CodeChallenge_20.py @@ -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)) \ No newline at end of file diff --git a/CodeChallenge_21.py b/CodeChallenge_21.py new file mode 100644 index 0000000..5fd0555 --- /dev/null +++ b/CodeChallenge_21.py @@ -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 \ No newline at end of file diff --git a/CodeChallenge_22.py b/CodeChallenge_22.py new file mode 100644 index 0000000..f6acc7c --- /dev/null +++ b/CodeChallenge_22.py @@ -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: \ No newline at end of file diff --git a/CodeChallenge_23.py b/CodeChallenge_23.py new file mode 100644 index 0000000..81a5d08 --- /dev/null +++ b/CodeChallenge_23.py @@ -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 diff --git a/CodeChallenge_24.py b/CodeChallenge_24.py new file mode 100644 index 0000000..f9be9c0 --- /dev/null +++ b/CodeChallenge_24.py @@ -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: "-" \ No newline at end of file diff --git a/CodeChallenge_25.py b/CodeChallenge_25.py new file mode 100644 index 0000000..4a07858 --- /dev/null +++ b/CodeChallenge_25.py @@ -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 \ No newline at end of file diff --git a/CodeChallenge_26.py b/CodeChallenge_26.py new file mode 100644 index 0000000..2a4c97f --- /dev/null +++ b/CodeChallenge_26.py @@ -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 \ No newline at end of file diff --git a/CodeChallenge_27.py b/CodeChallenge_27.py new file mode 100644 index 0000000..0953876 --- /dev/null +++ b/CodeChallenge_27.py @@ -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 diff --git a/CodeChallenge_28.py b/CodeChallenge_28.py new file mode 100644 index 0000000..2846f68 --- /dev/null +++ b/CodeChallenge_28.py @@ -0,0 +1,41 @@ +''' +Liam enjoys playing chess, and so does his friend Noah. One day, they played n games in a row. For each game, it is known who the winner was—Liam or Noah. +None of the games ended in a tie. + +Now Liam is curious to know who won more games - him or Noah. Can you help him find out? +Given a string s, consisting of uppercase English letters L and N — the outcome of each of the games. The i-th character of the string is equal to L if the Liam +won the i-th game and N if Noah won the i-th game, return a string with Noah If Noah won more games than Liam and Liam in the opposite case. If Noah and Liam won +the same number of games, return Friendship + +Example 1 +Input: +LNLLLL +Output: +Liam +Example 2 +Input: +NLNLNL +Output: +Friendship +Example 3 +Input: +NNLNLN +Output: +Noah +''' + +class Solution(object): + def solve(self, s:str) -> str: + liam_wins = s.count('L') + noah_wins = s.count('N') + if liam_wins > noah_wins: + return "Liam" + elif noah_wins > liam_wins: + return "Noah" + else: + return "Friendship" + +s = Solution() +print(s.solve("LNLLLL")) # Output: Liam +print(s.solve("NLNLNL")) # Output: Friendship +print(s.solve("NNLNLN")) # Output: Noah \ No newline at end of file diff --git a/CodeChallenge_29.py b/CodeChallenge_29.py new file mode 100644 index 0000000..fcd7316 --- /dev/null +++ b/CodeChallenge_29.py @@ -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 + +''' + diff --git a/CodeChallenge_3.py b/CodeChallenge_3.py new file mode 100644 index 0000000..1c599ee --- /dev/null +++ b/CodeChallenge_3.py @@ -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)) \ No newline at end of file diff --git a/CodeChallenge_30.py b/CodeChallenge_30.py new file mode 100644 index 0000000..aad4b73 --- /dev/null +++ b/CodeChallenge_30.py @@ -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 \ No newline at end of file diff --git a/CodeChallenge_31.py b/CodeChallenge_31.py new file mode 100644 index 0000000..b39f70d --- /dev/null +++ b/CodeChallenge_31.py @@ -0,0 +1,34 @@ +''' +A young girl named Emily is learning how to subtract one from a number, but she has a unique way of doing it when the number has two or more digits. + +Emily follows these steps: +If the last digit of the number is not zero, she simply subtracts one from the number. +If the last digit of the number is zero, she divides the number by 10 (effectively removing the last digit). +You are given an integer number n. Emily will perform this subtraction process k times. Your task is to determine the final result after all k subtractions. It is guaranteed that the result will always be a positive integer. + +Example 1 +Input: +n = 512, k = 4 +Output: +50 +Explanation: +512→511→510→51→50 +''' + +class Solution(object): + def solve(self, n:int, k:int) -> int: + for _ in range(k): + if n % 10 != 0: + n -= 1 + else: + n //= 10 + return n + + +# Example usage: +if __name__ == "__main__": + solution = Solution() + print(solution.solve(512, 4)) # Output: 50 + print(solution.solve(100, 3)) # Output: 10 + print(solution.solve(12345, 5)) # Output: 12340 + print(solution.solve(10, 1)) # Output: 1 \ No newline at end of file diff --git a/CodeChallenge_32.py b/CodeChallenge_32.py new file mode 100644 index 0000000..1682bb1 --- /dev/null +++ b/CodeChallenge_32.py @@ -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" \ No newline at end of file diff --git a/CodeChallenge_33.py b/CodeChallenge_33.py new file mode 100644 index 0000000..7b11fcd --- /dev/null +++ b/CodeChallenge_33.py @@ -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 \ No newline at end of file diff --git a/CodeChallenge_34.py b/CodeChallenge_34.py new file mode 100644 index 0000000..e4e847b --- /dev/null +++ b/CodeChallenge_34.py @@ -0,0 +1,40 @@ +''' +Sometimes, certain words like optimization or kubernetes are so lengthy that writing them repeatedly in a single text becomes quite tedious. + +Let’s define a word as too long if its length is strictly greater than 7 characters. All such words should be replaced with a special abbreviation. + +The abbreviation is created as follows: +Write the first and last letter of the word, and between them, insert the number of letters that appear between the first and last letters. This number is +written in decimal format and should not contain any leading zeros. + +Your task is to automate the process of abbreviating words. Replace all too long words with their abbreviations, while leaving shorter words unchanged. + +Example 1 +Input: +optimization +Output: +o10n +Example 2 +Input: +kubernetes +Output: +k8s +Example 3 +Input: +word +Output: +word +''' +class Solution(object): + def solve(self, s:str) -> str: + if len(s) > 7: + return f"{s[0]}{len(s) - 2}{s[-1]}" + return s + +solution = Solution() +print(solution.solve("optimization")) # Output: "o10n" +print(solution.solve("kubernetes")) # Output: "k8s" +print(solution.solve("word")) # Output: "word" +print(solution.solve("hello")) # Output: "hello" +print(solution.solve("supercalifragilisticexpialidocious")) # Output: "s30s" +print(solution.solve("bergermeisterblindarmentzuntuntoperationschwierigkeiten")) # Output: "b56n" \ No newline at end of file diff --git a/CodeChallenge_35.py b/CodeChallenge_35.py new file mode 100644 index 0000000..710721a --- /dev/null +++ b/CodeChallenge_35.py @@ -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! \ No newline at end of file diff --git a/CodeChallenge_36.py b/CodeChallenge_36.py new file mode 100644 index 0000000..53125de --- /dev/null +++ b/CodeChallenge_36.py @@ -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)) + \ No newline at end of file diff --git a/CodeChallenge_37.py b/CodeChallenge_37.py new file mode 100644 index 0000000..4efaaae --- /dev/null +++ b/CodeChallenge_37.py @@ -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 \ No newline at end of file diff --git a/CodeChallenge_38.py b/CodeChallenge_38.py new file mode 100644 index 0000000..97949a5 --- /dev/null +++ b/CodeChallenge_38.py @@ -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)) + + \ No newline at end of file diff --git a/CodeChallenge_39.py b/CodeChallenge_39.py new file mode 100644 index 0000000..ab432b5 --- /dev/null +++ b/CodeChallenge_39.py @@ -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)) + + + \ No newline at end of file diff --git a/CodeChallenge_4.py b/CodeChallenge_4.py new file mode 100644 index 0000000..5d45aff --- /dev/null +++ b/CodeChallenge_4.py @@ -0,0 +1,34 @@ +''' +One cozy afternoon, Lily and her friend Noah decided to buy a large cake from their favorite bakery. They chose the most decadent one, layered with rich frosting and +fresh berries. After purchasing, the cake was weighed, showing a total weight of n grams. Excited to share it, they hurried home but soon realized they faced a tricky +problem. Lily and Noah are big fans of even numbers, so they want to divide the cake in such a way that each of the two portions weighs an even number of grams. The +portions don’t need to be equal, but each must have a positive weight. Since they’re both tired and eager to enjoy the cake, you need to help them determine if it’s +possible to split it the way they want. Given an integer number n - the weight of cake bought by Lily and Noah, return a string YES, if Lily and Noah can divide the +cake into two parts, each of them weighing an even number of grams and NO in the opposite case. + +Example 1 +Input: +120 +Output: +YES + +Example 2 +Input: +155 +Output: +NO + +''' + +class Solution(object): + def solve(self, n: int) -> str: + print(f"n: {n}") + # Check if n is even and greater than 2 + if n % 2 == 0 and n > 2: + return "YES" + else: + return "NO" + +s = Solution() +print(s.solve(120)) # Output: YES +print(s.solve(155)) # Output: NO \ No newline at end of file diff --git a/CodeChallenge_5.py b/CodeChallenge_5.py new file mode 100644 index 0000000..35bb1c3 --- /dev/null +++ b/CodeChallenge_5.py @@ -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 diff --git a/CodeChallenge_6.py b/CodeChallenge_6.py new file mode 100644 index 0000000..97c3f2c --- /dev/null +++ b/CodeChallenge_6.py @@ -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 diff --git a/CodeChallenge_7.py b/CodeChallenge_7.py new file mode 100644 index 0000000..04e63a7 --- /dev/null +++ b/CodeChallenge_7.py @@ -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 \ No newline at end of file diff --git a/CodeChallenge_8.py b/CodeChallenge_8.py new file mode 100644 index 0000000..bf51232 --- /dev/null +++ b/CodeChallenge_8.py @@ -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 \ No newline at end of file diff --git a/CodeChallenge_9.py b/CodeChallenge_9.py new file mode 100644 index 0000000..75ebbc9 --- /dev/null +++ b/CodeChallenge_9.py @@ -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 diff --git a/Code_Challenge_medium_1.py b/Code_Challenge_medium_1.py new file mode 100644 index 0000000..f85f110 --- /dev/null +++ b/Code_Challenge_medium_1.py @@ -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] + + \ No newline at end of file diff --git a/Context_Managers.py b/Context_Managers.py new file mode 100644 index 0000000..d3b2832 --- /dev/null +++ b/Context_Managers.py @@ -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.") + diff --git a/Hello_Python_World.py b/Hello_Python_World.py new file mode 100644 index 0000000..9ae3c15 --- /dev/null +++ b/Hello_Python_World.py @@ -0,0 +1 @@ +print("Hello Python World") diff --git a/Hello_Python_World_Alternative.py b/Hello_Python_World_Alternative.py new file mode 100644 index 0000000..d58d76a --- /dev/null +++ b/Hello_Python_World_Alternative.py @@ -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) diff --git a/Lambda_funcs.py b/Lambda_funcs.py new file mode 100644 index 0000000..9e15722 --- /dev/null +++ b/Lambda_funcs.py @@ -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) \ No newline at end of file diff --git a/Lists_In_Functions.py b/Lists_In_Functions.py new file mode 100644 index 0000000..3d16122 --- /dev/null +++ b/Lists_In_Functions.py @@ -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'] \ No newline at end of file diff --git a/Projects.code-workspace b/Projects.code-workspace new file mode 100644 index 0000000..aecd6d4 --- /dev/null +++ b/Projects.code-workspace @@ -0,0 +1,15 @@ +{ + "folders": [ + { + "path": "../../../home/datapioneer/Projects" + }, + { + "path": "." + } + ], + "settings": { + "files.exclude": { + "**/.git": false + } + } +} \ No newline at end of file diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..e69de29 diff --git a/README_GITEA_PUSH.md b/README_GITEA_PUSH.md new file mode 100644 index 0000000..a24c0a6 --- /dev/null +++ b/README_GITEA_PUSH.md @@ -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 won’t 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 doesn’t 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 +``` diff --git a/RMD_Calculator.py b/RMD_Calculator.py new file mode 100644 index 0000000..7d0c2fc --- /dev/null +++ b/RMD_Calculator.py @@ -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}") \ No newline at end of file diff --git a/URLSuffixHash.py b/URLSuffixHash.py new file mode 100644 index 0000000..f00d8ef --- /dev/null +++ b/URLSuffixHash.py @@ -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 + diff --git a/activations.py b/activations.py new file mode 100644 index 0000000..a4af1f5 --- /dev/null +++ b/activations.py @@ -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() diff --git a/alien.py b/alien.py new file mode 100644 index 0000000..af6f4d6 --- /dev/null +++ b/alien.py @@ -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) \ No newline at end of file diff --git a/alien1.py b/alien1.py new file mode 100644 index 0000000..0be56db --- /dev/null +++ b/alien1.py @@ -0,0 +1,4 @@ +alien_1 = {} +alien_1['color'] = 'green' +alien_1['points'] = 5 +print(alien_1) diff --git a/alien2.py b/alien2.py new file mode 100644 index 0000000..e5de19b --- /dev/null +++ b/alien2.py @@ -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']}") diff --git a/alien3.py b/alien3.py new file mode 100644 index 0000000..7735739 --- /dev/null +++ b/alien3.py @@ -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']}") + diff --git a/alien4.py b/alien4.py new file mode 100644 index 0000000..e06b3c7 --- /dev/null +++ b/alien4.py @@ -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) + diff --git a/alien5.py b/alien5.py new file mode 100644 index 0000000..af6f4d6 --- /dev/null +++ b/alien5.py @@ -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) \ No newline at end of file diff --git a/alien5a.py b/alien5a.py new file mode 100644 index 0000000..6a7ed73 --- /dev/null +++ b/alien5a.py @@ -0,0 +1,3 @@ +alien_5 = {'color': 'green', 'speed': 'slow'} +point_value = alien_5.get('points', 'No point value assigned.') +print(point_value) diff --git a/alien5get_method.py b/alien5get_method.py new file mode 100644 index 0000000..6a7ed73 --- /dev/null +++ b/alien5get_method.py @@ -0,0 +1,3 @@ +alien_5 = {'color': 'green', 'speed': 'slow'} +point_value = alien_5.get('points', 'No point value assigned.') +print(point_value) diff --git a/aliens.py b/aliens.py new file mode 100644 index 0000000..6847036 --- /dev/null +++ b/aliens.py @@ -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) + \ No newline at end of file diff --git a/amusement_park.py b/amusement_park.py new file mode 100644 index 0000000..e37c76c --- /dev/null +++ b/amusement_park.py @@ -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.') + + diff --git a/amusement_park_alternate.py b/amusement_park_alternate.py new file mode 100644 index 0000000..1f17976 --- /dev/null +++ b/amusement_park_alternate.py @@ -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}") + + + diff --git a/animal_talk.py b/animal_talk.py new file mode 100644 index 0000000..3804e83 --- /dev/null +++ b/animal_talk.py @@ -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()}") + + \ No newline at end of file diff --git a/apostrophe.py b/apostrophe.py new file mode 100644 index 0000000..fb25c22 --- /dev/null +++ b/apostrophe.py @@ -0,0 +1,2 @@ +message = "One of python's strengths is its diverse community." +print(message) diff --git a/areaOfTriangle.py b/areaOfTriangle.py new file mode 100644 index 0000000..2a02592 --- /dev/null +++ b/areaOfTriangle.py @@ -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) \ No newline at end of file diff --git a/args_and_kargs_in_func.py b/args_and_kargs_in_func.py new file mode 100644 index 0000000..7378256 --- /dev/null +++ b/args_and_kargs_in_func.py @@ -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) + diff --git a/args_and_optionals.py b/args_and_optionals.py new file mode 100644 index 0000000..ec2684e --- /dev/null +++ b/args_and_optionals.py @@ -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) \ No newline at end of file diff --git a/array_boolean_indexing.py b/array_boolean_indexing.py new file mode 100644 index 0000000..fb32966 --- /dev/null +++ b/array_boolean_indexing.py @@ -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]) \ No newline at end of file diff --git a/array_comparisons.py b/array_comparisons.py new file mode 100644 index 0000000..d9cc0e4 --- /dev/null +++ b/array_comparisons.py @@ -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. +''' \ No newline at end of file diff --git a/array_copying.py b/array_copying.py new file mode 100644 index 0000000..e61a325 --- /dev/null +++ b/array_copying.py @@ -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}') \ No newline at end of file diff --git a/array_creation_functions.py b/array_creation_functions.py new file mode 100644 index 0000000..9f0b4ed --- /dev/null +++ b/array_creation_functions.py @@ -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}') \ No newline at end of file diff --git a/array_indexing.py b/array_indexing.py new file mode 100644 index 0000000..5fbb0ea --- /dev/null +++ b/array_indexing.py @@ -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) \ No newline at end of file diff --git a/array_manipulation.py b/array_manipulation.py new file mode 100644 index 0000000..3e61678 --- /dev/null +++ b/array_manipulation.py @@ -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) \ No newline at end of file diff --git a/array_scalar_operations.py b/array_scalar_operations.py new file mode 100644 index 0000000..d5d1fcc --- /dev/null +++ b/array_scalar_operations.py @@ -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}') + diff --git a/array_statistical_operations.py b/array_statistical_operations.py new file mode 100644 index 0000000..3e7eff1 --- /dev/null +++ b/array_statistical_operations.py @@ -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}') \ No newline at end of file diff --git a/assigning_values_to_indexed_elements.py b/assigning_values_to_indexed_elements.py new file mode 100644 index 0000000..e1007b6 --- /dev/null +++ b/assigning_values_to_indexed_elements.py @@ -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) + diff --git a/banned_users.py b/banned_users.py new file mode 100644 index 0000000..b236498 --- /dev/null +++ b/banned_users.py @@ -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.") + diff --git a/bicycles.py b/bicycles.py new file mode 100644 index 0000000..edd61b9 --- /dev/null +++ b/bicycles.py @@ -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()}") + + + + diff --git a/broadcasting_arrays.py b/broadcasting_arrays.py new file mode 100644 index 0000000..2aad302 --- /dev/null +++ b/broadcasting_arrays.py @@ -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) diff --git a/cars.py b/cars.py new file mode 100644 index 0000000..c0c4534 --- /dev/null +++ b/cars.py @@ -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) diff --git a/cars2.py b/cars2.py new file mode 100644 index 0000000..fb9730e --- /dev/null +++ b/cars2.py @@ -0,0 +1,7 @@ +cars = ['audi', 'bmw', 'suburu', 'toyota'] +for car in cars: + if car == 'bmw': + print(car.upper()) + else: + print(car.title()) + diff --git a/class_Pet.py b/class_Pet.py new file mode 100644 index 0000000..26b57ea --- /dev/null +++ b/class_Pet.py @@ -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 diff --git a/class_inheritance.py b/class_inheritance.py new file mode 100644 index 0000000..bac727a --- /dev/null +++ b/class_inheritance.py @@ -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() + + + \ No newline at end of file diff --git a/class_user_def_context_mgr.py b/class_user_def_context_mgr.py new file mode 100644 index 0000000..8428d63 --- /dev/null +++ b/class_user_def_context_mgr.py @@ -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. \ No newline at end of file diff --git a/classes_fundamentals.py b/classes_fundamentals.py new file mode 100644 index 0000000..8d1e089 --- /dev/null +++ b/classes_fundamentals.py @@ -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 diff --git a/complex_class.py b/complex_class.py new file mode 100644 index 0000000..8232a96 --- /dev/null +++ b/complex_class.py @@ -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) + \ No newline at end of file diff --git a/concatenating_arrays.py b/concatenating_arrays.py new file mode 100644 index 0000000..70710cd --- /dev/null +++ b/concatenating_arrays.py @@ -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}') \ No newline at end of file diff --git a/console_print_with_function.py b/console_print_with_function.py new file mode 100644 index 0000000..7657733 --- /dev/null +++ b/console_print_with_function.py @@ -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) \ No newline at end of file diff --git a/cylinder_max.py b/cylinder_max.py new file mode 100644 index 0000000..c7d21d8 --- /dev/null +++ b/cylinder_max.py @@ -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) diff --git a/decorator_add.py b/decorator_add.py new file mode 100644 index 0000000..283a071 --- /dev/null +++ b/decorator_add.py @@ -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!") \ No newline at end of file diff --git a/decorator_chaining.py b/decorator_chaining.py new file mode 100644 index 0000000..88c1f2c --- /dev/null +++ b/decorator_chaining.py @@ -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. + +''' \ No newline at end of file diff --git a/decorator_exercise.py b/decorator_exercise.py new file mode 100644 index 0000000..9da34c7 --- /dev/null +++ b/decorator_exercise.py @@ -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. +''' \ No newline at end of file diff --git a/decorator_validation.py b/decorator_validation.py new file mode 100644 index 0000000..590cffb --- /dev/null +++ b/decorator_validation.py @@ -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 \ No newline at end of file diff --git a/def decode_permissions(permissions):.py b/def decode_permissions(permissions):.py new file mode 100644 index 0000000..ab02c57 --- /dev/null +++ b/def decode_permissions(permissions):.py @@ -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 \ No newline at end of file diff --git a/default_func_parameters.py b/default_func_parameters.py new file mode 100644 index 0000000..a71789a --- /dev/null +++ b/default_func_parameters.py @@ -0,0 +1,12 @@ +# Define a function with a default `discount` argument +def apply_discount(price, discount=0.10): + discounted_price = price * (1 - discount) + return discounted_price + +# Call the function without providing a `discount`, using the default value +default_discount_price = apply_discount(100) +print(f"Price after applying the default discount: ${default_discount_price}") + +# Call the function with a custom `discount` value +custom_discount_price = apply_discount(100, 0.20) +print(f"Price after applying a custom discount: ${custom_discount_price}") \ No newline at end of file diff --git a/dict_merge.py b/dict_merge.py new file mode 100644 index 0000000..79461bf --- /dev/null +++ b/dict_merge.py @@ -0,0 +1,6 @@ +# Merging two dictionaries in Python +dict_a = {'a': 1, 'b': 2} +dict_b = {'c': 3, 'd': 4} + +my_dict = {**dict_a, **dict_b} +print(my_dict) diff --git a/digital_to_binary.py b/digital_to_binary.py new file mode 100644 index 0000000..7566b94 --- /dev/null +++ b/digital_to_binary.py @@ -0,0 +1,23 @@ +def digital_to_binary(digital_number): + """ + Convert a digital number to its binary representation. + + Parameters: + digital_number (int): The digital number to convert. + + Returns: + str: The binary representation of the digital number. + """ + if not isinstance(digital_number, int) or digital_number < 0: + raise ValueError("Input must be a non-negative integer.") + + return bin(digital_number)[2:] + +# Example usage: +if __name__ == "__main__": + try: + number = 1078 # Example digital number + binary_representation = digital_to_binary(number) + print(f"The binary representation of {number} is {binary_representation}") + except ValueError as e: + print(e) \ No newline at end of file diff --git a/digital_to_hexidecimal.py b/digital_to_hexidecimal.py new file mode 100644 index 0000000..0abd6ba --- /dev/null +++ b/digital_to_hexidecimal.py @@ -0,0 +1,23 @@ +def digital_to_hexidecimal(digital_number): + """ + Convert a digital number to its hexadecimal representation. + + Parameters: + digital_number (int): The digital number to convert. + + Returns: + str: The hexadecimal representation of the digital number. + """ + if not isinstance(digital_number, int) or digital_number < 0: + raise ValueError("Input must be a non-negative integer.") + + return hex(digital_number)[2:].upper() + +# Example usage: +if __name__ == "__main__": + try: + number = 1500 # Example digital number + hex_representation = digital_to_hexidecimal(number) + print(f"The hexadecimal representation of {number} is {hex_representation}") + except ValueError as e: + print(e) \ No newline at end of file diff --git a/dimensions.py b/dimensions.py new file mode 100644 index 0000000..85c6580 --- /dev/null +++ b/dimensions.py @@ -0,0 +1,35 @@ +# example of the immutable tuple + +# dimensions = (200, 50) +# print(dimensions) +# print(dimensions[0]) +# print(dimensions[1]) + +# attempting to change the first element in the tuple + +#dimensions = (200, 50) +#dimensions[0] = 250 + +# example of a one-element tuple + +#my_tuple = (3,) +#print(my_tuple) + +# looping through the elements of a tuple + +# dimensions = (200, 50) +#for dimension in dimensions: +# print(dimension) + +# writing over a tuple + +dimensions = (200, 50) +print("Original dimensions:") +for dimension in dimensions: + print(dimension) + +dimensions = (400, 50) +print("\nModified dimensions") +for dimension in dimensions: + print(dimension) + diff --git a/discounted_list_prices.py b/discounted_list_prices.py new file mode 100644 index 0000000..a7e7a8b --- /dev/null +++ b/discounted_list_prices.py @@ -0,0 +1,14 @@ +# List of product prices +product_prices = [1.50, 2.50, 3.00, 0.99, 2.30] + +def apply_discount(prices): + prices_copy = product_prices.copy() + for index in range(len(prices_copy)): + if prices_copy[index] > 2.00: + prices_copy[index] *= .90 + return prices_copy + +# Call the function and store the updated prices +updated_prices = apply_discount(product_prices) + +print(f"Updated product prices: {updated_prices}") \ No newline at end of file diff --git a/enhanced_decorators.py b/enhanced_decorators.py new file mode 100644 index 0000000..7ddeff3 --- /dev/null +++ b/enhanced_decorators.py @@ -0,0 +1,42 @@ +def simple_decorator(func): + def wrapper(): + print("Something is happening before the function is called.") + func() + print("Something is happening after the function is called.") + return wrapper + +@simple_decorator +def say_hello(): + print("Hello!") + +say_hello() + +# Now, the enhanced decorator +def decorator_with_args(arg1, arg2): + def decorator(func): + def wrapper(*args, **kwargs): + print(f"Decorator args: {arg1}, {arg2}") + return func(*args, **kwargs) + return wrapper + return decorator + +@decorator_with_args("hello", 42) +def print_numbers(a, b): + print(a + b) + +print_numbers(10, 5) + +''' +How it works: +1. The `simple_decorator` function is defined, which takes a function `func` as an argument. +2. Inside `simple_decorator`, a `wrapper` function is defined that prints messages before and after calling `func`. +3. The `wrapper` function is returned from `simple_decorator`. + +4. The `decorator_with_args` function is defined, which takes two arguments `arg1` and `arg2`. +5. Inside `decorator_with_args`, a `decorator` function is defined that takes a function `func` as an argument. +6. Inside `decorator`, a `wrapper` function is defined that prints the decorator arguments and then calls `func`. +7. The `wrapper` function is returned from `decorator`, and `decorator` is returned from `decorator_with_args`. + +8. The `print_numbers` function is decorated with `@decorator_with_args("hello", 42")`. +9. When `print_numbers` is called, it prints the sum of its arguments and the decorator arguments. +''' \ No newline at end of file diff --git a/even_numbers.py b/even_numbers.py new file mode 100644 index 0000000..9737c28 --- /dev/null +++ b/even_numbers.py @@ -0,0 +1,2 @@ +even_numbers = list(range(2, 11, 2)) +print(even_numbers) diff --git a/famous_quote.py b/famous_quote.py new file mode 100644 index 0000000..419c81f --- /dev/null +++ b/famous_quote.py @@ -0,0 +1,3 @@ +name = "albert einstein" +print(f"{name.title()} once said, \"A person who never made a mistake never") +print("\btried anything new.\"") diff --git a/famous_quote_2.py b/famous_quote_2.py new file mode 100644 index 0000000..a2bdf1c --- /dev/null +++ b/famous_quote_2.py @@ -0,0 +1,4 @@ +famous_person = "Albert Einstein" +print(f"{famous_person} once said, \"A person who never made a mistake") +print("\bnever tried anything new.\"") + diff --git a/favorite_language_values.py b/favorite_language_values.py new file mode 100644 index 0000000..33df4ee --- /dev/null +++ b/favorite_language_values.py @@ -0,0 +1,11 @@ +favorite_languages = { + 'jen': 'python', + 'sarah': 'c', + 'edward': 'rust', + 'phil': 'python', + } +print('The following languages have been mentioned:') +for language in favorite_languages.values(): + print(language.title()) + + \ No newline at end of file diff --git a/favorite_languages.py b/favorite_languages.py new file mode 100644 index 0000000..2db6b80 --- /dev/null +++ b/favorite_languages.py @@ -0,0 +1,10 @@ +favorite_languages = { + 'jen': 'python', + 'sarah': 'c', + 'edward': 'rust', + 'phil': 'python', + } +language = favorite_languages['sarah'].title() +print(f"Sarah's favorite language is {language}.") +# Asking for Sarah's favorite language +favorite_languages['sarah'] diff --git a/favorite_languages2.py b/favorite_languages2.py new file mode 100644 index 0000000..a905798 --- /dev/null +++ b/favorite_languages2.py @@ -0,0 +1,9 @@ +favorite_languages = { + 'jen': 'python', + 'sarah': 'c', + 'edward': 'rust', + 'phil': 'python', + } +for name, language in favorite_languages.items(): + print(f"{name.title()}'s favorite language is {language.title()}.") + \ No newline at end of file diff --git a/favorite_languages3.py b/favorite_languages3.py new file mode 100644 index 0000000..b9d03f6 --- /dev/null +++ b/favorite_languages3.py @@ -0,0 +1,8 @@ +favorite_languages = { + 'jen': 'python', + 'sarah': 'c', + 'edward': 'rust', + 'phil': 'python', + } +for name in favorite_languages.keys(): + print(name.title()) diff --git a/favorite_languages4.py b/favorite_languages4.py new file mode 100644 index 0000000..350005c --- /dev/null +++ b/favorite_languages4.py @@ -0,0 +1,12 @@ +favorite_languages = { + 'jen': 'python', + 'sarah': 'c', + 'edward': 'rust', + 'phil': 'python', + } +friends = ['phil', 'sarah'] +for name in favorite_languages.keys(): + print(f"Hi, {name.title()}.") + if name in friends: + language = favorite_languages[name].title() + print(f"\t{name.title()}, I see you love {language}!") diff --git a/favorite_languages_in_set.py b/favorite_languages_in_set.py new file mode 100644 index 0000000..64ea684 --- /dev/null +++ b/favorite_languages_in_set.py @@ -0,0 +1,11 @@ +favorite_languages = { + 'jen': 'python', + 'sarah': 'c', + 'edward': 'rust', + 'phil': 'python', + } +print('The following languages have been mentioned:') +for language in set(favorite_languages.values()): + print(language.title()) + + \ No newline at end of file diff --git a/favorite_languages_modified.py b/favorite_languages_modified.py new file mode 100644 index 0000000..843a646 --- /dev/null +++ b/favorite_languages_modified.py @@ -0,0 +1,12 @@ +favorite_languages = { + 'jen': ['python', 'rust'], + 'sarah': ['c'], + 'edward': ['rust', 'go'], + 'phil': ['python', 'haskell'], + +} +for name, languages in favorite_languages.items(): + print(f"\n{name.title()}'s favorite languages are:") + for language in languages: + print(f"\t{language.title()}") + diff --git a/favorite_languages_sorted.py b/favorite_languages_sorted.py new file mode 100644 index 0000000..f83a3cf --- /dev/null +++ b/favorite_languages_sorted.py @@ -0,0 +1,9 @@ +favorite_languages = { + 'jen': 'python', + 'sarah': 'c', + 'edward': 'rust', + 'phil': 'python', + } +for name in sorted(favorite_languages.keys()): + print(f"{name.title()}, thank you for taking the poll.") + \ No newline at end of file diff --git a/file_extension.py b/file_extension.py new file mode 100644 index 0000000..b88d42b --- /dev/null +++ b/file_extension.py @@ -0,0 +1,2 @@ +filename = "filename.txt" +print(filename.removesuffix(".txt")) diff --git a/first_numbers.py b/first_numbers.py new file mode 100644 index 0000000..de4cbe9 --- /dev/null +++ b/first_numbers.py @@ -0,0 +1,5 @@ +#for value in range(1, 5): + #print(value) + +numbers = list(range(1, 6)) +print(numbers) diff --git a/flattening_arrays.py b/flattening_arrays.py new file mode 100644 index 0000000..fca5df2 --- /dev/null +++ b/flattening_arrays.py @@ -0,0 +1,27 @@ +import numpy as np +""" +This script demonstrates three different methods to flatten a NumPy array: +1. `flatten()`: Returns a copy of the array collapsed into one dimension. +2. `reshape(-1)`: Reshapes the array into a one-dimensional array. +3. `ravel()`: Returns a flattened array; returns a view whenever possible. +The script uses a simulated exam scores array for three students across three subjects. +It prints the results of each flattening method and shows that modifying the copy returned by `flatten()` does not affect the original array. +""" +# Simulated exam scores for three students in three subjects +exam_scores = np.array([[75, 82, 90], [92, 88, 78], [60, 70, 85]]) +# Use the flatten() method for flattening +flattened_exam_scores = exam_scores.flatten() +print(flattened_exam_scores) + +# Use the reshape() method for flattening +exam_scores_reshaped = exam_scores.reshape(-1) +print(exam_scores_reshaped) + +# Use the ravel() method for flattening +exam_scores_raveled = exam_scores.ravel() +print(exam_scores_raveled) + +# Set the first element of the flattened copy to 100 +flattened_exam_scores[0] = 100 +print(flattened_exam_scores) +print(exam_scores) # Original array remains unchanged \ No newline at end of file diff --git a/flexible_decorators.py b/flexible_decorators.py new file mode 100644 index 0000000..c6ca4c0 --- /dev/null +++ b/flexible_decorators.py @@ -0,0 +1,49 @@ +def indicate(func): + def wrapper(*args, **kwargs): + print("=" * 15) + print("Taken arguments:", *args, kwargs) + result = func(*args, **kwargs) + print("=" * 15) + return result + return wrapper + + +@indicate +def avg_two(a, b): + """Calculate the average of two numbers""" + return round((a + b) / 2, 1) + +@indicate +def avg_three(a, b, c): + """Calculate the average of three numbers""" + return round((a + b + c) / 3, 1) + +@indicate +def avg_many_kwargs(**kwargs): + """Calculate the average of multiple numbers in a dictionary""" + keys = 0 + total = 0 + + for value in kwargs.values(): + keys += 1 + total += value + + return round(total / keys, 1) + +print("Returned:", avg_two(14, 21), "\n") +print("Returned:", avg_three(225, 12, 11), "\n") +print("Returned:", avg_many_kwargs(first=51, second=11, third=47, fourth=93)) + +''' How this code works: +This code defines a decorator indicate and three functions avg_two, avg_three, and avg_many_kwargs , each decorated with indicate. Here's a brief description of each component: + +Decorator indicate(func) function: +- Adds functionality to print arguments and a separator before and after executing a function. +- wrapper takes arguments *args and **kwargs and pass them to the func call. +- The *args allows the wrapper() function to accept any number of positional arguments as a tuple. +- The **kwargs allows the wrapper() function to accept any number of keyword arguments as a dictionary. +The @indicate decorator is applied to three functions: +- avg_two(a, b): Calculates and returns the average of two numbers, displaying additional information due to the decorator. +- avg_three(a, b, c): Computes the average of three numbers, with additional prints from the decorator. +- avg_many_kwargs(**kwargs): Finds the average of multiple numbers passed as keyword arguments, also showing argument details through the decorator. +''' \ No newline at end of file diff --git a/foods.py b/foods.py new file mode 100644 index 0000000..a4ebacc --- /dev/null +++ b/foods.py @@ -0,0 +1,30 @@ +#my_foods = ['pizza', 'falafal', 'carrot cake'] +#friends_foods = my_foods[:] +#print("My favorite foods are:") +#print(my_foods) +#print("\nMy friend's favorite foods are:") +#print(friends_foods) + +# Now, we add an item to each list and check to see if each list is correct + +my_foods = ['pizza', 'falafal', 'carrot cake'] +friends_foods = ['pizza', 'falafal' 'carrot cake'] + +# This doesn't work + +#friends_foods = my_foods + +# Instead, use the slice when copying the lists + +friends_foods = my_foods[:] + +my_foods.append('cannoli') +friends_foods.append('ice cream') + +print("My favorite foods are:") +print(my_foods) + +print("\nMy friend's favorite foods are:") +print(friends_foods) + + diff --git a/full_name.py b/full_name.py new file mode 100644 index 0000000..2b1bce0 --- /dev/null +++ b/full_name.py @@ -0,0 +1,6 @@ +first_name = "ada" +last_name = "lovelace" +full_name = f"{first_name} {last_name}" +print(f"Hello, {full_name.title()}!") + + diff --git a/func_calls_func.py b/func_calls_func.py new file mode 100644 index 0000000..44722b4 --- /dev/null +++ b/func_calls_func.py @@ -0,0 +1,25 @@ +# Dictionary representing the current stock of products +inventory = { + "apples": 17, + "bananas": 75, + "oranges": 2, + "grapes": 50 +} + +# Function to restock items that have low stock levels by adding a specified amount +def restock(product, inventory, restock_amount): + inventory[product] += restock_amount + print(f"Restock order placed for {product}. New stock level: {inventory[product]} units.") + +# Function to check which items are below the stock threshold and trigger the `restock` function +def check_stock_levels(inventory, threshold): + for product, quantity in inventory.items(): + if quantity < threshold: + # If the stock is below the threshold, call the `restock` function to add 50 units + restock(product, inventory, 50) + +# Checking the stock levels for all products in the inventory with a threshold of 30 units +check_stock_levels(inventory, 30) + +# Display the final inventory after restocking +print("Final inventory status:", inventory) \ No newline at end of file diff --git a/generators.py b/generators.py new file mode 100644 index 0000000..d9a9512 --- /dev/null +++ b/generators.py @@ -0,0 +1,63 @@ +import time + +def my_generator(): + yield 3 + yield 2 + yield 1 + +for value in my_generator(): + print(value) + + +# Using next() to manually iterate through the generator +g = my_generator() +print(next(g)) # Output: 1 +print(next(g)) # Output: 2 +print(next(g)) # Output: 3 + +print(sum(my_generator())) # Output: 6 +print(sorted(my_generator())) # Output: [1, 2, 3] + +def countdown(n): + while n > 0: + yield n + n -= 1 + +for number in countdown(4): + print(number) + time.sleep(1) # Pause for 1 second between numbers + +# Example of a generator function to yield first n numbers +def firstn(n): + num = 0 + while num < n: + yield num + num += 1 + +# calling firstn(): +for number in firstn(10): + print(number) + + +print(sum(firstn(100))) # Output: 4950 + + +# Example of a generator expression +squared = (x * x for x in range(10)) +for num in squared: + print(num) + +# Fibonacci sequence generator +def fibonacci(n): + a, b = 0, 1 + for _ in range(n): + yield a + a, b = b, a + b + +for num in fibonacci(30): + print(num) + +print(list(fibonacci(30))) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] + + + \ No newline at end of file diff --git a/global_variables.py b/global_variables.py new file mode 100644 index 0000000..e5df3d5 --- /dev/null +++ b/global_variables.py @@ -0,0 +1,47 @@ + + +""" +This script demonstrates the use of global variables and the `global` keyword in Python functions. +Global Variables: +- `age`: An integer representing a person's age. +Functions: +- birthday_greet(): + - First definition: Prints a birthday greeting using the global `age` variable, incremented by 1 (without modifying the global variable). + - Second definition: Uses the `global` keyword to modify the global `age` variable by incrementing it by 1, then prints a birthday greeting. +- birthday_greet_global(): + - First definition: Prints a birthday greeting using the global `age` variable, incremented by 5 (without modifying the global variable). + - Second definition: Uses the `global` keyword to modify the global `age` variable by incrementing it by 5, then prints a birthday greeting. +Demonstrates: +- The difference between accessing and modifying global variables inside functions. +- The effect of the `global` keyword on variable scope and assignment. +""" +age = 24 + +def birthday_greet(): + print(f"Happy B-Day! You are {age + 1}! (local message)") + +birthday_greet() # Call the local function +print("Global message", age) # Print the global variable + +def birthday_greet_global(): + print(f"Happy B-Day! You are {age + 5}! (global message)") +birthday_greet_global() # Call the global function + + + +age = 20 + +def birthday_greet(): + global age # Added 'global' keyword + age += 1 + print(f"Happy B-Day! You are {age}! (local message)") + +birthday_greet() +print("Global message", age) + +def birthday_greet_global(): + global age # Added 'global' keyword + age += 5 + print(f"Happy B-Day! You are {age}! (global message)") + +birthday_greet_global() # Call the global function \ No newline at end of file diff --git a/high-order_functions.py b/high-order_functions.py new file mode 100644 index 0000000..6dad97f --- /dev/null +++ b/high-order_functions.py @@ -0,0 +1,50 @@ +# File: OneDrive/Documents/Python%20Code/using_kwargs.py +# Using map to apply a function to each item in an iterable +def square(x): + return x * x + +numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # List of numbers from 1 to 10 +squared_numbers = map(square, numbers) + +# Convert the map object to a list +squared_numbers_list = list(squared_numbers) +print(squared_numbers_list) + +# Using map to cube numbers +def cube(x): + return x * x * x + +cubed_numbers = map(cube, numbers) +cubed_numbers_list = list(cubed_numbers) +print(cubed_numbers_list) + +# Using filter to filter out even numbers +def is_even(x): + return x % 2 == 0 + +even_numbers = filter(is_even, numbers) +even_numbers_list = list(even_numbers) +print(even_numbers_list) +# Using filter to filter out odd numbers +def is_odd(x): + return x % 2 != 0 + +odd_numbers = filter(is_odd, numbers) +odd_numbers_list = list(odd_numbers) +print(odd_numbers_list) + +# Step 1: Define the list of temperatures in Celsius +temp_celsius = [-40, 0, 25, 30, 40, 100] + +# Step 2: Define a custom function to convert Celsius to Fahrenheit +def celsius_to_fahrenheit(celsius): + """Convert temperature from Celsius to Fahrenheit.""" + fahrenheit = (celsius * 9/5) + 32 + return fahrenheit + +# Step 3: Use map() with the custom function +temp_fahrenheit = map(celsius_to_fahrenheit, temp_celsius) + +# Step 4: Convert the map object to a list and print +temp_fahrenheit_list = list(temp_fahrenheit) +print(temp_fahrenheit_list) diff --git a/item_class.py b/item_class.py new file mode 100644 index 0000000..5e70709 --- /dev/null +++ b/item_class.py @@ -0,0 +1,170 @@ +class item: + def __init__(self, name: str, price: float, quantity=0): + # Run validations to the received arguments + assert price >= 0, f"Price {price} is not greater than or equal to zero!" + assert quantity >= 0, f"Quantity {quantity} is not greater than or equal to zero!" + + # Assign to self object + self.name = name + self.price = price + self.quantity = quantity + + def calculate_total_price(self): + return self.price * self.quantity + + def apply_discount(self, discount): + self.price = self.price * (1 - discount) + assert self.price >= 0, f"Price {self.price} is not greater than or equal to zero!" + return self.price + + def __repr__(self): + return f"item('{self.name}', {self.price}, {self.quantity})" + + def __str__(self): + return f"Item: {self.name}, Price: {self.price}, Quantity: {self.quantity}" + + @property + def name(self): + return self._name + + @property + def price(self): + return self._price + + @property + def quantity(self): + return self._quantity + @name.setter + def name(self, value): + if len(value) > 10: + raise Exception("The name is too long!") + else: + self._name = value + + @price.setter + def price(self, value): + if value < 0: + raise Exception("Price cannot be negative!") + else: + self._price = value + + @quantity.setter + def quantity(self, value): + if value < 0: + raise Exception("Quantity cannot be negative!") + else: + self._quantity = value + + @classmethod + def instantiate_from_csv(cls, filename): + import csv + with open(filename, 'r') as f: + reader = csv.DictReader(f) + items = list(reader) + for item in items: + item['price'] = float(item['price']) + item['quantity'] = int(item['quantity']) + return [cls(**item) for item in items] + @staticmethod + def is_integer(num): + # We will count out the floats that are point zero + if isinstance(num, float): + # Count out the floats that are point zero + return num.is_integer() + elif isinstance(num, int): + return True + else: + return False + def __add__(self, other): + if isinstance(other, item): + return self.quantity + other.quantity + else: + raise Exception("You cannot add these two objects") + def __radd__(self, other): + return self.__add__(other) + def __mul__(self, other): + if isinstance(other, (int, float)): + return self.price * other + else: + raise Exception("You cannot multiply these two objects") + def __rmul__(self, other): + return self.__mul__(other) + def __eq__(self, other): + if isinstance(other, item): + return self.price == other.price and self.quantity == other.quantity + else: + return False + def __lt__(self, other): + if isinstance(other, item): + return self.price < other.price + else: + raise Exception("You cannot compare these two objects") + def __le__(self, other): + if isinstance(other, item): + return self.price <= other.price + else: + raise Exception("You cannot compare these two objects") + def __gt__(self, other): + if isinstance(other, item): + return self.price > other.price + else: + raise Exception("You cannot compare these two objects") + def __ge__(self, other): + if isinstance(other, item): + return self.price >= other.price + else: + raise Exception("You cannot compare these two objects") + + def __ne__(self, other): + if isinstance(other, item): + return self.price != other.price or self.quantity != other.quantity + else: + return True + def __hash__(self): + return hash((self.name, self.price, self.quantity)) + def __bool__(self): + return self.quantity > 0 + def __len__(self): + return len(self.name) + def __getitem__(self, index): + return self.name[index] + def __setitem__(self, index, value): + name_list = list(self.name) + name_list[index] = value + self.name = ''.join(name_list) + def __delitem__(self, index): + name_list = list(self.name) + del name_list[index] + self.name = ''.join(name_list) + def __contains__(self, item): + return item in self.name + def __dir__(self): + return ['name', 'price', 'quantity', 'calculate_total_price', 'apply_discount', 'instantiate_from_csv', 'is_integer'] + def __format__(self, format_spec): + if format_spec == 'name': + return self.name + elif format_spec == 'price': + return f"{self.price:.2f}" + elif format_spec == 'quantity': + return str(self.quantity) + else: + return str(self) + def __getstate__(self): + return self.__dict__ + def __setstate__(self, state): + self.__dict__.update(state) + def __copy__(self): + return item(self.name, self.price, self.quantity) + def __deepcopy__(self, memo): + from copy import deepcopy + return item(deepcopy(self.name, memo), deepcopy(self.price, memo), deepcopy(self.quantity, memo)) + def __reversed__(self): + return item(self.name[::-1], self.price, self.quantity) + # The following methods are already defined above, so they should not be duplicated. + # Remove the duplicate definitions to avoid syntax errors and keep only one implementation. + + # (No code needed here, as the correct implementations are already present earlier in the class.) +example = item("Example", 10.0, 5) +print(example) # Output: Item: Example, Price: 10.0, Quantity: 5 +print(repr(example)) # Output: item('Example', 10.0, 5) +print(example.calculate_total_price()) # Output: 50.0 \ No newline at end of file diff --git a/kargs_in_dynamic_funcs.py b/kargs_in_dynamic_funcs.py new file mode 100644 index 0000000..4334477 --- /dev/null +++ b/kargs_in_dynamic_funcs.py @@ -0,0 +1,21 @@ +def personal_info(name, **kwargs): + print(f"Name: {name}") + for key, value in kwargs.items(): + print(f"{key.capitalize()}: {value}") + + + """ + Prints personal information including a required name and any number of additional keyword arguments. + Args: + name (str): The person's name. + **kwargs: Arbitrary keyword arguments representing additional personal information (e.g., surname, son, cats, breed). + kwargs.key is capitalized in the output. + Returns: + None + """ +# Example usage of the personal_info function +personal_info("Sarah", surname="Conor", son="John") +personal_info("Natalie", cats="3", breed="Maine Coon") +personal_info("John", surname="Doe", age=30, city="New York", occupation="Engineer") +personal_info("Alice", hobbies="reading, hiking", favorite_color="blue") + diff --git a/keyword_arguments_in_func_exercise.py b/keyword_arguments_in_func_exercise.py new file mode 100644 index 0000000..929a394 --- /dev/null +++ b/keyword_arguments_in_func_exercise.py @@ -0,0 +1,18 @@ +def apply_discount(price, discount=0.05): + discounted_price = price * (1 - discount) + return discounted_price + +def apply_tax(price, tax=0.07): + price_with_tax = price * (1 + tax) + return price_with_tax + +def calculate_total(price, discount=0.05, tax=0.07): + discounted_price = apply_discount(price, discount) + discounted_price_with_tax = apply_tax(discounted_price, tax) + return discounted_price_with_tax + +total_price_with_defaults = calculate_total(120) +total_price_with_custom_values = calculate_total(100, discount=0.10, tax=0.08) + +print(f"Total cost with default discount and tax: ${total_price_with_defaults}") +print(f"Total cost with custom discount and tax: ${total_price_with_custom_values}") \ No newline at end of file diff --git a/keyword_arguments_in_func_solution.py b/keyword_arguments_in_func_solution.py new file mode 100644 index 0000000..ec84ddf --- /dev/null +++ b/keyword_arguments_in_func_solution.py @@ -0,0 +1,28 @@ +# Task 1: Define a function to apply a discount with a default discount value of 5% +def apply_discount(price, discount=0.05): + # Calculate and return the discounted price + return price * (1 - discount) + +# Task 2: Define a function to apply tax with a default tax rate of 7% +def apply_tax(price, tax=0.07): + # Calculate and return the price with tax + return price * (1 + tax) + +# Task 3: Define a function to calculate the total price by applying both discount and tax +def calculate_total(price, discount=0.05, tax=0.07): + # Apply the discount first + discounted_price = apply_discount(price, discount) + + # Apply tax on the discounted price + final_price = apply_tax(discounted_price, tax) + + # Return the final total price + return final_price + +# Task 4: Call `calculate_total` using only the default discount and tax values +total_price_default = calculate_total(120) +print(f"Total cost with default discount and tax: ${total_price_default}") + +# Task 5: Call `calculate_total` with a custom discount of 10% and a custom tax of 8% +total_price_custom = calculate_total(100, discount=0.10, tax=0.08) +print(f"Total cost with custom discount and tax: ${total_price_custom}") \ No newline at end of file diff --git a/keyword_arguments_in_funcs.py b/keyword_arguments_in_funcs.py new file mode 100644 index 0000000..92b52fe --- /dev/null +++ b/keyword_arguments_in_funcs.py @@ -0,0 +1,8 @@ +# Function where `tax` has a default value +def calculate_total(price, discount, tax=0.05): + total = price * (1 + tax) * (1 - discount) + return total + +# Calling the function using keyword arguments +total_cost = calculate_total(price=100, discount=0.15) +print(f"Total cost after applying discount: ${total_cost}") \ No newline at end of file diff --git a/lambda_funcs_with_built-ins.py b/lambda_funcs_with_built-ins.py new file mode 100644 index 0000000..c78e17c --- /dev/null +++ b/lambda_funcs_with_built-ins.py @@ -0,0 +1,46 @@ +numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + +# Using a lambda function to filter out odd numbers +even_numbers = filter(lambda x: x % 2 == 0, numbers) + +# Convert the filter object to a list +even_numbers_list = list(even_numbers) +print(even_numbers_list) + + +tuples = [(1, 'banana'), (2, 'apple'), (3, 'orange'), (4, 'grape')] + +# Using a lambda function to sort a list of tuples in descending order by the second element +sorted_tuples = sorted(tuples, key=lambda x: x[1], reverse=True) +print(sorted_tuples) + + +# Using a lambda function to sort a list of tuples in ascending order by the second element +sorted_tuples = sorted(tuples, key=lambda x: x[1], reverse=False) +print(sorted_tuples) + + +# Using a lambda function to sort a list of tuples in descending order by the first element +sorted_tuples = sorted(tuples, key=lambda x: x[0], reverse=True) +print(sorted_tuples) + + +# Step 1: Define the list of books +books = [ + {"title": "Harry Potter and the Deathly Hallows", "pages": 640}, + {"title": "Rich Dad Poor Dad", "pages": 336}, + {"title": "The Great Gatsby", "pages": 160}, + {"title": "The Hobbit", "pages": 400} +] + +# Step 2: Create a custom function +def has_many_pages(book, min_pages=350): + """Check if the book has more than min_pages.""" + return book["pages"] > min_pages + +# Step 3: Use filter() with the custom function +filtered_books = filter(lambda book: has_many_pages(book), books) + +# Convert the filter object to a list and print +filtered_books_list = list(filtered_books) +print(filtered_books_list) diff --git a/lambda_with_lists.py b/lambda_with_lists.py new file mode 100644 index 0000000..c11d7a2 --- /dev/null +++ b/lambda_with_lists.py @@ -0,0 +1,10 @@ +def apply_func(func, list_of_lists): + return [func(*args) for args in zip(*list_of_lists)] + +# Example usage: +if __name__ == "__main__": + list1 = [1, 2, 3] + list2 = [4, 5, 6] + result = apply_func(lambda x, y: x + y, [list1, list2]) + print(result) + diff --git a/layers.py b/layers.py new file mode 100644 index 0000000..dee2463 --- /dev/null +++ b/layers.py @@ -0,0 +1,46 @@ +import numpy as np + +np.random.seed(10) + + +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) + + +class Layer: + def __init__(self, n_inputs, n_neurons, activation_function): + self.inputs = np.zeros((n_inputs, 1)) + self.outputs = np.zeros((n_neurons, 1)) + self.weights = np.random.uniform(-1, 1, (n_neurons, n_inputs)) + self.biases = np.random.uniform(-1, 1, (n_neurons, 1)) + self.activation = activation_function + + def forward(self, inputs): + self.inputs = np.array(inputs).reshape(-1, 1) + self.outputs = np.dot(self.weights, self.inputs) + self.biases + return self.activation(self.outputs) + + +relu = ReLU() +sigmoid = Sigmoid() + +input_size = 2 +hidden_size = 3 +output_size = 1 + +hidden_1 = Layer(input_size, hidden_size, relu) +hidden_2 = Layer(hidden_size, hidden_size, relu) +output_layer = Layer(hidden_size, output_size, sigmoid) diff --git a/layers.py.py b/layers.py.py new file mode 100644 index 0000000..dee2463 --- /dev/null +++ b/layers.py.py @@ -0,0 +1,46 @@ +import numpy as np + +np.random.seed(10) + + +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) + + +class Layer: + def __init__(self, n_inputs, n_neurons, activation_function): + self.inputs = np.zeros((n_inputs, 1)) + self.outputs = np.zeros((n_neurons, 1)) + self.weights = np.random.uniform(-1, 1, (n_neurons, n_inputs)) + self.biases = np.random.uniform(-1, 1, (n_neurons, 1)) + self.activation = activation_function + + def forward(self, inputs): + self.inputs = np.array(inputs).reshape(-1, 1) + self.outputs = np.dot(self.weights, self.inputs) + self.biases + return self.activation(self.outputs) + + +relu = ReLU() +sigmoid = Sigmoid() + +input_size = 2 +hidden_size = 3 +output_size = 1 + +hidden_1 = Layer(input_size, hidden_size, relu) +hidden_2 = Layer(hidden_size, hidden_size, relu) +output_layer = Layer(hidden_size, output_size, sigmoid) diff --git a/len.py b/len.py new file mode 100644 index 0000000..2eaa623 --- /dev/null +++ b/len.py @@ -0,0 +1,4 @@ +cars = ["audi", "BMW", "Toyota", "Fiat"] +print(f"{len(cars)}") + + diff --git a/linear_algebra.py b/linear_algebra.py new file mode 100644 index 0000000..d96ca97 --- /dev/null +++ b/linear_algebra.py @@ -0,0 +1,59 @@ +import numpy as np +""" +This script demonstrates basic linear algebra operations using NumPy, including: +1. Matrix transposition. +2. Dot product of vectors using both np.dot() and the @ operator. +3. Matrix multiplication using both np.dot() and the @ operator. +4. Calculation of weighted final scores for students based on exam scores and subject coefficients. +Sections: +- Matrix and vector creation and display. +- Transposing matrices. +- Dot product and matrix multiplication. +- Application example: computing weighted final scores for students. +Variables: +- matrix: 2D NumPy array representing a matrix. +- transposed_matrix: Transposed version of 'matrix'. +- vector_1, vector_2: 1D NumPy arrays representing vectors. +- matrix_1, matrix_2: 2D NumPy arrays for matrix multiplication. +- exams_scores: 2D NumPy array of students' exam scores. +- coefficients: 1D NumPy array of subject weights. +- final_scores: 1D NumPy array of weighted final scores for each student. +""" + +matrix = np.array([[1, 2, 3], [4, 5, 6]]) +print(f'Original matrix:\n{matrix}') +# Transposing a matrix +transposed_matrix = matrix.T +print(f'\nTransposed matrix:\n{transposed_matrix}') + + +vector_1 = np.array([1, 2, 3]) +print(f'\nVector 1: {vector_1}') +vector_2 = np.array([4, 5, 6]) +print(f'Vector 2: {vector_2}') +# Dot product using the dot() function +print(f'\nDot product (dot function): {np.dot(vector_1, vector_2)}') +# Dot product using the @ operator +print(f'Dot product (@ operator): {vector_1 @ vector_2}') +matrix_1 = np.array([[1, 2, 3], [4, 5, 6]]) +print(f'\nMatrix 1:\n{matrix_1}') +matrix_2 = np.array([[7, 10], [8, 11], [9, 12]]) +print(f'\nMatrix 2:\n{matrix_2}') +# Matrix multiplication using the dot() function +print(f'\nMatrix multiplication (dot function):\n{np.dot(matrix_1, matrix_2)}') +# Matrix multiplication using the @ operator +print(f'\nMatrix multiplication (@ operator):\n{matrix_1 @ matrix_2}') + + +# Task: Simulated exams scores of three students from three subjects +exams_scores = np.array([[100, 82, 95], [56, 70, 90], [45, 98, 66]]) +print +coefficients = np.array([0.5, 0.3, 0.2]) +print(f'\nExams scores:\n{exams_scores}') +print(f'Coefficients:\n{coefficients}') +# Calculate the dot product between exam_scores and coefficients +final_scores = np.dot(exams_scores, coefficients) +print(f'\nFinal scores (dot function):\n{final_scores}') + +final_scores = (exams_scores @ coefficients) +print(f'\nFinal scores (@ operator):\n{final_scores}') \ No newline at end of file diff --git a/magic_number.py b/magic_number.py new file mode 100644 index 0000000..df0bf46 --- /dev/null +++ b/magic_number.py @@ -0,0 +1,4 @@ +answer = 17 +if answer != 42: + print('That is not the correct answer. Please try again!') + diff --git a/magicians.py b/magicians.py new file mode 100644 index 0000000..655d030 --- /dev/null +++ b/magicians.py @@ -0,0 +1,6 @@ +magicians = ["david", "alice", "carolina"] +for magician in magicians: + #print(magician) + print(f"{magician.title()}, that was a great trick!") + print(f"I can't wait to see your next trick, {magician.title()}. \n") +print("Thank you, everyone, that was a great magic show!") \ No newline at end of file diff --git a/many_users.py b/many_users.py new file mode 100644 index 0000000..3338b95 --- /dev/null +++ b/many_users.py @@ -0,0 +1,26 @@ +users = { + 'aeinstein': { + 'first': 'albert', + 'last': 'einstein', + 'location': 'princeton', + }, + + 'mcurie': { + 'first': 'marie', + 'last': 'curie', + 'location': 'paris', + }, + + 'datapioneer': { + 'first': 'Dan', + 'last': 'Calloway', + 'location': 'Asheville', + }, +} + +for username, user_info in users.items(): + print(f"\nUsername: {username}") + full_name = f"{user_info['first']} {user_info['last']}" + location = user_info['location'] + print(f"\tFull Name: {full_name.title()}") + print(f"\tLocation: {location.title()}") \ No newline at end of file diff --git a/matrix_class.py b/matrix_class.py new file mode 100644 index 0000000..e7a101e --- /dev/null +++ b/matrix_class.py @@ -0,0 +1,73 @@ +import numpy as np + +class Matrix: + def __init__(self, rows, cols): + self.rows = rows + self.cols = cols + self.data = [[0] * cols for _ in range(rows)] + + def set_value(self, row, col, value): + if 0 <= row < self.rows and 0 <= col < self.cols: + self.data[row][col] = value + else: + raise IndexError("Index out of bounds") + + def get_value(self, row, col): + if 0 <= row < self.rows and 0 <= col < self.cols: + return self.data[row][col] + else: + raise IndexError("Index out of bounds") + + def __str__(self): + return '\n'.join([' '.join(map(str, row)) for row in self.data]) + + def __mul__(self, other): + if self.cols != other.rows: + raise ValueError("Cannot multiply: incompatible dimensions") + result = Matrix(self.rows, other.cols) + for i in range(self.rows): + for j in range(other.cols): + for k in range(self.cols): + result.data[i][j] += self.data[i][k] * other.data[k][j] + return result + + +myMatrix = Matrix(3, 4) +myOtherMatrix = Matrix(4, 3) + # This will raise an error since multiplication is not defined +multMatrix = myMatrix * myOtherMatrix +print(multMatrix) +# Output: 1 0 0 0 +# 0 2 0 0 +# 0 0 3 0 + +matrix_2d = np.full((3, 3), 5) +print(f'3x3 matrix filled with 5:\n{matrix_2d}') + +# Create a 5x5 identity matrix +matrix_identity = np.eye(5) +print(f'5x5 identity matrix:\n{matrix_identity}') + +#create a 5x1 column vector +column_vector = np.full((5, 1), 3) +print(f'5x1 column vector:\n{column_vector}') + +def __multiply__(matrix1, matrix2): + return matrix1 * matrix2 +# Creating a 2D matrix using the Matrix class +myMatrix = Matrix(2, 2) +# Setting values in the matrix +myMatrix.set_value(0, 0, 1) +myMatrix.set_value(0, 1, 4) +myMatrix.set_value(1, 0, -3) +myMatrix.set_value(1, 1, 2) + +myOtherMatrix = Matrix(2, 2) +myOtherMatrix.set_value(0, 0, -5) +myOtherMatrix.set_value(0, 1, 6) +myOtherMatrix.set_value(1, 0, 7) +myOtherMatrix.set_value(1, 1, -8) + +# Example usage of the Matrix multiply class +result = __multiply__(myMatrix, myOtherMatrix) +print(f'Result of multiplying myMatrix and myOtherMatrix:\n{result}') diff --git a/merge_arrays.py b/merge_arrays.py new file mode 100644 index 0000000..cb7da07 --- /dev/null +++ b/merge_arrays.py @@ -0,0 +1,13 @@ +def merge_arrays(arr1, arr2): + # 1. Merge the two arrays + # 2. Remove duplicates + # 3. Sort the list in ascending order + return sorted(set(arr1 + arr2)) + + +a = list(range(0, 10, 2)) +b = list(range(2, 21, 3)) +print(a) +print(b) +print(merge_arrays(a, b)) + diff --git a/modify_data_structure.py b/modify_data_structure.py new file mode 100644 index 0000000..12d057d --- /dev/null +++ b/modify_data_structure.py @@ -0,0 +1,25 @@ +# Define the function that adjusts inventory levels +def update_inventory(inventory, items_sold): + # Iterate over each item in the dictionary + for product, quantity_sold in items_sold.items(): + # Decrease the inventory by the quantity sold for each product + inventory[product] -= quantity_sold + +# Inventory dictionary +inventory = { + "apples": 50, + "bananas": 75, + "oranges": 100 +} + +# Items sold dictionary +items_sold = { + "apples": 5, + "oranges": 15 +} + +# Update the inventory based on items sold +update_inventory(inventory, items_sold) + +# Display the updated inventory +print("Updated inventory:", inventory) \ No newline at end of file diff --git a/modify_global_var_in_func.py b/modify_global_var_in_func.py new file mode 100644 index 0000000..d37d93d --- /dev/null +++ b/modify_global_var_in_func.py @@ -0,0 +1,8 @@ +global_var = 10 + +def modify_global(): + global global_var + global_var += 5 + +modify_global() +print("Modified global variable:", global_var) \ No newline at end of file diff --git a/modifying_a_tuple.py b/modifying_a_tuple.py new file mode 100644 index 0000000..e499aa0 --- /dev/null +++ b/modifying_a_tuple.py @@ -0,0 +1,11 @@ +dimensions = (200, 50) +print("Original dimensions:") +for dimension in dimensions: + print(dimension) + +dimensions = (400, 50) +print("\nModified dimensions") +for dimension in dimensions: + print(dimension) + + \ No newline at end of file diff --git a/motorcycles.py b/motorcycles.py new file mode 100644 index 0000000..2125928 --- /dev/null +++ b/motorcycles.py @@ -0,0 +1,75 @@ +# creating a list of motorcycles, then printing the list + +#motorcycles = ['honda', 'yamaha', 'suzuki'] +#print(motorcycles) + +# printing the first element in the list + +#motorcycles[0] = 'ducati' +#print(motorcycles) + +# appending a new item to the list + +#motorcycles.append('ducati') +#print(motorcycles) + +# starting with an empty list, then adding to it using a series of append +# statements + +#motorcycles = [] +#motorcycles.append('honda') +#motorcycles.append('yamaha') +#motorcycles.append('suzuki') +#print(motorcycles) + +# inserting an element at the beginning of a list + +#motorcycles = ['honda', 'yamaha', 'suzuki'] +#motorcycles.insert(0, 'ducati') +#print(motorcycles) + +# deleting an element from a list; in the example below, we're deleting the 2nd element from the list of motorcycles + +#motorcycles = ['honda', 'yamaha', 'suzuki'] +#del motorcycles[1] +#print(motorcycles) + +# popping an element from the end of a list, then being able to use that element afterwards + +#motorcycles = ['honda', 'yamaha', 'suzuki'] +#print(motorcycles) +#popped_motorcycles = motorcycles.pop() +#print(popped_motorcycles) + +# printing the last-owned motorcycle as a statement + +#motorcycles = ['honda', 'yamaha', 'suzuki'] +#last_owned = motorcycles.pop() +#print(f"The last motorcycle I owned was a {last_owned}.") + + +# printing the first-owned motorcycle as a statement + +#motorcycles = ['honda', 'yamaha', 'suzuki'] +#first_owned = motorcycles.pop(0) +#print(f"The first motorcycle I owned was a {first_owned}.") + +# removing an item from a list based on its value rather than its position + +#motorcycles = ['honda', 'yamaha', 'ducati', 'suzuki'] +#print(motorcycles) +#motorcycles.remove('ducati') +#print(motorcycles) + +# printing a statement about a particular element of a motorcycle list that's too expensive for the owner + +motorcycles = ['honda', 'yamaha', 'ducati', 'suzuki'] +print(motorcycles) +too_expensive = 'ducati' +motorcycles.remove(too_expensive) +print(motorcycles) +print(f"\nThe {too_expensive.title()} is just too expensive for me.") + + + + diff --git a/mult.py b/mult.py new file mode 100644 index 0000000..842af4a --- /dev/null +++ b/mult.py @@ -0,0 +1,25 @@ +# Multiprocessing: Sharing data between processes (a Value or Array memory share must be created as processes do not share data by default + +from multiprocessing import Process, Value, Array, Lock +import os +import time + +def add_100(number, lock): + for _ in range(100): + time.sleep(0.01) + with lock: + number.value += 1 + print(f'Process {os.getpid()} has finished execution.') + +if __name__ == "__main__": + lock = Lock() + shared_number = Value('i', 0) + + print('Number at the beginning is: ', shared_number.value) + p1 = Process(target=add_100, args=(shared_number, lock)) + p2 = Process(target=add_100, args=(shared_number, lock)) + p1.start() + p2.start() + p1.join() + p2.join() + print('Number at the end is: ', shared_number.value) \ No newline at end of file diff --git a/mult_array.py b/mult_array.py new file mode 100644 index 0000000..efe429d --- /dev/null +++ b/mult_array.py @@ -0,0 +1,25 @@ +# Multiprocessing: Sharing data between processes (a Value or Array memory share must be created as processes do not share data by default) +from multiprocessing import Process, Value, Array, Lock +import os +import time + +def add_100(numbers, lock): + for _ in range(100): + time.sleep(0.01) + for i in range(len(numbers)): + with lock: + numbers[i] += 1 + print(f'Process {os.getpid()} has finished execution.') + +if __name__ == "__main__": + lock = Lock() + shared_array = Array('d', [0.0, 100.0, 200.0, 300.0, 400.0]) + + print('Array at the beginning is: ', list(shared_array)) + p1 = Process(target=add_100, args=(shared_array, lock)) + p2 = Process(target=add_100, args=(shared_array, lock)) + p1.start() + p2.start() + p1.join() + p2.join() + print('Array at the end is: ', list(shared_array)) \ No newline at end of file diff --git a/mult_with_pool.py b/mult_with_pool.py new file mode 100644 index 0000000..1da34af --- /dev/null +++ b/mult_with_pool.py @@ -0,0 +1,17 @@ +# Multiprocessing: Sharing data between processes (a Value or Array memory share must be created as processes do not share data by default) +from multiprocessing import Pool + +def cube(number): + return number * number * number + + +if __name__ == "__main__": + + # pool methods most often used: map, apply, close, join + pool = Pool() + + numbers = range(21) + results = pool.map(cube, numbers) + pool.close() + pool.join() + print('Cubed results: ', results) diff --git a/mult_with_queue.py b/mult_with_queue.py new file mode 100644 index 0000000..b3b6819 --- /dev/null +++ b/mult_with_queue.py @@ -0,0 +1,30 @@ +# Multiprocessing: Sharing data between processes (a Value or Array memory share must be created as processes do not share data by default) +from multiprocessing import Process, Value, Array, Lock +from multiprocessing import Queue +import os +import time + +def add_100(numbers, lock, queue): + for _ in range(100): + time.sleep(0.01) + for i in range(len(numbers)): + with lock: + numbers[i] += 1 + queue.put(list(numbers)) + print(f'Process {os.getpid()} has finished execution.') + +if __name__ == "__main__": + lock = Lock() + shared_array = Array('d', [0.0, 100.0, 200.0, 300.0, 400.0]) + queue = Queue() + + print('Array at the beginning is: ', list(shared_array)) + p1 = Process(target=add_100, args=(shared_array, lock, queue)) + p2 = Process(target=add_100, args=(shared_array, lock, queue)) + p1.start() + p2.start() + p1.join() + p2.join() + print('Array at the end is: ', list(shared_array)) + while not queue.empty(): + print('Process output: ', queue.get()) \ No newline at end of file diff --git a/multi-layer-perceptron.py b/multi-layer-perceptron.py new file mode 100644 index 0000000..4ac043c --- /dev/null +++ b/multi-layer-perceptron.py @@ -0,0 +1,56 @@ +import numpy as np +import os + +from activations import relu, sigmoid + +# Fix the seed for reproducibility +np.random.seed(10) + +class Layer: + def __init__(self, n_inputs, n_neurons, activation_function): + self.inputs = np.zeros((n_inputs, 1)) + self.outputs = np.zeros((n_neurons, 1)) + # 1. Initialize the weight matrix and the bias vector with random values + self.weights = np.random.uniform(-1, 1, (n_neurons, n_inputs)) + self.biases = np.random.uniform(-1, 1, (n_neurons, 1)) + self.activation = activation_function + + def forward(self, inputs): + self.inputs = np.array(inputs).reshape(-1, 1) + # 2. Compute the raw output values of the neurons + self.outputs = np.dot(self.weights, self.inputs) + self.biases + # 3. Apply the activation function + return self.activation(self.outputs) + +class Perceptron: + def __init__(self, layers): + self.layers = layers + +input_size = 2 +hidden_size = 6 +output_size = 1 + + +# 4. Define three layers: 2 hidden layers and 1 output layer +hidden_1 = Layer(input_size, hidden_size, relu) +hidden_2 = Layer(hidden_size, hidden_size, relu) +output_layer = Layer(hidden_size, output_size, sigmoid) + +layers = [hidden_1, hidden_2, output_layer] +perceptron = Perceptron(layers) + +print("Weights of the third neuron in the second hidden layer:") +print(np.round(perceptron.layers[1].weights[2], 2)) + +print("Weights of the neuron in the output layer:") +print(np.round(perceptron.layers[2].weights[0], 2)) + +''' +How it works: +# The perceptron consists of multiple layers, each with its own weights and biases. The forward method computes the output of each +# layer by applying the activation function to the weighted sum of inputs. The weights and biases are initialized randomly, and +# the perceptron can be used to process inputs through its layers. +# The output of the second hidden layer and the output layer can be accessed through the perceptron's layers attribute. +# The weights of the third neuron in the second hidden layer and the output layer are printed, showing how the perceptron is structured. + +''' \ No newline at end of file diff --git a/multi_layer_network.py b/multi_layer_network.py new file mode 100644 index 0000000..55ad550 --- /dev/null +++ b/multi_layer_network.py @@ -0,0 +1,27 @@ +import numpy as np +import os +os.system('wget https://codefinity-content-media.s3.eu-west-1.amazonaws.com/f9fc718f-c98b-470d-ba78-d84ef16ba45f/section_2/layers.py 2>/dev/null') +from layers import hidden_1, hidden_2, output_layer + +# Fix the seed of the "random" library, so it will be easier to test our code +np.random.seed(10) + +class Perceptron: + def __init__(self, layers): + self.layers = layers + + def forward(self, inputs): + x = inputs + # 1. Iterate over the layers + for layer in self.layers: + # 2. Pass x layer by layer + x = layer.forward(x) + # 3. Return the result + return x + +layers = [hidden_1, hidden_2, output_layer] +perceptron = Perceptron(layers) +# Testing the perceptron with two inputs: 1 and 0 +inputs = [1, 0] +print(f'Inputs: {inputs}') +print(f'Outputs: {perceptron.forward(inputs)[0, 0]:.2f}') \ No newline at end of file diff --git a/multiple_aliens.py b/multiple_aliens.py new file mode 100644 index 0000000..3c63788 --- /dev/null +++ b/multiple_aliens.py @@ -0,0 +1,14 @@ +# Make an empty list for storing aliens +aliens = [] +# Make 30 green aliens +for alien_number in range(30): + new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} + aliens.append(new_alien) + # Show the first 5 aliens +for alien in aliens[:5]: + print(alien) +print('...') + +# Show how many aliens have been created +print(f"\nThe total number of aliens is {len(aliens)}") + diff --git a/multiple_aliens_modified.py b/multiple_aliens_modified.py new file mode 100644 index 0000000..73de24b --- /dev/null +++ b/multiple_aliens_modified.py @@ -0,0 +1,27 @@ +# Make an empty list for storing aliens +aliens = [] +# Make 30 green aliens +for alien_number in range(30): + new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} + aliens.append(new_alien) +# Change the characteristics of green aliens +for alien in aliens[:3]: + if alien['color'] == 'green': + alien['color'] = 'yellow' + alien['speed'] = 'medium' + alien['points'] = 10 +for alien in aliens[0:3]: + if alien['color'] == 'green': + alien['color'] = 'yellow' + alien['speed'] = 'medium' + alien['points'] = 10 + elif alien['color'] == 'yellow': + alien['color'] = 'red' + alien['speed'] = 'fast' + alien['points'] = 15 + +# Show the first 5 aliens +for alien in aliens[:5]: + print(alien) + + \ No newline at end of file diff --git a/myCode_1.py b/myCode_1.py new file mode 100644 index 0000000..10bc4cf --- /dev/null +++ b/myCode_1.py @@ -0,0 +1,26 @@ +# Enter a sentence containing only letters of the alphabet and numbers 0-9 and output the morse code equivalent. + +class MorseCode + morse_code: (text) -> + morse_code_map = + a: '.-', b: '-...', c: '-.-.', d: '-..', e: '.' + f: '..-.', g: '--.', h: '....', i: '..', j: '.---' + k: '-.-', l: '.-..', m: '--', n: '-.', o: '---' + p: '.--.', q: '--.-', r: '.-.', s: '...', t: '-' + u: '..-', v: '...-', w: '.--', x: '-..-', y: '-.--' + z: '--..' + '0': '-----', '1': '.----', '2': '..---', '3': '...--' + '4': '....-', '5': '.....', '6': '-....', '7': '--...' + '8': '---..', '9': '----.' + result = [] + for char in text.toLowerCase() + if morse_code_map[char]? + result.push morse_code_map[char] + else if char is ' ' + result.push ' / ' + result.join '' + +s = new MorseCode() +console.log s.morse_code "To be or not to be" + + \ No newline at end of file diff --git a/myCode_2.py b/myCode_2.py new file mode 100644 index 0000000..fdcc9b2 --- /dev/null +++ b/myCode_2.py @@ -0,0 +1,21 @@ +""" +Translate a string of text: letter a becomes z, b becomes y, ..., z becomes a. +""" + +class Translate: + def translation(self, text: str) -> str: + # Create translation table for a-z + import string + table = str.maketrans( + string.ascii_lowercase, + string.ascii_lowercase[::-1] + ) + return text.translate(table) + +# Example usage +if __name__ == "__main__": + t = Translate() + sentence = "Tobeornottobethatisthequestion" + print(t.translation("sentence")) # Output: zyxcba + + \ No newline at end of file diff --git a/name.py b/name.py new file mode 100644 index 0000000..3e77c01 --- /dev/null +++ b/name.py @@ -0,0 +1,7 @@ +name = "ada lovelace" +print(name.title()) + +print(name.upper()) + +print(name.lower()) + diff --git a/name_case.py b/name_case.py new file mode 100644 index 0000000..f3a0b2a --- /dev/null +++ b/name_case.py @@ -0,0 +1,5 @@ +name = "albert einstein" +print(name.upper()) +print(name.lower()) +print(name.title()) + diff --git a/nested_functions.py b/nested_functions.py new file mode 100644 index 0000000..1ca27e0 --- /dev/null +++ b/nested_functions.py @@ -0,0 +1,19 @@ + + +def count_percent(num1, num2, num3): + def inner(num): + return num * 30 / 100 + return (inner(num1), inner(num2), inner(num3)) + +print(count_percent(700, 300, 1000)) + + + +def apply_function(func, *args): + args = (x for x in args) + return map(func, args) + +result = apply_function(lambda x: x * 30 / 100, 700.7, 300.6, 1000.0, 2000.0, 3000.0, 3500.0) +list_result = list(result) +print(list_result) + diff --git a/neural_network_example.py b/neural_network_example.py new file mode 100644 index 0000000..2cbb9f5 --- /dev/null +++ b/neural_network_example.py @@ -0,0 +1,36 @@ +import torch +import torch.nn as nn +import torch.optim as optim + +# Synthetic input and target data +inputs = torch.randn(100, 10) # 100 samples, 10 features each +targets = torch.randn(100, 1) # 100 target values + +class TinyModel(nn.Module): + def __init__(self): + super().__init__() + self.layer1 = nn.Linear(10, 5) + self.relu = nn.ReLU() + self.layer2 = nn.Linear(5, 1) + + def forward(self, x): + x = self.layer1(x) + x = self.relu(x) + x = self.layer2(x) + return x + + model = TinyModel() +loss_fn = nn.MSELoss() +optimizer = optim.SGD(model.parameters(), lr=0.01) + +for epoch in range(200): + outputs = model(inputs) + loss = loss_fn(outputs, targets) + + optimizer.zero_grad() + loss.backward() + optimizer.step() + + if epoch % 20 == 0: + print(f"Epoch {epoch}: Loss = {loss.item():.4f}") + diff --git a/non_local_variables.py b/non_local_variables.py new file mode 100644 index 0000000..f1b4503 --- /dev/null +++ b/non_local_variables.py @@ -0,0 +1,12 @@ +def outer_function(): + outer_var = 10 + + def inner_function(): + nonlocal outer_var # Declare outer_var as nonlocal to modify it + outer_var += 5 + print("Nonlocal variable in inner function:", outer_var) + + inner_function() + print("Nonlocal variable in outer function:", outer_var) + +outer_function() \ No newline at end of file diff --git a/numpy_2D_matrices.py b/numpy_2D_matrices.py new file mode 100644 index 0000000..d7eb458 --- /dev/null +++ b/numpy_2D_matrices.py @@ -0,0 +1,7 @@ +import numpy as np +# Creating a 2x2 identity matrix +identity_matrix = np.eye(2) +print(f'2x2 identity matrix:\n{identity_matrix}') +# Creating a 4x3 matrix with np.eye() +rectangular_matrix = np.eye(4, 3, dtype=np.int8) +print(f'4x3 matrix:\n{rectangular_matrix}') \ No newline at end of file diff --git a/numpy_array.py b/numpy_array.py new file mode 100644 index 0000000..4736237 --- /dev/null +++ b/numpy_array.py @@ -0,0 +1,44 @@ +import numpy as np +# Creating an array from list +array_from_list = np.array([1, 2, 3, 2, 6, 1]) +# Creating an array from tuple +array_from_tuple = np.array((1, 2, 3, 2, 6, 1)) +print(f'Array from list: {array_from_list}') +print(f'Array from tuple: {array_from_tuple}') + +# Explicitly specifying data type +array_with_dtype = np.array([1.5, 2, 3, 2, 6, 1], dtype=float) +print(f'Array with specified dtype: {array_with_dtype.dtype.name}') + +#Higher dimensional arrays +array_2d = np.array([[1, 2, 3], [4, 5, 6]]) +print(f'2D Array:\n{array_2d}') + +#3d array +import numpy as np +# Creating a 3D array +array_3d = np.array([ + [[1, 2, 3], [4, 5, 6], [7, 8, 9]], + [[10, 11, 12], [13, 14, 15], [16, 17, 18]], + [[19, 20, 21], [22, 23, 24], [25, 26, 27]] +]) +print(f'3-dimensional array: \n{array_3d}') + +#arange function +array_arange = np.arange(10) # Creates an array with values from 0 to 9 +print(f'Array using arange: {array_arange}') + +array_arange = np.arange(0, 30, 3) # Creates an array with values from 0 to 29 with step 3 +print(f'Array using arange: {array_arange}') + +# Creating an array of integers from 0 to 10 exclusive with step=1 +array_1 = np.arange(11) +print(array_1) +# Creating an array of integers from 1 to 10 exclusive with step=1 +array_2 = np.arange(1, 11) +print(array_2) +# Creating an array of integers from 0 to 20 exclusive with step=2 +array_3 = np.arange(0, 21, 2) +print(array_3) + + diff --git a/numpy_linspace_function.py b/numpy_linspace_function.py new file mode 100644 index 0000000..d84f8cf --- /dev/null +++ b/numpy_linspace_function.py @@ -0,0 +1,27 @@ +import numpy as np +# Generating 5 equally spaced values between 0 and 1 (inclusive) +array_1 = np.linspace(0, 1, 5) +print('Example 1:', array_1) +# Generating 7 equally spaced values between -1 and 1 (inclusive) +array_2 = np.linspace(-1, 1, 7) +print('Example 2:', array_2) + +array_2 = np.linspace(-1, 1, 7) +print(f"Example 2:", {array_2.dtype.name}) + +#setting endpoint to False +array_3 = np.linspace(0, 1, 5, endpoint=False) + +# Generating 5 equally spaced values between 0 and 1 (inclusive) +array_inclusive = np.linspace(0, 1, 5) +print('Endpoint = True:', array_inclusive) +# Generating 5 equally spaced values between 0 and 1 (exclusive) +array_exclusive = np.linspace(0, 1, 5, endpoint=False) +print('Endpoint = False:', array_exclusive) + +# Create an array of even numbers from 2 to 21 exclusive +even_numbers = np.arange(2, 21, 2) +# Create an array of 10 equally spaced numbers between 5 and 6 exclusive +samples = np.linspace(5, 6, 10, endpoint=False) +print(even_numbers) +print(samples) \ No newline at end of file diff --git a/orbital.py b/orbital.py new file mode 100644 index 0000000..4d26eaf --- /dev/null +++ b/orbital.py @@ -0,0 +1,51 @@ +import numpy as np + +import matplotlib.pyplot as plt + + + +# Constants +G = 6.67430e-11 # Gravitational constant (m^3 kg^-1 s^-2) +M = 5.972e24 # Mass of Earth (kg) +R = 6.371e6 # Radius of Earth (m) + +# Initial conditions +r0 = R + 400e3 # Initial distance from Earth's center (400 km altitude) +v0 = np.sqrt(G * M / r0) # Circular orbit velocity + +# Simulation parameters +dt = 10 # Time step (s) +num_steps = 10000 + +# Arrays to store position +x = np.zeros(num_steps) +y = np.zeros(num_steps) +vx = np.zeros(num_steps) +vy = np.zeros(num_steps) + +# Initial position and velocity +x[0] = r0 +y[0] = 0 +vx[0] = 0 +vy[0] = v0 + +for i in range(1, num_steps): + r = np.sqrt(x[i-1]**2 + y[i-1]**2) + ax = -G * M * x[i-1] / r**3 + ay = -G * M * y[i-1] / r**3 + vx[i] = vx[i-1] + ax * dt + vy[i] = vy[i-1] + ay * dt + x[i] = x[i-1] + vx[i] * dt + y[i] = y[i-1] + vy[i] * dt + +# Plotting +plt.figure(figsize=(6,6)) +earth = plt.Circle((0, 0), R, color='b', alpha=0.3) +plt.gca().add_patch(earth) +plt.plot(x, y, label='Orbit') +plt.xlabel('x (m)') +plt.ylabel('y (m)') +plt.title('Orbital Mechanics Demonstration') +plt.axis('equal') +plt.legend() +plt.show() \ No newline at end of file diff --git a/packing-unpacking.py b/packing-unpacking.py new file mode 100644 index 0000000..60f22f0 --- /dev/null +++ b/packing-unpacking.py @@ -0,0 +1,7 @@ +# unpacking +a, b, c = (1, 2, 3) # a = 1, b = 2, c = 3 +print(f"a = {a}, b = {b}, c = {c}") + +# packing +a, b, *c = 1, 2, 3, 4, 5 # a = 1, b = 2, c = [3, 4, 5] +print(f"a = {a}, b = {b}, c = {c}") \ No newline at end of file diff --git a/packing.py b/packing.py new file mode 100644 index 0000000..bcf5997 --- /dev/null +++ b/packing.py @@ -0,0 +1,138 @@ +# string +a, b, c = "123" # a = "1", b = "2", c ="3" +# list +a, b, c = [1, 2, 3] # a = 1, b = 2, c = 3 +# range +a, b, c = range(3) # a = 0, b = 1, c = 2 +# set +a, b, c = {1, 2, 3} # a = 1, b = 2, c = 3 +a, b, c = {3, 2, 1} # a = 1, b = 2, c = 3 + +# dict +dict_num = {"one": 1, "two": 2, "three": 3} +a, b, c = dict_num # a = "one", b = "two", c = "three" +a, b, c = dict_num.values() # a = 1, b = 2, c = 3 +a, b, c = dict_num.items() # a = ("one", 1), b = ("two", 2), c = ("three", 3) + +# assignment to the list +[a, b, c] = 1, 2, 3 # a = 1, b = 2, c = 3 +[a, b, c] = "123" # a = "1", b = "2", c ="3" + +# Examples: + +my_tuple = ("Anna", 27, "Python Developer") + +name, age, career = my_tuple + +print(name, age, career) + +# Using starred variables +# *a, *b = 1, 2, 3, 4 # Error: Only one starred expression is allowed +a, *b = 1, 2, 3, 4 # a = 1, b = [2, 3, 4] +print(a, b) + +# *a, *b, *c = 1, 2, 3 # Error: Only one starred expression is allowed + +# Practice +# Unpacking a tuple +my_tuple = (1, 2, 3) +a, b, c = my_tuple # a = 1, b = 2, c = 3 +print(a, b, c) +# Unpacking a list + +my_list = [4, 5, 6] +d, e, f = my_list # d = 4, e = 5, f = 6 +print(d, e, f) + +# Unpacking a string +my_string = "abc" +x, y, z = my_string # x = "a", y = "b", z = "c" +print(x, y, z) + +# Unpacking a set +my_set = {7, 8, 9} +a, b, c = my_set # a = 7, b = 8, c = 9 +print(a, b, c) + +# Unpacking a dictionary values +my_dict = {"name": "John", "age": 30, "city": "New York"} +name, age, city = my_dict.values() +print(name, age, city) + +# Unpacking a dictionary items +my_dict = {"name": "John", "age": 30, "city": "New York"} +name, age, city = my_dict.items() # name = ("name", "John"), age = ("age", 30), city = ("city", "New York") +print(name, age, city) + +# Unpacking a dictionary vaules into a list +name_list = [name[1], age[1], city[1]] +print(name_list) + +# Unpacking a dictionary values into a list using list comprehension +name_list = [name[1] for name in my_dict.items()] # Extracting names from the dictionary items +print(name_list) + +# Unpacking a dictionary items into a list +item_list = [item for item in my_dict.items()] +print(item_list) + +my_list = list(my_dict.items()) # Converting dictionary items to a list of tuples +print(my_list) + +my_list = list(my_dict.values()) # Converting dictionary values to a list +print(my_list) + +# Dropping unneeded variables +# Unpacking with an underscore to ignore variables +my_tuple = (1, 2, 3, 4) +a, b, _, d = my_tuple # a = 1, b = 2, d = 4 +print(a, b, d) + +# Unpacking with an underscore to ignore variables in a list +my_list = [5, 6, 7, 8] +e, f, _, g = my_list # e = 5, f = 6, g = 8 +print(e, f, g) + +# Unpacking with an underscore to ignore variables in a string +my_string = "xyz" +x, y, _ = my_string # x = "x", y = "y" +print(x, y) + +# Unpacking with an underscore to ignore variables in a set +my_set = {10, 11, 12} +a, b, _ = my_set # a = 10, b = 11 +print(a, b) + +# Unpacking with an underscore to ignore variables in a dictionary +my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"} +key1, key2, _ = my_dict # key1 = "key1", key2 = "key2" +print(key1, key2) + +# Unpacking with an underscore to ignore variables in a dictionary values +my_dict = {"name": "Alice", "age": 25, "city": "Wonderland"} +name, age, _ = my_dict.values() # name = "Alice", age = 25 +print(name, age) + +# Unpacking with an underscore to ignore variables in a dictionary items +my_dict = {"name": "Bob", "age": 30, "city": "Atlantis"} +name, age, _ = my_dict.items() # name = ("name", "Bob"), age = ("age", 30) +print(name, age) + +# Using unpacking to create a new dictionary from an existing one +my_dict = {"name": "Bob", "age": 30, "city": "Atlantis"} +name, age, _ = my_dict.items() # name = ("name", "Bob"), age = ("age", 30) tuple +my_new_dict = {name[0]: name[1], age[0]: age[1]} # Creating a new dictionary +print(my_new_dict) + +# Using unpacking to create a new dictionary from an existing one using dict +my_dict = {"name": "Bob", "age": 30, "city": "Atlantis"} +name, age, _ = my_dict.items() # name = ("name", "Bob"), age = ("age", 30) tuple +my_new_dict = dict(name=name[1], age=age[1]) # Creating a new dictionary +print(my_new_dict) + + +a, *b, c = 1, 2, 3, 4, 5 # a = 1, b = [2, 3, 4], c = 5 +print(a, b, c) + +a, _, b, *_ = 1, 2, 3, 4, 5 # a = 1, b = 2, _ = 3, *_ = [4, 5] +print(f"a={a}, b={b}") diff --git a/personal_message.py b/personal_message.py new file mode 100644 index 0000000..99e9962 --- /dev/null +++ b/personal_message.py @@ -0,0 +1,2 @@ +name = "Eric" +print(f"Hello {name}, would you like to learn some python today?") \ No newline at end of file diff --git a/pizza.py b/pizza.py new file mode 100644 index 0000000..a1deb91 --- /dev/null +++ b/pizza.py @@ -0,0 +1,11 @@ +# Store information about a pizza being ordered +pizza = { + 'crust': 'thick', + 'toppings': ['mushrooms', 'extra cheese'], +} + +# Summarize the order +print(f"You ordered a {pizza['crust']}-crust pizza with the following toppings: ") +"with the following toppings:" +for topping in pizza['toppings']: + print(f"\t{topping}") diff --git a/players.py b/players.py new file mode 100644 index 0000000..502747f --- /dev/null +++ b/players.py @@ -0,0 +1,27 @@ +players = ['charles', 'martina', 'michael', 'florence', 'eli'] + +# slice the list beginning with the first index element through the 2nd index +# element; thus 3 elements + +#print(players[0:3]) + +# slice the list starting with index[0] and stopping at index[3] + +#print(players[:4]) + +# slice the list beginning at index[2] or 3rd element and ending at the end of +# the list + +#print(players[2:]) + +# if you want to slice the list and print the last 3 elements in the list, use +# this + +print(players[-3:]) + +# printing the first three players on my team in title case + +print("Here are the first three players on my team:") +for player in players[:3]: + print(player.title()) + diff --git a/playing_cards.py b/playing_cards.py new file mode 100644 index 0000000..f343d89 --- /dev/null +++ b/playing_cards.py @@ -0,0 +1,81 @@ +class Card: + def __init__(self, suit: str, rank: str) -> None: + self.suit = suit + self.rank = rank + + def __str__(self) -> str: + return f"{self.rank} of {self.suit}" + + def __repr__(self) -> str: + return f"Card(suit={self.suit}, rank={self.rank})" + + def __eq__(self, other): + if not isinstance(other, Card): + return NotImplemented + return (self.suit, self.rank) == (other.suit, other.rank) + + +class Deck: + def __init__(self) -> None: + self.cards = [] + suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] + ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] + for suit in suits: + for rank in ranks: + self.cards.append(Card(suit, rank)) + + def __str__(self) -> str: + return ', '.join(str(card) for card in self.cards) + + def __repr__(self) -> str: + return f"Deck(cards={self.cards})" + + def shuffle(self): + import random + random.shuffle(self.cards) + + def deal(self, num_cards: int) -> list[Card]: + if num_cards > len(self.cards): + raise ValueError("Not enough cards in the deck to deal.") + dealt_cards = self.cards[:num_cards] + self.cards = self.cards[num_cards:] + return dealt_cards + def remaining_cards(self) -> int: + return len(self.cards) + + +class Hand: + def __init__(self, cards: list[Card]) -> None: + self.cards = cards + + def __str__(self) -> str: + return ', '.join(str(card) for card in self.cards) + + def __repr__(self) -> str: + return f"Hand(cards={self.cards})" + + def add_card(self, card: Card): + self.cards.append(card) + + def clear(self): + self.cards.clear() + +# Example usage: +if __name__ == "__main__": + #print("Unshuffled deck of cards...") + deck = Deck() + #print(deck) + deck.shuffle() + #print("Shuffled deck:") + #print(deck) + dealt = deck.deal(5) + player1_hand = Hand(dealt) + print("Dealt cards:") + for card in player1_hand.cards: + print(card) + print(f"Remaining cards in the deck: {deck.remaining_cards()}") + + player1_hand.add_card(Card('Hearts', 'Ace')) + print("Player 1's hand after adding an Ace of Hearts:") + for card in player1_hand.cards: + print(card) diff --git a/poker.py b/poker.py new file mode 100644 index 0000000..978e2cb --- /dev/null +++ b/poker.py @@ -0,0 +1,66 @@ +import random + +SUITS = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] +RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] +RANK_VALUES = {rank: i for i, rank in enumerate(RANKS, 2)} + +def create_deck(): + return [(rank, suit) for suit in SUITS for rank in RANKS] + +def deal_hand(deck, num=5): + hand = random.sample(deck, num) + for card in hand: + deck.remove(card) + return hand + +def hand_rank(hand): + ranks = sorted([RANK_VALUES[card[0]] for card in hand], reverse=True) + suits = [card[1] for card in hand] + rank_counts = {r: ranks.count(r) for r in ranks} + is_flush = len(set(suits)) == 1 + is_straight = all(ranks[i] - 1 == ranks[i+1] for i in range(len(ranks)-1)) + counts = sorted(rank_counts.values(), reverse=True) + if is_straight and is_flush: + return (8, ranks) # Straight flush + elif counts[0] == 4: + return (7, ranks) # Four of a kind + elif counts[0] == 3 and counts[1] == 2: + return (6, ranks) # Full house + elif is_flush: + return (5, ranks) # Flush + elif is_straight: + return (4, ranks) # Straight + elif counts[0] == 3: + return (3, ranks) # Three of a kind + elif counts[0] == 2 and counts[1] == 2: + return (2, ranks) # Two pair + elif counts[0] == 2: + return (1, ranks) # One pair + else: + return (0, ranks) # High card + +def show_hand(hand): + return '\n '.join([f"{rank} of {suit}" for rank, suit in hand]) + +def main(): + deck = create_deck() + random.shuffle(deck) + player1 = deal_hand(deck) + player2 = deal_hand(deck) + print("Player 1's hand:\n", show_hand(player1)) + print() + print("Player 2's hand:\n", show_hand(player2)) + rank1 = hand_rank(player1) + rank2 = hand_rank(player2) + if rank1 > rank2: + print("Player 1 wins! with rank:", rank1) + print("Player 2 loses with rank:", rank2) + elif rank2 > rank1: + print("Player 2 wins! with rank:", rank2) + print("Player 1 loses with rank:", rank1) + else: + print("It's a tie!") + print("Both players have rank:", rank1) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/practice_1.py b/practice_1.py new file mode 100644 index 0000000..2dbdc6c --- /dev/null +++ b/practice_1.py @@ -0,0 +1,62 @@ +class Math(object): + def sum (self, *args, **kargs) -> float: + result = sum(args) + return result + + def sub (self, *args, **kargs) -> float: + if len(args) < 2: + raise ValueError("sub requires at least two arguments") + result = args[0] - args[1] + return result + + def mult (self, *args, **kargs) -> float: + if len(args) < 2: + raise ValueError("mult requires at least two arguments") + result = args[0] * args[1] + return result + + def div (self, *args, **kargs) -> float: + if len(args) < 2: + raise ValueError("div requires at least two arguments") + result = args[0] / args[1] + return result + + def fdiv (self, *args, **kargs) -> float: + if len(args) < 2: + raise ValueError("fdiv requires at least two arguments") + result = args[0] // args[1] + return result + + def pow (self, *args, **kargs) -> float: + if len(args) < 2: + raise ValueError("pow requires at least two arguments") + result = args[0] ** args[1] + return result + + def mod (self, *args, **kargs) -> float: + if len(args) < 2: + raise ValueError("mod requires at least two arguments") + result = args[0] % args[1] + return result + + def avg (self, *args, **kargs) -> float: + if len(args) < 2: + raise ValueError("avg requires at least two arguments") + result = (sum(args)/len(args)) + return result + + + +s = Math() + +print(f"Sum: {s.sum(3.564, 92.335, 14.56):.2f}") +print(f"Product: {s.mult(8.56, 3.567):.2f}") +print(f"Difference: {s.sub(8.56, 3.567):.2f}") +print(f"Floor Division: {s.fdiv(8.56, 3.567):.2f}") +print(f"Power: {s.pow(8.56, 3.567):.2f}") +print(f"Mod: {s.mod(8.0, 3.0):.2f}") +print(f"Average: {s.avg(8.56, 3.567, 73.45, 10.778, 14.334, 56.789):.2f}") +print(f"Division: {s.div(8.56, 3.567):.2f}") + + +print(f"Average: {s.avg(2, 3, 4, 53, 6):.2f}") diff --git a/prime_numbers_over_an_interval.py b/prime_numbers_over_an_interval.py new file mode 100644 index 0000000..12d0c32 --- /dev/null +++ b/prime_numbers_over_an_interval.py @@ -0,0 +1,20 @@ +"""This program prints all prime numbers over a specified interval""" + +x, y = 2, 100 # defining the range + +# create a boolean list to mark primes, assume all are prime initially +primes = [True] * (y + 1) + +# 0 and 1 are not prime +primes[0], primes[1] = False, False + +# Sieve of Eratosthenes to mark non-primes +for i in range(2, int(y ** 0.5) + 1): + if primes[i]: + for j in range(i * i, y + 1, i): + primes[j] = False + +# collect primes in the range [x, y] +res = [i for i in range(x, y + 1) if primes[i]] +print(res if res else "No") +print ("the number of primes is: ", len(res)) diff --git a/product_revenues_exercise.py b/product_revenues_exercise.py new file mode 100644 index 0000000..202d29a --- /dev/null +++ b/product_revenues_exercise.py @@ -0,0 +1,21 @@ + # List of products, their prices, and the quantities sold +products = ["Bread", "Apples", "Oranges", "Bananas"] +prices = [0.50, 1.20, 2.50, 2.00] # price per item +quantities_sold = [150, 200, 100, 50] # number of items sold +def calculate_revenue(product_price, product_sold): + revenue = [] + for index in range(len(product_price)): + revenue.append(product_price[index] * product_sold[index]) + return revenue + +revenue = calculate_revenue(prices, quantities_sold) + +def formatted_output(products_list, revenue_list): + revenue_per_product = list(zip(products_list, revenue_list)) + sorted(revenue_per_product) + return revenue_per_product + +revenue_per_product = formatted_output(products, revenue) + +for product, rev in revenue_per_product: + print(f"{product} has total revenue of ${rev}") diff --git a/python-cheat-sheet.pdf b/python-cheat-sheet.pdf new file mode 100644 index 0000000..b2b9903 Binary files /dev/null and b/python-cheat-sheet.pdf differ diff --git a/python_closures.py b/python_closures.py new file mode 100644 index 0000000..bc1e880 --- /dev/null +++ b/python_closures.py @@ -0,0 +1,17 @@ +def calculate_income(percent): + def annual_income(amount): + return amount * percent / 100 + return annual_income # function returned by outer function + +interest_rate_3 = calculate_income(3) # function assigned to the variable +interest_rate_7 = calculate_income(7) +interest_rate_10 = calculate_income(10) + +print(interest_rate_3(1500)) # 45.0 +print(interest_rate_3(2000)) # 60.0 +print(interest_rate_10(1500)) # 150.0 + +print(interest_rate_7(1500)) # 105.0 +print(interest_rate_7(2000)) # 140.0 +print(interest_rate_10(2000)) # 200.0 + \ No newline at end of file diff --git a/python_decorators.py b/python_decorators.py new file mode 100644 index 0000000..f66632e --- /dev/null +++ b/python_decorators.py @@ -0,0 +1,21 @@ +def decorator(func): + def wrapper(argument1, argument2): + print("Function starts executing") + result = func(argument1, argument2) + print("Function ends executing") + + return result + + return wrapper + + +def add(a, b): + print(f"Function add: {a} + {b}") + return a + b + + +add = decorator(add) + +print(add(14, 12)) +print(add(11, 28)) +print(add(33, 16)) \ No newline at end of file diff --git a/random_arrays.py b/random_arrays.py new file mode 100644 index 0000000..09d21d0 --- /dev/null +++ b/random_arrays.py @@ -0,0 +1,15 @@ +import numpy as np +# Generating a random integer from 0 to 3 exclusive +random_integer = np.random.randint(3) +print(random_integer) +# Generating a 1D array of random integers in [0, 5) with 4 elements +random_int_array = np.random.randint(5, size=4) +print(random_int_array) +# Generating a 1D array of random integers in [2, 5) with 4 elements +random_int_array_2 = np.random.randint(2, 5, size=4) +print(random_int_array_2) +# Generating a random 2D array of random integers in [1, 6) of shape 4x2 +random_int_matrix = np.random.randint(1, 6, size=(4, 2)) +print(random_int_matrix) + + diff --git a/random_arrays_2.py b/random_arrays_2.py new file mode 100644 index 0000000..a62486d --- /dev/null +++ b/random_arrays_2.py @@ -0,0 +1,20 @@ +import numpy as np +# Generating a random number +random_number = np.random.rand() +print(random_number) +# Generating a random 1D array with 5 elements +random_array = np.random.rand(5) +print(random_array) +# Generating a random 2D array (matrix) of shape 4x3 +random_matrix = np.random.rand(4, 3) +print(random_matrix) + +# Generate a 1D array of random floats in [0, 1) with 4 elements +random_floats_array = np.random.rand(4) +# Generate a 2D array of random floats in [0, 1) of shape 3x2 +random_floats_matrix = np.random.rand(3, 2) +# Generate a 2D array of random integers in [10, 21) of shape 3x2 +random_integers_matrix = np.random.randint(10, 21, size=(3, 2)) +print(random_floats_array) +print(random_floats_matrix) +print(random_integers_matrix) \ No newline at end of file diff --git a/reshape_array.py b/reshape_array.py new file mode 100644 index 0000000..73554fd --- /dev/null +++ b/reshape_array.py @@ -0,0 +1,37 @@ +import numpy as np +""" +This script demonstrates how to reshape NumPy arrays into different dimensions. +Functionality: +1. Creates a 1D NumPy array with values from 0 to 11. +2. Reshapes the 1D array into a 3x4 2D array and prints it. +3. Reshapes the same 1D array into a 2x2x3 3D array and prints it. +4. Creates another 1D NumPy array with values from 0 to 4. +5. Reshapes this array into a 2D column vector (shape: 5x1) and prints it. +Usage: +- Demonstrates the use of `np.arange` for array creation. +- Shows how to use the `reshape` method for changing array dimensions. +""" + +# Creating a 1D array from 0 to 11 inclusive +array = np.arange(12) +# Reshaping the array to a 3x4 2D array (matrix) +reshaped_array_2d = array.reshape(3, 4) +print(reshaped_array_2d) +# Reshaping the array to a 2x2x3 3D array +reshaped_array_3d = array.reshape(2, 2, 3) +print(reshaped_array_3d) + + +import numpy as np +# Creating a 1D array from 0 to 4 inclusive +array = np.arange(5) + +# Reshaping the array to a 2D array with one column +reshaped_array = array.reshape(-1, 1) +print(reshaped_array) + +array = np.arange(18) + +# Reshaping the array to a 2D array with three columns +reshaped_array = array.reshape(-1, 3) +print(reshaped_array) \ No newline at end of file diff --git a/single_node_neural_network.py b/single_node_neural_network.py new file mode 100644 index 0000000..35d54c2 --- /dev/null +++ b/single_node_neural_network.py @@ -0,0 +1,36 @@ +from ast import arg +import numpy as np # type: ignore + +# Fix the seed for reproducibility +np.random.seed(100) + +def sigmoid(z): + return 1 / (1 + np.exp(-z)) + +class Neuron: + def __init__(self, *args): + # 1. Initialize weights and bias with random values + self.weights = np.random.uniform(-1, 1, size=args[0]) + self.bias = np.random.uniform(-1, 1) + + def activate(self, inputs): + # 2. Compute the weighted sum using dot product and add bias + input_sum_with_bias = np.dot(inputs, self.weights) + self.bias + # 3. Apply the sigmoid activation function + output = sigmoid(input_sum_with_bias) + return output + +# Create a neuron with 6 inputs +neuron = Neuron(6) +# Generate inputs for the neuron +neuron_inputs = np.array([-0.5, 0.4, -0.8, 0.2, 0.1, -0.3]) +# Pass the inputs to the created neuron +neuron_output = neuron.activate(neuron_inputs) + +print(f'Output of the neuron is {neuron_output:.3f}') + +''' +How it works: +# The neuron takes any number of inputs, computes the weighted sum, applies the sigmoid function, and returns the output which is a value between 0 and 1. + +''' \ No newline at end of file diff --git a/sleeping_decorator.py b/sleeping_decorator.py new file mode 100644 index 0000000..92c2061 --- /dev/null +++ b/sleeping_decorator.py @@ -0,0 +1,18 @@ + +import time + +def sleep_decorator(seconds): + def decorator(func): + def wrapper(*args, **kwargs): + print(f"Sleeping for {seconds} seconds before executing '{func.__name__}'") + time.sleep(seconds) + return func(*args, **kwargs) + return wrapper + return decorator + +@sleep_decorator(5) +def my_function(): + print("Function executed!") + +# Usage +my_function() \ No newline at end of file diff --git a/slicing_1D_arrays.py b/slicing_1D_arrays.py new file mode 100644 index 0000000..50309a2 --- /dev/null +++ b/slicing_1D_arrays.py @@ -0,0 +1,31 @@ +import numpy as np + +array = np.array([5, 10, 2, 8, 9, 1, 0, 4]) +print(f'Initial array: {array}') +# Slicing from the element at index 2 to the element at index 4 exclusive +print(array[2:4]) +# Slicing from the first element to the element at index 5 exclusive +print(array[:5]) +# Slicing from the element at index 5 to the last element inclusive +print(array[5:]) + + + +#import numpy as np +# Initial array +array = np.array([5, 10, 2, 8, 9, 1, 0, 4]) +print(f'Initial array: {array}') +# Slicing from the first element to the last element inclusive with step=2 +print(array[::2]) +# Slicing from the element at index 4 to the element at index 2 exclusive (step=-1) +print(array[4:2:-1]) +# Slicing from the last element to the first element inclusive (reversed array) +print(array[::-1]) +# Slicing from the first element to the last inclusive (the same as our array) +print(array[:]) + +# Sales data for the past week (Monday to Sunday) +weekly_sales = np.array([150, 200, 170, 180, 160, 210, 190]) +# Create a slice of weekly_sales with every second day's sales starting from the second day +alternate_day_sales = weekly_sales[1::2] +print(alternate_day_sales) \ No newline at end of file diff --git a/sorted_arrays.py b/sorted_arrays.py new file mode 100644 index 0000000..116e189 --- /dev/null +++ b/sorted_arrays.py @@ -0,0 +1,16 @@ +import array +import numpy as np +array_1d = np.array([10, 2, 5, 1, 6, 5]) +array_1d_sorted = np.sort(array_1d, kind='quicksort') + +print("Unsorted 1D array:", array_1d) +print("Sorted 1D array (ascending):", array_1d_sorted) +print("Sorted 1D array (descending):", np.sort(array_1d)[::-1]) + +# Employee salaries +salaries = np.array([45000, 38000, 52000, 47000, 43000, 39000]) +print("Original salaries:", salaries) +# Sort the salaries in descending order +sorted_salaries = np.sort(salaries)[::-1] +# Print top 3 salaries +print("Top 3 salaries:", sorted_salaries[:3]) \ No newline at end of file diff --git a/sorting_2d_arrays.py b/sorting_2d_arrays.py new file mode 100644 index 0000000..1d62988 --- /dev/null +++ b/sorting_2d_arrays.py @@ -0,0 +1,24 @@ +import numpy as np +''' +array_2d = np.array([[2, 9, 3], [1, 6, 4], [5, 7, 8]]) +# Sorting a 2D array along axis 1 +print(np.sort(array_2d)) + +# Sorting a 2D array along axis 0 +print(np.sort(array_2d, axis=0)[::-1]) + +# Creating a 1D sorted array out of the elements of array_2d +print(np.sort(array_2d, axis=None)) +''' + +# Simulated exam scores for three students in three subjects +exam_scores = np.array([[75, 82, 90], [92, 88, 78], [60, 70, 85], [80, 95, 88], [70, 65, 80], [85, 90, 92]]) +# Create an array with every column sorted by scores in descending order +top_scores_subject = np.sort(exam_scores, axis=0)[::-1] +# Create a 1D array of all scores sorted in ascending order +sorted_scores = np.sort(exam_scores, axis=None) +print("Top scores by subject:") +print(top_scores_subject) +print("All scores sorted (ascending):") +print(sorted_scores) +print("Average score:", sum(sorted_scores) / len(sorted_scores)) # Length of the first dimension (number of rows) \ No newline at end of file diff --git a/square_numbers.py b/square_numbers.py new file mode 100644 index 0000000..1342c9f --- /dev/null +++ b/square_numbers.py @@ -0,0 +1,6 @@ +squares = [] +for value in range(1, 11): + #square = value ** 2 + squares.append(value ** 2) +print(squares) + diff --git a/square_numbers2.py b/square_numbers2.py new file mode 100644 index 0000000..60d29b8 --- /dev/null +++ b/square_numbers2.py @@ -0,0 +1,2 @@ +squares = [value ** 2 for value in range (1, 11)] +print(squares) \ No newline at end of file diff --git a/stripping_names.py b/stripping_names.py new file mode 100644 index 0000000..e6f6e0f --- /dev/null +++ b/stripping_names.py @@ -0,0 +1,6 @@ +name = "\t Benjamin Franklin \n" +print(name) +print(name.lstrip()) +print(name.rstrip()) +print(name.strip()) + diff --git a/temperature_conversion.py b/temperature_conversion.py new file mode 100644 index 0000000..d7daf8b --- /dev/null +++ b/temperature_conversion.py @@ -0,0 +1,21 @@ +#This program converts temperature from Fahrenheit to Celcius or Celcius to Fahrenheit depending on the input from the user + +unit = input("Is this temperature in Celcius or Fahrenheit (C/F)?: ") +temp = float(input("Please enter a temperature: ")) +if unit == "C": + temp = round((temp * 1.8)+32, 2) + print(f"The temperature in degrees F is {temp}F") +elif unit == "F": + temp = round((temp - 32) * 5 / 9, 2) + print(f"The temperature in degrees C is {temp}C") +else: + print(f"{unit} is an invalid unit of measurement.") + + + + + + + + + diff --git a/test.py b/test.py new file mode 100644 index 0000000..3a26e4b --- /dev/null +++ b/test.py @@ -0,0 +1,24 @@ +import numpy as np + +'''array_1d_1 = np.array([1, 4, 6, 2, 9, 10, 11]) +# Assigning an array to the slice of array_1d +array_1d_1[2:] = np.array([3, 5, ]) +print(array_1d_1) + + +import numpy as np + +arr = np.zeros((5,)) +arr[:] = np.array([1, 2]) # ❌ ValueError + + +np.zeros((5)) # Interpreted as np.zeros(5), returns a 1D array of size 5 +np.zeros((5,)) # Explicitly a tuple, also returns a 1D array of size 5 +''' + +print(np.zeros((5))) +print(np.zeros((5,))) +print(np.zeros((5, 1))) # 2D array with shape (5, 1) +print(np.zeros((5, 2))) # 2D array with shape (5 + +print(np.full((5, 5), 1)) # 2D array of 1's with shape (5, 5) \ No newline at end of file diff --git a/test2.py b/test2.py new file mode 100644 index 0000000..39e4937 --- /dev/null +++ b/test2.py @@ -0,0 +1,19 @@ +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) + diff --git a/test_digital_to_hexidecimal.py b/test_digital_to_hexidecimal.py new file mode 100644 index 0000000..e69de29 diff --git a/threshold_checker.py b/threshold_checker.py new file mode 100644 index 0000000..f96d47e --- /dev/null +++ b/threshold_checker.py @@ -0,0 +1,16 @@ +def threshold_checker(threshold): + def check(value): + return threshold < value + + return check + +# Usage +greater_than_10 = threshold_checker(10) +print(greater_than_10(12)) +print(greater_than_10(8)) +print(greater_than_10(10)) + +greater_than_100 = threshold_checker(100) +print(greater_than_100(150)) +print(greater_than_100(80)) +print(greater_than_100(100)) \ No newline at end of file diff --git a/timing_decorator.py b/timing_decorator.py new file mode 100644 index 0000000..ee67e2a --- /dev/null +++ b/timing_decorator.py @@ -0,0 +1,18 @@ +import time + +def timing_decorator(func): + def wrapper(*args, **kwargs): + start_time = time.time() + result = func(*args, **kwargs) + end_time = time.time() + print(f"'{func.__name__}' executed in {end_time - start_time} seconds") + return result + return wrapper + +@timing_decorator +def some_function(): + time.sleep(1) # Simulating a task + print("Function completed") + +# Usage +some_function() \ No newline at end of file diff --git a/toppings.py b/toppings.py new file mode 100644 index 0000000..f33a9bf --- /dev/null +++ b/toppings.py @@ -0,0 +1,4 @@ +requested_toppings = 'mushrooms' +if requested_toppings != 'anchovies': + print('Hold the anchovies!') + diff --git a/toppings2.py b/toppings2.py new file mode 100644 index 0000000..6ad5964 --- /dev/null +++ b/toppings2.py @@ -0,0 +1,9 @@ +requested_toppings = ['mushrooms', 'extra cheese'] +if 'mushrooms' in requested_toppings: + print('adding mushrooms!') +if 'pepperoni' in requested_toppings: + print('adding pepperoni') +if 'extra cheese' in requested_toppings: + print('adding extra cheese') + +print('\nFinished making your Pizza!') diff --git a/toppings3.py b/toppings3.py new file mode 100644 index 0000000..f590e02 --- /dev/null +++ b/toppings3.py @@ -0,0 +1,9 @@ +requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] +for requested_topping in requested_toppings: + if requested_topping == 'green peppers': + print('Sorry, we are out of green pappers right now') + else: + print(f'adding {requested_topping}.') + +print('\nFinished making your Pizza!') + diff --git a/toppings4.py b/toppings4.py new file mode 100644 index 0000000..a3074b3 --- /dev/null +++ b/toppings4.py @@ -0,0 +1,11 @@ +#requested_toppings = [] +requested_toppings = ['mushrooms', 'pepperoni', 'green peppers', 'extra cheese'] +if requested_toppings: + for requested_topping in requested_toppings: + print(f'adding {requested_topping}.') + print('\nFinished making your Pizza!') +else: + print('Are you sure you want a plain Pizza?') + + + diff --git a/toppings5.py b/toppings5.py new file mode 100644 index 0000000..eac65c6 --- /dev/null +++ b/toppings5.py @@ -0,0 +1,10 @@ +available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese'] +requested_toppings = ['mushrooms', 'french fries', 'extra cheese'] +for requested_topping in requested_toppings: + if requested_topping in available_toppings: + print(f'Adding {requested_topping}.') + else: + print(f'Sorry, we don\'t have the {requested_topping}.') +print('\nFinished making your Pizza!') + + diff --git a/toppings6.py b/toppings6.py new file mode 100644 index 0000000..e69de29 diff --git a/two_numbers_sum_to_9.py b/two_numbers_sum_to_9.py new file mode 100644 index 0000000..2c88014 --- /dev/null +++ b/two_numbers_sum_to_9.py @@ -0,0 +1,33 @@ +from itertools import combinations + +# Step 1: Define the set and target sum +numbers = list(range(1, 9)) +target = 9 + +# Step 2: Generate all 5-number combinations +valid_combinations = list(combinations(numbers, 5)) + +# Step 3: Define the 4 mutually exclusive pairs that sum to 9 +pairs = [(1, 8), (2, 7), (3, 6), (4, 5)] + +# Step 4: Check each combination for the required condition +def has_pair_summing_to_target(combo, pair_list): + for a, b in pair_list: + if a in combo and b in combo: + return True + return False + +# Step 5: Verify each combination +always_has_pair = all(has_pair_summing_to_target(c, pairs) for c in valid_combinations) + +print(f"Every 5-number combination has at least one pair summing to {target}: {always_has_pair}") + +''' +The code verifies if every 5-number combination from 1 to 8 contains at least one of the specified pairs that sum to 9. +# Output: True or False based on the verification +# Note: The output will be True since every combination of 5 numbers from 1 to 8 will always +# include at least one of the pairs (1, 8), (2, 7), (3, 6), or (4, 5) due to the nature of combinations and the range of numbers. +How it works: +1. It generates all combinations of 5 numbers from the set {1, 2, 3, 4, 5, 6, 7, 8}. +2. It checks each combination to see if it contains at least one of the pairs that sum to 9. +''' \ No newline at end of file diff --git a/unpacking.py b/unpacking.py new file mode 100644 index 0000000..60f22f0 --- /dev/null +++ b/unpacking.py @@ -0,0 +1,7 @@ +# unpacking +a, b, c = (1, 2, 3) # a = 1, b = 2, c = 3 +print(f"a = {a}, b = {b}, c = {c}") + +# packing +a, b, *c = 1, 2, 3, 4, 5 # a = 1, b = 2, c = [3, 4, 5] +print(f"a = {a}, b = {b}, c = {c}") \ No newline at end of file diff --git a/user.py b/user.py new file mode 100644 index 0000000..dcecc4a --- /dev/null +++ b/user.py @@ -0,0 +1,10 @@ +# program prints key and value pairs +user_0 = { + 'username': 'efermi', + 'first': 'enrico', + 'last': 'fermi', +} +for key, value in user_0.items(): + print(f'\nKey: {key}') + print(f'Value: {value}') + diff --git a/using_eval_function.py b/using_eval_function.py new file mode 100644 index 0000000..553b5a2 --- /dev/null +++ b/using_eval_function.py @@ -0,0 +1,3 @@ +expression = input("Enter an arithmetic expression") +result = eval(expression) +print("Result:", result) diff --git a/using_kwargs.py b/using_kwargs.py new file mode 100644 index 0000000..425955c --- /dev/null +++ b/using_kwargs.py @@ -0,0 +1,21 @@ +def create_user_profile(**kwargs): + if not kwargs: + return "No profile data provided." + + profile_parts = [] + for key, value in kwargs.items(): + profile_parts.append(f"{key.capitalize()}: {value}") + + # If you want to return a single string with all profile parts joined by newlines + return "\n".join(profile_parts) + + # If you want to return a list of profile parts, use + # return profile_parts + + +# Example usage +profile = create_user_profile(name="Alice", age=30, occupation="Engineer") +print(profile) + +profile_empty = create_user_profile() +print(profile_empty) diff --git a/using_zip.py b/using_zip.py new file mode 100644 index 0000000..7e566e6 --- /dev/null +++ b/using_zip.py @@ -0,0 +1,23 @@ +#Zipping two lists of equal length +names = ['Alice', 'Bob', 'Charlie'] +scores = [85, 92, 78] +paired = list(zip(names, scores)) +print(paired) + +#Creating a dictionary +keys = ['id', 'name', 'age'] +values = [101, 'Alice', 30] +data = dict(zip(keys, values)) +print(data) + +#Unzipping the zipped lists +zipped = [('Alice', 85), ('Bob', 92), ('Charlie', 78)] +names, scores = zip(*zipped) +print(names) # ('Alice', 'Bob', 'Charlie') +print(scores) # (85, 92, 78) + +#Unzipping the dictionary to a list of key, value tuples +data = {'id': 101, 'name': "Alice", 'age' : 30} +keys, values = zip(*data.items()) +print(keys, values) + diff --git a/voting.py b/voting.py new file mode 100644 index 0000000..ad8ba56 --- /dev/null +++ b/voting.py @@ -0,0 +1,5 @@ +age = 17 +if age >= 18: + print('You are old enough to vote') +else: + print('You are not old enough to vote.') \ No newline at end of file diff --git a/voting2.py b/voting2.py new file mode 100644 index 0000000..9f4d695 --- /dev/null +++ b/voting2.py @@ -0,0 +1,5 @@ +age = 19 +if age >= 18: + print('You\'re old enough to vote.') + print('Have you registered to vote yet?') + diff --git a/voting3.py b/voting3.py new file mode 100644 index 0000000..62af63d --- /dev/null +++ b/voting3.py @@ -0,0 +1,8 @@ +age = 17 +if age >= 18: + print('You\'re old enough to vote.') + print('Have you registered to vote yet?') +else: + print('Sorry, you\'re too young to vote.') + print('Please register to vote when you turn 18.') + diff --git a/votint3.py b/votint3.py new file mode 100644 index 0000000..e69de29 diff --git a/zipping_lists.py b/zipping_lists.py new file mode 100644 index 0000000..b5f8d58 --- /dev/null +++ b/zipping_lists.py @@ -0,0 +1,45 @@ +list_a = [1, 2, 3] +list_b = [4, 5, 6] +""" +This script demonstrates how to zip and unzip two lists in Python. +- `list_a` and `list_b` are two lists of integers. +- The `zip()` function combines these lists into a list of tuples, pairing elements by their positions. +- The zipped result is printed. +- The script then shows how to unzip the zipped list using unpacking (`*`) and `zip()`, resulting in tuples containing + the original lists' elements. +- The unzipped tuples are converted back to lists using `map(list, ...)`. +- The final output confirms that the original lists are successfully recovered after zipping and unzipping. +Example output: +list_a: [1, 2, 3] +list_b: [4, 5, 6] +list_a and list_b zipped: [(1, 4), (2, 5), (3, 6)] +zipped list unzipped: [(1, 2, 3), (4, 5, 6)] +list_a unzipped: [1, 2, 3] +list_b unzipped: [4, 5, 6] +""" + +print('list_a:', list_a) +print('list_b:', list_b) +zipped = zip(list_a, list_b) +print('list_a and list_b zipped:', list(zipped)) # Output: [(1, 4), (2, 5), (3, 6)] +# Unzipping +unzipped = zip(*zip(list_a, list_b)) +print('zipped list unzipped:', list(unzipped)) # Output: [(1, 2, 3), (4, 5, 6)] +# Note: The unzipped output is a list of tuples, each containing elements from the original lists. +# To convert tuples back to lists +list_a_unzipped, list_b_unzipped = map(list, zip(*zip(list_a, list_b))) + +print('list_a unzipped:', list(list_a_unzipped)) # Output: [1, 2, 3] +print('list_b unzipped:', list(list_b_unzipped)) # Output: [4, 5, 6] + +# Use cases + +for num, char in zip([1, 2, 3], ['a', 'b', 'c']): + print('num', num, 'char', char) + +pairs = [(1, 'a'), (2, 'b'), (3, 'c')] + +nums, chars = zip(*pairs) +print('list of unzipped pairs:', list(zip(*pairs))) +print('list of nums:', list(nums)) # (1, 2, 3) +print('list of chars:', list(chars)) # ('a', 'b', 'c') \ No newline at end of file