diff --git a/.gitignore b/.gitignore index c18dd8d8..58200d4d 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -__pycache__/ +__pycache__/ diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..dbd9e233 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,15 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Python: Current File", + "type": "python", + "request": "launch", + "program": "${file}", + "console": "integratedTerminal" + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..9aa899da --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.pythonPath": "C:\\Users\\Christopher\\AppData\\Local\\Programs\\Python\\Python38-32\\python.exe" +} \ No newline at end of file diff --git a/README.md b/README.md index 268b8284..0c7d4809 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ -# Exercises - -| Module ID | Module Name | -|:-----------:|:--------:| -| 1 | [Introduction and Environment](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_and_environment) | -| 2 | [Introduction to Python](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_to_python) | -| 3 | [Data Structures](https://github.com/ByteAcademyCo/Exercises/tree/master/data_structures) | -| 4 | [Algorithms](https://github.com/ByteAcademyCo/Exercises/tree/master/algorithms) | -| 5 | [Software Theory](https://github.com/ByteAcademyCo/Exercises/tree/master/software_theory) | +# Exercises + +| Module ID | Module Name | +|:-----------:|:--------:| +| 1 | [Introduction and Environment](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_and_environment) | +| 2 | [Introduction to Python](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_to_python) | +| 3 | [Data Structures](https://github.com/ByteAcademyCo/Exercises/tree/master/data_structures) | +| 4 | [Algorithms](https://github.com/ByteAcademyCo/Exercises/tree/master/algorithms) | +| 5 | [Software Theory](https://github.com/ByteAcademyCo/Exercises/tree/master/software_theory) | diff --git a/algorithms/README.md b/algorithms/README.md index 2e573ceb..35f1d978 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -1,8 +1,8 @@ -# Exercise Organization - -## Exercise Sections -* Graph Traversal -* Sorting -* Bit Manipulation -* String Manipulation -* Dynamic Programming +# Exercise Organization + +## Exercise Sections +* Graph Traversal +* Sorting +* Bit Manipulation +* String Manipulation +* Dynamic Programming diff --git a/algorithms/dynamic_programming/.vscode/settings.json b/algorithms/dynamic_programming/.vscode/settings.json index 988937c0..56c57afb 100644 --- a/algorithms/dynamic_programming/.vscode/settings.json +++ b/algorithms/dynamic_programming/.vscode/settings.json @@ -1,3 +1,3 @@ -{ - "python.pythonPath": "/usr/local/bin/python3" +{ + "python.pythonPath": "/usr/local/bin/python3" } \ No newline at end of file diff --git a/algorithms/dynamic_programming/README.md b/algorithms/dynamic_programming/README.md index dc187424..c1c793a2 100644 --- a/algorithms/dynamic_programming/README.md +++ b/algorithms/dynamic_programming/README.md @@ -1,8 +1,8 @@ -# Exercises for Dynamic Programming - -* 1_Dynamic_Programming1 -* 1_Dynamic_Programming2 -* 1_Dynamic_Programming3 -* 2_Dynamic_Programming1 -* 2_Dynamic_Programming2 -* 3_Dynamic_Programming1 +# Exercises for Dynamic Programming + +* 1_Dynamic_Programming1 +* 1_Dynamic_Programming2 +* 1_Dynamic_Programming3 +* 2_Dynamic_Programming1 +* 2_Dynamic_Programming2 +* 3_Dynamic_Programming1 diff --git a/algorithms/dynamic_programming/Tribonacci/README.md b/algorithms/dynamic_programming/Tribonacci/README.md index 90783dc7..60dc5f0c 100644 --- a/algorithms/dynamic_programming/Tribonacci/README.md +++ b/algorithms/dynamic_programming/Tribonacci/README.md @@ -1,21 +1,21 @@ -# Dynamic Programming Recursion - Tribonacci Sequence - -## Motivation -We use Dynamic Programming algorithms when we have overlapping subproblems. If we have a naive recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. We can store the results of the subproblems, so that we do not have to re-compute them when needed later. -Dynamic programing can optimize the time complexity of a problem from exponential `O(2^n)` to polynomial `O(n^c)`, for some constant `c`. - -## Problem Description -The Tribonacci sequence is defined as `T(0) = 0`, `T(1) = 0`, `T(2) = 1`, and `T(n) = T(n-1) + T(n-2) + T(n-3)` for `n>=3`. In the *solution.py* file, using dynamic programming, define a recursive function `tribonacci` that consumes a positive integer `n` and returns the `nth` tribonacci number. - -## Example -``` -tribonacci(3) == 1 -tribonacci(6) == 7 -tribonacci(10) == 81 -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Dynamic Programming Recursion - Tribonacci Sequence + +## Motivation +We use Dynamic Programming algorithms when we have overlapping subproblems. If we have a naive recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. We can store the results of the subproblems, so that we do not have to re-compute them when needed later. +Dynamic programing can optimize the time complexity of a problem from exponential `O(2^n)` to polynomial `O(n^c)`, for some constant `c`. + +## Problem Description +The Tribonacci sequence is defined as `T(0) = 0`, `T(1) = 0`, `T(2) = 1`, and `T(n) = T(n-1) + T(n-2) + T(n-3)` for `n>=3`. In the *solution.py* file, using dynamic programming, define a recursive function `tribonacci` that consumes a positive integer `n` and returns the `nth` tribonacci number. + +## Example +``` +tribonacci(3) == 1 +tribonacci(6) == 7 +tribonacci(10) == 81 +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory \ No newline at end of file diff --git a/algorithms/dynamic_programming/Tribonacci/solution/solution.py b/algorithms/dynamic_programming/Tribonacci/solution/solution.py index 7e9b2f2d..c5193430 100644 --- a/algorithms/dynamic_programming/Tribonacci/solution/solution.py +++ b/algorithms/dynamic_programming/Tribonacci/solution/solution.py @@ -1,15 +1,15 @@ -def tribonacci(n): - if n == 0: - return 0 - elif n == 1: - return 0 - elif n == 2: - return 1 - # create a memo list to store the ith tribonacci number at memo[i] - memo = [-1 for i in range(n+1)] - memo[0] = 0 - memo[1] = 0 - memo[2] = 1 - for i in range(3, n+1): - memo[i] = memo[i-3] + memo[i-2] + memo[i-1] +def tribonacci(n): + if n == 0: + return 0 + elif n == 1: + return 0 + elif n == 2: + return 1 + # create a memo list to store the ith tribonacci number at memo[i] + memo = [-1 for i in range(n+1)] + memo[0] = 0 + memo[1] = 0 + memo[2] = 1 + for i in range(3, n+1): + memo[i] = memo[i-3] + memo[i-2] + memo[i-1] return memo[i] \ No newline at end of file diff --git a/algorithms/dynamic_programming/Tribonacci/solution/test_solution.py b/algorithms/dynamic_programming/Tribonacci/solution/test_solution.py index 426ff084..c0b0172c 100644 --- a/algorithms/dynamic_programming/Tribonacci/solution/test_solution.py +++ b/algorithms/dynamic_programming/Tribonacci/solution/test_solution.py @@ -1,12 +1,12 @@ -def test_solution(): - import solution - - assert solution.tribonacci(0) == 0 - assert solution.tribonacci(1) == 0 - assert solution.tribonacci(2) == 1 - assert solution.tribonacci(3) == 1 - assert solution.tribonacci(4) == 2 - assert solution.tribonacci(5) == 4 - assert solution.tribonacci(10) == 81 - assert solution.tribonacci(15) == 1705 +def test_solution(): + import solution + + assert solution.tribonacci(0) == 0 + assert solution.tribonacci(1) == 0 + assert solution.tribonacci(2) == 1 + assert solution.tribonacci(3) == 1 + assert solution.tribonacci(4) == 2 + assert solution.tribonacci(5) == 4 + assert solution.tribonacci(10) == 81 + assert solution.tribonacci(15) == 1705 assert solution.tribonacci(19) == 19513 \ No newline at end of file diff --git a/algorithms/dynamic_programming/factorial/README.md b/algorithms/dynamic_programming/factorial/README.md index 1cb616e5..bddab376 100644 --- a/algorithms/dynamic_programming/factorial/README.md +++ b/algorithms/dynamic_programming/factorial/README.md @@ -1,18 +1,18 @@ -# Simple Recursion - Factorial - -## Problem Description -In the *solution.py* file, define a recursive function `factorial` that consumes a positive integer `n` and returns the factorial of `n`. We define the factorial of `n` as `n! = n*(n-1)*(n-2)* ... *1`. - -## Example -``` -factorial(1) == 1 -factorial(2) == 2 -factorial(5) == 120 -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Simple Recursion - Factorial + +## Problem Description +In the *solution.py* file, define a recursive function `factorial` that consumes a positive integer `n` and returns the factorial of `n`. We define the factorial of `n` as `n! = n*(n-1)*(n-2)* ... *1`. + +## Example +``` +factorial(1) == 1 +factorial(2) == 2 +factorial(5) == 120 +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/dynamic_programming/factorial/solution/solution.py b/algorithms/dynamic_programming/factorial/solution/solution.py index fa53c9fc..e3ea6521 100644 --- a/algorithms/dynamic_programming/factorial/solution/solution.py +++ b/algorithms/dynamic_programming/factorial/solution/solution.py @@ -1,5 +1,5 @@ -def factorial(n): - if n <= 1: - return 1 - else: +def factorial(n): + if n <= 1: + return 1 + else: return n * factorial(n-1) \ No newline at end of file diff --git a/algorithms/dynamic_programming/factorial/solution/test_solution.py b/algorithms/dynamic_programming/factorial/solution/test_solution.py index cd254b93..3e700b91 100644 --- a/algorithms/dynamic_programming/factorial/solution/test_solution.py +++ b/algorithms/dynamic_programming/factorial/solution/test_solution.py @@ -1,8 +1,8 @@ -def test_solution(): - import solution - - assert solution.factorial(1) == 1 - assert solution.factorial(2) == 2 - assert solution.factorial(5) == 120 - assert solution.factorial(10) == 3628800 - +def test_solution(): + import solution + + assert solution.factorial(1) == 1 + assert solution.factorial(2) == 2 + assert solution.factorial(5) == 120 + assert solution.factorial(10) == 3628800 + diff --git a/algorithms/dynamic_programming/is_palindrome/README.md b/algorithms/dynamic_programming/is_palindrome/README.md index 88163ea2..ef2820f5 100644 --- a/algorithms/dynamic_programming/is_palindrome/README.md +++ b/algorithms/dynamic_programming/is_palindrome/README.md @@ -1,18 +1,18 @@ -# Simple Recursion - Is Palindrome - -## Problem Description -In the *solution.py* file, define a recursive function `is_palindrome` that consumes a string `str` and returns the boolean value `True` if the string is a palindrome and `False` otherwise. A palindrome is defined as a string of letters that reads the same forwards and backwards. - -## Example -``` -is_palindrome("racecar") == True -is_palindrome("mom") == True -is_palindrome("shrek") == False -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Simple Recursion - Is Palindrome + +## Problem Description +In the *solution.py* file, define a recursive function `is_palindrome` that consumes a string `str` and returns the boolean value `True` if the string is a palindrome and `False` otherwise. A palindrome is defined as a string of letters that reads the same forwards and backwards. + +## Example +``` +is_palindrome("racecar") == True +is_palindrome("mom") == True +is_palindrome("shrek") == False +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/dynamic_programming/is_palindrome/solution/solution.py b/algorithms/dynamic_programming/is_palindrome/solution/solution.py index b03e61bf..a12f56da 100644 --- a/algorithms/dynamic_programming/is_palindrome/solution/solution.py +++ b/algorithms/dynamic_programming/is_palindrome/solution/solution.py @@ -1,10 +1,10 @@ -def is_palindrome(string): - # a string of len 1 is by defnition a palindrome so we return True - if len(string) <= 1: - return True - else: - # if the first and last charaters are equal - # we recurse in the rest of the string removing the - # first and last character to check if the rest of - # the string is a palindrome. +def is_palindrome(string): + # a string of len 1 is by defnition a palindrome so we return True + if len(string) <= 1: + return True + else: + # if the first and last charaters are equal + # we recurse in the rest of the string removing the + # first and last character to check if the rest of + # the string is a palindrome. return string[0] == string[-1] and is_palindrome(string[1:-1]) \ No newline at end of file diff --git a/algorithms/dynamic_programming/is_palindrome/solution/test_solution.py b/algorithms/dynamic_programming/is_palindrome/solution/test_solution.py index 5d877e33..8d23da18 100644 --- a/algorithms/dynamic_programming/is_palindrome/solution/test_solution.py +++ b/algorithms/dynamic_programming/is_palindrome/solution/test_solution.py @@ -1,11 +1,11 @@ -def test_solution(): - import solution - - assert solution.is_palindrome("racecar") == True - assert solution.is_palindrome("a") == True - assert solution.is_palindrome("racecars") == False - assert solution.is_palindrome("lol") == True - assert solution.is_palindrome("noon") == True - assert solution.is_palindrome("at") == False - assert solution.is_palindrome("shrek") == False - +def test_solution(): + import solution + + assert solution.is_palindrome("racecar") == True + assert solution.is_palindrome("a") == True + assert solution.is_palindrome("racecars") == False + assert solution.is_palindrome("lol") == True + assert solution.is_palindrome("noon") == True + assert solution.is_palindrome("at") == False + assert solution.is_palindrome("shrek") == False + diff --git a/algorithms/dynamic_programming/knap_sack_problem/README.md b/algorithms/dynamic_programming/knap_sack_problem/README.md index 10f871e7..9d54bee8 100644 --- a/algorithms/dynamic_programming/knap_sack_problem/README.md +++ b/algorithms/dynamic_programming/knap_sack_problem/README.md @@ -1,23 +1,23 @@ -# Dynamic Programming Recursion - Knapsack Problem - -## Motivation -We use Dynamic Programming algorithms when we have overlapping subproblems. If we have a naive recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. We can store the results of the subproblems, so that we do not have to re-compute them when needed later. -Dynamic programing can optimize the time complexity of a problem from exponential `O(2^n)` to polynomial `O(n^c)`, for some constant `c`. - -## Problem Description -You are going on a camping trip and you have a knapsack you wish to pack with a weight capacity of `x` lbs. You are given a dictiomary where the keys are strings containing the names of items which you wish bring on your trip, which are mapped to a touple, containing the value of the given item and weight in lbs of the given item. The higher the value of the item, the more important it is to you to bring on your trip. - -In the *solution.py* file, using dynamic programming, define a function `knap_sack` that consumes a positive integer `x` and a dictionary `items`, and returns the maximal value of items you can bring in your knapsack without exceeding the maximal capacity `x`. - -## Example -``` -items = {"hat": (1,2), "sunscreen": (3,2), "food": (6,4), "water": (5,3)} -knap_sack(5, items) == 8 -``` -You could either bring a hat and water on your trip, which would give you a total weight of 5lbs in your knapsack, and a value of 6. Or you could only bring food on your trip, which would give you total weight of 4lbs in your knapsack and a value of 6. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Dynamic Programming Recursion - Knapsack Problem + +## Motivation +We use Dynamic Programming algorithms when we have overlapping subproblems. If we have a naive recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. We can store the results of the subproblems, so that we do not have to re-compute them when needed later. +Dynamic programing can optimize the time complexity of a problem from exponential `O(2^n)` to polynomial `O(n^c)`, for some constant `c`. + +## Problem Description +You are going on a camping trip and you have a knapsack you wish to pack with a weight capacity of `x` lbs. You are given a dictiomary where the keys are strings containing the names of items which you wish bring on your trip, which are mapped to a touple, containing the value of the given item and weight in lbs of the given item. The higher the value of the item, the more important it is to you to bring on your trip. + +In the *solution.py* file, using dynamic programming, define a function `knap_sack` that consumes a positive integer `x` and a dictionary `items`, and returns the maximal value of items you can bring in your knapsack without exceeding the maximal capacity `x`. + +## Example +``` +items = {"hat": (1,2), "sunscreen": (3,2), "food": (6,4), "water": (5,3)} +knap_sack(5, items) == 8 +``` +You could either bring a hat and water on your trip, which would give you a total weight of 5lbs in your knapsack, and a value of 6. Or you could only bring food on your trip, which would give you total weight of 4lbs in your knapsack and a value of 6. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory \ No newline at end of file diff --git a/algorithms/dynamic_programming/knap_sack_problem/solution/solution.py b/algorithms/dynamic_programming/knap_sack_problem/solution/solution.py index 25db6f49..e4f6ae43 100644 --- a/algorithms/dynamic_programming/knap_sack_problem/solution/solution.py +++ b/algorithms/dynamic_programming/knap_sack_problem/solution/solution.py @@ -1,34 +1,34 @@ -def knap_sack(x, items): - num_items = len(items) - wt_lst = [] - val_lst = [] - # get the weight and values of each item in val_lst and wt_lst. - for v,w in items.values(): - val_lst.append(v) - wt_lst.append(w) - - # Create a len(items) by x array to keep track of the max_val once - # you've looked at all items up to the ith item if you have a weight of w. - K = [[0 for i in range(x + 1)] for i in range(num_items + 1)] - - # for i from 0 to num_items - for i in range(num_items + 1): - # for weight from 0 to x - for w in range(x + 1): - # when we hae no items and weight 0, we have 0 value in our bag - if i == 0 or w == 0: - K[i][w] = 0 - # if the weight of the ith item is less than or equal to current - # weight w, the max value we can add is either the val of the ith - # item + the max-val of all the i-1 elements and weight - weight of ith - # element or the value of all the i-1 elements with current weight. - elif wt_lst[i-1] <= w: - # note that the val and weight of the ith element is at position i-1 - # in val_lst and wt_lst. - K[i][w] = max(val_lst[i-1] + K[i-1][w-wt_lst[i-1]], K[i-1][w]) - else: - # if the weight of the ith element is greater than w, we cannot use it - # so the max value we can have is just the maximum value we found for - # all the i-1 elements with current weight w. - K[i][w] = K[i-1][w] +def knap_sack(x, items): + num_items = len(items) + wt_lst = [] + val_lst = [] + # get the weight and values of each item in val_lst and wt_lst. + for v,w in items.values(): + val_lst.append(v) + wt_lst.append(w) + + # Create a len(items) by x array to keep track of the max_val once + # you've looked at all items up to the ith item if you have a weight of w. + K = [[0 for i in range(x + 1)] for i in range(num_items + 1)] + + # for i from 0 to num_items + for i in range(num_items + 1): + # for weight from 0 to x + for w in range(x + 1): + # when we hae no items and weight 0, we have 0 value in our bag + if i == 0 or w == 0: + K[i][w] = 0 + # if the weight of the ith item is less than or equal to current + # weight w, the max value we can add is either the val of the ith + # item + the max-val of all the i-1 elements and weight - weight of ith + # element or the value of all the i-1 elements with current weight. + elif wt_lst[i-1] <= w: + # note that the val and weight of the ith element is at position i-1 + # in val_lst and wt_lst. + K[i][w] = max(val_lst[i-1] + K[i-1][w-wt_lst[i-1]], K[i-1][w]) + else: + # if the weight of the ith element is greater than w, we cannot use it + # so the max value we can have is just the maximum value we found for + # all the i-1 elements with current weight w. + K[i][w] = K[i-1][w] return K[num_items][x] \ No newline at end of file diff --git a/algorithms/dynamic_programming/knap_sack_problem/solution/test_solution.py b/algorithms/dynamic_programming/knap_sack_problem/solution/test_solution.py index 1e1acae8..1752ab70 100644 --- a/algorithms/dynamic_programming/knap_sack_problem/solution/test_solution.py +++ b/algorithms/dynamic_programming/knap_sack_problem/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - import solution - - assert solution.knap_sack(5, {"hat": (1,2), "sunscreen": (3,2), "food": (6,4), "water": (5,3)}) == 8 - assert solution.knap_sack(5, {}) == 0 - assert solution.knap_sack(0, {"hat": (1,2), "sunscreen": (3,2), "food": (6,4), "water": (5,3)}) == 0 +def test_solution(): + import solution + + assert solution.knap_sack(5, {"hat": (1,2), "sunscreen": (3,2), "food": (6,4), "water": (5,3)}) == 8 + assert solution.knap_sack(5, {}) == 0 + assert solution.knap_sack(0, {"hat": (1,2), "sunscreen": (3,2), "food": (6,4), "water": (5,3)}) == 0 assert solution.knap_sack(5, {"hat": (2,2), "sunscreen": (3,2), "food": (4,4)}) == 5 \ No newline at end of file diff --git a/algorithms/dynamic_programming/longest_common_subsequence/README.md b/algorithms/dynamic_programming/longest_common_subsequence/README.md index 33cd17f1..8666d31c 100644 --- a/algorithms/dynamic_programming/longest_common_subsequence/README.md +++ b/algorithms/dynamic_programming/longest_common_subsequence/README.md @@ -1,22 +1,22 @@ -# Dynamic Programming Recursion - Longest Common Subsequence - -## Motivation -We use Dynamic Programming algorithms when we have overlapping subproblems. If we have a naive recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. We can store the results of the subproblems, so that we do not have to re-compute them when needed later. -Dynamic programing can optimize the time complexity of a problem from exponential `O(2^n)` to polynomial `O(n^c)`, for some constant `c`. - -## Problem Description -In the *solution.py* file, using dynamic programming, define a function `longest_common_subseq` that consumes two strings `str1` and `str2` and returns the length of the longest common subsequence between the two strings. Note that the characters do not need to be in contiguous order within the strings to be considered a subsequence. - -## Example -``` -str1 = "abcdabcf" -str2 = "ecfdacagb" -longest_common_subseq(str1, str2) == 4 -``` -The longest common subsquence between str1 and str2 is either "cdac" or "cdab" both which have length 4. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Dynamic Programming Recursion - Longest Common Subsequence + +## Motivation +We use Dynamic Programming algorithms when we have overlapping subproblems. If we have a naive recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. We can store the results of the subproblems, so that we do not have to re-compute them when needed later. +Dynamic programing can optimize the time complexity of a problem from exponential `O(2^n)` to polynomial `O(n^c)`, for some constant `c`. + +## Problem Description +In the *solution.py* file, using dynamic programming, define a function `longest_common_subseq` that consumes two strings `str1` and `str2` and returns the length of the longest common subsequence between the two strings. Note that the characters do not need to be in contiguous order within the strings to be considered a subsequence. + +## Example +``` +str1 = "abcdabcf" +str2 = "ecfdacagb" +longest_common_subseq(str1, str2) == 4 +``` +The longest common subsquence between str1 and str2 is either "cdac" or "cdab" both which have length 4. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory \ No newline at end of file diff --git a/algorithms/dynamic_programming/longest_common_subsequence/solution/solution.py b/algorithms/dynamic_programming/longest_common_subsequence/solution/solution.py index 5c2ebfec..5587219b 100644 --- a/algorithms/dynamic_programming/longest_common_subsequence/solution/solution.py +++ b/algorithms/dynamic_programming/longest_common_subsequence/solution/solution.py @@ -1,29 +1,29 @@ -def longest_common_subseq(str1, str2): - # find the length of the strings - len1 = len(str1) - len2 = len(str2) - - # memo will be a len2 by len1 matrix. memo[i][j] will - # be used to store the length of the LCS of str1[0...i-1] - # and str2[0...j-1] - memo = [[None]*(len2 + 1) for i in range(len1 + 1)] - - for i in range(len1 + 1): - for j in range(len2 + 1): - # if either i or j is 0, the LCS will be 0 - if i == 0 or j == 0 : - memo[i][j] = 0 - # if the ith element in str1 == the ith element in str2 - # the LCS will be 1+ the LCS of str1[0...i-2] and str2[0...j-2] - # which we already stored in memo[i-1][j-1]. - elif str1[i-1] == str2[j-1]: - memo[i][j] = memo[i-1][j-1]+1 - else: - # otherwise the ith and jth elements are not equal - # so the LCS will be the max of the LCS for - # str1[0...i-2] and str2[0...j-1] OR - # str1[0...i-1] and str2[0...j-2]. - memo[i][j] = max(memo[i-1][j], memo[i][j-1]) - - # memo[len1][len2] contains the length of LCS of str1[0..len1-1] & str2[0..len2-1] +def longest_common_subseq(str1, str2): + # find the length of the strings + len1 = len(str1) + len2 = len(str2) + + # memo will be a len2 by len1 matrix. memo[i][j] will + # be used to store the length of the LCS of str1[0...i-1] + # and str2[0...j-1] + memo = [[None]*(len2 + 1) for i in range(len1 + 1)] + + for i in range(len1 + 1): + for j in range(len2 + 1): + # if either i or j is 0, the LCS will be 0 + if i == 0 or j == 0 : + memo[i][j] = 0 + # if the ith element in str1 == the ith element in str2 + # the LCS will be 1+ the LCS of str1[0...i-2] and str2[0...j-2] + # which we already stored in memo[i-1][j-1]. + elif str1[i-1] == str2[j-1]: + memo[i][j] = memo[i-1][j-1]+1 + else: + # otherwise the ith and jth elements are not equal + # so the LCS will be the max of the LCS for + # str1[0...i-2] and str2[0...j-1] OR + # str1[0...i-1] and str2[0...j-2]. + memo[i][j] = max(memo[i-1][j], memo[i][j-1]) + + # memo[len1][len2] contains the length of LCS of str1[0..len1-1] & str2[0..len2-1] return memo[len1][len2] \ No newline at end of file diff --git a/algorithms/dynamic_programming/longest_common_subsequence/solution/test_solution.py b/algorithms/dynamic_programming/longest_common_subsequence/solution/test_solution.py index ee6a2cad..b2701c02 100644 --- a/algorithms/dynamic_programming/longest_common_subsequence/solution/test_solution.py +++ b/algorithms/dynamic_programming/longest_common_subsequence/solution/test_solution.py @@ -1,11 +1,11 @@ -def test_solution(): - import solution - - assert solution.longest_common_subseq("abcdabcf", "ecfdacagb") == 4 - assert solution.longest_common_subseq("", "") == 0 - assert solution.longest_common_subseq("abc", "") == 0 - assert solution.longest_common_subseq("", "a") == 0 - assert solution.longest_common_subseq("a", "bc") == 0 - assert solution.longest_common_subseq("a", "ba") == 1 - assert solution.longest_common_subseq("abcdefg", "hijklmn") == 0 +def test_solution(): + import solution + + assert solution.longest_common_subseq("abcdabcf", "ecfdacagb") == 4 + assert solution.longest_common_subseq("", "") == 0 + assert solution.longest_common_subseq("abc", "") == 0 + assert solution.longest_common_subseq("", "a") == 0 + assert solution.longest_common_subseq("a", "bc") == 0 + assert solution.longest_common_subseq("a", "ba") == 1 + assert solution.longest_common_subseq("abcdefg", "hijklmn") == 0 assert solution.longest_common_subseq("abcda", "fgafbhadce") == 3 \ No newline at end of file diff --git a/algorithms/dynamic_programming/palindromic_substring/README.md b/algorithms/dynamic_programming/palindromic_substring/README.md index ebac261c..5d858e8a 100644 --- a/algorithms/dynamic_programming/palindromic_substring/README.md +++ b/algorithms/dynamic_programming/palindromic_substring/README.md @@ -1,20 +1,20 @@ -# Dynamic Programming Recursion - Longest Palindromic Substring - -## Motivation -We use Dynamic Programming algorithms when we have overlapping subproblems. If we have a naive recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. We can store the results of the subproblems, so that we do not have to re-compute them when needed later. -Dynamic programing can optimize the time complexity of a problem from exponential `O(2^n)` to polynomial `O(n^c)`, for some constant `c`. - -## Problem Description -In the *solution.py* file, using dynamic programming, define a function `longest_palindrome_substr` that consumes a string `str` and returns the length of the longest palindromic substring contained in the string. - -## Example -``` -longest_palindrome_substr("abaccad") == 4 -longest_palindrome_substr("abcadefb") == 1 -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Dynamic Programming Recursion - Longest Palindromic Substring + +## Motivation +We use Dynamic Programming algorithms when we have overlapping subproblems. If we have a naive recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. We can store the results of the subproblems, so that we do not have to re-compute them when needed later. +Dynamic programing can optimize the time complexity of a problem from exponential `O(2^n)` to polynomial `O(n^c)`, for some constant `c`. + +## Problem Description +In the *solution.py* file, using dynamic programming, define a function `longest_palindrome_substr` that consumes a string `str` and returns the length of the longest palindromic substring contained in the string. + +## Example +``` +longest_palindrome_substr("abaccad") == 4 +longest_palindrome_substr("abcadefb") == 1 +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory \ No newline at end of file diff --git a/algorithms/dynamic_programming/palindromic_substring/solution/solution.py b/algorithms/dynamic_programming/palindromic_substring/solution/solution.py index 708a87d2..57ae09f2 100644 --- a/algorithms/dynamic_programming/palindromic_substring/solution/solution.py +++ b/algorithms/dynamic_programming/palindromic_substring/solution/solution.py @@ -1,44 +1,44 @@ -def longest_palindrome_substr(str): - n = len(str) - if n == 0: - return 0 - - # We create an n by n table, wwhere table[i][j] - # will be True if substring str[i..j] is a palindrome - # and False otherwise. We initialise all values to 0. - table = [[0 for x in range(n)] for y in range(n)] - - # All substrings of length 1 are palindromes set the - # maxLength palindrome we've seen so far to be 1. - maxLength = 1 - # table[i][i] is looking at substrings str[i] only one - # element, so it will always be True that it is a palindrome. - for i in range(n): - table[i][i] = True - - # check for sub-strings of length 2. - for i in range(n-1): - # for substring length 2 we just need to check if str[i] == str[i+1] - if (str[i] == str[i + 1]): - table[i][i + 1] = True - # maxLength we've seen so far is 2. - maxLength = 2 - - # Check for lengths greater than 2. - # k is length of substring - for k in range(3, n+1): - # Fix the starting index - for i in range(n - k + 1): - - # Get the ending index of substring from - # starting index i and length k - j = i + k - 1 - - # checking for sub-string from ith index to jth index - # iff str[i+1] to st[j-1] is a palindrome - if (table[i + 1][j - 1] and str[i] == str[j]): - table[i][j] = True - if (k > maxLength): - maxLength = k - # return the maxLength substring we have found. +def longest_palindrome_substr(str): + n = len(str) + if n == 0: + return 0 + + # We create an n by n table, wwhere table[i][j] + # will be True if substring str[i..j] is a palindrome + # and False otherwise. We initialise all values to 0. + table = [[0 for x in range(n)] for y in range(n)] + + # All substrings of length 1 are palindromes set the + # maxLength palindrome we've seen so far to be 1. + maxLength = 1 + # table[i][i] is looking at substrings str[i] only one + # element, so it will always be True that it is a palindrome. + for i in range(n): + table[i][i] = True + + # check for sub-strings of length 2. + for i in range(n-1): + # for substring length 2 we just need to check if str[i] == str[i+1] + if (str[i] == str[i + 1]): + table[i][i + 1] = True + # maxLength we've seen so far is 2. + maxLength = 2 + + # Check for lengths greater than 2. + # k is length of substring + for k in range(3, n+1): + # Fix the starting index + for i in range(n - k + 1): + + # Get the ending index of substring from + # starting index i and length k + j = i + k - 1 + + # checking for sub-string from ith index to jth index + # iff str[i+1] to st[j-1] is a palindrome + if (table[i + 1][j - 1] and str[i] == str[j]): + table[i][j] = True + if (k > maxLength): + maxLength = k + # return the maxLength substring we have found. return maxLength \ No newline at end of file diff --git a/algorithms/dynamic_programming/palindromic_substring/solution/test_solution.py b/algorithms/dynamic_programming/palindromic_substring/solution/test_solution.py index fe1362d1..fa98d086 100644 --- a/algorithms/dynamic_programming/palindromic_substring/solution/test_solution.py +++ b/algorithms/dynamic_programming/palindromic_substring/solution/test_solution.py @@ -1,8 +1,8 @@ -def test_solution(): - import solution - - assert solution.longest_palindrome_substr("abaccad") == 4 - assert solution.longest_palindrome_substr("abcadefb") == 1 - assert solution.longest_palindrome_substr("") == 0 - assert solution.longest_palindrome_substr("a") == 1 +def test_solution(): + import solution + + assert solution.longest_palindrome_substr("abaccad") == 4 + assert solution.longest_palindrome_substr("abcadefb") == 1 + assert solution.longest_palindrome_substr("") == 0 + assert solution.longest_palindrome_substr("a") == 1 assert solution.longest_palindrome_substr("abcadefbbfcfbbfeads") == 11 \ No newline at end of file diff --git a/algorithms/dynamic_programming/paths_to_nth_stair/README.md b/algorithms/dynamic_programming/paths_to_nth_stair/README.md index 2bd72b28..2f64e1e2 100644 --- a/algorithms/dynamic_programming/paths_to_nth_stair/README.md +++ b/algorithms/dynamic_programming/paths_to_nth_stair/README.md @@ -1,20 +1,20 @@ -# Dynamic Programming Recursion - Paths to nth Stair - -## Motivation -We use Dynamic Programming algorithms when we have overlapping subproblems. If we have a naive recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. We can store the results of the subproblems, so that we do not have to re-compute them when needed later. -Dynamic programing can optimize the time complexity of a problem from exponential `O(2^n)` to polynomial `O(n^c)`, for some constant `c`. - -## Problem Description -You are given a flight of stairs where you can either climb up by one or two stairs at each step. In the *solution.py* file, define a recursive function `paths_nth_stair` that consumes a positive integer `n` and returns the total number of ways to get to the `nth` stair. - -## Example -``` -paths_nth_stair(3) == 3 -``` -We can go up the stairs one at a time, or we can take the first two stairs at once and then take the final stair, or we can take the first stair and finish by taking the last two stairs in our final step. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Dynamic Programming Recursion - Paths to nth Stair + +## Motivation +We use Dynamic Programming algorithms when we have overlapping subproblems. If we have a naive recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. We can store the results of the subproblems, so that we do not have to re-compute them when needed later. +Dynamic programing can optimize the time complexity of a problem from exponential `O(2^n)` to polynomial `O(n^c)`, for some constant `c`. + +## Problem Description +You are given a flight of stairs where you can either climb up by one or two stairs at each step. In the *solution.py* file, define a recursive function `paths_nth_stair` that consumes a positive integer `n` and returns the total number of ways to get to the `nth` stair. + +## Example +``` +paths_nth_stair(3) == 3 +``` +We can go up the stairs one at a time, or we can take the first two stairs at once and then take the final stair, or we can take the first stair and finish by taking the last two stairs in our final step. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/dynamic_programming/paths_to_nth_stair/solution/solution.py b/algorithms/dynamic_programming/paths_to_nth_stair/solution/solution.py index 11285e5f..e6c41818 100644 --- a/algorithms/dynamic_programming/paths_to_nth_stair/solution/solution.py +++ b/algorithms/dynamic_programming/paths_to_nth_stair/solution/solution.py @@ -1,19 +1,19 @@ -def paths_nth_stair(n): - # if n is 0, 1, or 2, the number of ways to climb up is just n. - if n <= 2: - return n - else: - # we create a memo list to keep track of the number of ways to climb to - # the ith stair. We initialise the values to -1. - memo = [-1 for i in range(n+1)] - # we know the ways to climb to the 1st stair is 1 so memo[1] = 1 - memo[1] = 1 - # we know the ways to climb to the 2nd stair is 2 so memo[2] = 2 - memo[2] = 2 - # we itterate through the rest of the indices, and notice the - # recurrence relation, the number of ways to get to the ith stair - # will be to start by climbing up 1 stair and then climbing up i-1 stairs - # or climbing up 2 stairs and then climbing up i-2 stairs - for i in range(3, n+1): - memo[i] = memo[i-1] + memo[i-2] +def paths_nth_stair(n): + # if n is 0, 1, or 2, the number of ways to climb up is just n. + if n <= 2: + return n + else: + # we create a memo list to keep track of the number of ways to climb to + # the ith stair. We initialise the values to -1. + memo = [-1 for i in range(n+1)] + # we know the ways to climb to the 1st stair is 1 so memo[1] = 1 + memo[1] = 1 + # we know the ways to climb to the 2nd stair is 2 so memo[2] = 2 + memo[2] = 2 + # we itterate through the rest of the indices, and notice the + # recurrence relation, the number of ways to get to the ith stair + # will be to start by climbing up 1 stair and then climbing up i-1 stairs + # or climbing up 2 stairs and then climbing up i-2 stairs + for i in range(3, n+1): + memo[i] = memo[i-1] + memo[i-2] return memo[n] \ No newline at end of file diff --git a/algorithms/dynamic_programming/paths_to_nth_stair/solution/test_solution.py b/algorithms/dynamic_programming/paths_to_nth_stair/solution/test_solution.py index b491a991..372f1257 100644 --- a/algorithms/dynamic_programming/paths_to_nth_stair/solution/test_solution.py +++ b/algorithms/dynamic_programming/paths_to_nth_stair/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - import solution - - assert solution.paths_nth_stair(3) == 3 - assert solution.paths_nth_stair(1) == 1 - assert solution.paths_nth_stair(2) == 2 +def test_solution(): + import solution + + assert solution.paths_nth_stair(3) == 3 + assert solution.paths_nth_stair(1) == 1 + assert solution.paths_nth_stair(2) == 2 assert solution.paths_nth_stair(5) == 8 \ No newline at end of file diff --git a/algorithms/dynamic_programming/product_sequence_n/README.md b/algorithms/dynamic_programming/product_sequence_n/README.md index a763967c..5ddedc47 100644 --- a/algorithms/dynamic_programming/product_sequence_n/README.md +++ b/algorithms/dynamic_programming/product_sequence_n/README.md @@ -1,17 +1,17 @@ -# Simple Recursion - Product of Sequence - -## Problem Description -In the *solution.py* file, define a recursive function `product_sequence_n` that consumes a positive integer `n` and returns the product of the mathematical sequence `n*(n-2)*(n-4) ... *(n-x)>0`. - -## Example -``` -product_sequence_n(4) == 8 -product_sequence_n(5) == 15 -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Simple Recursion - Product of Sequence + +## Problem Description +In the *solution.py* file, define a recursive function `product_sequence_n` that consumes a positive integer `n` and returns the product of the mathematical sequence `n*(n-2)*(n-4) ... *(n-x)>0`. + +## Example +``` +product_sequence_n(4) == 8 +product_sequence_n(5) == 15 +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/dynamic_programming/product_sequence_n/solution/solution.py b/algorithms/dynamic_programming/product_sequence_n/solution/solution.py index feb88c59..6b9a25bb 100644 --- a/algorithms/dynamic_programming/product_sequence_n/solution/solution.py +++ b/algorithms/dynamic_programming/product_sequence_n/solution/solution.py @@ -1,5 +1,5 @@ -def product_sequence_n(n): - if n <= 1: - return 1 - else: +def product_sequence_n(n): + if n <= 1: + return 1 + else: return n * product_sequence_n(n-2) \ No newline at end of file diff --git a/algorithms/dynamic_programming/product_sequence_n/solution/test_solution.py b/algorithms/dynamic_programming/product_sequence_n/solution/test_solution.py index ebeba96d..57afabc1 100644 --- a/algorithms/dynamic_programming/product_sequence_n/solution/test_solution.py +++ b/algorithms/dynamic_programming/product_sequence_n/solution/test_solution.py @@ -1,9 +1,9 @@ -def test_solution(): - import solution - - assert solution.product_sequence_n(2) == 2 - assert solution.product_sequence_n(5) == 15 - assert solution.product_sequence_n(1) == 1 - assert solution.product_sequence_n(8) == 384 - assert solution.product_sequence_n(9) == 945 - +def test_solution(): + import solution + + assert solution.product_sequence_n(2) == 2 + assert solution.product_sequence_n(5) == 15 + assert solution.product_sequence_n(1) == 1 + assert solution.product_sequence_n(8) == 384 + assert solution.product_sequence_n(9) == 945 + diff --git a/algorithms/dynamic_programming/shortest_path_to_1/README.md b/algorithms/dynamic_programming/shortest_path_to_1/README.md index 38b9f12a..9661c8dc 100644 --- a/algorithms/dynamic_programming/shortest_path_to_1/README.md +++ b/algorithms/dynamic_programming/shortest_path_to_1/README.md @@ -1,20 +1,20 @@ -# Dynamic Programming Recursion - Shortest Path to 1 - -## Motivation -We use Dynamic Programming algorithms when we have overlapping subproblems. If we have a naive recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. We can store the results of the subproblems, so that we do not have to re-compute them when needed later. -Dynamic programing can optimize the time complexity of a problem from exponential `O(2^n)` to polynomial `O(n^c)`, for some constant `c`. - -## Problem Description -You are given three mathematical operations: `-1`, `/2`, and `/3`. In the *solution.py* file, define a function `shortest_path_to_1` that consumes a positive integer `n` and returns the lowest number of operations you can perform to get to 1. You may solve this using breath first search or dynamic programming. - -## Example -``` -shortest_path_to_1(10) == 3 -``` -In the example, with `n=10`, we can naivly assume since `10` is divisible by `2`, we could do `10/2 = 5`, `5-1 = 4`, `4/2 = 2`, `2/2 = 1`. But this is not the shortest path we can take. The shortest path of operations we can take is `10-1 = 9`, `9/3 = 3`, `3/3 = 1`. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Dynamic Programming Recursion - Shortest Path to 1 + +## Motivation +We use Dynamic Programming algorithms when we have overlapping subproblems. If we have a naive recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. We can store the results of the subproblems, so that we do not have to re-compute them when needed later. +Dynamic programing can optimize the time complexity of a problem from exponential `O(2^n)` to polynomial `O(n^c)`, for some constant `c`. + +## Problem Description +You are given three mathematical operations: `-1`, `/2`, and `/3`. In the *solution.py* file, define a function `shortest_path_to_1` that consumes a positive integer `n` and returns the lowest number of operations you can perform to get to 1. You may solve this using breath first search or dynamic programming. + +## Example +``` +shortest_path_to_1(10) == 3 +``` +In the example, with `n=10`, we can naivly assume since `10` is divisible by `2`, we could do `10/2 = 5`, `5-1 = 4`, `4/2 = 2`, `2/2 = 1`. But this is not the shortest path we can take. The shortest path of operations we can take is `10-1 = 9`, `9/3 = 3`, `3/3 = 1`. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/dynamic_programming/shortest_path_to_1/solution/solution.py b/algorithms/dynamic_programming/shortest_path_to_1/solution/solution.py index 76501e02..ffb93745 100644 --- a/algorithms/dynamic_programming/shortest_path_to_1/solution/solution.py +++ b/algorithms/dynamic_programming/shortest_path_to_1/solution/solution.py @@ -1,30 +1,30 @@ -def shortest_path_to_1(n): - # if n is 1 we need 0 steps to get to 1 - if n == 1: - return 0 - # if n is 2 or 3, we only need one step to get to 1 - if n == 2 or n == 3: - return 1 - # create a memo list. memo[i] will store the number of steps - # to get to the ith stair. We initialise the values to -1. - memo = [-1 for i in range(n+1)] - memo[1] = 0 - memo[2] = 1 - memo[3] = 1 - for i in range(4, n+1): - # if i is divisible by 2 and 3 the shortest path will be - # 1 + the minimum path for i-1, i/2 or i/3. We already - # have those values calculated and stored in our memo list. - if i%3 == 0 and i%2 == 0: - memo[i] = 1 + min(memo[i-1], memo[i//3], memo[i//2]) - # if i is divisible by 3 the shortest path will be - # 1 + the minimum path for i-1, or i/3. - elif i%3 == 0: - memo[i] = 1 + min(memo[i-1], memo[i//3]) - # if i is divisible by 2 the shortest path will be - # 1 + the minimum path for i-1, or i/2. - elif i%2 == 0: - memo[i] = 1 + min(memo[i-1], memo[i//2]) - else: - memo[i] = 1 + memo[i-1] - return memo[n] +def shortest_path_to_1(n): + # if n is 1 we need 0 steps to get to 1 + if n == 1: + return 0 + # if n is 2 or 3, we only need one step to get to 1 + if n == 2 or n == 3: + return 1 + # create a memo list. memo[i] will store the number of steps + # to get to the ith stair. We initialise the values to -1. + memo = [-1 for i in range(n+1)] + memo[1] = 0 + memo[2] = 1 + memo[3] = 1 + for i in range(4, n+1): + # if i is divisible by 2 and 3 the shortest path will be + # 1 + the minimum path for i-1, i/2 or i/3. We already + # have those values calculated and stored in our memo list. + if i%3 == 0 and i%2 == 0: + memo[i] = 1 + min(memo[i-1], memo[i//3], memo[i//2]) + # if i is divisible by 3 the shortest path will be + # 1 + the minimum path for i-1, or i/3. + elif i%3 == 0: + memo[i] = 1 + min(memo[i-1], memo[i//3]) + # if i is divisible by 2 the shortest path will be + # 1 + the minimum path for i-1, or i/2. + elif i%2 == 0: + memo[i] = 1 + min(memo[i-1], memo[i//2]) + else: + memo[i] = 1 + memo[i-1] + return memo[n] diff --git a/algorithms/dynamic_programming/shortest_path_to_1/solution/test_solution.py b/algorithms/dynamic_programming/shortest_path_to_1/solution/test_solution.py index d9f4933b..f3ad5c34 100644 --- a/algorithms/dynamic_programming/shortest_path_to_1/solution/test_solution.py +++ b/algorithms/dynamic_programming/shortest_path_to_1/solution/test_solution.py @@ -1,10 +1,10 @@ -def test_solution(): - import solution - - assert solution.shortest_path_to_1(1) == 0 - assert solution.shortest_path_to_1(2) == 1 - assert solution.shortest_path_to_1(3) == 1 - assert solution.shortest_path_to_1(4) == 2 - assert solution.shortest_path_to_1(10) == 3 - assert solution.shortest_path_to_1(16) == 4 +def test_solution(): + import solution + + assert solution.shortest_path_to_1(1) == 0 + assert solution.shortest_path_to_1(2) == 1 + assert solution.shortest_path_to_1(3) == 1 + assert solution.shortest_path_to_1(4) == 2 + assert solution.shortest_path_to_1(10) == 3 + assert solution.shortest_path_to_1(16) == 4 assert solution.shortest_path_to_1(22) == 5 \ No newline at end of file diff --git a/algorithms/dynamic_programming/sum_first_n_integers/README.md b/algorithms/dynamic_programming/sum_first_n_integers/README.md index 15a74f4d..e96df457 100644 --- a/algorithms/dynamic_programming/sum_first_n_integers/README.md +++ b/algorithms/dynamic_programming/sum_first_n_integers/README.md @@ -1,17 +1,17 @@ -# Simple Recursion - Sum of the First n Integers - -## Problem Description -In the *solution.py* file, define a recursive function `sum_first_n` that consumes a positive integer `n` and returns the sum of all the positive integers from `1` to `n` inclusive. I.e. `sum_first_n(n) = 1+2+3...+n`. - -## Example -``` -sum_first_n(2) == 3 -sum_first_n(5) == 15 -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Simple Recursion - Sum of the First n Integers + +## Problem Description +In the *solution.py* file, define a recursive function `sum_first_n` that consumes a positive integer `n` and returns the sum of all the positive integers from `1` to `n` inclusive. I.e. `sum_first_n(n) = 1+2+3...+n`. + +## Example +``` +sum_first_n(2) == 3 +sum_first_n(5) == 15 +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/dynamic_programming/sum_first_n_integers/solution/solution.py b/algorithms/dynamic_programming/sum_first_n_integers/solution/solution.py index 3b1fad98..49a04740 100644 --- a/algorithms/dynamic_programming/sum_first_n_integers/solution/solution.py +++ b/algorithms/dynamic_programming/sum_first_n_integers/solution/solution.py @@ -1,5 +1,5 @@ -def sum_first_n(n): - if n == 1: - return 1 - else: +def sum_first_n(n): + if n == 1: + return 1 + else: return n + sum_first_n(n-1) \ No newline at end of file diff --git a/algorithms/dynamic_programming/sum_first_n_integers/solution/test_solution.py b/algorithms/dynamic_programming/sum_first_n_integers/solution/test_solution.py index d30b394d..b73242fa 100644 --- a/algorithms/dynamic_programming/sum_first_n_integers/solution/test_solution.py +++ b/algorithms/dynamic_programming/sum_first_n_integers/solution/test_solution.py @@ -1,8 +1,8 @@ -def test_solution(): - import solution - - assert solution.sum_first_n(5) == 15 - assert solution.sum_first_n(1) == 1 - assert solution.sum_first_n(15) == 120 - assert solution.sum_first_n(20) == 210 - +def test_solution(): + import solution + + assert solution.sum_first_n(5) == 15 + assert solution.sum_first_n(1) == 1 + assert solution.sum_first_n(15) == 120 + assert solution.sum_first_n(20) == 210 + diff --git a/algorithms/graph_traversal/README.md b/algorithms/graph_traversal/README.md index 76eaaa66..ee2a6fc9 100644 --- a/algorithms/graph_traversal/README.md +++ b/algorithms/graph_traversal/README.md @@ -1,5 +1,5 @@ -# Exercises for Graph Traversal - -* 1_Length -* 2_Most_Neighbors -* 3_Permutations +# Exercises for Graph Traversal + +* 1_Length +* 2_Most_Neighbors +* 3_Permutations diff --git a/algorithms/graph_traversal/count_edges_matrix/README.md b/algorithms/graph_traversal/count_edges_matrix/README.md index 772a6bfe..44607751 100644 --- a/algorithms/graph_traversal/count_edges_matrix/README.md +++ b/algorithms/graph_traversal/count_edges_matrix/README.md @@ -1,36 +1,36 @@ -# Count the Edges - Adjacency Matrix Representation - -## Motivation -A Graph is a non-linear data structure consisting of nodes and edges. -There are two common ways to represent a graph in python: - -1. Adjacency Matrix Representation: - Let n be the number of node in our graph. - We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` - -2. Adjacency List Representation: - We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. - -## Problem Description -In the *solution.py* file, define a function `count_edges` that consumes an adjacency matrix and returns the total -number of edges in the graph defined by the given matrix. A value of `1` at index `ij` represents an edge from node `i` -to node `j`. - -## Example -``` -matrix = [ - [0, 1, 1, 0, 0, 1], - [1, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 1, 1], - [0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0] -] -count_edges(matrix) == 10 -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Count the Edges - Adjacency Matrix Representation + +## Motivation +A Graph is a non-linear data structure consisting of nodes and edges. +There are two common ways to represent a graph in python: + +1. Adjacency Matrix Representation: + Let n be the number of node in our graph. + We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` + +2. Adjacency List Representation: + We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. + +## Problem Description +In the *solution.py* file, define a function `count_edges` that consumes an adjacency matrix and returns the total +number of edges in the graph defined by the given matrix. A value of `1` at index `ij` represents an edge from node `i` +to node `j`. + +## Example +``` +matrix = [ + [0, 1, 1, 0, 0, 1], + [1, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0] +] +count_edges(matrix) == 10 +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/graph_traversal/count_edges_matrix/solution/solution.py b/algorithms/graph_traversal/count_edges_matrix/solution/solution.py index 3f215a5d..72514f4e 100644 --- a/algorithms/graph_traversal/count_edges_matrix/solution/solution.py +++ b/algorithms/graph_traversal/count_edges_matrix/solution/solution.py @@ -1,6 +1,6 @@ -def count_edges(matrix): - edge_count = 0 - for i in range(len(matrix)): - for j in range(len(matrix[i])): - edge_count += matrix[i][j] +def count_edges(matrix): + edge_count = 0 + for i in range(len(matrix)): + for j in range(len(matrix[i])): + edge_count += matrix[i][j] return edge_count \ No newline at end of file diff --git a/algorithms/graph_traversal/count_edges_matrix/solution/test_solution.py b/algorithms/graph_traversal/count_edges_matrix/solution/test_solution.py index a39a8671..710b1c46 100644 --- a/algorithms/graph_traversal/count_edges_matrix/solution/test_solution.py +++ b/algorithms/graph_traversal/count_edges_matrix/solution/test_solution.py @@ -1,13 +1,13 @@ -def test_solution(): - import solution - - matrix = [ - [0, 1, 1, 0, 0, 1], - [1, 0, 1, 0, 1, 0], - [1, 1, 0, 0, 1, 1], - [0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 1, 1] - ] - - assert solution.count_edges(matrix) == 14 - +def test_solution(): + import solution + + matrix = [ + [0, 1, 1, 0, 0, 1], + [1, 0, 1, 0, 1, 0], + [1, 1, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 1, 1] + ] + + assert solution.count_edges(matrix) == 14 + diff --git a/algorithms/graph_traversal/count_islands_list/README.md b/algorithms/graph_traversal/count_islands_list/README.md index 382fd919..1731c097 100644 --- a/algorithms/graph_traversal/count_islands_list/README.md +++ b/algorithms/graph_traversal/count_islands_list/README.md @@ -1,38 +1,38 @@ -# Count the Islands - Adjacency List Representation - -## Motivation -A Graph is a non-linear data structure consisting of nodes and edges. -There are two common ways to represent a graph in python: - -1. Adjacency Matrix Representation: - Let n be the number of node in our graph. - We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` - -2. Adjacency List Representation: - We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. - -## Problem Description -An island is a node with zero incoming or outgoing edges. -In the *solution.py* file, define a function `count_islands` that consumes an adjacency list and returns the total -number of islands in the graph defined by the given adjacency list. - -## Example -``` -adjacency_list = { - 0: [1,3,5], - 1: [0,1,3,6], - 2: [], - 3: [0,3], - 4: [], - 5: [6], - 6: [3,5] -} -count_islands(adjacency_List) == 2 -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Count the Islands - Adjacency List Representation + +## Motivation +A Graph is a non-linear data structure consisting of nodes and edges. +There are two common ways to represent a graph in python: + +1. Adjacency Matrix Representation: + Let n be the number of node in our graph. + We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` + +2. Adjacency List Representation: + We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. + +## Problem Description +An island is a node with zero incoming or outgoing edges. +In the *solution.py* file, define a function `count_islands` that consumes an adjacency list and returns the total +number of islands in the graph defined by the given adjacency list. + +## Example +``` +adjacency_list = { + 0: [1,3,5], + 1: [0,1,3,6], + 2: [], + 3: [0,3], + 4: [], + 5: [6], + 6: [3,5] +} +count_islands(adjacency_List) == 2 +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/graph_traversal/count_islands_list/solution/solution.py b/algorithms/graph_traversal/count_islands_list/solution/solution.py index 379b8895..dedfb130 100644 --- a/algorithms/graph_traversal/count_islands_list/solution/solution.py +++ b/algorithms/graph_traversal/count_islands_list/solution/solution.py @@ -1,12 +1,12 @@ -def count_islands(adjacency_list): - dict_count_edges = dict.fromkeys(adjacency_list.keys(), 0) - for adjkeyNode, edge_lst in adjacency_list.items(): - for keyNode in dict_count_edges.keys(): - if not adjkeyNode == keyNode: - if keyNode in edge_lst: - dict_count_edges[keyNode] += 1 - numIslands = 0 - for edgeCount in dict_count_edges.values(): - if edgeCount == 0: - numIslands += 1 +def count_islands(adjacency_list): + dict_count_edges = dict.fromkeys(adjacency_list.keys(), 0) + for adjkeyNode, edge_lst in adjacency_list.items(): + for keyNode in dict_count_edges.keys(): + if not adjkeyNode == keyNode: + if keyNode in edge_lst: + dict_count_edges[keyNode] += 1 + numIslands = 0 + for edgeCount in dict_count_edges.values(): + if edgeCount == 0: + numIslands += 1 return numIslands \ No newline at end of file diff --git a/algorithms/graph_traversal/count_islands_list/solution/test_solution.py b/algorithms/graph_traversal/count_islands_list/solution/test_solution.py index 72258950..96c6220a 100644 --- a/algorithms/graph_traversal/count_islands_list/solution/test_solution.py +++ b/algorithms/graph_traversal/count_islands_list/solution/test_solution.py @@ -1,15 +1,15 @@ -def test_solution(): - import solution - - adjacency_list = { - 0: [1,3,6], - 1: [0,1,3,6], - 2: [], - 3: [0,3], - 4: [], - 5: [], - 6: [3], - 7: [] - } - assert solution.count_islands(adjacency_list) == 4 - +def test_solution(): + import solution + + adjacency_list = { + 0: [1,3,6], + 1: [0,1,3,6], + 2: [], + 3: [0,3], + 4: [], + 5: [], + 6: [3], + 7: [] + } + assert solution.count_islands(adjacency_list) == 4 + diff --git a/algorithms/graph_traversal/defining_a_graph_list/README.md b/algorithms/graph_traversal/defining_a_graph_list/README.md index 7a10452c..8e09bfe0 100644 --- a/algorithms/graph_traversal/defining_a_graph_list/README.md +++ b/algorithms/graph_traversal/defining_a_graph_list/README.md @@ -1,22 +1,22 @@ -# Defining a Matrix - Graph Representation - -## Motivation -A Graph is a non-linear data structure consisting of nodes and edges. -There are two common ways to represent a graph in python: - -1. Adjacency Matrix Representation: - Let n be the number of node in our graph. - We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` - -2. Adjacency List Representation: - We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. - -## Problem Description -An island node is a node with no outgoing or incoming edges. -The *solution.py* file contains the variable `adjacency_list`. Set the value of `adjacency_list` to be a python dictionary representing an adjacency list. Define a graph with 4 total nodes and 4 total edges with nodes labelled from `0` to `3`. Node `0` should be an island node. There are many possible solutions. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Defining a Matrix - Graph Representation + +## Motivation +A Graph is a non-linear data structure consisting of nodes and edges. +There are two common ways to represent a graph in python: + +1. Adjacency Matrix Representation: + Let n be the number of node in our graph. + We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` + +2. Adjacency List Representation: + We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. + +## Problem Description +An island node is a node with no outgoing or incoming edges. +The *solution.py* file contains the variable `adjacency_list`. Set the value of `adjacency_list` to be a python dictionary representing an adjacency list. Define a graph with 4 total nodes and 4 total edges with nodes labelled from `0` to `3`. Node `0` should be an island node. There are many possible solutions. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/graph_traversal/defining_a_graph_list/solution/test_solution.py b/algorithms/graph_traversal/defining_a_graph_list/solution/test_solution.py index 0d162bf3..3d9116e8 100644 --- a/algorithms/graph_traversal/defining_a_graph_list/solution/test_solution.py +++ b/algorithms/graph_traversal/defining_a_graph_list/solution/test_solution.py @@ -1,12 +1,12 @@ -def count_edges(alist): - edges = 0 - for i in range(len(alist)): - edges += len(alist[i]) - return edges - -def test_solution(): - import solution - assert len(solution.adjacency_list) == 4 - assert count_edges(solution.adjacency_list) == 4 - assert len(solution.adjacency_list[0]) == 0 - +def count_edges(alist): + edges = 0 + for i in range(len(alist)): + edges += len(alist[i]) + return edges + +def test_solution(): + import solution + assert len(solution.adjacency_list) == 4 + assert count_edges(solution.adjacency_list) == 4 + assert len(solution.adjacency_list[0]) == 0 + diff --git a/algorithms/graph_traversal/defining_a_graph_matrix/README.md b/algorithms/graph_traversal/defining_a_graph_matrix/README.md index 04bf2d57..93f5d93e 100644 --- a/algorithms/graph_traversal/defining_a_graph_matrix/README.md +++ b/algorithms/graph_traversal/defining_a_graph_matrix/README.md @@ -1,22 +1,22 @@ -# Defining a Matrix - Graph Representation - -## Motivation -A Graph is a non-linear data structure consisting of nodes and edges. -There are two common ways to represent a graph in python: - -1. Adjacency Matrix Representation: - Let n be the number of node in our graph. - We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` - -2. Adjacency List Representation: - We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. - -## Problem Description -The *solution.py* file contains the variable `adjacency_matrix`. Set the value of `adjacency_matrix` to be an adjacency -matrix which defines a graph with 3 nodes and 4 edges. There are many possible correct answers. A value of `1` at index `ij` represents an edge from node `i` to node `j`. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Defining a Matrix - Graph Representation + +## Motivation +A Graph is a non-linear data structure consisting of nodes and edges. +There are two common ways to represent a graph in python: + +1. Adjacency Matrix Representation: + Let n be the number of node in our graph. + We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` + +2. Adjacency List Representation: + We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. + +## Problem Description +The *solution.py* file contains the variable `adjacency_matrix`. Set the value of `adjacency_matrix` to be an adjacency +matrix which defines a graph with 3 nodes and 4 edges. There are many possible correct answers. A value of `1` at index `ij` represents an edge from node `i` to node `j`. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/graph_traversal/defining_a_graph_matrix/solution/solution.py b/algorithms/graph_traversal/defining_a_graph_matrix/solution/solution.py index 57a7c22d..85751b55 100644 --- a/algorithms/graph_traversal/defining_a_graph_matrix/solution/solution.py +++ b/algorithms/graph_traversal/defining_a_graph_matrix/solution/solution.py @@ -1,3 +1,3 @@ -adjacency_matrix = [[0, 1, 0], - [1, 0, 1], +adjacency_matrix = [[0, 1, 0], + [1, 0, 1], [0, 1, 0]] \ No newline at end of file diff --git a/algorithms/graph_traversal/defining_a_graph_matrix/solution/test_solution.py b/algorithms/graph_traversal/defining_a_graph_matrix/solution/test_solution.py index 61667a37..63587558 100644 --- a/algorithms/graph_traversal/defining_a_graph_matrix/solution/test_solution.py +++ b/algorithms/graph_traversal/defining_a_graph_matrix/solution/test_solution.py @@ -1,16 +1,16 @@ -def is_3_by_3_matrix(matrix): - return len(matrix) == 3 and len(matrix[0]) == 3 - -def count_edges(matrix): - edges = 0 - for i in range(len(matrix)): - for j in range(len(matrix[0])): - if matrix[i][j] == 1: - edges += 1 - return edges - -def test_solution(): - import solution - assert is_3_by_3_matrix(solution.adjacency_matrix) - assert count_edges(solution.adjacency_matrix) == 4 - +def is_3_by_3_matrix(matrix): + return len(matrix) == 3 and len(matrix[0]) == 3 + +def count_edges(matrix): + edges = 0 + for i in range(len(matrix)): + for j in range(len(matrix[0])): + if matrix[i][j] == 1: + edges += 1 + return edges + +def test_solution(): + import solution + assert is_3_by_3_matrix(solution.adjacency_matrix) + assert count_edges(solution.adjacency_matrix) == 4 + diff --git a/algorithms/graph_traversal/depth_first_search_matrix/README.md b/algorithms/graph_traversal/depth_first_search_matrix/README.md index a87a8785..8794da18 100644 --- a/algorithms/graph_traversal/depth_first_search_matrix/README.md +++ b/algorithms/graph_traversal/depth_first_search_matrix/README.md @@ -1,39 +1,39 @@ -# Depth First Search - Adjacency Matrix - -## Motivation -A Graph is a non-linear data structure consisting of nodes and edges. -There are two common ways to represent a graph in python: - -1. Adjacency Matrix Representation: - Let n be the number of node in our graph. - We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` - -2. Adjacency List Representation: - We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. - -## Problem Description -In the *solution.py* file, define a function `exists_path` that consumes 3 parameters, `adjacency_matrix` an adjacency -matrix representation of a graph, `origin` a number representing a node in the graph, and `destination` representing a -node in the graph. The function returns `True` if `destination` is reachable from `origin` and `False` otherwise. The function -returns `False` if either `origin` or `destination` is not contained in the given graph. - -## Example -``` -matrix = [ - [0, 1, 0], - [0, 0, 1], - [0, 1, 0] -] - -exists_path(matrix, 0, 2) == True -exists_path(matrix, 1, 0) == False -exists_path(matrix, 2, 4) == False -exists_path(matrix, 3, 0) == False -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Depth First Search - Adjacency Matrix + +## Motivation +A Graph is a non-linear data structure consisting of nodes and edges. +There are two common ways to represent a graph in python: + +1. Adjacency Matrix Representation: + Let n be the number of node in our graph. + We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` + +2. Adjacency List Representation: + We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. + +## Problem Description +In the *solution.py* file, define a function `exists_path` that consumes 3 parameters, `adjacency_matrix` an adjacency +matrix representation of a graph, `origin` a number representing a node in the graph, and `destination` representing a +node in the graph. The function returns `True` if `destination` is reachable from `origin` and `False` otherwise. The function +returns `False` if either `origin` or `destination` is not contained in the given graph. + +## Example +``` +matrix = [ + [0, 1, 0], + [0, 0, 1], + [0, 1, 0] +] + +exists_path(matrix, 0, 2) == True +exists_path(matrix, 1, 0) == False +exists_path(matrix, 2, 4) == False +exists_path(matrix, 3, 0) == False +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/graph_traversal/depth_first_search_matrix/solution/solution.py b/algorithms/graph_traversal/depth_first_search_matrix/solution/solution.py index ae8142d8..d7e354e2 100644 --- a/algorithms/graph_traversal/depth_first_search_matrix/solution/solution.py +++ b/algorithms/graph_traversal/depth_first_search_matrix/solution/solution.py @@ -1,42 +1,42 @@ -# Depth First Search Solution -def exists_path(matrix, origin, destination): - def exists_path_visited(matrix, origin, destination, visited): - if origin in visited: - return False - if not (origin in range(len(matrix)) and - destination in range(len(matrix))): - return False - elif matrix[origin][destination] == 1: - return True - visited.append(origin) - for j in range(len(matrix[origin])): - if matrix[origin][j] == 1 and exists_path_visited(matrix, j, destination, visited): - return True - return False - return exists_path_visited(matrix, origin, destination, []) - - -# Ineficient Solution -def reachable_dict(matrix): - reachable_dict = {} - for i in range(len(matrix)): - reachable_lst = [] - for j in range(len(matrix[i])): - if matrix[i][j] == 1: - reachable_lst.append(j) - reachable_dict[i] = reachable_lst - all_reachable = {} - for i, neighbours in reachable_dict.items(): - all_reachable_lst = [] - for n in neighbours: - all_reachable_lst = all_reachable_lst + reachable_dict[n] - all_reachable_lst = all_reachable_lst + [n] - all_reachable[i] = all_reachable_lst - return all_reachable - -def exists_path2(matrix, origin, destination): - reachable = reachable_dict(matrix) - if not origin in reachable: - return False - else: +# Depth First Search Solution +def exists_path(matrix, origin, destination): + def exists_path_visited(matrix, origin, destination, visited): + if origin in visited: + return False + if not (origin in range(len(matrix)) and + destination in range(len(matrix))): + return False + elif matrix[origin][destination] == 1: + return True + visited.append(origin) + for j in range(len(matrix[origin])): + if matrix[origin][j] == 1 and exists_path_visited(matrix, j, destination, visited): + return True + return False + return exists_path_visited(matrix, origin, destination, []) + + +# Ineficient Solution +def reachable_dict(matrix): + reachable_dict = {} + for i in range(len(matrix)): + reachable_lst = [] + for j in range(len(matrix[i])): + if matrix[i][j] == 1: + reachable_lst.append(j) + reachable_dict[i] = reachable_lst + all_reachable = {} + for i, neighbours in reachable_dict.items(): + all_reachable_lst = [] + for n in neighbours: + all_reachable_lst = all_reachable_lst + reachable_dict[n] + all_reachable_lst = all_reachable_lst + [n] + all_reachable[i] = all_reachable_lst + return all_reachable + +def exists_path2(matrix, origin, destination): + reachable = reachable_dict(matrix) + if not origin in reachable: + return False + else: return destination in reachable[origin] \ No newline at end of file diff --git a/algorithms/graph_traversal/depth_first_search_matrix/solution/test_solution.py b/algorithms/graph_traversal/depth_first_search_matrix/solution/test_solution.py index 8eee6c7e..70ead6a4 100644 --- a/algorithms/graph_traversal/depth_first_search_matrix/solution/test_solution.py +++ b/algorithms/graph_traversal/depth_first_search_matrix/solution/test_solution.py @@ -1,15 +1,15 @@ -def test_solution(): - import solution - - matrix = [ - [1, 1, 0, 1], - [0, 0, 1, 1], - [1, 0, 0, 1], - [0, 0, 0, 1] - ] - assert solution.exists_path(matrix, 0, 2) == True - assert solution.exists_path(matrix, 1, 0) == True - assert solution.exists_path(matrix, 4, 2) == False - assert solution.exists_path(matrix, 0, 4) == False - assert solution.exists_path(matrix, 3, 1) == False - +def test_solution(): + import solution + + matrix = [ + [1, 1, 0, 1], + [0, 0, 1, 1], + [1, 0, 0, 1], + [0, 0, 0, 1] + ] + assert solution.exists_path(matrix, 0, 2) == True + assert solution.exists_path(matrix, 1, 0) == True + assert solution.exists_path(matrix, 4, 2) == False + assert solution.exists_path(matrix, 0, 4) == False + assert solution.exists_path(matrix, 3, 1) == False + diff --git a/algorithms/graph_traversal/list_to_matrix_representation/README.md b/algorithms/graph_traversal/list_to_matrix_representation/README.md index 15b91f67..72401d7a 100644 --- a/algorithms/graph_traversal/list_to_matrix_representation/README.md +++ b/algorithms/graph_traversal/list_to_matrix_representation/README.md @@ -1,33 +1,33 @@ -# Adjacency List to Adjacency Matrix Representation - -## Motivation -A Graph is a non-linear data structure consisting of nodes and edges. -There are two common ways to represent a graph in python: - -1. Adjacency Matrix Representation: - Let n be the number of node in our graph. - We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` - -2. Adjacency List Representation: - We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. - -## Problem Description -Below is an adjacency list representation of a directed graph. The *solution.py* file contains a python dictionary -`adjacency_matrix`. Set the value of `adjacency_matrix` to be the adjacency matrix representation of the given dictionary, where each edge from node `i` to node `j` is represented by a value of `1` at position `ij` in your matrix. - -``` -adjacency_list = { - 0: [0, 1, 3], - 1: [3, 4], - 2: [1], - 3: [0, 2], - 4: [] -} -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Adjacency List to Adjacency Matrix Representation + +## Motivation +A Graph is a non-linear data structure consisting of nodes and edges. +There are two common ways to represent a graph in python: + +1. Adjacency Matrix Representation: + Let n be the number of node in our graph. + We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` + +2. Adjacency List Representation: + We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. + +## Problem Description +Below is an adjacency list representation of a directed graph. The *solution.py* file contains a python dictionary +`adjacency_matrix`. Set the value of `adjacency_matrix` to be the adjacency matrix representation of the given dictionary, where each edge from node `i` to node `j` is represented by a value of `1` at position `ij` in your matrix. + +``` +adjacency_list = { + 0: [0, 1, 3], + 1: [3, 4], + 2: [1], + 3: [0, 2], + 4: [] +} +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/graph_traversal/list_to_matrix_representation/solution/solution.py b/algorithms/graph_traversal/list_to_matrix_representation/solution/solution.py index 7b477ca4..257dc19a 100644 --- a/algorithms/graph_traversal/list_to_matrix_representation/solution/solution.py +++ b/algorithms/graph_traversal/list_to_matrix_representation/solution/solution.py @@ -1,7 +1,7 @@ -adjacency_matrix = [ - [1, 1, 0, 1, 0], - [0, 0, 0, 1, 1], - [0, 1, 0, 0, 0], - [1, 0, 1, 0, 0], - [0, 0, 0, 0, 0] +adjacency_matrix = [ + [1, 1, 0, 1, 0], + [0, 0, 0, 1, 1], + [0, 1, 0, 0, 0], + [1, 0, 1, 0, 0], + [0, 0, 0, 0, 0] ] \ No newline at end of file diff --git a/algorithms/graph_traversal/list_to_matrix_representation/solution/test_solution.py b/algorithms/graph_traversal/list_to_matrix_representation/solution/test_solution.py index acec6019..7ff1e326 100644 --- a/algorithms/graph_traversal/list_to_matrix_representation/solution/test_solution.py +++ b/algorithms/graph_traversal/list_to_matrix_representation/solution/test_solution.py @@ -1,12 +1,12 @@ -def test_solution(): - import solution - - adjacency_matrix = [ - [1, 1, 0, 1, 0], - [0, 0, 0, 1, 1], - [0, 1, 0, 0, 0], - [1, 0, 1, 0, 0], - [0, 0, 0, 0, 0], - ] - assert solution.adjacency_matrix == adjacency_matrix - +def test_solution(): + import solution + + adjacency_matrix = [ + [1, 1, 0, 1, 0], + [0, 0, 0, 1, 1], + [0, 1, 0, 0, 0], + [1, 0, 1, 0, 0], + [0, 0, 0, 0, 0], + ] + assert solution.adjacency_matrix == adjacency_matrix + diff --git a/algorithms/graph_traversal/matrix_to_list_representation/README.md b/algorithms/graph_traversal/matrix_to_list_representation/README.md index bb48eeb1..085d93b7 100644 --- a/algorithms/graph_traversal/matrix_to_list_representation/README.md +++ b/algorithms/graph_traversal/matrix_to_list_representation/README.md @@ -1,34 +1,34 @@ -# Adjacency Matrix to Adjacency List Representation - -## Motivation -A Graph is a non-linear data structure consisting of nodes and edges. -There are two common ways to represent a graph in python: - -1. Adjacency Matrix Representation: - Let n be the number of node in our graph. - We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` - -2. Adjacency List Representation: - We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. - -## Problem Description -Below is an adjacency matrix representation of a directed graph. The *solution.py* file contains a python dictionary -`adjacency_list`. Set the value of `adjacency_list` to be the adjacency list representation of the given graph. - -The graph represented by the given matrix has nodes labelled from `0-3`. A value of `1` at index `ij` represents an edge from node `i` to node `j`. - -``` -adjacency_matrix = [ - [0, 1, 1, 1] - [1, 0, 0, 1] - [0, 1, 0, 0] - [1, 0, 0, 1] -] -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Adjacency Matrix to Adjacency List Representation + +## Motivation +A Graph is a non-linear data structure consisting of nodes and edges. +There are two common ways to represent a graph in python: + +1. Adjacency Matrix Representation: + Let n be the number of node in our graph. + We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` + +2. Adjacency List Representation: + We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. + +## Problem Description +Below is an adjacency matrix representation of a directed graph. The *solution.py* file contains a python dictionary +`adjacency_list`. Set the value of `adjacency_list` to be the adjacency list representation of the given graph. + +The graph represented by the given matrix has nodes labelled from `0-3`. A value of `1` at index `ij` represents an edge from node `i` to node `j`. + +``` +adjacency_matrix = [ + [0, 1, 1, 1] + [1, 0, 0, 1] + [0, 1, 0, 0] + [1, 0, 0, 1] +] +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/graph_traversal/matrix_to_list_representation/solution/solution.py b/algorithms/graph_traversal/matrix_to_list_representation/solution/solution.py index f7c80d5c..333afc6e 100644 --- a/algorithms/graph_traversal/matrix_to_list_representation/solution/solution.py +++ b/algorithms/graph_traversal/matrix_to_list_representation/solution/solution.py @@ -1,6 +1,6 @@ -adjacency_list = { - 0: [1,2,3], - 1: [0,3], - 2: [1], - 3: [0,3] +adjacency_list = { + 0: [1,2,3], + 1: [0,3], + 2: [1], + 3: [0,3] } \ No newline at end of file diff --git a/algorithms/graph_traversal/matrix_to_list_representation/solution/test_solution.py b/algorithms/graph_traversal/matrix_to_list_representation/solution/test_solution.py index 7847c480..398bee6c 100644 --- a/algorithms/graph_traversal/matrix_to_list_representation/solution/test_solution.py +++ b/algorithms/graph_traversal/matrix_to_list_representation/solution/test_solution.py @@ -1,10 +1,10 @@ -def test_solution(): - import solution - - adjacency_list = { - 0: [1,2,3], - 1: [0,3], - 2: [1], - 3: [0,3] - } - assert solution.adjacency_list == adjacency_list +def test_solution(): + import solution + + adjacency_list = { + 0: [1,2,3], + 1: [0,3], + 2: [1], + 3: [0,3] + } + assert solution.adjacency_list == adjacency_list diff --git a/algorithms/graph_traversal/most_neighbors/README.md b/algorithms/graph_traversal/most_neighbors/README.md index f549fc65..d0c2d0ca 100644 --- a/algorithms/graph_traversal/most_neighbors/README.md +++ b/algorithms/graph_traversal/most_neighbors/README.md @@ -1,38 +1,38 @@ -# Most Neighbours - Adjacency List - -## Motivation -A Graph is a non-linear data structure consisting of nodes and edges. -There are two common ways to represent a graph in python: - -1. Adjacency Matrix Representation: - Let n be the number of node in our graph. - We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` - -2. Adjacency List Representation: - We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. - -## Problem Description -Two nodes are neighbours if there is an edge going from one to the other. - -In the *solution.py* file, define a function `most_neighbours` that consumes one parameter `adjacency_list` and returns a number representing the node that has the largest number of neighbours in the graph. In the result of a tie, the function should return the lowest numbered node. - -## Example -``` -adjacency_list = { - 0: [1,3,5], - 1: [0,1,3,6], - 2: [], - 3: [0,1,2,3], - 4: [], - 5: [4] -} - -most_neighbours(adjacency_list) == 1 -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Most Neighbours - Adjacency List + +## Motivation +A Graph is a non-linear data structure consisting of nodes and edges. +There are two common ways to represent a graph in python: + +1. Adjacency Matrix Representation: + Let n be the number of node in our graph. + We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` + +2. Adjacency List Representation: + We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. + +## Problem Description +Two nodes are neighbours if there is an edge going from one to the other. + +In the *solution.py* file, define a function `most_neighbours` that consumes one parameter `adjacency_list` and returns a number representing the node that has the largest number of neighbours in the graph. In the result of a tie, the function should return the lowest numbered node. + +## Example +``` +adjacency_list = { + 0: [1,3,5], + 1: [0,1,3,6], + 2: [], + 3: [0,1,2,3], + 4: [], + 5: [4] +} + +most_neighbours(adjacency_list) == 1 +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/graph_traversal/most_neighbors/solution/solution.py b/algorithms/graph_traversal/most_neighbors/solution/solution.py index 082ea391..ff9ac60c 100644 --- a/algorithms/graph_traversal/most_neighbors/solution/solution.py +++ b/algorithms/graph_traversal/most_neighbors/solution/solution.py @@ -1,11 +1,11 @@ -def most_neighbours(adjacency_list): - max_len = -1 - max_key = -1 - for keyNode, edge_lst in adjacency_list.items(): - num_neighbours = len(edge_lst) - if num_neighbours > max_len: - max_key = keyNode - max_len = num_neighbours - elif num_neighbours == max_len and keyNode < max_key: - max_key = keyNode +def most_neighbours(adjacency_list): + max_len = -1 + max_key = -1 + for keyNode, edge_lst in adjacency_list.items(): + num_neighbours = len(edge_lst) + if num_neighbours > max_len: + max_key = keyNode + max_len = num_neighbours + elif num_neighbours == max_len and keyNode < max_key: + max_key = keyNode return max_key \ No newline at end of file diff --git a/algorithms/graph_traversal/most_neighbors/solution/test_solution.py b/algorithms/graph_traversal/most_neighbors/solution/test_solution.py index 540016a0..2c612af5 100644 --- a/algorithms/graph_traversal/most_neighbors/solution/test_solution.py +++ b/algorithms/graph_traversal/most_neighbors/solution/test_solution.py @@ -1,27 +1,27 @@ -def test_solution(): - import solution - - adj_list1 = { - 0: [1,4,5], - 1: [0,2,3,6], - 2: [0], - 3: [], - 4: [1,5], - 5: [6], - 6: [3,5] - } - - adj_list2 = { - 0: [1,2], - 1: [0,2], - 2: [0] - } - - adj_list3 = { - 0: [], - 1: [], - 2: [] - } - assert solution.most_neighbours(adj_list1) == 1 - assert solution.most_neighbours(adj_list2) == 0 - assert solution.most_neighbours(adj_list3) == 0 +def test_solution(): + import solution + + adj_list1 = { + 0: [1,4,5], + 1: [0,2,3,6], + 2: [0], + 3: [], + 4: [1,5], + 5: [6], + 6: [3,5] + } + + adj_list2 = { + 0: [1,2], + 1: [0,2], + 2: [0] + } + + adj_list3 = { + 0: [], + 1: [], + 2: [] + } + assert solution.most_neighbours(adj_list1) == 1 + assert solution.most_neighbours(adj_list2) == 0 + assert solution.most_neighbours(adj_list3) == 0 diff --git a/algorithms/graph_traversal/num_components/README.md b/algorithms/graph_traversal/num_components/README.md index 010d68ee..df8879ae 100644 --- a/algorithms/graph_traversal/num_components/README.md +++ b/algorithms/graph_traversal/num_components/README.md @@ -1,38 +1,38 @@ -# Number of Components - Adjacency List - -## Motivation -A Graph is a non-linear data structure consisting of nodes and edges. -There are two common ways to represent a graph in python: - -1. Adjacency Matrix Representation: - Let n be the number of node in our graph. - We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` - -2. Adjacency List Representation: - We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. - -## Problem Description -A component of an undirected graph is a subset of nodes. There must be a path between any two nodes in a component. There cannot be a path from inside the component to outside the component. - -In the *solution.py* file, define a function `num_components` that consumes `adjacency_matrix` an adjacency matrix -representation of a graph, and returns the number of components in the graph. `adjacency_matrix` is guaranteed to be an -undirected graph, where all edges are bi-directional. - -## Example -``` -adjacency_matrix = [ - [0, 1, 1, 0], - [1, 0, 1, 0], - [1, 1, 0, 0], - [0, 0, 0, 0] -] - -num_components(adj_list) == 2 -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Number of Components - Adjacency List + +## Motivation +A Graph is a non-linear data structure consisting of nodes and edges. +There are two common ways to represent a graph in python: + +1. Adjacency Matrix Representation: + Let n be the number of node in our graph. + We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` + +2. Adjacency List Representation: + We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. + +## Problem Description +A component of an undirected graph is a subset of nodes. There must be a path between any two nodes in a component. There cannot be a path from inside the component to outside the component. + +In the *solution.py* file, define a function `num_components` that consumes `adjacency_matrix` an adjacency matrix +representation of a graph, and returns the number of components in the graph. `adjacency_matrix` is guaranteed to be an +undirected graph, where all edges are bi-directional. + +## Example +``` +adjacency_matrix = [ + [0, 1, 1, 0], + [1, 0, 1, 0], + [1, 1, 0, 0], + [0, 0, 0, 0] +] + +num_components(adj_list) == 2 +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/graph_traversal/num_components/solution/solution.py b/algorithms/graph_traversal/num_components/solution/solution.py index 00f6c324..5c1f5d97 100644 --- a/algorithms/graph_traversal/num_components/solution/solution.py +++ b/algorithms/graph_traversal/num_components/solution/solution.py @@ -1,27 +1,27 @@ -def reachable_dict(matrix): - reachable_dict = {} - for i in range(len(matrix)): - reachable_lst = [] - for j in range(len(matrix[i])): - if matrix[i][j] == 1: - reachable_lst.append(j) - reachable_dict[i] = reachable_lst - all_reachable = {} - for i, neighbours in reachable_dict.items(): - all_reachable_lst = [] - for n in neighbours: - all_reachable_lst = all_reachable_lst + reachable_dict[n] - all_reachable_lst = all_reachable_lst + [n] - all_reachable[i] = all_reachable_lst - return all_reachable - -def num_components(adjacency_matrix): - reachableDict = reachable_dict(adjacency_matrix) - num_components = 0 - visited = [False for i in range(len(adjacency_matrix))] - for i in range(len(adjacency_matrix)): - if visited[i] == False: - num_components += 1 - for j in reachableDict[i]: - visited[j] = True +def reachable_dict(matrix): + reachable_dict = {} + for i in range(len(matrix)): + reachable_lst = [] + for j in range(len(matrix[i])): + if matrix[i][j] == 1: + reachable_lst.append(j) + reachable_dict[i] = reachable_lst + all_reachable = {} + for i, neighbours in reachable_dict.items(): + all_reachable_lst = [] + for n in neighbours: + all_reachable_lst = all_reachable_lst + reachable_dict[n] + all_reachable_lst = all_reachable_lst + [n] + all_reachable[i] = all_reachable_lst + return all_reachable + +def num_components(adjacency_matrix): + reachableDict = reachable_dict(adjacency_matrix) + num_components = 0 + visited = [False for i in range(len(adjacency_matrix))] + for i in range(len(adjacency_matrix)): + if visited[i] == False: + num_components += 1 + for j in reachableDict[i]: + visited[j] = True return num_components \ No newline at end of file diff --git a/algorithms/graph_traversal/num_components/solution/test_solution.py b/algorithms/graph_traversal/num_components/solution/test_solution.py index a76441f5..12a868e3 100644 --- a/algorithms/graph_traversal/num_components/solution/test_solution.py +++ b/algorithms/graph_traversal/num_components/solution/test_solution.py @@ -1,30 +1,30 @@ -def test_solution(): - import solution - - adj_matrix1 = [ - [0, 1, 1, 0], - [1, 0, 1, 0], - [1, 1, 0, 0], - [0, 0, 0, 0] - ] - - adj_matrix2 = [ - [0, 1, 1], - [1, 0, 0], - [1, 0, 0] - ] - - adj_matrix3 = [ - [0, 0, 0, 0], - [0, 0, 0, 1], - [0, 0, 0, 0], - [0, 1, 0, 0] - ] - - adj_matrix4 = [] - assert solution.num_components(adj_matrix1) == 2 - assert solution.num_components(adj_matrix2) == 1 - assert solution.num_components(adj_matrix3) == 3 - assert solution.num_components(adj_matrix4) == 0 - - +def test_solution(): + import solution + + adj_matrix1 = [ + [0, 1, 1, 0], + [1, 0, 1, 0], + [1, 1, 0, 0], + [0, 0, 0, 0] + ] + + adj_matrix2 = [ + [0, 1, 1], + [1, 0, 0], + [1, 0, 0] + ] + + adj_matrix3 = [ + [0, 0, 0, 0], + [0, 0, 0, 1], + [0, 0, 0, 0], + [0, 1, 0, 0] + ] + + adj_matrix4 = [] + assert solution.num_components(adj_matrix1) == 2 + assert solution.num_components(adj_matrix2) == 1 + assert solution.num_components(adj_matrix3) == 3 + assert solution.num_components(adj_matrix4) == 0 + + diff --git a/algorithms/graph_traversal/num_hops_away_list/README.md b/algorithms/graph_traversal/num_hops_away_list/README.md index 370072ee..a9b0ce4a 100644 --- a/algorithms/graph_traversal/num_hops_away_list/README.md +++ b/algorithms/graph_traversal/num_hops_away_list/README.md @@ -1,43 +1,43 @@ -# Number of Hop Away - Adjacency List - -## Motivation -A Graph is a non-linear data structure consisting of nodes and edges. -There are two common ways to represent a graph in python: - -1. Adjacency Matrix Representation: - Let n be the number of node in our graph. - We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` - -2. Adjacency List Representation: - We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. - -## Problem Description -In the *solution.py* file, define a function `hops_away` that consumes 3 parameters, `adjacency_list` an adjacency list -representation of a graph, `node` a number representing a node in the graph, and `num_hops` a non-negative integer, and returns a list of -numbers representing the nodes that are exactly `num_hops` away from `node` in `adjacency_list`. The function returns an -empty list if `node` is not contained in the given graph. - -## Example -``` -adj_list = { - 0: [1,3,5], - 1: [0,1,3,6], - 2: [], - 3: [0,3,5], - 4: [], - 5: [6], - 6: [3,5] -} - -hops_away(adj_list, 0, 2) == [0, 1, 3, 6, 5] -hops_away(adj_list, 1, 0) == [1] -hops_away(adj_list, 7, 4) == [] -hops_away(adj_list, 4, 3) == [] -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Number of Hop Away - Adjacency List + +## Motivation +A Graph is a non-linear data structure consisting of nodes and edges. +There are two common ways to represent a graph in python: + +1. Adjacency Matrix Representation: + Let n be the number of node in our graph. + We can create an n by n matrix `M`, where `M[i][j] = 1` if there exists an edge from node `i` to node `j`. If there does not exist an edge from node `i` to node `j`, `M[i][j] = 0` + +2. Adjacency List Representation: + We can use a dictionary to represent a graph, where each key in the dictionary represents a node, and the values for each node `i` will be a list of all the nodes `j` where there exists an edge from node `i` to node `j`. + +## Problem Description +In the *solution.py* file, define a function `hops_away` that consumes 3 parameters, `adjacency_list` an adjacency list +representation of a graph, `node` a number representing a node in the graph, and `num_hops` a non-negative integer, and returns a list of +numbers representing the nodes that are exactly `num_hops` away from `node` in `adjacency_list`. The function returns an +empty list if `node` is not contained in the given graph. + +## Example +``` +adj_list = { + 0: [1,3,5], + 1: [0,1,3,6], + 2: [], + 3: [0,3,5], + 4: [], + 5: [6], + 6: [3,5] +} + +hops_away(adj_list, 0, 2) == [0, 1, 3, 6, 5] +hops_away(adj_list, 1, 0) == [1] +hops_away(adj_list, 7, 4) == [] +hops_away(adj_list, 4, 3) == [] +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/graph_traversal/num_hops_away_list/solution/solution.py b/algorithms/graph_traversal/num_hops_away_list/solution/solution.py index c5db2b56..aaa724ab 100644 --- a/algorithms/graph_traversal/num_hops_away_list/solution/solution.py +++ b/algorithms/graph_traversal/num_hops_away_list/solution/solution.py @@ -1,14 +1,14 @@ -def hops_away(adjacency_list, node, num_hops): - if not node in adjacency_list.keys(): - return [] - elif num_hops == 0: - return [node] - else: - hops_away_neighbours = [] - for neighbour in adjacency_list[node]: - hops_away_neighbours.extend(hops_away(adjacency_list, neighbour, num_hops-1)) - hops_away_neighbours_unique = [] - for n in hops_away_neighbours: - if not n in hops_away_neighbours_unique: - hops_away_neighbours_unique.append(n) +def hops_away(adjacency_list, node, num_hops): + if not node in adjacency_list.keys(): + return [] + elif num_hops == 0: + return [node] + else: + hops_away_neighbours = [] + for neighbour in adjacency_list[node]: + hops_away_neighbours.extend(hops_away(adjacency_list, neighbour, num_hops-1)) + hops_away_neighbours_unique = [] + for n in hops_away_neighbours: + if not n in hops_away_neighbours_unique: + hops_away_neighbours_unique.append(n) return hops_away_neighbours_unique \ No newline at end of file diff --git a/algorithms/graph_traversal/num_hops_away_list/solution/test_solution.py b/algorithms/graph_traversal/num_hops_away_list/solution/test_solution.py index c13ca300..d118a04a 100644 --- a/algorithms/graph_traversal/num_hops_away_list/solution/test_solution.py +++ b/algorithms/graph_traversal/num_hops_away_list/solution/test_solution.py @@ -1,18 +1,18 @@ -def test_solution(): - import solution - - adjacency_list = { - 0: [1,4,5], - 1: [0,2,3,6], - 2: [0], - 3: [], - 4: [1,5], - 5: [6], - 6: [3,5] - } - assert sorted(solution.hops_away(adjacency_list, 0, 2)) == [0,1,2,3,5,6] - assert sorted(solution.hops_away(adjacency_list, 2, 0)) == [2] - assert sorted(solution.hops_away(adjacency_list, 5, 3)) == [6] - assert sorted(solution.hops_away(adjacency_list, 7, 2)) == [] - assert sorted(solution.hops_away(adjacency_list, 3, 4)) == [] - +def test_solution(): + import solution + + adjacency_list = { + 0: [1,4,5], + 1: [0,2,3,6], + 2: [0], + 3: [], + 4: [1,5], + 5: [6], + 6: [3,5] + } + assert sorted(solution.hops_away(adjacency_list, 0, 2)) == [0,1,2,3,5,6] + assert sorted(solution.hops_away(adjacency_list, 2, 0)) == [2] + assert sorted(solution.hops_away(adjacency_list, 5, 3)) == [6] + assert sorted(solution.hops_away(adjacency_list, 7, 2)) == [] + assert sorted(solution.hops_away(adjacency_list, 3, 4)) == [] + diff --git a/algorithms/greedy_and_divide_and_conquer/binary_search/README.md b/algorithms/greedy_and_divide_and_conquer/binary_search/README.md index e2423bfe..7345d77f 100644 --- a/algorithms/greedy_and_divide_and_conquer/binary_search/README.md +++ b/algorithms/greedy_and_divide_and_conquer/binary_search/README.md @@ -1,23 +1,23 @@ -# Divide and Conquer Algorithm - Binary Search - -## Motivation -Divide and Conquer Algorithms breaks up a problem into smaller subproblems, solves the subproblems recursively and finally combines the results of the subproblems to find the answer the the main problem. -Often if we can come up with a divide and conquer approach to a problem, this will be much faster than a naive recursive solution. - - -## Problem Description -In the *solution.py* file, define a function `binary_search` that takes in a sorted list of numbers `lst`, and a target, `x`. Using the divide and conquer Binary Search algorithm, return the index of `x`, if `x` exists in `lst`, otherwise return `-1`. - -## Example -``` -lst = [1, 2, 4, 5, 9, 10, 11] -binary_search(lst, 2) == 1 -binary_search(lst, 7) == -1 -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Divide and Conquer Algorithm - Binary Search + +## Motivation +Divide and Conquer Algorithms breaks up a problem into smaller subproblems, solves the subproblems recursively and finally combines the results of the subproblems to find the answer the the main problem. +Often if we can come up with a divide and conquer approach to a problem, this will be much faster than a naive recursive solution. + + +## Problem Description +In the *solution.py* file, define a function `binary_search` that takes in a sorted list of numbers `lst`, and a target, `x`. Using the divide and conquer Binary Search algorithm, return the index of `x`, if `x` exists in `lst`, otherwise return `-1`. + +## Example +``` +lst = [1, 2, 4, 5, 9, 10, 11] +binary_search(lst, 2) == 1 +binary_search(lst, 7) == -1 +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/greedy_and_divide_and_conquer/binary_search/solution/solution.py b/algorithms/greedy_and_divide_and_conquer/binary_search/solution/solution.py index 0fbf1679..b17b66eb 100644 --- a/algorithms/greedy_and_divide_and_conquer/binary_search/solution/solution.py +++ b/algorithms/greedy_and_divide_and_conquer/binary_search/solution/solution.py @@ -1,20 +1,20 @@ -def binary_search_helper(lst, x, low, high): - if high >= low: - # Get index of middle element in lst - mid = (high + low) // 2 - # If element is at mid idx - if lst[mid] == x: - return mid - # If element is smaller than mid, then it will be in left subarray - elif lst[mid] > x: - return binary_search_helper(lst, x, low, mid - 1) - # Else the element can only be present in right subarray - else: - return binary_search_helper(lst, x, mid + 1, high) - - else: - # Element is not present in the array - return -1 - -def binary_search(lst, x): - return binary_search_helper(lst, x, 0, len(lst)-1) +def binary_search_helper(lst, x, low, high): + if high >= low: + # Get index of middle element in lst + mid = (high + low) // 2 + # If element is at mid idx + if lst[mid] == x: + return mid + # If element is smaller than mid, then it will be in left subarray + elif lst[mid] > x: + return binary_search_helper(lst, x, low, mid - 1) + # Else the element can only be present in right subarray + else: + return binary_search_helper(lst, x, mid + 1, high) + + else: + # Element is not present in the array + return -1 + +def binary_search(lst, x): + return binary_search_helper(lst, x, 0, len(lst)-1) diff --git a/algorithms/greedy_and_divide_and_conquer/binary_search/solution/test_solution.py b/algorithms/greedy_and_divide_and_conquer/binary_search/solution/test_solution.py index d2fa9569..bd1fcbd1 100644 --- a/algorithms/greedy_and_divide_and_conquer/binary_search/solution/test_solution.py +++ b/algorithms/greedy_and_divide_and_conquer/binary_search/solution/test_solution.py @@ -1,9 +1,9 @@ -def test_solution(): - import solution - - assert solution.binary_search([1, 2, 4, 5, 9, 10, 11], 2) == 1 - assert solution.binary_search([1, 2, 4, 5, 9, 10, 11], 7) == -1 - assert solution.binary_search([], 2) == -1 - assert solution.binary_search([1, 10], 5) == -1 - assert solution.binary_search([1, 2, 4, 5, 6, 9, 10, 11], 6) == 4 - assert solution.binary_search([1, 2, 4, 5, 6, 9, 10, 11], 11) == 7 +def test_solution(): + import solution + + assert solution.binary_search([1, 2, 4, 5, 9, 10, 11], 2) == 1 + assert solution.binary_search([1, 2, 4, 5, 9, 10, 11], 7) == -1 + assert solution.binary_search([], 2) == -1 + assert solution.binary_search([1, 10], 5) == -1 + assert solution.binary_search([1, 2, 4, 5, 6, 9, 10, 11], 6) == 4 + assert solution.binary_search([1, 2, 4, 5, 6, 9, 10, 11], 11) == 7 diff --git a/algorithms/greedy_and_divide_and_conquer/frog_hops/README.md b/algorithms/greedy_and_divide_and_conquer/frog_hops/README.md index 1d2dfa8b..d1347258 100644 --- a/algorithms/greedy_and_divide_and_conquer/frog_hops/README.md +++ b/algorithms/greedy_and_divide_and_conquer/frog_hops/README.md @@ -1,22 +1,22 @@ -# Greedy Algorithm - Frog Hops - -## Motivation -A greedy algorithm is a type of algorithm that builds up a solution piece by piece always choosing the piece that offers the most imediate benifit. We choose the locally optimal solution at each step to get a globally optimal solution to the problem. - -## Problem Description -Kermit the frog is standing on a lily pad at position `0` on the river. Kermit wants to get to get to the lily pad at position `n` on the river. We will represent the river as an array `river` where `river[i] = 1` if there exists a lily pad at position `i` and `river[i] = 0` if there is no lily pad at position `i` on the river. Kermit can hop up to `x` units at a time along the river. -In the *solution.py* file, define a function `min_hops` that takes in the maximum number of units `max_units` Kermit can move in one hop, and `n` the position on the river Kermit is trying to reach, and `river`, the array representation of the river with lily pads, and outputs the minimum number of hops Kermit can make to get to position `n`. Output `-1` if it is impossible for Kermit to reach the lily pad at position `n`. - -## Example -``` -river = [1, 0, 0, 1, 1, 0, 0, 1] -min_hops(3, 7, river) == 3 -``` -In this example Kermit can first make one hop to jump 3 spaces to the lily pad at position `3`. He then he makes another hop to move one space to get to the lily pad at position `4`, and he makes a final hop to move 3 spaces to get to the lily pad at position `7`. - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Greedy Algorithm - Frog Hops + +## Motivation +A greedy algorithm is a type of algorithm that builds up a solution piece by piece always choosing the piece that offers the most imediate benifit. We choose the locally optimal solution at each step to get a globally optimal solution to the problem. + +## Problem Description +Kermit the frog is standing on a lily pad at position `0` on the river. Kermit wants to get to get to the lily pad at position `n` on the river. We will represent the river as an array `river` where `river[i] = 1` if there exists a lily pad at position `i` and `river[i] = 0` if there is no lily pad at position `i` on the river. Kermit can hop up to `x` units at a time along the river. +In the *solution.py* file, define a function `min_hops` that takes in the maximum number of units `max_units` Kermit can move in one hop, and `n` the position on the river Kermit is trying to reach, and `river`, the array representation of the river with lily pads, and outputs the minimum number of hops Kermit can make to get to position `n`. Output `-1` if it is impossible for Kermit to reach the lily pad at position `n`. + +## Example +``` +river = [1, 0, 0, 1, 1, 0, 0, 1] +min_hops(3, 7, river) == 3 +``` +In this example Kermit can first make one hop to jump 3 spaces to the lily pad at position `3`. He then he makes another hop to move one space to get to the lily pad at position `4`, and he makes a final hop to move 3 spaces to get to the lily pad at position `7`. + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/greedy_and_divide_and_conquer/frog_hops/solution/solution.py b/algorithms/greedy_and_divide_and_conquer/frog_hops/solution/solution.py index 633885a6..14516e20 100644 --- a/algorithms/greedy_and_divide_and_conquer/frog_hops/solution/solution.py +++ b/algorithms/greedy_and_divide_and_conquer/frog_hops/solution/solution.py @@ -1,30 +1,30 @@ -def min_hops_helper(max_units, n, river, num_hops): - # Frog starts at position 0 - position = 0 - # Frog can hop up to max_units. We want to hop as far as we can - # So we itterate through from max_units backwards to 0 to find the - # largest jump we can make. - for i in range(max_units, 0, -1): - # Check if our current position + i the number of hops we want to make - # is less than or equal to our final destination poition n. - # and check if there is a lily pad a position + i. - # if there is a lily pad at position + i, we can hop there! - if position + i <= n and river[position + i] == 1: - # After we hop i units we update num hops by 1 - # and we are now at position + i - num_hops += 1 - position = position + i - # we then recurse updating our destitination to n-i, - # updating river to now start at our current position. - return min_hops_helper(max_units, n-i, river[position:], num_hops) - # If we got to position == n we made it! so we return the total num_hops we made. - if position == n: - return num_hops - # Otherwise we couldn't make it to position n and we return -1. - else: - return -1 - -def min_hops(max_units, n, river): - return min_hops_helper(max_units, n, river, 0) - +def min_hops_helper(max_units, n, river, num_hops): + # Frog starts at position 0 + position = 0 + # Frog can hop up to max_units. We want to hop as far as we can + # So we itterate through from max_units backwards to 0 to find the + # largest jump we can make. + for i in range(max_units, 0, -1): + # Check if our current position + i the number of hops we want to make + # is less than or equal to our final destination poition n. + # and check if there is a lily pad a position + i. + # if there is a lily pad at position + i, we can hop there! + if position + i <= n and river[position + i] == 1: + # After we hop i units we update num hops by 1 + # and we are now at position + i + num_hops += 1 + position = position + i + # we then recurse updating our destitination to n-i, + # updating river to now start at our current position. + return min_hops_helper(max_units, n-i, river[position:], num_hops) + # If we got to position == n we made it! so we return the total num_hops we made. + if position == n: + return num_hops + # Otherwise we couldn't make it to position n and we return -1. + else: + return -1 + +def min_hops(max_units, n, river): + return min_hops_helper(max_units, n, river, 0) + print(min_hops(3, 7, [1, 0, 0, 1, 1, 0, 0, 1])) \ No newline at end of file diff --git a/algorithms/greedy_and_divide_and_conquer/frog_hops/solution/test_solution.py b/algorithms/greedy_and_divide_and_conquer/frog_hops/solution/test_solution.py index af10e2ff..be0cc651 100644 --- a/algorithms/greedy_and_divide_and_conquer/frog_hops/solution/test_solution.py +++ b/algorithms/greedy_and_divide_and_conquer/frog_hops/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - import solution - - assert solution.min_hops(3, 7, [1, 0, 0, 1, 1, 0, 0, 1]) == 3 - assert solution.min_hops(3, 4, [1, 0, 0, 0, 1]) == -1 - assert solution.min_hops(1, 3, [1, 1, 1, 1]) == 3 +def test_solution(): + import solution + + assert solution.min_hops(3, 7, [1, 0, 0, 1, 1, 0, 0, 1]) == 3 + assert solution.min_hops(3, 4, [1, 0, 0, 0, 1]) == -1 + assert solution.min_hops(1, 3, [1, 1, 1, 1]) == 3 assert solution.min_hops(2, 6, [1, 1, 0, 1, 1, 0, 1]) == 4 \ No newline at end of file diff --git a/algorithms/greedy_and_divide_and_conquer/jewel_thief/README.md b/algorithms/greedy_and_divide_and_conquer/jewel_thief/README.md index b3c6fcf5..b1fb1b72 100644 --- a/algorithms/greedy_and_divide_and_conquer/jewel_thief/README.md +++ b/algorithms/greedy_and_divide_and_conquer/jewel_thief/README.md @@ -1,23 +1,23 @@ -# Greedy Algorithm - Jewel Thief - -## Motivation -A greedy algorithm is a type of algorithm that builds up a solution piece by piece always choosing the piece that offers the most imediate benifit. We choose the locally optimal solution at each step to get a globally optimal solution to the problem. - - -## Problem Description -You are a jewel thief and you are going on a heist at a jewel museum. You bring with you a bag with a maximum capacity of `xkg`. The jewels in the museum are represented as a list of tuples `(weight, value)` where the weight is the weight of the given jewel in kg and the value is the monetary value of the given jewel. -In the *solution.py* file, define a function `steal_jewels` that takes in the maximum capacity of your bag `x` and a list of jewels in the museum `jewels` and outputs the maximal value of jewels you can steal from the museum. If a jewel is too heavy for your bag, you may smash the jewel on the floor and take a fraction of the jewel. - -## Example -``` -jewels = [(1, 4), (2, 8), (3, 15), (9, 50)] -steal_jewels(10, jewels) == 55 -``` -In this example we get the highest value by stealing the last jewel at `9kg` with a value of `50`, and we smash the third jewel and take a third of it at 1kg with a value of `5`, which gives us a full bag at 10kg with a total value of `55`. - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Greedy Algorithm - Jewel Thief + +## Motivation +A greedy algorithm is a type of algorithm that builds up a solution piece by piece always choosing the piece that offers the most imediate benifit. We choose the locally optimal solution at each step to get a globally optimal solution to the problem. + + +## Problem Description +You are a jewel thief and you are going on a heist at a jewel museum. You bring with you a bag with a maximum capacity of `xkg`. The jewels in the museum are represented as a list of tuples `(weight, value)` where the weight is the weight of the given jewel in kg and the value is the monetary value of the given jewel. +In the *solution.py* file, define a function `steal_jewels` that takes in the maximum capacity of your bag `x` and a list of jewels in the museum `jewels` and outputs the maximal value of jewels you can steal from the museum. If a jewel is too heavy for your bag, you may smash the jewel on the floor and take a fraction of the jewel. + +## Example +``` +jewels = [(1, 4), (2, 8), (3, 15), (9, 50)] +steal_jewels(10, jewels) == 55 +``` +In this example we get the highest value by stealing the last jewel at `9kg` with a value of `50`, and we smash the third jewel and take a third of it at 1kg with a value of `5`, which gives us a full bag at 10kg with a total value of `55`. + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/greedy_and_divide_and_conquer/jewel_thief/solution/solution.py b/algorithms/greedy_and_divide_and_conquer/jewel_thief/solution/solution.py index a6118d89..03106f53 100644 --- a/algorithms/greedy_and_divide_and_conquer/jewel_thief/solution/solution.py +++ b/algorithms/greedy_and_divide_and_conquer/jewel_thief/solution/solution.py @@ -1,39 +1,39 @@ -def sort_tuples(tup): - tup.sort(key = lambda t: t[1]) - tup.reverse() - return tup - -def steal_jewels(x, jewels): - # max_val will keep track of the max_val we can add to our bag. - max_val = 0 - # we sort the list of jewel tuples in decresing order by value. - # so the highet value jewel will be at the first of the list. - sorted_value_jewels = sort_tuples(jewels) - # we loop through the list of jewel tuples - for jewel in sorted_value_jewels: - jewel_weight = jewel[0] - jewel_value = jewel[1] - # if our bag weight capacity is 0 we return the maximum value - # we've added to our bag max_val. - if x == 0: - return max_val - # if the weight of the current jewel is <= x we add it to our bag - # and update the capacity of our bag, and update the max_value we - # have so far. - elif jewel_weight <= x: - max_val += jewel_value - x = x-jewel_weight - else: - # if the jewel weight is larger than the capacity of our bag, - # we calculate the value of a 1kg portion of the jewel - unit_val = jewel_value/jewel_weight - # we add an xkg portion of the jewel to our bag - max_val += x * unit_val - # our bag is now full and we return max_val - return max_val - # after we itterate through all the jewels, we've added everything we can - # so we return max_val - return max_val - -jewels = [(1, 4), (2, 8), (3, 15), (9, 50)] +def sort_tuples(tup): + tup.sort(key = lambda t: t[1]) + tup.reverse() + return tup + +def steal_jewels(x, jewels): + # max_val will keep track of the max_val we can add to our bag. + max_val = 0 + # we sort the list of jewel tuples in decresing order by value. + # so the highet value jewel will be at the first of the list. + sorted_value_jewels = sort_tuples(jewels) + # we loop through the list of jewel tuples + for jewel in sorted_value_jewels: + jewel_weight = jewel[0] + jewel_value = jewel[1] + # if our bag weight capacity is 0 we return the maximum value + # we've added to our bag max_val. + if x == 0: + return max_val + # if the weight of the current jewel is <= x we add it to our bag + # and update the capacity of our bag, and update the max_value we + # have so far. + elif jewel_weight <= x: + max_val += jewel_value + x = x-jewel_weight + else: + # if the jewel weight is larger than the capacity of our bag, + # we calculate the value of a 1kg portion of the jewel + unit_val = jewel_value/jewel_weight + # we add an xkg portion of the jewel to our bag + max_val += x * unit_val + # our bag is now full and we return max_val + return max_val + # after we itterate through all the jewels, we've added everything we can + # so we return max_val + return max_val + +jewels = [(1, 4), (2, 8), (3, 15), (9, 50)] print(steal_jewels(10, jewels)) \ No newline at end of file diff --git a/algorithms/greedy_and_divide_and_conquer/jewel_thief/solution/test_solution.py b/algorithms/greedy_and_divide_and_conquer/jewel_thief/solution/test_solution.py index 296a69e9..13ac4203 100644 --- a/algorithms/greedy_and_divide_and_conquer/jewel_thief/solution/test_solution.py +++ b/algorithms/greedy_and_divide_and_conquer/jewel_thief/solution/test_solution.py @@ -1,12 +1,12 @@ -def test_solution(): - import solution - - jewels1 = [(1, 4), (2, 8), (3, 15), (9, 50)] - jewels2 = [(1, 1)] - jewels3 = [(1, 1), (2, 8), (3, 15), (4,24)] - - assert solution.steal_jewels(10, jewels1) == 55 - assert solution.steal_jewels(10, []) == 0 - assert solution.steal_jewels(1, jewels2) == 1 - assert solution.steal_jewels(3, jewels2) == 1 +def test_solution(): + import solution + + jewels1 = [(1, 4), (2, 8), (3, 15), (9, 50)] + jewels2 = [(1, 1)] + jewels3 = [(1, 1), (2, 8), (3, 15), (4,24)] + + assert solution.steal_jewels(10, jewels1) == 55 + assert solution.steal_jewels(10, []) == 0 + assert solution.steal_jewels(1, jewels2) == 1 + assert solution.steal_jewels(3, jewels2) == 1 assert solution.steal_jewels(3, jewels3) == 18 \ No newline at end of file diff --git a/algorithms/greedy_and_divide_and_conquer/lemonade_stand/README.md b/algorithms/greedy_and_divide_and_conquer/lemonade_stand/README.md index b183713e..20d11818 100644 --- a/algorithms/greedy_and_divide_and_conquer/lemonade_stand/README.md +++ b/algorithms/greedy_and_divide_and_conquer/lemonade_stand/README.md @@ -1,30 +1,30 @@ -# Greedy Algorithm - Lemonade Stand - -## Motivation -A greedy algorithm is a type of algorithm that builds up a solution piece by piece always choosing the piece that offers the most imediate benifit. We choose the locally optimal solution at each step to get a globally optimal solution to the problem. - - -## Problem Description -You have a lemonade stand and you are selling each glass of lemonade for 5$. You have a list of customers each wanting to buy one glass of lemonade, the customers in the list are in order of when they come to your stand. Customers can pay using either 5$, 10$, or 20$ bills. You start your day with no change or bills in your cash register. -In the *solution.py* file, define a function `lemonade_change` that consumes a list of integers `customer_bills` representing the bill denomination each customer would like to pay with. Return `True` if you are able to make change for all the customers, and `False` otherwise. - -## Example -``` -customer_bills = [5, 10, 5, 20] -lemonade_change(customer_bills) == True - -customer_bills = [5, 20, 10] -lemonade_change(customer_bills) == False -``` -In the first example, the first customer buys one glass for 5$, so we now have 5$ in our register. The next customer buys one glass and gives us a 10$ bill, so we give him our 5$ bill and we now have one 10$ bill in our register. The third customer buys one glass for 5$, so we now have one 10$ bill and one 5$ bill in our register. The last customer comes and buys one glass and gives us a 20$ bill and we can give him our 10$ bill and our 5$ bill as change in return. - -In the second example, when the second customer comes to our stand they want to pay with a 20$ bill, but we only have one 5$ bill in our register so we cannot make change for him. - - - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Greedy Algorithm - Lemonade Stand + +## Motivation +A greedy algorithm is a type of algorithm that builds up a solution piece by piece always choosing the piece that offers the most imediate benifit. We choose the locally optimal solution at each step to get a globally optimal solution to the problem. + + +## Problem Description +You have a lemonade stand and you are selling each glass of lemonade for 5$. You have a list of customers each wanting to buy one glass of lemonade, the customers in the list are in order of when they come to your stand. Customers can pay using either 5$, 10$, or 20$ bills. You start your day with no change or bills in your cash register. +In the *solution.py* file, define a function `lemonade_change` that consumes a list of integers `customer_bills` representing the bill denomination each customer would like to pay with. Return `True` if you are able to make change for all the customers, and `False` otherwise. + +## Example +``` +customer_bills = [5, 10, 5, 20] +lemonade_change(customer_bills) == True + +customer_bills = [5, 20, 10] +lemonade_change(customer_bills) == False +``` +In the first example, the first customer buys one glass for 5$, so we now have 5$ in our register. The next customer buys one glass and gives us a 10$ bill, so we give him our 5$ bill and we now have one 10$ bill in our register. The third customer buys one glass for 5$, so we now have one 10$ bill and one 5$ bill in our register. The last customer comes and buys one glass and gives us a 20$ bill and we can give him our 10$ bill and our 5$ bill as change in return. + +In the second example, when the second customer comes to our stand they want to pay with a 20$ bill, but we only have one 5$ bill in our register so we cannot make change for him. + + + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/greedy_and_divide_and_conquer/lemonade_stand/solution/solution.py b/algorithms/greedy_and_divide_and_conquer/lemonade_stand/solution/solution.py index 3d60f200..5c7326f1 100644 --- a/algorithms/greedy_and_divide_and_conquer/lemonade_stand/solution/solution.py +++ b/algorithms/greedy_and_divide_and_conquer/lemonade_stand/solution/solution.py @@ -1,44 +1,44 @@ -def lemonade_change(customer_bills): - # we create a dictionary to keep track of all the bills - # of each denomination in our register. - # we start with 0 of each bill. - register = {5: 0, 10: 0, 20: 0} - # we itterate through the list of customer_bills - for bill in customer_bills: - # if the bill is 5, we don't need any change - # so we serve them lemodane and add the 5$ bill - # to our register updating the dictionary at 5 by 1. - if bill == 5: - register[5] +=1 - # if the bill is 10, we need to check if we have any - # 5$ bills to make change for the customer. - elif bill == 10: - # If we have a 5, - # we update the register removing a 5 an adding a 10$ bill. - if not register[5] == 0: - register[5] -= 1 - register[10] += 1 - else: - # if we have no 5 bills we cannot make change and return false. - return False - # if the customer has a 20$ bill we need to try and make change with 10s or 5s. - elif bill == 20: - # if we have no 10s we need 3 5$ bills - if register[10] == 0: - if register[5] >= 3: - register[5] -= 3 - register[20] +=1 - else: - return False - # if we have a 10, we also need one 5$ bill. - elif register[10] >= 1 and register[5] >= 1: - register[10] -= 1 - register[5] -= 1 - register[20] += 1 - else: - return False - # once we've itterated through all customers, we were able to make all - # the change so we return True. - return True - -print(lemonade_change([5, 20, 5, 20])) +def lemonade_change(customer_bills): + # we create a dictionary to keep track of all the bills + # of each denomination in our register. + # we start with 0 of each bill. + register = {5: 0, 10: 0, 20: 0} + # we itterate through the list of customer_bills + for bill in customer_bills: + # if the bill is 5, we don't need any change + # so we serve them lemodane and add the 5$ bill + # to our register updating the dictionary at 5 by 1. + if bill == 5: + register[5] +=1 + # if the bill is 10, we need to check if we have any + # 5$ bills to make change for the customer. + elif bill == 10: + # If we have a 5, + # we update the register removing a 5 an adding a 10$ bill. + if not register[5] == 0: + register[5] -= 1 + register[10] += 1 + else: + # if we have no 5 bills we cannot make change and return false. + return False + # if the customer has a 20$ bill we need to try and make change with 10s or 5s. + elif bill == 20: + # if we have no 10s we need 3 5$ bills + if register[10] == 0: + if register[5] >= 3: + register[5] -= 3 + register[20] +=1 + else: + return False + # if we have a 10, we also need one 5$ bill. + elif register[10] >= 1 and register[5] >= 1: + register[10] -= 1 + register[5] -= 1 + register[20] += 1 + else: + return False + # once we've itterated through all customers, we were able to make all + # the change so we return True. + return True + +print(lemonade_change([5, 20, 5, 20])) diff --git a/algorithms/greedy_and_divide_and_conquer/lemonade_stand/solution/test_solution.py b/algorithms/greedy_and_divide_and_conquer/lemonade_stand/solution/test_solution.py index 635df8f1..8bf6750a 100644 --- a/algorithms/greedy_and_divide_and_conquer/lemonade_stand/solution/test_solution.py +++ b/algorithms/greedy_and_divide_and_conquer/lemonade_stand/solution/test_solution.py @@ -1,9 +1,9 @@ -def test_solution(): - import solution - - assert solution.lemonade_change([5, 10, 5, 20]) == True - assert solution.lemonade_change([]) == True - assert solution.lemonade_change([5, 20, 5, 20]) == False - assert solution.lemonade_change([5]) == True - assert solution.lemonade_change([10]) == False - assert solution.lemonade_change([5, 10, 10, 20]) == False +def test_solution(): + import solution + + assert solution.lemonade_change([5, 10, 5, 20]) == True + assert solution.lemonade_change([]) == True + assert solution.lemonade_change([5, 20, 5, 20]) == False + assert solution.lemonade_change([5]) == True + assert solution.lemonade_change([10]) == False + assert solution.lemonade_change([5, 10, 10, 20]) == False diff --git a/algorithms/greedy_and_divide_and_conquer/make_change/README.md b/algorithms/greedy_and_divide_and_conquer/make_change/README.md index 57f4fe0a..f220dca3 100644 --- a/algorithms/greedy_and_divide_and_conquer/make_change/README.md +++ b/algorithms/greedy_and_divide_and_conquer/make_change/README.md @@ -1,22 +1,22 @@ -# Greedy Algorithm - European Coin Change - -## Motivation -A greedy algorithm is a type of algorithm that builds up a solution piece by piece always choosing the piece that offers the most imediate benifit. We choose the locally optimal solution at each step to get a globally optimal solution to the problem. - - -## Problem Description -In the *solution.py* file, define a function `make_change` that consumes a positive integer `amount` which will be a monertary value given in Euro cents, and a list of coin values `denominations` given in european cent denominations, and using a greedy algorithm, returns the minimum number of coins needed to make change for `amount`. If you cannot make change for `amount` return `-1`. - -## Example -``` -denominations = [1, 2, 5, 10, 20, 50, 100, 200] -make_change(450, denominations) == 3 -``` -In this example we use two 200c (2€) coins and one 50c coin. - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Greedy Algorithm - European Coin Change + +## Motivation +A greedy algorithm is a type of algorithm that builds up a solution piece by piece always choosing the piece that offers the most imediate benifit. We choose the locally optimal solution at each step to get a globally optimal solution to the problem. + + +## Problem Description +In the *solution.py* file, define a function `make_change` that consumes a positive integer `amount` which will be a monertary value given in Euro cents, and a list of coin values `denominations` given in european cent denominations, and using a greedy algorithm, returns the minimum number of coins needed to make change for `amount`. If you cannot make change for `amount` return `-1`. + +## Example +``` +denominations = [1, 2, 5, 10, 20, 50, 100, 200] +make_change(450, denominations) == 3 +``` +In this example we use two 200c (2€) coins and one 50c coin. + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/greedy_and_divide_and_conquer/make_change/solution/solution.py b/algorithms/greedy_and_divide_and_conquer/make_change/solution/solution.py index 517bc5c0..cf4a5752 100644 --- a/algorithms/greedy_and_divide_and_conquer/make_change/solution/solution.py +++ b/algorithms/greedy_and_divide_and_conquer/make_change/solution/solution.py @@ -1,19 +1,19 @@ -def make_change_helper(amount, denominations, num_coins): - # if amount is 0 we made all the change and we return num_coins. - if amount == 0: - return num_coins - # itterate through denominations from largest to smallest - for i in range(len(denominations)): - # if the amount is larger or equal to the current coin value - # we recurse, decreasing the amount by that coin value, and - # increasing the number of coins by 1. - if amount >= denominations[i]: - return make_change_helper(amount-denominations[i], denominations, num_coins+1) - # once we've itterated through all the coins we never hit amount == 0, so we - # have a remainder we could not make change for and we return -1. - return -1 - -def make_change(amount, denominations): - # Sort denominations in decreasing order - denominations = sorted(denominations, reverse=True) - return make_change_helper(amount, denominations, 0) +def make_change_helper(amount, denominations, num_coins): + # if amount is 0 we made all the change and we return num_coins. + if amount == 0: + return num_coins + # itterate through denominations from largest to smallest + for i in range(len(denominations)): + # if the amount is larger or equal to the current coin value + # we recurse, decreasing the amount by that coin value, and + # increasing the number of coins by 1. + if amount >= denominations[i]: + return make_change_helper(amount-denominations[i], denominations, num_coins+1) + # once we've itterated through all the coins we never hit amount == 0, so we + # have a remainder we could not make change for and we return -1. + return -1 + +def make_change(amount, denominations): + # Sort denominations in decreasing order + denominations = sorted(denominations, reverse=True) + return make_change_helper(amount, denominations, 0) diff --git a/algorithms/greedy_and_divide_and_conquer/make_change/solution/test_solution.py b/algorithms/greedy_and_divide_and_conquer/make_change/solution/test_solution.py index 42bd2c98..6c9f08cf 100644 --- a/algorithms/greedy_and_divide_and_conquer/make_change/solution/test_solution.py +++ b/algorithms/greedy_and_divide_and_conquer/make_change/solution/test_solution.py @@ -1,13 +1,13 @@ -def test_solution(): - import solution - - denominations1 = [1, 2, 5, 10, 20, 50, 100, 200] - denominations2 = [1, 2, 5, 100] - denominations3 = [20, 50, 100, 200] - denominations4 = [1, 100, 200] - - assert solution.make_change(450, denominations1) == 3 - assert solution.make_change(50, denominations1) == 1 - assert solution.make_change(233, denominations2) == 10 - assert solution.make_change(30, denominations3) == -1 - assert solution.make_change(77, denominations4) == 77 +def test_solution(): + import solution + + denominations1 = [1, 2, 5, 10, 20, 50, 100, 200] + denominations2 = [1, 2, 5, 100] + denominations3 = [20, 50, 100, 200] + denominations4 = [1, 100, 200] + + assert solution.make_change(450, denominations1) == 3 + assert solution.make_change(50, denominations1) == 1 + assert solution.make_change(233, denominations2) == 10 + assert solution.make_change(30, denominations3) == -1 + assert solution.make_change(77, denominations4) == 77 diff --git a/algorithms/greedy_and_divide_and_conquer/make_change_limited_coins/README.md b/algorithms/greedy_and_divide_and_conquer/make_change_limited_coins/README.md index db23fedc..478952e5 100644 --- a/algorithms/greedy_and_divide_and_conquer/make_change_limited_coins/README.md +++ b/algorithms/greedy_and_divide_and_conquer/make_change_limited_coins/README.md @@ -1,21 +1,21 @@ -# Greedy Algorithm - European Coin Change with Limited Coins - -## Motivation -A greedy algorithm is a type of algorithm that builds up a solution piece by piece always choosing the piece that offers the most imediate benifit. We choose the locally optimal solution at each step to get a globally optimal solution to the problem. - -## Problem Description -In the *solution.py* file, define a function `make_change` that consumes a positive integer `amount` which will be a monertary value given in Euro cents, and a list `denominations` which is a dictionary of `{value: count}` where value is the value of a coin, given in european cent denominations, and `count` is how many of that coin you have in your pocket. Using a greedy algorithm, return the minimum number of coins needed to make change for `amount`, given the coins in your pocket. If you cannot make change for `amount` return `-1`. - -## Example -``` -denominations = {1: 5, 2: 1, 10: 5, 50: 3, 100: 1, 200: 1} -make_change(450, denominations) == 5 -``` -In this example we use one 200c (2€) coin, one 100c (1€) coin, and all three of our 50c coins. - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Greedy Algorithm - European Coin Change with Limited Coins + +## Motivation +A greedy algorithm is a type of algorithm that builds up a solution piece by piece always choosing the piece that offers the most imediate benifit. We choose the locally optimal solution at each step to get a globally optimal solution to the problem. + +## Problem Description +In the *solution.py* file, define a function `make_change` that consumes a positive integer `amount` which will be a monertary value given in Euro cents, and a list `denominations` which is a dictionary of `{value: count}` where value is the value of a coin, given in european cent denominations, and `count` is how many of that coin you have in your pocket. Using a greedy algorithm, return the minimum number of coins needed to make change for `amount`, given the coins in your pocket. If you cannot make change for `amount` return `-1`. + +## Example +``` +denominations = {1: 5, 2: 1, 10: 5, 50: 3, 100: 1, 200: 1} +make_change(450, denominations) == 5 +``` +In this example we use one 200c (2€) coin, one 100c (1€) coin, and all three of our 50c coins. + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/greedy_and_divide_and_conquer/make_change_limited_coins/solution/solution.py b/algorithms/greedy_and_divide_and_conquer/make_change_limited_coins/solution/solution.py index 78b13f73..5b056e8e 100644 --- a/algorithms/greedy_and_divide_and_conquer/make_change_limited_coins/solution/solution.py +++ b/algorithms/greedy_and_divide_and_conquer/make_change_limited_coins/solution/solution.py @@ -1,26 +1,26 @@ -def make_change_helper(amount, denominations, denomination_keys, num_coins): - # if we have ammount 0, we made all the change and we return num_coins. - if amount == 0: - return num_coins - # we itterate through the denomination_keys list by index and the denomination key - for idx, k in enumerate(denomination_keys): - # if amount is greater than the denomination key - if amount >= k: - # we update the denomination dict taking one away - denominations[k] -= 1 - # if we now have none of that coin left in our denominations dict - # we update the list by removing that element and only looking at the - # denominations in the rest of the list. - if denominations[k] == 0: - denomination_keys = denomination_keys[idx+1:] - # we recurse, updating the amount by subtracting the coin we saw, and - # adding one to num_coins - return make_change_helper(amount-k, denominations, denomination_keys, num_coins+1) - # if we itterated through all the coins and still have a remainder, we could not - # make all the change, so we return -1. - return -1 - -def make_change(amount, denominations): - # create a list of denomination values sorted in decreasing order. - denomination_keys = sorted(denominations.keys(), reverse=True) - return make_change_helper(amount, denominations, denomination_keys, 0) +def make_change_helper(amount, denominations, denomination_keys, num_coins): + # if we have ammount 0, we made all the change and we return num_coins. + if amount == 0: + return num_coins + # we itterate through the denomination_keys list by index and the denomination key + for idx, k in enumerate(denomination_keys): + # if amount is greater than the denomination key + if amount >= k: + # we update the denomination dict taking one away + denominations[k] -= 1 + # if we now have none of that coin left in our denominations dict + # we update the list by removing that element and only looking at the + # denominations in the rest of the list. + if denominations[k] == 0: + denomination_keys = denomination_keys[idx+1:] + # we recurse, updating the amount by subtracting the coin we saw, and + # adding one to num_coins + return make_change_helper(amount-k, denominations, denomination_keys, num_coins+1) + # if we itterated through all the coins and still have a remainder, we could not + # make all the change, so we return -1. + return -1 + +def make_change(amount, denominations): + # create a list of denomination values sorted in decreasing order. + denomination_keys = sorted(denominations.keys(), reverse=True) + return make_change_helper(amount, denominations, denomination_keys, 0) diff --git a/algorithms/greedy_and_divide_and_conquer/make_change_limited_coins/solution/test_solution.py b/algorithms/greedy_and_divide_and_conquer/make_change_limited_coins/solution/test_solution.py index ca7140a2..0f81ae39 100644 --- a/algorithms/greedy_and_divide_and_conquer/make_change_limited_coins/solution/test_solution.py +++ b/algorithms/greedy_and_divide_and_conquer/make_change_limited_coins/solution/test_solution.py @@ -1,13 +1,13 @@ -def test_solution(): - import solution - - denominations1 = {1: 5, 2: 1, 10: 5, 50: 3, 100: 1, 200: 1} - denominations2 = {1: 5, 2: 1, 50: 3, 100: 1, 200: 1} - denominations3 = {1: 5, 2: 1, 5: 1, 10: 1, 20: 1, 50: 3} - denominations4 = {1: 5, 2: 1, 50: 3, 100: 1, 200: 1} - - assert solution.make_change(450, denominations1) == 5 - assert solution.make_change(10, denominations2) == -1 - assert solution.make_change(10, {}) == -1 - assert solution.make_change(305, denominations4) == 6 - assert solution.make_change(43, denominations3) == -1 +def test_solution(): + import solution + + denominations1 = {1: 5, 2: 1, 10: 5, 50: 3, 100: 1, 200: 1} + denominations2 = {1: 5, 2: 1, 50: 3, 100: 1, 200: 1} + denominations3 = {1: 5, 2: 1, 5: 1, 10: 1, 20: 1, 50: 3} + denominations4 = {1: 5, 2: 1, 50: 3, 100: 1, 200: 1} + + assert solution.make_change(450, denominations1) == 5 + assert solution.make_change(10, denominations2) == -1 + assert solution.make_change(10, {}) == -1 + assert solution.make_change(305, denominations4) == 6 + assert solution.make_change(43, denominations3) == -1 diff --git a/algorithms/greedy_and_divide_and_conquer/min_max/README.md b/algorithms/greedy_and_divide_and_conquer/min_max/README.md index 9b85fc92..da36c9eb 100644 --- a/algorithms/greedy_and_divide_and_conquer/min_max/README.md +++ b/algorithms/greedy_and_divide_and_conquer/min_max/README.md @@ -1,19 +1,19 @@ -# Divide and Conquer Algorithm - Min and Max of a list - -## Motivation -Divide and Conquer Algorithms breaks up a problem into smaller subproblems, solves the subproblems recursively and finally combines the results of the subproblems to find the answer the the main problem. -Often if we can come up with a divide and conquer approach to a problem, this will be much faster than a naive recursive solution. - -## Problem Description -In the *solution.py* file, define a function `min_max` that takes in a non-empty list of integers `lst`, and using a binary search technique outputs a tuple `(min, max)`, which contains the the minimum and maximum integers in `lst`. Hint: Recursively divide the list in halves at each step and compare the min and max of the smaller sublists. - -## Example -``` -min_max([8, 2, 1, 3, 1, 5]) == (1, 8) -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Divide and Conquer Algorithm - Min and Max of a list + +## Motivation +Divide and Conquer Algorithms breaks up a problem into smaller subproblems, solves the subproblems recursively and finally combines the results of the subproblems to find the answer the the main problem. +Often if we can come up with a divide and conquer approach to a problem, this will be much faster than a naive recursive solution. + +## Problem Description +In the *solution.py* file, define a function `min_max` that takes in a non-empty list of integers `lst`, and using a binary search technique outputs a tuple `(min, max)`, which contains the the minimum and maximum integers in `lst`. Hint: Recursively divide the list in halves at each step and compare the min and max of the smaller sublists. + +## Example +``` +min_max([8, 2, 1, 3, 1, 5]) == (1, 8) +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/greedy_and_divide_and_conquer/min_max/solution/solution.py b/algorithms/greedy_and_divide_and_conquer/min_max/solution/solution.py index e3edf2c8..a8824e65 100644 --- a/algorithms/greedy_and_divide_and_conquer/min_max/solution/solution.py +++ b/algorithms/greedy_and_divide_and_conquer/min_max/solution/solution.py @@ -1,31 +1,31 @@ -def min_max_divider(lst, low, high): - max_elem = lst[low] - min_elem = lst[low] - - # If there is only one element - if low == high: - return (min_elem, max_elem) - - # If there is only two element - elif high == low + 1: - if lst[low] > lst[high]: - max_elem = lst[low] - min_elem = lst[high] - else: - max_elem = lst[high] - min_elem = lst[low] - return (min_elem, max_elem) - else: - # If there are more than 2 elements - mid = int((low + high) / 2) - # recuse to find the min, max in the sublist from low to mid - min1, max1 = min_max_divider(lst, low, mid) - # recuse to find the min, max in the sublist from mid to high - min2, max2 = min_max_divider(lst, mid + 1, high) - # return the global min, max by taking the min and max of the mins - # and maxs in the two sublists - return (min(min1, min2), max(max1, max2)) - - -def min_max(lst): - return min_max_divider(lst, 0, len(lst)-1) +def min_max_divider(lst, low, high): + max_elem = lst[low] + min_elem = lst[low] + + # If there is only one element + if low == high: + return (min_elem, max_elem) + + # If there is only two element + elif high == low + 1: + if lst[low] > lst[high]: + max_elem = lst[low] + min_elem = lst[high] + else: + max_elem = lst[high] + min_elem = lst[low] + return (min_elem, max_elem) + else: + # If there are more than 2 elements + mid = int((low + high) / 2) + # recuse to find the min, max in the sublist from low to mid + min1, max1 = min_max_divider(lst, low, mid) + # recuse to find the min, max in the sublist from mid to high + min2, max2 = min_max_divider(lst, mid + 1, high) + # return the global min, max by taking the min and max of the mins + # and maxs in the two sublists + return (min(min1, min2), max(max1, max2)) + + +def min_max(lst): + return min_max_divider(lst, 0, len(lst)-1) diff --git a/algorithms/greedy_and_divide_and_conquer/min_max/solution/test_solution.py b/algorithms/greedy_and_divide_and_conquer/min_max/solution/test_solution.py index 41c20a01..2151ece0 100644 --- a/algorithms/greedy_and_divide_and_conquer/min_max/solution/test_solution.py +++ b/algorithms/greedy_and_divide_and_conquer/min_max/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - import solution - - assert solution.min_max([1]) == (1, 1) - assert solution.min_max([1, 3, 2]) == (1, 3) - assert solution.min_max([1, 3, 2, 1, 8, 1]) == (1, 8) +def test_solution(): + import solution + + assert solution.min_max([1]) == (1, 1) + assert solution.min_max([1, 3, 2]) == (1, 3) + assert solution.min_max([1, 3, 2, 1, 8, 1]) == (1, 8) assert solution.min_max([9, 7, 2, 3, 3, 4]) == (2, 9) \ No newline at end of file diff --git a/algorithms/greedy_and_divide_and_conquer/scheduling/README.md b/algorithms/greedy_and_divide_and_conquer/scheduling/README.md index 8a913a62..98e3cee8 100644 --- a/algorithms/greedy_and_divide_and_conquer/scheduling/README.md +++ b/algorithms/greedy_and_divide_and_conquer/scheduling/README.md @@ -1,21 +1,21 @@ -# Greedy Algorithm - Scheduling Tasks - -## Motivation -A greedy algorithm is a type of algorithm that builds up a solution piece by piece always choosing the piece that offers the most imediate benifit. We choose the locally optimal solution at each step to get a globally optimal solution to the problem. - -## Problem Description -Your boss gives you a list of tasks you have to complete on that day for your job, each with a start time and end time given as a tuple `(start, end)`. `Start` and `end` will be given in hrs on a 24hr clock. -In the *solution.py* file, define a function `task_schedule` that takes in the list of tasks `tasks`, and outputs the maximum number of tasks you can complete in the day. You cannot do more than one task at a time. Hint: Sort the list by finishing time. - -## Example -``` -tasks = [(14, 15), (8, 13), (9, 11), (11, 13), (14, 16)] -task_schedule(tasks) == 3 -``` -In this example, we can do the task from 9am-11am, the next task from 11am-1pm, and the final task from 2pm-4pm. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Greedy Algorithm - Scheduling Tasks + +## Motivation +A greedy algorithm is a type of algorithm that builds up a solution piece by piece always choosing the piece that offers the most imediate benifit. We choose the locally optimal solution at each step to get a globally optimal solution to the problem. + +## Problem Description +Your boss gives you a list of tasks you have to complete on that day for your job, each with a start time and end time given as a tuple `(start, end)`. `Start` and `end` will be given in hrs on a 24hr clock. +In the *solution.py* file, define a function `task_schedule` that takes in the list of tasks `tasks`, and outputs the maximum number of tasks you can complete in the day. You cannot do more than one task at a time. Hint: Sort the list by finishing time. + +## Example +``` +tasks = [(14, 15), (8, 13), (9, 11), (11, 13), (14, 16)] +task_schedule(tasks) == 3 +``` +In this example, we can do the task from 9am-11am, the next task from 11am-1pm, and the final task from 2pm-4pm. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/greedy_and_divide_and_conquer/scheduling/solution/solution.py b/algorithms/greedy_and_divide_and_conquer/scheduling/solution/solution.py index d72b6b59..2480ee20 100644 --- a/algorithms/greedy_and_divide_and_conquer/scheduling/solution/solution.py +++ b/algorithms/greedy_and_divide_and_conquer/scheduling/solution/solution.py @@ -1,16 +1,16 @@ -def task_schedule(tasks): - # sort the tasks list by finishing time. - tasks.sort(key = lambda t: t[1]) - num_tasks = 0 - cur_end = 0 - # itterate through the tasks - for t in tasks: - # if task ts start time is later or equal to our current end time - # we can do that task, so we update the end time to ts end time and - # increment the number of tasks by 1. - if t[0] >= cur_end: - cur_end = t[1] - num_tasks += 1 - # once we've itterated through all the tasks we return the num_tasks - # we could complete. +def task_schedule(tasks): + # sort the tasks list by finishing time. + tasks.sort(key = lambda t: t[1]) + num_tasks = 0 + cur_end = 0 + # itterate through the tasks + for t in tasks: + # if task ts start time is later or equal to our current end time + # we can do that task, so we update the end time to ts end time and + # increment the number of tasks by 1. + if t[0] >= cur_end: + cur_end = t[1] + num_tasks += 1 + # once we've itterated through all the tasks we return the num_tasks + # we could complete. return num_tasks \ No newline at end of file diff --git a/algorithms/greedy_and_divide_and_conquer/scheduling/solution/test_solution.py b/algorithms/greedy_and_divide_and_conquer/scheduling/solution/test_solution.py index bd52383e..375f5447 100644 --- a/algorithms/greedy_and_divide_and_conquer/scheduling/solution/test_solution.py +++ b/algorithms/greedy_and_divide_and_conquer/scheduling/solution/test_solution.py @@ -1,14 +1,14 @@ -def test_solution(): - import solution - - tasks1 = [(14, 15), (8, 13), (9, 11), (11, 13), (14, 16)] - tasks2 = [(9, 17), (9,12), (13, 17)] - tasks3 = [(9, 17), (10,17), (13, 17)] - tasks4 = [(10, 15), (10,17), (10, 13)] - - assert solution.task_schedule(tasks1) == 3 - assert solution.task_schedule([]) == 0 - assert solution.task_schedule([(9, 17)]) == 1 - assert solution.task_schedule(tasks2) == 2 - assert solution.task_schedule(tasks3) == 1 +def test_solution(): + import solution + + tasks1 = [(14, 15), (8, 13), (9, 11), (11, 13), (14, 16)] + tasks2 = [(9, 17), (9,12), (13, 17)] + tasks3 = [(9, 17), (10,17), (13, 17)] + tasks4 = [(10, 15), (10,17), (10, 13)] + + assert solution.task_schedule(tasks1) == 3 + assert solution.task_schedule([]) == 0 + assert solution.task_schedule([(9, 17)]) == 1 + assert solution.task_schedule(tasks2) == 2 + assert solution.task_schedule(tasks3) == 1 assert solution.task_schedule(tasks4) == 1 \ No newline at end of file diff --git a/algorithms/greedy_and_divide_and_conquer/square_root/README.md b/algorithms/greedy_and_divide_and_conquer/square_root/README.md index d20a93bd..62af8a7e 100644 --- a/algorithms/greedy_and_divide_and_conquer/square_root/README.md +++ b/algorithms/greedy_and_divide_and_conquer/square_root/README.md @@ -1,20 +1,20 @@ -# Divide and Conquer Algorithm - Square Root Using Binary Search - -## Motivation -Divide and Conquer Algorithms breaks up a problem into smaller subproblems, solves the subproblems recursively and finally combines the results of the subproblems to find the answer the the main problem. -Often if we can come up with a divide and conquer approach to a problem, this will be much faster than a naive recursive solution. - -## Problem Description -In the *solution.py* file, define a function `bin_sqrt` that takes in a positive integer `n`, and using a binary search technique outputs the closest integer which is less than or equal to the square root of `n`. Hint: At each step compare the square of the middle of a given interval with `n`. - -## Example -``` -bin_sqrt(9) == 3 -bin_sqrt(26) == 5 -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Divide and Conquer Algorithm - Square Root Using Binary Search + +## Motivation +Divide and Conquer Algorithms breaks up a problem into smaller subproblems, solves the subproblems recursively and finally combines the results of the subproblems to find the answer the the main problem. +Often if we can come up with a divide and conquer approach to a problem, this will be much faster than a naive recursive solution. + +## Problem Description +In the *solution.py* file, define a function `bin_sqrt` that takes in a positive integer `n`, and using a binary search technique outputs the closest integer which is less than or equal to the square root of `n`. Hint: At each step compare the square of the middle of a given interval with `n`. + +## Example +``` +bin_sqrt(9) == 3 +bin_sqrt(26) == 5 +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/greedy_and_divide_and_conquer/square_root/solution/solution.py b/algorithms/greedy_and_divide_and_conquer/square_root/solution/solution.py index 5ae102ff..7e82c690 100644 --- a/algorithms/greedy_and_divide_and_conquer/square_root/solution/solution.py +++ b/algorithms/greedy_and_divide_and_conquer/square_root/solution/solution.py @@ -1,31 +1,31 @@ -def bin_sqrt(n): - # Base cases - if (n == 0 or n == 1) : - return n - - # Do Binary Search for floor(sqrt(x)) - # we start a 1 and count up to end - start = 1 - end = n - while (start <= end) : - # calculate the mid point between start and end - mid = (start + end) // 2 - - # If n is a perfect square - if (mid*mid == n) : - return mid - - # update answer when mid*mid is smaller - # than n, and move closer to sqrt(n) - if (mid * mid < n) : - # update the starting point because the answer will - # either be mid or somewhere between mid+1 and end. - start = mid + 1 - ans = mid - - else : - # If mid*mid is greater than n we update end - # because the answer will be between start and mid-1 - end = mid-1 - +def bin_sqrt(n): + # Base cases + if (n == 0 or n == 1) : + return n + + # Do Binary Search for floor(sqrt(x)) + # we start a 1 and count up to end + start = 1 + end = n + while (start <= end) : + # calculate the mid point between start and end + mid = (start + end) // 2 + + # If n is a perfect square + if (mid*mid == n) : + return mid + + # update answer when mid*mid is smaller + # than n, and move closer to sqrt(n) + if (mid * mid < n) : + # update the starting point because the answer will + # either be mid or somewhere between mid+1 and end. + start = mid + 1 + ans = mid + + else : + # If mid*mid is greater than n we update end + # because the answer will be between start and mid-1 + end = mid-1 + return ans \ No newline at end of file diff --git a/algorithms/greedy_and_divide_and_conquer/square_root/solution/test_solution.py b/algorithms/greedy_and_divide_and_conquer/square_root/solution/test_solution.py index cecb7c8f..8d3be9ae 100644 --- a/algorithms/greedy_and_divide_and_conquer/square_root/solution/test_solution.py +++ b/algorithms/greedy_and_divide_and_conquer/square_root/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - import solution - - assert solution.bin_sqrt(9) == 3 - assert solution.bin_sqrt(26) == 5 - assert solution.bin_sqrt(120) == 10 +def test_solution(): + import solution + + assert solution.bin_sqrt(9) == 3 + assert solution.bin_sqrt(26) == 5 + assert solution.bin_sqrt(120) == 10 assert solution.bin_sqrt(4) == 2 \ No newline at end of file diff --git a/algorithms/greedy_and_divide_and_conquer/work_projects/README.md b/algorithms/greedy_and_divide_and_conquer/work_projects/README.md index 2e76829e..4c9d1238 100644 --- a/algorithms/greedy_and_divide_and_conquer/work_projects/README.md +++ b/algorithms/greedy_and_divide_and_conquer/work_projects/README.md @@ -1,21 +1,21 @@ -# Greedy Algorithm - Work Projects - -## Motivation -A greedy algorithm is a type of algorithm that builds up a solution piece by piece always choosing the piece that offers the most imediate benifit. We choose the locally optimal solution at each step to get a globally optimal solution to the problem. - -## Problem Description -Your boss gives you a list of work projects each with a deadline and profit given as a tuple `(deadline, profit)`. The deadline will be an integer representing the time unit after which the project cannot be executed. Each project takes one unit of time. For example, a project with a deadline of `2` can only be executed in the first or second time slot. Profit will be an integer represeting the total profits earned from completing that project. -In the *solution.py* file, define a function `max_profits` that takes in the list of projects `projects`, and outputs the maximal profits you can make given the list of projects. Hint: Sort the list by maximal profit. - -## Example -``` -projects = [(1, 100), (2, 150), (2, 300), (4, 200), (3, 100)] -max_profits(projects) == 750 -``` -In this example, we choose to execute `(2, 150)` in the first time slot, we execute `(2, 300)` in the second time slot, we execute `(3, 100)` in the third time slot, and we execute `(4, 200)` in the fourth time slot. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Greedy Algorithm - Work Projects + +## Motivation +A greedy algorithm is a type of algorithm that builds up a solution piece by piece always choosing the piece that offers the most imediate benifit. We choose the locally optimal solution at each step to get a globally optimal solution to the problem. + +## Problem Description +Your boss gives you a list of work projects each with a deadline and profit given as a tuple `(deadline, profit)`. The deadline will be an integer representing the time unit after which the project cannot be executed. Each project takes one unit of time. For example, a project with a deadline of `2` can only be executed in the first or second time slot. Profit will be an integer represeting the total profits earned from completing that project. +In the *solution.py* file, define a function `max_profits` that takes in the list of projects `projects`, and outputs the maximal profits you can make given the list of projects. Hint: Sort the list by maximal profit. + +## Example +``` +projects = [(1, 100), (2, 150), (2, 300), (4, 200), (3, 100)] +max_profits(projects) == 750 +``` +In this example, we choose to execute `(2, 150)` in the first time slot, we execute `(2, 300)` in the second time slot, we execute `(3, 100)` in the third time slot, and we execute `(4, 200)` in the fourth time slot. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/greedy_and_divide_and_conquer/work_projects/solution/solution.py b/algorithms/greedy_and_divide_and_conquer/work_projects/solution/solution.py index 1a5a740f..1750bdcf 100644 --- a/algorithms/greedy_and_divide_and_conquer/work_projects/solution/solution.py +++ b/algorithms/greedy_and_divide_and_conquer/work_projects/solution/solution.py @@ -1,21 +1,21 @@ -def max_profits(projects): - # sort list of project tuples by highest profit - projects.sort(key = lambda t: t[1], reverse=True) - project_dict = {} - total_profit = 0 - # itterate through the list of projects - for p in projects: - # itterare through the possible time slots you can complete - # that project in starting at the latest time slot. - for i in range(p[0],0, -1): - # add project p to latest time slot it can be added - # to in project dict without an existing project - if not i in project_dict: - # add this project to our project dict. - project_dict[i] = p[1] - # update total_profit - total_profit += p[1] - # break out of inner loop if we've added the project - break - # return total_profit once we've added all the projects we can. +def max_profits(projects): + # sort list of project tuples by highest profit + projects.sort(key = lambda t: t[1], reverse=True) + project_dict = {} + total_profit = 0 + # itterate through the list of projects + for p in projects: + # itterare through the possible time slots you can complete + # that project in starting at the latest time slot. + for i in range(p[0],0, -1): + # add project p to latest time slot it can be added + # to in project dict without an existing project + if not i in project_dict: + # add this project to our project dict. + project_dict[i] = p[1] + # update total_profit + total_profit += p[1] + # break out of inner loop if we've added the project + break + # return total_profit once we've added all the projects we can. return total_profit \ No newline at end of file diff --git a/algorithms/greedy_and_divide_and_conquer/work_projects/solution/test_solution.py b/algorithms/greedy_and_divide_and_conquer/work_projects/solution/test_solution.py index 7d6163e8..fccf3b53 100644 --- a/algorithms/greedy_and_divide_and_conquer/work_projects/solution/test_solution.py +++ b/algorithms/greedy_and_divide_and_conquer/work_projects/solution/test_solution.py @@ -1,12 +1,12 @@ -def test_solution(): - import solution - - projects1 = [(1, 100), (2, 150), (2, 300), (4, 200), (3, 100)] - projects2 = [(2, 300), (2, 100), (2, 200)] - projects3 = [(2, 300), (2, 100), (2, 200), (4, 50), (3, 200), (4, 100)] - - assert solution.max_profits(projects1) == 750 - assert solution.max_profits([]) == 0 - assert solution.max_profits([(4, 200)]) == 200 - assert solution.max_profits(projects2) == 500 - assert solution.max_profits(projects3) == 800 +def test_solution(): + import solution + + projects1 = [(1, 100), (2, 150), (2, 300), (4, 200), (3, 100)] + projects2 = [(2, 300), (2, 100), (2, 200)] + projects3 = [(2, 300), (2, 100), (2, 200), (4, 50), (3, 200), (4, 100)] + + assert solution.max_profits(projects1) == 750 + assert solution.max_profits([]) == 0 + assert solution.max_profits([(4, 200)]) == 200 + assert solution.max_profits(projects2) == 500 + assert solution.max_profits(projects3) == 800 diff --git a/algorithms/sorting/README.md b/algorithms/sorting/README.md index 00637a11..d01bed09 100644 --- a/algorithms/sorting/README.md +++ b/algorithms/sorting/README.md @@ -1,8 +1,8 @@ -# Exercises for Sorting - -* 1_Sorting1 -* 1_Sorting2 -* 1_Sorting3 -* 2_Sorting1 -* 2_Sorting2 -* 3_Sorting1 +# Exercises for Sorting + +* 1_Sorting1 +* 1_Sorting2 +* 1_Sorting3 +* 2_Sorting1 +* 2_Sorting2 +* 3_Sorting1 diff --git a/algorithms/sorting/frequency_array/README.md b/algorithms/sorting/frequency_array/README.md index 73c03a9b..a5b73409 100644 --- a/algorithms/sorting/frequency_array/README.md +++ b/algorithms/sorting/frequency_array/README.md @@ -1,22 +1,22 @@ -# Counting Sort - Frequency Array - -## Motivation -Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. -Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. - -## Problem Description -In the *solution.py* file, define a function `frequency_array` that consumes a lists of non-negative integers `lst` and returns a new list where the length of the new list is one more than the value of the largest element in the original list `lst`, and the values at each index `i` in the new list is the frequency, the number of times `i` apprears in the list `lst`. - -## Example -``` -lst = [1, 1, 3, 4, 4, 5, 6, 8, 8, 8, 9] -frequency_array(lst) == [0, 2, 0, 1, 2, 1, 1, 0, 3, 1] -``` -The largest element in `lst` is `9`, so our returned list has length `10`. In the returned list we can see there are no `0`s in `lst`, two `1`s in `lst`, no `2`s in `lst` and so on. - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Counting Sort - Frequency Array + +## Motivation +Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. +Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. + +## Problem Description +In the *solution.py* file, define a function `frequency_array` that consumes a lists of non-negative integers `lst` and returns a new list where the length of the new list is one more than the value of the largest element in the original list `lst`, and the values at each index `i` in the new list is the frequency, the number of times `i` apprears in the list `lst`. + +## Example +``` +lst = [1, 1, 3, 4, 4, 5, 6, 8, 8, 8, 9] +frequency_array(lst) == [0, 2, 0, 1, 2, 1, 1, 0, 3, 1] +``` +The largest element in `lst` is `9`, so our returned list has length `10`. In the returned list we can see there are no `0`s in `lst`, two `1`s in `lst`, no `2`s in `lst` and so on. + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/sorting/frequency_array/solution/solution.py b/algorithms/sorting/frequency_array/solution/solution.py index 5c6136ea..3f068d15 100644 --- a/algorithms/sorting/frequency_array/solution/solution.py +++ b/algorithms/sorting/frequency_array/solution/solution.py @@ -1,19 +1,19 @@ -def frequency_array(lst): - # max_elem is variable we will use to store the largest - # element in our list - max_elem = -1 - # itterate through our elements to find the - # largest element in lst. - for i in lst: - if i > max_elem: - max_elem = i - # create a list of all 0s of len(max_elem) - # freq_lst will keep track of each time we see an element - # to count the number of times it appears in lst. - freq_lst = [0 for i in range(max_elem+1)] - # itterate through elements in lst, for each element we add - # 1 to the value in freq list at the index of that value. - for elem in lst: - freq_lst[elem] += 1 - # return the freq_lst +def frequency_array(lst): + # max_elem is variable we will use to store the largest + # element in our list + max_elem = -1 + # itterate through our elements to find the + # largest element in lst. + for i in lst: + if i > max_elem: + max_elem = i + # create a list of all 0s of len(max_elem) + # freq_lst will keep track of each time we see an element + # to count the number of times it appears in lst. + freq_lst = [0 for i in range(max_elem+1)] + # itterate through elements in lst, for each element we add + # 1 to the value in freq list at the index of that value. + for elem in lst: + freq_lst[elem] += 1 + # return the freq_lst return freq_lst \ No newline at end of file diff --git a/algorithms/sorting/frequency_array/solution/test_solution.py b/algorithms/sorting/frequency_array/solution/test_solution.py index 2eb48781..dc1e94b2 100644 --- a/algorithms/sorting/frequency_array/solution/test_solution.py +++ b/algorithms/sorting/frequency_array/solution/test_solution.py @@ -1,9 +1,9 @@ -def test_solution(): - import solution - - assert solution.frequency_array([]) == [] - assert solution.frequency_array([0]) == [1] - assert solution.frequency_array([1]) == [0, 1] - assert solution.frequency_array([3]) == [0, 0, 0, 1] - assert solution.frequency_array([1, 1, 2, 3, 3, 3, 5, 8, 8]) == [0, 2, 1, 3, 0, 1, 0, 0, 2] - assert solution.frequency_array([1, 1, 4, 3, 8, 5, 9, 8, 8, 4, 6]) == [0, 2, 0, 1, 2, 1, 1, 0, 3, 1] +def test_solution(): + import solution + + assert solution.frequency_array([]) == [] + assert solution.frequency_array([0]) == [1] + assert solution.frequency_array([1]) == [0, 1] + assert solution.frequency_array([3]) == [0, 0, 0, 1] + assert solution.frequency_array([1, 1, 2, 3, 3, 3, 5, 8, 8]) == [0, 2, 1, 3, 0, 1, 0, 0, 2] + assert solution.frequency_array([1, 1, 4, 3, 8, 5, 9, 8, 8, 4, 6]) == [0, 2, 0, 1, 2, 1, 1, 0, 3, 1] diff --git a/algorithms/sorting/frequency_array_cumulative/README.md b/algorithms/sorting/frequency_array_cumulative/README.md index b1f579b0..fa0cf387 100644 --- a/algorithms/sorting/frequency_array_cumulative/README.md +++ b/algorithms/sorting/frequency_array_cumulative/README.md @@ -1,24 +1,24 @@ -# Counting Sort - Frequency Array Cumulative - -## Motivation -Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. -Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. - -## Problem Description -In the *solution.py* file, define a function `frequency_array_cumulative` that consumes a lists of non-negative integers `lst` and returns a new list where the length of the new list is one more than the value of the largest element in the original list `lst`, and the values at each index `i` in the new list is the cumulative frequency, the number of times `i` apprears in the list `lst` plus the number of times elements less than `i` appear in `lst`. Hint: You may first use your frequency_array from part 1 as a helper function and then itirate through that list to get the cumulative counts. - -## Example -``` -lst = [1, 1, 4, 3, 8, 5, 9, 8, 8, 4, 6] -lstsorted = [1, 1, 3, 4, 4, 5, 6, 8, 8, 8, 9] - -frequency_array_cumulative(lst) == [0, 2, 2, 3, 5, 6, 7, 7, 10, 11] -``` -The largest element in `lst` is `9`, so our returned list has length `10`. In the returned list we can see there are no `0`s in `lst`, two `1`s in `lst`, no `2`s in `lst`, so our cumulative count at position `2` in the `lst` remains `2`, there is one `3` in `lst`, so the cumulative count at `3` becomes `3`, there are two `4`s in `lst`, so the cumulative count at `4` becomes `5`, and so on. - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Counting Sort - Frequency Array Cumulative + +## Motivation +Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. +Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. + +## Problem Description +In the *solution.py* file, define a function `frequency_array_cumulative` that consumes a lists of non-negative integers `lst` and returns a new list where the length of the new list is one more than the value of the largest element in the original list `lst`, and the values at each index `i` in the new list is the cumulative frequency, the number of times `i` apprears in the list `lst` plus the number of times elements less than `i` appear in `lst`. Hint: You may first use your frequency_array from part 1 as a helper function and then itirate through that list to get the cumulative counts. + +## Example +``` +lst = [1, 1, 4, 3, 8, 5, 9, 8, 8, 4, 6] +lstsorted = [1, 1, 3, 4, 4, 5, 6, 8, 8, 8, 9] + +frequency_array_cumulative(lst) == [0, 2, 2, 3, 5, 6, 7, 7, 10, 11] +``` +The largest element in `lst` is `9`, so our returned list has length `10`. In the returned list we can see there are no `0`s in `lst`, two `1`s in `lst`, no `2`s in `lst`, so our cumulative count at position `2` in the `lst` remains `2`, there is one `3` in `lst`, so the cumulative count at `3` becomes `3`, there are two `4`s in `lst`, so the cumulative count at `4` becomes `5`, and so on. + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/sorting/frequency_array_cumulative/solution/solution.py b/algorithms/sorting/frequency_array_cumulative/solution/solution.py index 46305a2d..036cbcdc 100644 --- a/algorithms/sorting/frequency_array_cumulative/solution/solution.py +++ b/algorithms/sorting/frequency_array_cumulative/solution/solution.py @@ -1,26 +1,26 @@ -def frequency_array(lst): - max_elem = -1 - for i in lst: - if i > max_elem: - max_elem = i - freq_lst = [0 for i in range(max_elem+1)] - - for i in range(len(lst)): - freq_lst[lst[i]] += 1 - return freq_lst - -def frequency_array_cumulative(lst): - # create frequency array as question 1. - freq_lst = frequency_array(lst) - freq_len = len(freq_lst) - # initialise freq_cum_list with all 0 values. - freq_cum_lst = [0 for i in range(freq_len)] - # itterate through indices in the freq_list - for i in range(freq_len): - # at index 0, the freq_cum_list will be the same as the freq_lst at 0 - if i == 0: - freq_cum_lst[i] = freq_lst[i] - # at every index > 0 we add the previous frequency count with the new freq_lst[i] - else: - freq_cum_lst[i] = freq_lst[i] + freq_cum_lst[i-1] +def frequency_array(lst): + max_elem = -1 + for i in lst: + if i > max_elem: + max_elem = i + freq_lst = [0 for i in range(max_elem+1)] + + for i in range(len(lst)): + freq_lst[lst[i]] += 1 + return freq_lst + +def frequency_array_cumulative(lst): + # create frequency array as question 1. + freq_lst = frequency_array(lst) + freq_len = len(freq_lst) + # initialise freq_cum_list with all 0 values. + freq_cum_lst = [0 for i in range(freq_len)] + # itterate through indices in the freq_list + for i in range(freq_len): + # at index 0, the freq_cum_list will be the same as the freq_lst at 0 + if i == 0: + freq_cum_lst[i] = freq_lst[i] + # at every index > 0 we add the previous frequency count with the new freq_lst[i] + else: + freq_cum_lst[i] = freq_lst[i] + freq_cum_lst[i-1] return freq_cum_lst \ No newline at end of file diff --git a/algorithms/sorting/frequency_array_cumulative/solution/test_solution.py b/algorithms/sorting/frequency_array_cumulative/solution/test_solution.py index f284012e..ad1d07d5 100644 --- a/algorithms/sorting/frequency_array_cumulative/solution/test_solution.py +++ b/algorithms/sorting/frequency_array_cumulative/solution/test_solution.py @@ -1,9 +1,9 @@ -def test_solution(): - import solution - - assert solution.frequency_array_cumulative([]) == [] - assert solution.frequency_array_cumulative([0]) == [1] - assert solution.frequency_array_cumulative([1]) == [0, 1] - assert solution.frequency_array_cumulative([3]) == [0, 0, 0, 1] - assert solution.frequency_array_cumulative([1, 1, 2, 3, 3, 3, 5, 8, 8]) == [0, 2, 3, 6, 6, 7, 7, 7, 9] - assert solution.frequency_array_cumulative([1, 1, 4, 3, 8, 5, 9, 8, 8, 4, 6]) == [0, 2, 2, 3, 5, 6, 7, 7, 10, 11] +def test_solution(): + import solution + + assert solution.frequency_array_cumulative([]) == [] + assert solution.frequency_array_cumulative([0]) == [1] + assert solution.frequency_array_cumulative([1]) == [0, 1] + assert solution.frequency_array_cumulative([3]) == [0, 0, 0, 1] + assert solution.frequency_array_cumulative([1, 1, 2, 3, 3, 3, 5, 8, 8]) == [0, 2, 3, 6, 6, 7, 7, 7, 9] + assert solution.frequency_array_cumulative([1, 1, 4, 3, 8, 5, 9, 8, 8, 4, 6]) == [0, 2, 2, 3, 5, 6, 7, 7, 10, 11] diff --git a/algorithms/sorting/median_of_medians/README.md b/algorithms/sorting/median_of_medians/README.md index cbc24baa..3693fafe 100644 --- a/algorithms/sorting/median_of_medians/README.md +++ b/algorithms/sorting/median_of_medians/README.md @@ -1,20 +1,20 @@ -# Pivot Selection - Median of Medians - -## Motivation -Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. -Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. - -## Problem Description -In the *solution.py* file, define a function `median_of_medians` that consumes a lists of integers `lst` and uses the median of medians algorithm to recursively find and return the approximate median value of `lst`. You may assume `lst` is never empty. - -## Example -``` -lst = [9, 1, 0, 2, 3, 4, 6, 8, 7, 10, 5] -median_of_medians(lst) == 5 -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Pivot Selection - Median of Medians + +## Motivation +Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. +Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. + +## Problem Description +In the *solution.py* file, define a function `median_of_medians` that consumes a lists of integers `lst` and uses the median of medians algorithm to recursively find and return the approximate median value of `lst`. You may assume `lst` is never empty. + +## Example +``` +lst = [9, 1, 0, 2, 3, 4, 6, 8, 7, 10, 5] +median_of_medians(lst) == 5 +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/sorting/median_of_medians/solution/solution.py b/algorithms/sorting/median_of_medians/solution/solution.py index fa6004ee..126d0279 100644 --- a/algorithms/sorting/median_of_medians/solution/solution.py +++ b/algorithms/sorting/median_of_medians/solution/solution.py @@ -1,15 +1,15 @@ -def median_of_medians(lst): - # Split our list into sublists len 5. (The last list may have < 5 elements) - sublists = [lst[j:j+5] for j in range(0, len(lst), 5)] - print(f'sublists: {sublists}') - # create list medians to store medians in all sublists - medians = [] - for sublist in sublists: - # append the median of each sublist to our medians list - medians.append(sorted(sublist)[len(sublist)//2]) - # if we have <= 5 medians we get the middle element in our medians list. - if len(medians) <= 5: - return sorted(medians)[len(medians)//2] - # if we have more than 5 medians, we recurse on our medians list - else: +def median_of_medians(lst): + # Split our list into sublists len 5. (The last list may have < 5 elements) + sublists = [lst[j:j+5] for j in range(0, len(lst), 5)] + print(f'sublists: {sublists}') + # create list medians to store medians in all sublists + medians = [] + for sublist in sublists: + # append the median of each sublist to our medians list + medians.append(sorted(sublist)[len(sublist)//2]) + # if we have <= 5 medians we get the middle element in our medians list. + if len(medians) <= 5: + return sorted(medians)[len(medians)//2] + # if we have more than 5 medians, we recurse on our medians list + else: return median_of_medians(medians) \ No newline at end of file diff --git a/algorithms/sorting/median_of_medians/solution/test_solution.py b/algorithms/sorting/median_of_medians/solution/test_solution.py index 0f30c820..7dc85d5b 100644 --- a/algorithms/sorting/median_of_medians/solution/test_solution.py +++ b/algorithms/sorting/median_of_medians/solution/test_solution.py @@ -1,8 +1,8 @@ -def test_solution(): - import solution - - assert solution.median_of_medians([9, 1, 0, 2, 3, 4, 6, 8, 7, 10, 5]) == 5 - assert solution.median_of_medians([1]) == 1 - assert solution.median_of_medians([1, 2, 3]) == 2 - assert solution.median_of_medians([1, 2, 2, 3]) == 2 - +def test_solution(): + import solution + + assert solution.median_of_medians([9, 1, 0, 2, 3, 4, 6, 8, 7, 10, 5]) == 5 + assert solution.median_of_medians([1]) == 1 + assert solution.median_of_medians([1, 2, 3]) == 2 + assert solution.median_of_medians([1, 2, 2, 3]) == 2 + diff --git a/algorithms/sorting/merge_sorted/README.md b/algorithms/sorting/merge_sorted/README.md index 5f5a259b..8154e95c 100644 --- a/algorithms/sorting/merge_sorted/README.md +++ b/algorithms/sorting/merge_sorted/README.md @@ -1,22 +1,22 @@ -# Merge Sort - Merge two Sorted List - -## Motivation -Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. -Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. - -## Problem Description -In the *solution.py* file, define a function `merge_sorted` that consumes two sorted lists of integers in increasing order, `lst1` and `lst2`, and returns a new list containing all the elements from `lst1` and `lst2` in increasing sorted order. - -## Example -``` -lst1 = [-1, 1, 4, 6] -lst2 = [0, 1, 2, 5, 7] -merge_sorted(lst1, lst2) == [-1, 0, 1, 1, 2, 4, 5, 6, 7] -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Merge Sort - Merge two Sorted List + +## Motivation +Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. +Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. + +## Problem Description +In the *solution.py* file, define a function `merge_sorted` that consumes two sorted lists of integers in increasing order, `lst1` and `lst2`, and returns a new list containing all the elements from `lst1` and `lst2` in increasing sorted order. + +## Example +``` +lst1 = [-1, 1, 4, 6] +lst2 = [0, 1, 2, 5, 7] +merge_sorted(lst1, lst2) == [-1, 0, 1, 1, 2, 4, 5, 6, 7] +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/sorting/merge_sorted/solution/solution.py b/algorithms/sorting/merge_sorted/solution/solution.py index aac5cf7c..59ea276d 100644 --- a/algorithms/sorting/merge_sorted/solution/solution.py +++ b/algorithms/sorting/merge_sorted/solution/solution.py @@ -1,25 +1,25 @@ -def merge_sorted(lst1, lst2): - def merge_helper(lst1, lst2, merged_lst): - # if list1 has no elements we add lst2 to the - # end of our merged_lst - if len(lst1) == 0: - merged_lst.extend(lst2) - return merged_lst - # if list2 has no elements we add lst1 to the - # end of our merged_lst - elif len(lst2) == 0: - merged_lst.extend(lst1) - return merged_lst - # if first element of lst1 <= first element of lst2 - elif lst1[0] <= lst2[0]: - # we add that element to our merged list - merged_lst.append(lst1[0]) - # and we recurse on the rest of lst1, keeping lst2 unchanged - return merge_helper(lst1[1:], lst2, merged_lst) - else: - # the first element of lst2 < first element of lst1 - # so we add that element to our merged list - merged_lst.append(lst2[0]) - # and we recurse on the rest of lst2, keeping lst1 unchanged - return merge_helper(lst1, lst2[1:], merged_lst) +def merge_sorted(lst1, lst2): + def merge_helper(lst1, lst2, merged_lst): + # if list1 has no elements we add lst2 to the + # end of our merged_lst + if len(lst1) == 0: + merged_lst.extend(lst2) + return merged_lst + # if list2 has no elements we add lst1 to the + # end of our merged_lst + elif len(lst2) == 0: + merged_lst.extend(lst1) + return merged_lst + # if first element of lst1 <= first element of lst2 + elif lst1[0] <= lst2[0]: + # we add that element to our merged list + merged_lst.append(lst1[0]) + # and we recurse on the rest of lst1, keeping lst2 unchanged + return merge_helper(lst1[1:], lst2, merged_lst) + else: + # the first element of lst2 < first element of lst1 + # so we add that element to our merged list + merged_lst.append(lst2[0]) + # and we recurse on the rest of lst2, keeping lst1 unchanged + return merge_helper(lst1, lst2[1:], merged_lst) return merge_helper(lst1, lst2, []) \ No newline at end of file diff --git a/algorithms/sorting/merge_sorted/solution/test_solution.py b/algorithms/sorting/merge_sorted/solution/test_solution.py index 285b1b7a..81454cc1 100644 --- a/algorithms/sorting/merge_sorted/solution/test_solution.py +++ b/algorithms/sorting/merge_sorted/solution/test_solution.py @@ -1,10 +1,10 @@ -def test_solution(): - import solution - - assert solution.merge_sorted([],[]) == [] - assert solution.merge_sorted([1],[]) == [1] - assert solution.merge_sorted([],[1]) == [1] - assert solution.merge_sorted([2],[1]) == [1, 2] - assert solution.merge_sorted([1, 2],[3]) == [1, 2, 3] - assert solution.merge_sorted([1, 2, 4, 6], [3, 4, 5, 7, 8]) == [1, 2, 3, 4, 4, 5, 6, 7, 8] - +def test_solution(): + import solution + + assert solution.merge_sorted([],[]) == [] + assert solution.merge_sorted([1],[]) == [1] + assert solution.merge_sorted([],[1]) == [1] + assert solution.merge_sorted([2],[1]) == [1, 2] + assert solution.merge_sorted([1, 2],[3]) == [1, 2, 3] + assert solution.merge_sorted([1, 2, 4, 6], [3, 4, 5, 7, 8]) == [1, 2, 3, 4, 4, 5, 6, 7, 8] + diff --git a/algorithms/sorting/min_or_max_heap/README.md b/algorithms/sorting/min_or_max_heap/README.md index 9065051c..5f296511 100644 --- a/algorithms/sorting/min_or_max_heap/README.md +++ b/algorithms/sorting/min_or_max_heap/README.md @@ -1,27 +1,27 @@ -# Heap Sort - Min or Max Heap - -## Motivation -Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. -Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. - -## Problem Description -In the *solution.py* file, define a function `min_or_max_heap` that consumes a heap of integers `heap`, and returns the string `"min"` if `heap` is a min heap, `max` if `heap` is a max heap and `"neither"` if the heap is neither a min nor a max heap. If `heap` satisfies the properties of both min and max heap, you may return either `"min"` or `"max"`. Recall a min heap is a tree structure such that each node is smaller than its child nodes and a max heap is a tree structue such that each node is larger than its child nodes. In python we will represent the heap `heap` as an array where the root of the tree is at index `0`, and for the `ith` node, `heap[(i-1)/2]` will be the parent of `heap[i]`, `heap[(2*i)+1]` will be the left child of `heap[i]`, and `heap[(2*i)+2]` will be the right child of `heap[i]`. - -## Example -``` -heap = [1, 3, 6, 7, 9, 8] -min_or_max_heap(heap) == "min" - -heap = [10, 5, 9, 4, 2, 8] -min_or_max_heap(heap) => "max" - -heap = [10, 5, 8, 4, 2, 9] -min_or_max_heap(heap) => "neither" -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Heap Sort - Min or Max Heap + +## Motivation +Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. +Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. + +## Problem Description +In the *solution.py* file, define a function `min_or_max_heap` that consumes a heap of integers `heap`, and returns the string `"min"` if `heap` is a min heap, `max` if `heap` is a max heap and `"neither"` if the heap is neither a min nor a max heap. If `heap` satisfies the properties of both min and max heap, you may return either `"min"` or `"max"`. Recall a min heap is a tree structure such that each node is smaller than its child nodes and a max heap is a tree structue such that each node is larger than its child nodes. In python we will represent the heap `heap` as an array where the root of the tree is at index `0`, and for the `ith` node, `heap[(i-1)/2]` will be the parent of `heap[i]`, `heap[(2*i)+1]` will be the left child of `heap[i]`, and `heap[(2*i)+2]` will be the right child of `heap[i]`. + +## Example +``` +heap = [1, 3, 6, 7, 9, 8] +min_or_max_heap(heap) == "min" + +heap = [10, 5, 9, 4, 2, 8] +min_or_max_heap(heap) => "max" + +heap = [10, 5, 8, 4, 2, 9] +min_or_max_heap(heap) => "neither" +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/sorting/min_or_max_heap/solution/solution.py b/algorithms/sorting/min_or_max_heap/solution/solution.py index 57a21297..d3a3e5bd 100644 --- a/algorithms/sorting/min_or_max_heap/solution/solution.py +++ b/algorithms/sorting/min_or_max_heap/solution/solution.py @@ -1,102 +1,102 @@ -def is_max_heap(heap): - # if no elemts in the heap, it is by definition a max_heap - # so we return true. - if len(heap) == 0: - return True - # we itterate through the heap - for i in range(len(heap)): - # get value of the root element - root = heap[i] - # get the left and right child indices in the heap - leftidx = (2*i) + 1 - rightidx = (2*i) + 2 - # initialise left and right child variables to None - left_child = None - right_child = None - # if leftidx is valid index in the heap we set the leftchild value - if leftidx < len(heap): - left_child = heap[leftidx] - # if leftidx is valid index in the heap we set the leftchild value - if rightidx < len(heap): - right_child = heap[rightidx] - # if both children are None, heap is a max_heap - if left_child == None and right_child == None: - return True - # if we have no left child we only need to check the right side of - # the tree. - if left_child == None: - # if right child is less than root we recurse on the right side of the heap - if right_child < root: - return is_max_heap(heap[rightidx:]) - # if right child is greater than root it is not max_heap - elif right_child > root: - return False - # if we have no right child we only need to check the left side of - # the tree. - if right_child == None: - # if left child is less than root we recurse on the left side of the heap - if left_child < root: - return is_max_heap(heap[leftidx:]) - # if left child is greater than root it is not max_heap - elif left_child > root: - return False - # if either left or right is greater than the root it is not max_heap - if left_child > root or right_child > root: - return False - return True - -def is_min_heap(heap): - # if no elemts in the heap, it is by definition a min_heap - # so we return true. - if len(heap) == 0: - return True - # we itterate through the heap - for i in range(len(heap)): - # get value of the root element - root = heap[i] - # get the left and right child indices in the heap - leftidx = (2*i) + 1 - rightidx = (2*i) + 2 - # initialise left and right child variables to None - left_child = None - right_child = None - # if leftidx is valid index in the heap we set the leftchild value - if leftidx < len(heap): - left_child = heap[leftidx] - # if leftidx is valid index in the heap we set the leftchild value - if rightidx < len(heap): - right_child = heap[rightidx] - # if both children are None, heap is a min_heap - if left_child == None and right_child == None: - return True - # if we have no left child we only need to check the right side of - # the tree. - if left_child == None: - # if right child is greater than root we recurse on the right side of the heap - if right_child > root: - return is_min_heap(heap[rightidx:]) - # if right child is less than root it is not min_heap - elif right_child < root: - return False - # if we have no right child we only need to check the left side of - # the tree. - if right_child == None: - # if left child is greater than root we recurse on the left side of the heap - if left_child > root: - return is_min_heap(heap[leftidx:]) - # if left child is less than root it is not min_heap - elif left_child < root: - return False - # if either left or right is less than the root it is not min_heap - if left_child < root or right_child < root: - return False - return True - - -def min_or_max_heap(heap): - if is_min_heap(heap): - return "min" - elif is_max_heap(heap): - return "max" - else: +def is_max_heap(heap): + # if no elemts in the heap, it is by definition a max_heap + # so we return true. + if len(heap) == 0: + return True + # we itterate through the heap + for i in range(len(heap)): + # get value of the root element + root = heap[i] + # get the left and right child indices in the heap + leftidx = (2*i) + 1 + rightidx = (2*i) + 2 + # initialise left and right child variables to None + left_child = None + right_child = None + # if leftidx is valid index in the heap we set the leftchild value + if leftidx < len(heap): + left_child = heap[leftidx] + # if leftidx is valid index in the heap we set the leftchild value + if rightidx < len(heap): + right_child = heap[rightidx] + # if both children are None, heap is a max_heap + if left_child == None and right_child == None: + return True + # if we have no left child we only need to check the right side of + # the tree. + if left_child == None: + # if right child is less than root we recurse on the right side of the heap + if right_child < root: + return is_max_heap(heap[rightidx:]) + # if right child is greater than root it is not max_heap + elif right_child > root: + return False + # if we have no right child we only need to check the left side of + # the tree. + if right_child == None: + # if left child is less than root we recurse on the left side of the heap + if left_child < root: + return is_max_heap(heap[leftidx:]) + # if left child is greater than root it is not max_heap + elif left_child > root: + return False + # if either left or right is greater than the root it is not max_heap + if left_child > root or right_child > root: + return False + return True + +def is_min_heap(heap): + # if no elemts in the heap, it is by definition a min_heap + # so we return true. + if len(heap) == 0: + return True + # we itterate through the heap + for i in range(len(heap)): + # get value of the root element + root = heap[i] + # get the left and right child indices in the heap + leftidx = (2*i) + 1 + rightidx = (2*i) + 2 + # initialise left and right child variables to None + left_child = None + right_child = None + # if leftidx is valid index in the heap we set the leftchild value + if leftidx < len(heap): + left_child = heap[leftidx] + # if leftidx is valid index in the heap we set the leftchild value + if rightidx < len(heap): + right_child = heap[rightidx] + # if both children are None, heap is a min_heap + if left_child == None and right_child == None: + return True + # if we have no left child we only need to check the right side of + # the tree. + if left_child == None: + # if right child is greater than root we recurse on the right side of the heap + if right_child > root: + return is_min_heap(heap[rightidx:]) + # if right child is less than root it is not min_heap + elif right_child < root: + return False + # if we have no right child we only need to check the left side of + # the tree. + if right_child == None: + # if left child is greater than root we recurse on the left side of the heap + if left_child > root: + return is_min_heap(heap[leftidx:]) + # if left child is less than root it is not min_heap + elif left_child < root: + return False + # if either left or right is less than the root it is not min_heap + if left_child < root or right_child < root: + return False + return True + + +def min_or_max_heap(heap): + if is_min_heap(heap): + return "min" + elif is_max_heap(heap): + return "max" + else: return "neither" \ No newline at end of file diff --git a/algorithms/sorting/min_or_max_heap/solution/test_solution.py b/algorithms/sorting/min_or_max_heap/solution/test_solution.py index a7a2f103..67dac155 100644 --- a/algorithms/sorting/min_or_max_heap/solution/test_solution.py +++ b/algorithms/sorting/min_or_max_heap/solution/test_solution.py @@ -1,9 +1,9 @@ -def test_solution(): - import solution - - assert ((solution.min_or_max_heap([]) == "min") or (solution.min_or_max_heap([]) == "max")) - assert solution.min_or_max_heap([1, 3, 5, 7, 4, 8]) == "min" - assert solution.min_or_max_heap([10, 5, 9, 4, 2, 8]) == "max" - assert solution.min_or_max_heap([10, 5, 8, 4, 2, 9]) == "neither" - assert ((solution.min_or_max_heap([5]) == "min") or (solution.min_or_max_heap([5]) == "max")) - +def test_solution(): + import solution + + assert ((solution.min_or_max_heap([]) == "min") or (solution.min_or_max_heap([]) == "max")) + assert solution.min_or_max_heap([1, 3, 5, 7, 4, 8]) == "min" + assert solution.min_or_max_heap([10, 5, 9, 4, 2, 8]) == "max" + assert solution.min_or_max_heap([10, 5, 8, 4, 2, 9]) == "neither" + assert ((solution.min_or_max_heap([5]) == "min") or (solution.min_or_max_heap([5]) == "max")) + diff --git a/algorithms/sorting/quick_sort/README.md b/algorithms/sorting/quick_sort/README.md index 008009ff..01b58250 100644 --- a/algorithms/sorting/quick_sort/README.md +++ b/algorithms/sorting/quick_sort/README.md @@ -1,21 +1,21 @@ -# Quick Sort - Quick Sort using Median of Medians - -## Motivation -Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. -Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. - -## Problem Description -In the *solution.py* file, define a function `quick_sort` that consumes a lists of integers `lst` and sorts the list. Use the median of medians algorithm for optimal pivot selection. - -## Example -``` -lst = [9, 1, 0, 2, 3, 4, 6, 8, 7, 10, 5] -quick_sort(lst) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Quick Sort - Quick Sort using Median of Medians + +## Motivation +Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. +Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. + +## Problem Description +In the *solution.py* file, define a function `quick_sort` that consumes a lists of integers `lst` and sorts the list. Use the median of medians algorithm for optimal pivot selection. + +## Example +``` +lst = [9, 1, 0, 2, 3, 4, 6, 8, 7, 10, 5] +quick_sort(lst) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/sorting/quick_sort/solution/solution.py b/algorithms/sorting/quick_sort/solution/solution.py index 7eae55b3..88c04941 100644 --- a/algorithms/sorting/quick_sort/solution/solution.py +++ b/algorithms/sorting/quick_sort/solution/solution.py @@ -1,47 +1,47 @@ -def median_of_medians(lst): - # Split our list into sublists len 5. (The last list may have < 5 elements) - sublists = [lst[j:j+5] for j in range(0, len(lst), 5)] - # create list medians to store medians in all sublists - medians = [] - for sublist in sublists: - # append the median of each sublist to our medians list - medians.append(sorted(sublist)[len(sublist)//2]) - # if we have <= 5 medians we get the middle element in our medians list. - if len(medians) <= 5: - return sorted(medians)[len(medians)//2] - # if we have more than 5 medians, we recurse on our medians list - else: - return median_of_medians(medians) - -def _partition(lst, min_index, max_index): - # get pivot index using the median of medians algorithm. - pivot_index = lst.index(median_of_medians(lst[min_index:max_index+1])) - # swap the position of the first element in lst and the pivot element - lst[min_index], lst[pivot_index] = lst[pivot_index], lst[min_index] - # swap the indices, pivot index is now at the front of the list. - pivot_index = min_index - # itterate through min_index to max_index+1 - for index in range(min_index, max_index + 1): - # if elem at index is less than pivot - if lst[index] < lst[pivot_index]: - # swap the position elem and pivot. - lst[pivot_index], lst[index] = lst[index], lst[pivot_index] - # move pivot to next position in the list swapping next element with pivot element. - lst[pivot_index + 1], lst[index] = lst[index], lst[pivot_index + 1] - # update pivot index. - pivot_index += 1 - return pivot_index - -def quick_sort_helper(lst, min_index, max_index): - if min_index < max_index: - # find the pivot index partitioning list of all elems - # less than median pivot and all elems greater than pivot - pivot_index = _partition(lst, min_index, max_index) - # recurse on list of elems smaller than pivot - quick_sort_helper(lst, min_index, pivot_index - 1) - # recurse on list of elems greater than pivot - quick_sort_helper(lst, pivot_index + 1, max_index) - -def quick_sort(lst): - quick_sort_helper(lst, 0, len(lst) - 1) - return lst +def median_of_medians(lst): + # Split our list into sublists len 5. (The last list may have < 5 elements) + sublists = [lst[j:j+5] for j in range(0, len(lst), 5)] + # create list medians to store medians in all sublists + medians = [] + for sublist in sublists: + # append the median of each sublist to our medians list + medians.append(sorted(sublist)[len(sublist)//2]) + # if we have <= 5 medians we get the middle element in our medians list. + if len(medians) <= 5: + return sorted(medians)[len(medians)//2] + # if we have more than 5 medians, we recurse on our medians list + else: + return median_of_medians(medians) + +def _partition(lst, min_index, max_index): + # get pivot index using the median of medians algorithm. + pivot_index = lst.index(median_of_medians(lst[min_index:max_index+1])) + # swap the position of the first element in lst and the pivot element + lst[min_index], lst[pivot_index] = lst[pivot_index], lst[min_index] + # swap the indices, pivot index is now at the front of the list. + pivot_index = min_index + # itterate through min_index to max_index+1 + for index in range(min_index, max_index + 1): + # if elem at index is less than pivot + if lst[index] < lst[pivot_index]: + # swap the position elem and pivot. + lst[pivot_index], lst[index] = lst[index], lst[pivot_index] + # move pivot to next position in the list swapping next element with pivot element. + lst[pivot_index + 1], lst[index] = lst[index], lst[pivot_index + 1] + # update pivot index. + pivot_index += 1 + return pivot_index + +def quick_sort_helper(lst, min_index, max_index): + if min_index < max_index: + # find the pivot index partitioning list of all elems + # less than median pivot and all elems greater than pivot + pivot_index = _partition(lst, min_index, max_index) + # recurse on list of elems smaller than pivot + quick_sort_helper(lst, min_index, pivot_index - 1) + # recurse on list of elems greater than pivot + quick_sort_helper(lst, pivot_index + 1, max_index) + +def quick_sort(lst): + quick_sort_helper(lst, 0, len(lst) - 1) + return lst diff --git a/algorithms/sorting/quick_sort/solution/test_solution.py b/algorithms/sorting/quick_sort/solution/test_solution.py index 68be2554..3e6e3369 100644 --- a/algorithms/sorting/quick_sort/solution/test_solution.py +++ b/algorithms/sorting/quick_sort/solution/test_solution.py @@ -1,9 +1,9 @@ -def test_solution(): - import solution - - assert solution.quick_sort([9, 1, 0, 2, 3, 4, 6, 8, 7, 10, 5]) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - assert solution.quick_sort([]) == [] - assert solution.quick_sort([5]) == [5] - assert solution.quick_sort([1, 2, 1]) == [1, 1, 2] - assert solution.quick_sort([3, 2, 1, 0]) == [0, 1, 2, 3] - +def test_solution(): + import solution + + assert solution.quick_sort([9, 1, 0, 2, 3, 4, 6, 8, 7, 10, 5]) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + assert solution.quick_sort([]) == [] + assert solution.quick_sort([5]) == [5] + assert solution.quick_sort([1, 2, 1]) == [1, 1, 2] + assert solution.quick_sort([3, 2, 1, 0]) == [0, 1, 2, 3] + diff --git a/algorithms/sorting/sort_linked_list/README.md b/algorithms/sorting/sort_linked_list/README.md index eee82452..82133e71 100644 --- a/algorithms/sorting/sort_linked_list/README.md +++ b/algorithms/sorting/sort_linked_list/README.md @@ -1,45 +1,45 @@ -# Linked Lists - Sort a Linked List - -## Motivation -Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. -Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. - -## Problem Description -In the *solution.py* file, define a method `sort_ll` inside the LinkedList class that sorts a linked list using your prefered sorting method. -``` -class LinkedList: - def __init__(self, head=None): - self.head = head - - def sort_ll(self): - return - -class ListNode: - def __init__(self, value=None, next=None): - self.value = value - self.next = None -``` - -## Example -``` -n1 = ListNode(5) -n2 = ListNode(6, n1) -n3 = ListNode (4, n2) -n4 = ListNode(1, n3) -llst = LinkedList(n4) - -r1 = ListNode(6) -r2 = ListNode(5, r1) -r3 = ListNode(4, r2) -r4 = ListNode(1, r3) -returnlst = LinkedList(r4) - -llst.sort_ll() == returnlst -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Linked Lists - Sort a Linked List + +## Motivation +Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. +Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. + +## Problem Description +In the *solution.py* file, define a method `sort_ll` inside the LinkedList class that sorts a linked list using your prefered sorting method. +``` +class LinkedList: + def __init__(self, head=None): + self.head = head + + def sort_ll(self): + return + +class ListNode: + def __init__(self, value=None, next=None): + self.value = value + self.next = None +``` + +## Example +``` +n1 = ListNode(5) +n2 = ListNode(6, n1) +n3 = ListNode (4, n2) +n4 = ListNode(1, n3) +llst = LinkedList(n4) + +r1 = ListNode(6) +r2 = ListNode(5, r1) +r3 = ListNode(4, r2) +r4 = ListNode(1, r3) +returnlst = LinkedList(r4) + +llst.sort_ll() == returnlst +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/sorting/sort_linked_list/solution/solution.py b/algorithms/sorting/sort_linked_list/solution/solution.py index 70d70620..6412ea3c 100644 --- a/algorithms/sorting/sort_linked_list/solution/solution.py +++ b/algorithms/sorting/sort_linked_list/solution/solution.py @@ -1,44 +1,44 @@ -class ListNode: - def __init__(self, value=None, next=None): - self.value = value - self.next = next - -class LinkedList: - def __init__(self, head=None): - self.head = head - - def sort_ll(self): - # if head is None, list is sorted. - if self.head == None: - return - # set current node to head node - current = self.head - # set index to None - next_node = None - # itterate though the linked list - while(current != None): - # next_node will point to node next to current - next_node = current.next - while(next_node != None): - # If current node's data is greater than index's node data, swap the data between them - if(current.value > next_node.value): - temp = current.value - current.value = next_node.value - next_node.value = temp - next_node = next_node.next - current = current.next - -n1 = ListNode(5) -n2 = ListNode(6, n1) -n3 = ListNode(4, n2) -n4 = ListNode(1, n3) -llst = LinkedList(n4) - -def printlst(lst): - current = lst.head - while(current != None): - print(current.value) - current = current.next - - - +class ListNode: + def __init__(self, value=None, next=None): + self.value = value + self.next = next + +class LinkedList: + def __init__(self, head=None): + self.head = head + + def sort_ll(self): + # if head is None, list is sorted. + if self.head == None: + return + # set current node to head node + current = self.head + # set index to None + next_node = None + # itterate though the linked list + while(current != None): + # next_node will point to node next to current + next_node = current.next + while(next_node != None): + # If current node's data is greater than index's node data, swap the data between them + if(current.value > next_node.value): + temp = current.value + current.value = next_node.value + next_node.value = temp + next_node = next_node.next + current = current.next + +n1 = ListNode(5) +n2 = ListNode(6, n1) +n3 = ListNode(4, n2) +n4 = ListNode(1, n3) +llst = LinkedList(n4) + +def printlst(lst): + current = lst.head + while(current != None): + print(current.value) + current = current.next + + + diff --git a/algorithms/sorting/sort_linked_list/solution/test_solution.py b/algorithms/sorting/sort_linked_list/solution/test_solution.py index fa73611d..b8bf3491 100644 --- a/algorithms/sorting/sort_linked_list/solution/test_solution.py +++ b/algorithms/sorting/sort_linked_list/solution/test_solution.py @@ -1,27 +1,27 @@ -def test_solution(): - import solution - - n1 = solution.ListNode(5) - n2 = solution.ListNode(6, n1) - n3 = solution.ListNode (4, n2) - n4 = solution.ListNode(1, n3) - llst = solution.LinkedList(n4) - - llst2 = solution.LinkedList(n1) - - r1 = solution.ListNode(6) - r2 = solution.ListNode(5, r1) - r3 = solution.ListNode(4, r2) - r4 = solution.ListNode(1, r3) - returnlst = solution.LinkedList(r4) - - llst.sort_ll() - llst2.sort_ll() - - assert (llst.head.value == returnlst.head.value and - llst.head.next.value == returnlst.head.next.value and - llst.head.next.next.value == returnlst.head.next.next.value and - llst.head.next.next.next.value == returnlst.head.next.next.next.value) - - assert (llst2.head.value == llst2.head.value and llst2.head.next == None) - +def test_solution(): + import solution + + n1 = solution.ListNode(5) + n2 = solution.ListNode(6, n1) + n3 = solution.ListNode (4, n2) + n4 = solution.ListNode(1, n3) + llst = solution.LinkedList(n4) + + llst2 = solution.LinkedList(n1) + + r1 = solution.ListNode(6) + r2 = solution.ListNode(5, r1) + r3 = solution.ListNode(4, r2) + r4 = solution.ListNode(1, r3) + returnlst = solution.LinkedList(r4) + + llst.sort_ll() + llst2.sort_ll() + + assert (llst.head.value == returnlst.head.value and + llst.head.next.value == returnlst.head.next.value and + llst.head.next.next.value == returnlst.head.next.next.value and + llst.head.next.next.next.value == returnlst.head.next.next.next.value) + + assert (llst2.head.value == llst2.head.value and llst2.head.next == None) + diff --git a/algorithms/sorting/sort_siblings/README.md b/algorithms/sorting/sort_siblings/README.md index d7e2af34..c8394aa1 100644 --- a/algorithms/sorting/sort_siblings/README.md +++ b/algorithms/sorting/sort_siblings/README.md @@ -1,25 +1,25 @@ -# Sort Siblings - Sorting Siblings by Age - -## Motivation -Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. -Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. - -## Problem Description -In the *solution.py* file, define a function `sort_siblings` that consumes a dictionary of siblings `sib_dict`, where the keys are the names of each sibling given as a string, and the value is the age of the sibling given as an integer. Output a list of sorted tuples `(name, age)` sorted in increasing order by age. If two siblings have the same age, sort them lexicographically. You may assume no two siblings have the same name. - -## Example -``` -sib_dict = {"Anton": 29, - "Cosette": 3, - "Nancy": 15, - "Lucas": 15} - -sort_siblings(sib_dict) == [("Cosette", 3), ("Lucas", 15), ("Nancy", 15), ("Anton", 29))] -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Sort Siblings - Sorting Siblings by Age + +## Motivation +Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. +Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. + +## Problem Description +In the *solution.py* file, define a function `sort_siblings` that consumes a dictionary of siblings `sib_dict`, where the keys are the names of each sibling given as a string, and the value is the age of the sibling given as an integer. Output a list of sorted tuples `(name, age)` sorted in increasing order by age. If two siblings have the same age, sort them lexicographically. You may assume no two siblings have the same name. + +## Example +``` +sib_dict = {"Anton": 29, + "Cosette": 3, + "Nancy": 15, + "Lucas": 15} + +sort_siblings(sib_dict) == [("Cosette", 3), ("Lucas", 15), ("Nancy", 15), ("Anton", 29))] +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/sorting/sort_siblings/solution/solution.py b/algorithms/sorting/sort_siblings/solution/solution.py index 77135cfa..77b7045c 100644 --- a/algorithms/sorting/sort_siblings/solution/solution.py +++ b/algorithms/sorting/sort_siblings/solution/solution.py @@ -1,46 +1,46 @@ -def sib_compare(sib_tup1, sib_tup2): - # if age of sib1 < age of sib2 - if sib_tup1[1] < sib_tup2[1]: - return "less" - # if ages are equal, compare names of sibs - elif sib_tup1[1] == sib_tup2[1] and sib_tup1[0] < sib_tup2[0]: - return "less" - else: - return "greater" - -def merge_sort_tuples(tuple_lst): - if len(tuple_lst) > 1: - mid = len(tuple_lst)//2 # Finding the mid of the array - L = tuple_lst[:mid] # Dividing the array elements - R = tuple_lst[mid:] # into 2 halves - - merge_sort_tuples(L) # Sorting the first half - merge_sort_tuples(R) # Sorting the second half - - i = j = k = 0 - - # Copy data to temp arrays L[] and R[] - while i < len(L) and j < len(R): - if sib_compare(L[i], R[j]) == "less": - tuple_lst[k] = L[i] - i+= 1 - else: - tuple_lst[k] = R[j] - j+= 1 - k+= 1 - - # Checking if any element was left - while i < len(L): - tuple_lst[k] = L[i] - i+= 1 - k+= 1 - - while j < len(R): - tuple_lst[k] = R[j] - j+= 1 - k+= 1 - return tuple_lst - -def sort_siblings(sib_dict): - tuple_lst = [(name, age) for name, age in sib_dict.items()] +def sib_compare(sib_tup1, sib_tup2): + # if age of sib1 < age of sib2 + if sib_tup1[1] < sib_tup2[1]: + return "less" + # if ages are equal, compare names of sibs + elif sib_tup1[1] == sib_tup2[1] and sib_tup1[0] < sib_tup2[0]: + return "less" + else: + return "greater" + +def merge_sort_tuples(tuple_lst): + if len(tuple_lst) > 1: + mid = len(tuple_lst)//2 # Finding the mid of the array + L = tuple_lst[:mid] # Dividing the array elements + R = tuple_lst[mid:] # into 2 halves + + merge_sort_tuples(L) # Sorting the first half + merge_sort_tuples(R) # Sorting the second half + + i = j = k = 0 + + # Copy data to temp arrays L[] and R[] + while i < len(L) and j < len(R): + if sib_compare(L[i], R[j]) == "less": + tuple_lst[k] = L[i] + i+= 1 + else: + tuple_lst[k] = R[j] + j+= 1 + k+= 1 + + # Checking if any element was left + while i < len(L): + tuple_lst[k] = L[i] + i+= 1 + k+= 1 + + while j < len(R): + tuple_lst[k] = R[j] + j+= 1 + k+= 1 + return tuple_lst + +def sort_siblings(sib_dict): + tuple_lst = [(name, age) for name, age in sib_dict.items()] return merge_sort_tuples(tuple_lst) \ No newline at end of file diff --git a/algorithms/sorting/sort_siblings/solution/test_solution.py b/algorithms/sorting/sort_siblings/solution/test_solution.py index cea4a3b5..7ed9968b 100644 --- a/algorithms/sorting/sort_siblings/solution/test_solution.py +++ b/algorithms/sorting/sort_siblings/solution/test_solution.py @@ -1,19 +1,19 @@ -def test_solution(): - import solution - - sib_dict1 = {"Anton": 10, - "Cosette": 3, - "Nancy": 15, - "Lucas": 15} - ret1 = [("Cosette", 3), ("Anton", 10), ("Lucas", 15), ("Nancy", 15)] - - sib_dict2 = {"Sara": 15, - "Reena": 15, - "Alex": 15, - "Justin": 15} - ret2 = [("Alex", 15), ("Justin", 15), ("Reena", 15), ("Sara", 15)] - - assert solution.sort_siblings(sib_dict1) == ret1 - assert solution.sort_siblings({}) == [] - assert solution.sort_siblings({"Anton": 10}) == [("Anton", 10)] - assert solution.sort_siblings(sib_dict2) == ret2 +def test_solution(): + import solution + + sib_dict1 = {"Anton": 10, + "Cosette": 3, + "Nancy": 15, + "Lucas": 15} + ret1 = [("Cosette", 3), ("Anton", 10), ("Lucas", 15), ("Nancy", 15)] + + sib_dict2 = {"Sara": 15, + "Reena": 15, + "Alex": 15, + "Justin": 15} + ret2 = [("Alex", 15), ("Justin", 15), ("Reena", 15), ("Sara", 15)] + + assert solution.sort_siblings(sib_dict1) == ret1 + assert solution.sort_siblings({}) == [] + assert solution.sort_siblings({"Anton": 10}) == [("Anton", 10)] + assert solution.sort_siblings(sib_dict2) == ret2 diff --git a/algorithms/sorting/sort_students/README.md b/algorithms/sorting/sort_students/README.md index 1b65456a..53df8404 100644 --- a/algorithms/sorting/sort_students/README.md +++ b/algorithms/sorting/sort_students/README.md @@ -1,34 +1,34 @@ -# Linked Lists - Sort a Linked List - -## Motivation -Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. -Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. - -## Problem Description -You are given a class Student, where Students have a name (a string), average (an integer value between 0-100), and grade (an integer value between 1-12). In the *solution.py* file, define a function `sort_students` that consumes a list of Students `slst` and returns a sorted list of Students in increasing order, where the students are sorted first by grade, then by average, then by name. You may use the magic method `__lt__`, and you may use any sorting algorithm from class or Python's built in sorting method. -``` -class Student: - def __init__(self, name=None, avg=None, grade=None): - self.name = name - self.avg = avg - self.grade = grade -``` - -## Example -``` -student1 = Student("Bob", 75, 10) -student2 = Student("Annie", 90, 8) -student3 = Student("Carrie", 82, 8) -student4 = Student("Harry", 75, 10) - -slst = [student1, student2, student3, student4] - -sort_students(slst) == [student3, student2, student1, student4] -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Linked Lists - Sort a Linked List + +## Motivation +Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. +Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. + +## Problem Description +You are given a class Student, where Students have a name (a string), average (an integer value between 0-100), and grade (an integer value between 1-12). In the *solution.py* file, define a function `sort_students` that consumes a list of Students `slst` and returns a sorted list of Students in increasing order, where the students are sorted first by grade, then by average, then by name. You may use the magic method `__lt__`, and you may use any sorting algorithm from class or Python's built in sorting method. +``` +class Student: + def __init__(self, name=None, avg=None, grade=None): + self.name = name + self.avg = avg + self.grade = grade +``` + +## Example +``` +student1 = Student("Bob", 75, 10) +student2 = Student("Annie", 90, 8) +student3 = Student("Carrie", 82, 8) +student4 = Student("Harry", 75, 10) + +slst = [student1, student2, student3, student4] + +sort_students(slst) == [student3, student2, student1, student4] +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/sorting/sort_students/solution/solution.py b/algorithms/sorting/sort_students/solution/solution.py index 4350e38a..b8e9823f 100644 --- a/algorithms/sorting/sort_students/solution/solution.py +++ b/algorithms/sorting/sort_students/solution/solution.py @@ -1,29 +1,29 @@ -class Student: - def __init__(self, name=None, avg=None, grade=None): - self.name = name - self.avg = avg - self.grade = grade - - def __lt__(self, other): - if self.grade < other.grade: - return True - if self.grade == other.grade: - if self.avg < other.avg: - return True - if self.avg == other.avg: - return self.name < other.name - return False - - def __repr__(self): - return f'name: {self.name} avg: {self.avg} grade: {self.grade}' - -def sort_students(slst): - return sorted(slst) - -student1 = Student("Bob", 75, 10) -student2 = Student("Annie", 90, 8) -student3 = Student("Carrie", 82, 8) -student4 = Student("Harry", 75, 10) - -slst = [student1, student2, student3, student4] +class Student: + def __init__(self, name=None, avg=None, grade=None): + self.name = name + self.avg = avg + self.grade = grade + + def __lt__(self, other): + if self.grade < other.grade: + return True + if self.grade == other.grade: + if self.avg < other.avg: + return True + if self.avg == other.avg: + return self.name < other.name + return False + + def __repr__(self): + return f'name: {self.name} avg: {self.avg} grade: {self.grade}' + +def sort_students(slst): + return sorted(slst) + +student1 = Student("Bob", 75, 10) +student2 = Student("Annie", 90, 8) +student3 = Student("Carrie", 82, 8) +student4 = Student("Harry", 75, 10) + +slst = [student1, student2, student3, student4] print(sort_students(slst)) \ No newline at end of file diff --git a/algorithms/sorting/sort_students/solution/test_solution.py b/algorithms/sorting/sort_students/solution/test_solution.py index 19225e9b..46dff027 100644 --- a/algorithms/sorting/sort_students/solution/test_solution.py +++ b/algorithms/sorting/sort_students/solution/test_solution.py @@ -1,14 +1,14 @@ -def test_solution(): - import solution - - student1 = solution.Student("Bob", 75, 10) - student2 = solution.Student("Annie", 90, 8) - student3 = solution.Student("Carrie", 82, 8) - student4 = solution.Student("Harry", 75, 10) - - slst = [student1, student2, student3, student4] - assert solution.sort_students(slst) == [student3, student2, student1, student4] - assert solution.sort_students([]) == [] - assert solution.sort_students([student1]) == [student1] - assert solution.sort_students([student2, student3]) == [student3, student2] - assert solution.sort_students([student4, student1]) == [student1, student4] +def test_solution(): + import solution + + student1 = solution.Student("Bob", 75, 10) + student2 = solution.Student("Annie", 90, 8) + student3 = solution.Student("Carrie", 82, 8) + student4 = solution.Student("Harry", 75, 10) + + slst = [student1, student2, student3, student4] + assert solution.sort_students(slst) == [student3, student2, student1, student4] + assert solution.sort_students([]) == [] + assert solution.sort_students([student1]) == [student1] + assert solution.sort_students([student2, student3]) == [student3, student2] + assert solution.sort_students([student4, student1]) == [student1, student4] diff --git a/algorithms/sorting/sort_vectors/README.md b/algorithms/sorting/sort_vectors/README.md index 7f74f5f3..43b044f5 100644 --- a/algorithms/sorting/sort_vectors/README.md +++ b/algorithms/sorting/sort_vectors/README.md @@ -1,21 +1,21 @@ -# Sort Vectors - Sort Vectors by Magnitude - -## Motivation -Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. -Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. - -## Problem Description -In the *solution.py* file, define a function `sort_vectors` that consumes a lists of vecotrs `vector_lst`, which is a list of tuples of tuples `((x1, y1), (x2, y2))` coordinates, and sorts the list of vectors in increasing order by magnitude. Hint: The magnitude of a vector can be calculated using the formula `magnitude = sqrt((x2 - x1)**2 + (y2 - y1)**2)`. - -## Example -``` -vector_lst = [((1, 3), (2, 6)), ((1, 5), (3, 4)), ((2, 6), (2, 9))] -sort_vectors(vector_lst) == [((1, 5), (3, 4)), ((2, 6), (2, 9)), ((1, 3), (2, 6))] -``` -The magnitude of the first vector in `vector_lst` is sqrt(10), the magnitude of the second vector is sqrt(5), and the magnitude of the third vector is sqrt(9). Thus we sort the list accordingly. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Sort Vectors - Sort Vectors by Magnitude + +## Motivation +Sorting is one of the most studied type of algorithms in computer science. There are many different sorting algorithms which may have different benifits and drawbacks given the problem you are trying to solve and your data. You must consider your time contraints and space constraints when choosing the appropriate sorting algorithm for your problem. +Sorting is important because it allows us to optimize data searching to a very high level, when data is stored in a sorted manner. Sorting also allows us to represent data in more readable formats. + +## Problem Description +In the *solution.py* file, define a function `sort_vectors` that consumes a lists of vecotrs `vector_lst`, which is a list of tuples of tuples `((x1, y1), (x2, y2))` coordinates, and sorts the list of vectors in increasing order by magnitude. Hint: The magnitude of a vector can be calculated using the formula `magnitude = sqrt((x2 - x1)**2 + (y2 - y1)**2)`. + +## Example +``` +vector_lst = [((1, 3), (2, 6)), ((1, 5), (3, 4)), ((2, 6), (2, 9))] +sort_vectors(vector_lst) == [((1, 5), (3, 4)), ((2, 6), (2, 9)), ((1, 3), (2, 6))] +``` +The magnitude of the first vector in `vector_lst` is sqrt(10), the magnitude of the second vector is sqrt(5), and the magnitude of the third vector is sqrt(9). Thus we sort the list accordingly. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/algorithms/sorting/sort_vectors/solution/solution.py b/algorithms/sorting/sort_vectors/solution/solution.py index 64ca7ba0..2cdf2229 100644 --- a/algorithms/sorting/sort_vectors/solution/solution.py +++ b/algorithms/sorting/sort_vectors/solution/solution.py @@ -1,10 +1,10 @@ -import math - -def magnitude(vector): - # calculate magnitude of a vector - return math.sqrt((vector[0][0] - vector[1][0])**2 + (vector[0][1] - vector[1][1])**2) - -def sort_vectors(vector_lst): - return sorted(vector_lst, key=lambda vector: magnitude(vector)) - +import math + +def magnitude(vector): + # calculate magnitude of a vector + return math.sqrt((vector[0][0] - vector[1][0])**2 + (vector[0][1] - vector[1][1])**2) + +def sort_vectors(vector_lst): + return sorted(vector_lst, key=lambda vector: magnitude(vector)) + vects = [((1, 3), (2, 6)), ((1, 5), (3, 4)), ((2, 6), (2, 9))] \ No newline at end of file diff --git a/algorithms/sorting/sort_vectors/solution/test_solution.py b/algorithms/sorting/sort_vectors/solution/test_solution.py index 88123a6d..36b37c57 100644 --- a/algorithms/sorting/sort_vectors/solution/test_solution.py +++ b/algorithms/sorting/sort_vectors/solution/test_solution.py @@ -1,17 +1,17 @@ - - -def test_solution(): - import solution - - vects1 = [((1, 3), (2, 6)), ((1, 5), (3, 4)), ((2, 6), (2, 9))] - ret1 = [((1, 5), (3, 4)), ((2, 6), (2, 9)), ((1, 3), (2, 6))] - - vects2 = [((2, 6), (2, 9)), ((1, 3), (2, 6))] #sorted order - - vects3 = [((1, 8), (2, 4))] - - assert solution.sort_vectors(vects1) == ret1 - assert solution.sort_vectors([]) == [] - assert solution.sort_vectors(vects2) == vects2 - assert solution.sort_vectors(vects3) == vects3 - + + +def test_solution(): + import solution + + vects1 = [((1, 3), (2, 6)), ((1, 5), (3, 4)), ((2, 6), (2, 9))] + ret1 = [((1, 5), (3, 4)), ((2, 6), (2, 9)), ((1, 3), (2, 6))] + + vects2 = [((2, 6), (2, 9)), ((1, 3), (2, 6))] #sorted order + + vects3 = [((1, 8), (2, 4))] + + assert solution.sort_vectors(vects1) == ret1 + assert solution.sort_vectors([]) == [] + assert solution.sort_vectors(vects2) == vects2 + assert solution.sort_vectors(vects3) == vects3 + diff --git a/data_structures/README.md b/data_structures/README.md index b30bd737..10ae040b 100644 --- a/data_structures/README.md +++ b/data_structures/README.md @@ -1,8 +1,8 @@ -# Exercise Organization - -## Exercise Sections -* Dictionaries and Arrays -* Linked Lists -* Stacks and Queues -* Binary Trees -* Heaps +# Exercise Organization + +## Exercise Sections +* Dictionaries and Arrays +* Linked Lists +* Stacks and Queues +* Binary Trees +* Heaps diff --git a/data_structures/binary_trees/README.md b/data_structures/binary_trees/README.md index 1cf9930c..7dd6f214 100644 --- a/data_structures/binary_trees/README.md +++ b/data_structures/binary_trees/README.md @@ -1,14 +1,14 @@ -# Exercises - Binary Trees - -| Exercise ID | Exercise | -|:-----------:|:--------:| -| easy_e1 | [Binary Tree] | -| easy_e2 | [Closest Value] | -| easy_e3 | [Height of Tree] | -| medium_e1 | [Inorder List] | -| medium_e2 | [Postorder List] | -| medium_e3 | [Preorder List] | -| medium_e4 | [Search Node] | -| hard_e1 | [Insert Node] | -| hard_e2 | [nth Inorder ] | -| hard_e3 | [nth Preorder] | +# Exercises - Binary Trees + +| Exercise ID | Exercise | +|:-----------:|:--------:| +| easy_e1 | [Binary Tree] | +| easy_e2 | [Closest Value] | +| easy_e3 | [Height of Tree] | +| medium_e1 | [Inorder List] | +| medium_e2 | [Postorder List] | +| medium_e3 | [Preorder List] | +| medium_e4 | [Search Node] | +| hard_e1 | [Insert Node] | +| hard_e2 | [nth Inorder ] | +| hard_e3 | [nth Preorder] | diff --git a/data_structures/binary_trees/binary_tree/README.md b/data_structures/binary_trees/binary_tree/README.md index 5dea8043..6ce5f943 100644 --- a/data_structures/binary_trees/binary_tree/README.md +++ b/data_structures/binary_trees/binary_tree/README.md @@ -1,27 +1,27 @@ -# Binary Tree - -## Motivation -A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child. Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data structures. -We can define a binary tree (BT) to contain the following parts: -1. Key (of any type or None) -2. Left (of type None or BT) -3. Right (of Type None or BT) - -# Problem Description -Define a python class `Node` constructor having arguments `key` representing the individual node data and `left` and `right`representing the respective children. The argumets should default to `None` if no values are given for `key`, `left`, and `right`. -Create a tree in object `sample_tree` with 5 as the root node key, 4 as the key of the left child and 7 as the key of the right child. - -# Example -``` -Output: - 5 - / \ - 4 7 - -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Binary Tree + +## Motivation +A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child. Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data structures. +We can define a binary tree (BT) to contain the following parts: +1. Key (of any type or None) +2. Left (of type None or BT) +3. Right (of Type None or BT) + +# Problem Description +Define a python class `Node` constructor having arguments `key` representing the individual node data and `left` and `right`representing the respective children. The argumets should default to `None` if no values are given for `key`, `left`, and `right`. +Create a tree in object `sample_tree` with 5 as the root node key, 4 as the key of the left child and 7 as the key of the right child. + +# Example +``` +Output: + 5 + / \ + 4 7 + +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/data_structures/binary_trees/binary_tree/solution/n_solution.py b/data_structures/binary_trees/binary_tree/solution/n_solution.py new file mode 100644 index 00000000..0a900885 --- /dev/null +++ b/data_structures/binary_trees/binary_tree/solution/n_solution.py @@ -0,0 +1,2 @@ +def inventory_price(idict, quantity, price): + return [quantity] \ No newline at end of file diff --git a/data_structures/binary_trees/binary_tree/solution/solution.py b/data_structures/binary_trees/binary_tree/solution/solution.py index cf283222..caba306a 100644 --- a/data_structures/binary_trees/binary_tree/solution/solution.py +++ b/data_structures/binary_trees/binary_tree/solution/solution.py @@ -1,19 +1,19 @@ -class Node: - def __init__(self, key, left=None, right=None): - self.left = left - self.right = right - self.key = key - - -left_child = Node(6, None, None) -right_child = Node(7, None, None) -sample_tree = Node(5, left_child, right_child) - - -print(f'key is: {sample_tree.key}') -print(f'left child is: {sample_tree.left.key}') -print(f'right child is: {sample_tree.right.key}') - - - - +class Node: + def __init__(self, key, left=None, right=None): + self.left = left + self.right = right + self.key = key + + +left_child = Node(6, None, None) +right_child = Node(7, None, None) +sample_tree = Node(5, left_child, right_child) + + +print(f'key is: {sample_tree.key}') +print(f'left child is: {sample_tree.left.key}') +print(f'right child is: {sample_tree.right.key}') + + + + diff --git a/data_structures/binary_trees/binary_tree/solution/test_public.py b/data_structures/binary_trees/binary_tree/solution/test_public.py index 1d5d8624..4b2eed4f 100644 --- a/data_structures/binary_trees/binary_tree/solution/test_public.py +++ b/data_structures/binary_trees/binary_tree/solution/test_public.py @@ -1,6 +1,6 @@ -def test_solution(): - from solution import sample_tree - - assert sample_tree.key == 5 - assert sample_tree.left.key == 4 - assert sample_tree.right.key == 7 +def test_solution(): + from solution import sample_tree + + assert sample_tree.key == 5 + assert sample_tree.left.key == 4 + assert sample_tree.right.key == 7 diff --git a/data_structures/binary_trees/closest_value/README.md b/data_structures/binary_trees/closest_value/README.md index dd4e85fe..617e3124 100644 --- a/data_structures/binary_trees/closest_value/README.md +++ b/data_structures/binary_trees/closest_value/README.md @@ -1,44 +1,44 @@ -# Perfect Binary Tree - -## Motivation -Tree is a hierarchical data structure. Main uses of trees include maintaining hierarchical data, providing moderate access and insert/delete operations. Binary trees are special cases of tree where every node has at most two children. - -A Binary tree is a Perfect Binary Tree in which all the internal nodes have two children and all leaf nodes are at the same level. - -# Problem Description -Given the following Binary tree definition: - -''' -class Node: - def __init__(self,key,left=None,right=None): - self.left = left - self.right = right - self.key = key -''' -Define a function `closest_value` which consumes two arguments `node` and `target`. The function returns closest value of a given target value in a given non-empty Binary Search Tree (BST) of unique values. If `target` it equidistant from more than one node in the tree, your function should produce the node that comes first in a level order traversal of the tree. - -# Example -``` -Input: - 6 - / \ - 4 10 - / \ / \ - 3 5 8 12 - -root = Node(6) -root.left = Node(4) -root.right = Node(10) -root.left.left = Node(3) -root.left.right = Node(5) -root.right.left = Node(8) -root.right.right = Node(12) - -closest_value(root, 7) == 6 - -``` -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Perfect Binary Tree + +## Motivation +Tree is a hierarchical data structure. Main uses of trees include maintaining hierarchical data, providing moderate access and insert/delete operations. Binary trees are special cases of tree where every node has at most two children. + +A Binary tree is a Perfect Binary Tree in which all the internal nodes have two children and all leaf nodes are at the same level. + +# Problem Description +Given the following Binary tree definition: + +''' +class Node: + def __init__(self,key,left=None,right=None): + self.left = left + self.right = right + self.key = key +''' +Define a function `closest_value` which consumes two arguments `node` and `target`. The function returns closest value of a given target value in a given non-empty Binary Search Tree (BST) of unique values. If `target` it equidistant from more than one node in the tree, your function should produce the node that comes first in a level order traversal of the tree. + +# Example +``` +Input: + 6 + / \ + 4 10 + / \ / \ + 3 5 8 12 + +root = Node(6) +root.left = Node(4) +root.right = Node(10) +root.left.left = Node(3) +root.left.right = Node(5) +root.right.left = Node(8) +root.right.right = Node(12) + +closest_value(root, 7) == 6 + +``` +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/binary_trees/closest_value/solution/solution.py b/data_structures/binary_trees/closest_value/solution/solution.py index 106ea0b6..bde47b6a 100644 --- a/data_structures/binary_trees/closest_value/solution/solution.py +++ b/data_structures/binary_trees/closest_value/solution/solution.py @@ -1,38 +1,38 @@ -class Node: - def __init__(self, key, left=None, right=None): - self.left = left - self.right = right - self.key = key - -def closest_value_node(node, target, prev): - if node: - if node.key == target: - return node.key - child = node.left if target < node.key else node.right - closest_child_val = closest_value_node(child, target, node.key) - if abs(target - node.key) < abs(target - closest_child_val): - node.key - else: - return closest_child_val - return prev - -def closest_value(node, target): - return closest_value_node(node, target, node.key) - -root = Node(6) -root.left = Node(4) -root.right = Node(10) -root.left.left = Node(3) -root.left.right = Node(5) -root.right.left = Node(8) -root.right.right = Node(12) - -print(closest_value(root, 12)) - -def closest_value2(root, target): - a = root.key - kid = root.left if target < a else root.right - if not kid: - return a - b = closest_value(kid, target) +class Node: + def __init__(self, key, left=None, right=None): + self.left = left + self.right = right + self.key = key + +def closest_value_node(node, target, prev): + if node: + if node.key == target: + return node.key + child = node.left if target < node.key else node.right + closest_child_val = closest_value_node(child, target, node.key) + if abs(target - node.key) < abs(target - closest_child_val): + node.key + else: + return closest_child_val + return prev + +def closest_value(node, target): + return closest_value_node(node, target, node.key) + +root = Node(6) +root.left = Node(4) +root.right = Node(10) +root.left.left = Node(3) +root.left.right = Node(5) +root.right.left = Node(8) +root.right.right = Node(12) + +print(closest_value(root, 12)) + +def closest_value2(root, target): + a = root.key + kid = root.left if target < a else root.right + if not kid: + return a + b = closest_value(kid, target) return min((a,b), key=lambda x: abs(target-x)) \ No newline at end of file diff --git a/data_structures/binary_trees/closest_value/solution/test_public.py b/data_structures/binary_trees/closest_value/solution/test_public.py index 7daba70a..542fa986 100644 --- a/data_structures/binary_trees/closest_value/solution/test_public.py +++ b/data_structures/binary_trees/closest_value/solution/test_public.py @@ -1,14 +1,14 @@ -def test_solution(): - from solution import Node, closest_value - - root = Node(8) - root.left = Node(5) - root.right = Node(14) - root.left.left = Node(4) - root.left.right = Node(6) - root.left.right.left = Node(8) - root.left.right.right = Node(7) - root.right.right = Node(24) - root.right.right.left = Node(22) - result = closest_value(root, 9) - assert result == 8 +def test_solution(): + from solution import Node, closest_value + + root = Node(8) + root.left = Node(5) + root.right = Node(14) + root.left.left = Node(4) + root.left.right = Node(6) + root.left.right.left = Node(8) + root.left.right.right = Node(7) + root.right.right = Node(24) + root.right.right.left = Node(22) + result = closest_value(root, 9) + assert result == 8 diff --git a/data_structures/binary_trees/height_of_tree/README.md b/data_structures/binary_trees/height_of_tree/README.md index 2b03237f..e3a0a914 100644 --- a/data_structures/binary_trees/height_of_tree/README.md +++ b/data_structures/binary_trees/height_of_tree/README.md @@ -1,36 +1,36 @@ -# Complete Binary tree - -## Motivation -Binary Tree is a complete Binary Tree if all the levels are completely filled except possibly the last level and the last level has all keys as left as possible - -# Problem Description -Given the following Binary tree definition: - -''' -class Node: - def __init__(self,key,left=None,right=None): - self.left = left - self.right = right - self.key = key -''' - - -Define a function `height` which consumes one argument `node`. The function returns height of a tree.(the number of nodes along the longest path from the root node down to the farthest leaf node) - -# Example -``` -Input: - 6 - / \ - 4 7 - / \ - 3 5 - -output: 3 - -``` -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Complete Binary tree + +## Motivation +Binary Tree is a complete Binary Tree if all the levels are completely filled except possibly the last level and the last level has all keys as left as possible + +# Problem Description +Given the following Binary tree definition: + +''' +class Node: + def __init__(self,key,left=None,right=None): + self.left = left + self.right = right + self.key = key +''' + + +Define a function `height` which consumes one argument `node`. The function returns height of a tree.(the number of nodes along the longest path from the root node down to the farthest leaf node) + +# Example +``` +Input: + 6 + / \ + 4 7 + / \ + 3 5 + +output: 3 + +``` +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/binary_trees/height_of_tree/solution/solution.py b/data_structures/binary_trees/height_of_tree/solution/solution.py index 1efad1ea..7b01589f 100644 --- a/data_structures/binary_trees/height_of_tree/solution/solution.py +++ b/data_structures/binary_trees/height_of_tree/solution/solution.py @@ -1,11 +1,11 @@ -def height(node): - if node is None: - return 0 - else: - lheight = height(node.left) - rheight = height(node.right) - - if lheight > rheight: - return lheight + 1 - else: +def height(node): + if node is None: + return 0 + else: + lheight = height(node.left) + rheight = height(node.right) + + if lheight > rheight: + return lheight + 1 + else: return rheight + 1 \ No newline at end of file diff --git a/data_structures/binary_trees/height_of_tree/solution/test_public.py b/data_structures/binary_trees/height_of_tree/solution/test_public.py index 3d5a1290..5d535965 100644 --- a/data_structures/binary_trees/height_of_tree/solution/test_public.py +++ b/data_structures/binary_trees/height_of_tree/solution/test_public.py @@ -1,11 +1,11 @@ -def test_solution(): - from solution import Node, height - - left_child = Node(6, None, None) - right_child = Node(7, None, None) - items = Node(5, left_child, right_child) - items.left.left = Node(8) - items.left.right = Node(9) - items.right.left = Node(10) - result = height(items) - assert result == 3 +def test_solution(): + from solution import Node, height + + left_child = Node(6, None, None) + right_child = Node(7, None, None) + items = Node(5, left_child, right_child) + items.left.left = Node(8) + items.left.right = Node(9) + items.right.left = Node(10) + result = height(items) + assert result == 3 diff --git a/data_structures/binary_trees/inorder_list/README.md b/data_structures/binary_trees/inorder_list/README.md index 17efd403..1301f9ad 100644 --- a/data_structures/binary_trees/inorder_list/README.md +++ b/data_structures/binary_trees/inorder_list/README.md @@ -1,43 +1,43 @@ -# Inorder List - -## Motivation -Algorithm Inorder(tree) -1. Traverse the left subtree, i.e., call Inorder(left-subtree) -2. Visit the root. -3. Traverse the right subtree, i.e., call Inorder(right-subtree) - -# Problem Description -Given the following Binary tree definition: - -''' -class Node: - def __init__(self,key,left=None,right=None): - self.left = left - self.right = right - self.key = key -''' - -Define a function `Inorder` which consumes one argument `root`. The function returns the inorder traversal of a given binary tree. - -# Example -``` -Input: - 6 - / \ - 4 7 - / \ - 3 5 - -items = Node(6) -items.left = Node(4) -items.right = Node(7) -items.left.left = Node(3) -items.left.right = Node(5) -Inorder(items) == [3, 4, 5, 6, 7] - -``` -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Inorder List + +## Motivation +Algorithm Inorder(tree) +1. Traverse the left subtree, i.e., call Inorder(left-subtree) +2. Visit the root. +3. Traverse the right subtree, i.e., call Inorder(right-subtree) + +# Problem Description +Given the following Binary tree definition: + +''' +class Node: + def __init__(self,key,left=None,right=None): + self.left = left + self.right = right + self.key = key +''' + +Define a function `Inorder` which consumes one argument `root`. The function returns the inorder traversal of a given binary tree. + +# Example +``` +Input: + 6 + / \ + 4 7 + / \ + 3 5 + +items = Node(6) +items.left = Node(4) +items.right = Node(7) +items.left.left = Node(3) +items.left.right = Node(5) +Inorder(items) == [3, 4, 5, 6, 7] + +``` +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/binary_trees/inorder_list/solution/solution.py b/data_structures/binary_trees/inorder_list/solution/solution.py index 1840705e..41a59098 100644 --- a/data_structures/binary_trees/inorder_list/solution/solution.py +++ b/data_structures/binary_trees/inorder_list/solution/solution.py @@ -1,18 +1,18 @@ -class Node: - def __init__(self, key, left=None, right=None): - self.left = left - self.right = right - self.key = key - - -def Inorder(root): - if not root: - return [] - return Inorder(root.left) + [root.key] + Inorder(root.right) - -items = Node(6) -items.left = Node(4) -items.right = Node(7) -items.left.left = Node(3) -items.left.right = Node(5) +class Node: + def __init__(self, key, left=None, right=None): + self.left = left + self.right = right + self.key = key + + +def Inorder(root): + if not root: + return [] + return Inorder(root.left) + [root.key] + Inorder(root.right) + +items = Node(6) +items.left = Node(4) +items.right = Node(7) +items.left.left = Node(3) +items.left.right = Node(5) print(Inorder(items)) \ No newline at end of file diff --git a/data_structures/binary_trees/inorder_list/solution/test_public.py b/data_structures/binary_trees/inorder_list/solution/test_public.py index 37b89211..d74fdf49 100644 --- a/data_structures/binary_trees/inorder_list/solution/test_public.py +++ b/data_structures/binary_trees/inorder_list/solution/test_public.py @@ -1,11 +1,11 @@ -def test_solution(): - from solution import Node, Inorder - - items = Node(5) - items.left = Node(6) - items.right = Node(7) - items.left.left = Node(8) - items.left.right = Node(9) - result_value_1 = Inorder(items) - result = [8, 6, 9, 5, 7] - assert result_value_1 == result +def test_solution(): + from solution import Node, Inorder + + items = Node(5) + items.left = Node(6) + items.right = Node(7) + items.left.left = Node(8) + items.left.right = Node(9) + result_value_1 = Inorder(items) + result = [8, 6, 9, 5, 7] + assert result_value_1 == result diff --git a/data_structures/binary_trees/insert_node/README.md b/data_structures/binary_trees/insert_node/README.md index f32242d0..b150cf84 100644 --- a/data_structures/binary_trees/insert_node/README.md +++ b/data_structures/binary_trees/insert_node/README.md @@ -1,58 +1,58 @@ -# Insert node - -## Motivation -Given a binary tree and a key, insert the key into the binary tree at first position available in level order. - -# Problem Description -Given the following Binary tree definition: - -''' -class Node: - def __init__(self,key,left=None,right=None): - self.left = left - self.right = right - self.key = key -''' - -Define a methode `insert` inside the Node class which consumes two arguments `self` and `key`. The function inserts `key` into the binary tree at first position available in level order. - - -# Example -``` -Input: - 6 - / \ - 11 9 - / / \ - 7 15 8 - -items = Node(6) -items.left = Node(11) -items.right = Node(9) -items.left.left = Node(7) -items.right.left = Node(15) -items.right.right = Node(8) - -items.insert(12) - -output: - 10 - / \ - 11 9 - / \ / \ - 7 12 15 8 - -``` - -items = Node(6) -items.left = Node(11) -items.right = Node(9) -items.left.left = Node(7) -items.right.left = Node(15) -items.right.right = Node(8) - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Insert node + +## Motivation +Given a binary tree and a key, insert the key into the binary tree at first position available in level order. + +# Problem Description +Given the following Binary tree definition: + +''' +class Node: + def __init__(self,key,left=None,right=None): + self.left = left + self.right = right + self.key = key +''' + +Define a methode `insert` inside the Node class which consumes two arguments `self` and `key`. The function inserts `key` into the binary tree at first position available in level order. + + +# Example +``` +Input: + 6 + / \ + 11 9 + / / \ + 7 15 8 + +items = Node(6) +items.left = Node(11) +items.right = Node(9) +items.left.left = Node(7) +items.right.left = Node(15) +items.right.right = Node(8) + +items.insert(12) + +output: + 10 + / \ + 11 9 + / \ / \ + 7 12 15 8 + +``` + +items = Node(6) +items.left = Node(11) +items.right = Node(9) +items.left.left = Node(7) +items.right.left = Node(15) +items.right.right = Node(8) + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/binary_trees/insert_node/solution/solution.py b/data_structures/binary_trees/insert_node/solution/solution.py index fe81862d..eb0fd3f3 100644 --- a/data_structures/binary_trees/insert_node/solution/solution.py +++ b/data_structures/binary_trees/insert_node/solution/solution.py @@ -1,64 +1,64 @@ -#Write your solutions here -class Node: - def __init__(self, key, left=None, right=None): - self.left = left - self.right = right - self.key = key - - def inorder_nodes(self): - if not self: - return [] - leftNodes = self.left.inorder_nodes() if self.left else [] - rightNodes = self.right.inorder_nodes() if self.right else [] - return [self] + leftNodes + rightNodes - - def insert(self, key): - if not self: - return Node(key) - inorder_node_lst = self.inorder_nodes() - new_node = Node(key) - for node in inorder_node_lst: - if not node.left: - node.left = new_node - return - if not node.right: - node.right = new_node - return - - - def PrintTree(self): - if self.left: - self.left.PrintTree() - print(self.key), - if self.right: - self.right.PrintTree() - - - # solution #2 - def insert2(self, data): - # Compare the new value with the parent node - if self.key: - if data < self.key: - if self.left is None: - self.left = Node(data) - else: - self.left.insert(data) - elif data > self.key: - if self.right is None: - self.right = Node(data) - else: - self.right.insert(data) - else: - self.key = data - -items = Node(6) -items.left = Node(11) -items.right = Node(9) -items.left.left = Node(7) -items.right.left = Node(15) -items.right.right = Node(8) - -items.insert2(12) -items.PrintTree() - - +#Write your solutions here +class Node: + def __init__(self, key, left=None, right=None): + self.left = left + self.right = right + self.key = key + + def inorder_nodes(self): + if not self: + return [] + leftNodes = self.left.inorder_nodes() if self.left else [] + rightNodes = self.right.inorder_nodes() if self.right else [] + return [self] + leftNodes + rightNodes + + def insert(self, key): + if not self: + return Node(key) + inorder_node_lst = self.inorder_nodes() + new_node = Node(key) + for node in inorder_node_lst: + if not node.left: + node.left = new_node + return + if not node.right: + node.right = new_node + return + + + def PrintTree(self): + if self.left: + self.left.PrintTree() + print(self.key), + if self.right: + self.right.PrintTree() + + + # solution #2 + def insert2(self, data): + # Compare the new value with the parent node + if self.key: + if data < self.key: + if self.left is None: + self.left = Node(data) + else: + self.left.insert(data) + elif data > self.key: + if self.right is None: + self.right = Node(data) + else: + self.right.insert(data) + else: + self.key = data + +items = Node(6) +items.left = Node(11) +items.right = Node(9) +items.left.left = Node(7) +items.right.left = Node(15) +items.right.right = Node(8) + +items.insert2(12) +items.PrintTree() + + diff --git a/data_structures/binary_trees/insert_node/solution/test_public.py b/data_structures/binary_trees/insert_node/solution/test_public.py index d68c32b5..faba37f3 100644 --- a/data_structures/binary_trees/insert_node/solution/test_public.py +++ b/data_structures/binary_trees/insert_node/solution/test_public.py @@ -1,12 +1,12 @@ -def test_solution(): - from solution import Node - - items = Node(10) - items.left = Node(11) - items.left.left = Node(7) - items.right = Node(9) - items.right.left = Node(15) - items.right.right = Node(8) - val = 12 - items.insert(val) - assert items.left.right.key == 12 +def test_solution(): + from solution import Node + + items = Node(10) + items.left = Node(11) + items.left.left = Node(7) + items.right = Node(9) + items.right.left = Node(15) + items.right.right = Node(8) + val = 12 + items.insert(val) + assert items.left.right.key == 12 diff --git a/data_structures/binary_trees/nth_inorder/README.md b/data_structures/binary_trees/nth_inorder/README.md index 213c54c9..afa049f6 100644 --- a/data_structures/binary_trees/nth_inorder/README.md +++ b/data_structures/binary_trees/nth_inorder/README.md @@ -1,53 +1,53 @@ -# nth Inorder - -## Motivation -Given the binary tree and you have to find out the n-th node of inorder traversal. -Input : n = 3 -``` - 7 - / \ - 2 3 - / \ - 8 5 -``` -Output : 8 -Inorder: 2 7 8 3 5 -3rd node is 8 - -# Problem Description -Given the following Binary tree definition: - -''' -class Node: - def __init__(self,key,left=None,right=None): - self.left = left - self.right = right - self.key = key -''' - -Define a function `NthInorder` which consumes two arguments `root`, a binary tree,and `n`, a non-negative integer. The function returns n-th node of inorder traversal. If there are less than `n` elements in the tree `root` return the string `"no n-th element"` where `n` in the string is the number coresponding to the parameter `n`. - -# Example -``` -Input: - 5 - / \ - 6 7 - / \ - 8 9 - -items = Node(5) -items.left = Node(6) -items.right = Node(7) -items.left.left = Node(8) -items.left.right = Node(9) - -Inorder Traversal = [8,6,9,5,7] - -NthInorder(items,4) == 5 -NthInorder(items,6) == "no 6-th element" - -``` - -## Submission +# nth Inorder + +## Motivation +Given the binary tree and you have to find out the n-th node of inorder traversal. +Input : n = 3 +``` + 7 + / \ + 2 3 + / \ + 8 5 +``` +Output : 8 +Inorder: 2 7 8 3 5 +3rd node is 8 + +# Problem Description +Given the following Binary tree definition: + +''' +class Node: + def __init__(self,key,left=None,right=None): + self.left = left + self.right = right + self.key = key +''' + +Define a function `NthInorder` which consumes two arguments `root`, a binary tree,and `n`, a non-negative integer. The function returns n-th node of inorder traversal. If there are less than `n` elements in the tree `root` return the string `"no n-th element"` where `n` in the string is the number coresponding to the parameter `n`. + +# Example +``` +Input: + 5 + / \ + 6 7 + / \ + 8 9 + +items = Node(5) +items.left = Node(6) +items.right = Node(7) +items.left.left = Node(8) +items.left.right = Node(9) + +Inorder Traversal = [8,6,9,5,7] + +NthInorder(items,4) == 5 +NthInorder(items,6) == "no 6-th element" + +``` + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/binary_trees/nth_inorder/solution/solution.py b/data_structures/binary_trees/nth_inorder/solution/solution.py index 252dab54..ceb4a1d9 100644 --- a/data_structures/binary_trees/nth_inorder/solution/solution.py +++ b/data_structures/binary_trees/nth_inorder/solution/solution.py @@ -1,27 +1,27 @@ -class Node: - def __init__(self, key, left=None, right=None): - self.left = left - self.right = right - self.key = key - - -def Inorder(root): - if not root: - return [] - return Inorder(root.left) + [root.key] + Inorder(root.right) - -def NthInorder(root, n): - inorder_keys = Inorder(root) - if len(inorder_keys) > n: - return inorder_keys[n-1] - else: - return f'no {n}-th element' - - -items = Node(6) -items.left = Node(4) -items.right = Node(7) -items.left.left = Node(3) -items.left.right = Node(5) -print(Inorder(items)) +class Node: + def __init__(self, key, left=None, right=None): + self.left = left + self.right = right + self.key = key + + +def Inorder(root): + if not root: + return [] + return Inorder(root.left) + [root.key] + Inorder(root.right) + +def NthInorder(root, n): + inorder_keys = Inorder(root) + if len(inorder_keys) > n: + return inorder_keys[n-1] + else: + return f'no {n}-th element' + + +items = Node(6) +items.left = Node(4) +items.right = Node(7) +items.left.left = Node(3) +items.left.right = Node(5) +print(Inorder(items)) print(NthInorder(items, 6)) \ No newline at end of file diff --git a/data_structures/binary_trees/nth_inorder/solution/test_public.py b/data_structures/binary_trees/nth_inorder/solution/test_public.py index e5fe4d65..0526c7c2 100644 --- a/data_structures/binary_trees/nth_inorder/solution/test_public.py +++ b/data_structures/binary_trees/nth_inorder/solution/test_public.py @@ -1,14 +1,14 @@ -def test_solution(): - from solution import Node, NthInorder - - items = Node(5) - items.left = Node(6) - items.right = Node(7) - items.left.left = Node(8) - items.left.right = Node(9) - - [8, 6, 9, 5, 7] - - assert NthInorder(items, 4) == 5 - assert NthInorder(items, 1) == 8 +def test_solution(): + from solution import Node, NthInorder + + items = Node(5) + items.left = Node(6) + items.right = Node(7) + items.left.left = Node(8) + items.left.right = Node(9) + + [8, 6, 9, 5, 7] + + assert NthInorder(items, 4) == 5 + assert NthInorder(items, 1) == 8 assert NthInorder(items, 6) == "no 6-th element" \ No newline at end of file diff --git a/data_structures/binary_trees/nth_preorder/README.md b/data_structures/binary_trees/nth_preorder/README.md index 704f9cce..0e6b9ef7 100644 --- a/data_structures/binary_trees/nth_preorder/README.md +++ b/data_structures/binary_trees/nth_preorder/README.md @@ -1,52 +1,52 @@ -# nth Preorder - -## Motivation -Given the binary tree and you have to find out the N-th node from the Preorder traversal -Input: n = 5 - - 25 - / \ - 20 30 - / \ / \ - 18 22 24 32 - -Output: 30 - - -# Problem Description -Given the following Binary tree definition: - -''' -class Node: - def __init__(self,key,left=None,right=None): - self.left = left - self.right = right - self.key = key -''' - -Define a function `NthPreorder` which consumes two arguments `root`, a binary tree,and `n`, a non-negative integer. The function returns n-th node of a preorder traversal. If there are less than `n` elements in the tree `root` return the string `"no n-th element"` where `n` in the string is the number coresponding to the parameter `n`. - -# Example -``` -Input: - 5 - / \ - 6 7 - / \ - 8 9 - - -items = Node(5) -items.left = Node(6) -items.right = Node(7) -items.left.left = Node(8) -items.left.right = Node(9) - -Preorder Traversal = [5,6,8,9,7] - -NthPreorder(items,3) == 8 -NthPreorder(items,6) == "no 6-th element" - ``` - -## Submission +# nth Preorder + +## Motivation +Given the binary tree and you have to find out the N-th node from the Preorder traversal +Input: n = 5 + + 25 + / \ + 20 30 + / \ / \ + 18 22 24 32 + +Output: 30 + + +# Problem Description +Given the following Binary tree definition: + +''' +class Node: + def __init__(self,key,left=None,right=None): + self.left = left + self.right = right + self.key = key +''' + +Define a function `NthPreorder` which consumes two arguments `root`, a binary tree,and `n`, a non-negative integer. The function returns n-th node of a preorder traversal. If there are less than `n` elements in the tree `root` return the string `"no n-th element"` where `n` in the string is the number coresponding to the parameter `n`. + +# Example +``` +Input: + 5 + / \ + 6 7 + / \ + 8 9 + + +items = Node(5) +items.left = Node(6) +items.right = Node(7) +items.left.left = Node(8) +items.left.right = Node(9) + +Preorder Traversal = [5,6,8,9,7] + +NthPreorder(items,3) == 8 +NthPreorder(items,6) == "no 6-th element" + ``` + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/binary_trees/nth_preorder/solution/solution.py b/data_structures/binary_trees/nth_preorder/solution/solution.py index f6c18fbd..76fbe2e1 100644 --- a/data_structures/binary_trees/nth_preorder/solution/solution.py +++ b/data_structures/binary_trees/nth_preorder/solution/solution.py @@ -1,26 +1,26 @@ -class Node: - def __init__(self, key, left=None, right=None): - self.left = left - self.right = right - self.key = key - -def Preorder(root): - if not root: - return [] - return [root.key] + Preorder(root.left) + Preorder(root.right) - -def NthPreorder(root, n): - preorder_keys = Preorder(root) - if len(preorder_keys) > n: - return preorder_keys[n-1] - else: - return f'no {n}-th element' - - -items = Node(6) -items.left = Node(4) -items.right = Node(7) -items.left.left = Node(3) -items.left.right = Node(5) -print(Preorder(items)) +class Node: + def __init__(self, key, left=None, right=None): + self.left = left + self.right = right + self.key = key + +def Preorder(root): + if not root: + return [] + return [root.key] + Preorder(root.left) + Preorder(root.right) + +def NthPreorder(root, n): + preorder_keys = Preorder(root) + if len(preorder_keys) > n: + return preorder_keys[n-1] + else: + return f'no {n}-th element' + + +items = Node(6) +items.left = Node(4) +items.right = Node(7) +items.left.left = Node(3) +items.left.right = Node(5) +print(Preorder(items)) print(NthPreorder(items, 3)) \ No newline at end of file diff --git a/data_structures/binary_trees/nth_preorder/solution/test_public.py b/data_structures/binary_trees/nth_preorder/solution/test_public.py index edbef284..13820e43 100644 --- a/data_structures/binary_trees/nth_preorder/solution/test_public.py +++ b/data_structures/binary_trees/nth_preorder/solution/test_public.py @@ -1,14 +1,14 @@ -def test_solution(): - from solution import Node, NthPreorder - - items = Node(25) - items.left = Node(20) - items.right = Node(30) - items.left.left = Node(18) - items.left.right = Node(22) - items.right.left = Node(24) - items.right.right = Node(32) - - assert NthPreorder(items, 6) == 24 - assert NthPreorder(items, 4) == 22 +def test_solution(): + from solution import Node, NthPreorder + + items = Node(25) + items.left = Node(20) + items.right = Node(30) + items.left.left = Node(18) + items.left.right = Node(22) + items.right.left = Node(24) + items.right.right = Node(32) + + assert NthPreorder(items, 6) == 24 + assert NthPreorder(items, 4) == 22 assert NthPreorder(items, 8) == "no 8-th element" \ No newline at end of file diff --git a/data_structures/binary_trees/postorder_list/README.md b/data_structures/binary_trees/postorder_list/README.md index 3bcb6e82..b7582bfb 100644 --- a/data_structures/binary_trees/postorder_list/README.md +++ b/data_structures/binary_trees/postorder_list/README.md @@ -1,43 +1,43 @@ -# Postorder List - -## Motivation -Algorithm Postorder(tree)- -1. Traverse the left subtree, i.e., call Postorder(left-subtree) -2. Traverse the right subtree, i.e., call Postorder(right-subtree) -3. Visit the root. - -# Problem Description -Given the following Binary tree definition: - -''' -class Node: - def __init__(self,key,left=None,right=None): - self.left = left - self.right = right - self.key = key -''' - -Define a function `Postorder` which consumes one argument `root`. The function returns the postorder traversal of the given binary tree. - -# Example -``` -Input: - 6 - / \ - 4 7 - / \ - 3 5 - -items = Node(6) -items.left = Node(4) -items.right = Node(7) -items.left.left = Node(3) -items.left.right = Node(5) -Postorder(items) == [3, 5, 4, 7, 6] -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Postorder List + +## Motivation +Algorithm Postorder(tree)- +1. Traverse the left subtree, i.e., call Postorder(left-subtree) +2. Traverse the right subtree, i.e., call Postorder(right-subtree) +3. Visit the root. + +# Problem Description +Given the following Binary tree definition: + +''' +class Node: + def __init__(self,key,left=None,right=None): + self.left = left + self.right = right + self.key = key +''' + +Define a function `Postorder` which consumes one argument `root`. The function returns the postorder traversal of the given binary tree. + +# Example +``` +Input: + 6 + / \ + 4 7 + / \ + 3 5 + +items = Node(6) +items.left = Node(4) +items.right = Node(7) +items.left.left = Node(3) +items.left.right = Node(5) +Postorder(items) == [3, 5, 4, 7, 6] +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/binary_trees/postorder_list/solution/solution.py b/data_structures/binary_trees/postorder_list/solution/solution.py index 864e1698..64ee31fe 100644 --- a/data_structures/binary_trees/postorder_list/solution/solution.py +++ b/data_structures/binary_trees/postorder_list/solution/solution.py @@ -1,17 +1,17 @@ -class Node: - def __init__(self, key, left=None, right=None): - self.left = left - self.right = right - self.key = key - -def Postorder(root): - if not root: - return [] - return Postorder(root.left) + Postorder(root.right) + [root.key] - -items = Node(6) -items.left = Node(4) -items.right = Node(7) -items.left.left = Node(3) -items.left.right = Node(5) +class Node: + def __init__(self, key, left=None, right=None): + self.left = left + self.right = right + self.key = key + +def Postorder(root): + if not root: + return [] + return Postorder(root.left) + Postorder(root.right) + [root.key] + +items = Node(6) +items.left = Node(4) +items.right = Node(7) +items.left.left = Node(3) +items.left.right = Node(5) print(Postorder(items)) \ No newline at end of file diff --git a/data_structures/binary_trees/postorder_list/solution/test_public.py b/data_structures/binary_trees/postorder_list/solution/test_public.py index 5978f67a..da0f026f 100644 --- a/data_structures/binary_trees/postorder_list/solution/test_public.py +++ b/data_structures/binary_trees/postorder_list/solution/test_public.py @@ -1,11 +1,11 @@ -def test_solution(): - from solution import Node, Postorder - - items = Node(5) - items.left = Node(6) - items.right = Node(7) - items.left.left = Node(8) - items.left.right = Node(9) - result_value_1 = Postorder(items) - result = [8, 9, 6, 7, 5] - assert result_value_1 == result +def test_solution(): + from solution import Node, Postorder + + items = Node(5) + items.left = Node(6) + items.right = Node(7) + items.left.left = Node(8) + items.left.right = Node(9) + result_value_1 = Postorder(items) + result = [8, 9, 6, 7, 5] + assert result_value_1 == result diff --git a/data_structures/binary_trees/preorder_list/README.md b/data_structures/binary_trees/preorder_list/README.md index eb0c2f29..126c0bc4 100644 --- a/data_structures/binary_trees/preorder_list/README.md +++ b/data_structures/binary_trees/preorder_list/README.md @@ -1,44 +1,44 @@ -# Preorder List - -## Motivation -Algorithm Preorder(tree)- -1. Visit the root. -2. Traverse the left subtree, i.e., call Preorder(left-subtree) -3. Traverse the right subtree, i.e., call Preorder(right-subtree) - -# Problem Description -Given the following Binary tree definition: - -''' -class Node: - def __init__(self,key=None,left=None,right=None): - self.left = left - self.right = right - self.key = key -''' - -Define a function `Preorder` which consumes one argument `root`. The function returns the preorder traversal of the given binary tree. - -# Example -``` -Input: - 6 - / \ - 4 7 - / \ - 3 5 - -items = Node(6) -items.left = Node(4) -items.right = Node(7) -items.left.left = Node(3) -items.left.right = Node(5) -Preorder(items) == [6, 4, 3, 5, 7] - -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Preorder List + +## Motivation +Algorithm Preorder(tree)- +1. Visit the root. +2. Traverse the left subtree, i.e., call Preorder(left-subtree) +3. Traverse the right subtree, i.e., call Preorder(right-subtree) + +# Problem Description +Given the following Binary tree definition: + +''' +class Node: + def __init__(self,key=None,left=None,right=None): + self.left = left + self.right = right + self.key = key +''' + +Define a function `Preorder` which consumes one argument `root`. The function returns the preorder traversal of the given binary tree. + +# Example +``` +Input: + 6 + / \ + 4 7 + / \ + 3 5 + +items = Node(6) +items.left = Node(4) +items.right = Node(7) +items.left.left = Node(3) +items.left.right = Node(5) +Preorder(items) == [6, 4, 3, 5, 7] + +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/binary_trees/preorder_list/solution/solution.py b/data_structures/binary_trees/preorder_list/solution/solution.py index 9cc9bdb1..91c87a68 100644 --- a/data_structures/binary_trees/preorder_list/solution/solution.py +++ b/data_structures/binary_trees/preorder_list/solution/solution.py @@ -1,17 +1,17 @@ -class Node: - def __init__(self, key, left=None, right=None): - self.left = left - self.right = right - self.key = key - -def Preorder(root): - if not root: - return [] - return [root.key] + Preorder(root.left) + Preorder(root.right) - -items = Node(6) -items.left = Node(4) -items.right = Node(7) -items.left.left = Node(3) -items.left.right = Node(5) +class Node: + def __init__(self, key, left=None, right=None): + self.left = left + self.right = right + self.key = key + +def Preorder(root): + if not root: + return [] + return [root.key] + Preorder(root.left) + Preorder(root.right) + +items = Node(6) +items.left = Node(4) +items.right = Node(7) +items.left.left = Node(3) +items.left.right = Node(5) print(Preorder(items)) \ No newline at end of file diff --git a/data_structures/binary_trees/preorder_list/solution/test_public.py b/data_structures/binary_trees/preorder_list/solution/test_public.py index 9ea523e2..97b78298 100644 --- a/data_structures/binary_trees/preorder_list/solution/test_public.py +++ b/data_structures/binary_trees/preorder_list/solution/test_public.py @@ -1,11 +1,11 @@ -def test_solution(): - from solution import Node, Preorder - - items = Node(5) - items.left = Node(6) - items.right = Node(7) - items.left.left = Node(8) - items.left.right = Node(9) - result_value_1 = Preorder(items) - result = [5, 6, 8, 9, 7] - assert result_value_1 == result +def test_solution(): + from solution import Node, Preorder + + items = Node(5) + items.left = Node(6) + items.right = Node(7) + items.left.left = Node(8) + items.left.right = Node(9) + result_value_1 = Preorder(items) + result = [5, 6, 8, 9, 7] + assert result_value_1 == result diff --git a/data_structures/binary_trees/search_node/README.md b/data_structures/binary_trees/search_node/README.md index 61623f6b..a8417bc0 100644 --- a/data_structures/binary_trees/search_node/README.md +++ b/data_structures/binary_trees/search_node/README.md @@ -1,52 +1,52 @@ -# Search Node - -## Motivation -Let a binary search tree (BST) is defined as follows: -The left subtree of a node contains only nodes with keys less than the node's key. -The right subtree of a node contains only nodes with keys greater than the node's key. -Both the left and right subtrees must also be binary search trees. - -Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. -1. Inorder -2. Preorder -3. Postorder - -# Problem Description -Given the following Binary tree definition: - -''' -class Node: - def __init__(self,key,left=None,right=None): - self.left = left - self.right = right - self.key = key -''' - -Define a function `search` which consumes two arguments `root` and `key`. The function returns `True` if `key` is in the tree `root` and `False` otherwise. - -# Example -``` - 6 - / \ - 4 9 - / \ / \ - 3 5 7 11 - -items = Node(6) -items.left = Node(4) -items.right = Node(9) -items.left.left = Node(3) -items.left.right = Node(5) -items.right.left = Node(7) -items.right.right = Node(11) - -search(items,11) == True -search(items,8) == False - -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Search Node + +## Motivation +Let a binary search tree (BST) is defined as follows: +The left subtree of a node contains only nodes with keys less than the node's key. +The right subtree of a node contains only nodes with keys greater than the node's key. +Both the left and right subtrees must also be binary search trees. + +Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. +1. Inorder +2. Preorder +3. Postorder + +# Problem Description +Given the following Binary tree definition: + +''' +class Node: + def __init__(self,key,left=None,right=None): + self.left = left + self.right = right + self.key = key +''' + +Define a function `search` which consumes two arguments `root` and `key`. The function returns `True` if `key` is in the tree `root` and `False` otherwise. + +# Example +``` + 6 + / \ + 4 9 + / \ / \ + 3 5 7 11 + +items = Node(6) +items.left = Node(4) +items.right = Node(9) +items.left.left = Node(3) +items.left.right = Node(5) +items.right.left = Node(7) +items.right.right = Node(11) + +search(items,11) == True +search(items,8) == False + +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/binary_trees/search_node/solution/solution.py b/data_structures/binary_trees/search_node/solution/solution.py index fb0b6a16..af0996cb 100644 --- a/data_structures/binary_trees/search_node/solution/solution.py +++ b/data_structures/binary_trees/search_node/solution/solution.py @@ -1,26 +1,26 @@ -class Node: - def __init__(self, key, left=None, right=None): - self.left = left - self.right = right - self.key = key - - -def search(root, key): - if not root: - return False - if key == root.key: - return True - elif key < root.key: - return search(root.left, key) - else: - return search(root.right, key) - -items = Node(6) -items.left = Node(4) -items.right = Node(9) -items.left.left = Node(3) -items.left.right = Node(5) -items.right.left = Node(7) -items.right.right = Node(11) - +class Node: + def __init__(self, key, left=None, right=None): + self.left = left + self.right = right + self.key = key + + +def search(root, key): + if not root: + return False + if key == root.key: + return True + elif key < root.key: + return search(root.left, key) + else: + return search(root.right, key) + +items = Node(6) +items.left = Node(4) +items.right = Node(9) +items.left.left = Node(3) +items.left.right = Node(5) +items.right.left = Node(7) +items.right.right = Node(11) + print(search(items,11)) \ No newline at end of file diff --git a/data_structures/binary_trees/search_node/solution/test_public.py b/data_structures/binary_trees/search_node/solution/test_public.py index bd016b88..4aa36fdf 100644 --- a/data_structures/binary_trees/search_node/solution/test_public.py +++ b/data_structures/binary_trees/search_node/solution/test_public.py @@ -1,14 +1,14 @@ -def test_solution(): - from solution import Node, search - - items = Node(5) - items.left = Node(6) - items.right = Node(7) - items.left.left = Node(8) - items.left.right = Node(9) - items.right.left = Node(10) - items.right.right = Node(11) - result_value = search(items, 11) - result_value_2 = search(items, 99) - assert result_value == True - assert result_value_2 == False +def test_solution(): + from solution import Node, search + + items = Node(5) + items.left = Node(6) + items.right = Node(7) + items.left.left = Node(8) + items.left.right = Node(9) + items.right.left = Node(10) + items.right.right = Node(11) + result_value = search(items, 11) + result_value_2 = search(items, 99) + assert result_value == True + assert result_value_2 == False diff --git a/data_structures/changes.md b/data_structures/changes.md index 64b4d705..61ca4cde 100644 --- a/data_structures/changes.md +++ b/data_structures/changes.md @@ -1,25 +1,25 @@ -# Second Iteration Changes - -**Main things to look for** - -1) Differentiate public/private tests -In the second iteration, we want more comprehensive tests that can test a) edge cases b) invalid inputs c) runtime constraints. The directory structure should also reflect this change and be structured in a specific format. Please reference [this](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/2_fibonacci/solution) section for a template on directory structure and comprenhensive tests. - -2) Templated problem description. -Each section should have a standardized problem description. It is almost ALWAYS asking them to define a function, the only exceptions being the modules before they learn what a function is. Here is the problem description template: -``` -Define a Python function named A that consumes a B C and returns D. -``` -where `A` is the name of the function. `B` is the type of `C`. `C` is the name of the argument. There can be many `B`-`C` pairs, one for each argument. `D` is a sentence that references `C`. -Please look in the recursie functions section to see a completed section following [this](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions) template if you would like a reference. - -3) Include examples in the READMEs. Just a basic snippet like. These should also be the public tests. -``` -assert factorial(3) == 6 -``` - -4) Omit the testing portion of the `README.md` file. Pretty self explanatory - this is the file the student views, this testing portion holds no value. - -5) Naming conventions for files/directories. All `README.md` files should be capitalized as shown. All `.py` files should be in `lowercase_snakecase.py` format, all directories should be the same (currently a lot of solutions directories start with capital S) - -6) The main `README.md` file for the section that contains all the exercises should have a valid id-exercise mapping with appropriate links. The links in the table simply point to the folder containing the exercise, see https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions as a template. +# Second Iteration Changes + +**Main things to look for** + +1) Differentiate public/private tests +In the second iteration, we want more comprehensive tests that can test a) edge cases b) invalid inputs c) runtime constraints. The directory structure should also reflect this change and be structured in a specific format. Please reference [this](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/2_fibonacci/solution) section for a template on directory structure and comprenhensive tests. + +2) Templated problem description. +Each section should have a standardized problem description. It is almost ALWAYS asking them to define a function, the only exceptions being the modules before they learn what a function is. Here is the problem description template: +``` +Define a Python function named A that consumes a B C and returns D. +``` +where `A` is the name of the function. `B` is the type of `C`. `C` is the name of the argument. There can be many `B`-`C` pairs, one for each argument. `D` is a sentence that references `C`. +Please look in the recursie functions section to see a completed section following [this](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions) template if you would like a reference. + +3) Include examples in the READMEs. Just a basic snippet like. These should also be the public tests. +``` +assert factorial(3) == 6 +``` + +4) Omit the testing portion of the `README.md` file. Pretty self explanatory - this is the file the student views, this testing portion holds no value. + +5) Naming conventions for files/directories. All `README.md` files should be capitalized as shown. All `.py` files should be in `lowercase_snakecase.py` format, all directories should be the same (currently a lot of solutions directories start with capital S) + +6) The main `README.md` file for the section that contains all the exercises should have a valid id-exercise mapping with appropriate links. The links in the table simply point to the folder containing the exercise, see https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions as a template. diff --git a/data_structures/dictionaries_and_arrays/Readme.md b/data_structures/dictionaries_and_arrays/Readme.md index 515c2bbc..aea1b989 100755 --- a/data_structures/dictionaries_and_arrays/Readme.md +++ b/data_structures/dictionaries_and_arrays/Readme.md @@ -1,14 +1,14 @@ -# Introduction To Arrays and Dictionary Exercises - -| Exercise ID | Exercise | -|:-----------:|:--------:| -| easy_e1 | [Sum_Tuples](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/1.sum_tuples) | -| easy_e2 | [Student_Grades_Dict](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/1.student_grades_dict) | -| easy_e3 | [Intersect_Lists](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/1.intersect_lists) | -| easy_e4 | [Squares_Dictionary](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/1.squares_dictionary) | -| medium_e1 | [Sum_Imaginary](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/2.sum_imaginary) | -| medium_e2 | [Age_Range](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/2.age_range | -| medium_e3 | [Inventory_Dict](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/2.inventory_dict) | -| medium_e4 | [Election](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_and_environment/introduction_to_programming/election) | -| hard_e1 | [Prime_Factors](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/3.prime_factors) | +# Introduction To Arrays and Dictionary Exercises + +| Exercise ID | Exercise | +|:-----------:|:--------:| +| easy_e1 | [Sum_Tuples](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/1.sum_tuples) | +| easy_e2 | [Student_Grades_Dict](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/1.student_grades_dict) | +| easy_e3 | [Intersect_Lists](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/1.intersect_lists) | +| easy_e4 | [Squares_Dictionary](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/1.squares_dictionary) | +| medium_e1 | [Sum_Imaginary](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/2.sum_imaginary) | +| medium_e2 | [Age_Range](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/2.age_range | +| medium_e3 | [Inventory_Dict](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/2.inventory_dict) | +| medium_e4 | [Election](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_and_environment/introduction_to_programming/election) | +| hard_e1 | [Prime_Factors](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/3.prime_factors) | | hard_e2 | [Shopping_List](https://github.com/ByteAcademyCo/Data-Structures/tree/Arrays/exercises/dictionaries_and_arrays/3.shopping_list) | \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/age_range/Readme.md b/data_structures/dictionaries_and_arrays/age_range/Readme.md index 8e3181f7..ee1f9e42 100755 --- a/data_structures/dictionaries_and_arrays/age_range/Readme.md +++ b/data_structures/dictionaries_and_arrays/age_range/Readme.md @@ -1,17 +1,17 @@ -# Age Range Dictionary - -## Problem Description -Define a Python function `remove_ages` which consumes a dictionary `pdict`, and two non-negative integers `x` and `y` where `x <= y`. The keys in `pdict` are strings representing names of people, and the values are non-negative integers representing the age of the person. Return a dictionary with all the key-value pairs in `pdict` where the age falls inside of the range `[x,y]`. - -## Examples -``` -pdict = {"Nell": 26, "Sue": 30, "Billy": 4} -remove_ages(pdict, 10, 30) == {"Nell": 26, "Sue": 30} -``` - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Age Range Dictionary + +## Problem Description +Define a Python function `remove_ages` which consumes a dictionary `pdict`, and two non-negative integers `x` and `y` where `x <= y`. The keys in `pdict` are strings representing names of people, and the values are non-negative integers representing the age of the person. Return a dictionary with all the key-value pairs in `pdict` where the age falls inside of the range `[x,y]`. + +## Examples +``` +pdict = {"Nell": 26, "Sue": 30, "Billy": 4} +remove_ages(pdict, 10, 30) == {"Nell": 26, "Sue": 30} +``` + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/age_range/solution/solution.py b/data_structures/dictionaries_and_arrays/age_range/solution/solution.py index 27eebd67..c23eba98 100755 --- a/data_structures/dictionaries_and_arrays/age_range/solution/solution.py +++ b/data_structures/dictionaries_and_arrays/age_range/solution/solution.py @@ -1,6 +1,6 @@ -def remove_ages(pdict, x, y): - ret_dict = {} - for p, age in pdict.items(): - if age >= x and age <= y: - ret_dict[p] = age - return ret_dict \ No newline at end of file +def remove_ages(pdict, x, y): + ret_dict = {} + for p, age in pdict.items(): + if age >= x and age <= y: + ret_dict[p] = age + return ret_dict diff --git a/data_structures/dictionaries_and_arrays/age_range/solution/test_solution.py b/data_structures/dictionaries_and_arrays/age_range/solution/test_solution.py index 82975946..16d5d7df 100755 --- a/data_structures/dictionaries_and_arrays/age_range/solution/test_solution.py +++ b/data_structures/dictionaries_and_arrays/age_range/solution/test_solution.py @@ -1,9 +1,9 @@ -def test_solution(): - from solution import remove_ages - - pdict = {"Nell": 26, "Sue": 30, "Billy": 4} - - assert remove_ages(pdict, 10, 30) == {"Nell": 26, "Sue": 30} - assert remove_ages({}, 10, 30) == {} - assert remove_ages({"b": 10}, 12, 40) == {} +def test_solution(): + from solution import remove_ages + + pdict = {"Nell": 26, "Sue": 30, "Billy": 4} + + assert remove_ages(pdict, 10, 30) == {"Nell": 26, "Sue": 30} + assert remove_ages({}, 10, 30) == {} + assert remove_ages({"b": 10}, 12, 40) == {} assert remove_ages({"b": 10}, 10, 10) == {"b": 10} \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/election/Readme.md b/data_structures/dictionaries_and_arrays/election/Readme.md index ae339c95..4dddede0 100755 --- a/data_structures/dictionaries_and_arrays/election/Readme.md +++ b/data_structures/dictionaries_and_arrays/election/Readme.md @@ -1,16 +1,16 @@ -# Election Winner - -## Problem Description -You are holding an election. Define a Python function named `election_winner` that consumes a non-empty list of candidate names as strings `clst`, where each name in the list represents a vote for that candidate. Return the name of the candidate who wins the election. If there is a tie, output the name of the candidate which comes first in lexicographical order. - -## Examples -``` -clst = ["Trump", "Bernie", "Bernie", "Oprah", "Biden", "Bernie", "Trump"] -election_winner(clst) == "Bernie" -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Election Winner + +## Problem Description +You are holding an election. Define a Python function named `election_winner` that consumes a non-empty list of candidate names as strings `clst`, where each name in the list represents a vote for that candidate. Return the name of the candidate who wins the election. If there is a tie, output the name of the candidate which comes first in lexicographical order. + +## Examples +``` +clst = ["Trump", "Bernie", "Bernie", "Oprah", "Biden", "Bernie", "Trump"] +election_winner(clst) == "Bernie" +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/election/solution/election.py b/data_structures/dictionaries_and_arrays/election/solution/election.py new file mode 100644 index 00000000..8ad28715 --- /dev/null +++ b/data_structures/dictionaries_and_arrays/election/solution/election.py @@ -0,0 +1,16 @@ +def election_winner(clst): + candidate_dict = {} + for r in clst: + if r not in candidate_dict: + candidate_dict[r] = 1 + else: + candidate_dict[r] += 1 + max_votes = 0 + winner ="" + for cname, num_votes in candidate_dict.items(): + if num_votes > max_votes: + max_votes = num_votes + winner = cname + elif num_votes == max_votes and cname < winner: + winner = cname + return winner \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/election/solution/solution.py b/data_structures/dictionaries_and_arrays/election/solution/solution.py index f18efc66..bd3f2b00 100755 --- a/data_structures/dictionaries_and_arrays/election/solution/solution.py +++ b/data_structures/dictionaries_and_arrays/election/solution/solution.py @@ -1,30 +1,30 @@ -def election_winner(clst): - # create a dict to store the names of candidates as keys - # and the number of votes for that candidate as the value - candidate_dict = {} - # itterate through the votes - for c in clst: - # if it is a new candidate we havent seen yet - # add it to our dict and set the value of votes to 1. - if c not in candidate_dict: - candidate_dict[c] = 1 - # otherwise increment the votes for that candidate by 1 - else: - candidate_dict[c] += 1 - # keep track of maximal votes we've seen so far - max_votes = 0 - # keep track of winner so far - winner = "" - for cname, num_votes in candidate_dict.items(): - # if the current candidate beats the max so far - # we update the max and set the winner so far - # to this candidate. - if num_votes > max_votes: - max_votes = num_votes - winner = cname - # if this candidate is tied with the max so far - # we compare the name, if it is less than winners - # name we update the winner so far. - elif num_votes == max_votes and cname < winner: - winner = cname - return winner +def election_winner(clst): + # create a dict to store the names of candidates as keys + # and the number of votes for that candidate as the value + candidate_dict = {} + # itterate through the votes + for c in clst: + # if it is a new candidate we havent seen yet + # add it to our dict and set the value of votes to 1. + if c not in candidate_dict: + candidate_dict[c] = 1 + # otherwise increment the votes for that candidate by 1 + else: + candidate_dict[c] += 1 + # keep track of maximal votes we've seen so far + max_votes = 0 + # keep track of winner so far + winner = "" + for cname, num_votes in candidate_dict.items(): + # if the current candidate beats the max so far + # we update the max and set the winner so far + # to this candidate. + if num_votes > max_votes: + max_votes = num_votes + winner = cname + # if this candidate is tied with the max so far + # we compare the name, if it is less than winners + # name we update the winner so far. + elif num_votes == max_votes and cname < winner: + winner = cname + return winner diff --git a/data_structures/dictionaries_and_arrays/election/solution/test_solution.py b/data_structures/dictionaries_and_arrays/election/solution/test_solution.py index 5e817ed2..da4e784c 100755 --- a/data_structures/dictionaries_and_arrays/election/solution/test_solution.py +++ b/data_structures/dictionaries_and_arrays/election/solution/test_solution.py @@ -1,12 +1,12 @@ -def test_solution(): - from solution import election_winner - - clst1 = ["Trump", "Bernie", "Bernie", "Oprah", "Biden", "Bernie", "Trump"] - assert election_winner(clst1) == "Bernie" - - clst2 = ["Trump", "Bernie", "Bernie", "Trump"] - assert election_winner(clst2) == "Bernie" - - assert election_winner(["Oprah"]) == "Oprah" - - +def test_solution(): + from election import election_winner + + clst1 = ["Trump", "Bernie", "Bernie", "Oprah", "Biden", "Bernie", "Trump"] + assert election_winner(clst1) == "Bernie" + + clst2 = ["Trump", "Bernie", "Bernie", "Trump"] + assert election_winner(clst2) == "Bernie" + + assert election_winner(["Oprah"]) == "Oprah" + + diff --git a/data_structures/dictionaries_and_arrays/intersect_lists/Readme.md b/data_structures/dictionaries_and_arrays/intersect_lists/Readme.md index e06f702b..5ba77607 100755 --- a/data_structures/dictionaries_and_arrays/intersect_lists/Readme.md +++ b/data_structures/dictionaries_and_arrays/intersect_lists/Readme.md @@ -1,18 +1,18 @@ -# Intersection of Two Lists - -## Problem Description -Define a Python function `intersect_lists`, which consumes two lists, `lst1` and `lst2`, -and returns a list containing all the values that appear in both `lst1` and `lst2`. The values may appear in any order in the returned list. - -## Examples -``` -lst1 = [1, "a", -2, 1.4] -lst2 = ["cat", 0.5, "a", 1, 2] -intersect_lists(lst1, lst2) == ["a", 1] -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Intersection of Two Lists + +## Problem Description +Define a Python function `intersect_lists`, which consumes two lists, `lst1` and `lst2`, +and returns a list containing all the values that appear in both `lst1` and `lst2`. The values may appear in any order in the returned list. + +## Examples +``` +lst1 = [1, "a", -2, 1.4] +lst2 = ["cat", 0.5, "a", 1, 2] +intersect_lists(lst1, lst2) == ["a", 1] +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/intersect_lists/solution/.model_solution/solution.py b/data_structures/dictionaries_and_arrays/intersect_lists/solution/.model_solution/solution.py index 93ad2a4d..96d58d11 100644 --- a/data_structures/dictionaries_and_arrays/intersect_lists/solution/.model_solution/solution.py +++ b/data_structures/dictionaries_and_arrays/intersect_lists/solution/.model_solution/solution.py @@ -1,4 +1,4 @@ -def update_dict(key,value): - create_dict_ = {} - create_dict[key] = value - return create_dict +def update_dict(key,value): + create_dict_ = {} + create_dict[key] = value + return create_dict diff --git a/data_structures/dictionaries_and_arrays/intersect_lists/solution/intersect.py b/data_structures/dictionaries_and_arrays/intersect_lists/solution/intersect.py new file mode 100644 index 00000000..6fabaf02 --- /dev/null +++ b/data_structures/dictionaries_and_arrays/intersect_lists/solution/intersect.py @@ -0,0 +1,2 @@ +def intersect_lists(lst1, lst2): + return [x for x in lst1 if x in lst2] \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/intersect_lists/solution/solution.py b/data_structures/dictionaries_and_arrays/intersect_lists/solution/solution.py index 999852ed..6fabaf02 100755 --- a/data_structures/dictionaries_and_arrays/intersect_lists/solution/solution.py +++ b/data_structures/dictionaries_and_arrays/intersect_lists/solution/solution.py @@ -1,2 +1,2 @@ -def intersect_lists(lst1, lst2): +def intersect_lists(lst1, lst2): return [x for x in lst1 if x in lst2] \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/intersect_lists/solution/test_solution.py b/data_structures/dictionaries_and_arrays/intersect_lists/solution/test_solution.py index 39de3c65..8dfefd1c 100755 --- a/data_structures/dictionaries_and_arrays/intersect_lists/solution/test_solution.py +++ b/data_structures/dictionaries_and_arrays/intersect_lists/solution/test_solution.py @@ -1,14 +1,14 @@ -def test_solution(): - from solution import intersect_lists - - lst1 = [1, "a", -2, 1.4] - lst2 = ["cat", 0.5, "a", 1, 2] - - ret_lst = intersect_lists(lst1, lst2) - - ret_lst2 = intersect_lists(["a", "b"], ["b", "a"]) - - assert (ret_lst == ["a", 1] or ret_lst == [1, "a"]) == True - assert intersect_lists([1, 2, 3], [4, 5]) == [] - assert intersect_lists([], []) == [] - assert (ret_lst2 == ["a", "b"] or ret_lst2 == ["b", "a"]) == True +def test_solution(): + from intersect import intersect_lists + + lst1 = [1, "a", -2, 1.4] + lst2 = ["cat", 0.5, "a", 1, 2] + + ret_lst = intersect_lists(lst1, lst2) + + ret_lst2 = intersect_lists(["a", "b"], ["b", "a"]) + + assert (ret_lst == ["a", 1] or ret_lst == [1, "a"]) == True + assert intersect_lists([1, 2, 3], [4, 5]) == [] + assert intersect_lists([], []) == [] + assert (ret_lst2 == ["a", "b"] or ret_lst2 == ["b", "a"]) == True diff --git a/data_structures/dictionaries_and_arrays/inventory_dict/Readme.md b/data_structures/dictionaries_and_arrays/inventory_dict/Readme.md index e44c238b..130eebc7 100755 --- a/data_structures/dictionaries_and_arrays/inventory_dict/Readme.md +++ b/data_structures/dictionaries_and_arrays/inventory_dict/Readme.md @@ -1,16 +1,16 @@ -# Inventory Dictionary - Stock Price - -## Problem Description -You own a store with a variety of products on stock in diffrent quantities. Define a Python function `inventory_price`, which consumes a dictionary `idict`, where the keys are strings representing the names of your products, and the values are tuples `(quantity, price)`, where `quantity` is an integer and `price` is a float. Output the total price of the inventory in your store. - -## Example -``` -idict = {"hat": (20, 15.50), "tshirt": (50, 19.99), "jeans": (10, 69.55)} -inventory_price(idict) == 2005.0 -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Inventory Dictionary - Stock Price + +## Problem Description +You own a store with a variety of products on stock in diffrent quantities. Define a Python function `inventory_price`, which consumes a dictionary `idict`, where the keys are strings representing the names of your products, and the values are tuples `(quantity, price)`, where `quantity` is an integer and `price` is a float. Output the total price of the inventory in your store. + +## Example +``` +idict = {"hat": (20, 15.50), "tshirt": (50, 19.99), "jeans": (10, 69.55)} +inventory_price(idict) == 2005.0 +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/inventory_dict/solution/solution.py b/data_structures/dictionaries_and_arrays/inventory_dict/solution/solution.py index 6ad6ab3e..c336ec03 100755 --- a/data_structures/dictionaries_and_arrays/inventory_dict/solution/solution.py +++ b/data_structures/dictionaries_and_arrays/inventory_dict/solution/solution.py @@ -1,6 +1,6 @@ -def inventory_price(idict): - # varible to store the price - price = 0 - for product in idict.values(): - price += product[0]*product[1] +def inventory_price(idict): + # varible to store the price + price = 0 + for product in idict.values(): + price += product[0]*product[1] return price \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/inventory_dict/solution/test_solution.py b/data_structures/dictionaries_and_arrays/inventory_dict/solution/test_solution.py index 99bd6621..9e6938e2 100755 --- a/data_structures/dictionaries_and_arrays/inventory_dict/solution/test_solution.py +++ b/data_structures/dictionaries_and_arrays/inventory_dict/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - from solution import inventory_price - - idict = {"hat": (20, 15.50), "tshirt": (50, 19.99), "jeans": (10, 69.55)} - assert inventory_price(idict) == 2005 - assert inventory_price({"hat": (20, 15.50)}) == 310 - assert inventory_price({}) == 0 +def test_solution(): + from solution import inventory_price + + idict = {"hat": (20, 15.50), "tshirt": (50, 19.99), "jeans": (10, 69.55)} + assert inventory_price(idict) == 2005 + assert inventory_price({"hat": (20, 15.50)}) == 310 + assert inventory_price({}) == 0 diff --git a/data_structures/dictionaries_and_arrays/prime_factors/Readme.md b/data_structures/dictionaries_and_arrays/prime_factors/Readme.md index f2d5a31d..aa8a4510 100755 --- a/data_structures/dictionaries_and_arrays/prime_factors/Readme.md +++ b/data_structures/dictionaries_and_arrays/prime_factors/Readme.md @@ -1,16 +1,16 @@ -# Difference - -## Problem Description -Define a Python function `prime_factors`, that consumes a positive integer `n`, and returns a list of all the prime factors of `n` in increasing order. - -## Examples -``` -prime_factors(10) == [1, 2, 5] -prime_factors(13) == [1, 13] -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Difference + +## Problem Description +Define a Python function `prime_factors`, that consumes a positive integer `n`, and returns a list of all the prime factors of `n` in increasing order. + +## Examples +``` +prime_factors(10) == [1, 2, 5] +prime_factors(13) == [1, 13] +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/prime_factors/solution/solution.py b/data_structures/dictionaries_and_arrays/prime_factors/solution/solution.py index c5e16fee..27134b29 100755 --- a/data_structures/dictionaries_and_arrays/prime_factors/solution/solution.py +++ b/data_structures/dictionaries_and_arrays/prime_factors/solution/solution.py @@ -1,21 +1,21 @@ -from math import sqrt - -def is_prime(x): - # itterate through numbers 2...sqrt(n) - for i in range(2, int(sqrt(x)+1)): - # if i is a factor of x, x is not prime - if x%i == 0: - return False - # if we found no factors x is prime - return True - -def prime_factors(n): - # list to keep track of prime factors - factors = [] - # loop through numbers 1...n - for i in range(1, n+1): - # if i is a factor of n and i is prime - if n%i == 0 and is_prime(i): - # append i to our prime factors list - factors.append(i) - return factors +from math import sqrt + +def is_prime(x): + # itterate through numbers 2...sqrt(n) + for i in range(2, int(sqrt(x)+1)): + # if i is a factor of x, x is not prime + if x%i == 0: + return False + # if we found no factors x is prime + return True + +def prime_factors(n): + # list to keep track of prime factors + factors = [] + # loop through numbers 1...n + for i in range(1, n+1): + # if i is a factor of n and i is prime + if n%i == 0 and is_prime(i): + # append i to our prime factors list + factors.append(i) + return factors diff --git a/data_structures/dictionaries_and_arrays/prime_factors/solution/test_solution.py b/data_structures/dictionaries_and_arrays/prime_factors/solution/test_solution.py index c0d5a24e..a37de5b8 100755 --- a/data_structures/dictionaries_and_arrays/prime_factors/solution/test_solution.py +++ b/data_structures/dictionaries_and_arrays/prime_factors/solution/test_solution.py @@ -1,8 +1,8 @@ -def test_solution(): - from solution import prime_factors - - assert prime_factors(1) == [1] - assert prime_factors(13) == [1, 13] - assert prime_factors(4) == [1, 2] - assert prime_factors(10) == [1, 2, 5] +def test_solution(): + from solution import prime_factors + + assert prime_factors(1) == [1] + assert prime_factors(13) == [1, 13] + assert prime_factors(4) == [1, 2] + assert prime_factors(10) == [1, 2, 5] assert prime_factors(12) == [1, 2, 3] \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/shopping_list/Readme.md b/data_structures/dictionaries_and_arrays/shopping_list/Readme.md index b0f1489d..74be95de 100755 --- a/data_structures/dictionaries_and_arrays/shopping_list/Readme.md +++ b/data_structures/dictionaries_and_arrays/shopping_list/Readme.md @@ -1,30 +1,30 @@ -# Shopping List - Cheapest Store - -## Problem Description -You are going grocery shopping and want to find the cheapest grocery store to shop at. Define a python function `cheapest_store`, that consumes a non-empty dictionary, `grocery_dict` and a list, `shopping_list`. `grocery_dict` will have strings as keys which are the names of grocery stores, and that values for each key are also a dictionary, where the keys are names of products as strings and the values are the price of each product as a float. `shopping_list` will be a list of string names of all the products you want to buy. Output the name of the store where you can buy your groceries for the cheapest amount of money. If a store doesn't carry a product on your grocery list, add a penalty of `$5` to your total spenditure at that store. If two stores are tied, return the store with the name that comes first lexicographically. - -## Examples -``` -grocery_dict = {"Walmart": {"pasta": 2.0, - "bread": 1.5, - "cheese": 6.0, - "ketchup": 3.0, - "salami": 9.0, - "onions": 1.0}, - "Thriftys": {"bread": 4.0, - "ham": 6.0, - "salami": 12.0, - "pasta": 1.75, - "mayo": 4.0, - "onions": 2.0, - "ketchup": 3.5} - } -shopping_list = ["ham", "salami", "ketchup", "mayo", "pasta", "cheese", "tuna"] -cheapest_store(grocery_store, shopping_list) == "Walmart" -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Shopping List - Cheapest Store + +## Problem Description +You are going grocery shopping and want to find the cheapest grocery store to shop at. Define a python function `cheapest_store`, that consumes a non-empty dictionary, `grocery_dict` and a list, `shopping_list`. `grocery_dict` will have strings as keys which are the names of grocery stores, and that values for each key are also a dictionary, where the keys are names of products as strings and the values are the price of each product as a float. `shopping_list` will be a list of string names of all the products you want to buy. Output the name of the store where you can buy your groceries for the cheapest amount of money. If a store doesn't carry a product on your grocery list, add a penalty of `$5` to your total spenditure at that store. If two stores are tied, return the store with the name that comes first lexicographically. + +## Examples +``` +grocery_dict = {"Walmart": {"pasta": 2.0, + "bread": 1.5, + "cheese": 6.0, + "ketchup": 3.0, + "salami": 9.0, + "onions": 1.0}, + "Thriftys": {"bread": 4.0, + "ham": 6.0, + "salami": 12.0, + "pasta": 1.75, + "mayo": 4.0, + "onions": 2.0, + "ketchup": 3.5} + } +shopping_list = ["ham", "salami", "ketchup", "mayo", "pasta", "cheese", "tuna"] +cheapest_store(grocery_store, shopping_list) == "Walmart" +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/shopping_list/solution/solution.py b/data_structures/dictionaries_and_arrays/shopping_list/solution/solution.py index 62abfa98..636e9311 100755 --- a/data_structures/dictionaries_and_arrays/shopping_list/solution/solution.py +++ b/data_structures/dictionaries_and_arrays/shopping_list/solution/solution.py @@ -1,22 +1,22 @@ -from math import inf - -def grocery_cost(store_items, shopping_list): - total_cost = 0 - for item in shopping_list: - if item in store_items: - total_cost += store_items[item] - else: - total_cost += 5 - return total_cost - -def cheapest_store(grocery_store, shopping_list): - min_cost = inf - min_store = "" - for store, store_items in grocery_store.items(): - store_cost = grocery_cost(store_items, shopping_list) - if store_cost < min_cost: - min_cost = store_cost - min_store = store - elif store_cost == min_cost and store < min_store: - min_store = store - return min_store +from math import inf + +def grocery_cost(store_items, shopping_list): + total_cost = 0 + for item in shopping_list: + if item in store_items: + total_cost += store_items[item] + else: + total_cost += 5 + return total_cost + +def cheapest_store(grocery_store, shopping_list): + min_cost = inf + min_store = "" + for store, store_items in grocery_store.items(): + store_cost = grocery_cost(store_items, shopping_list) + if store_cost < min_cost: + min_cost = store_cost + min_store = store + elif store_cost == min_cost and store < min_store: + min_store = store + return min_store diff --git a/data_structures/dictionaries_and_arrays/shopping_list/solution/test_solution.py b/data_structures/dictionaries_and_arrays/shopping_list/solution/test_solution.py index b9c2888f..f65b5658 100755 --- a/data_structures/dictionaries_and_arrays/shopping_list/solution/test_solution.py +++ b/data_structures/dictionaries_and_arrays/shopping_list/solution/test_solution.py @@ -1,36 +1,36 @@ -def test_solution(): - from solution import cheapest_store - - grocery_dict1 = {"Walmart": {"pasta": 2.0, - "bread": 1.5, - "cheese": 6.0, - "ketchup": 3.0, - "salami": 9.0, - "onions": 1.0}, - "Thriftys": {"bread": 4.0, - "ham": 6.0, - "salami": 12.0, - "pasta": 1.75, - "mayo": 4.0, - "onions": 2.0, - "ketchup": 3.5} - } - - shopping_list1 = ["ham", "salami", "ketchup", "mayo", "pasta", "cheese", "tuna"] - - assert cheapest_store(grocery_dict1, shopping_list1) == "Walmart" - - grocery_dict2 = {"Whole Foods": {"fish": 5.0, - "meat": 6.0, - "waffles": 3.0} - } - shopping_list2 = ["fish", "bread"] - assert cheapest_store(grocery_dict2, shopping_list2) == "Whole Foods" - - grocery_dict3 = {"Whole Foods": {"fish": 5.0, - "meat": 6.0, - "waffles": 3.0}, - "Walmart": {"fish": 5.0, - "bread": 2.0} - } - assert cheapest_store(grocery_dict3, ["pasta", "cheese"]) == "Walmart" +def test_solution(): + from solution import cheapest_store + + grocery_dict1 = {"Walmart": {"pasta": 2.0, + "bread": 1.5, + "cheese": 6.0, + "ketchup": 3.0, + "salami": 9.0, + "onions": 1.0}, + "Thriftys": {"bread": 4.0, + "ham": 6.0, + "salami": 12.0, + "pasta": 1.75, + "mayo": 4.0, + "onions": 2.0, + "ketchup": 3.5} + } + + shopping_list1 = ["ham", "salami", "ketchup", "mayo", "pasta", "cheese", "tuna"] + + assert cheapest_store(grocery_dict1, shopping_list1) == "Walmart" + + grocery_dict2 = {"Whole Foods": {"fish": 5.0, + "meat": 6.0, + "waffles": 3.0} + } + shopping_list2 = ["fish", "bread"] + assert cheapest_store(grocery_dict2, shopping_list2) == "Whole Foods" + + grocery_dict3 = {"Whole Foods": {"fish": 5.0, + "meat": 6.0, + "waffles": 3.0}, + "Walmart": {"fish": 5.0, + "bread": 2.0} + } + assert cheapest_store(grocery_dict3, ["pasta", "cheese"]) == "Walmart" diff --git a/data_structures/dictionaries_and_arrays/squares_dictionary/Readme.md b/data_structures/dictionaries_and_arrays/squares_dictionary/Readme.md index 90b21fba..8b999808 100755 --- a/data_structures/dictionaries_and_arrays/squares_dictionary/Readme.md +++ b/data_structures/dictionaries_and_arrays/squares_dictionary/Readme.md @@ -1,20 +1,20 @@ -# Squares Dictionary - -# Motivation -Dictionaries are Python’s implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. - -You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). A colon (:) separates each key from its associated value: - -## Problem Description -Define a python function `squares_dict`, that consumes a positive integer, `n`, and returns a dictionary where the key-value pairs are of the form `x: x*x`, for all `x` between `1` to `n`. - -## Examples -``` -squares_dict(4) == {1: 1, 2: 4, 3: 9, 4: 16} -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Squares Dictionary + +# Motivation +Dictionaries are Python’s implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. + +You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). A colon (:) separates each key from its associated value: + +## Problem Description +Define a python function `squares_dict`, that consumes a positive integer, `n`, and returns a dictionary where the key-value pairs are of the form `x: x*x`, for all `x` between `1` to `n`. + +## Examples +``` +squares_dict(4) == {1: 1, 2: 4, 3: 9, 4: 16} +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/squares_dictionary/solution/solution.py b/data_structures/dictionaries_and_arrays/squares_dictionary/solution/solution.py index a517329c..bbb1e604 100755 --- a/data_structures/dictionaries_and_arrays/squares_dictionary/solution/solution.py +++ b/data_structures/dictionaries_and_arrays/squares_dictionary/solution/solution.py @@ -1,2 +1,2 @@ -def squares_dict(n): +def squares_dict(n): return {x: x*x for x in range(1, n+1)} \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/squares_dictionary/solution/test_solution.py b/data_structures/dictionaries_and_arrays/squares_dictionary/solution/test_solution.py index 3674ee28..ea94d8ce 100755 --- a/data_structures/dictionaries_and_arrays/squares_dictionary/solution/test_solution.py +++ b/data_structures/dictionaries_and_arrays/squares_dictionary/solution/test_solution.py @@ -1,6 +1,6 @@ -def test_solution(monkeypatch): - from solution import squares_dict - - assert squares_dict(3) == {1:1, 2: 4, 3: 9} - assert squares_dict(1) == {1:1} +def test_solution(monkeypatch): + from solution import squares_dict + + assert squares_dict(3) == {1:1, 2: 4, 3: 9} + assert squares_dict(1) == {1:1} assert squares_dict(4) == {1:1, 2: 4, 3: 9, 4: 16} \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/student_grades_dict/README.md b/data_structures/dictionaries_and_arrays/student_grades_dict/README.md index 513bd181..adfc50fb 100755 --- a/data_structures/dictionaries_and_arrays/student_grades_dict/README.md +++ b/data_structures/dictionaries_and_arrays/student_grades_dict/README.md @@ -1,26 +1,26 @@ -# Student Grades Dictionary - -# Motivation -Dictionaries are Python’s implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. - -You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). A colon (:) separates each key from its associated value: - -## Problem Description -Define a Python function `student_grades`, that consumes two dictionaries, `sgrades`, and `letter_grades`. `sgrades` will have strings representing the names of students as its keys and non-empty lists of integers between `1` and `100` representing the grades for that student in all their classes. `letter_grades` will be a dictionary with the key being a string, `A` to `F` and the value for each key being a tuple representing the range of values corresponding to that letter grade. Output a dictionary where the names of each student are the keys and the values in your new dictionary will be a tuple `(letter_grade, average)` where average is rounded to the nearest integer, for each student. - - -## Examples -``` -sgrades = {"Anton": [62, 55, 82], "Wasif": [100, 72, 94, 50], "Nell": [99, 100]} - -letter_grades = {"A": (90, 100), "B": (75, 89), "C": (60, 74), "D": (45, 59), "E": (30, 44), "F": (1, 29)} - -student_grades(sgrades, letter_grades) == -{"Anton": ("C", 66), "Wasif": ("B", 79), "Nell": ("A", 99)} -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Student Grades Dictionary + +# Motivation +Dictionaries are Python’s implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. + +You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). A colon (:) separates each key from its associated value: + +## Problem Description +Define a Python function `student_grades`, that consumes two dictionaries, `sgrades`, and `letter_grades`. `sgrades` will have strings representing the names of students as its keys and non-empty lists of integers between `1` and `100` representing the grades for that student in all their classes. `letter_grades` will be a dictionary with the key being a string, `A` to `F` and the value for each key being a tuple representing the range of values corresponding to that letter grade. Output a dictionary where the names of each student are the keys and the values in your new dictionary will be a tuple `(letter_grade, average)` where average is rounded to the nearest integer, for each student. + + +## Examples +``` +sgrades = {"Anton": [62, 55, 82], "Wasif": [100, 72, 94, 50], "Nell": [99, 100]} + +letter_grades = {"A": (90, 100), "B": (75, 89), "C": (60, 74), "D": (45, 59), "E": (30, 44), "F": (1, 29)} + +student_grades(sgrades, letter_grades) == +{"Anton": ("C", 66), "Wasif": ("B", 79), "Nell": ("A", 99)} +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/data_structures/dictionaries_and_arrays/student_grades_dict/solution/solution.py b/data_structures/dictionaries_and_arrays/student_grades_dict/solution/solution.py index 1e39d326..bfae3829 100755 --- a/data_structures/dictionaries_and_arrays/student_grades_dict/solution/solution.py +++ b/data_structures/dictionaries_and_arrays/student_grades_dict/solution/solution.py @@ -1,19 +1,19 @@ -def average(glst): - avg = 0 - for g in glst: - avg += g - return int(avg/len(glst)) - -def get_letter(avg, letter_grades): - for letter, grade_range in letter_grades.items(): - if avg in range(grade_range[0], grade_range[1]+1): - return letter - -def student_grades(sgrades, letter_grades): - ret_dict = {} - for name, grades in sgrades.items(): - avg = average(grades) - letter = get_letter(avg, letter_grades) - ret_dict[name] = (letter, avg) - return ret_dict +def average(glst): + avg = 0 + for g in glst: + avg += g + return int(avg/len(glst)) + +def get_letter(avg, letter_grades): + for letter, grade_range in letter_grades.items(): + if avg in range(grade_range[0], grade_range[1]+1): + return letter + +def student_grades(sgrades, letter_grades): + ret_dict = {} + for name, grades in sgrades.items(): + avg = average(grades) + letter = get_letter(avg, letter_grades) + ret_dict[name] = (letter, avg) + return ret_dict \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/student_grades_dict/solution/test_solution.py b/data_structures/dictionaries_and_arrays/student_grades_dict/solution/test_solution.py index c57b0257..9ed5e10b 100755 --- a/data_structures/dictionaries_and_arrays/student_grades_dict/solution/test_solution.py +++ b/data_structures/dictionaries_and_arrays/student_grades_dict/solution/test_solution.py @@ -1,12 +1,12 @@ -def test_solution(monkeypatch): - from solution import student_grades - letter_grades = {"A": (90, 100), "B": (75, 89), "C": (60, 74), "D": (45, 59), "E": (30, 44), "F": (1, 29)} - - sgrades1 = {"Anton": [62, 55, 82], "Wasif": [100, 72, 94, 50], "Nell": [99, 100]} - ret_val1 = {"Anton": ("C", 66), "Wasif": ("B", 79), "Nell": ("A", 99)} - - sgrades2 = {"Bob": [1, 30], "Sue": [35]} - ret_val2 = {"Bob": ("F", 15), "Sue": ("E", 35)} - - assert student_grades(sgrades1, letter_grades) == ret_val1 - assert student_grades(sgrades2, letter_grades) == ret_val2 +def test_solution(monkeypatch): + from solution import student_grades + letter_grades = {"A": (90, 100), "B": (75, 89), "C": (60, 74), "D": (45, 59), "E": (30, 44), "F": (1, 29)} + + sgrades1 = {"Anton": [62, 55, 82], "Wasif": [100, 72, 94, 50], "Nell": [99, 100]} + ret_val1 = {"Anton": ("C", 66), "Wasif": ("B", 79), "Nell": ("A", 99)} + + sgrades2 = {"Bob": [1, 30], "Sue": [35]} + ret_val2 = {"Bob": ("F", 15), "Sue": ("E", 35)} + + assert student_grades(sgrades1, letter_grades) == ret_val1 + assert student_grades(sgrades2, letter_grades) == ret_val2 diff --git a/data_structures/dictionaries_and_arrays/sum_imaginary/Readme.md b/data_structures/dictionaries_and_arrays/sum_imaginary/Readme.md index 7aef83a3..678ea3f0 100755 --- a/data_structures/dictionaries_and_arrays/sum_imaginary/Readme.md +++ b/data_structures/dictionaries_and_arrays/sum_imaginary/Readme.md @@ -1,17 +1,17 @@ -# Sum Imaginary Numbers - -## Problem Description -Define a Python function `sum_imaginary`, that consumes a list `ilst` of imaginary numbers represented as tuples of the form `(x,y) = x+yi`, and returns the sum of all the imaginary numbers in `ilst` as a tuple. -Hint: The sum of two imaginary numbers `a+bi + c+di = (a+c)+(b+d)i`. - -## Examples -``` -ilst = [(1,2), (4,-1), (0, 0), (-2, -2)] -sum_imginary(ilst) == (3,-1) -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Sum Imaginary Numbers + +## Problem Description +Define a Python function `sum_imaginary`, that consumes a list `ilst` of imaginary numbers represented as tuples of the form `(x,y) = x+yi`, and returns the sum of all the imaginary numbers in `ilst` as a tuple. +Hint: The sum of two imaginary numbers `a+bi + c+di = (a+c)+(b+d)i`. + +## Examples +``` +ilst = [(1,2), (4,-1), (0, 0), (-2, -2)] +sum_imginary(ilst) == (3,-1) +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/sum_imaginary/solution/solution.py b/data_structures/dictionaries_and_arrays/sum_imaginary/solution/solution.py index 615bc03a..854f370f 100755 --- a/data_structures/dictionaries_and_arrays/sum_imaginary/solution/solution.py +++ b/data_structures/dictionaries_and_arrays/sum_imaginary/solution/solution.py @@ -1,7 +1,7 @@ -def sum_imaginary(ilst): - real = 0 - img = 0 - for tup in ilst: - real += tup[0] - img += tup[1] +def sum_imaginary(ilst): + real = 0 + img = 0 + for tup in ilst: + real += tup[0] + img += tup[1] return (real, img) \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/sum_imaginary/solution/test_solution.py b/data_structures/dictionaries_and_arrays/sum_imaginary/solution/test_solution.py index 4af79816..8f56f518 100755 --- a/data_structures/dictionaries_and_arrays/sum_imaginary/solution/test_solution.py +++ b/data_structures/dictionaries_and_arrays/sum_imaginary/solution/test_solution.py @@ -1,6 +1,6 @@ -def test_solution(): - from solution import sum_imaginary - - assert sum_imaginary([(1,2), (4,-1), (0, 0), (-2, -2)]) == (3,-1) - assert sum_imaginary([(1,2)]) == (1,2) +def test_solution(): + from solution import sum_imaginary + + assert sum_imaginary([(1,2), (4,-1), (0, 0), (-2, -2)]) == (3,-1) + assert sum_imaginary([(1,2)]) == (1,2) assert sum_imaginary([]) == (0,0) \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/sum_tuples/Readme.md b/data_structures/dictionaries_and_arrays/sum_tuples/Readme.md index 6a3cf397..e41e4801 100755 --- a/data_structures/dictionaries_and_arrays/sum_tuples/Readme.md +++ b/data_structures/dictionaries_and_arrays/sum_tuples/Readme.md @@ -1,25 +1,25 @@ -# Sum Tuple Components - -# Motivation -A list is a container which can hold a collection of elements. - -Element − Each item stored in an array is called an element. - -Index − Each location of an element in an array has a numerical index, which is used to identify the element. - -A Tuple is an element of the form (x, y) which can be indexed like a list. - -## Problem Description -Define a Python function `sum_tuples` which consumes a list of tuples `tlst`, where the tuples are of the form `(x, y)` where `x` and `y` integers. The functions should returns a list of integers, where each integer is the sum of the `x` and `y` components in each tuple. - -## Examples -``` -tlst = [(4, 2), (5, 5), (-1, 2)] -sum_tuples(tlst) == [6, 10, 1] -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Sum Tuple Components + +# Motivation +A list is a container which can hold a collection of elements. + +Element − Each item stored in an array is called an element. + +Index − Each location of an element in an array has a numerical index, which is used to identify the element. + +A Tuple is an element of the form (x, y) which can be indexed like a list. + +## Problem Description +Define a Python function `sum_tuples` which consumes a list of tuples `tlst`, where the tuples are of the form `(x, y)` where `x` and `y` integers. The functions should returns a list of integers, where each integer is the sum of the `x` and `y` components in each tuple. + +## Examples +``` +tlst = [(4, 2), (5, 5), (-1, 2)] +sum_tuples(tlst) == [6, 10, 1] +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/sum_tuples/solution/solution.py b/data_structures/dictionaries_and_arrays/sum_tuples/solution/solution.py index b46fcfde..11afff16 100755 --- a/data_structures/dictionaries_and_arrays/sum_tuples/solution/solution.py +++ b/data_structures/dictionaries_and_arrays/sum_tuples/solution/solution.py @@ -1,2 +1,2 @@ -def sum_tuples(tlst): +def sum_tuples(tlst): return [t[0] + t[1] for t in tlst] \ No newline at end of file diff --git a/data_structures/dictionaries_and_arrays/sum_tuples/solution/test_solution.py b/data_structures/dictionaries_and_arrays/sum_tuples/solution/test_solution.py index 4cf087d8..204db877 100755 --- a/data_structures/dictionaries_and_arrays/sum_tuples/solution/test_solution.py +++ b/data_structures/dictionaries_and_arrays/sum_tuples/solution/test_solution.py @@ -1,6 +1,6 @@ -def test_solution(monkeypatch): - from solution import sum_tuples - - assert sum_tuples([(1,2), (3,4)]) == [3, 7] - assert sum_tuples([(-1,-2)]) == [-3] - assert sum_tuples([]) == [] +def test_solution(monkeypatch): + from solution import sum_tuples + + assert sum_tuples([(1,2), (3,4)]) == [3, 7] + assert sum_tuples([(-1,-2)]) == [-3] + assert sum_tuples([]) == [] diff --git a/data_structures/heaps/README.md b/data_structures/heaps/README.md index 0b28a0f2..eada5fcd 100644 --- a/data_structures/heaps/README.md +++ b/data_structures/heaps/README.md @@ -1,15 +1,15 @@ -# Exercises for heaps - - -| Exercise ID | Exercise | -|:-----------:|:--------:| -| easy_e1 | [Arbitary List To Heap](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/heaps/1_arbitary_list_to_heap) | -| easy_e2 | [Get Largest Int](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/heaps/1_get_largest_ints) | -| easy_e3 | [Get Smalled Int](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/heaps/1_get_smalled_ints) | -| easy_e4 | [Is Leaf Node](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/heaps/1_is_leaf_node) | -| medium_e1 | [Get Child Node](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/heaps/2_get_child_node) | -| medium_e2 | [Get Parent Node](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/heaps/2_get_parent_node) | -| hard_e1 | [Create Max Heap From Array](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/heaps/3_create_max_heap_from_array) | -| hard_e2 | [Create Min Heap From Array](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/heaps/3_create_min_geap_from_array) | -| hard_e3 | [Pop Item From Heap](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/heaps/3_pop_item_from_heap) | -| hard_e4 | [Push Item To Heap](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/heaps/3_push_item_to_heap) | +# Exercises for heaps + + +| Exercise ID | Exercise | +|:-----------:|:--------:| +| easy_e1 | [Arbitary List To Heap](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/heaps/1_arbitary_list_to_heap) | +| easy_e2 | [Get Largest Int](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/heaps/1_get_largest_ints) | +| easy_e3 | [Get Smalled Int](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/heaps/1_get_smalled_ints) | +| easy_e4 | [Is Leaf Node](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/heaps/1_is_leaf_node) | +| medium_e1 | [Get Child Node](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/heaps/2_get_child_node) | +| medium_e2 | [Get Parent Node](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/heaps/2_get_parent_node) | +| hard_e1 | [Create Max Heap From Array](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/heaps/3_create_max_heap_from_array) | +| hard_e2 | [Create Min Heap From Array](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/heaps/3_create_min_geap_from_array) | +| hard_e3 | [Pop Item From Heap](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/heaps/3_pop_item_from_heap) | +| hard_e4 | [Push Item To Heap](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/heaps/3_push_item_to_heap) | diff --git a/data_structures/heaps/complete_bin_tree/Readme.md b/data_structures/heaps/complete_bin_tree/Readme.md index 4010f540..f4b9ad05 100644 --- a/data_structures/heaps/complete_bin_tree/Readme.md +++ b/data_structures/heaps/complete_bin_tree/Readme.md @@ -1,48 +1,48 @@ -# Complete Binary Tree - -# Motivation -A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. -A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. -It is very useful when implementing priority queues where the queue item with higher weightage is given more priority in processing. - -``` -class Tree: - def __init__(self, root_node=None): - self.root_node = root_node - -class TreeNode: - def __init__(self, value, left=None, right=None): - self.value = value - self.left = left - self.right = right -``` - -## Problem Description -Given the definition for a Binary Tree. Define a python function `is_complete` that consumes an argument `tree` and returns `True` if `tree` is a complete binary tree and `False` otherwise. - - -## Example -``` - 7 - / \ - 3 6 - / \ / \ - 1 2 4 5 - -n1 = TreeNode(1) -n2 = TreeNode(2) -n3 = TreeNode(3, n1, n2) -n4 = TreeNode(4) -n5 = TreeNode(5) -n6 = TreeNode(6, n4, n5) -n7 = TreeNode(7, n3, n6) -tree = Tree(n7) - -is_complete(tree) == True -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Complete Binary Tree + +# Motivation +A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. +A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. +It is very useful when implementing priority queues where the queue item with higher weightage is given more priority in processing. + +``` +class Tree: + def __init__(self, root_node=None): + self.root_node = root_node + +class TreeNode: + def __init__(self, value, left=None, right=None): + self.value = value + self.left = left + self.right = right +``` + +## Problem Description +Given the definition for a Binary Tree. Define a python function `is_complete` that consumes an argument `tree` and returns `True` if `tree` is a complete binary tree and `False` otherwise. + + +## Example +``` + 7 + / \ + 3 6 + / \ / \ + 1 2 4 5 + +n1 = TreeNode(1) +n2 = TreeNode(2) +n3 = TreeNode(3, n1, n2) +n4 = TreeNode(4) +n5 = TreeNode(5) +n6 = TreeNode(6, n4, n5) +n7 = TreeNode(7, n3, n6) +tree = Tree(n7) + +is_complete(tree) == True +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/heaps/complete_bin_tree/solution/solution.py b/data_structures/heaps/complete_bin_tree/solution/solution.py index dcdb5457..4ce92074 100644 --- a/data_structures/heaps/complete_bin_tree/solution/solution.py +++ b/data_structures/heaps/complete_bin_tree/solution/solution.py @@ -1,37 +1,37 @@ -class Tree: - def __init__(self, root_node=None): - self.root_node = root_node - -class TreeNode: - def __init__(self, value, left=None, right=None): - self.value = value - self.left = left - self.right = right - -def is_complete(tree): - return is_complete_node(tree.root_node) - -def is_complete_node(treeNode): - if not treeNode: - return True - elif not treeNode.left and not treeNode.right: - return True - elif treeNode.left and treeNode.right: - return is_complete_node(treeNode.left) and is_complete_node(treeNode.right) - elif treeNode.left: - return is_complete_node(treeNode.left) - elif treeNode.right: - return False - else: - return False - -n1 = TreeNode(1) -n2 = TreeNode(2) -n3 = TreeNode(3, n1, n2) -n4 = TreeNode(4) -n5 = TreeNode(5) -n6 = TreeNode(6, n4, n5) -n7 = TreeNode(7, n3, n6) -tree = Tree(n7) - +class Tree: + def __init__(self, root_node=None): + self.root_node = root_node + +class TreeNode: + def __init__(self, value, left=None, right=None): + self.value = value + self.left = left + self.right = right + +def is_complete(tree): + return is_complete_node(tree.root_node) + +def is_complete_node(treeNode): + if not treeNode: + return True + elif not treeNode.left and not treeNode.right: + return True + elif treeNode.left and treeNode.right: + return is_complete_node(treeNode.left) and is_complete_node(treeNode.right) + elif treeNode.left: + return is_complete_node(treeNode.left) + elif treeNode.right: + return False + else: + return False + +n1 = TreeNode(1) +n2 = TreeNode(2) +n3 = TreeNode(3, n1, n2) +n4 = TreeNode(4) +n5 = TreeNode(5) +n6 = TreeNode(6, n4, n5) +n7 = TreeNode(7, n3, n6) +tree = Tree(n7) + print(is_complete(tree)) \ No newline at end of file diff --git a/data_structures/heaps/complete_bin_tree/solution/test_solution.py b/data_structures/heaps/complete_bin_tree/solution/test_solution.py index e9cf3621..b398c112 100644 --- a/data_structures/heaps/complete_bin_tree/solution/test_solution.py +++ b/data_structures/heaps/complete_bin_tree/solution/test_solution.py @@ -1,25 +1,25 @@ -def test_solution(): - from solution import Tree, TreeNode, is_complete - - n1 = TreeNode(1) - n2 = TreeNode(2) - n3 = TreeNode(3, n1, n2) - n4 = TreeNode(4) - n5 = TreeNode(5) - n6 = TreeNode(6, n4, n5) - n7 = TreeNode(7, n3, n6) - tree1 = Tree(n7) - - m1 = TreeNode(1) - m3 = TreeNode(3, m1, None) - tree2 = Tree(m3) - - p1 = TreeNode(1) - p3 = TreeNode(3, None, p1) - tree4 = Tree(p3) - - tree3 = Tree() - assert is_complete(tree1) == True - assert is_complete(tree2) == True - assert is_complete(tree3) == True +def test_solution(): + from solution import Tree, TreeNode, is_complete + + n1 = TreeNode(1) + n2 = TreeNode(2) + n3 = TreeNode(3, n1, n2) + n4 = TreeNode(4) + n5 = TreeNode(5) + n6 = TreeNode(6, n4, n5) + n7 = TreeNode(7, n3, n6) + tree1 = Tree(n7) + + m1 = TreeNode(1) + m3 = TreeNode(3, m1, None) + tree2 = Tree(m3) + + p1 = TreeNode(1) + p3 = TreeNode(3, None, p1) + tree4 = Tree(p3) + + tree3 = Tree() + assert is_complete(tree1) == True + assert is_complete(tree2) == True + assert is_complete(tree3) == True assert is_complete(tree4) == False \ No newline at end of file diff --git a/data_structures/heaps/convert_to_max_heap/Readme.md b/data_structures/heaps/convert_to_max_heap/Readme.md index 1ea2965a..1b076284 100644 --- a/data_structures/heaps/convert_to_max_heap/Readme.md +++ b/data_structures/heaps/convert_to_max_heap/Readme.md @@ -1,37 +1,37 @@ -# Convert to Max Heap - -# Motivation -A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. -A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. -It is very useful when implementing priority queues where the queue item with higher weightage is given more priority in processing. - - -## Problem Description -Define a python function `convert_to_maxHeap` that consumes an argument `tree`, a complete binary tree, and converts `tree` to a max heap and return the heap. Add nodes one at a time to your min heap using a preorder traversal of `tree`. - - -## Example -``` - 7 - / \ - 3 6 - / \ / \ - 1 2 4 5 - -n1 = TreeNode(1) -n2 = TreeNode(2) -n3 = TreeNode(3, n1, n2) -n4 = TreeNode(4) -n5 = TreeNode(5) -n6 = TreeNode(6, n4, n5) -n7 = TreeNode(7, n3, n6) -tree = Tree(n7) - -convert_to_maxHeap(tree) == MaxHeap([7, 6, 5, 2, 3, 1, 4]) -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Convert to Max Heap + +# Motivation +A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. +A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. +It is very useful when implementing priority queues where the queue item with higher weightage is given more priority in processing. + + +## Problem Description +Define a python function `convert_to_maxHeap` that consumes an argument `tree`, a complete binary tree, and converts `tree` to a max heap and return the heap. Add nodes one at a time to your min heap using a preorder traversal of `tree`. + + +## Example +``` + 7 + / \ + 3 6 + / \ / \ + 1 2 4 5 + +n1 = TreeNode(1) +n2 = TreeNode(2) +n3 = TreeNode(3, n1, n2) +n4 = TreeNode(4) +n5 = TreeNode(5) +n6 = TreeNode(6, n4, n5) +n7 = TreeNode(7, n3, n6) +tree = Tree(n7) + +convert_to_maxHeap(tree) == MaxHeap([7, 6, 5, 2, 3, 1, 4]) +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/heaps/convert_to_max_heap/solution/solution.py b/data_structures/heaps/convert_to_max_heap/solution/solution.py index 4b75a18e..a8c4b79b 100644 --- a/data_structures/heaps/convert_to_max_heap/solution/solution.py +++ b/data_structures/heaps/convert_to_max_heap/solution/solution.py @@ -1,62 +1,62 @@ -class Tree: - def __init__(self, root_node=None): - self.root_node = root_node - -class TreeNode: - def __init__(self, value, left=None, right=None): - self.value = value - self.left = left - self.right = right - -class MaxHeap: - def __init__(self): - self._heap = [] - - def __str__(self): - return str(self._heap) - - def _is_valid_index(self, index): - if 0 <= index and index < len(self._heap): - return True - return False - - def _swap_nodes(self, index1, index2): - self._heap[index1], self._heap[index2] = self._heap[index2], self._heap[index1] - - def push(self, value): - self._heap.append(value) - self._sift_up(len(self._heap) - 1) - - def _sift_up(self, index): - parent_index = (index-1) // 2 - if self._is_valid_index(parent_index) and self._heap[index] > self._heap[parent_index]: - self._swap_nodes(index, parent_index) - self._sift_up(parent_index) - - -def convert_to_array_nodes(treeNode): - if not treeNode: - return [] - return [treeNode.value] + convert_to_array_nodes(treeNode.left) + convert_to_array_nodes(treeNode.right) - -def convert_to_maxHeap(tree): - mheap = MaxHeap() - if not tree: - return mheap - nodeList = convert_to_array_nodes(tree.root_node) - for n in nodeList: - mheap.push(n) - return mheap - - -n1 = TreeNode(1) -n2 = TreeNode(2) -n3 = TreeNode(3, n1, n2) -n4 = TreeNode(4) -n5 = TreeNode(5) -n6 = TreeNode(6, n4, n5) -n7 = TreeNode(7, n3, n6) -tree = Tree(n7) - -print(convert_to_maxHeap(tree)) +class Tree: + def __init__(self, root_node=None): + self.root_node = root_node + +class TreeNode: + def __init__(self, value, left=None, right=None): + self.value = value + self.left = left + self.right = right + +class MaxHeap: + def __init__(self): + self._heap = [] + + def __str__(self): + return str(self._heap) + + def _is_valid_index(self, index): + if 0 <= index and index < len(self._heap): + return True + return False + + def _swap_nodes(self, index1, index2): + self._heap[index1], self._heap[index2] = self._heap[index2], self._heap[index1] + + def push(self, value): + self._heap.append(value) + self._sift_up(len(self._heap) - 1) + + def _sift_up(self, index): + parent_index = (index-1) // 2 + if self._is_valid_index(parent_index) and self._heap[index] > self._heap[parent_index]: + self._swap_nodes(index, parent_index) + self._sift_up(parent_index) + + +def convert_to_array_nodes(treeNode): + if not treeNode: + return [] + return [treeNode.value] + convert_to_array_nodes(treeNode.left) + convert_to_array_nodes(treeNode.right) + +def convert_to_maxHeap(tree): + mheap = MaxHeap() + if not tree: + return mheap + nodeList = convert_to_array_nodes(tree.root_node) + for n in nodeList: + mheap.push(n) + return mheap + + +n1 = TreeNode(1) +n2 = TreeNode(2) +n3 = TreeNode(3, n1, n2) +n4 = TreeNode(4) +n5 = TreeNode(5) +n6 = TreeNode(6, n4, n5) +n7 = TreeNode(7, n3, n6) +tree = Tree(n7) + +print(convert_to_maxHeap(tree)) \ No newline at end of file diff --git a/data_structures/heaps/convert_to_max_heap/solution/test_solution.py b/data_structures/heaps/convert_to_max_heap/solution/test_solution.py index dd137218..b17d25cb 100644 --- a/data_structures/heaps/convert_to_max_heap/solution/test_solution.py +++ b/data_structures/heaps/convert_to_max_heap/solution/test_solution.py @@ -1,21 +1,21 @@ -def test_solution(): - from solution import Tree, TreeNode, MaxHeap, convert_to_maxHeap - - n1 = TreeNode(1) - n2 = TreeNode(2) - n3 = TreeNode(3, n1, n2) - n4 = TreeNode(4) - n5 = TreeNode(5) - n6 = TreeNode(6, n4, n5) - n7 = TreeNode(7, n3, n6) - tree1 = Tree(n7) - - - m1 = TreeNode(1) - m3 = TreeNode(3, m1, None) - tree2 = Tree(m3) - - tree3 = Tree() - assert convert_to_maxHeap(tree1)._heap == [7, 6, 5, 2, 3, 1, 4] - assert convert_to_maxHeap(tree2)._heap == [3, 1] +def test_solution(): + from solution import Tree, TreeNode, MaxHeap, convert_to_maxHeap + + n1 = TreeNode(1) + n2 = TreeNode(2) + n3 = TreeNode(3, n1, n2) + n4 = TreeNode(4) + n5 = TreeNode(5) + n6 = TreeNode(6, n4, n5) + n7 = TreeNode(7, n3, n6) + tree1 = Tree(n7) + + + m1 = TreeNode(1) + m3 = TreeNode(3, m1, None) + tree2 = Tree(m3) + + tree3 = Tree() + assert convert_to_maxHeap(tree1)._heap == [7, 6, 5, 2, 3, 1, 4] + assert convert_to_maxHeap(tree2)._heap == [3, 1] assert convert_to_maxHeap(tree3)._heap == [] \ No newline at end of file diff --git a/data_structures/heaps/convert_to_min_heap/Readme.md b/data_structures/heaps/convert_to_min_heap/Readme.md index 12a3bf5f..034ff3e7 100644 --- a/data_structures/heaps/convert_to_min_heap/Readme.md +++ b/data_structures/heaps/convert_to_min_heap/Readme.md @@ -1,37 +1,37 @@ -# Convert to Min Heap - -# Motivation -A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. -A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. -It is very useful when implementing priority queues where the queue item with higher weightage is given more priority in processing. - - -## Problem Description -Define a python function `convert_to_minHeap` that consumes an argument `tree`, a complete binary tree, and converts `tree` to a min heap and return the heap. Add nodes one at a time to your min heap using a preorder traversal of `tree`. - - -## Example -``` - 7 - / \ - 3 6 - / \ / \ - 1 2 4 5 - -n1 = TreeNode(1) -n2 = TreeNode(2) -n3 = TreeNode(3, n1, n2) -n4 = TreeNode(4) -n5 = TreeNode(5) -n6 = TreeNode(6, n4, n5) -n7 = TreeNode(7, n3, n6) -tree = Tree(n7) - -convert_to_minHeap(tree) == MinHeap([1, 2, 3, 7, 6, 4, 5]) -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Convert to Min Heap + +# Motivation +A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. +A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. +It is very useful when implementing priority queues where the queue item with higher weightage is given more priority in processing. + + +## Problem Description +Define a python function `convert_to_minHeap` that consumes an argument `tree`, a complete binary tree, and converts `tree` to a min heap and return the heap. Add nodes one at a time to your min heap using a preorder traversal of `tree`. + + +## Example +``` + 7 + / \ + 3 6 + / \ / \ + 1 2 4 5 + +n1 = TreeNode(1) +n2 = TreeNode(2) +n3 = TreeNode(3, n1, n2) +n4 = TreeNode(4) +n5 = TreeNode(5) +n6 = TreeNode(6, n4, n5) +n7 = TreeNode(7, n3, n6) +tree = Tree(n7) + +convert_to_minHeap(tree) == MinHeap([1, 2, 3, 7, 6, 4, 5]) +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/heaps/convert_to_min_heap/solution/solution.py b/data_structures/heaps/convert_to_min_heap/solution/solution.py index a7b52ac6..87eced25 100644 --- a/data_structures/heaps/convert_to_min_heap/solution/solution.py +++ b/data_structures/heaps/convert_to_min_heap/solution/solution.py @@ -1,60 +1,60 @@ -class Tree: - def __init__(self, root_node=None): - self.root_node = root_node - -class TreeNode: - def __init__(self, value, left=None, right=None): - self.value = value - self.left = left - self.right = right - -class MinHeap: - def __init__(self): - self._heap = [] - - def __str__(self): - return str(self._heap) - - def _is_valid_index(self, index): - if 0 <= index and index < len(self._heap): - return True - return False - - def _swap_nodes(self, index1, index2): - self._heap[index1], self._heap[index2] = self._heap[index2], self._heap[index1] - - def push(self, value): - self._heap.append(value) - self._sift_up(len(self._heap) - 1) - - def _sift_up(self, index): - parent_index = (index-1) // 2 - if self._is_valid_index(parent_index) and self._heap[index] < self._heap[parent_index]: - self._swap_nodes(index, parent_index) - self._sift_up(parent_index) - -def convert_to_array_nodes(treeNode): - if not treeNode: - return [] - return [treeNode.value] + convert_to_array_nodes(treeNode.left) + convert_to_array_nodes(treeNode.right) - -def convert_to_minHeap(tree): - mheap = MinHeap() - if not tree: - return mheap - nodeList = convert_to_array_nodes(tree.root_node) - for n in nodeList: - mheap.push(n) - return mheap - - -n1 = TreeNode(1) -n2 = TreeNode(2) -n3 = TreeNode(3, n1, n2) -n4 = TreeNode(4) -n5 = TreeNode(5) -n6 = TreeNode(6, n4, n5) -n7 = TreeNode(7, n3, n6) -tree = Tree(n7) - +class Tree: + def __init__(self, root_node=None): + self.root_node = root_node + +class TreeNode: + def __init__(self, value, left=None, right=None): + self.value = value + self.left = left + self.right = right + +class MinHeap: + def __init__(self): + self._heap = [] + + def __str__(self): + return str(self._heap) + + def _is_valid_index(self, index): + if 0 <= index and index < len(self._heap): + return True + return False + + def _swap_nodes(self, index1, index2): + self._heap[index1], self._heap[index2] = self._heap[index2], self._heap[index1] + + def push(self, value): + self._heap.append(value) + self._sift_up(len(self._heap) - 1) + + def _sift_up(self, index): + parent_index = (index-1) // 2 + if self._is_valid_index(parent_index) and self._heap[index] < self._heap[parent_index]: + self._swap_nodes(index, parent_index) + self._sift_up(parent_index) + +def convert_to_array_nodes(treeNode): + if not treeNode: + return [] + return [treeNode.value] + convert_to_array_nodes(treeNode.left) + convert_to_array_nodes(treeNode.right) + +def convert_to_minHeap(tree): + mheap = MinHeap() + if not tree: + return mheap + nodeList = convert_to_array_nodes(tree.root_node) + for n in nodeList: + mheap.push(n) + return mheap + + +n1 = TreeNode(1) +n2 = TreeNode(2) +n3 = TreeNode(3, n1, n2) +n4 = TreeNode(4) +n5 = TreeNode(5) +n6 = TreeNode(6, n4, n5) +n7 = TreeNode(7, n3, n6) +tree = Tree(n7) + print(convert_to_minHeap(tree)) \ No newline at end of file diff --git a/data_structures/heaps/convert_to_min_heap/solution/test_solution.py b/data_structures/heaps/convert_to_min_heap/solution/test_solution.py index f1c7d49d..b644091a 100644 --- a/data_structures/heaps/convert_to_min_heap/solution/test_solution.py +++ b/data_structures/heaps/convert_to_min_heap/solution/test_solution.py @@ -1,20 +1,20 @@ -def test_solution(): - from solution import Tree, TreeNode, MinHeap, convert_to_minHeap - - n1 = TreeNode(1) - n2 = TreeNode(2) - n3 = TreeNode(3, n1, n2) - n4 = TreeNode(4) - n5 = TreeNode(5) - n6 = TreeNode(6, n4, n5) - n7 = TreeNode(7, n3, n6) - tree1 = Tree(n7) - - m1 = TreeNode(1) - m3 = TreeNode(3, m1, None) - tree2 = Tree(m3) - - tree3 = Tree() - assert convert_to_minHeap(tree1)._heap == [1, 2, 3, 7, 6, 4, 5] - assert convert_to_minHeap(tree2)._heap == [1, 3] +def test_solution(): + from solution import Tree, TreeNode, MinHeap, convert_to_minHeap + + n1 = TreeNode(1) + n2 = TreeNode(2) + n3 = TreeNode(3, n1, n2) + n4 = TreeNode(4) + n5 = TreeNode(5) + n6 = TreeNode(6, n4, n5) + n7 = TreeNode(7, n3, n6) + tree1 = Tree(n7) + + m1 = TreeNode(1) + m3 = TreeNode(3, m1, None) + tree2 = Tree(m3) + + tree3 = Tree() + assert convert_to_minHeap(tree1)._heap == [1, 2, 3, 7, 6, 4, 5] + assert convert_to_minHeap(tree2)._heap == [1, 3] assert convert_to_minHeap(tree3)._heap == [] \ No newline at end of file diff --git a/data_structures/heaps/find_kth_largest/Readme.md b/data_structures/heaps/find_kth_largest/Readme.md index 2c2b246a..962d9c35 100644 --- a/data_structures/heaps/find_kth_largest/Readme.md +++ b/data_structures/heaps/find_kth_largest/Readme.md @@ -1,22 +1,22 @@ -# Find Median of a List - -# Motivation -A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. -A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. -It is very useful when implementing priority queues where the queue item with higher weightage is given more priority in processing. - -## Problem Description -Define a python function `find_kth_largest` that consumes an argument `lst`, a non-empty unsorted list of integers, and an positive integer `k`, where `k <= len(lst)`, and using a MinHeap, return the `kth` largest value in `lst`. - - -## Example -``` -find_kth_largest([1, 2, 7, 6, 4], 2) == 6 -find_kth_largest([1, 2, 5, 4, 9], 3) == 4 -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Find Median of a List + +# Motivation +A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. +A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. +It is very useful when implementing priority queues where the queue item with higher weightage is given more priority in processing. + +## Problem Description +Define a python function `find_kth_largest` that consumes an argument `lst`, a non-empty unsorted list of integers, and an positive integer `k`, where `k <= len(lst)`, and using a MinHeap, return the `kth` largest value in `lst`. + + +## Example +``` +find_kth_largest([1, 2, 7, 6, 4], 2) == 6 +find_kth_largest([1, 2, 5, 4, 9], 3) == 4 +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/heaps/find_kth_largest/solution/solution.py b/data_structures/heaps/find_kth_largest/solution/solution.py index 7110ff83..f85e96f4 100644 --- a/data_structures/heaps/find_kth_largest/solution/solution.py +++ b/data_structures/heaps/find_kth_largest/solution/solution.py @@ -1,64 +1,64 @@ -class MinHeap: - def __init__(self): - self._heap = [] - - def __str__(self): - return str(self._heap) - - def _is_valid_index(self, index): - if 0 <= index and index < len(self._heap): - return True - return False - - def _swap_nodes(self, index1, index2): - self._heap[index1], self._heap[index2] = self._heap[index2], self._heap[index1] - - def push(self, value): - self._heap.append(value) - self._sift_up(len(self._heap) - 1) - - def _sift_up(self, index): - parent_index = (index-1) // 2 - if self._is_valid_index(parent_index) and self._heap[index] < self._heap[parent_index]: - self._swap_nodes(index, parent_index) - self._sift_up(parent_index) - - def pop_min(self): - if not self._heap: - raise IndexError("Tried to pop an empty MinHeap") - self._swap_nodes(0, -1) - min_value = self._heap.pop() - self._sift_down(0) - return min_value - - def _sift_down(self, index): - left_child_index = 2*index + 1 - right_child_index = 2*index + 2 - if self._is_valid_index(right_child_index): - if self._heap[left_child_index] < self._heap[right_child_index]: - smallest_child_index = left_child_index - else: - smallest_child_index = right_child_index - elif self._is_valid_index(left_child_index): - smallest_child_index = left_child_index - else: - return - if self._heap[smallest_child_index] < self._heap[index]: - self._swap_nodes(smallest_child_index, index) - self._sift_down(smallest_child_index) - return - -def find_kth_largest(lst, k): - mheap = MinHeap() - for i in range(k): - print(lst[i]) - mheap.push(lst[i]) - for i in range(k, len(lst)): - print(lst[i]) - if lst[i] > mheap._heap[0]: - mheap.pop_min() - mheap.push(lst[i]) - print(mheap._heap) - return mheap._heap[0] - +class MinHeap: + def __init__(self): + self._heap = [] + + def __str__(self): + return str(self._heap) + + def _is_valid_index(self, index): + if 0 <= index and index < len(self._heap): + return True + return False + + def _swap_nodes(self, index1, index2): + self._heap[index1], self._heap[index2] = self._heap[index2], self._heap[index1] + + def push(self, value): + self._heap.append(value) + self._sift_up(len(self._heap) - 1) + + def _sift_up(self, index): + parent_index = (index-1) // 2 + if self._is_valid_index(parent_index) and self._heap[index] < self._heap[parent_index]: + self._swap_nodes(index, parent_index) + self._sift_up(parent_index) + + def pop_min(self): + if not self._heap: + raise IndexError("Tried to pop an empty MinHeap") + self._swap_nodes(0, -1) + min_value = self._heap.pop() + self._sift_down(0) + return min_value + + def _sift_down(self, index): + left_child_index = 2*index + 1 + right_child_index = 2*index + 2 + if self._is_valid_index(right_child_index): + if self._heap[left_child_index] < self._heap[right_child_index]: + smallest_child_index = left_child_index + else: + smallest_child_index = right_child_index + elif self._is_valid_index(left_child_index): + smallest_child_index = left_child_index + else: + return + if self._heap[smallest_child_index] < self._heap[index]: + self._swap_nodes(smallest_child_index, index) + self._sift_down(smallest_child_index) + return + +def find_kth_largest(lst, k): + mheap = MinHeap() + for i in range(k): + print(lst[i]) + mheap.push(lst[i]) + for i in range(k, len(lst)): + print(lst[i]) + if lst[i] > mheap._heap[0]: + mheap.pop_min() + mheap.push(lst[i]) + print(mheap._heap) + return mheap._heap[0] + print(find_kth_largest([1, 2], 2)) \ No newline at end of file diff --git a/data_structures/heaps/find_kth_largest/solution/test_solution.py b/data_structures/heaps/find_kth_largest/solution/test_solution.py index 46e75aee..a595cd01 100644 --- a/data_structures/heaps/find_kth_largest/solution/test_solution.py +++ b/data_structures/heaps/find_kth_largest/solution/test_solution.py @@ -1,5 +1,5 @@ -def test_solution(): - from solution import find_kth_largest - assert find_kth_largest([1, 2, 7, 6, 4], 2) == 6 - assert find_kth_largest([1, 2], 2) == 1 +def test_solution(): + from solution import find_kth_largest + assert find_kth_largest([1, 2, 7, 6, 4], 2) == 6 + assert find_kth_largest([1, 2], 2) == 1 assert find_kth_largest([7, 1, 2, 9], 1) == 9 \ No newline at end of file diff --git a/data_structures/heaps/find_median/Readme.md b/data_structures/heaps/find_median/Readme.md index 3e7dbed7..ed0a8d9a 100644 --- a/data_structures/heaps/find_median/Readme.md +++ b/data_structures/heaps/find_median/Readme.md @@ -1,22 +1,22 @@ -# Find Median of a List - -# Motivation -A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. -A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. -It is very useful when implementing priority queues where the queue item with higher weightage is given more priority in processing. - -## Problem Description -Define a python function `find_median` that consumes an argument `lst`, a non-empty unsorted list of integers, and using a MinHeap, return the median of `lst`. If the length of `lst` is even, return the larger of the two values. - - -## Example -``` -find_median([1, 2, 3, 7, 6, 4, 5]) == 4 -find_median([5, 1]) == 5 -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Find Median of a List + +# Motivation +A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. +A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. +It is very useful when implementing priority queues where the queue item with higher weightage is given more priority in processing. + +## Problem Description +Define a python function `find_median` that consumes an argument `lst`, a non-empty unsorted list of integers, and using a MinHeap, return the median of `lst`. If the length of `lst` is even, return the larger of the two values. + + +## Example +``` +find_median([1, 2, 3, 7, 6, 4, 5]) == 4 +find_median([5, 1]) == 5 +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/heaps/find_median/solution/solution.py b/data_structures/heaps/find_median/solution/solution.py index c3d7abbb..715db8fe 100644 --- a/data_structures/heaps/find_median/solution/solution.py +++ b/data_structures/heaps/find_median/solution/solution.py @@ -1,59 +1,59 @@ -class MinHeap: - def __init__(self): - self._heap = [] - - def __str__(self): - return str(self._heap) - - def _is_valid_index(self, index): - if 0 <= index and index < len(self._heap): - return True - return False - - def _swap_nodes(self, index1, index2): - self._heap[index1], self._heap[index2] = self._heap[index2], self._heap[index1] - - def push(self, value): - self._heap.append(value) - self._sift_up(len(self._heap) - 1) - - def _sift_up(self, index): - parent_index = (index-1) // 2 - if self._is_valid_index(parent_index) and self._heap[index] < self._heap[parent_index]: - self._swap_nodes(index, parent_index) - self._sift_up(parent_index) - - def pop_min(self): - if not self._heap: - raise IndexError("Tried to pop an empty MinHeap") - self._swap_nodes(0, -1) - min_value = self._heap.pop() - self._sift_down(0) - return min_value - - def _sift_down(self, index): - left_child_index = 2*index + 1 - right_child_index = 2*index + 2 - if self._is_valid_index(right_child_index): - if self._heap[left_child_index] < self._heap[right_child_index]: - smallest_child_index = left_child_index - else: - smallest_child_index = right_child_index - elif self._is_valid_index(left_child_index): - smallest_child_index = left_child_index - else: - return - if self._heap[smallest_child_index] < self._heap[index]: - self._swap_nodes(smallest_child_index, index) - self._sift_down(smallest_child_index) - return - -def find_median(lst): - mheap = MinHeap() - for i in lst: - mheap.push(i) - for i in range(0,len(lst)//2): - mheap.pop_min() - return mheap.pop_min() - +class MinHeap: + def __init__(self): + self._heap = [] + + def __str__(self): + return str(self._heap) + + def _is_valid_index(self, index): + if 0 <= index and index < len(self._heap): + return True + return False + + def _swap_nodes(self, index1, index2): + self._heap[index1], self._heap[index2] = self._heap[index2], self._heap[index1] + + def push(self, value): + self._heap.append(value) + self._sift_up(len(self._heap) - 1) + + def _sift_up(self, index): + parent_index = (index-1) // 2 + if self._is_valid_index(parent_index) and self._heap[index] < self._heap[parent_index]: + self._swap_nodes(index, parent_index) + self._sift_up(parent_index) + + def pop_min(self): + if not self._heap: + raise IndexError("Tried to pop an empty MinHeap") + self._swap_nodes(0, -1) + min_value = self._heap.pop() + self._sift_down(0) + return min_value + + def _sift_down(self, index): + left_child_index = 2*index + 1 + right_child_index = 2*index + 2 + if self._is_valid_index(right_child_index): + if self._heap[left_child_index] < self._heap[right_child_index]: + smallest_child_index = left_child_index + else: + smallest_child_index = right_child_index + elif self._is_valid_index(left_child_index): + smallest_child_index = left_child_index + else: + return + if self._heap[smallest_child_index] < self._heap[index]: + self._swap_nodes(smallest_child_index, index) + self._sift_down(smallest_child_index) + return + +def find_median(lst): + mheap = MinHeap() + for i in lst: + mheap.push(i) + for i in range(0,len(lst)//2): + mheap.pop_min() + return mheap.pop_min() + print(find_median([1, 2, 3, 7, 6, 4, 5])) \ No newline at end of file diff --git a/data_structures/heaps/find_median/solution/test_solution.py b/data_structures/heaps/find_median/solution/test_solution.py index 75b7504d..8e6c4c17 100644 --- a/data_structures/heaps/find_median/solution/test_solution.py +++ b/data_structures/heaps/find_median/solution/test_solution.py @@ -1,5 +1,5 @@ -def test_solution(): - from solution import find_median - assert find_median([1, 2, 3, 7, 6, 4, 5]) == 4 - assert find_median([1]) == 1 +def test_solution(): + from solution import find_median + assert find_median([1, 2, 3, 7, 6, 4, 5]) == 4 + assert find_median([1]) == 1 assert find_median([1,2]) == 2 \ No newline at end of file diff --git a/data_structures/heaps/get_child_nodes/Readme.md b/data_structures/heaps/get_child_nodes/Readme.md index 9a446e8b..8de166f2 100644 --- a/data_structures/heaps/get_child_nodes/Readme.md +++ b/data_structures/heaps/get_child_nodes/Readme.md @@ -1,19 +1,19 @@ -# Get the Value of Child Nodes - -# Motivation -A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. -A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. -It is very useful is implementing priority queues where the queue item with higher weightage is given more priority in processing. - -## Problem Description -Given a Heap, define a python function `get_child_nodes` that consumes two arguments `heap`, a heap array, and `index` that returns the values of the children as a list `[left_child, right_child]` of the node at `index`. If `index` is not a valid index in the list return an empty list. If the node at `index` only has one child or no children, the list should just contain the one element or no elements respectively. - -## Example -``` -get_child_nodes([2, 3, 4, 5, 10], 0) == [3, 4] -get_child_nodes([2, 3, 4, 5, 10], 3) == [] -get_child_nodes([2, 3, 4, 5, 10, 11], 2) == [11] -``` - -## Submission +# Get the Value of Child Nodes + +# Motivation +A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. +A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. +It is very useful is implementing priority queues where the queue item with higher weightage is given more priority in processing. + +## Problem Description +Given a Heap, define a python function `get_child_nodes` that consumes two arguments `heap`, a heap array, and `index` that returns the values of the children as a list `[left_child, right_child]` of the node at `index`. If `index` is not a valid index in the list return an empty list. If the node at `index` only has one child or no children, the list should just contain the one element or no elements respectively. + +## Example +``` +get_child_nodes([2, 3, 4, 5, 10], 0) == [3, 4] +get_child_nodes([2, 3, 4, 5, 10], 3) == [] +get_child_nodes([2, 3, 4, 5, 10, 11], 2) == [11] +``` + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/heaps/get_child_nodes/solution/solution.py b/data_structures/heaps/get_child_nodes/solution/solution.py index b94fe0c6..552ddc94 100644 --- a/data_structures/heaps/get_child_nodes/solution/solution.py +++ b/data_structures/heaps/get_child_nodes/solution/solution.py @@ -1,9 +1,9 @@ -def get_child_nodes(heap, index): - left_idx = index*2 + 1 - right_idx = index*2 + 2 - child_lst = [] - if left_idx < len(heap): - child_lst.append(heap[left_idx]) - if right_idx < len(heap): - child_lst.append(heap[right_idx]) +def get_child_nodes(heap, index): + left_idx = index*2 + 1 + right_idx = index*2 + 2 + child_lst = [] + if left_idx < len(heap): + child_lst.append(heap[left_idx]) + if right_idx < len(heap): + child_lst.append(heap[right_idx]) return child_lst \ No newline at end of file diff --git a/data_structures/heaps/get_child_nodes/solution/test_solution.py b/data_structures/heaps/get_child_nodes/solution/test_solution.py index 5b5318d2..9652bcb1 100644 --- a/data_structures/heaps/get_child_nodes/solution/test_solution.py +++ b/data_structures/heaps/get_child_nodes/solution/test_solution.py @@ -1,6 +1,6 @@ -def test_solution(): - from solution import get_child_nodes - assert get_child_nodes([2, 3, 4, 5, 10], 0) == [3, 4] - assert get_child_nodes([2, 3, 4, 5, 10], 3) == [] - assert get_child_nodes([2, 3, 4, 5, 10, 11], 2) == [11] +def test_solution(): + from solution import get_child_nodes + assert get_child_nodes([2, 3, 4, 5, 10], 0) == [3, 4] + assert get_child_nodes([2, 3, 4, 5, 10], 3) == [] + assert get_child_nodes([2, 3, 4, 5, 10, 11], 2) == [11] assert get_child_nodes([], 2) == [] \ No newline at end of file diff --git a/data_structures/heaps/get_parent_node/Readme.md b/data_structures/heaps/get_parent_node/Readme.md index 8f380f14..06bcdae1 100644 --- a/data_structures/heaps/get_parent_node/Readme.md +++ b/data_structures/heaps/get_parent_node/Readme.md @@ -1,20 +1,20 @@ -# Get Value of Parent Node - -# Motivation -A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. -A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. -It is very useful is implementing priority queues where the queue item with higher weightage is given more priority in processing. - -## Problem Description -Given a Heap, Define a python function `get_parent_node` that consumes two arguments `heap`, a heap array, and `index` that returns the value of parent node for the node at the given `index`. If `index` is the root node, return the value of the root. If `index` is not a valid index in the list return the string `"{index} is not a valid index in the heap"` where `{index}` is replaced by the number `index`. - - -## Example -``` -get_parent_node([2,3,4,5,10], 4) == 3 -get_parent_node([2,3,4,5,10], 0) == 2 -get_parent_node([2,3,4,5,10], 5) == "5 is not a valid index in the heap" -``` - -## Submission +# Get Value of Parent Node + +# Motivation +A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. +A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. +It is very useful is implementing priority queues where the queue item with higher weightage is given more priority in processing. + +## Problem Description +Given a Heap, Define a python function `get_parent_node` that consumes two arguments `heap`, a heap array, and `index` that returns the value of parent node for the node at the given `index`. If `index` is the root node, return the value of the root. If `index` is not a valid index in the list return the string `"{index} is not a valid index in the heap"` where `{index}` is replaced by the number `index`. + + +## Example +``` +get_parent_node([2,3,4,5,10], 4) == 3 +get_parent_node([2,3,4,5,10], 0) == 2 +get_parent_node([2,3,4,5,10], 5) == "5 is not a valid index in the heap" +``` + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/heaps/get_parent_node/solution/solution.py b/data_structures/heaps/get_parent_node/solution/solution.py index f482d750..cb186eca 100644 --- a/data_structures/heaps/get_parent_node/solution/solution.py +++ b/data_structures/heaps/get_parent_node/solution/solution.py @@ -1,8 +1,8 @@ -def get_parent_node(heap, index): - parent_idx = (index-1)//2 - if index == 0 and len(heap)>0: - return heap[0] - if index0: + return heap[0] + if index= (len(heap)//2) and index < len(heap): - return True - return False +def is_leaf(heap, index): + if index >= (len(heap)//2) and index < len(heap): + return True + return False diff --git a/data_structures/heaps/is_leaf_node/solution/test_solution.py b/data_structures/heaps/is_leaf_node/solution/test_solution.py index e5ff02b8..c01f2823 100644 --- a/data_structures/heaps/is_leaf_node/solution/test_solution.py +++ b/data_structures/heaps/is_leaf_node/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - from solution import is_leaf - assert is_leaf([1, 2, 3, 4, 5, 6], 3) == True - assert is_leaf([1, 2, 3, 4, 5, 6], 5) == True - assert is_leaf([1, 2, 3, 4, 5, 6], 1) == False - assert is_leaf([], 1) == False +def test_solution(): + from solution import is_leaf + assert is_leaf([1, 2, 3, 4, 5, 6], 3) == True + assert is_leaf([1, 2, 3, 4, 5, 6], 5) == True + assert is_leaf([1, 2, 3, 4, 5, 6], 1) == False + assert is_leaf([], 1) == False assert is_leaf([1, 2, 3], 3) == False \ No newline at end of file diff --git a/data_structures/heaps/is_max_heap/Readme.md b/data_structures/heaps/is_max_heap/Readme.md index edb549c8..9a099762 100644 --- a/data_structures/heaps/is_max_heap/Readme.md +++ b/data_structures/heaps/is_max_heap/Readme.md @@ -1,27 +1,27 @@ -# Is Max Heap - -# Motivation -A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. -A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. -It is very useful when implementing priority queues where the queue item with higher weightage is given more priority in processing. - -## Problem Description -Define a python function `is_max_heap` that consumes a list `lst`, and returns `True` if lst is in the order of a valid maxHeap and `False` otherwise. -Recall in a maxHeap: -* The root will be at `lst[0]` -* The Parent of `lst[i]` will be at `lst[(i-1)/2]` -* The left child of `lst[i]` will be at `lst[(2*i)+1]` -* The right child of `lst[i]` will be at `lst[(2*i)+2]` - -## Example -``` -is_min_heap([1, 2, 3, 7, 6, 4, 5]) == False -is_min_heap([5, 3, 4, 1, 2]) == True -is_min_heap([]) == True -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Is Max Heap + +# Motivation +A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. +A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. +It is very useful when implementing priority queues where the queue item with higher weightage is given more priority in processing. + +## Problem Description +Define a python function `is_max_heap` that consumes a list `lst`, and returns `True` if lst is in the order of a valid maxHeap and `False` otherwise. +Recall in a maxHeap: +* The root will be at `lst[0]` +* The Parent of `lst[i]` will be at `lst[(i-1)/2]` +* The left child of `lst[i]` will be at `lst[(2*i)+1]` +* The right child of `lst[i]` will be at `lst[(2*i)+2]` + +## Example +``` +is_min_heap([1, 2, 3, 7, 6, 4, 5]) == False +is_min_heap([5, 3, 4, 1, 2]) == True +is_min_heap([]) == True +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/heaps/is_max_heap/solution/solution.py b/data_structures/heaps/is_max_heap/solution/solution.py index 7f9fe960..7e4f8db9 100644 --- a/data_structures/heaps/is_max_heap/solution/solution.py +++ b/data_structures/heaps/is_max_heap/solution/solution.py @@ -1,28 +1,28 @@ -def is_max_heap(lst): - if len(lst) == 0: - return True - for i in range(len(lst)): - root = lst[i] - leftidx = (2*i) + 1 - rightidx = (2*i) + 2 - left_child = None - right_child = None - if (2*i)+1 < len(lst): - left_child = lst[(2*i)+1] - if (2*i)+2 < len(lst): - right_child = lst[(2*i)+2] - if left_child == None and right_child == None: - return True - if left_child == None: - if right_child < root: - return is_max_heap(lst[rightidx:]) - elif right_child > root: - return False - if right_child == None: - if left_child < root: - return is_max_heap(lst[leftidx:]) - elif left_child > root: - return False - if left_child > root or right_child > root: - return False +def is_max_heap(lst): + if len(lst) == 0: + return True + for i in range(len(lst)): + root = lst[i] + leftidx = (2*i) + 1 + rightidx = (2*i) + 2 + left_child = None + right_child = None + if (2*i)+1 < len(lst): + left_child = lst[(2*i)+1] + if (2*i)+2 < len(lst): + right_child = lst[(2*i)+2] + if left_child == None and right_child == None: + return True + if left_child == None: + if right_child < root: + return is_max_heap(lst[rightidx:]) + elif right_child > root: + return False + if right_child == None: + if left_child < root: + return is_max_heap(lst[leftidx:]) + elif left_child > root: + return False + if left_child > root or right_child > root: + return False return True \ No newline at end of file diff --git a/data_structures/heaps/is_max_heap/solution/test_solution.py b/data_structures/heaps/is_max_heap/solution/test_solution.py index 806880b6..35bb7a3c 100644 --- a/data_structures/heaps/is_max_heap/solution/test_solution.py +++ b/data_structures/heaps/is_max_heap/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - from solution import is_max_heap - assert is_max_heap([1, 2, 3, 7, 6, 4, 5]) == False - assert is_max_heap([1]) == True - assert is_max_heap([2,1]) == True - assert is_max_heap([6, 5, 4, 3, 1, 2]) == True - assert is_max_heap([]) == True +def test_solution(): + from solution import is_max_heap + assert is_max_heap([1, 2, 3, 7, 6, 4, 5]) == False + assert is_max_heap([1]) == True + assert is_max_heap([2,1]) == True + assert is_max_heap([6, 5, 4, 3, 1, 2]) == True + assert is_max_heap([]) == True diff --git a/data_structures/heaps/is_min_heap/Readme.md b/data_structures/heaps/is_min_heap/Readme.md index 3fde2594..0af8d55c 100644 --- a/data_structures/heaps/is_min_heap/Readme.md +++ b/data_structures/heaps/is_min_heap/Readme.md @@ -1,27 +1,27 @@ -# Is Min Heap - -# Motivation -A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. -A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. -It is very useful when implementing priority queues where the queue item with higher weightage is given more priority in processing. - -## Problem Description -Define a python function `is_min_heap` that consumes a list `lst`, and returns `True` if lst is in the order of a valid minHeap and `False` otherwise. -Recall in a minHeap: -* The root will be at `lst[0]` -* The Parent of `lst[i]` will be at `lst[(i-1)/2]` -* The left child of `lst[i]` will be at `lst[(2*i)+1]` -* The right child of `lst[i]` will be at `lst[(2*i)+2]` - -## Example -``` -is_min_heap([1, 2, 3, 7, 6, 4, 5]) == True -is_min_heap([5, 1]) == False -is_min_heap([]) == True -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Is Min Heap + +# Motivation +A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. +A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. +It is very useful when implementing priority queues where the queue item with higher weightage is given more priority in processing. + +## Problem Description +Define a python function `is_min_heap` that consumes a list `lst`, and returns `True` if lst is in the order of a valid minHeap and `False` otherwise. +Recall in a minHeap: +* The root will be at `lst[0]` +* The Parent of `lst[i]` will be at `lst[(i-1)/2]` +* The left child of `lst[i]` will be at `lst[(2*i)+1]` +* The right child of `lst[i]` will be at `lst[(2*i)+2]` + +## Example +``` +is_min_heap([1, 2, 3, 7, 6, 4, 5]) == True +is_min_heap([5, 1]) == False +is_min_heap([]) == True +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/heaps/is_min_heap/solution/solution.py b/data_structures/heaps/is_min_heap/solution/solution.py index 1b67b3a4..ec262f41 100644 --- a/data_structures/heaps/is_min_heap/solution/solution.py +++ b/data_structures/heaps/is_min_heap/solution/solution.py @@ -1,28 +1,28 @@ -def is_min_heap(lst): - if len(lst) == 0: - return True - for i in range(len(lst)): - root = lst[i] - leftidx = (2*i) + 1 - rightidx = (2*i) + 2 - left_child = None - right_child = None - if (2*i)+1 < len(lst): - left_child = lst[(2*i)+1] - if (2*i)+2 < len(lst): - right_child = lst[(2*i)+2] - if left_child == None and right_child == None: - return True - if left_child == None: - if right_child > root: - return is_min_heap(lst[rightidx:]) - elif right_child < root: - return False - if right_child == None: - if left_child > root: - return is_min_heap(lst[leftidx:]) - elif left_child < root: - return False - if left_child < root or right_child < root: - return False +def is_min_heap(lst): + if len(lst) == 0: + return True + for i in range(len(lst)): + root = lst[i] + leftidx = (2*i) + 1 + rightidx = (2*i) + 2 + left_child = None + right_child = None + if (2*i)+1 < len(lst): + left_child = lst[(2*i)+1] + if (2*i)+2 < len(lst): + right_child = lst[(2*i)+2] + if left_child == None and right_child == None: + return True + if left_child == None: + if right_child > root: + return is_min_heap(lst[rightidx:]) + elif right_child < root: + return False + if right_child == None: + if left_child > root: + return is_min_heap(lst[leftidx:]) + elif left_child < root: + return False + if left_child < root or right_child < root: + return False return True \ No newline at end of file diff --git a/data_structures/heaps/is_min_heap/solution/test_solution.py b/data_structures/heaps/is_min_heap/solution/test_solution.py index 1215d07e..75f27755 100644 --- a/data_structures/heaps/is_min_heap/solution/test_solution.py +++ b/data_structures/heaps/is_min_heap/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - from solution import is_min_heap - assert is_min_heap([1, 2, 3, 7, 6, 4, 5]) == True - assert is_min_heap([1]) == True - assert is_min_heap([2,1]) == False - assert is_min_heap([6, 5, 4, 7, 9]) == False - assert is_min_heap([]) == True +def test_solution(): + from solution import is_min_heap + assert is_min_heap([1, 2, 3, 7, 6, 4, 5]) == True + assert is_min_heap([1]) == True + assert is_min_heap([2,1]) == False + assert is_min_heap([6, 5, 4, 7, 9]) == False + assert is_min_heap([]) == True diff --git a/data_structures/linked_lists/README.md b/data_structures/linked_lists/README.md index 53c5c173..8bfd7c74 100644 --- a/data_structures/linked_lists/README.md +++ b/data_structures/linked_lists/README.md @@ -1,14 +1,14 @@ -# Exercises - Linked List - -| Exercise ID | Exercise | -|:-----------:|:--------:| -| easy_e1 | [Delete End](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/1_delete_end) | -| easy_e2 | [Insert After](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/1_insert_after) | -| easy_e3 | [Insert Start](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/1_insert_start) | -| medium_e1 | [Delete Item Value](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/2_delete_item_value) | -| medium_e2 | [Insert End](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/2_insert_end) | -| medium_e3 | [Search Item](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/2_search_item) | -| hard_e1 | [Count Items](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/3_count_items) | -| hard_e2 | [Index Insertion](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/3_index_insertion) | -| hard_e3 | [Node Traverse](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/3_node_traverse) | -| hard_e4 | [Reverse](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/3_reverse) | +# Exercises - Linked List + +| Exercise ID | Exercise | +|:-----------:|:--------:| +| easy_e1 | [Delete End](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/1_delete_end) | +| easy_e2 | [Insert After](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/1_insert_after) | +| easy_e3 | [Insert Start](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/1_insert_start) | +| medium_e1 | [Delete Item Value](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/2_delete_item_value) | +| medium_e2 | [Insert End](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/2_insert_end) | +| medium_e3 | [Search Item](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/2_search_item) | +| hard_e1 | [Count Items](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/3_count_items) | +| hard_e2 | [Index Insertion](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/3_index_insertion) | +| hard_e3 | [Node Traverse](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/3_node_traverse) | +| hard_e4 | [Reverse](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/linked_lists/3_reverse) | diff --git a/data_structures/linked_lists/count_items/README.md b/data_structures/linked_lists/count_items/README.md index 14af5f6e..54695c6d 100644 --- a/data_structures/linked_lists/count_items/README.md +++ b/data_structures/linked_lists/count_items/README.md @@ -1,34 +1,34 @@ -# Count Data Items - -## Motivation -A linked list is a dynamic data structure which means that the memory reserved for the link list can be increased or reduced at runtime. No memory is allocated for a linked list data structure in advance. Whenever a new item is required to be added to the linked, the memory for the new node is created at run time. On the other hand, in case of the array, memory has to be allocated in advance for a specific number of items. In cases where sufficient items are not available to fill all array index, memory space is wasted. - -## Problem Description -Given the following Linked List definition: - -A Linked List is either: -a) None -b) Node - -``` -class Node: - def __init__(self, data=None): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head): - self.head = head -``` - -Define a method within class `linkedList` named `get_count` that returns the count of number of elements in the linked_list. - -## Example -``` -sample_LL = Node(5, Node(3, Node(-1, None))) -sample_LL.get_count() == 3 -``` - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Count Data Items + +## Motivation +A linked list is a dynamic data structure which means that the memory reserved for the link list can be increased or reduced at runtime. No memory is allocated for a linked list data structure in advance. Whenever a new item is required to be added to the linked, the memory for the new node is created at run time. On the other hand, in case of the array, memory has to be allocated in advance for a specific number of items. In cases where sufficient items are not available to fill all array index, memory space is wasted. + +## Problem Description +Given the following Linked List definition: + +A Linked List is either: +a) None +b) Node + +``` +class Node: + def __init__(self, data=None): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head): + self.head = head +``` + +Define a method within class `linkedList` named `get_count` that returns the count of number of elements in the linked_list. + +## Example +``` +sample_LL = Node(5, Node(3, Node(-1, None))) +sample_LL.get_count() == 3 +``` + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/data_structures/linked_lists/count_items/solution/count_items.py b/data_structures/linked_lists/count_items/solution/count_items.py new file mode 100644 index 00000000..04234167 --- /dev/null +++ b/data_structures/linked_lists/count_items/solution/count_items.py @@ -0,0 +1,17 @@ +class Node: + def __init__(self, data=None): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head=None): + self.head = head + + def get_count(self): + temp = self.head + count = 0 + while(not temp == None): + count += 1 + temp = temp.next + return count \ No newline at end of file diff --git a/data_structures/linked_lists/count_items/solution/solution.py b/data_structures/linked_lists/count_items/solution/solution.py index 1dc72528..625e063f 100644 --- a/data_structures/linked_lists/count_items/solution/solution.py +++ b/data_structures/linked_lists/count_items/solution/solution.py @@ -1,17 +1,17 @@ -class Node: - def __init__(self, data=None): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head=None): - self.head = head - - def get_count(self): - count = 0 - cur_node = self.head - while(not cur_node == None): - count += 1 - cur_node = cur_node.next +class Node: + def __init__(self, data=None): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head=None): + self.head = head + + def get_count(self): + count = 0 + cur_node = self.head + while(not cur_node == None): + count += 1 + cur_node = cur_node.next return count \ No newline at end of file diff --git a/data_structures/linked_lists/count_items/solution/solution_2.py b/data_structures/linked_lists/count_items/solution/solution_2.py new file mode 100644 index 00000000..ba02ece9 --- /dev/null +++ b/data_structures/linked_lists/count_items/solution/solution_2.py @@ -0,0 +1,37 @@ +class Node: + def __init__(self, data=None): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head=None): + self.head = head + #self.counter = 0 + + def get_count(self): + temp = self.head + count = 0 + while(not temp == None): + count += 1 + temp = temp.next + return count + +#def push(self, new_data): + #new_node = Node(new_data) + #new_node.next = self.headself.head = new_node + +#def printList(self): + #temp = self.head + #while(temp): + #print(temp.data) + #temp = temp.next + +#def get_count(self, temp, key): + #if temp is None: + #return 0 + #if temp.data == key: + #return 1 + get_count(temp.next, key) + #return get_count(temp.next, key) + + diff --git a/data_structures/linked_lists/count_items/solution/solution_3.py b/data_structures/linked_lists/count_items/solution/solution_3.py new file mode 100644 index 00000000..adad4b8e --- /dev/null +++ b/data_structures/linked_lists/count_items/solution/solution_3.py @@ -0,0 +1,17 @@ +class Node: + def __init__(self, data=None): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head=None): + self.head = head + + def get_count(self): + count = 0 + temp = self.head + while(not temp == None): + count += 1 + temp = temp.next + return count \ No newline at end of file diff --git a/data_structures/linked_lists/count_items/solution/test_solution.py b/data_structures/linked_lists/count_items/solution/test_solution.py index cdf30f3e..2f8057d3 100644 --- a/data_structures/linked_lists/count_items/solution/test_solution.py +++ b/data_structures/linked_lists/count_items/solution/test_solution.py @@ -1,9 +1,9 @@ -def test_solution(): - from solution import Node, linkedList - - items = linkedList() - items.head = Node(20) - items.head.next = Node(30) - items.head.next.next = Node(40) - - assert items.get_count() == 3 +def test_solution(): + from solution_3 import Node, linkedList + + items = linkedList() + items.head = Node(20) + items.head.next = Node(30) + items.head.next.next = Node(40) + + assert items.get_count() == 3 diff --git a/data_structures/linked_lists/delete_end/README.md b/data_structures/linked_lists/delete_end/README.md index 785c85e0..c87755a1 100644 --- a/data_structures/linked_lists/delete_end/README.md +++ b/data_structures/linked_lists/delete_end/README.md @@ -1,35 +1,35 @@ -# Delete Data End - -## Motivation -To delete an element from the end of the list, we simply have to iterate through the linked list till the second last element, and then we need to set the reference of the second last element to none, which will convert the second last element to last element. - -## Problem Description -Given the following Linked List definition: - -A Linked List is either: -a) None -b) Node - -``` -class Node: - def __init__(self, data): - self.data = data - self.next = None - - -class linkedlist: - def __init__(self, head=None): - self.head = head -``` - -Define a method within class `linkedlist` named `delete_end` that deletes the last node in the Linked List. - -## Example -``` -sample_LL = Node(5, Node(3, Node(-1, None))) -sample_LL.delete_end() -sample_LL == Node(5, Node(3, None)) -``` - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Delete Data End + +## Motivation +To delete an element from the end of the list, we simply have to iterate through the linked list till the second last element, and then we need to set the reference of the second last element to none, which will convert the second last element to last element. + +## Problem Description +Given the following Linked List definition: + +A Linked List is either: +a) None +b) Node + +``` +class Node: + def __init__(self, data): + self.data = data + self.next = None + + +class linkedlist: + def __init__(self, head=None): + self.head = head +``` + +Define a method within class `linkedlist` named `delete_end` that deletes the last node in the Linked List. + +## Example +``` +sample_LL = Node(5, Node(3, Node(-1, None))) +sample_LL.delete_end() +sample_LL == Node(5, Node(3, None)) +``` + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/data_structures/linked_lists/delete_end/solution/delete_end.py b/data_structures/linked_lists/delete_end/solution/delete_end.py new file mode 100644 index 00000000..50cee5cd --- /dev/null +++ b/data_structures/linked_lists/delete_end/solution/delete_end.py @@ -0,0 +1,29 @@ +class Node: + def __init__(self, data): + self.data = data + self.next = None + + +class linkedlist: + def __init__(self, head=None): + self.head = head + + # def push(head, data): + # if not head: + # return Node(data) + # temp = Node(data) + # temp.next = head + # head = temp + # return head + + def delete_at_end(self): + if self.head == None: + return None + # if self.head.next == None: + # head = None + # return None + second_last = self.head + while(second_last.next.next is not None): + second_last = second_last.next + second_last.next = None + return second_last \ No newline at end of file diff --git a/data_structures/linked_lists/delete_end/solution/solution.py b/data_structures/linked_lists/delete_end/solution/solution.py index f3d9b377..4158cb5b 100644 --- a/data_structures/linked_lists/delete_end/solution/solution.py +++ b/data_structures/linked_lists/delete_end/solution/solution.py @@ -1,20 +1,20 @@ -class Node: - def __init__(self, data): - self.data = data - self.next = None - - def __str__(self): - return str(self.data) - - -class linkedlist: - def __init__(self, head=None): - self.head = head - - def delete_at_end(self): - if self.head is None: - return - n = self.head - while n.next.next is not None: - n = n.next +class Node: + def __init__(self, data): + self.data = data + self.next = None + + def __str__(self): + return str(self.data) + + +class linkedlist: + def __init__(self, head=None): + self.head = head + + def delete_at_end(self): + if self.head is None: + return + n = self.head + while n.next.next is not None: + n = n.next n.next = None \ No newline at end of file diff --git a/data_structures/linked_lists/delete_end/solution/solution_2.py b/data_structures/linked_lists/delete_end/solution/solution_2.py new file mode 100644 index 00000000..e69de29b diff --git a/data_structures/linked_lists/delete_end/solution/test_solution.py b/data_structures/linked_lists/delete_end/solution/test_solution.py index 172b9361..adb03e44 100644 --- a/data_structures/linked_lists/delete_end/solution/test_solution.py +++ b/data_structures/linked_lists/delete_end/solution/test_solution.py @@ -1,12 +1,12 @@ -def test_solution(): - from solution import Node, linkedlist - - items = linkedlist() - items.head = Node(20) - items.head.next = Node(30) - items.head.next.next = Node(50) - print(items.head, items.head.next, items.head.next.next) - items.delete_at_end() - assert items.head.data == 20 - assert items.head.next.data == 30 +def test_solution(): + from delete_end import Node, linkedlist + + items = linkedlist() + items.head = Node(20) + items.head.next = Node(30) + items.head.next.next = Node(50) + print(items.head, items.head.next, items.head.next.next) + items.delete_at_end() + assert items.head.data == 20 + assert items.head.next.data == 30 assert items.head.next.next == None \ No newline at end of file diff --git a/data_structures/linked_lists/delete_item_value/README.md b/data_structures/linked_lists/delete_item_value/README.md index 5072b2fa..1fd03866 100644 --- a/data_structures/linked_lists/delete_item_value/README.md +++ b/data_structures/linked_lists/delete_item_value/README.md @@ -1,37 +1,37 @@ -# Delete Item Value - -## Motivation -Deletion by Item Value - -To delete the element by value, we first have to find the node that contains the item with the specified value and then delete the node. Finding the item with the specified value is pretty similar to searching the item. Once the item to be deleted is found, the reference of the node before the item is set to the node that exists after the item being deleted. - -## Problem Description -Given the following Linked List definition: - -A Linked List is either: -a) None -b) Node - -``` -class Node: - def __init__(self, data): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head): - self.head = head -``` - -Define a method within class `linkedList` named `delete_item_by_value` that consumes one parameter `x`.The method deletes the specified data value from the linked_list. If `x` is not in the list, the list should remain unchanged. - -## Example -``` -sample_LL = Node(5, Node(3, Node(-1, None))) -sample_LL.delete_item_by_value(3) -sample_LL == Node(5, Node(-1, None)) -``` - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Delete Item Value + +## Motivation +Deletion by Item Value + +To delete the element by value, we first have to find the node that contains the item with the specified value and then delete the node. Finding the item with the specified value is pretty similar to searching the item. Once the item to be deleted is found, the reference of the node before the item is set to the node that exists after the item being deleted. + +## Problem Description +Given the following Linked List definition: + +A Linked List is either: +a) None +b) Node + +``` +class Node: + def __init__(self, data): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head): + self.head = head +``` + +Define a method within class `linkedList` named `delete_item_by_value` that consumes one parameter `x`.The method deletes the specified data value from the linked_list. If `x` is not in the list, the list should remain unchanged. + +## Example +``` +sample_LL = Node(5, Node(3, Node(-1, None))) +sample_LL.delete_item_by_value(3) +sample_LL == Node(5, Node(-1, None)) +``` + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/data_structures/linked_lists/delete_item_value/solution/solution.py b/data_structures/linked_lists/delete_item_value/solution/solution.py index cca3e41c..800f1c91 100644 --- a/data_structures/linked_lists/delete_item_value/solution/solution.py +++ b/data_structures/linked_lists/delete_item_value/solution/solution.py @@ -1,18 +1,18 @@ -class Node: - def __init__(self, data): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head=None): - self.head = head - - def delete_item_by_value(self, x): - cur_node = self.head - prev_node = cur_node - while(not cur_node == None and not cur_node.data == x): - prev_node = cur_node - cur_node = cur_node.next - if not cur_node == None: - prev_node.next = cur_node.next +class Node: + def __init__(self, data): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head=None): + self.head = head + + def delete_item_by_value(self, x): + cur_node = self.head + prev_node = cur_node + while(not cur_node == None and not cur_node.data == x): + prev_node = cur_node + cur_node = cur_node.next + if not cur_node == None: + prev_node.next = cur_node.next diff --git a/data_structures/linked_lists/delete_item_value/solution/solution_2.py b/data_structures/linked_lists/delete_item_value/solution/solution_2.py new file mode 100644 index 00000000..53b796f0 --- /dev/null +++ b/data_structures/linked_lists/delete_item_value/solution/solution_2.py @@ -0,0 +1,19 @@ +class Node: + def __init__(self, data): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head=None): + self.head = head + + def delete_item_by_value(self, x): + items = self.head + prev_node = items + while(not items == None and not items.data == x): + prev_node = items + items = items.next + if not items == None: + prev_node.next = items.next + return \ No newline at end of file diff --git a/data_structures/linked_lists/delete_item_value/solution/test_solution.py b/data_structures/linked_lists/delete_item_value/solution/test_solution.py index 2a6d05b1..14caf427 100644 --- a/data_structures/linked_lists/delete_item_value/solution/test_solution.py +++ b/data_structures/linked_lists/delete_item_value/solution/test_solution.py @@ -1,13 +1,13 @@ -def test_solution(): - from solution import Node, linkedList - - items = linkedList() - items.head = Node(20) - items.head.next = Node(30) - items.head.next.next = Node(40) - items.head.next.next.next = Node(50) - items.delete_item_by_value(40) - - assert items.head.data == 20 - assert items.head.next.data == 30 - assert items.head.next.next.data == 50 +def test_solution(): + from solution_2 import Node, linkedList + + items = linkedList() + items.head = Node(20) + items.head.next = Node(30) + items.head.next.next = Node(40) + items.head.next.next.next = Node(50) + items.delete_item_by_value(40) + + assert items.head.data == 20 + assert items.head.next.data == 30 + assert items.head.next.next.data == 50 diff --git a/data_structures/linked_lists/index_insertion/README.md b/data_structures/linked_lists/index_insertion/README.md index e4a392b2..dbd95078 100644 --- a/data_structures/linked_lists/index_insertion/README.md +++ b/data_structures/linked_lists/index_insertion/README.md @@ -1,41 +1,41 @@ -# Index Insertion - -## Motivation -However, there are some downsides to the linked list as well. - -Since each linked list item has to store the reference to the next item, some extra memory is required. - -Unlike Arrays, where you can directly access an item, you cannot access a linked list item directly since the only information you have is the reference to the first item. In Big O terms, worst-case access time is O(n). - -## Problem Description -Given the following Linked List definition: - -A Linked List is either: -a) None -b) Node - -``` -class Node: - def __init__(self, data=None): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head=None): - self.head = head -``` - -Define a method within class `linkedList` named `insert_at_index` which consumes two parameters `index` and `data`. The method inserts the data element at given index position in the linked_list. You may assume `index` is a valid index in the list. -Note - index starts from `1` - -## Example -``` -sample_LL = Node(5, Node(3, Node(-1, None))) -sample_LL.insert_at_index(2, 2) -sample_LL = Node(5, Node(2, Node(3, Node(-1, None))) - -``` - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Index Insertion + +## Motivation +However, there are some downsides to the linked list as well. + +Since each linked list item has to store the reference to the next item, some extra memory is required. + +Unlike Arrays, where you can directly access an item, you cannot access a linked list item directly since the only information you have is the reference to the first item. In Big O terms, worst-case access time is O(n). + +## Problem Description +Given the following Linked List definition: + +A Linked List is either: +a) None +b) Node + +``` +class Node: + def __init__(self, data=None): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head=None): + self.head = head +``` + +Define a method within class `linkedList` named `insert_at_index` which consumes two parameters `index` and `data`. The method inserts the data element at given index position in the linked_list. You may assume `index` is a valid index in the list. +Note - index starts from `1` + +## Example +``` +sample_LL = Node(5, Node(3, Node(-1, None))) +sample_LL.insert_at_index(2, 2) +sample_LL = Node(5, Node(2, Node(3, Node(-1, None))) + +``` + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/data_structures/linked_lists/index_insertion/solution/solution.py b/data_structures/linked_lists/index_insertion/solution/solution.py index ac42237e..ec7e8859 100644 --- a/data_structures/linked_lists/index_insertion/solution/solution.py +++ b/data_structures/linked_lists/index_insertion/solution/solution.py @@ -1,24 +1,24 @@ -class Node: - def __init__(self, data=None): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head=None): - self.head = head - - def insert_at_index(self, index, data): - cur_idx = 1 - cur_node = self.head - prev_node = cur_node - new_node = Node(data) - - while(cur_idx < index): - prev_node = cur_node - cur_node = cur_node.next - cur_idx += 1 - new_node.next = cur_node - prev_node.next = new_node - - +class Node: + def __init__(self, data=None): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head=None): + self.head = head + + def insert_at_index(self, index, data): + cur_idx = 1 + cur_node = self.head + prev_node = cur_node + new_node = Node(data) + + while(cur_idx < index): + prev_node = cur_node + cur_node = cur_node.next + cur_idx += 1 + new_node.next = cur_node + prev_node.next = new_node + + diff --git a/data_structures/linked_lists/index_insertion/solution/test_solution.py b/data_structures/linked_lists/index_insertion/solution/test_solution.py index 2ea4beb7..9ee458ad 100644 --- a/data_structures/linked_lists/index_insertion/solution/test_solution.py +++ b/data_structures/linked_lists/index_insertion/solution/test_solution.py @@ -1,11 +1,11 @@ -def test_solution(): - from solution import Node, linkedList - - items = linkedList() - items.head = Node(20) - items.head.next = Node(30) - items.head.next.next = Node(40) - items.insert_at_index(2, 2) - - assert items.head.data == 20 - assert items.head.next.data == 2 +def test_solution(): + from solution import Node, linkedList + + items = linkedList() + items.head = Node(20) + items.head.next = Node(30) + items.head.next.next = Node(40) + items.insert_at_index(2, 2) + + assert items.head.data == 20 + assert items.head.next.data == 2 diff --git a/data_structures/linked_lists/insert_after/README.md b/data_structures/linked_lists/insert_after/README.md index 70dd4bcd..227ee6f3 100644 --- a/data_structures/linked_lists/insert_after/README.md +++ b/data_structures/linked_lists/insert_after/README.md @@ -1,32 +1,32 @@ -# Insert After Data - - -## Problem Description -Given the following Linked List definition: - -A Linked List is either: -a) None -b) Node - -``` -class Node: - def __init__(self, data): - self.data = data - self.next = None - -class linkedList: - def __init__(self, head=None): - self.head = head -``` - -Define a method within class `linkedList` named `insert_after_item` that consumes two paraeters `x` and `data` and inserts an node with data `data` after the node in the linked_list with data `x`. If no node in the list has data `x`, insert the node with `data` at the end of the list. - -## Example -``` -sample_LL = Node(5, Node(3, Node(-1, None))) -sample_LL.insert_after_item(3, 0) -sample_LL == Node(5, Node(3, Node(0, Node(-1, None)))) -``` - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Insert After Data + + +## Problem Description +Given the following Linked List definition: + +A Linked List is either: +a) None +b) Node + +``` +class Node: + def __init__(self, data): + self.data = data + self.next = None + +class linkedList: + def __init__(self, head=None): + self.head = head +``` + +Define a method within class `linkedList` named `insert_after_item` that consumes two paraeters `x` and `data` and inserts an node with data `data` after the node in the linked_list with data `x`. If no node in the list has data `x`, insert the node with `data` at the end of the list. + +## Example +``` +sample_LL = Node(5, Node(3, Node(-1, None))) +sample_LL.insert_after_item(3, 0) +sample_LL == Node(5, Node(3, Node(0, Node(-1, None)))) +``` + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/data_structures/linked_lists/insert_after/solution/solution.py b/data_structures/linked_lists/insert_after/solution/solution.py index 79a495cb..cf36ef58 100644 --- a/data_structures/linked_lists/insert_after/solution/solution.py +++ b/data_structures/linked_lists/insert_after/solution/solution.py @@ -1,28 +1,28 @@ -class Node: - def __init__(self, data): - self.data = data - self.next = None - -class linkedList: - def __init__(self, head=None): - self.head = head - - def insert_after_item(self, x, data): - cur_node = self.head - prev_node = self.head - if cur_node == None: - new_node = Node(data) - self.head = new_node - return - while(not cur_node == None and cur_node.data != x): - prev_node = cur_node - cur_node = cur_node.next - new_node = Node(data) - if cur_node == None: - prev_node.next = new_node - else: - temp_next = cur_node.next - cur_node.next = new_node - new_node.next = temp_next - - +class Node: + def __init__(self, data): + self.data = data + self.next = None + +class linkedList: + def __init__(self, head=None): + self.head = head + + def insert_after_item(self, x, data): + cur_node = self.head + prev_node = self.head + if cur_node == None: + new_node = Node(data) + self.head = new_node + return + while(not cur_node == None and cur_node.data != x): + prev_node = cur_node + cur_node = cur_node.next + new_node = Node(data) + if cur_node == None: + prev_node.next = new_node + else: + temp_next = cur_node.next + cur_node.next = new_node + new_node.next = temp_next + + diff --git a/data_structures/linked_lists/insert_after/solution/solution_2.py b/data_structures/linked_lists/insert_after/solution/solution_2.py new file mode 100644 index 00000000..bb9e4398 --- /dev/null +++ b/data_structures/linked_lists/insert_after/solution/solution_2.py @@ -0,0 +1,8 @@ +class Node: + def __init__(self, data): + self.data = data + self.next = None + +class linkedList: + def __init__(self, head=None): + self.head = head \ No newline at end of file diff --git a/data_structures/linked_lists/insert_after/solution/test_solution.py b/data_structures/linked_lists/insert_after/solution/test_solution.py index 7ef0c0a8..e0aa0b5c 100644 --- a/data_structures/linked_lists/insert_after/solution/test_solution.py +++ b/data_structures/linked_lists/insert_after/solution/test_solution.py @@ -1,11 +1,11 @@ -def test_solution(): - from solution import Node, linkedList - - items = linkedList() - items.head = Node(20) - items.head.next = Node(30) - items.head.next.next = Node(50) - items.insert_after_item(30, 0) - assert items.head.data == 20 - assert items.head.next.data == 30 - assert items.head.next.next.data == 0 +def test_solution(): + from solution import Node, linkedList + + items = linkedList() + items.head = Node(20) + items.head.next = Node(30) + items.head.next.next = Node(50) + items.insert_after_item(30, 0) + assert items.head.data == 20 + assert items.head.next.data == 30 + assert items.head.next.next.data == 0 diff --git a/data_structures/linked_lists/insert_end/README.md b/data_structures/linked_lists/insert_end/README.md index 21e039f7..e08d2bf3 100644 --- a/data_structures/linked_lists/insert_end/README.md +++ b/data_structures/linked_lists/insert_end/README.md @@ -1,32 +1,32 @@ -# Insert Data End - -## Problem Description -Given the following Linked List definition: - -A Linked List is either: -a) None -b) Node - -``` -class Node: - def __init__(self, data): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head): - self.head = head -``` - -Define a method within class `linkedList` named `insert_at_end` that consumes an integer `data` inserts a new node with `data` into the linked list at the end of the data structure. - -## Example -``` -sample_LL = Node(5, Node(3, Node(-1, None))) -sample_LL.insert_at_end(40) -sample_LL == Node(5, Node(3, Node(-1, Node(40, None)))) -``` - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Insert Data End + +## Problem Description +Given the following Linked List definition: + +A Linked List is either: +a) None +b) Node + +``` +class Node: + def __init__(self, data): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head): + self.head = head +``` + +Define a method within class `linkedList` named `insert_at_end` that consumes an integer `data` inserts a new node with `data` into the linked list at the end of the data structure. + +## Example +``` +sample_LL = Node(5, Node(3, Node(-1, None))) +sample_LL.insert_at_end(40) +sample_LL == Node(5, Node(3, Node(-1, Node(40, None)))) +``` + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/data_structures/linked_lists/insert_end/solution/solution.py b/data_structures/linked_lists/insert_end/solution/solution.py index 1f3e0740..ccffb7d7 100644 --- a/data_structures/linked_lists/insert_end/solution/solution.py +++ b/data_structures/linked_lists/insert_end/solution/solution.py @@ -1,18 +1,18 @@ -class Node: - def __init__(self, data): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head=None): - self.head = head - - def insert_at_end(self, data): - cur_node = self.head - prev_node = cur_node - while(not cur_node == None): - prev_node = cur_node - cur_node = cur_node.next - new_node = Node(data) +class Node: + def __init__(self, data): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head=None): + self.head = head + + def insert_at_end(self, data): + cur_node = self.head + prev_node = cur_node + while(not cur_node == None): + prev_node = cur_node + cur_node = cur_node.next + new_node = Node(data) prev_node.next = new_node \ No newline at end of file diff --git a/data_structures/linked_lists/insert_end/solution/test_solution.py b/data_structures/linked_lists/insert_end/solution/test_solution.py index 25105832..f4b70f6f 100644 --- a/data_structures/linked_lists/insert_end/solution/test_solution.py +++ b/data_structures/linked_lists/insert_end/solution/test_solution.py @@ -1,11 +1,11 @@ -def test_solution(): - from solution import Node, linkedList - - items = linkedList() - items.head = Node(20) - items.head.next = Node(30) - items.insert_at_end(40) - - assert items.head.data == 20 - assert items.head.next.data == 30 - assert items.head.next.next.data == 40 +def test_solution(): + from solution import Node, linkedList + + items = linkedList() + items.head = Node(20) + items.head.next = Node(30) + items.insert_at_end(40) + + assert items.head.data == 20 + assert items.head.next.data == 30 + assert items.head.next.next.data == 40 diff --git a/data_structures/linked_lists/insert_start/README.md b/data_structures/linked_lists/insert_start/README.md index aa578875..5abc62be 100644 --- a/data_structures/linked_lists/insert_start/README.md +++ b/data_structures/linked_lists/insert_start/README.md @@ -1,38 +1,38 @@ -# Insert Data Start - -## Motivation -Depending upon the location where you want to insert an item, there are different ways to insert items in a single linked list. - -Inserting Items at the Beginning- -The simplest way to insert an item in a single linked list is to add an item at the start of the list. - -## Problem Description -Given the following Linked List definition: - -A Linked List is either: -a) None -b) Node - -``` -class Node: - def __init__(self, data): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head): - self.head = head -``` - -Define a method within class `linkedlist` named `insert_at_start` that consumes an integer `data` and inserts a node with `data` into the linked list at the start of the data structure. - -## Example -``` -sample_LL = Node(5, Node(3, Node(-1, None))) -sample_LL.insert_at_start(50) -sample_LL == Node(50, Node(5, Node(3, Node(-1, None)))) -``` - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Insert Data Start + +## Motivation +Depending upon the location where you want to insert an item, there are different ways to insert items in a single linked list. + +Inserting Items at the Beginning- +The simplest way to insert an item in a single linked list is to add an item at the start of the list. + +## Problem Description +Given the following Linked List definition: + +A Linked List is either: +a) None +b) Node + +``` +class Node: + def __init__(self, data): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head): + self.head = head +``` + +Define a method within class `linkedlist` named `insert_at_start` that consumes an integer `data` and inserts a node with `data` into the linked list at the start of the data structure. + +## Example +``` +sample_LL = Node(5, Node(3, Node(-1, None))) +sample_LL.insert_at_start(50) +sample_LL == Node(50, Node(5, Node(3, Node(-1, None)))) +``` + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/data_structures/linked_lists/insert_start/solution/solution.py b/data_structures/linked_lists/insert_start/solution/solution.py index 4141ffef..4f7a0cdf 100644 --- a/data_structures/linked_lists/insert_start/solution/solution.py +++ b/data_structures/linked_lists/insert_start/solution/solution.py @@ -1,14 +1,14 @@ -class Node: - def __init__(self, data): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head=None): - self.head = head - - def insert_at_start(self, data): - new_node = Node(data) - new_node.next = self.head - self.head = new_node +class Node: + def __init__(self, data): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head=None): + self.head = head + + def insert_at_start(self, data): + new_node = Node(data) + new_node.next = self.head + self.head = new_node diff --git a/data_structures/linked_lists/insert_start/solution/test_solution.py b/data_structures/linked_lists/insert_start/solution/test_solution.py index db5bc760..13219e55 100644 --- a/data_structures/linked_lists/insert_start/solution/test_solution.py +++ b/data_structures/linked_lists/insert_start/solution/test_solution.py @@ -1,10 +1,10 @@ -def test_solution(): - from solution import Node, linkedList - - items = linkedList() - items.head = Node(20) - items.insert_at_start(40) - items.insert_at_start(50) - assert items.head.data == 50 - assert items.head.next.data == 40 - assert items.head.next.next.data == 20 +def test_solution(): + from solution import Node, linkedList + + items = linkedList() + items.head = Node(20) + items.insert_at_start(40) + items.insert_at_start(50) + assert items.head.data == 50 + assert items.head.next.data == 40 + assert items.head.next.next.data == 20 diff --git a/data_structures/linked_lists/node_traverse/README.md b/data_structures/linked_lists/node_traverse/README.md index 757d7133..53c623ec 100644 --- a/data_structures/linked_lists/node_traverse/README.md +++ b/data_structures/linked_lists/node_traverse/README.md @@ -1,39 +1,39 @@ -# Connect Node Traverse - -## Motivation -Linked lists are one of the most commonly used data structures in any programming language. -Every node in a single linked list contains an item and reference to the next item and that's it. - -## Problem Description -Given the following Linked List definition: - -A Linked List is either: -a) None -b) Node - -``` -class Node: - def __init__(self, data=None): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head=None): - self.head = head -``` - -Define a method within class `linkedList` named `traverse` that traverses through each element in the Linked_list, and prints out each element in the list, each on a new line. - -## Example -``` -sample_LL = Node(5, Node(3, Node(-1, None))) -sample_LL.traverse() -output -5 -3 --1 -``` - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Connect Node Traverse + +## Motivation +Linked lists are one of the most commonly used data structures in any programming language. +Every node in a single linked list contains an item and reference to the next item and that's it. + +## Problem Description +Given the following Linked List definition: + +A Linked List is either: +a) None +b) Node + +``` +class Node: + def __init__(self, data=None): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head=None): + self.head = head +``` + +Define a method within class `linkedList` named `traverse` that traverses through each element in the Linked_list, and prints out each element in the list, each on a new line. + +## Example +``` +sample_LL = Node(5, Node(3, Node(-1, None))) +sample_LL.traverse() +output +5 +3 +-1 +``` + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/data_structures/linked_lists/node_traverse/solution/solution.py b/data_structures/linked_lists/node_traverse/solution/solution.py index c995d50d..13a5705b 100644 --- a/data_structures/linked_lists/node_traverse/solution/solution.py +++ b/data_structures/linked_lists/node_traverse/solution/solution.py @@ -1,15 +1,15 @@ -class Node: - def __init__(self, data=None): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head=None): - self.head = head - - def traverse(self): - cur_node = self.head - while(cur_node): - print(cur_node.data) +class Node: + def __init__(self, data=None): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head=None): + self.head = head + + def traverse(self): + cur_node = self.head + while(cur_node): + print(cur_node.data) cur_node = cur_node.next \ No newline at end of file diff --git a/data_structures/linked_lists/node_traverse/solution/test_solution.py b/data_structures/linked_lists/node_traverse/solution/test_solution.py index 2d9a1a41..40a23772 100644 --- a/data_structures/linked_lists/node_traverse/solution/test_solution.py +++ b/data_structures/linked_lists/node_traverse/solution/test_solution.py @@ -1,18 +1,18 @@ -def test_solution(monkeypatch): - ret_val = [] - - def g(num): - ret_val.append(num) - - monkeypatch.setattr("builtins.print", g) - - from solution import Node, linkedList - - items = linkedList() - items.head = Node(1) - e2 = Node(2) - items.head.next = e2 - items.traverse() - - assert ret_val[0] == 1 - assert ret_val[1] == 2 +def test_solution(monkeypatch): + ret_val = [] + + def g(num): + ret_val.append(num) + + monkeypatch.setattr("builtins.print", g) + + from solution import Node, linkedList + + items = linkedList() + items.head = Node(1) + e2 = Node(2) + items.head.next = e2 + items.traverse() + + assert ret_val[0] == 1 + assert ret_val[1] == 2 diff --git a/data_structures/linked_lists/reverse/README.md b/data_structures/linked_lists/reverse/README.md index b792a79a..9f3f60d3 100644 --- a/data_structures/linked_lists/reverse/README.md +++ b/data_structures/linked_lists/reverse/README.md @@ -1,32 +1,32 @@ -# Reverse Linked List - -## Problem Description -Given the following Linked List definition: - -A Linked List is either: -a) None -b) Node - -``` -class Node: - def __init__(self, data=None): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head=None): - self.head = head -``` - -Define a method within class `linkedList` named `reverse` that reverses the linkedList. The linked list should be mutated, and you should not create a new linkedList. - -## Example -``` -sample_LL = Node(5, Node(3, Node(-1, None))) -sample_LL.reverse() -sample_LL = Node(-1, Node(3, Node(5, None))) -``` - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Reverse Linked List + +## Problem Description +Given the following Linked List definition: + +A Linked List is either: +a) None +b) Node + +``` +class Node: + def __init__(self, data=None): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head=None): + self.head = head +``` + +Define a method within class `linkedList` named `reverse` that reverses the linkedList. The linked list should be mutated, and you should not create a new linkedList. + +## Example +``` +sample_LL = Node(5, Node(3, Node(-1, None))) +sample_LL.reverse() +sample_LL = Node(-1, Node(3, Node(5, None))) +``` + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/data_structures/linked_lists/reverse/solution/solution.py b/data_structures/linked_lists/reverse/solution/solution.py index b59f7d2c..514ebe95 100644 --- a/data_structures/linked_lists/reverse/solution/solution.py +++ b/data_structures/linked_lists/reverse/solution/solution.py @@ -1,19 +1,19 @@ -class Node: - def __init__(self, data=None): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head=None): - self.head = head - - def reverse(self): - cur_node = self.head - prev_node = None - while(cur_node): - next_node = cur_node.next - cur_node.next = prev_node - prev_node = cur_node - cur_node = next_node +class Node: + def __init__(self, data=None): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head=None): + self.head = head + + def reverse(self): + cur_node = self.head + prev_node = None + while(cur_node): + next_node = cur_node.next + cur_node.next = prev_node + prev_node = cur_node + cur_node = next_node self.head = prev_node \ No newline at end of file diff --git a/data_structures/linked_lists/reverse/solution/test_solution.py b/data_structures/linked_lists/reverse/solution/test_solution.py index d98a2d24..25b2df72 100644 --- a/data_structures/linked_lists/reverse/solution/test_solution.py +++ b/data_structures/linked_lists/reverse/solution/test_solution.py @@ -1,11 +1,11 @@ -def test_solution(): - from solution import Node, linkedList - - items = linkedList() - items.head = Node(20) - items.head.next = Node(30) - items.head.next.next = Node(40) - items.reverse() - - assert items.head.data == 40 - assert items.head.next.data == 30 +def test_solution(): + from solution import Node, linkedList + + items = linkedList() + items.head = Node(20) + items.head.next = Node(30) + items.head.next.next = Node(40) + items.reverse() + + assert items.head.data == 40 + assert items.head.next.data == 30 diff --git a/data_structures/linked_lists/search_item/README.md b/data_structures/linked_lists/search_item/README.md index a02f0f85..d0a86bab 100644 --- a/data_structures/linked_lists/search_item/README.md +++ b/data_structures/linked_lists/search_item/README.md @@ -1,37 +1,37 @@ -# Search Item Exists - -## Motivation -Since arrays require contiguous memory locations, it is very difficult to remove or insert an item in an array since the memory locations of a large number of items have to be updated. On the other hand, linked list items are not stored in a contiguous memory location, therefore you can easily update linked lists. - -Owing to its flexibility, a linked list is more suitable for implementing data structures like stacks, queues, and lists. - -## Problem Description -Given the following Linked List definition: - -A Linked List is either: -a) None -b) Node - -``` -class Node: - def __init__(self, data=None): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head): - self.head = head -``` - -Define a method within class `linkedList` named `search` that consumes one parameter `x`.The method returns `True` if the given item `x` exists in the Linked_list and `False` otherwise. - -## Example -``` -sample_LL = Node(5, Node(3, Node(-1, None))) -sample_LL.search(3) == True -sample_LL.search(0) == False -``` - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Search Item Exists + +## Motivation +Since arrays require contiguous memory locations, it is very difficult to remove or insert an item in an array since the memory locations of a large number of items have to be updated. On the other hand, linked list items are not stored in a contiguous memory location, therefore you can easily update linked lists. + +Owing to its flexibility, a linked list is more suitable for implementing data structures like stacks, queues, and lists. + +## Problem Description +Given the following Linked List definition: + +A Linked List is either: +a) None +b) Node + +``` +class Node: + def __init__(self, data=None): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head): + self.head = head +``` + +Define a method within class `linkedList` named `search` that consumes one parameter `x`.The method returns `True` if the given item `x` exists in the Linked_list and `False` otherwise. + +## Example +``` +sample_LL = Node(5, Node(3, Node(-1, None))) +sample_LL.search(3) == True +sample_LL.search(0) == False +``` + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/data_structures/linked_lists/search_item/solution/solution.py b/data_structures/linked_lists/search_item/solution/solution.py index be29a1a4..805d5232 100644 --- a/data_structures/linked_lists/search_item/solution/solution.py +++ b/data_structures/linked_lists/search_item/solution/solution.py @@ -1,17 +1,17 @@ -class Node: - def __init__(self, data=None): - self.data = data - self.next = None - - -class linkedList: - def __init__(self, head=None): - self.head = head - - def search(self, x): - cur_node = self.head - while(not cur_node == None): - if cur_node.data == x: - return True - cur_node = cur_node.next +class Node: + def __init__(self, data=None): + self.data = data + self.next = None + + +class linkedList: + def __init__(self, head=None): + self.head = head + + def search(self, x): + cur_node = self.head + while(not cur_node == None): + if cur_node.data == x: + return True + cur_node = cur_node.next return False \ No newline at end of file diff --git a/data_structures/linked_lists/search_item/solution/test_solution.py b/data_structures/linked_lists/search_item/solution/test_solution.py index 305a2be7..8abcc89e 100644 --- a/data_structures/linked_lists/search_item/solution/test_solution.py +++ b/data_structures/linked_lists/search_item/solution/test_solution.py @@ -1,10 +1,10 @@ -def test_solution(): - from solution import Node, linkedList - - items = linkedList() - items.head = Node(20) - items.head.next = Node(30) - items.head.next.next = Node(40) - - assert items.search(30) == True - assert items.search(10) == False +def test_solution(): + from solution import Node, linkedList + + items = linkedList() + items.head = Node(20) + items.head.next = Node(30) + items.head.next.next = Node(40) + + assert items.search(30) == True + assert items.search(10) == False diff --git a/data_structures/stacks_and_queues/README.md b/data_structures/stacks_and_queues/README.md index eb216a72..11227afd 100644 --- a/data_structures/stacks_and_queues/README.md +++ b/data_structures/stacks_and_queues/README.md @@ -1,14 +1,14 @@ -# Exercises - Stacks And Queues - -| Exercise ID | Exercise | -|:-----------:|:--------:| -| easy_e1 | [Queue Bool](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/queue_bool) | -| easy_e2 | [Queue Len](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/queue_len) | -| easy_e3 | [Queue Eq](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/queue_eq) | -| easy_e4 | [Inorder To Postorder](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/inorder_to_postorder) | -| medium_e1 | [Minimum Parentheses](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/minimum_parentheses) | -| medium_e2 | [Postfix Evaluation](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/postfix_evaluation) | -| medium_e3 | [Reverse Words](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/reverse_words) | -| medium_e4 | [Reverse Queue](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/reverse_queue) | -| hard_e1 | [Binary Numbers](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/binary_numbers) | -| hard_e2 | [Backspace Compare](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/backspace_compare) | +# Exercises - Stacks And Queues + +| Exercise ID | Exercise | +|:-----------:|:--------:| +| easy_e1 | [Queue Bool](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/queue_bool) | +| easy_e2 | [Queue Len](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/queue_len) | +| easy_e3 | [Queue Eq](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/queue_eq) | +| easy_e4 | [Inorder To Postorder](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/inorder_to_postorder) | +| medium_e1 | [Minimum Parentheses](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/minimum_parentheses) | +| medium_e2 | [Postfix Evaluation](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/postfix_evaluation) | +| medium_e3 | [Reverse Words](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/reverse_words) | +| medium_e4 | [Reverse Queue](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/reverse_queue) | +| hard_e1 | [Binary Numbers](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/binary_numbers) | +| hard_e2 | [Backspace Compare](https://github.com/ByteAcademyCo/Data-Structures/tree/master/exercises/stacks_and_queues/backspace_compare) | diff --git a/data_structures/stacks_and_queues/backspace_compare/README.md b/data_structures/stacks_and_queues/backspace_compare/README.md index 7ca05b51..cc4cd5b5 100644 --- a/data_structures/stacks_and_queues/backspace_compare/README.md +++ b/data_structures/stacks_and_queues/backspace_compare/README.md @@ -1,37 +1,37 @@ -# Stacks and Queues - Backspace Compare - -## Motivation -Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. - -A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. - -In stacks, elements are stored one over another, and these elements get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First out. - -Stacks and Queues are implemented using Linked Lists - -## Problem Description -Define a Python function `backspace_compare` that comsumes two strings `str1` and `str2` and returns `True` if they are equal when typed into empty text editors and `False` otherwise. The character `#` means a backspace character. -Hint1: Try to think whether a Stack or a queue may be a useful tool to solve this problem! -Hint2: You may find your previously defined magic methods or a new magic method useful for this question. -You may use the implementation of a stack or queue from the lecture slides. - -## Example: -``` -str1 = "ab#c" -str2 = "ad#c" -backspace_compare(str1, str2) == True - -str1 = "a##c" -str2 = "#a#c" -backspace_compare(str1, str2) == True - -str1 = "a#c" -str2 = "c#d" -backspace_compare(str1, str2) == False -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Stacks and Queues - Backspace Compare + +## Motivation +Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. + +A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. + +In stacks, elements are stored one over another, and these elements get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First out. + +Stacks and Queues are implemented using Linked Lists + +## Problem Description +Define a Python function `backspace_compare` that comsumes two strings `str1` and `str2` and returns `True` if they are equal when typed into empty text editors and `False` otherwise. The character `#` means a backspace character. +Hint1: Try to think whether a Stack or a queue may be a useful tool to solve this problem! +Hint2: You may find your previously defined magic methods or a new magic method useful for this question. +You may use the implementation of a stack or queue from the lecture slides. + +## Example: +``` +str1 = "ab#c" +str2 = "ad#c" +backspace_compare(str1, str2) == True + +str1 = "a##c" +str2 = "#a#c" +backspace_compare(str1, str2) == True + +str1 = "a#c" +str2 = "c#d" +backspace_compare(str1, str2) == False +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/stacks_and_queues/backspace_compare/solution/solution.py b/data_structures/stacks_and_queues/backspace_compare/solution/solution.py index b401fb69..d52234c3 100644 --- a/data_structures/stacks_and_queues/backspace_compare/solution/solution.py +++ b/data_structures/stacks_and_queues/backspace_compare/solution/solution.py @@ -1,71 +1,71 @@ -class ListNode: - def __init__(self, value): - self.value = value - self.next = None - -class Stack: - def __init__(self): - self.head_node = None - - def push(self, value): - new_head = ListNode(value) - new_head.next = self.head_node - self.head_node = new_head - - def pop(self): - if self.head_node: - value = self.head_node.value - self.head_node = self.head_node.next - return value - else: - raise IndexError - - def __bool__(self): - return not self.head_node == None - - def __len__(self): - cur_node = self.head_node - num_nodes = 0 - while(cur_node): - num_nodes += 1 - cur_node = cur_node.next - return num_nodes - - def __eq__(self, other): - if(len(self) == len(other)): - cur_node1 = self.head_node - cur_node2 = other.head_node - while(cur_node1): - if not cur_node1.value == cur_node2.value: - return False - else: - cur_node1 = cur_node1.next - cur_node2 = cur_node2.next - return True - return False - - -def backspace_compare(str1, str2): - stack1 = Stack() - stack2 = Stack() - for char in str1: - if(char == "#"): - if (stack1): - stack1.pop() - else: - stack1.push(char) - for char in str2: - if(char == "#"): - if (stack2): - stack2.pop() - else: - stack2.push(char) - return stack1 == stack2 - -str1 = "ab#c" -str2 = "ad#c" -print(backspace_compare(str1, str2)) - -str1 = "a#c" -str2 = "c#d" +class ListNode: + def __init__(self, value): + self.value = value + self.next = None + +class Stack: + def __init__(self): + self.head_node = None + + def push(self, value): + new_head = ListNode(value) + new_head.next = self.head_node + self.head_node = new_head + + def pop(self): + if self.head_node: + value = self.head_node.value + self.head_node = self.head_node.next + return value + else: + raise IndexError + + def __bool__(self): + return not self.head_node == None + + def __len__(self): + cur_node = self.head_node + num_nodes = 0 + while(cur_node): + num_nodes += 1 + cur_node = cur_node.next + return num_nodes + + def __eq__(self, other): + if(len(self) == len(other)): + cur_node1 = self.head_node + cur_node2 = other.head_node + while(cur_node1): + if not cur_node1.value == cur_node2.value: + return False + else: + cur_node1 = cur_node1.next + cur_node2 = cur_node2.next + return True + return False + + +def backspace_compare(str1, str2): + stack1 = Stack() + stack2 = Stack() + for char in str1: + if(char == "#"): + if (stack1): + stack1.pop() + else: + stack1.push(char) + for char in str2: + if(char == "#"): + if (stack2): + stack2.pop() + else: + stack2.push(char) + return stack1 == stack2 + +str1 = "ab#c" +str2 = "ad#c" +print(backspace_compare(str1, str2)) + +str1 = "a#c" +str2 = "c#d" print(backspace_compare(str1, str2)) \ No newline at end of file diff --git a/data_structures/stacks_and_queues/backspace_compare/solution/test_solution.py b/data_structures/stacks_and_queues/backspace_compare/solution/test_solution.py index 4e5abbd4..5323b096 100644 --- a/data_structures/stacks_and_queues/backspace_compare/solution/test_solution.py +++ b/data_structures/stacks_and_queues/backspace_compare/solution/test_solution.py @@ -1,6 +1,6 @@ -def test_solution(): - import solution - - assert solution.backspace_compare("ab#c", "ad#c") == True - assert solution.backspace_compare("a##c", "#a#c") == True - assert solution.backspace_compare("a#c", "c#d") == False +def test_solution(): + import solution + + assert solution.backspace_compare("ab#c", "ad#c") == True + assert solution.backspace_compare("a##c", "#a#c") == True + assert solution.backspace_compare("a#c", "c#d") == False diff --git a/data_structures/stacks_and_queues/binary_numbers/README.md b/data_structures/stacks_and_queues/binary_numbers/README.md index 2e4df485..9406608f 100644 --- a/data_structures/stacks_and_queues/binary_numbers/README.md +++ b/data_structures/stacks_and_queues/binary_numbers/README.md @@ -1,25 +1,25 @@ -# Stacks and Queues - Backspace Compare - -## Motivation -Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. - -A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. - -In stacks, elements are stored one over another, and these elements get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First out. - -Stacks and Queues are implemented using Linked Lists - -## Problem Description -Define a Python function `binary_numbers` that comsumes a positive integer `n`, and returns a list of strings of all binary numbers from `1` to `n`. -Hint1: You may find a Queue to be a useful tool to solve this problem! - -## Example: -``` -binary_numbers(5) == ['1', '10', '11', '100', '101'] -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Stacks and Queues - Backspace Compare + +## Motivation +Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. + +A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. + +In stacks, elements are stored one over another, and these elements get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First out. + +Stacks and Queues are implemented using Linked Lists + +## Problem Description +Define a Python function `binary_numbers` that comsumes a positive integer `n`, and returns a list of strings of all binary numbers from `1` to `n`. +Hint1: You may find a Queue to be a useful tool to solve this problem! + +## Example: +``` +binary_numbers(5) == ['1', '10', '11', '100', '101'] +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/stacks_and_queues/binary_numbers/solution/solution.py b/data_structures/stacks_and_queues/binary_numbers/solution/solution.py index c5a2310a..a9f2ed7b 100644 --- a/data_structures/stacks_and_queues/binary_numbers/solution/solution.py +++ b/data_structures/stacks_and_queues/binary_numbers/solution/solution.py @@ -1,86 +1,86 @@ -class ListNode: - def __init__(self, value): - self.value = value - self.next = None - -class Queue: - def __init__(self): - self.head_node = None - self.tail_node = None - - def enqueue(self, value): - new_node = ListNode(value) - if not self.tail_node: - self.head_node = new_node - self.tail_node = new_node - else: - self.tail_node.next = new_node - self.tail_node = new_node - - def dequeue(self): - if not self.head_node: - raise IndexError - value = self.head_node.value - self.head_node = self.head_node.next - if not self.head_node: - self.tail_node = None - return value - - def empty(self): - if self.head_node: - return False - return True - - def __bool__(self): - return not self.head_node == None - - def __len__(self): - cur_node = self.head_node - num_nodes = 0 - while(cur_node): - num_nodes += 1 - cur_node = cur_node.next - return num_nodes - - def __eq__(self, other): - if(len(self) == len(other)): - cur_node1 = self.head_node - cur_node2 = other.head_node - while(cur_node1): - if not cur_node1.value == cur_node2.value: - return False - else: - cur_node1 = cur_node1.next - cur_node2 = cur_node2.next - return True - return False - - def printQ(self): - cur = self.head_node - while(cur): - print(cur.value) - cur = cur.next - - -def binary_numbers(n): - # use a queue to keep track of previous binary numbers - queue = Queue() - # add '1' to our queue are the first binary number - queue.enqueue('1') - bin_lst = [] - for i in range(n): - bin_val = queue.dequeue() - bin_lst.append(bin_val) - queue.enqueue(bin_val+'0') - queue.enqueue(bin_val+'1') - return bin_lst - -print(binary_numbers(1)) - - - - - - - - +class ListNode: + def __init__(self, value): + self.value = value + self.next = None + +class Queue: + def __init__(self): + self.head_node = None + self.tail_node = None + + def enqueue(self, value): + new_node = ListNode(value) + if not self.tail_node: + self.head_node = new_node + self.tail_node = new_node + else: + self.tail_node.next = new_node + self.tail_node = new_node + + def dequeue(self): + if not self.head_node: + raise IndexError + value = self.head_node.value + self.head_node = self.head_node.next + if not self.head_node: + self.tail_node = None + return value + + def empty(self): + if self.head_node: + return False + return True + + def __bool__(self): + return not self.head_node == None + + def __len__(self): + cur_node = self.head_node + num_nodes = 0 + while(cur_node): + num_nodes += 1 + cur_node = cur_node.next + return num_nodes + + def __eq__(self, other): + if(len(self) == len(other)): + cur_node1 = self.head_node + cur_node2 = other.head_node + while(cur_node1): + if not cur_node1.value == cur_node2.value: + return False + else: + cur_node1 = cur_node1.next + cur_node2 = cur_node2.next + return True + return False + + def printQ(self): + cur = self.head_node + while(cur): + print(cur.value) + cur = cur.next + + +def binary_numbers(n): + # use a queue to keep track of previous binary numbers + queue = Queue() + # add '1' to our queue are the first binary number + queue.enqueue('1') + bin_lst = [] + for i in range(n): + bin_val = queue.dequeue() + bin_lst.append(bin_val) + queue.enqueue(bin_val+'0') + queue.enqueue(bin_val+'1') + return bin_lst + +print(binary_numbers(1)) + + + + + + + + diff --git a/data_structures/stacks_and_queues/binary_numbers/solution/test_solution.py b/data_structures/stacks_and_queues/binary_numbers/solution/test_solution.py index 5b9ef82e..74a26baa 100644 --- a/data_structures/stacks_and_queues/binary_numbers/solution/test_solution.py +++ b/data_structures/stacks_and_queues/binary_numbers/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - from solution import binary_numbers - - assert binary_numbers(1) == ['1'] - assert binary_numbers(2) == ['1', '10'] - assert binary_numbers(4) == ['1', '10', '11', '100'] - assert binary_numbers(5) == ['1', '10', '11', '100', '101'] +def test_solution(): + from solution import binary_numbers + + assert binary_numbers(1) == ['1'] + assert binary_numbers(2) == ['1', '10'] + assert binary_numbers(4) == ['1', '10', '11', '100'] + assert binary_numbers(5) == ['1', '10', '11', '100', '101'] diff --git a/data_structures/stacks_and_queues/inorder_to_postorder/README.md b/data_structures/stacks_and_queues/inorder_to_postorder/README.md index 944c1a51..0fa607b5 100644 --- a/data_structures/stacks_and_queues/inorder_to_postorder/README.md +++ b/data_structures/stacks_and_queues/inorder_to_postorder/README.md @@ -1,27 +1,27 @@ -# Stacks and Queues - Backspace Compare - -## Motivation -Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. - -A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. - -In stacks, elements are stored one over another, and these elements get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First out. - -Stacks and Queues are implemented using Linked Lists - -## Problem Description -Define a Python function `inorder_to_postorder` that consues a string, `exp` which will be a mathematical expression in normal inorder notation, and returns a new string with `exp` represented in postorder notation. Note that in this question we will assume expressions are computed in the order of operands. You do not need to worry about the `BEDMAS` rules - (brackets, exponentials, division, multiplication, addition, substraction). -You may use the implementation of a stack and queue from the lecture slides. - - -## Example: -``` -inorder_to_postorder("1+2*3") == "123+*" -inorder_to_postorder("1-2/3+4") == "1234-/+" -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Stacks and Queues - Backspace Compare + +## Motivation +Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. + +A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. + +In stacks, elements are stored one over another, and these elements get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First out. + +Stacks and Queues are implemented using Linked Lists + +## Problem Description +Define a Python function `inorder_to_postorder` that consues a string, `exp` which will be a mathematical expression in normal inorder notation, and returns a new string with `exp` represented in postorder notation. Note that in this question we will assume expressions are computed in the order of operands. You do not need to worry about the `BEDMAS` rules - (brackets, exponentials, division, multiplication, addition, substraction). +You may use the implementation of a stack and queue from the lecture slides. + + +## Example: +``` +inorder_to_postorder("1+2*3") == "123+*" +inorder_to_postorder("1-2/3+4") == "1234-/+" +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/stacks_and_queues/inorder_to_postorder/solution/solution.py b/data_structures/stacks_and_queues/inorder_to_postorder/solution/solution.py index a698d5c9..fd5fa1dc 100644 --- a/data_structures/stacks_and_queues/inorder_to_postorder/solution/solution.py +++ b/data_structures/stacks_and_queues/inorder_to_postorder/solution/solution.py @@ -1,93 +1,93 @@ -class ListNode: - def __init__(self, value): - self.value = value - self.next = None - -class Queue: - def __init__(self): - self.head_node = None - self.tail_node = None - - def enqueue(self, value): - new_node = ListNode(value) - if not self.tail_node: - self.head_node = new_node - self.tail_node = new_node - else: - self.tail_node.next = new_node - self.tail_node = new_node - - def dequeue(self): - if not self.head_node: - raise IndexError - value = self.head_node.value - self.head_node = self.head_node.next - if not self.head_node: - self.tail_node = None - return value - - def empty(self): - if self.head_node: - return False - return True - - def __bool__(self): - return not self.head_node == None - - # Fill in the code for __len__ - def __len__(self): - cur_node = self.head_node - num_nodes = 0 - while(cur_node): - num_nodes += 1 - cur_node = cur_node.next - return num_nodes - - def __eq__(self, other): - if(len(self) == len(other)): - cur_node1 = self.head_node - cur_node2 = other.head_node - while(cur_node1): - if not cur_node1.value == cur_node2.value: - return False - else: - cur_node1 = cur_node1.next - cur_node2 = cur_node2.next - return True - return False - - def printQ(self): - cur = self.head_node - while(cur): - print(cur.value) - cur = cur.next - -def inorder_to_postorder(exp): - # create a queue to store our numbers - num_queue = Queue() - # create a queue to store our operands - op_queue = Queue() - - # itterate through exp enqueuing numbers to num_stack - # and operators to op_stack - for char in exp: - if char.isdigit(): - num_queue.enqueue(char) - else: - op_queue.enqueue(char) - # post_exp will be our postfix expression - post_exp = "" - # itterate through both queues appeding the values to post_exp - while num_queue: - post_exp += num_queue.dequeue() - while op_queue: - post_exp += op_queue.dequeue() - return post_exp - - -print(inorder_to_postorder("1-2/3+4")) -print(inorder_to_postorder("1+2*3")) - - - - +class ListNode: + def __init__(self, value): + self.value = value + self.next = None + +class Queue: + def __init__(self): + self.head_node = None + self.tail_node = None + + def enqueue(self, value): + new_node = ListNode(value) + if not self.tail_node: + self.head_node = new_node + self.tail_node = new_node + else: + self.tail_node.next = new_node + self.tail_node = new_node + + def dequeue(self): + if not self.head_node: + raise IndexError + value = self.head_node.value + self.head_node = self.head_node.next + if not self.head_node: + self.tail_node = None + return value + + def empty(self): + if self.head_node: + return False + return True + + def __bool__(self): + return not self.head_node == None + + # Fill in the code for __len__ + def __len__(self): + cur_node = self.head_node + num_nodes = 0 + while(cur_node): + num_nodes += 1 + cur_node = cur_node.next + return num_nodes + + def __eq__(self, other): + if(len(self) == len(other)): + cur_node1 = self.head_node + cur_node2 = other.head_node + while(cur_node1): + if not cur_node1.value == cur_node2.value: + return False + else: + cur_node1 = cur_node1.next + cur_node2 = cur_node2.next + return True + return False + + def printQ(self): + cur = self.head_node + while(cur): + print(cur.value) + cur = cur.next + +def inorder_to_postorder(exp): + # create a queue to store our numbers + num_queue = Queue() + # create a queue to store our operands + op_queue = Queue() + + # itterate through exp enqueuing numbers to num_stack + # and operators to op_stack + for char in exp: + if char.isdigit(): + num_queue.enqueue(char) + else: + op_queue.enqueue(char) + # post_exp will be our postfix expression + post_exp = "" + # itterate through both queues appeding the values to post_exp + while num_queue: + post_exp += num_queue.dequeue() + while op_queue: + post_exp += op_queue.dequeue() + return post_exp + + +print(inorder_to_postorder("1-2/3+4")) +print(inorder_to_postorder("1+2*3")) + + + + diff --git a/data_structures/stacks_and_queues/inorder_to_postorder/solution/test_solution.py b/data_structures/stacks_and_queues/inorder_to_postorder/solution/test_solution.py index 3cb27d93..c1568b6a 100644 --- a/data_structures/stacks_and_queues/inorder_to_postorder/solution/test_solution.py +++ b/data_structures/stacks_and_queues/inorder_to_postorder/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - from solution import inorder_to_postorder - - assert inorder_to_postorder("1+2+3") == "123++" - assert inorder_to_postorder("1+2*3-4/2") == "12342+*-/" - assert inorder_to_postorder("1") == "1" +def test_solution(): + from solution import inorder_to_postorder + + assert inorder_to_postorder("1+2+3") == "123++" + assert inorder_to_postorder("1+2*3-4/2") == "12342+*-/" + assert inorder_to_postorder("1") == "1" assert inorder_to_postorder("") == "" \ No newline at end of file diff --git a/data_structures/stacks_and_queues/minimum_parentheses/README.md b/data_structures/stacks_and_queues/minimum_parentheses/README.md index 1a78e071..4115c4eb 100644 --- a/data_structures/stacks_and_queues/minimum_parentheses/README.md +++ b/data_structures/stacks_and_queues/minimum_parentheses/README.md @@ -1,32 +1,32 @@ -# Stacks and Queues - Backspace Compare - -## Motivation -Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. - -A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. - -In stacks, elements are stored one over another, and these elements get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First out. - -Stacks and Queues are implemented using Linked Lists - -## Problem Description -Define a Python function `minimum_parenteses` that comsumes a string, `pstr` of open and close parentheses, `(` and `)`. Return the minimum number of parentheses needed to make the string valid. You may add `(` and `)` parentheses in any position in the string. -Hint1: You may find a Stack to be a useful tool to solve this problem! - -## Example: -``` -pstr = "()))((" -minimum_parentheses(pstr) == 4 - -pstr = "((" -minimum_parentheses(pstr) == 2 - -str = "(()())" -minimum_parentheses(pstr) == 0 -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Stacks and Queues - Backspace Compare + +## Motivation +Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. + +A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. + +In stacks, elements are stored one over another, and these elements get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First out. + +Stacks and Queues are implemented using Linked Lists + +## Problem Description +Define a Python function `minimum_parenteses` that comsumes a string, `pstr` of open and close parentheses, `(` and `)`. Return the minimum number of parentheses needed to make the string valid. You may add `(` and `)` parentheses in any position in the string. +Hint1: You may find a Stack to be a useful tool to solve this problem! + +## Example: +``` +pstr = "()))((" +minimum_parentheses(pstr) == 4 + +pstr = "((" +minimum_parentheses(pstr) == 2 + +str = "(()())" +minimum_parentheses(pstr) == 0 +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/stacks_and_queues/minimum_parentheses/solution/solution.py b/data_structures/stacks_and_queues/minimum_parentheses/solution/solution.py index 6edf3893..448eb20c 100644 --- a/data_structures/stacks_and_queues/minimum_parentheses/solution/solution.py +++ b/data_structures/stacks_and_queues/minimum_parentheses/solution/solution.py @@ -1,84 +1,84 @@ -class ListNode: - def __init__(self, value): - self.value = value - self.next = None - -class Stack: - def __init__(self): - self.head_node = None - - def push(self, value): - new_head = ListNode(value) - new_head.next = self.head_node - self.head_node = new_head - - def pop(self): - if self.head_node: - value = self.head_node.value - self.head_node = self.head_node.next - return value - else: - raise IndexError - - def __bool__(self): - return not self.head_node == None - - def __len__(self): - cur_node = self.head_node - num_nodes = 0 - while(cur_node): - num_nodes += 1 - cur_node = cur_node.next - return num_nodes - - def __eq__(self, other): - if(len(self) == len(other)): - cur_node1 = self.head_node - cur_node2 = other.head_node - while(cur_node1): - if not cur_node1.value == cur_node2.value: - return False - else: - cur_node1 = cur_node1.next - cur_node2 = cur_node2.next - return True - return False - - -def minimum_parentheses(pstr): - # use a stack to keep track of open parentheses - stack = Stack() - # keep track of num parentheses you need to add. - num_paren = 0 - - # loop through the parentheses in pstr - for p in pstr: - # push open parentheses onto your stack - if p == '(': - stack.push(p) - # if p is ')' and we have an open parenthese for it to match with - # pop an open parenthese off the stack - elif stack: - stack.pop() - # otherwise we need to add an open parenthese to pstr before p. - else: - num_paren += 1 - # after itterating through the string we need to check if we have - # any remaining opening parentheses in the stack we didn't have - # a matching close parenthese for - while stack: - num_paren += 1 - stack.pop() - return num_paren - -pstr = "()))((" -print(minimum_parentheses(pstr)) - -pstr = "((" -print(minimum_parentheses(pstr)) - -pstr = "(()())" -print(minimum_parentheses(pstr)) - - +class ListNode: + def __init__(self, value): + self.value = value + self.next = None + +class Stack: + def __init__(self): + self.head_node = None + + def push(self, value): + new_head = ListNode(value) + new_head.next = self.head_node + self.head_node = new_head + + def pop(self): + if self.head_node: + value = self.head_node.value + self.head_node = self.head_node.next + return value + else: + raise IndexError + + def __bool__(self): + return not self.head_node == None + + def __len__(self): + cur_node = self.head_node + num_nodes = 0 + while(cur_node): + num_nodes += 1 + cur_node = cur_node.next + return num_nodes + + def __eq__(self, other): + if(len(self) == len(other)): + cur_node1 = self.head_node + cur_node2 = other.head_node + while(cur_node1): + if not cur_node1.value == cur_node2.value: + return False + else: + cur_node1 = cur_node1.next + cur_node2 = cur_node2.next + return True + return False + + +def minimum_parentheses(pstr): + # use a stack to keep track of open parentheses + stack = Stack() + # keep track of num parentheses you need to add. + num_paren = 0 + + # loop through the parentheses in pstr + for p in pstr: + # push open parentheses onto your stack + if p == '(': + stack.push(p) + # if p is ')' and we have an open parenthese for it to match with + # pop an open parenthese off the stack + elif stack: + stack.pop() + # otherwise we need to add an open parenthese to pstr before p. + else: + num_paren += 1 + # after itterating through the string we need to check if we have + # any remaining opening parentheses in the stack we didn't have + # a matching close parenthese for + while stack: + num_paren += 1 + stack.pop() + return num_paren + +pstr = "()))((" +print(minimum_parentheses(pstr)) + +pstr = "((" +print(minimum_parentheses(pstr)) + +pstr = "(()())" +print(minimum_parentheses(pstr)) + + \ No newline at end of file diff --git a/data_structures/stacks_and_queues/minimum_parentheses/solution/test_solution.py b/data_structures/stacks_and_queues/minimum_parentheses/solution/test_solution.py index 7bef1b17..fae1a676 100644 --- a/data_structures/stacks_and_queues/minimum_parentheses/solution/test_solution.py +++ b/data_structures/stacks_and_queues/minimum_parentheses/solution/test_solution.py @@ -1,8 +1,8 @@ -def test_solution(): - from solution import minimum_parentheses - - assert minimum_parentheses("") == 0 - assert minimum_parentheses("(") == 1 - assert minimum_parentheses("()(()())") == 0 - assert minimum_parentheses("()((") == 2 - assert minimum_parentheses("()))((()") == 4 +def test_solution(): + from solution import minimum_parentheses + + assert minimum_parentheses("") == 0 + assert minimum_parentheses("(") == 1 + assert minimum_parentheses("()(()())") == 0 + assert minimum_parentheses("()((") == 2 + assert minimum_parentheses("()))((()") == 4 diff --git a/data_structures/stacks_and_queues/postfix_evaluation/README.md b/data_structures/stacks_and_queues/postfix_evaluation/README.md index 734efcfe..b97ffac3 100644 --- a/data_structures/stacks_and_queues/postfix_evaluation/README.md +++ b/data_structures/stacks_and_queues/postfix_evaluation/README.md @@ -1,34 +1,34 @@ -# Stacks and Queues - Backspace Compare - -## Motivation -Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. - -A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. - -In stacks, elements are stored one over another, and these elements get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First out. - -Stacks and Queues are implemented using Linked Lists - -## Problem Description -Define a Python function `postfix_eval` that comsumes a string, `exp` which is a string of integers followed by operators. This is a mathematical expression in postfix notation. Return the postfix evaluation of the expression. -Hint1: You may find a Queue to be a useful tool to solve this problem! - -## Example: -``` -exp = "123+*" -postfix_eval(exp) == 9 -1+2 = 3 -3*3 = 9 - -exp = "1223+*/" -postfix_eval(exp) == 3 -1+2 = 3 -3*2 = 6 -6/2 = 3 -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Stacks and Queues - Backspace Compare + +## Motivation +Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. + +A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. + +In stacks, elements are stored one over another, and these elements get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First out. + +Stacks and Queues are implemented using Linked Lists + +## Problem Description +Define a Python function `postfix_eval` that comsumes a string, `exp` which is a string of integers followed by operators. This is a mathematical expression in postfix notation. Return the postfix evaluation of the expression. +Hint1: You may find a Queue to be a useful tool to solve this problem! + +## Example: +``` +exp = "123+*" +postfix_eval(exp) == 9 +1+2 = 3 +3*3 = 9 + +exp = "1223+*/" +postfix_eval(exp) == 3 +1+2 = 3 +3*2 = 6 +6/2 = 3 +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/stacks_and_queues/postfix_evaluation/solution/solution.py b/data_structures/stacks_and_queues/postfix_evaluation/solution/solution.py index 722004ca..dd564eed 100644 --- a/data_structures/stacks_and_queues/postfix_evaluation/solution/solution.py +++ b/data_structures/stacks_and_queues/postfix_evaluation/solution/solution.py @@ -1,123 +1,123 @@ -class ListNode: - def __init__(self, value): - self.value = value - self.next = None - -class Queue: - def __init__(self): - self.head_node = None - self.tail_node = None - - def enqueue(self, value): - new_node = ListNode(value) - if not self.tail_node: - self.head_node = new_node - self.tail_node = new_node - else: - self.tail_node.next = new_node - self.tail_node = new_node - - def dequeue(self): - if not self.head_node: - raise IndexError - value = self.head_node.value - self.head_node = self.head_node.next - if not self.head_node: - self.tail_node = None - return value - - def empty(self): - if self.head_node: - return False - return True - - def __bool__(self): - return not self.head_node == None - - # Fill in the code for __len__ - def __len__(self): - cur_node = self.head_node - num_nodes = 0 - while(cur_node): - num_nodes += 1 - cur_node = cur_node.next - return num_nodes - - def __eq__(self, other): - if(len(self) == len(other)): - cur_node1 = self.head_node - cur_node2 = other.head_node - while(cur_node1): - if not cur_node1.value == cur_node2.value: - return False - else: - cur_node1 = cur_node1.next - cur_node2 = cur_node2.next - return True - return False - - def printQ(self): - cur = self.head_node - while(cur): - print(cur.value) - cur = cur.next - - - -def apply(operator, arg1, arg2): - if operator == '+': - return arg1 + arg2 - elif operator == '-': - return arg1 - arg2 - elif operator == '*': - return arg1 * arg2 - elif operator == '/': - return arg1 / arg2 - -def postfix_eval(exp): - # use a queue to keep track of operands - queue = Queue() - # ret_val will contain the evaluated expression - ret_val = 0 - operator = None - - i = 0 - # loop through the digits in exp and add it to our queue - while i < len(exp) and exp[i].isdigit(): - queue.enqueue(int(exp[i])) - i += 1 - queue.printQ() - # if our queue is not empty, assign the first number to ret_val - if queue: - ret_val = queue.dequeue() - # we now hit the operators in exp, so we get the first - # operator and apply it to our first two digits - if i < len(exp): - operator = exp[i] - arg2 = queue.dequeue() - ret_val = apply(operator, ret_val, arg2) - # we increment i to move to the next operator - i += 1 - while i < len(exp): - # get the next operator - operator = exp[i] - # get the next number from the queue for our argument - arg2 = queue.dequeue() - # update ret_val by applying the operator to - # ret_val and the new argument - ret_val = apply(operator, ret_val, arg2) - i += 1 - return ret_val - -exp = "123+*" -print(postfix_eval(exp)) - -exp = "1224+*/" -print(postfix_eval(exp)) - -print(postfix_eval("")) - - - - - +class ListNode: + def __init__(self, value): + self.value = value + self.next = None + +class Queue: + def __init__(self): + self.head_node = None + self.tail_node = None + + def enqueue(self, value): + new_node = ListNode(value) + if not self.tail_node: + self.head_node = new_node + self.tail_node = new_node + else: + self.tail_node.next = new_node + self.tail_node = new_node + + def dequeue(self): + if not self.head_node: + raise IndexError + value = self.head_node.value + self.head_node = self.head_node.next + if not self.head_node: + self.tail_node = None + return value + + def empty(self): + if self.head_node: + return False + return True + + def __bool__(self): + return not self.head_node == None + + # Fill in the code for __len__ + def __len__(self): + cur_node = self.head_node + num_nodes = 0 + while(cur_node): + num_nodes += 1 + cur_node = cur_node.next + return num_nodes + + def __eq__(self, other): + if(len(self) == len(other)): + cur_node1 = self.head_node + cur_node2 = other.head_node + while(cur_node1): + if not cur_node1.value == cur_node2.value: + return False + else: + cur_node1 = cur_node1.next + cur_node2 = cur_node2.next + return True + return False + + def printQ(self): + cur = self.head_node + while(cur): + print(cur.value) + cur = cur.next + + + +def apply(operator, arg1, arg2): + if operator == '+': + return arg1 + arg2 + elif operator == '-': + return arg1 - arg2 + elif operator == '*': + return arg1 * arg2 + elif operator == '/': + return arg1 / arg2 + +def postfix_eval(exp): + # use a queue to keep track of operands + queue = Queue() + # ret_val will contain the evaluated expression + ret_val = 0 + operator = None + + i = 0 + # loop through the digits in exp and add it to our queue + while i < len(exp) and exp[i].isdigit(): + queue.enqueue(int(exp[i])) + i += 1 + queue.printQ() + # if our queue is not empty, assign the first number to ret_val + if queue: + ret_val = queue.dequeue() + # we now hit the operators in exp, so we get the first + # operator and apply it to our first two digits + if i < len(exp): + operator = exp[i] + arg2 = queue.dequeue() + ret_val = apply(operator, ret_val, arg2) + # we increment i to move to the next operator + i += 1 + while i < len(exp): + # get the next operator + operator = exp[i] + # get the next number from the queue for our argument + arg2 = queue.dequeue() + # update ret_val by applying the operator to + # ret_val and the new argument + ret_val = apply(operator, ret_val, arg2) + i += 1 + return ret_val + +exp = "123+*" +print(postfix_eval(exp)) + +exp = "1224+*/" +print(postfix_eval(exp)) + +print(postfix_eval("")) + + + + + diff --git a/data_structures/stacks_and_queues/postfix_evaluation/solution/test_solution.py b/data_structures/stacks_and_queues/postfix_evaluation/solution/test_solution.py index 701e38be..0f47c1e9 100644 --- a/data_structures/stacks_and_queues/postfix_evaluation/solution/test_solution.py +++ b/data_structures/stacks_and_queues/postfix_evaluation/solution/test_solution.py @@ -1,8 +1,8 @@ -def test_solution(): - from solution import postfix_eval - - assert postfix_eval("123+*") == 9 - assert postfix_eval("") == 0 - assert postfix_eval("2") == 2 - assert postfix_eval("3134-*/") == 1.5 - assert postfix_eval("142-*") == -6 +def test_solution(): + from solution import postfix_eval + + assert postfix_eval("123+*") == 9 + assert postfix_eval("") == 0 + assert postfix_eval("2") == 2 + assert postfix_eval("3134-*/") == 1.5 + assert postfix_eval("142-*") == -6 diff --git a/data_structures/stacks_and_queues/queue_bool/README.md b/data_structures/stacks_and_queues/queue_bool/README.md index 6b42c666..1cb7e863 100644 --- a/data_structures/stacks_and_queues/queue_bool/README.md +++ b/data_structures/stacks_and_queues/queue_bool/README.md @@ -1,31 +1,31 @@ -# Queue Magic Method - Boolean - -## Motivation -Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. - -A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. - -A Queue is implemented using Linked Lists - -## Problem Description -Define a Python magic method `__bool__` inside the `Queue` class that returns `False` if the queue is an empty queue and `True` otherwise. -By defining this magic method, we can then use the convenient shorthand notation `if queue: ...` or `while queue: ...` in python. - -You may use the inplementation of a queue from the lecture slides. - -## Example: -``` -queue1 = Queue() -queue1.enqueue(1) -queue1.enqueue(2) -bool(queue1) == True - -queue2 = Queue() -bool(queue2) == False -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Queue Magic Method - Boolean + +## Motivation +Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. + +A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. + +A Queue is implemented using Linked Lists + +## Problem Description +Define a Python magic method `__bool__` inside the `Queue` class that returns `False` if the queue is an empty queue and `True` otherwise. +By defining this magic method, we can then use the convenient shorthand notation `if queue: ...` or `while queue: ...` in python. + +You may use the inplementation of a queue from the lecture slides. + +## Example: +``` +queue1 = Queue() +queue1.enqueue(1) +queue1.enqueue(2) +bool(queue1) == True + +queue2 = Queue() +bool(queue2) == False +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/stacks_and_queues/queue_bool/solution/solution.py b/data_structures/stacks_and_queues/queue_bool/solution/solution.py index c2d512b6..1d2b480b 100644 --- a/data_structures/stacks_and_queues/queue_bool/solution/solution.py +++ b/data_structures/stacks_and_queues/queue_bool/solution/solution.py @@ -1,35 +1,35 @@ -class ListNode: - def __init__(self, value): - self.value = value - self.next = None - -class Queue: - def __init__(self): - self.head_node = None - self.tail_node = None - - def enqueue(self, value): - new_node = ListNode(value) - if not self.tail_node: - self.head_node = new_node - self.tail_node = new_node - else: - self.tail_node.next = new_node - self.tail_node = new_node - - def dequeue(self): - if not self.head_node: - raise IndexError - value = self.head_node.value - self.head_node = self.head_node.next - if not self.head_node: - self.tail_node = None - return value - - def empty(self): - if self.head_node: - return False - return True - - def __bool__(self): - return not self.head_node == None +class ListNode: + def __init__(self, value): + self.value = value + self.next = None + +class Queue: + def __init__(self): + self.head_node = None + self.tail_node = None + + def enqueue(self, value): + new_node = ListNode(value) + if not self.tail_node: + self.head_node = new_node + self.tail_node = new_node + else: + self.tail_node.next = new_node + self.tail_node = new_node + + def dequeue(self): + if not self.head_node: + raise IndexError + value = self.head_node.value + self.head_node = self.head_node.next + if not self.head_node: + self.tail_node = None + return value + + def empty(self): + if self.head_node: + return False + return True + + def __bool__(self): + return not self.head_node == None diff --git a/data_structures/stacks_and_queues/queue_bool/solution/test_solution.py b/data_structures/stacks_and_queues/queue_bool/solution/test_solution.py index 523fae7e..a4d81d04 100644 --- a/data_structures/stacks_and_queues/queue_bool/solution/test_solution.py +++ b/data_structures/stacks_and_queues/queue_bool/solution/test_solution.py @@ -1,11 +1,11 @@ -def test_solution(): - import solution - - queue1 = solution.Queue() - queue1.enqueue(1) - queue1.enqueue(2) - - queue2 = solution.Queue() - - assert bool(queue1) == True - assert bool(queue2) == False +def test_solution(): + import solution + + queue1 = solution.Queue() + queue1.enqueue(1) + queue1.enqueue(2) + + queue2 = solution.Queue() + + assert bool(queue1) == True + assert bool(queue2) == False diff --git a/data_structures/stacks_and_queues/queue_eq/README.md b/data_structures/stacks_and_queues/queue_eq/README.md index 2e40b2cd..5ba50a8a 100644 --- a/data_structures/stacks_and_queues/queue_eq/README.md +++ b/data_structures/stacks_and_queues/queue_eq/README.md @@ -1,32 +1,32 @@ -# Queue Magic Method - Equals - -## Motivation -Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. - -A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. - -A Queue is implemented using Linked Lists - -## Problem Description -Define a Python magic method `__eq__` inside the `Queue` class that returns `True` if two queues are equal and `False` otherwise. -By defining this magic method, we can then use the shothand built in python `==` on a queue objects. - -You may use the inplementation of a queue from the lecture slides. - -## Example: -``` -queue1 = Queue() -queue1.enqueue(1) -queue1.enqueue(2) -queue1.enqueue(3) - -queue2 = Queue() - -(queue1 == queue2) == False -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Queue Magic Method - Equals + +## Motivation +Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. + +A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. + +A Queue is implemented using Linked Lists + +## Problem Description +Define a Python magic method `__eq__` inside the `Queue` class that returns `True` if two queues are equal and `False` otherwise. +By defining this magic method, we can then use the shothand built in python `==` on a queue objects. + +You may use the inplementation of a queue from the lecture slides. + +## Example: +``` +queue1 = Queue() +queue1.enqueue(1) +queue1.enqueue(2) +queue1.enqueue(3) + +queue2 = Queue() + +(queue1 == queue2) == False +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/stacks_and_queues/queue_eq/solution/solution.py b/data_structures/stacks_and_queues/queue_eq/solution/solution.py index 5c663291..fb9f67fb 100644 --- a/data_structures/stacks_and_queues/queue_eq/solution/solution.py +++ b/data_structures/stacks_and_queues/queue_eq/solution/solution.py @@ -1,54 +1,54 @@ -class ListNode: - def __init__(self, value): - self.value = value - self.next = None - -class Queue: - def __init__(self): - self.head_node = None - self.tail_node = None - - def enqueue(self, value): - new_node = ListNode(value) - if not self.tail_node: - self.head_node = new_node - self.tail_node = new_node - else: - self.tail_node.next = new_node - self.tail_node = new_node - - def dequeue(self): - if not self.head_node: - raise IndexError - value = self.head_node.value - self.head_node = self.head_node.next - if not self.head_node: - self.tail_node = None - return value - - def empty(self): - if self.head_node: - return False - return True - - # Fill in the code for __len__ - def __len__(self): - cur_node = self.head_node - num_nodes = 0 - while(cur_node): - num_nodes += 1 - cur_node = cur_node.next - return num_nodes - - def __eq__(self, other): - if(len(self) == len(other)): - cur_node1 = self.head_node - cur_node2 = other.head_node - while(cur_node1): - if not cur_node1.value == cur_node2.value: - return False - else: - cur_node1 = cur_node1.next - cur_node2 = cur_node2.next - return True - return False +class ListNode: + def __init__(self, value): + self.value = value + self.next = None + +class Queue: + def __init__(self): + self.head_node = None + self.tail_node = None + + def enqueue(self, value): + new_node = ListNode(value) + if not self.tail_node: + self.head_node = new_node + self.tail_node = new_node + else: + self.tail_node.next = new_node + self.tail_node = new_node + + def dequeue(self): + if not self.head_node: + raise IndexError + value = self.head_node.value + self.head_node = self.head_node.next + if not self.head_node: + self.tail_node = None + return value + + def empty(self): + if self.head_node: + return False + return True + + # Fill in the code for __len__ + def __len__(self): + cur_node = self.head_node + num_nodes = 0 + while(cur_node): + num_nodes += 1 + cur_node = cur_node.next + return num_nodes + + def __eq__(self, other): + if(len(self) == len(other)): + cur_node1 = self.head_node + cur_node2 = other.head_node + while(cur_node1): + if not cur_node1.value == cur_node2.value: + return False + else: + cur_node1 = cur_node1.next + cur_node2 = cur_node2.next + return True + return False diff --git a/data_structures/stacks_and_queues/queue_eq/solution/test_solution.py b/data_structures/stacks_and_queues/queue_eq/solution/test_solution.py index b9f9ca51..26b50152 100644 --- a/data_structures/stacks_and_queues/queue_eq/solution/test_solution.py +++ b/data_structures/stacks_and_queues/queue_eq/solution/test_solution.py @@ -1,17 +1,17 @@ -def test_solution(): - import solution - - queue1 = solution.Queue() - queue1.enqueue(1) - queue1.enqueue(2) - queue1.enqueue(3) - - queue2 = solution.Queue() - queue2.enqueue(1) - - queue3 = solution.Queue() - queue3.enqueue(1) - - assert (queue1 == queue2) == False - assert (queue2 == queue3) == True +def test_solution(): + import solution + + queue1 = solution.Queue() + queue1.enqueue(1) + queue1.enqueue(2) + queue1.enqueue(3) + + queue2 = solution.Queue() + queue2.enqueue(1) + + queue3 = solution.Queue() + queue3.enqueue(1) + + assert (queue1 == queue2) == False + assert (queue2 == queue3) == True assert (queue3 == queue1) == False \ No newline at end of file diff --git a/data_structures/stacks_and_queues/queue_len/README.md b/data_structures/stacks_and_queues/queue_len/README.md index 212d48ad..773fba4a 100644 --- a/data_structures/stacks_and_queues/queue_len/README.md +++ b/data_structures/stacks_and_queues/queue_len/README.md @@ -1,33 +1,33 @@ -# Queue Magic Method - Length - -## Motivation -Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. - -A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. - -A Queue is implemented using Linked Lists - -## Problem Description -Define a Python magic method `__len__` inside the `Queue` class that returns the length of the queue. -By defining this magic method, we can then use the shothand built in python len() on a queue object. - -You may use the inplementation of a queue from the lecture slides. - - -## Example: -``` -queue1 = Queue() -queue1.enqueue(1) -queue1.enqueue(2) -queue1.enqueue(3) -len(queue1) == 3 - -queue2 = Queue() -len(queue2) == 0 -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Queue Magic Method - Length + +## Motivation +Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. + +A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. + +A Queue is implemented using Linked Lists + +## Problem Description +Define a Python magic method `__len__` inside the `Queue` class that returns the length of the queue. +By defining this magic method, we can then use the shothand built in python len() on a queue object. + +You may use the inplementation of a queue from the lecture slides. + + +## Example: +``` +queue1 = Queue() +queue1.enqueue(1) +queue1.enqueue(2) +queue1.enqueue(3) +len(queue1) == 3 + +queue2 = Queue() +len(queue2) == 0 +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/stacks_and_queues/queue_len/solution/solution.py b/data_structures/stacks_and_queues/queue_len/solution/solution.py index da525158..9d8f8534 100644 --- a/data_structures/stacks_and_queues/queue_len/solution/solution.py +++ b/data_structures/stacks_and_queues/queue_len/solution/solution.py @@ -1,41 +1,41 @@ -class ListNode: - def __init__(self, value): - self.value = value - self.next = None - -class Queue: - def __init__(self): - self.head_node = None - self.tail_node = None - - def enqueue(self, value): - new_node = ListNode(value) - if not self.tail_node: - self.head_node = new_node - self.tail_node = new_node - else: - self.tail_node.next = new_node - self.tail_node = new_node - - def dequeue(self): - if not self.head_node: - raise IndexError - value = self.head_node.value - self.head_node = self.head_node.next - if not self.head_node: - self.tail_node = None - return value - - def empty(self): - if self.head_node: - return False - return True - - # Fill in the code for __len__ - def __len__(self): - cur_node = self.head_node - num_nodes = 0 - while(cur_node): - num_nodes += 1 - cur_node = cur_node.next +class ListNode: + def __init__(self, value): + self.value = value + self.next = None + +class Queue: + def __init__(self): + self.head_node = None + self.tail_node = None + + def enqueue(self, value): + new_node = ListNode(value) + if not self.tail_node: + self.head_node = new_node + self.tail_node = new_node + else: + self.tail_node.next = new_node + self.tail_node = new_node + + def dequeue(self): + if not self.head_node: + raise IndexError + value = self.head_node.value + self.head_node = self.head_node.next + if not self.head_node: + self.tail_node = None + return value + + def empty(self): + if self.head_node: + return False + return True + + # Fill in the code for __len__ + def __len__(self): + cur_node = self.head_node + num_nodes = 0 + while(cur_node): + num_nodes += 1 + cur_node = cur_node.next return num_nodes \ No newline at end of file diff --git a/data_structures/stacks_and_queues/queue_len/solution/test_solution.py b/data_structures/stacks_and_queues/queue_len/solution/test_solution.py index 2d59cb5b..144a2843 100644 --- a/data_structures/stacks_and_queues/queue_len/solution/test_solution.py +++ b/data_structures/stacks_and_queues/queue_len/solution/test_solution.py @@ -1,18 +1,18 @@ -def test_solution(): - import solution - - queue1 = solution.Queue() - queue1.enqueue(1) - queue1.enqueue(2) - queue1.enqueue(3) - queue1.enqueue(4) - queue1.enqueue(5) - - queue2 = solution.Queue() - queue2.enqueue(2) - - queue3 = solution.Queue() - - assert len(queue1) == 5 - assert len(queue2) == 1 +def test_solution(): + import solution + + queue1 = solution.Queue() + queue1.enqueue(1) + queue1.enqueue(2) + queue1.enqueue(3) + queue1.enqueue(4) + queue1.enqueue(5) + + queue2 = solution.Queue() + queue2.enqueue(2) + + queue3 = solution.Queue() + + assert len(queue1) == 5 + assert len(queue2) == 1 assert len(queue3) == 0 \ No newline at end of file diff --git a/data_structures/stacks_and_queues/reverse_queue/README.md b/data_structures/stacks_and_queues/reverse_queue/README.md index 567992d4..b92c6713 100644 --- a/data_structures/stacks_and_queues/reverse_queue/README.md +++ b/data_structures/stacks_and_queues/reverse_queue/README.md @@ -1,37 +1,37 @@ -# Stacks and Queues - Backspace Compare - -## Motivation -Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. - -A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. - -In stacks, elements are stored one over another, and these elements get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First out. - -Stacks and Queues are implemented using Linked Lists - -## Problem Description -In the Queue class, define a method `reverse_queue` that reverses a queue and returns None. You may use a stack in the implementation of this method. -You may use the implementation of a stack and queue from the lecture slides. - - -## Example: -``` -queue = Queue() -queue.enqueue(1) -queue.enqueue(2) -queue.enqueue(3) - -retqueue = Queue() -retqueue.enqueue(3) -retqueue.enqueue(2) -retqueue.enqueue(1) - -queue.reverse_queue() == None -queue == retqueue -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Stacks and Queues - Backspace Compare + +## Motivation +Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. + +A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. + +In stacks, elements are stored one over another, and these elements get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First out. + +Stacks and Queues are implemented using Linked Lists + +## Problem Description +In the Queue class, define a method `reverse_queue` that reverses a queue and returns None. You may use a stack in the implementation of this method. +You may use the implementation of a stack and queue from the lecture slides. + + +## Example: +``` +queue = Queue() +queue.enqueue(1) +queue.enqueue(2) +queue.enqueue(3) + +retqueue = Queue() +retqueue.enqueue(3) +retqueue.enqueue(2) +retqueue.enqueue(1) + +queue.reverse_queue() == None +queue == retqueue +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/stacks_and_queues/reverse_queue/solution/solution.py b/data_structures/stacks_and_queues/reverse_queue/solution/solution.py index 844d63cc..2823dfef 100644 --- a/data_structures/stacks_and_queues/reverse_queue/solution/solution.py +++ b/data_structures/stacks_and_queues/reverse_queue/solution/solution.py @@ -1,111 +1,111 @@ -class ListNode: - def __init__(self, value): - self.value = value - self.next = None - -class Stack: - def __init__(self): - self.head_node = None - - def push(self, value): - new_head = ListNode(value) - new_head.next = self.head_node - self.head_node = new_head - - def pop(self): - if self.head_node: - value = self.head_node.value - self.head_node = self.head_node.next - return value - else: - raise IndexError - - def __len__(self): - cur_node = self.head_node - num_nodes = 0 - while(cur_node): - num_nodes += 1 - cur_node = cur_node.next - return num_nodes - - def __bool__(self): - return not self.head_node == None - - -class Queue: - def __init__(self): - self.head_node = None - self.tail_node = None - - def enqueue(self, value): - new_node = ListNode(value) - if not self.tail_node: - self.head_node = new_node - self.tail_node = new_node - else: - self.tail_node.next = new_node - self.tail_node = new_node - - def dequeue(self): - if not self.head_node: - raise IndexError - value = self.head_node.value - self.head_node = self.head_node.next - if not self.head_node: - self.tail_node = None - return value - - def empty(self): - if self.head_node: - return False - return True - - def __bool__(self): - return not self.head_node == None - - def __len__(self): - cur_node = self.head_node - num_nodes = 0 - while(cur_node): - num_nodes += 1 - cur_node = cur_node.next - return num_nodes - - def __eq__(self, other): - if(len(self) == len(other)): - cur_node1 = self.head_node - cur_node2 = other.head_node - while(cur_node1): - if not cur_node1.value == cur_node2.value: - return False - else: - cur_node1 = cur_node1.next - cur_node2 = cur_node2.next - return True - return False - - def printQ(self): - cur = self.head_node - while(cur): - print(cur.value) - cur = cur.next - - def reverse_queue(self): - # create a new stack to store values in the queue - stack = Stack() - # get the first node in our queue - cur_node = self.head_node - # itterate through the nodes in our queue - while(cur_node): - # remove the node from queue and add the value to our stack - stack.push(self.dequeue()) - # move on to next node in queue - cur_node = cur_node.next - # itterate through the stack adding each value back into our queue - while(stack): - self.enqueue(stack.pop()) - - - - - +class ListNode: + def __init__(self, value): + self.value = value + self.next = None + +class Stack: + def __init__(self): + self.head_node = None + + def push(self, value): + new_head = ListNode(value) + new_head.next = self.head_node + self.head_node = new_head + + def pop(self): + if self.head_node: + value = self.head_node.value + self.head_node = self.head_node.next + return value + else: + raise IndexError + + def __len__(self): + cur_node = self.head_node + num_nodes = 0 + while(cur_node): + num_nodes += 1 + cur_node = cur_node.next + return num_nodes + + def __bool__(self): + return not self.head_node == None + + +class Queue: + def __init__(self): + self.head_node = None + self.tail_node = None + + def enqueue(self, value): + new_node = ListNode(value) + if not self.tail_node: + self.head_node = new_node + self.tail_node = new_node + else: + self.tail_node.next = new_node + self.tail_node = new_node + + def dequeue(self): + if not self.head_node: + raise IndexError + value = self.head_node.value + self.head_node = self.head_node.next + if not self.head_node: + self.tail_node = None + return value + + def empty(self): + if self.head_node: + return False + return True + + def __bool__(self): + return not self.head_node == None + + def __len__(self): + cur_node = self.head_node + num_nodes = 0 + while(cur_node): + num_nodes += 1 + cur_node = cur_node.next + return num_nodes + + def __eq__(self, other): + if(len(self) == len(other)): + cur_node1 = self.head_node + cur_node2 = other.head_node + while(cur_node1): + if not cur_node1.value == cur_node2.value: + return False + else: + cur_node1 = cur_node1.next + cur_node2 = cur_node2.next + return True + return False + + def printQ(self): + cur = self.head_node + while(cur): + print(cur.value) + cur = cur.next + + def reverse_queue(self): + # create a new stack to store values in the queue + stack = Stack() + # get the first node in our queue + cur_node = self.head_node + # itterate through the nodes in our queue + while(cur_node): + # remove the node from queue and add the value to our stack + stack.push(self.dequeue()) + # move on to next node in queue + cur_node = cur_node.next + # itterate through the stack adding each value back into our queue + while(stack): + self.enqueue(stack.pop()) + + + + + diff --git a/data_structures/stacks_and_queues/reverse_queue/solution/test_solution.py b/data_structures/stacks_and_queues/reverse_queue/solution/test_solution.py index 768fbd1e..2937d8f4 100644 --- a/data_structures/stacks_and_queues/reverse_queue/solution/test_solution.py +++ b/data_structures/stacks_and_queues/reverse_queue/solution/test_solution.py @@ -1,24 +1,24 @@ -def test_solution(): - from solution import Queue - - queue = Queue() - queue.enqueue(1) - queue.enqueue(2) - queue.enqueue(3) - - retqueue = Queue() - retqueue.enqueue(3) - retqueue.enqueue(2) - retqueue.enqueue(1) - - queue2 = Queue() - queue2.enqueue(1) - - queue3 = Queue() - - assert queue.reverse_queue() == None - assert queue == retqueue - assert queue2.reverse_queue() == None - assert queue2 == queue2 - assert queue3.reverse_queue() == None - assert queue3 == queue3 +def test_solution(): + from solution import Queue + + queue = Queue() + queue.enqueue(1) + queue.enqueue(2) + queue.enqueue(3) + + retqueue = Queue() + retqueue.enqueue(3) + retqueue.enqueue(2) + retqueue.enqueue(1) + + queue2 = Queue() + queue2.enqueue(1) + + queue3 = Queue() + + assert queue.reverse_queue() == None + assert queue == retqueue + assert queue2.reverse_queue() == None + assert queue2 == queue2 + assert queue3.reverse_queue() == None + assert queue3 == queue3 diff --git a/data_structures/stacks_and_queues/reverse_words/README.md b/data_structures/stacks_and_queues/reverse_words/README.md index 3e0068c0..6ae4b504 100644 --- a/data_structures/stacks_and_queues/reverse_words/README.md +++ b/data_structures/stacks_and_queues/reverse_words/README.md @@ -1,26 +1,26 @@ -# Stacks and Queues - Backspace Compare - -## Motivation -Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. - -A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. - -In stacks, elements are stored one over another, and these elements get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First out. - -Stacks and Queues are implemented using Linked Lists - -## Problem Description -Define a Python function `reverse_words` that comsumes a string `sentence`, which is a string of words seperated by spaces. Return a string where the order of the words in `sentece` is reversed. -You may use the implementation of a stack or queue from the lecture slides. - -## Example: -``` -sentence = "hello bonjour aloha" -reverse_words(sentence) == "aloha bonjour hello" -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Stacks and Queues - Backspace Compare + +## Motivation +Data structures organize the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. + +A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back and can remove elements from the front. + +In stacks, elements are stored one over another, and these elements get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First out. + +Stacks and Queues are implemented using Linked Lists + +## Problem Description +Define a Python function `reverse_words` that comsumes a string `sentence`, which is a string of words seperated by spaces. Return a string where the order of the words in `sentece` is reversed. +You may use the implementation of a stack or queue from the lecture slides. + +## Example: +``` +sentence = "hello bonjour aloha" +reverse_words(sentence) == "aloha bonjour hello" +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/data_structures/stacks_and_queues/reverse_words/solution/solution.py b/data_structures/stacks_and_queues/reverse_words/solution/solution.py index 45e6c26c..e4b1b1ba 100644 --- a/data_structures/stacks_and_queues/reverse_words/solution/solution.py +++ b/data_structures/stacks_and_queues/reverse_words/solution/solution.py @@ -1,69 +1,69 @@ -class ListNode: - def __init__(self, value): - self.value = value - self.next = None - -class Stack: - def __init__(self): - self.head_node = None - - def push(self, value): - new_head = ListNode(value) - new_head.next = self.head_node - self.head_node = new_head - - def pop(self): - if self.head_node: - value = self.head_node.value - self.head_node = self.head_node.next - return value - else: - raise IndexError - - def __bool__(self): - return not self.head_node == None - - def __len__(self): - cur_node = self.head_node - num_nodes = 0 - while(cur_node): - num_nodes += 1 - cur_node = cur_node.next - return num_nodes - - def __eq__(self, other): - if(len(self) == len(other)): - cur_node1 = self.head_node - cur_node2 = other.head_node - while(cur_node1): - if not cur_node1.value == cur_node2.value: - return False - else: - cur_node1 = cur_node1.next - cur_node2 = cur_node2.next - return True - return False - - -def reverse_words(sentence): - # create a stack to keep track of our words - stack = Stack() - # split our sentence on spaces - slst = sentence.split() - # push all words onto our stack. The last word will - # then be at the top of the stack. - for word in slst: - stack.push(word) - new_s = "" - # itterate through the stack appending each word to our new sentence - while stack: - new_s += stack.pop() - new_s += " " - # remove the last space character at the end of the sentence - return new_s[:-1] - -sentence = "hello bonjour aloha" -print(reverse_words(sentence)) - - - +class ListNode: + def __init__(self, value): + self.value = value + self.next = None + +class Stack: + def __init__(self): + self.head_node = None + + def push(self, value): + new_head = ListNode(value) + new_head.next = self.head_node + self.head_node = new_head + + def pop(self): + if self.head_node: + value = self.head_node.value + self.head_node = self.head_node.next + return value + else: + raise IndexError + + def __bool__(self): + return not self.head_node == None + + def __len__(self): + cur_node = self.head_node + num_nodes = 0 + while(cur_node): + num_nodes += 1 + cur_node = cur_node.next + return num_nodes + + def __eq__(self, other): + if(len(self) == len(other)): + cur_node1 = self.head_node + cur_node2 = other.head_node + while(cur_node1): + if not cur_node1.value == cur_node2.value: + return False + else: + cur_node1 = cur_node1.next + cur_node2 = cur_node2.next + return True + return False + + +def reverse_words(sentence): + # create a stack to keep track of our words + stack = Stack() + # split our sentence on spaces + slst = sentence.split() + # push all words onto our stack. The last word will + # then be at the top of the stack. + for word in slst: + stack.push(word) + new_s = "" + # itterate through the stack appending each word to our new sentence + while stack: + new_s += stack.pop() + new_s += " " + # remove the last space character at the end of the sentence + return new_s[:-1] + +sentence = "hello bonjour aloha" +print(reverse_words(sentence)) + + + diff --git a/data_structures/stacks_and_queues/reverse_words/solution/test_solution.py b/data_structures/stacks_and_queues/reverse_words/solution/test_solution.py index 5b0309ea..f71c5b73 100644 --- a/data_structures/stacks_and_queues/reverse_words/solution/test_solution.py +++ b/data_structures/stacks_and_queues/reverse_words/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - from solution import reverse_words - - assert reverse_words("hi there") == "there hi" - assert reverse_words("hello") == "hello" - assert reverse_words("") == "" +def test_solution(): + from solution import reverse_words + + assert reverse_words("hi there") == "there hi" + assert reverse_words("hello") == "hello" + assert reverse_words("") == "" assert reverse_words("don't forget to be awesome") == "awesome be to forget don't" \ No newline at end of file diff --git a/hello.txt b/hello.txt new file mode 100644 index 00000000..23c3aefe --- /dev/null +++ b/hello.txt @@ -0,0 +1 @@ +Hello World!! diff --git a/intro_&_enviro/README.md b/intro_&_enviro/README.md new file mode 100644 index 00000000..f229976c --- /dev/null +++ b/intro_&_enviro/README.md @@ -0,0 +1,9 @@ +# Exercise Organization + +| Section ID | Section Name | +|:-----------:|:--------:| +| 1 | [Hello World]() | +| 2 | [UNIX and Bash]() | +| 3 | [git]() | +| 4 | [Introduction to Programming]() | +| 5 | [Data Types and Control Flow]() | diff --git a/intro_&_enviro/data_types_and_control_flow/1_compare_check/README.md b/intro_&_enviro/data_types_and_control_flow/1_compare_check/README.md new file mode 100644 index 00000000..37954ff2 --- /dev/null +++ b/intro_&_enviro/data_types_and_control_flow/1_compare_check/README.md @@ -0,0 +1,17 @@ +# Compare Check + +## Motivation +Python provides == operator to check if the object on LHS and RHS hold similar values. + +!= for not equal values. + +## Problem Description +Write a python script that contains 2 integers `x` and `y` variable values whos contents is hidden from you. +Create a variable `result` to check if x and y hold same values or not. +Print the boolean result . + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/intro_&_enviro/data_types_and_control_flow/1_compare_check/Solution/.model_solution.py b/intro_&_enviro/data_types_and_control_flow/1_compare_check/Solution/.model_solution.py new file mode 100644 index 00000000..c92a4c1d --- /dev/null +++ b/intro_&_enviro/data_types_and_control_flow/1_compare_check/Solution/.model_solution.py @@ -0,0 +1,5 @@ +# Code your solution here +x = 200 +y = 201 +result = x == y +print(result) diff --git a/intro_&_enviro/data_types_and_control_flow/1_compare_check/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/1_compare_check/Solution/solution.py new file mode 100644 index 00000000..00016e55 --- /dev/null +++ b/intro_&_enviro/data_types_and_control_flow/1_compare_check/Solution/solution.py @@ -0,0 +1,5 @@ +# Code your solution here +x=200 +y=201 +result=x==y +print(result) diff --git a/intro_&_enviro/data_types_and_control_flow/1_compare_check/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/1_compare_check/Solution/test_solution.py new file mode 100644 index 00000000..e70c4f98 --- /dev/null +++ b/intro_&_enviro/data_types_and_control_flow/1_compare_check/Solution/test_solution.py @@ -0,0 +1,15 @@ + +def test_solution(monkeypatch): + ret_val1= None + + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.x==200 + assert solution.y==201 + + diff --git a/introduction_and_environment/data_types_and_control_flow/1_even_odd/README.md b/intro_&_enviro/data_types_and_control_flow/1_even_odd/README.md similarity index 96% rename from introduction_and_environment/data_types_and_control_flow/1_even_odd/README.md rename to intro_&_enviro/data_types_and_control_flow/1_even_odd/README.md index 8f1c3cb5..29b6f9d4 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_even_odd/README.md +++ b/intro_&_enviro/data_types_and_control_flow/1_even_odd/README.md @@ -1,15 +1,15 @@ -# Even Odd - -## Motivation -Natural numbers are either even or odd in nature. How do we check !? - -## Problem Description -Write a Python script that asks the user for an integer stored in object `number`. -Construct logic using If-Else where you check whether the number is `Even` or `Odd` and store result in `data` variable. -Print the result. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Even Odd + +## Motivation +Natural numbers are either even or odd in nature. How do we check !? + +## Problem Description +Write a Python script that asks the user for an integer stored in object `number`. +Construct logic using If-Else where you check whether the number is `Even` or `Odd` and store result in `data` variable. +Print the result. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/1_even_odd/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/1_even_odd/Solution/solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/1_even_odd/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/1_even_odd/Solution/solution.py index 952fb8ec..7933795e 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_even_odd/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/1_even_odd/Solution/solution.py @@ -1,7 +1,7 @@ -# Code your solution here -number=int(input()) -if (number%2)==0: - data="Even" -else: - data="Odd" +# Code your solution here +number=int(input()) +if (number%2)==0: + data="Even" +else: + data="Odd" print(data) \ No newline at end of file diff --git a/introduction_and_environment/data_types_and_control_flow/1_even_odd/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/1_even_odd/Solution/test_solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/1_even_odd/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/1_even_odd/Solution/test_solution.py index 3c17606b..9616f45a 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_even_odd/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/1_even_odd/Solution/test_solution.py @@ -1,20 +1,20 @@ -def test_solution(monkeypatch): - x=744 - ret_val1= None - - def f(): - nonlocal x - return x - - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.input',f) - monkeypatch.setattr('builtins.print',g) - - import solution - assert solution.number==x - - - +def test_solution(monkeypatch): + x=744 + ret_val1= None + + def f(): + nonlocal x + return x + + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.number==x + + + diff --git a/introduction_and_environment/data_types_and_control_flow/1_list_max/README.md b/intro_&_enviro/data_types_and_control_flow/1_list_max/README.md similarity index 98% rename from introduction_and_environment/data_types_and_control_flow/1_list_max/README.md rename to intro_&_enviro/data_types_and_control_flow/1_list_max/README.md index f6512542..827749d2 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_list_max/README.md +++ b/intro_&_enviro/data_types_and_control_flow/1_list_max/README.md @@ -1,15 +1,15 @@ -# Max in a 5 integer list - -You are provided with a list named `L` containing 5 integers whos contents is hidden from you in `solution.py`. Your goal is to determine which integer in the list is the maximum integer and store this integer in the `LIST_MAX` variable provided to you. - -* You can only use conditionals to solve this question - * Do not use iteration - * Do not use the `max` function - -## Testing -* To test your solution, simply type 'pytest' within the **Solutions** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory -* The file contains 1 variables - `LIST_MAX` representing the maximum integer in the list -* Overwrite this integer with your answers +# Max in a 5 integer list + +You are provided with a list named `L` containing 5 integers whos contents is hidden from you in `solution.py`. Your goal is to determine which integer in the list is the maximum integer and store this integer in the `LIST_MAX` variable provided to you. + +* You can only use conditionals to solve this question + * Do not use iteration + * Do not use the `max` function + +## Testing +* To test your solution, simply type 'pytest' within the **Solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +* The file contains 1 variables - `LIST_MAX` representing the maximum integer in the list +* Overwrite this integer with your answers diff --git a/introduction_and_environment/data_types_and_control_flow/1_list_max/solution/provided_code.py b/intro_&_enviro/data_types_and_control_flow/1_list_max/solution/provided_code.py similarity index 96% rename from introduction_and_environment/data_types_and_control_flow/1_list_max/solution/provided_code.py rename to intro_&_enviro/data_types_and_control_flow/1_list_max/solution/provided_code.py index e75ceae4..463c38c2 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_list_max/solution/provided_code.py +++ b/intro_&_enviro/data_types_and_control_flow/1_list_max/solution/provided_code.py @@ -1 +1 @@ -L = [152, 463, 1112, 1337, -10] +L = [152, 463, 1112, 1337, -10] diff --git a/introduction_and_environment/data_types_and_control_flow/1_list_max/solution/solution.py b/intro_&_enviro/data_types_and_control_flow/1_list_max/solution/solution.py similarity index 93% rename from introduction_and_environment/data_types_and_control_flow/1_list_max/solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/1_list_max/solution/solution.py index 1d2215ea..012e50e9 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_list_max/solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/1_list_max/solution/solution.py @@ -1,3 +1,3 @@ -from provided_code import L - -LIST_MAX = 0 +from provided_code import L + +LIST_MAX = 0 diff --git a/introduction_and_environment/data_types_and_control_flow/1_list_max/solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/1_list_max/solution/test_solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/1_list_max/solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/1_list_max/solution/test_solution.py index f7c22772..1036a290 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_list_max/solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/1_list_max/solution/test_solution.py @@ -1,4 +1,4 @@ -import solution - -def test_solution(): - assert solution.LIST_MAX == 1337 +import solution + +def test_solution(): + assert solution.LIST_MAX == 1337 diff --git a/introduction_and_environment/data_types_and_control_flow/1_loop_divisibility/README.md b/intro_&_enviro/data_types_and_control_flow/1_loop_divisibility/README.md similarity index 97% rename from introduction_and_environment/data_types_and_control_flow/1_loop_divisibility/README.md rename to intro_&_enviro/data_types_and_control_flow/1_loop_divisibility/README.md index 9f72426b..3b0479d1 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_loop_divisibility/README.md +++ b/intro_&_enviro/data_types_and_control_flow/1_loop_divisibility/README.md @@ -1,15 +1,15 @@ -# Loop Divisible - -## Motivation -Generate sequence of numbers which are divisible for 5 and 7 , having a limit range of upto 50. - -## Problem Description -Write a Python script that declares a variable `x` containing value hidden from you. -Construct a loop to run upto length of `x` to retrieve values which are divisible by 5 and 7 , store the result values in `data` variable. -Print the result. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Loop Divisible + +## Motivation +Generate sequence of numbers which are divisible for 5 and 7 , having a limit range of upto 50. + +## Problem Description +Write a Python script that declares a variable `x` containing value hidden from you. +Construct a loop to run upto length of `x` to retrieve values which are divisible by 5 and 7 , store the result values in `data` variable. +Print the result. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/1_loop_divisibility/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/1_loop_divisibility/Solution/solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/1_loop_divisibility/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/1_loop_divisibility/Solution/solution.py index d662c2c9..5c2cf4d2 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_loop_divisibility/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/1_loop_divisibility/Solution/solution.py @@ -1,11 +1,11 @@ -# Code your solution here -x=50 -data=[] -for i in range(1,x): - if (i%5)==0 and (i%7)==0: - data.append(i) - else: - pass -print(data) - +# Code your solution here +x=50 +data=[] +for i in range(1,x): + if (i%5)==0 and (i%7)==0: + data.append(i) + else: + pass +print(data) + \ No newline at end of file diff --git a/introduction_and_environment/data_types_and_control_flow/1_loop_divisibility/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/1_loop_divisibility/Solution/test_solution.py similarity index 93% rename from introduction_and_environment/data_types_and_control_flow/1_loop_divisibility/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/1_loop_divisibility/Solution/test_solution.py index 4affda4b..86f1cde7 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_loop_divisibility/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/1_loop_divisibility/Solution/test_solution.py @@ -1,14 +1,14 @@ -def test_solution(monkeypatch): - y=50 - ret_val1= None - - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - monkeypatch.setattr('builtins.print',g) - - import solution - assert solution.x==y - - - +def test_solution(monkeypatch): + y=50 + ret_val1= None + + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.x==y + + + diff --git a/introduction_and_environment/data_types_and_control_flow/1_string_convert/README.md b/intro_&_enviro/data_types_and_control_flow/1_string_convert/README.md similarity index 97% rename from introduction_and_environment/data_types_and_control_flow/1_string_convert/README.md rename to intro_&_enviro/data_types_and_control_flow/1_string_convert/README.md index 2b0085d7..a3395030 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_string_convert/README.md +++ b/intro_&_enviro/data_types_and_control_flow/1_string_convert/README.md @@ -1,15 +1,15 @@ -# String Convert - -## Motivation -By default the input() keyword captures data in a string format unless we try to explicitly type cast. - -## Problem Description -Write a Python script that asks the user for a string value stored in object `string`. -Your goal is to check whether the value is in upperCase ,if so convert the data into lowerCase else if value is in lowerCase , convert the data into upperCase and store the result in `data` variable. -Print the result. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# String Convert + +## Motivation +By default the input() keyword captures data in a string format unless we try to explicitly type cast. + +## Problem Description +Write a Python script that asks the user for a string value stored in object `string`. +Your goal is to check whether the value is in upperCase ,if so convert the data into lowerCase else if value is in lowerCase , convert the data into upperCase and store the result in `data` variable. +Print the result. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/1_string_convert/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/1_string_convert/Solution/solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/1_string_convert/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/1_string_convert/Solution/solution.py index ccc07303..bb95457b 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_string_convert/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/1_string_convert/Solution/solution.py @@ -1,9 +1,9 @@ -# Code your solution here -string=input() -if string.islower(): - data=string.upper() -elif string.isupper(): - data=string.lower() -else: - pass -print(data) +# Code your solution here +string=input() +if string.islower(): + data=string.upper() +elif string.isupper(): + data=string.lower() +else: + pass +print(data) diff --git a/introduction_and_environment/data_types_and_control_flow/1_string_convert/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/1_string_convert/Solution/test_solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/1_string_convert/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/1_string_convert/Solution/test_solution.py index 00546354..e22da011 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_string_convert/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/1_string_convert/Solution/test_solution.py @@ -1,21 +1,21 @@ -def test_solution(monkeypatch): - x='UNIVERSE' - y='universe' - ret_val1= None - - def f(): - nonlocal x - return x - - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.input',f) - monkeypatch.setattr('builtins.print',g) - - import solution - assert solution.string==x or solution.string==y - - - +def test_solution(monkeypatch): + x='UNIVERSE' + y='universe' + ret_val1= None + + def f(): + nonlocal x + return x + + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.string==x or solution.string==y + + + diff --git a/introduction_and_environment/data_types_and_control_flow/1_string_length/README.md b/intro_&_enviro/data_types_and_control_flow/1_string_length/README.md similarity index 96% rename from introduction_and_environment/data_types_and_control_flow/1_string_length/README.md rename to intro_&_enviro/data_types_and_control_flow/1_string_length/README.md index fc518c64..2e1d73fb 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_string_length/README.md +++ b/intro_&_enviro/data_types_and_control_flow/1_string_length/README.md @@ -1,15 +1,15 @@ -# String length - -## Motivation -Python provides inbuilt keyword len() used to retrieve the length of any data type. - -## Problem Description -Write a Python script that asks the user for a string_value and store it object `string_1`. -Find the length of the string and store the result in `data` variable. -Print the result. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# String length + +## Motivation +Python provides inbuilt keyword len() used to retrieve the length of any data type. + +## Problem Description +Write a Python script that asks the user for a string_value and store it object `string_1`. +Find the length of the string and store the result in `data` variable. +Print the result. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/1_string_length/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/1_string_length/Solution/solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/1_string_length/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/1_string_length/Solution/solution.py index 3cbc247b..f7df1367 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_string_length/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/1_string_length/Solution/solution.py @@ -1,4 +1,4 @@ -# Code your solution here -string_1=input() -data=len(string_1) -print(data) +# Code your solution here +string_1=input() +data=len(string_1) +print(data) diff --git a/introduction_and_environment/data_types_and_control_flow/1_string_length/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/1_string_length/Solution/test_solution.py similarity index 95% rename from introduction_and_environment/data_types_and_control_flow/1_string_length/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/1_string_length/Solution/test_solution.py index 04640fa9..4912503e 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_string_length/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/1_string_length/Solution/test_solution.py @@ -1,18 +1,18 @@ - -def test_solution(monkeypatch): - x='Hello' - ret_val1= None - - def f(): - nonlocal x - return x - - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.input',f) - monkeypatch.setattr('builtins.print',g) - - import solution + +def test_solution(monkeypatch): + x='Hello' + ret_val1= None + + def f(): + nonlocal x + return x + + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution assert solution.string_1==x \ No newline at end of file diff --git a/introduction_and_environment/data_types_and_control_flow/1_string_slice/README.md b/intro_&_enviro/data_types_and_control_flow/1_string_slice/README.md similarity index 98% rename from introduction_and_environment/data_types_and_control_flow/1_string_slice/README.md rename to intro_&_enviro/data_types_and_control_flow/1_string_slice/README.md index f9e87338..dd72b8e2 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_string_slice/README.md +++ b/intro_&_enviro/data_types_and_control_flow/1_string_slice/README.md @@ -1,19 +1,19 @@ -# String Slice - -## Motivation -Strings are sequential, immutable, collections of zero or more letters, numbers and other symbols. We call these letters, numbers and other symbols characters. String values are differentiated from identifiers by using quotation marks (either single or double). - -The operations on Lists and strings are exactly the same EXCEPT that strings are immutable and cannot be modified. To modify a string, the .replace() method must be used an must be set to another variable - -## Problem Description -Write a python script that contains a `string_value` variable holding data "Hello universe" -Perform slicing of "Hello" from `string_value` variable and store the result in `data` variable. -Concatenate `data` variable with string value "World" and store result in another variable `data_val`. -Print the result data. - - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# String Slice + +## Motivation +Strings are sequential, immutable, collections of zero or more letters, numbers and other symbols. We call these letters, numbers and other symbols characters. String values are differentiated from identifiers by using quotation marks (either single or double). + +The operations on Lists and strings are exactly the same EXCEPT that strings are immutable and cannot be modified. To modify a string, the .replace() method must be used an must be set to another variable + +## Problem Description +Write a python script that contains a `string_value` variable holding data "Hello universe" +Perform slicing of "Hello" from `string_value` variable and store the result in `data` variable. +Concatenate `data` variable with string value "World" and store result in another variable `data_val`. +Print the result data. + + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/1_string_slice/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/1_string_slice/Solution/solution.py similarity index 95% rename from introduction_and_environment/data_types_and_control_flow/1_string_slice/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/1_string_slice/Solution/solution.py index 9c01912e..e9006b77 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_string_slice/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/1_string_slice/Solution/solution.py @@ -1,6 +1,6 @@ -# Code your solution here -string_value="Hello Universe" -data=string_value[0:5] -data_value=data+"World" -print(data_value) - +# Code your solution here +string_value="Hello Universe" +data=string_value[0:5] +data_value=data+"World" +print(data_value) + diff --git a/introduction_and_environment/data_types_and_control_flow/1_string_slice/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/1_string_slice/Solution/test_solution.py similarity index 95% rename from introduction_and_environment/data_types_and_control_flow/1_string_slice/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/1_string_slice/Solution/test_solution.py index c7da1173..8ea192c3 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_string_slice/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/1_string_slice/Solution/test_solution.py @@ -1,13 +1,13 @@ - - -def test_solution(monkeypatch): - ret_val1=None - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.print',g) - - import solution - assert solution.string_value=="Hello Universe" + + +def test_solution(monkeypatch): + ret_val1=None + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.string_value=="Hello Universe" assert solution.data=="Hello" \ No newline at end of file diff --git a/introduction_and_environment/data_types_and_control_flow/2_add_item/README.md b/intro_&_enviro/data_types_and_control_flow/2_add_item/README.md similarity index 97% rename from introduction_and_environment/data_types_and_control_flow/2_add_item/README.md rename to intro_&_enviro/data_types_and_control_flow/2_add_item/README.md index d8cfd79c..d3cbac24 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_add_item/README.md +++ b/intro_&_enviro/data_types_and_control_flow/2_add_item/README.md @@ -1,15 +1,15 @@ -# Add Item - -## Motivation -Dictionary is a collection of ordered or unordered key:value pairs. - -## Problem Description -Write a python script that contains a `dict_a` dictionary variable holding a set of key:value pairs hidden from you. -Your objective is to add a new key:value pair to th existing dictionary set and store insdie variable `dict_val`. -Print the result. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Add Item + +## Motivation +Dictionary is a collection of ordered or unordered key:value pairs. + +## Problem Description +Write a python script that contains a `dict_a` dictionary variable holding a set of key:value pairs hidden from you. +Your objective is to add a new key:value pair to th existing dictionary set and store insdie variable `dict_val`. +Print the result. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/2_add_item/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/2_add_item/Solution/solution.py similarity index 97% rename from introduction_and_environment/data_types_and_control_flow/2_add_item/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/2_add_item/Solution/solution.py index 25393ca0..1698cfe6 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_add_item/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/2_add_item/Solution/solution.py @@ -1,4 +1,4 @@ -# Code your solution here -dict_a={'1':'Python','2':'Sql','3':'Javascript'} -dict_val=dict_a.update({'4':'Java'}) +# Code your solution here +dict_a={'1':'Python','2':'Sql','3':'Javascript'} +dict_val=dict_a.update({'4':'Java'}) print(dict_val) \ No newline at end of file diff --git a/introduction_and_environment/data_types_and_control_flow/2_add_item/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/2_add_item/Solution/test_solution.py similarity index 93% rename from introduction_and_environment/data_types_and_control_flow/2_add_item/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/2_add_item/Solution/test_solution.py index 02667ae6..f03c4611 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_add_item/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/2_add_item/Solution/test_solution.py @@ -1,13 +1,13 @@ - - -def test_solution(monkeypatch): - ret_val1=None - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.print',g) - - import solution - - + + +def test_solution(monkeypatch): + ret_val1=None + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.print',g) + + import solution + + diff --git a/introduction_and_environment/data_types_and_control_flow/2_append/README.md b/intro_&_enviro/data_types_and_control_flow/2_append/README.md similarity index 97% rename from introduction_and_environment/data_types_and_control_flow/2_append/README.md rename to intro_&_enviro/data_types_and_control_flow/2_append/README.md index 357f7e53..0263827e 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_append/README.md +++ b/intro_&_enviro/data_types_and_control_flow/2_append/README.md @@ -1,15 +1,15 @@ -# Append - -## Motivation -Python collective data type list provides mutable operations like index, slicing, pop, append etc. - -## Problem Description -Write a python script contains a `list_a` list variable holding items hidden from you. -Your goal is to insert a new item at the 3rd position of the list and store the result in another variable `list_b`. -Print the result. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Append + +## Motivation +Python collective data type list provides mutable operations like index, slicing, pop, append etc. + +## Problem Description +Write a python script contains a `list_a` list variable holding items hidden from you. +Your goal is to insert a new item at the 3rd position of the list and store the result in another variable `list_b`. +Print the result. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/intro_&_enviro/data_types_and_control_flow/2_append/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/2_append/Solution/solution.py new file mode 100644 index 00000000..f8ead7d5 --- /dev/null +++ b/intro_&_enviro/data_types_and_control_flow/2_append/Solution/solution.py @@ -0,0 +1,4 @@ +# Code your solution here +list_a=[True,False,False,False,False,True] +list_b=list_a.insert(3,True) +print(list_b) \ No newline at end of file diff --git a/introduction_and_environment/data_types_and_control_flow/2_append/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/2_append/Solution/test_solution.py similarity index 93% rename from introduction_and_environment/data_types_and_control_flow/2_append/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/2_append/Solution/test_solution.py index 02667ae6..f03c4611 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_append/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/2_append/Solution/test_solution.py @@ -1,13 +1,13 @@ - - -def test_solution(monkeypatch): - ret_val1=None - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.print',g) - - import solution - - + + +def test_solution(monkeypatch): + ret_val1=None + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.print',g) + + import solution + + diff --git a/introduction_and_environment/data_types_and_control_flow/2_except_letter/README.md b/intro_&_enviro/data_types_and_control_flow/2_except_letter/README.md similarity index 97% rename from introduction_and_environment/data_types_and_control_flow/2_except_letter/README.md rename to intro_&_enviro/data_types_and_control_flow/2_except_letter/README.md index 5d8f03cd..2d15b4c8 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_except_letter/README.md +++ b/intro_&_enviro/data_types_and_control_flow/2_except_letter/README.md @@ -1,14 +1,14 @@ -# Except Letter - -## Motivation -Vowels are 'a' | 'e' | 'i' | 'o' | 'u' . "BYTE ACADEMY"- Let us ignore the vowels from the Brand. - -## Problem Description -Write a Python script that declares a variable `string` which contains value `BYTE ACADEMY`. -Construct a loop to run upto length of `string` and check whether each character is a vowel or not. If not vowel , store the result of characters in another variable `data`. -Print the result. -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Except Letter + +## Motivation +Vowels are 'a' | 'e' | 'i' | 'o' | 'u' . "BYTE ACADEMY"- Let us ignore the vowels from the Brand. + +## Problem Description +Write a Python script that declares a variable `string` which contains value `BYTE ACADEMY`. +Construct a loop to run upto length of `string` and check whether each character is a vowel or not. If not vowel , store the result of characters in another variable `data`. +Print the result. +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/2_except_letter/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/2_except_letter/Solution/solution.py similarity index 93% rename from introduction_and_environment/data_types_and_control_flow/2_except_letter/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/2_except_letter/Solution/solution.py index 4e63ff5a..4d715b20 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_except_letter/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/2_except_letter/Solution/solution.py @@ -1,11 +1,11 @@ -# Code your solution here -string="BYTE ACADEMY" -data='' -for i in string: - if i!='E' and i!='A': - data=data+i - else: - pass -print(data) - - +# Code your solution here +string="BYTE ACADEMY" +data='' +for i in string: + if i!='E' and i!='A': + data=data+i + else: + pass +print(data) + + diff --git a/introduction_and_environment/data_types_and_control_flow/2_except_letter/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/2_except_letter/Solution/test_solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/2_except_letter/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/2_except_letter/Solution/test_solution.py index 20d94032..07a79b67 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_except_letter/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/2_except_letter/Solution/test_solution.py @@ -1,14 +1,14 @@ -def test_solution(monkeypatch): - x="BYTE ACADEMY" - ret_val1= None - - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.print',g) - - import solution - assert solution.string==x - - +def test_solution(monkeypatch): + x="BYTE ACADEMY" + ret_val1= None + + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.string==x + + diff --git a/introduction_and_environment/data_types_and_control_flow/2_farm_area/README.md b/intro_&_enviro/data_types_and_control_flow/2_farm_area/README.md similarity index 96% rename from introduction_and_environment/data_types_and_control_flow/2_farm_area/README.md rename to intro_&_enviro/data_types_and_control_flow/2_farm_area/README.md index 1838e75d..1831d68b 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_farm_area/README.md +++ b/intro_&_enviro/data_types_and_control_flow/2_farm_area/README.md @@ -1,15 +1,15 @@ -# Farm Area - -## Motivation -A Farmers field has length and breadth in feet. - -## Problem Description -Write a Python script that asks the user to enter the field values of length and bredth in objects `length` and `bredth`. -Your goal is to compute the area of the farmers field and store the result in variable `data`. -Print the result. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Farm Area + +## Motivation +A Farmers field has length and breadth in feet. + +## Problem Description +Write a Python script that asks the user to enter the field values of length and bredth in objects `length` and `bredth`. +Your goal is to compute the area of the farmers field and store the result in variable `data`. +Print the result. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/2_farm_area/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/2_farm_area/Solution/solution.py similarity index 95% rename from introduction_and_environment/data_types_and_control_flow/2_farm_area/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/2_farm_area/Solution/solution.py index c86b9f81..f8241e3a 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_farm_area/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/2_farm_area/Solution/solution.py @@ -1,8 +1,8 @@ -# Code your solution here -length=int(input()) -breadth=int(input()) -if length>breadth: - data=length*breadth -else: - pass +# Code your solution here +length=int(input()) +breadth=int(input()) +if length>breadth: + data=length*breadth +else: + pass print(data) \ No newline at end of file diff --git a/introduction_and_environment/data_types_and_control_flow/2_farm_area/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/2_farm_area/Solution/test_solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/2_farm_area/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/2_farm_area/Solution/test_solution.py index 55b4bd7b..51d55922 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_farm_area/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/2_farm_area/Solution/test_solution.py @@ -1,24 +1,24 @@ -def test_solution(monkeypatch): - x=[6,4] - index=-1 - ret_val1= None - - def f(): - nonlocal index - nonlocal x - index+=1 - return x[index] - - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.input',f) - monkeypatch.setattr('builtins.print',g) - - import solution - assert solution.length==6 - assert solution.breadth==4 - - - +def test_solution(monkeypatch): + x=[6,4] + index=-1 + ret_val1= None + + def f(): + nonlocal index + nonlocal x + index+=1 + return x[index] + + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.length==6 + assert solution.breadth==4 + + + diff --git a/introduction_and_environment/data_types_and_control_flow/2_remove_item/README.md b/intro_&_enviro/data_types_and_control_flow/2_remove_item/README.md similarity index 96% rename from introduction_and_environment/data_types_and_control_flow/2_remove_item/README.md rename to intro_&_enviro/data_types_and_control_flow/2_remove_item/README.md index 9bd09c4c..6fc5d28f 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_remove_item/README.md +++ b/intro_&_enviro/data_types_and_control_flow/2_remove_item/README.md @@ -1,12 +1,12 @@ -# Remove-Item - -## Problem Description -Write a python script that contains a `list_1` list variable holding items hidden from you. -Your goal is to remove an item from the list and store the result in another variable `lister`. -Print the result. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Remove-Item + +## Problem Description +Write a python script that contains a `list_1` list variable holding items hidden from you. +Your goal is to remove an item from the list and store the result in another variable `lister`. +Print the result. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/2_remove_item/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/2_remove_item/Solution/solution.py similarity index 96% rename from introduction_and_environment/data_types_and_control_flow/2_remove_item/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/2_remove_item/Solution/solution.py index 9cc9a93c..9c3ae713 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_remove_item/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/2_remove_item/Solution/solution.py @@ -1,4 +1,4 @@ -# Code your solution here -list_1=['Yo','Hi',1,2,3] -lister=list_1.remove('Yo') +# Code your solution here +list_1=['Yo','Hi',1,2,3] +lister=list_1.remove('Yo') print(lister) \ No newline at end of file diff --git a/intro_&_enviro/data_types_and_control_flow/2_remove_item/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/2_remove_item/Solution/test_solution.py new file mode 100644 index 00000000..76420db2 --- /dev/null +++ b/intro_&_enviro/data_types_and_control_flow/2_remove_item/Solution/test_solution.py @@ -0,0 +1,14 @@ + + + +def test_solution(monkeypatch): + ret_val1=None + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.print',g) + + import solution + + diff --git a/introduction_and_environment/data_types_and_control_flow/2_sum_list/README.md b/intro_&_enviro/data_types_and_control_flow/2_sum_list/README.md similarity index 96% rename from introduction_and_environment/data_types_and_control_flow/2_sum_list/README.md rename to intro_&_enviro/data_types_and_control_flow/2_sum_list/README.md index dd87a11a..9cc2b634 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_sum_list/README.md +++ b/intro_&_enviro/data_types_and_control_flow/2_sum_list/README.md @@ -1,15 +1,15 @@ -# Sum List - -## Motivation -List contains a set of elements maybe of same/different data type. - -## Problem Description -Write a python script that contains a `list_a` list variable holding items hidden from you. -Your goal is to sum the integer items from the list and store it in anotehr variable `total` -Print the result. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Sum List + +## Motivation +List contains a set of elements maybe of same/different data type. + +## Problem Description +Write a python script that contains a `list_a` list variable holding items hidden from you. +Your goal is to sum the integer items from the list and store it in anotehr variable `total` +Print the result. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/2_sum_list/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/2_sum_list/Solution/solution.py similarity index 95% rename from introduction_and_environment/data_types_and_control_flow/2_sum_list/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/2_sum_list/Solution/solution.py index 9a8ca2f3..3a86955d 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_sum_list/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/2_sum_list/Solution/solution.py @@ -1,4 +1,4 @@ -# Code your solution here -list_a=[10,20,30,40,50] -total=sum(list_a) -print(total) +# Code your solution here +list_a=[10,20,30,40,50] +total=sum(list_a) +print(total) diff --git a/introduction_and_environment/data_types_and_control_flow/2_sum_list/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/2_sum_list/Solution/test_solution.py similarity index 93% rename from introduction_and_environment/data_types_and_control_flow/2_sum_list/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/2_sum_list/Solution/test_solution.py index 02667ae6..f03c4611 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_sum_list/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/2_sum_list/Solution/test_solution.py @@ -1,13 +1,13 @@ - - -def test_solution(monkeypatch): - ret_val1=None - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.print',g) - - import solution - - + + +def test_solution(monkeypatch): + ret_val1=None + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.print',g) + + import solution + + diff --git a/introduction_and_environment/data_types_and_control_flow/2_vowel_consonant/README.md b/intro_&_enviro/data_types_and_control_flow/2_vowel_consonant/README.md similarity index 97% rename from introduction_and_environment/data_types_and_control_flow/2_vowel_consonant/README.md rename to intro_&_enviro/data_types_and_control_flow/2_vowel_consonant/README.md index 3292a38b..f0185d62 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_vowel_consonant/README.md +++ b/intro_&_enviro/data_types_and_control_flow/2_vowel_consonant/README.md @@ -1,17 +1,17 @@ -# Vowel / Consosnant - -## Motivation -Letters captured from the input method consists of combinations of characters, numbers, vowels and consosnants. -logic building here involves retreiving only vowels or consonants. - -## Problem Description -Write a Python script that asks the user for a character and declare in object `letter`. -Your goal is to check whether the character is a vowel or consonent and store the appropriate result in variable `data`. -Print the result. - - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Vowel / Consosnant + +## Motivation +Letters captured from the input method consists of combinations of characters, numbers, vowels and consosnants. +logic building here involves retreiving only vowels or consonants. + +## Problem Description +Write a Python script that asks the user for a character and declare in object `letter`. +Your goal is to check whether the character is a vowel or consonent and store the appropriate result in variable `data`. +Print the result. + + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/2_vowel_consonant/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/2_vowel_consonant/Solution/solution.py similarity index 96% rename from introduction_and_environment/data_types_and_control_flow/2_vowel_consonant/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/2_vowel_consonant/Solution/solution.py index 8e34b4a9..38685663 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_vowel_consonant/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/2_vowel_consonant/Solution/solution.py @@ -1,7 +1,7 @@ -# Code your solution here -letter=input() -if letter=='a'or letter=='e' or letter=='i' or letter=='o' or letter=='u': - data='Vowel' -else: - data='Consonant' +# Code your solution here +letter=input() +if letter=='a'or letter=='e' or letter=='i' or letter=='o' or letter=='u': + data='Vowel' +else: + data='Consonant' print(data) \ No newline at end of file diff --git a/introduction_and_environment/data_types_and_control_flow/2_vowel_consonant/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/2_vowel_consonant/Solution/test_solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/2_vowel_consonant/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/2_vowel_consonant/Solution/test_solution.py index 0774f5d7..7a3771a1 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_vowel_consonant/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/2_vowel_consonant/Solution/test_solution.py @@ -1,21 +1,21 @@ -def test_solution(monkeypatch): - x=['e','x'] - index=-1 - ret_val1= None - - def f(): - nonlocal x - nonlocal index - index+=1 - return x[index] - - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.input',f) - monkeypatch.setattr('builtins.print',g) - - import solution - - +def test_solution(monkeypatch): + x=['e','x'] + index=-1 + ret_val1= None + + def f(): + nonlocal x + nonlocal index + index+=1 + return x[index] + + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution + + diff --git a/introduction_and_environment/data_types_and_control_flow/3_count_duplicate/README.md b/intro_&_enviro/data_types_and_control_flow/3_count_duplicate/README.md similarity index 97% rename from introduction_and_environment/data_types_and_control_flow/3_count_duplicate/README.md rename to intro_&_enviro/data_types_and_control_flow/3_count_duplicate/README.md index 56fa6f84..42c078aa 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_count_duplicate/README.md +++ b/intro_&_enviro/data_types_and_control_flow/3_count_duplicate/README.md @@ -1,15 +1,15 @@ -# Count Duplicate - -## Motivation -List can contain multiple duplicate elements . We can check the occurrence of the duplicate items. - -## Problem Description -Write a python script that contains a `list_dup` list variable holding duplicate items hidden from you. -Your goal is to count the number of duplicates for a particular item and store the result in `tot` variable. -Print the result. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Count Duplicate + +## Motivation +List can contain multiple duplicate elements . We can check the occurrence of the duplicate items. + +## Problem Description +Write a python script that contains a `list_dup` list variable holding duplicate items hidden from you. +Your goal is to count the number of duplicates for a particular item and store the result in `tot` variable. +Print the result. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/3_count_duplicate/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/3_count_duplicate/Solution/solution.py similarity index 96% rename from introduction_and_environment/data_types_and_control_flow/3_count_duplicate/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/3_count_duplicate/Solution/solution.py index 3de4290e..55710683 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_count_duplicate/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/3_count_duplicate/Solution/solution.py @@ -1,4 +1,4 @@ -# Code your solution here -list_dup=[12,13,14,12,12,11] -tot=list_dup.count(12) +# Code your solution here +list_dup=[12,13,14,12,12,11] +tot=list_dup.count(12) print(tot) \ No newline at end of file diff --git a/intro_&_enviro/data_types_and_control_flow/3_count_duplicate/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/3_count_duplicate/Solution/test_solution.py new file mode 100644 index 00000000..f03c4611 --- /dev/null +++ b/intro_&_enviro/data_types_and_control_flow/3_count_duplicate/Solution/test_solution.py @@ -0,0 +1,13 @@ + + +def test_solution(monkeypatch): + ret_val1=None + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.print',g) + + import solution + + diff --git a/introduction_and_environment/data_types_and_control_flow/3_grade/README.md b/intro_&_enviro/data_types_and_control_flow/3_grade/README.md similarity index 96% rename from introduction_and_environment/data_types_and_control_flow/3_grade/README.md rename to intro_&_enviro/data_types_and_control_flow/3_grade/README.md index b42b196e..45691e91 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_grade/README.md +++ b/intro_&_enviro/data_types_and_control_flow/3_grade/README.md @@ -1,22 +1,22 @@ -# Grade - -## Motivation -Student Grade determines the next step to success. - -+ 90-100 -> A+ GRADE -+ 70-90-> B GRADE -+ 50-70-> C GRADE -+ 35-50-> D GRADE -+ Less than 35-> FAIL - -## Problem Description -Write a Python script that asks the user for the marks value residing in object `marks`. -Construct a series of If-Else conditioning in order to check under which grade the marks fall under category. -Store the result in variable `grade`. -Print the result. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Grade + +## Motivation +Student Grade determines the next step to success. + ++ 90-100 -> A+ GRADE ++ 70-90-> B GRADE ++ 50-70-> C GRADE ++ 35-50-> D GRADE ++ Less than 35-> FAIL + +## Problem Description +Write a Python script that asks the user for the marks value residing in object `marks`. +Construct a series of If-Else conditioning in order to check under which grade the marks fall under category. +Store the result in variable `grade`. +Print the result. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/3_grade/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/3_grade/Solution/solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/3_grade/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/3_grade/Solution/solution.py index 6fcbfe9c..b969533b 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_grade/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/3_grade/Solution/solution.py @@ -1,14 +1,14 @@ -# Code your solution here -mark=int(input()) -if mark >90 and mark <=100: - grade='A' -elif mark>70 and mark <=90: - grade='B' -elif mark>50 and mark<=70: - grade='C' -elif mark>35 and mark<=50: - grade='D' -else: - grade='F' - +# Code your solution here +mark=int(input()) +if mark >90 and mark <=100: + grade='A' +elif mark>70 and mark <=90: + grade='B' +elif mark>50 and mark<=70: + grade='C' +elif mark>35 and mark<=50: + grade='D' +else: + grade='F' + print(grade) \ No newline at end of file diff --git a/introduction_and_environment/data_types_and_control_flow/3_grade/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/3_grade/Solution/test_solution.py similarity index 93% rename from introduction_and_environment/data_types_and_control_flow/3_grade/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/3_grade/Solution/test_solution.py index f8dc6b26..9d0f84a5 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_grade/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/3_grade/Solution/test_solution.py @@ -1,21 +1,21 @@ -def test_solution(monkeypatch): - x=80 - ret_val1= None - - def f(): - nonlocal x - return x - - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.input',f) - monkeypatch.setattr('builtins.print',g) - - import solution - assert solution.mark==x - - - - +def test_solution(monkeypatch): + x=80 + ret_val1= None + + def f(): + nonlocal x + return x + + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.mark==x + + + + diff --git a/introduction_and_environment/data_types_and_control_flow/3_month_days/README.md b/intro_&_enviro/data_types_and_control_flow/3_month_days/README.md similarity index 97% rename from introduction_and_environment/data_types_and_control_flow/3_month_days/README.md rename to intro_&_enviro/data_types_and_control_flow/3_month_days/README.md index 01f1933f..4964b8e2 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_month_days/README.md +++ b/intro_&_enviro/data_types_and_control_flow/3_month_days/README.md @@ -1,19 +1,19 @@ -# Month Days - -## Motivation -Each month contains different number of overall days. From the month name , I can easily tell the number of overall days. - -## Problem Description -Write a Python script that asks the user for an wtring value associated with any month of the calendar year. -Store it in an object `month`. - -Your goal is to check whether the `month` exists in an alredy defined dictionary variable `month_dict` contais key:value pairs of MonthName:TotalMonthDaysInTheMonth format. - -If `month` exists- retrieve the TotalMothDayInTheMonth value from the dictionary w.r.t `month` and store the value in variable `data` -Print the result - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Month Days + +## Motivation +Each month contains different number of overall days. From the month name , I can easily tell the number of overall days. + +## Problem Description +Write a Python script that asks the user for an wtring value associated with any month of the calendar year. +Store it in an object `month`. + +Your goal is to check whether the `month` exists in an alredy defined dictionary variable `month_dict` contais key:value pairs of MonthName:TotalMonthDaysInTheMonth format. + +If `month` exists- retrieve the TotalMothDayInTheMonth value from the dictionary w.r.t `month` and store the value in variable `data` +Print the result + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/3_month_days/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/3_month_days/Solution/solution.py similarity index 97% rename from introduction_and_environment/data_types_and_control_flow/3_month_days/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/3_month_days/Solution/solution.py index 81eb8dc8..bb68f177 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_month_days/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/3_month_days/Solution/solution.py @@ -1,8 +1,8 @@ -# Code your solution here -month_dict={'january':31,'february':28,'march':31,'april':30,'may':31,'june':30,'july':31,'august':31,'september':30,'october':31,'november':30,'december':31} -month=str(input()) -if month in month_dict.keys(): - data=month_dict.get(month) -else: - pass +# Code your solution here +month_dict={'january':31,'february':28,'march':31,'april':30,'may':31,'june':30,'july':31,'august':31,'september':30,'october':31,'november':30,'december':31} +month=str(input()) +if month in month_dict.keys(): + data=month_dict.get(month) +else: + pass print(data) \ No newline at end of file diff --git a/introduction_and_environment/data_types_and_control_flow/3_month_days/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/3_month_days/Solution/test_solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/3_month_days/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/3_month_days/Solution/test_solution.py index b20f610e..dd9ec2cd 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_month_days/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/3_month_days/Solution/test_solution.py @@ -1,20 +1,20 @@ -def test_solution(monkeypatch): - x='august' - ret_val1= None - - def f(): - nonlocal x - return x - - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.input',f) - monkeypatch.setattr('builtins.print',g) - - import solution - assert solution.month==x - - - +def test_solution(monkeypatch): + x='august' + ret_val1= None + + def f(): + nonlocal x + return x + + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.month==x + + + diff --git a/introduction_and_environment/data_types_and_control_flow/3_palindrome/README.md b/intro_&_enviro/data_types_and_control_flow/3_palindrome/README.md similarity index 97% rename from introduction_and_environment/data_types_and_control_flow/3_palindrome/README.md rename to intro_&_enviro/data_types_and_control_flow/3_palindrome/README.md index 70493f9a..4e2538bc 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_palindrome/README.md +++ b/intro_&_enviro/data_types_and_control_flow/3_palindrome/README.md @@ -1,16 +1,16 @@ -# Palindrome - -## Motivation -A string is a palindrome if it is identical forward and backward. For example “anna”, -“civic”, “level” and “hannah” are all examples of palindromicwords. - -## Problem Description -Write a Python script that asks the user for a string value stored in object `line`. -Your goal is to check whether the object is a palindrome or not . Store the result in variable `is_palindrome`. -Print the result. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Palindrome + +## Motivation +A string is a palindrome if it is identical forward and backward. For example “anna”, +“civic”, “level” and “hannah” are all examples of palindromicwords. + +## Problem Description +Write a Python script that asks the user for a string value stored in object `line`. +Your goal is to check whether the object is a palindrome or not . Store the result in variable `is_palindrome`. +Print the result. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/3_palindrome/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/3_palindrome/Solution/solution.py similarity index 96% rename from introduction_and_environment/data_types_and_control_flow/3_palindrome/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/3_palindrome/Solution/solution.py index 141e52ef..df670444 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_palindrome/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/3_palindrome/Solution/solution.py @@ -1,9 +1,9 @@ -# Code your solution here -line=input() -is_palindrome=bool -for i in range(0,len(line)//2): - if line[i]!=line[len(line)-i-1]: - is_palindrome=False - else: - is_palindrome=True +# Code your solution here +line=input() +is_palindrome=bool +for i in range(0,len(line)//2): + if line[i]!=line[len(line)-i-1]: + is_palindrome=False + else: + is_palindrome=True print(is_palindrome) \ No newline at end of file diff --git a/introduction_and_environment/data_types_and_control_flow/3_palindrome/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/3_palindrome/Solution/test_solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/3_palindrome/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/3_palindrome/Solution/test_solution.py index e5f09b2e..c7569e53 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_palindrome/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/3_palindrome/Solution/test_solution.py @@ -1,20 +1,20 @@ -def test_solution(monkeypatch): - x='malayalam' - ret_val1= None - - def f(): - nonlocal x - return x - - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.input',f) - monkeypatch.setattr('builtins.print',g) - - import solution - assert solution.line==x - - - +def test_solution(monkeypatch): + x='malayalam' + ret_val1= None + + def f(): + nonlocal x + return x + + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.line==x + + + diff --git a/introduction_and_environment/data_types_and_control_flow/3_set_difference/README.md b/intro_&_enviro/data_types_and_control_flow/3_set_difference/README.md similarity index 96% rename from introduction_and_environment/data_types_and_control_flow/3_set_difference/README.md rename to intro_&_enviro/data_types_and_control_flow/3_set_difference/README.md index b7038048..23cf4ff9 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_set_difference/README.md +++ b/intro_&_enviro/data_types_and_control_flow/3_set_difference/README.md @@ -1,20 +1,20 @@ -# Set-Diff - -## Motivation -Sets in python are same as sets in mathematics. - -+ '|' set union -+ '-' set difference -+ '<=' set subset -+ '&' set intersection - -## Problem Description -Write a python script that contains a `set_1` and `set_2` set variables holding items hidden from you. -Your goal is to find the differences between the two sets and store the result in `result` variable. -Print the result. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Set-Diff + +## Motivation +Sets in python are same as sets in mathematics. + ++ '|' set union ++ '-' set difference ++ '<=' set subset ++ '&' set intersection + +## Problem Description +Write a python script that contains a `set_1` and `set_2` set variables holding items hidden from you. +Your goal is to find the differences between the two sets and store the result in `result` variable. +Print the result. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/3_set_difference/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/3_set_difference/Solution/solution.py similarity index 96% rename from introduction_and_environment/data_types_and_control_flow/3_set_difference/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/3_set_difference/Solution/solution.py index e3a653f0..575c919e 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_set_difference/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/3_set_difference/Solution/solution.py @@ -1,6 +1,6 @@ -# Code your solution here -set_1={100,200,150,250,300,400,500,450} -set_2={50,20,100,200,300,330,234,1,400} - -result=set_1-set_2 +# Code your solution here +set_1={100,200,150,250,300,400,500,450} +set_2={50,20,100,200,300,330,234,1,400} + +result=set_1-set_2 print(result) \ No newline at end of file diff --git a/introduction_and_environment/data_types_and_control_flow/2_remove_item/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/3_set_difference/Solution/test_solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/2_remove_item/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/3_set_difference/Solution/test_solution.py index 7d18da91..a366abde 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_remove_item/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/3_set_difference/Solution/test_solution.py @@ -1,14 +1,11 @@ - - - -def test_solution(monkeypatch): - ret_val1=None - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.print',g) - - import solution - - +def test_solution(monkeypatch): + ret_val1=None + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.print',g) + + import solution + + diff --git a/introduction_and_environment/data_types_and_control_flow/3_shape_check/README.md b/intro_&_enviro/data_types_and_control_flow/3_shape_check/README.md similarity index 97% rename from introduction_and_environment/data_types_and_control_flow/3_shape_check/README.md rename to intro_&_enviro/data_types_and_control_flow/3_shape_check/README.md index a0d5d50c..b26cef98 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_shape_check/README.md +++ b/intro_&_enviro/data_types_and_control_flow/3_shape_check/README.md @@ -1,15 +1,15 @@ -# Shape Check - -## Motivation - 3-Triangle , 4-Quadrilateral , 5-Pentagon , 6-Hexagon, 7-Heptagon, 8-Octagon, 9-Nonagon are just few shapes in geometry ranging 3-9. - -## Problem Description -Write a Python script that asks the user for a geometric shape value stored in object `figure`. -Your goal is to check if object belongs to any of the geometric shape values described in the Motivation to return a result w.r.t its geometric shape name, store the result in variable `data`. -Print the result. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Shape Check + +## Motivation + 3-Triangle , 4-Quadrilateral , 5-Pentagon , 6-Hexagon, 7-Heptagon, 8-Octagon, 9-Nonagon are just few shapes in geometry ranging 3-9. + +## Problem Description +Write a Python script that asks the user for a geometric shape value stored in object `figure`. +Your goal is to check if object belongs to any of the geometric shape values described in the Motivation to return a result w.r.t its geometric shape name, store the result in variable `data`. +Print the result. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/3_shape_check/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/3_shape_check/Solution/solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/3_shape_check/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/3_shape_check/Solution/solution.py index a35672e6..bda842c9 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_shape_check/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/3_shape_check/Solution/solution.py @@ -1,18 +1,18 @@ -# Code your solution here -figure=str(input()) -if figure=='3': - data='Triangle' -elif figure=='4': - data='Quadrilateral' -elif figure=='5': - data='Pentagon' -elif figure=='6': - data='hexagon' -elif figure=='7': - data='Heptagon' -elif figure=='8': - data='Octagon' -else: - data='Nonagon' - -print(data) +# Code your solution here +figure=str(input()) +if figure=='3': + data='Triangle' +elif figure=='4': + data='Quadrilateral' +elif figure=='5': + data='Pentagon' +elif figure=='6': + data='hexagon' +elif figure=='7': + data='Heptagon' +elif figure=='8': + data='Octagon' +else: + data='Nonagon' + +print(data) diff --git a/introduction_and_environment/data_types_and_control_flow/3_shape_check/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/3_shape_check/Solution/test_solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/3_shape_check/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/3_shape_check/Solution/test_solution.py index c5e4e272..6ed3abad 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_shape_check/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/3_shape_check/Solution/test_solution.py @@ -1,20 +1,20 @@ -def test_solution(monkeypatch): - x='5' - ret_val1= None - - def f(): - nonlocal x - return x - - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.input',f) - monkeypatch.setattr('builtins.print',g) - - import solution - assert solution.figure==x - - - +def test_solution(monkeypatch): + x='5' + ret_val1= None + + def f(): + nonlocal x + return x + + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.figure==x + + + diff --git a/introduction_and_environment/data_types_and_control_flow/3_string_case/README.md b/intro_&_enviro/data_types_and_control_flow/3_string_case/README.md similarity index 97% rename from introduction_and_environment/data_types_and_control_flow/3_string_case/README.md rename to intro_&_enviro/data_types_and_control_flow/3_string_case/README.md index 2cff220d..49e329d0 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_string_case/README.md +++ b/intro_&_enviro/data_types_and_control_flow/3_string_case/README.md @@ -1,15 +1,15 @@ -# String Case - -## Motivation -String values can have a mix of upper case and lower case letters. Python has inbuilt methods to convert from one case to another. - -## Problem Description -Write a Python script that asks the user for a string value residing inside object `string_val`. -Convert the value into upperCase and lowerCase and store the results in variables `upper_data` and `lower_data` respectively. -Print the results. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# String Case + +## Motivation +String values can have a mix of upper case and lower case letters. Python has inbuilt methods to convert from one case to another. + +## Problem Description +Write a Python script that asks the user for a string value residing inside object `string_val`. +Convert the value into upperCase and lowerCase and store the results in variables `upper_data` and `lower_data` respectively. +Print the results. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/3_string_case/Solution/solution.py b/intro_&_enviro/data_types_and_control_flow/3_string_case/Solution/solution.py similarity index 97% rename from introduction_and_environment/data_types_and_control_flow/3_string_case/Solution/solution.py rename to intro_&_enviro/data_types_and_control_flow/3_string_case/Solution/solution.py index a43882bf..8ea1f48d 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_string_case/Solution/solution.py +++ b/intro_&_enviro/data_types_and_control_flow/3_string_case/Solution/solution.py @@ -1,5 +1,5 @@ -# Code your solution here -string_val=str(input()) -upper_data=string_val.upper() -lower_data=string_val.lower() +# Code your solution here +string_val=str(input()) +upper_data=string_val.upper() +lower_data=string_val.lower() print(upper_data,lower_data) \ No newline at end of file diff --git a/introduction_and_environment/data_types_and_control_flow/3_string_case/Solution/test_solution.py b/intro_&_enviro/data_types_and_control_flow/3_string_case/Solution/test_solution.py similarity index 94% rename from introduction_and_environment/data_types_and_control_flow/3_string_case/Solution/test_solution.py rename to intro_&_enviro/data_types_and_control_flow/3_string_case/Solution/test_solution.py index e814eba5..7b958ec6 100644 --- a/introduction_and_environment/data_types_and_control_flow/3_string_case/Solution/test_solution.py +++ b/intro_&_enviro/data_types_and_control_flow/3_string_case/Solution/test_solution.py @@ -1,23 +1,23 @@ -def test_solution(monkeypatch): - x='Beautiful World' - ret_val1= None - ret_val2= None - - def f(): - nonlocal x - return x - - def g(num1,num2): - nonlocal ret_val1 - nonlocal ret_val2 - ret_val1=num1 - ret_val2=num2 - - monkeypatch.setattr('builtins.input',f) - monkeypatch.setattr('builtins.print',g) - - import solution - assert solution.string_val==x - - - +def test_solution(monkeypatch): + x='Beautiful World' + ret_val1= None + ret_val2= None + + def f(): + nonlocal x + return x + + def g(num1,num2): + nonlocal ret_val1 + nonlocal ret_val2 + ret_val1=num1 + ret_val2=num2 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.string_val==x + + + diff --git a/introduction_and_environment/data_types_and_control_flow/README.md b/intro_&_enviro/data_types_and_control_flow/README.md similarity index 99% rename from introduction_and_environment/data_types_and_control_flow/README.md rename to intro_&_enviro/data_types_and_control_flow/README.md index 82187164..7b461363 100644 --- a/introduction_and_environment/data_types_and_control_flow/README.md +++ b/intro_&_enviro/data_types_and_control_flow/README.md @@ -1,24 +1,24 @@ -# Exercises for Data Types and Control Flow -| **Exercise ID** | **Exercise** | -|:---------------:|:-------------------:| -| easy_e1 | [Compare Check](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/1_compare_check) | -| easy_e2 | [Even Odd](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/1_even_odd) | -| easy_e3 | [List Max](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/1_list_max) | -| easy_e4 | [Loop Divisibility](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/1_loop_divisibility) | -| easy_e5 | [String Convert](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/1_string_convert) | -| easy_e6 | [String Length](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/1_string_length) | -| easy_e7 | [String Slice](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/1_string_slice) | -| medium_e1 | [Add Item](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/2_add_item) | -| medium_e2 | [Append](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/2_append) | -| medium_e3 | [Except Letter](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/2_except_letter) | -| medium_e4 | [Farm Area](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/2_farm_area) | -| medium_e5 | [Remove Item](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/2_remove_item) | -| medium_e6 | [Sum List](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/2_sum_list) | -| medium_e7 | [Vowel Consonant](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/2_vowel_consonant) | -| hard_e1 | [Count Duplicate](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/3_count_duplicate) | -| hard_e2 | [Grade](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/3_grade) | -| hard_e3 | [Month Days](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/3_month_days) | -| hard_e4 | [Palindrome](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/3_palindrome) | -| hard_e5 | [Set Difference](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/3_set_difference) | -| hard_e6 | [Shape Check](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/3_shape_check) | -| hard_e7 | [String Case](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/3_string_case) | +# Exercises for Data Types and Control Flow +| **Exercise ID** | **Exercise** | +|:---------------:|:-------------------:| +| easy_e1 | [Compare Check](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/1_compare_check) | +| easy_e2 | [Even Odd](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/1_even_odd) | +| easy_e3 | [List Max](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/1_list_max) | +| easy_e4 | [Loop Divisibility](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/1_loop_divisibility) | +| easy_e5 | [String Convert](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/1_string_convert) | +| easy_e6 | [String Length](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/1_string_length) | +| easy_e7 | [String Slice](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/1_string_slice) | +| medium_e1 | [Add Item](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/2_add_item) | +| medium_e2 | [Append](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/2_append) | +| medium_e3 | [Except Letter](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/2_except_letter) | +| medium_e4 | [Farm Area](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/2_farm_area) | +| medium_e5 | [Remove Item](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/2_remove_item) | +| medium_e6 | [Sum List](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/2_sum_list) | +| medium_e7 | [Vowel Consonant](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/2_vowel_consonant) | +| hard_e1 | [Count Duplicate](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/3_count_duplicate) | +| hard_e2 | [Grade](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/3_grade) | +| hard_e3 | [Month Days](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/3_month_days) | +| hard_e4 | [Palindrome](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/3_palindrome) | +| hard_e5 | [Set Difference](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/3_set_difference) | +| hard_e6 | [Shape Check](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/3_shape_check) | +| hard_e7 | [String Case](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/data_types_and_control_flow/3_string_case) | diff --git a/intro_&_enviro/git/1_creating_a_repository/README.md b/intro_&_enviro/git/1_creating_a_repository/README.md new file mode 100644 index 00000000..9be43293 --- /dev/null +++ b/intro_&_enviro/git/1_creating_a_repository/README.md @@ -0,0 +1,12 @@ +# Creating a repository + +## Problem Description +Which of the following commands creates a repository? + +a) `git init` +b) `git add` +c) `git commit` +d) `git push` + +## Submission +* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. diff --git a/intro_&_enviro/git/1_creating_a_repository/Solution/solution.py b/intro_&_enviro/git/1_creating_a_repository/Solution/solution.py new file mode 100644 index 00000000..68217d2f --- /dev/null +++ b/intro_&_enviro/git/1_creating_a_repository/Solution/solution.py @@ -0,0 +1,2 @@ +# Code your solution here +answer = 'git init' diff --git a/intro_&_enviro/git/1_creating_a_repository/Solution/test_solution.py b/intro_&_enviro/git/1_creating_a_repository/Solution/test_solution.py new file mode 100644 index 00000000..990a2a46 --- /dev/null +++ b/intro_&_enviro/git/1_creating_a_repository/Solution/test_solution.py @@ -0,0 +1,5 @@ + +def test_solution(): + import solution + assert solution.answer in {'a', 'A'} + diff --git a/intro_&_enviro/git/1_remote_repository/README.md b/intro_&_enviro/git/1_remote_repository/README.md new file mode 100644 index 00000000..5cb150e8 --- /dev/null +++ b/intro_&_enviro/git/1_remote_repository/README.md @@ -0,0 +1,12 @@ +# Remote Repository + +## Problem Description +Which of the following synchronizes your local repository and the remote repository? + +a) `git init` +b) `git add` +c) `git commit` +d) `git push` + +## Submission +* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. diff --git a/intro_&_enviro/git/1_remote_repository/Solution/solution.py b/intro_&_enviro/git/1_remote_repository/Solution/solution.py new file mode 100644 index 00000000..a9082ea8 --- /dev/null +++ b/intro_&_enviro/git/1_remote_repository/Solution/solution.py @@ -0,0 +1,2 @@ +# Code your solution here +answer = 'git commit' diff --git a/intro_&_enviro/git/1_remote_repository/Solution/test_solution.py b/intro_&_enviro/git/1_remote_repository/Solution/test_solution.py new file mode 100644 index 00000000..e935c53f --- /dev/null +++ b/intro_&_enviro/git/1_remote_repository/Solution/test_solution.py @@ -0,0 +1,5 @@ + +def test_solution(): + import solution + assert solution.answer in {'d', 'D'} + diff --git a/intro_&_enviro/git/1_staging_area/README.md b/intro_&_enviro/git/1_staging_area/README.md new file mode 100644 index 00000000..f2df36be --- /dev/null +++ b/intro_&_enviro/git/1_staging_area/README.md @@ -0,0 +1,12 @@ +# Staging Area + +## Problem Description +Which of the following commands syncronizes the staging area with your repository? + +a) `git init` +b) `git add` +c) `git commit` +d) `git push` + +## Submission +* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. diff --git a/intro_&_enviro/git/1_staging_area/Solution/solution.py b/intro_&_enviro/git/1_staging_area/Solution/solution.py new file mode 100644 index 00000000..7c753050 --- /dev/null +++ b/intro_&_enviro/git/1_staging_area/Solution/solution.py @@ -0,0 +1,2 @@ +# Code your solution here +answer = 'git add' diff --git a/intro_&_enviro/git/1_staging_area/Solution/test_solution.py b/intro_&_enviro/git/1_staging_area/Solution/test_solution.py new file mode 100644 index 00000000..ef69e5ec --- /dev/null +++ b/intro_&_enviro/git/1_staging_area/Solution/test_solution.py @@ -0,0 +1,5 @@ + +def test_solution(): + import solution + assert solution.answer in {'c', 'C'} + diff --git a/intro_&_enviro/git/1_update_code/README.md b/intro_&_enviro/git/1_update_code/README.md new file mode 100644 index 00000000..cda1d184 --- /dev/null +++ b/intro_&_enviro/git/1_update_code/README.md @@ -0,0 +1,12 @@ +# Updating Code + +## Problem Description +Which of the following pushes changes from your working directory to your staging area? + +a) `git init` +b) `git add` +c) `git commit` +d) `git push` + +## Submission +* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. diff --git a/intro_&_enviro/git/1_update_code/Solution/solution.py b/intro_&_enviro/git/1_update_code/Solution/solution.py new file mode 100644 index 00000000..ed675848 --- /dev/null +++ b/intro_&_enviro/git/1_update_code/Solution/solution.py @@ -0,0 +1,2 @@ +# Code your solution here +answer = 'git push' diff --git a/intro_&_enviro/git/1_update_code/Solution/test_solution.py b/intro_&_enviro/git/1_update_code/Solution/test_solution.py new file mode 100644 index 00000000..09e33c52 --- /dev/null +++ b/intro_&_enviro/git/1_update_code/Solution/test_solution.py @@ -0,0 +1,5 @@ + +def test_solution(): + import solution + assert solution.answer in {'b', 'B'} + diff --git a/intro_&_enviro/git/README.md b/intro_&_enviro/git/README.md new file mode 100644 index 00000000..1af5adc3 --- /dev/null +++ b/intro_&_enviro/git/README.md @@ -0,0 +1,8 @@ +# Exercises for Git + +| **Exercise ID** | **Exercise** | +|:---------------:|:-------------------:| +| easy_e1 | [Staging Area](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/git/easy_e1) | +| easy_e2 | [Remote Repo](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/git/easy_e2) | +| easy_e3 | [Updating Code](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/git/easy_e3) | +| easy_e4 | [Creating a Repository](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/git/easy_e4) | diff --git a/intro_&_enviro/git/creating_a_repository/.solution.py.swp b/intro_&_enviro/git/creating_a_repository/.solution.py.swp new file mode 100644 index 00000000..973ac422 Binary files /dev/null and b/intro_&_enviro/git/creating_a_repository/.solution.py.swp differ diff --git a/intro_&_enviro/git/creating_a_repository/README.md b/intro_&_enviro/git/creating_a_repository/README.md new file mode 100644 index 00000000..9be43293 --- /dev/null +++ b/intro_&_enviro/git/creating_a_repository/README.md @@ -0,0 +1,12 @@ +# Creating a repository + +## Problem Description +Which of the following commands creates a repository? + +a) `git init` +b) `git add` +c) `git commit` +d) `git push` + +## Submission +* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. diff --git a/intro_&_enviro/git/creating_a_repository/solution/solution.py b/intro_&_enviro/git/creating_a_repository/solution/solution.py new file mode 100644 index 00000000..17038c37 --- /dev/null +++ b/intro_&_enviro/git/creating_a_repository/solution/solution.py @@ -0,0 +1,2 @@ +# Code your solution here +answer = '' diff --git a/intro_&_enviro/git/creating_a_repository/solution/test_solution.py b/intro_&_enviro/git/creating_a_repository/solution/test_solution.py new file mode 100644 index 00000000..990a2a46 --- /dev/null +++ b/intro_&_enviro/git/creating_a_repository/solution/test_solution.py @@ -0,0 +1,5 @@ + +def test_solution(): + import solution + assert solution.answer in {'a', 'A'} + diff --git a/intro_&_enviro/git/remote_repository/README.md b/intro_&_enviro/git/remote_repository/README.md new file mode 100644 index 00000000..5cb150e8 --- /dev/null +++ b/intro_&_enviro/git/remote_repository/README.md @@ -0,0 +1,12 @@ +# Remote Repository + +## Problem Description +Which of the following synchronizes your local repository and the remote repository? + +a) `git init` +b) `git add` +c) `git commit` +d) `git push` + +## Submission +* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. diff --git a/intro_&_enviro/git/remote_repository/solution/solution.py b/intro_&_enviro/git/remote_repository/solution/solution.py new file mode 100644 index 00000000..17038c37 --- /dev/null +++ b/intro_&_enviro/git/remote_repository/solution/solution.py @@ -0,0 +1,2 @@ +# Code your solution here +answer = '' diff --git a/intro_&_enviro/git/remote_repository/solution/test_solution.py b/intro_&_enviro/git/remote_repository/solution/test_solution.py new file mode 100644 index 00000000..e935c53f --- /dev/null +++ b/intro_&_enviro/git/remote_repository/solution/test_solution.py @@ -0,0 +1,5 @@ + +def test_solution(): + import solution + assert solution.answer in {'d', 'D'} + diff --git a/intro_&_enviro/git/staging_area/README.md b/intro_&_enviro/git/staging_area/README.md new file mode 100644 index 00000000..f2df36be --- /dev/null +++ b/intro_&_enviro/git/staging_area/README.md @@ -0,0 +1,12 @@ +# Staging Area + +## Problem Description +Which of the following commands syncronizes the staging area with your repository? + +a) `git init` +b) `git add` +c) `git commit` +d) `git push` + +## Submission +* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. diff --git a/intro_&_enviro/git/staging_area/solution/solution.py b/intro_&_enviro/git/staging_area/solution/solution.py new file mode 100644 index 00000000..17038c37 --- /dev/null +++ b/intro_&_enviro/git/staging_area/solution/solution.py @@ -0,0 +1,2 @@ +# Code your solution here +answer = '' diff --git a/intro_&_enviro/git/staging_area/solution/test_solution.py b/intro_&_enviro/git/staging_area/solution/test_solution.py new file mode 100644 index 00000000..ef69e5ec --- /dev/null +++ b/intro_&_enviro/git/staging_area/solution/test_solution.py @@ -0,0 +1,5 @@ + +def test_solution(): + import solution + assert solution.answer in {'c', 'C'} + diff --git a/intro_&_enviro/git/update_code/README.md b/intro_&_enviro/git/update_code/README.md new file mode 100644 index 00000000..cda1d184 --- /dev/null +++ b/intro_&_enviro/git/update_code/README.md @@ -0,0 +1,12 @@ +# Updating Code + +## Problem Description +Which of the following pushes changes from your working directory to your staging area? + +a) `git init` +b) `git add` +c) `git commit` +d) `git push` + +## Submission +* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. diff --git a/intro_&_enviro/git/update_code/solution/solution.py b/intro_&_enviro/git/update_code/solution/solution.py new file mode 100644 index 00000000..17038c37 --- /dev/null +++ b/intro_&_enviro/git/update_code/solution/solution.py @@ -0,0 +1,2 @@ +# Code your solution here +answer = '' diff --git a/intro_&_enviro/git/update_code/solution/test_solution.py b/intro_&_enviro/git/update_code/solution/test_solution.py new file mode 100644 index 00000000..09e33c52 --- /dev/null +++ b/intro_&_enviro/git/update_code/solution/test_solution.py @@ -0,0 +1,5 @@ + +def test_solution(): + import solution + assert solution.answer in {'b', 'B'} + diff --git a/intro_&_enviro/hello_world/1_arithmetic/README.md b/intro_&_enviro/hello_world/1_arithmetic/README.md new file mode 100644 index 00000000..6ba06d73 --- /dev/null +++ b/intro_&_enviro/hello_world/1_arithmetic/README.md @@ -0,0 +1,20 @@ +# Arithmetic + +## Problem Description +The *solution.py* file contains 2 variables `x` and `y` whose contents are hidden from you (the default values of 0 are placeholders). Below is a table of 7 variables you must create and the associated values they should be bound to. + + Variable | Value +:----------:|:-----: +`SUM` | `x + y` +`DIFF` | `x - y` +`MULT` | `x * y` +`DIV` | `x / y` +`POWER` | `x ** y` +`QUOTIENT` | `x // y` +`REMAINDER` | `x % y` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/1_arithmetic/solution/provided_code.py b/intro_&_enviro/hello_world/1_arithmetic/solution/provided_code.py new file mode 100644 index 00000000..5d460da9 --- /dev/null +++ b/intro_&_enviro/hello_world/1_arithmetic/solution/provided_code.py @@ -0,0 +1,2 @@ +x = 0 +y = 0 diff --git a/intro_&_enviro/hello_world/1_arithmetic/solution/solution.py b/intro_&_enviro/hello_world/1_arithmetic/solution/solution.py new file mode 100644 index 00000000..1acf24e6 --- /dev/null +++ b/intro_&_enviro/hello_world/1_arithmetic/solution/solution.py @@ -0,0 +1 @@ +from provided_code import x, y diff --git a/intro_&_enviro/hello_world/1_arithmetic/solution/test_solution.py b/intro_&_enviro/hello_world/1_arithmetic/solution/test_solution.py new file mode 100644 index 00000000..627d84b6 --- /dev/null +++ b/intro_&_enviro/hello_world/1_arithmetic/solution/test_solution.py @@ -0,0 +1,12 @@ +import provided_code +provided_code.x = 20 +provided_code.y = 10 +import solution + +def test_solution(): + assert solution.SUM == 30 + assert solution.DIFF == 10 + assert solution.MULT == 200 + assert solution.DIV == 2 + assert solution.QUOTIENT == 2 + assert solution.REMAINDER == 0 diff --git a/intro_&_enviro/hello_world/1_concantenation/README.md b/intro_&_enviro/hello_world/1_concantenation/README.md new file mode 100644 index 00000000..1bae5fc4 --- /dev/null +++ b/intro_&_enviro/hello_world/1_concantenation/README.md @@ -0,0 +1,15 @@ +## Concatenate Data + +## Motivation +Python allows the developer to concatenate string with string but never string with integer/float data type. + +## Problem Description +Write a python script that contains 2 string variables `string_1` and `string_2` whos contents is hidden from you. +Your goal is to concatenate the 2 variables and store inside another variable `result`. +Print the result. + +## Testing +*done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/1_concantenation/Solution/solution.py b/intro_&_enviro/hello_world/1_concantenation/Solution/solution.py new file mode 100644 index 00000000..dc11d437 --- /dev/null +++ b/intro_&_enviro/hello_world/1_concantenation/Solution/solution.py @@ -0,0 +1,5 @@ +# Code your solution here +string_1="Good Morning " +string_2= "Universe" +result=string_1+string_2 +print(result) \ No newline at end of file diff --git a/intro_&_enviro/hello_world/1_concantenation/Solution/test_solution.py b/intro_&_enviro/hello_world/1_concantenation/Solution/test_solution.py new file mode 100644 index 00000000..043656c5 --- /dev/null +++ b/intro_&_enviro/hello_world/1_concantenation/Solution/test_solution.py @@ -0,0 +1,16 @@ + + +def test_solution(monkeypatch): + x="Good Morning " + y="Universe" + ret_val1=None + + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.string_1==x + assert solution.string_2==y diff --git a/intro_&_enviro/hello_world/1_name_bindings/README.md b/intro_&_enviro/hello_world/1_name_bindings/README.md new file mode 100644 index 00000000..ef50a0d3 --- /dev/null +++ b/intro_&_enviro/hello_world/1_name_bindings/README.md @@ -0,0 +1,10 @@ +# Name Bindings + +## Problem Description +Declare 3 names in the *solution.py* file `x`, `y`, `z` which should the values `1337`, `'hello world'` and `13.5` respectively. + +## Testing +* To test your solution, type 'pytest' within the **Solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/1_name_bindings/solution/solution.py b/intro_&_enviro/hello_world/1_name_bindings/solution/solution.py new file mode 100644 index 00000000..c33bac44 --- /dev/null +++ b/intro_&_enviro/hello_world/1_name_bindings/solution/solution.py @@ -0,0 +1,3 @@ +x = 1337 +y = 'hello world' +z = 13.5 diff --git a/intro_&_enviro/hello_world/1_name_bindings/solution/test_solution.py b/intro_&_enviro/hello_world/1_name_bindings/solution/test_solution.py new file mode 100644 index 00000000..892eff71 --- /dev/null +++ b/intro_&_enviro/hello_world/1_name_bindings/solution/test_solution.py @@ -0,0 +1,6 @@ +import solution + +def test_solution(): + assert solution.x == 1337 + assert solution.y == 'hello world' + assert solution.z == 13.5 diff --git a/intro_&_enviro/hello_world/1_operators/README.md b/intro_&_enviro/hello_world/1_operators/README.md new file mode 100644 index 00000000..4f7d9342 --- /dev/null +++ b/intro_&_enviro/hello_world/1_operators/README.md @@ -0,0 +1,10 @@ +# Operators + +## Problem Description +Python provides us with `//` and `%` operators for integer types. Determine 2 integers `X` and `Y` such that `X % Y` equals `X // Y`. Store these numbers in their respective names. + +## Testing +* To test your solution, type 'pytest' within the **Solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/1_operators/solution/solution.py b/intro_&_enviro/hello_world/1_operators/solution/solution.py new file mode 100644 index 00000000..d226143b --- /dev/null +++ b/intro_&_enviro/hello_world/1_operators/solution/solution.py @@ -0,0 +1 @@ +# Code your solution here diff --git a/intro_&_enviro/hello_world/1_operators/solution/test_solution.py b/intro_&_enviro/hello_world/1_operators/solution/test_solution.py new file mode 100644 index 00000000..a344d918 --- /dev/null +++ b/intro_&_enviro/hello_world/1_operators/solution/test_solution.py @@ -0,0 +1,4 @@ +import solution + +def test_solution(): + assert solution.X % solution.Y == solution.X // solution.Y diff --git a/intro_&_enviro/hello_world/2_capture_display/README.md b/intro_&_enviro/hello_world/2_capture_display/README.md new file mode 100644 index 00000000..4935e8c2 --- /dev/null +++ b/intro_&_enviro/hello_world/2_capture_display/README.md @@ -0,0 +1,14 @@ +# Capture Display + +## Motivation +Python provides us with the input() keyword in order to capture data from the user. + +## Problem Description +Write a Python script that asks the user for name and age . Store these values in `name`, `age` objects respectively. +Print the values. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/2_capture_display/Solution/solution.py b/intro_&_enviro/hello_world/2_capture_display/Solution/solution.py new file mode 100644 index 00000000..7bb51060 --- /dev/null +++ b/intro_&_enviro/hello_world/2_capture_display/Solution/solution.py @@ -0,0 +1,5 @@ +# Code your solution here +name=input() +age=input() + +print(name,age) \ No newline at end of file diff --git a/intro_&_enviro/hello_world/2_capture_display/Solution/test_solution.py b/intro_&_enviro/hello_world/2_capture_display/Solution/test_solution.py new file mode 100644 index 00000000..6656f2e5 --- /dev/null +++ b/intro_&_enviro/hello_world/2_capture_display/Solution/test_solution.py @@ -0,0 +1,24 @@ + +def test_solution(monkeypatch): + x=['Charlie','100'] + index=-1 + ret_val1=None + ret_val2=None + + def f(): + nonlocal index + nonlocal x + index += 1 + return x[index] + + def g(num1,num2): + nonlocal ret_val1 + nonlocal ret_val2 + ret_val1=num1 + ret_val2=num2 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + import solution + assert solution.name=='Charlie' + assert solution.age=='100' diff --git a/intro_&_enviro/hello_world/2_python_caches/README.md b/intro_&_enviro/hello_world/2_python_caches/README.md new file mode 100644 index 00000000..77ea4f8c --- /dev/null +++ b/intro_&_enviro/hello_world/2_python_caches/README.md @@ -0,0 +1,35 @@ +# Python Caches + +## Motivation +The ``id`` function helps us determine the memory address of a particular variable. Python dynamically creates memory each time we create a variable. For example, if you type the following code into a Python command prompt, you will see the memory address of where x and y are stored. Notice how they change upon changing the variables - this is Python's dynamic nature of memory creation. **Note: Do not type this in an editor - reasons beyond the scope of this lesson**. +```Python +>>> x = 1 +>>> y = 1 +>>> id(x) +10914496 +>>> id(y) +10914496 +>>> x = 1234 +>>> id(x) +1400159191253392 +>>> y = 1234 +>>> id(y) +1400159191254216 +``` + +You will notice that when x and y are 1, they are stored in the same memory address while when x and y are 1234, they are stored in separate memory addresses. This is attributed to the fact that Python only dynamically creates integers above a certain range and stores small integers in memory as they are commonly used in a developers code. This is known as [caching](https://en.wikipedia.org/wiki/Cache_(computing)) and it improves the performance of Python code as dynamically creating memory is expensive. + +## Problem Descripton + +Your goal is to determine what range of integers Python saves in memory (caches). + +* a) What is the lower bound of the range? +* b) What is the upper bound of the range? + +## Testing +* To test your solution, type 'pytest' within the **Solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +* The file contains 2 variables - `LOWER_BOUND` and `UPPER_BOUND representing each bound respectively +* Overwrite these numbers with your answers diff --git a/intro_&_enviro/hello_world/2_python_caches/solution/solution.py b/intro_&_enviro/hello_world/2_python_caches/solution/solution.py new file mode 100644 index 00000000..dae07c9a --- /dev/null +++ b/intro_&_enviro/hello_world/2_python_caches/solution/solution.py @@ -0,0 +1,2 @@ +LOWER_BOUND = -5 +UPPER_BOUND = 256 diff --git a/intro_&_enviro/hello_world/2_python_caches/solution/test_solution.py b/intro_&_enviro/hello_world/2_python_caches/solution/test_solution.py new file mode 100644 index 00000000..1471bda4 --- /dev/null +++ b/intro_&_enviro/hello_world/2_python_caches/solution/test_solution.py @@ -0,0 +1,5 @@ +import solution + +def test_solution(): + assert solution.LOWER_BOUND == -5, "Incorrect lower bound" + assert solution.UPPER_BOUND == 256, "Incorrect upper bound" diff --git a/intro_&_enviro/hello_world/2_string_arithmetic/README.md b/intro_&_enviro/hello_world/2_string_arithmetic/README.md new file mode 100644 index 00000000..282bb011 --- /dev/null +++ b/intro_&_enviro/hello_world/2_string_arithmetic/README.md @@ -0,0 +1,15 @@ +# String Arithmetic + +## Motivation +In the [Arithmetic](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/Exercises/Hello-World/1-Arithmetic) exercise we saw the 7 arithmetic operators. Only some of the 7 operators (`+`, `-`, `*`, `/`, `**`, `//`, `%`) work on strings. + +## Problem Description +Determine how many of the 7 operators listed above work on the `str` type and store that number in a name `STR_ARITHMETIC`. + +Hint: Don't just try arithmetic with strings and strings, try arithmetic with strings and integers as well + +## Testing +* To test your solution, type 'pytest' within the **Solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/2_string_arithmetic/solution/solution.py b/intro_&_enviro/hello_world/2_string_arithmetic/solution/solution.py new file mode 100644 index 00000000..d226143b --- /dev/null +++ b/intro_&_enviro/hello_world/2_string_arithmetic/solution/solution.py @@ -0,0 +1 @@ +# Code your solution here diff --git a/intro_&_enviro/hello_world/2_string_arithmetic/solution/test_solution.py b/intro_&_enviro/hello_world/2_string_arithmetic/solution/test_solution.py new file mode 100644 index 00000000..859c9f07 --- /dev/null +++ b/intro_&_enviro/hello_world/2_string_arithmetic/solution/test_solution.py @@ -0,0 +1,4 @@ +import solution + +def test_solution(): + assert solution.STR_ARITHMETIC == 2 diff --git a/intro_&_enviro/hello_world/2_string_duplication/README.md b/intro_&_enviro/hello_world/2_string_duplication/README.md new file mode 100644 index 00000000..7dddd43c --- /dev/null +++ b/intro_&_enviro/hello_world/2_string_duplication/README.md @@ -0,0 +1,15 @@ +# String Duplicate + +## Motivation +String values can be duplicated with help of the * operator. + +## Problem Description +Write a Python script that asks the user for a string value and an intger value for number of times the user wishs to duplicate the string. +Store the values in `string_1` and `dup_val ` objects respectively. Store the result in variable `data`. +Print the result. + +## Testing +*done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/2_string_duplication/Solution/solution.py b/intro_&_enviro/hello_world/2_string_duplication/Solution/solution.py new file mode 100644 index 00000000..e566ccb1 --- /dev/null +++ b/intro_&_enviro/hello_world/2_string_duplication/Solution/solution.py @@ -0,0 +1,6 @@ +# Code your solution here + +string_1=input() +dup_val=input() +data=string_1*dup_val +print(data) diff --git a/intro_&_enviro/hello_world/2_string_duplication/Solution/test_solution.py b/intro_&_enviro/hello_world/2_string_duplication/Solution/test_solution.py new file mode 100644 index 00000000..75c09ce7 --- /dev/null +++ b/intro_&_enviro/hello_world/2_string_duplication/Solution/test_solution.py @@ -0,0 +1,24 @@ + + +def test_solution(monkeypatch): + x=['Charlie',5] + index=-1 + ret_val= None + + def f(): + nonlocal x + nonlocal index + index+=1 + return x[index] + + def g(num): + nonlocal ret_val + ret_val=num + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.string_1=='Charlie' + assert solution.dup_val==5 + diff --git a/intro_&_enviro/hello_world/2_type_check/README.md b/intro_&_enviro/hello_world/2_type_check/README.md new file mode 100644 index 00000000..73fcee0a --- /dev/null +++ b/intro_&_enviro/hello_world/2_type_check/README.md @@ -0,0 +1,17 @@ +# Type Check + +## Motivation +Python provides us with the type() method to capture and check the data type of a value from user. +STANDARD DATA TYPES: 1.Integer 2.Float 3.String 4.Boolean 5.Complex Number + +## Problem Description +Write a Python script that asks the user to input any 2 data type value. +Store the values in `input_1` and `input_2 ` objects respectively. Check the type and store the results in object `data_1` and `data_2`. +Print the result. + + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/2_type_check/Solution/solution.py b/intro_&_enviro/hello_world/2_type_check/Solution/solution.py new file mode 100644 index 00000000..a879db60 --- /dev/null +++ b/intro_&_enviro/hello_world/2_type_check/Solution/solution.py @@ -0,0 +1,5 @@ +input_1=int(input()) +input_2=float(input()) +data_1=type(input_1) +data_2=type(input_2) +print(data_1,data_2) \ No newline at end of file diff --git a/intro_&_enviro/hello_world/2_type_check/Solution/test_solution.py b/intro_&_enviro/hello_world/2_type_check/Solution/test_solution.py new file mode 100644 index 00000000..a1cdb6af --- /dev/null +++ b/intro_&_enviro/hello_world/2_type_check/Solution/test_solution.py @@ -0,0 +1,29 @@ + + +def test_solution(monkeypatch): + x=[1,2.0] + index = -1 + ret_val1= None + ret_val2= None + + def f(): + nonlocal index + nonlocal x + index += 1 + return x[index] + + def g(num1,num2): + nonlocal ret_val1 + nonlocal ret_val2 + ret_val1=num1 + ret_val2=num2 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.input_1==1 + assert solution.input_2==2.0 + + + diff --git a/intro_&_enviro/hello_world/3_type_change/README.md b/intro_&_enviro/hello_world/3_type_change/README.md new file mode 100644 index 00000000..508465b9 --- /dev/null +++ b/intro_&_enviro/hello_world/3_type_change/README.md @@ -0,0 +1,15 @@ +# Type Change + +## Motivation +Type() method is key for changing data type of an object value. + +## Problem Description +Write a python script that contains 2 variables `object_1` and `object_2` containing a float and string number value respectively. +Convert the variables into string and integer data types. +Print the change. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/3_type_change/Solution/solution.py b/intro_&_enviro/hello_world/3_type_change/Solution/solution.py new file mode 100644 index 00000000..53eca491 --- /dev/null +++ b/intro_&_enviro/hello_world/3_type_change/Solution/solution.py @@ -0,0 +1,8 @@ +# Code your solution here +object_1=100.0 +object_2="99" + +object_change_1=str(object_1) +object_change_2=int(object_2) + +print(object_change_1,object_change_2) \ No newline at end of file diff --git a/intro_&_enviro/hello_world/3_type_change/Solution/test_solution.py b/intro_&_enviro/hello_world/3_type_change/Solution/test_solution.py new file mode 100644 index 00000000..0b411814 --- /dev/null +++ b/intro_&_enviro/hello_world/3_type_change/Solution/test_solution.py @@ -0,0 +1,16 @@ + +def test_solution(monkeypatch): + ret_val1= None + ret_val2=None + + def g(num1,num2): + nonlocal ret_val1 + nonlocal ret_val2 + ret_val1=num1 + ret_val2=num2 + + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.object_1==100.0 + assert solution.object_2=="99" \ No newline at end of file diff --git a/intro_&_enviro/hello_world/3_user_input/README.md b/intro_&_enviro/hello_world/3_user_input/README.md new file mode 100644 index 00000000..92665349 --- /dev/null +++ b/intro_&_enviro/hello_world/3_user_input/README.md @@ -0,0 +1,10 @@ +# User Input + +## Problem Description +Write a Python script in *solution.py* that asks the user for 3 numbers. Store these numbers in `FIRST_NUM`, `SECOND_NUM` and `THIRD_NUM` respectively. Then print the average of these 3 numbers. + +## Testing +* To test your solution, type 'pytest' within the **Solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/3_user_input/solution/solution.py b/intro_&_enviro/hello_world/3_user_input/solution/solution.py new file mode 100644 index 00000000..d226143b --- /dev/null +++ b/intro_&_enviro/hello_world/3_user_input/solution/solution.py @@ -0,0 +1 @@ +# Code your solution here diff --git a/intro_&_enviro/hello_world/3_user_input/solution/test_solution.py b/intro_&_enviro/hello_world/3_user_input/solution/test_solution.py new file mode 100644 index 00000000..eecba99b --- /dev/null +++ b/intro_&_enviro/hello_world/3_user_input/solution/test_solution.py @@ -0,0 +1,9 @@ +def test_solution(monkeypatch): + print_val = 0 + def f(x): + nonlocal print_val + print_val = x + monkeypatch.setattr('builtins.input', lambda: 100) + monkeypatch.setattr('builtins.print', f) + import solution as S + assert S.FIRST_NUM == S.SECOND_NUM == S.THIRD_NUM == print_val == 100 diff --git a/intro_&_enviro/hello_world/Documents - Shortcut.lnk b/intro_&_enviro/hello_world/Documents - Shortcut.lnk new file mode 100644 index 00000000..4fade821 Binary files /dev/null and b/intro_&_enviro/hello_world/Documents - Shortcut.lnk differ diff --git a/intro_&_enviro/hello_world/README.md b/intro_&_enviro/hello_world/README.md new file mode 100644 index 00000000..170a4a3a --- /dev/null +++ b/intro_&_enviro/hello_world/README.md @@ -0,0 +1,16 @@ +# Exercises for Hello World + + +| Exercise ID | Exercise | +|:-----------:|:--------:| +| easy_e1 | [Arithmetic](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_and_environment/hello_world/1_arithmetic) | +| easy_e2 | [Concatenation](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_and_environment/hello_world/1_concantenation) | +| easy_e3 | [Name Bindings](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_and_environment/hello_world/1_name_bindings) | +| easy_e4 | [Operators](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_and_environment/hello_world/1_operators) | +| medium_e1 | [Capture Display](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_and_environment/hello_world/2_capture_display) | +| medium_e2 | [Python Caches](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_and_environment/hello_world/2_python_caches) | +| medium_e3 | [String Arithmetic](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_and_environment/hello_world/2_string_arithmetic) | +| medium_e4 | [String Duplication](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_and_environment/hello_world/2_string_duplication) | +| medium_e5 | [Type Checking](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_and_environment/hello_world/2_type_check) | +| hard_e1 | [Type Change](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_and_environment/hello_world/3_type_change) | +| hard_e2 | [User Input](https://github.com/ByteAcademyCo/Exercises/tree/master/introduction_and_environment/hello_world/3_user_input) | diff --git a/intro_&_enviro/hello_world/arithmetic/README.md b/intro_&_enviro/hello_world/arithmetic/README.md new file mode 100644 index 00000000..3d0bfc65 --- /dev/null +++ b/intro_&_enviro/hello_world/arithmetic/README.md @@ -0,0 +1,20 @@ +# Arithmetic + +## Problem Description +The *solution.py* file contains 2 variables `x` and `y` whose values are hidden from you. They will each default to 0. Create the following variables from the chart below and set them equal to the associated values. + + Variable | Value +:----------:|:-----: +`my_sum` | `x + y` +`my_diff` | `x - y` +`my_mult` | `x * y` +`my_div` | `x / y` +`my_power` | `x ** y` +`my_quotient` | `x // y` +`my_remainder` | `x % y` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/arithmetic/solution/provided_code.py b/intro_&_enviro/hello_world/arithmetic/solution/provided_code.py new file mode 100644 index 00000000..a0c8913c --- /dev/null +++ b/intro_&_enviro/hello_world/arithmetic/solution/provided_code.py @@ -0,0 +1,2 @@ +x = 10 +y = 30 diff --git a/intro_&_enviro/hello_world/arithmetic/solution/solution.py b/intro_&_enviro/hello_world/arithmetic/solution/solution.py new file mode 100644 index 00000000..2c710360 --- /dev/null +++ b/intro_&_enviro/hello_world/arithmetic/solution/solution.py @@ -0,0 +1,9 @@ +from provided_code import x, y + +my_sum = x + y +my_diff = x - y +my_mult = x * y +my_div = x / y +my_power = x ** y +my_quotient = x // y +my_remainder = x % y diff --git a/intro_&_enviro/hello_world/arithmetic/solution/test_solution.py b/intro_&_enviro/hello_world/arithmetic/solution/test_solution.py new file mode 100644 index 00000000..c48da514 --- /dev/null +++ b/intro_&_enviro/hello_world/arithmetic/solution/test_solution.py @@ -0,0 +1,13 @@ +import provided_code +provided_code.x = 20 +provided_code.y = 10 +import solution + +def test_solution(): + assert solution.my_sum == 30 + assert solution.my_diff == 10 + assert solution.my_mult == 200 + assert solution.my_div == 2 + assert solution.my_power == 10240000000000 + assert solution.my_quotient == 2 + assert solution.my_remainder == 0 diff --git a/intro_&_enviro/hello_world/capture_display/README.md b/intro_&_enviro/hello_world/capture_display/README.md new file mode 100644 index 00000000..39491add --- /dev/null +++ b/intro_&_enviro/hello_world/capture_display/README.md @@ -0,0 +1,14 @@ +# Capture Display + +## Motivation +Python provides us with the input() method in order to capture data from the user. + +## Problem Description +Write a Python script that asks the user for name and age . Store these values in variables called `name` and `age`, respectively. +Print the values. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/capture_display/solution/solution.py b/intro_&_enviro/hello_world/capture_display/solution/solution.py new file mode 100644 index 00000000..df9626fa --- /dev/null +++ b/intro_&_enviro/hello_world/capture_display/solution/solution.py @@ -0,0 +1,5 @@ +# Code your solution here +name = input("What is your name? ") +age = input("What is your age? ") + +print(name, age) \ No newline at end of file diff --git a/intro_&_enviro/hello_world/capture_display/solution/test_solution.py b/intro_&_enviro/hello_world/capture_display/solution/test_solution.py new file mode 100644 index 00000000..6656f2e5 --- /dev/null +++ b/intro_&_enviro/hello_world/capture_display/solution/test_solution.py @@ -0,0 +1,24 @@ + +def test_solution(monkeypatch): + x=['Charlie','100'] + index=-1 + ret_val1=None + ret_val2=None + + def f(): + nonlocal index + nonlocal x + index += 1 + return x[index] + + def g(num1,num2): + nonlocal ret_val1 + nonlocal ret_val2 + ret_val1=num1 + ret_val2=num2 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + import solution + assert solution.name=='Charlie' + assert solution.age=='100' diff --git a/intro_&_enviro/hello_world/concantenation/README.md b/intro_&_enviro/hello_world/concantenation/README.md new file mode 100644 index 00000000..ebdc95f0 --- /dev/null +++ b/intro_&_enviro/hello_world/concantenation/README.md @@ -0,0 +1,15 @@ +## Concatenate Data + +## Motivation +Concatenation in Python allows us to concatenate a string with another string, but never strings with other data types (such as integers, floats). + +## Problem Description +Write a python script that creates 2 string variables `string_1` and `string_2`. +Concatenate the 2 variables and store inside a new variable `result`. +Print the result. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/concantenation/solution/solution.py b/intro_&_enviro/hello_world/concantenation/solution/solution.py new file mode 100644 index 00000000..c1de7c52 --- /dev/null +++ b/intro_&_enviro/hello_world/concantenation/solution/solution.py @@ -0,0 +1,5 @@ +# Code your solution below +string_1 = "Good Morning " +string_2 = "Universe" +result = string_1 + string_2 +print(result) \ No newline at end of file diff --git a/intro_&_enviro/hello_world/concantenation/solution/test_solution.py b/intro_&_enviro/hello_world/concantenation/solution/test_solution.py new file mode 100644 index 00000000..ad80c475 --- /dev/null +++ b/intro_&_enviro/hello_world/concantenation/solution/test_solution.py @@ -0,0 +1,16 @@ + + +def test_solution(monkeypatch): + x = "Good Morning " + y = "Universe" + ret_val1 = None + + def g(num1): + nonlocal ret_val1 + ret_val1 = num1 + + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.string_1 == x + assert solution.string_2 == y diff --git a/intro_&_enviro/hello_world/name_bindings/README.md b/intro_&_enviro/hello_world/name_bindings/README.md new file mode 100644 index 00000000..9591f097 --- /dev/null +++ b/intro_&_enviro/hello_world/name_bindings/README.md @@ -0,0 +1,10 @@ +# Name Bindings + +## Problem Description +Create 3 variables in the *solution.py* file `x`, `y`, `z` which should hold the values 1337, `'hello world'` and 13.5 respectively. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/name_bindings/solution/solution.py b/intro_&_enviro/hello_world/name_bindings/solution/solution.py new file mode 100644 index 00000000..c33bac44 --- /dev/null +++ b/intro_&_enviro/hello_world/name_bindings/solution/solution.py @@ -0,0 +1,3 @@ +x = 1337 +y = 'hello world' +z = 13.5 diff --git a/intro_&_enviro/hello_world/name_bindings/solution/test_solution.py b/intro_&_enviro/hello_world/name_bindings/solution/test_solution.py new file mode 100644 index 00000000..892eff71 --- /dev/null +++ b/intro_&_enviro/hello_world/name_bindings/solution/test_solution.py @@ -0,0 +1,6 @@ +import solution + +def test_solution(): + assert solution.x == 1337 + assert solution.y == 'hello world' + assert solution.z == 13.5 diff --git a/intro_&_enviro/hello_world/operators/README.md b/intro_&_enviro/hello_world/operators/README.md new file mode 100644 index 00000000..98c7045b --- /dev/null +++ b/intro_&_enviro/hello_world/operators/README.md @@ -0,0 +1,10 @@ +# Operators + +## Problem Description +Python provides us with floor divison `//` and modulus division `%` operators for integer types. Create 2 variables named `x` and `y`, such that `x % y` equals `x // y`. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/operators/solution/solution.py b/intro_&_enviro/hello_world/operators/solution/solution.py new file mode 100644 index 00000000..35905d2c --- /dev/null +++ b/intro_&_enviro/hello_world/operators/solution/solution.py @@ -0,0 +1,3 @@ +# Code your solution here +x = 11 +y = 10 diff --git a/intro_&_enviro/hello_world/operators/solution/test_solution.py b/intro_&_enviro/hello_world/operators/solution/test_solution.py new file mode 100644 index 00000000..36c7ec86 --- /dev/null +++ b/intro_&_enviro/hello_world/operators/solution/test_solution.py @@ -0,0 +1,4 @@ +import solution + +def test_solution(): + assert solution.x % solution.y == solution.x // solution.y diff --git a/intro_&_enviro/hello_world/python_caches/README.md b/intro_&_enviro/hello_world/python_caches/README.md new file mode 100644 index 00000000..c7bcc0b6 --- /dev/null +++ b/intro_&_enviro/hello_world/python_caches/README.md @@ -0,0 +1,36 @@ +# Python Caches + +## Motivation +The Python built-in id() function tells us the memory address of a particular variable. Python dynamically saves contents to memory each time we create a variable. +For example, if you type the following code into a Python command prompt, you will see the memory address of where x and y are stored. Notice how they change upon changing the variables - this is Python's dynamic nature of memory creation. **Note: Do not type this in an editor - reasons beyond the scope of this lesson**. +```Python +>>> x = 1 +>>> y = 1 +>>> id(x) +10914496 +>>> id(y) +10914496 +>>> x = 1234 +>>> id(x) +1400159191253392 +>>> y = 1234 +>>> id(y) +1400159191254216 +``` + +You will notice that when x and y are both 1, they are stored in the same memory address while when x and y are both 1234, they are stored in separate memory addresses. This is attributed to the fact that Python only dynamically creates integers above a certain range and stores small integers in memory as they are commonly used in a developers code. This is known as [caching](https://en.wikipedia.org/wiki/Cache_(computing)) and it improves the performance of Python code since dynamically creating memory is expensive. + +## Problem Descripton + +Your goal is to determine what range of integers Python saves in memory (caches). + +* a) What is the lower bound of the range? Store this number in variable `lower_bound` +* b) What is the upper bound of the range? Store this number in variable `upper_bound` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +* The file contains 2 variables - `LOWER_BOUND` and `UPPER_BOUND` representing each bound respectively +* Overwrite these numbers with your answers diff --git a/intro_&_enviro/hello_world/python_caches/solution/solution.py b/intro_&_enviro/hello_world/python_caches/solution/solution.py new file mode 100644 index 00000000..5bb38671 --- /dev/null +++ b/intro_&_enviro/hello_world/python_caches/solution/solution.py @@ -0,0 +1,2 @@ +lower_bound = -5 +upper_bound = 256 \ No newline at end of file diff --git a/intro_&_enviro/hello_world/python_caches/solution/test_solution.py b/intro_&_enviro/hello_world/python_caches/solution/test_solution.py new file mode 100644 index 00000000..9d00a2a2 --- /dev/null +++ b/intro_&_enviro/hello_world/python_caches/solution/test_solution.py @@ -0,0 +1,5 @@ +import solution + +def test_solution(): + assert solution.lower_bound == -5, "Incorrect lower bound" + assert solution.upper_bound == 256, "Incorrect upper bound" diff --git a/intro_&_enviro/hello_world/string_arithmetic/README.md b/intro_&_enviro/hello_world/string_arithmetic/README.md new file mode 100644 index 00000000..282bb011 --- /dev/null +++ b/intro_&_enviro/hello_world/string_arithmetic/README.md @@ -0,0 +1,15 @@ +# String Arithmetic + +## Motivation +In the [Arithmetic](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/Exercises/Hello-World/1-Arithmetic) exercise we saw the 7 arithmetic operators. Only some of the 7 operators (`+`, `-`, `*`, `/`, `**`, `//`, `%`) work on strings. + +## Problem Description +Determine how many of the 7 operators listed above work on the `str` type and store that number in a name `STR_ARITHMETIC`. + +Hint: Don't just try arithmetic with strings and strings, try arithmetic with strings and integers as well + +## Testing +* To test your solution, type 'pytest' within the **Solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/string_arithmetic/solution/solution.py b/intro_&_enviro/hello_world/string_arithmetic/solution/solution.py new file mode 100644 index 00000000..dc572a6a --- /dev/null +++ b/intro_&_enviro/hello_world/string_arithmetic/solution/solution.py @@ -0,0 +1,3 @@ +# Code your solution here + +str_arithmetic = 2 \ No newline at end of file diff --git a/intro_&_enviro/hello_world/string_arithmetic/solution/test_solution.py b/intro_&_enviro/hello_world/string_arithmetic/solution/test_solution.py new file mode 100644 index 00000000..9560e0c2 --- /dev/null +++ b/intro_&_enviro/hello_world/string_arithmetic/solution/test_solution.py @@ -0,0 +1,4 @@ +import solution + +def test_solution(): + assert solution.str_arithmetic == 2 diff --git a/intro_&_enviro/hello_world/string_duplication/README.md b/intro_&_enviro/hello_world/string_duplication/README.md new file mode 100644 index 00000000..554fc103 --- /dev/null +++ b/intro_&_enviro/hello_world/string_duplication/README.md @@ -0,0 +1,15 @@ +# String Duplicate + +## Motivation +String values can be duplicated with help of the `*` operator. + +## Problem Description +Write a Python script that asks the user for a string value and an integer value, representing the number of times the user wishs to duplicate the string. +Store the values as `string_1` and `dup_val `, respectively. Then, repeat the string `dup_val` number of times and store the result with the variable name `data`. +Print `data`. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/string_duplication/solution/solution.py b/intro_&_enviro/hello_world/string_duplication/solution/solution.py new file mode 100644 index 00000000..feff16e9 --- /dev/null +++ b/intro_&_enviro/hello_world/string_duplication/solution/solution.py @@ -0,0 +1,5 @@ +# Code your solution here +string_1 = input() +dup_val = int(input()) +result = string_1 * dup_val +print(result) \ No newline at end of file diff --git a/intro_&_enviro/hello_world/string_duplication/solution/test_solution.py b/intro_&_enviro/hello_world/string_duplication/solution/test_solution.py new file mode 100644 index 00000000..75c09ce7 --- /dev/null +++ b/intro_&_enviro/hello_world/string_duplication/solution/test_solution.py @@ -0,0 +1,24 @@ + + +def test_solution(monkeypatch): + x=['Charlie',5] + index=-1 + ret_val= None + + def f(): + nonlocal x + nonlocal index + index+=1 + return x[index] + + def g(num): + nonlocal ret_val + ret_val=num + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.string_1=='Charlie' + assert solution.dup_val==5 + diff --git a/intro_&_enviro/hello_world/type_change/README.md b/intro_&_enviro/hello_world/type_change/README.md new file mode 100644 index 00000000..a50698c5 --- /dev/null +++ b/intro_&_enviro/hello_world/type_change/README.md @@ -0,0 +1,16 @@ +# Type Change + +## Motivation +There are multiple methods that will change the data type of a variable's value. + +## Problem Description +Write a python script that contains 2 variables, `object_1` and `object_2`, containing a float and string representation of a number, respectively. +Convert `object_1` to a string. +Convert `object_2` to an integer. +Print `object_1` and `object_2`. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/type_change/solution/solution.py b/intro_&_enviro/hello_world/type_change/solution/solution.py new file mode 100644 index 00000000..81f26da2 --- /dev/null +++ b/intro_&_enviro/hello_world/type_change/solution/solution.py @@ -0,0 +1,8 @@ +# Code your solution here +object_1 = 100.0 +object_2 = "99" + +object_change_1 = str(object_1) +object_change_2 = int(object_2) + +print(object_change_1, object_change_2) \ No newline at end of file diff --git a/intro_&_enviro/hello_world/type_change/solution/test_solution.py b/intro_&_enviro/hello_world/type_change/solution/test_solution.py new file mode 100644 index 00000000..6a92a44b --- /dev/null +++ b/intro_&_enviro/hello_world/type_change/solution/test_solution.py @@ -0,0 +1,16 @@ + +def test_solution(monkeypatch): + ret_val1 = None + ret_val2 = None + + def g(num1, num2): + nonlocal ret_val1 + nonlocal ret_val2 + ret_val1 = num1 + ret_val2 = num2 + + monkeypatch.setattr('builtins.print',g) + + import solution + assert type(solution.object_1) == float and type(solution.object_2) == str + assert type(ret_val1) == str and type(ret_val2) == int \ No newline at end of file diff --git a/intro_&_enviro/hello_world/type_check/README.md b/intro_&_enviro/hello_world/type_check/README.md new file mode 100644 index 00000000..99d9b6ef --- /dev/null +++ b/intro_&_enviro/hello_world/type_check/README.md @@ -0,0 +1,15 @@ +# Type Check + +## Motivation +Python provides us with the type() method to check the data type of a variable. + +## Problem Description +Write a Python script that asks the user to input any 2 values, and store the values in two variables, `input_1` and `input_2 `. +Check the type or each, and store the results in two new variables, `result_1` and `result_2`. +Print both results. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/type_check/solution/solution.py b/intro_&_enviro/hello_world/type_check/solution/solution.py new file mode 100644 index 00000000..bcd36479 --- /dev/null +++ b/intro_&_enviro/hello_world/type_check/solution/solution.py @@ -0,0 +1,6 @@ +# Code your solution here +input_1 = int(input()) +input_2 = float(input()) +result_1 = type(input_1) +result_2 = type(input_2) +print(result_1, result_2) \ No newline at end of file diff --git a/intro_&_enviro/hello_world/type_check/solution/test_solution.py b/intro_&_enviro/hello_world/type_check/solution/test_solution.py new file mode 100644 index 00000000..a1cdb6af --- /dev/null +++ b/intro_&_enviro/hello_world/type_check/solution/test_solution.py @@ -0,0 +1,29 @@ + + +def test_solution(monkeypatch): + x=[1,2.0] + index = -1 + ret_val1= None + ret_val2= None + + def f(): + nonlocal index + nonlocal x + index += 1 + return x[index] + + def g(num1,num2): + nonlocal ret_val1 + nonlocal ret_val2 + ret_val1=num1 + ret_val2=num2 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.input_1==1 + assert solution.input_2==2.0 + + + diff --git a/intro_&_enviro/hello_world/user_input/README.md b/intro_&_enviro/hello_world/user_input/README.md new file mode 100644 index 00000000..d40256f4 --- /dev/null +++ b/intro_&_enviro/hello_world/user_input/README.md @@ -0,0 +1,11 @@ +# User Input + +## Problem Description +Write a Python script in *solution.py* that asks the user for 3 numbers. Store these numbers in the variable names `first_num`, `second_num` and `third_num` respectively. +Print the average of these 3 numbers. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/intro_&_enviro/hello_world/user_input/solution/solution.py b/intro_&_enviro/hello_world/user_input/solution/solution.py new file mode 100644 index 00000000..95e78c11 --- /dev/null +++ b/intro_&_enviro/hello_world/user_input/solution/solution.py @@ -0,0 +1,6 @@ +# Code your solution here +first_num = input() +second_num = input() +third_num = input() +average = sum(first_num, second_num, third_num) / 3 +print(average) \ No newline at end of file diff --git a/intro_&_enviro/hello_world/user_input/solution/test_solution.py b/intro_&_enviro/hello_world/user_input/solution/test_solution.py new file mode 100644 index 00000000..eecba99b --- /dev/null +++ b/intro_&_enviro/hello_world/user_input/solution/test_solution.py @@ -0,0 +1,9 @@ +def test_solution(monkeypatch): + print_val = 0 + def f(x): + nonlocal print_val + print_val = x + monkeypatch.setattr('builtins.input', lambda: 100) + monkeypatch.setattr('builtins.print', f) + import solution as S + assert S.FIRST_NUM == S.SECOND_NUM == S.THIRD_NUM == print_val == 100 diff --git a/introduction_and_environment/introduction_to_programming/1_DNS/README.md b/intro_&_enviro/introduction_to_programming/1_DNS/README.md similarity index 94% rename from introduction_and_environment/introduction_to_programming/1_DNS/README.md rename to intro_&_enviro/introduction_to_programming/1_DNS/README.md index 5fc09d97..af46501a 100644 --- a/introduction_and_environment/introduction_to_programming/1_DNS/README.md +++ b/intro_&_enviro/introduction_to_programming/1_DNS/README.md @@ -1,18 +1,18 @@ -# DNS - -## Motivation - - -## Problem Description -DNS in internet technology stands for - -a.Distributed Name System -b.Data Name System -c.Dynamic Name System -d.Domain Name System - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# DNS + +## Motivation + + +## Problem Description +DNS in internet technology stands for + +a.Distributed Name System +b.Data Name System +c.Dynamic Name System +d.Domain Name System + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/introduction_to_programming/1_DNS/Solutions/solution.py b/intro_&_enviro/introduction_to_programming/1_DNS/Solutions/solution.py similarity index 97% rename from introduction_and_environment/introduction_to_programming/1_DNS/Solutions/solution.py rename to intro_&_enviro/introduction_to_programming/1_DNS/Solutions/solution.py index 2daa7c54..b788a0c9 100644 --- a/introduction_and_environment/introduction_to_programming/1_DNS/Solutions/solution.py +++ b/intro_&_enviro/introduction_to_programming/1_DNS/Solutions/solution.py @@ -1,2 +1,2 @@ -Answer = "Domain Name System" +Answer = "Domain Name System" print(Answer) \ No newline at end of file diff --git a/introduction_and_environment/introduction_to_programming/1_DNS/Solutions/test_solution.py b/intro_&_enviro/introduction_to_programming/1_DNS/Solutions/test_solution.py similarity index 93% rename from introduction_and_environment/introduction_to_programming/1_DNS/Solutions/test_solution.py rename to intro_&_enviro/introduction_to_programming/1_DNS/Solutions/test_solution.py index b9a42c76..178089d9 100644 --- a/introduction_and_environment/introduction_to_programming/1_DNS/Solutions/test_solution.py +++ b/intro_&_enviro/introduction_to_programming/1_DNS/Solutions/test_solution.py @@ -1,16 +1,16 @@ -import pytest - -ret_val= None - -def g(result): - global ret_val - ret_val = result - -def test_solution(monkeypatch): - monkeypatch.setattr('builtins.print',g) - - import solution - - assert ret_val == "Domain Name System" - - +import pytest + +ret_val= None + +def g(result): + global ret_val + ret_val = result + +def test_solution(monkeypatch): + monkeypatch.setattr('builtins.print',g) + + import solution + + assert ret_val == "Domain Name System" + + diff --git a/introduction_and_environment/introduction_to_programming/1_architecture/README.md b/intro_&_enviro/introduction_to_programming/1_architecture/README.md similarity index 94% rename from introduction_and_environment/introduction_to_programming/1_architecture/README.md rename to intro_&_enviro/introduction_to_programming/1_architecture/README.md index 80d764bf..747c4f32 100644 --- a/introduction_and_environment/introduction_to_programming/1_architecture/README.md +++ b/intro_&_enviro/introduction_to_programming/1_architecture/README.md @@ -1,18 +1,18 @@ -# Architecture - -## Motivation - - -## Problem Description -The basic architecture of computer was developed by - -a. John Von Neumann -b. Charles Babbage -c. Blaise Pascal -d. Garden Moore - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Architecture + +## Motivation + + +## Problem Description +The basic architecture of computer was developed by + +a. John Von Neumann +b. Charles Babbage +c. Blaise Pascal +d. Garden Moore + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/introduction_to_programming/1_architecture/Solutions/solution.py b/intro_&_enviro/introduction_to_programming/1_architecture/Solutions/solution.py similarity index 97% rename from introduction_and_environment/introduction_to_programming/1_architecture/Solutions/solution.py rename to intro_&_enviro/introduction_to_programming/1_architecture/Solutions/solution.py index 22fbf950..b14cf8d5 100644 --- a/introduction_and_environment/introduction_to_programming/1_architecture/Solutions/solution.py +++ b/intro_&_enviro/introduction_to_programming/1_architecture/Solutions/solution.py @@ -1,2 +1,2 @@ -Answer = "a.John Von Neuman" +Answer = "a.John Von Neuman" print(Answer) \ No newline at end of file diff --git a/introduction_and_environment/introduction_to_programming/1_architecture/Solutions/test_solution.py b/intro_&_enviro/introduction_to_programming/1_architecture/Solutions/test_solution.py similarity index 94% rename from introduction_and_environment/introduction_to_programming/1_architecture/Solutions/test_solution.py rename to intro_&_enviro/introduction_to_programming/1_architecture/Solutions/test_solution.py index c82012e8..a5e9c4bd 100644 --- a/introduction_and_environment/introduction_to_programming/1_architecture/Solutions/test_solution.py +++ b/intro_&_enviro/introduction_to_programming/1_architecture/Solutions/test_solution.py @@ -1,15 +1,15 @@ -import pytest - -ret_val= None - -def g(result): - global ret_val - ret_val = result - -def test_solution(monkeypatch): - monkeypatch.setattr('builtins.print',g) - - import solution - assert ret_val == "a.John Von Neuman" - - +import pytest + +ret_val= None + +def g(result): + global ret_val + ret_val = result + +def test_solution(monkeypatch): + monkeypatch.setattr('builtins.print',g) + + import solution + assert ret_val == "a.John Von Neuman" + + diff --git a/introduction_and_environment/introduction_to_programming/1_bytes/README.md b/intro_&_enviro/introduction_to_programming/1_bytes/README.md similarity index 94% rename from introduction_and_environment/introduction_to_programming/1_bytes/README.md rename to intro_&_enviro/introduction_to_programming/1_bytes/README.md index 1a0e678c..1fd52db7 100644 --- a/introduction_and_environment/introduction_to_programming/1_bytes/README.md +++ b/intro_&_enviro/introduction_to_programming/1_bytes/README.md @@ -1,18 +1,18 @@ -# Bytes - -## Motivation - - -## Problem Description -Which of the following is the largest unit of storage - -a.Gigabyte -b.Kilobyte -c.Megabyte -d.Terabyte - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Bytes + +## Motivation + + +## Problem Description +Which of the following is the largest unit of storage + +a.Gigabyte +b.Kilobyte +c.Megabyte +d.Terabyte + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/introduction_to_programming/1_bytes/Solutions/solution.py b/intro_&_enviro/introduction_to_programming/1_bytes/Solutions/solution.py similarity index 97% rename from introduction_and_environment/introduction_to_programming/1_bytes/Solutions/solution.py rename to intro_&_enviro/introduction_to_programming/1_bytes/Solutions/solution.py index 5d1995cd..13da983f 100644 --- a/introduction_and_environment/introduction_to_programming/1_bytes/Solutions/solution.py +++ b/intro_&_enviro/introduction_to_programming/1_bytes/Solutions/solution.py @@ -1,2 +1,2 @@ -Answer = "Gigabyte" +Answer = "Gigabyte" print(Answer) \ No newline at end of file diff --git a/introduction_and_environment/introduction_to_programming/1_bytes/Solutions/test_solution.py b/intro_&_enviro/introduction_to_programming/1_bytes/Solutions/test_solution.py similarity index 93% rename from introduction_and_environment/introduction_to_programming/1_bytes/Solutions/test_solution.py rename to intro_&_enviro/introduction_to_programming/1_bytes/Solutions/test_solution.py index 657bd1c8..5a0f817b 100644 --- a/introduction_and_environment/introduction_to_programming/1_bytes/Solutions/test_solution.py +++ b/intro_&_enviro/introduction_to_programming/1_bytes/Solutions/test_solution.py @@ -1,16 +1,16 @@ -import pytest - -ret_val= None - -def g(result): - global ret_val - ret_val = result - -def test_solution(monkeypatch): - monkeypatch.setattr('builtins.print',g) - - import solution - - assert ret_val == "Gigabyte" - - +import pytest + +ret_val= None + +def g(result): + global ret_val + ret_val = result + +def test_solution(monkeypatch): + monkeypatch.setattr('builtins.print',g) + + import solution + + assert ret_val == "Gigabyte" + + diff --git a/introduction_and_environment/introduction_to_programming/1_languages/README.md b/intro_&_enviro/introduction_to_programming/1_languages/README.md similarity index 94% rename from introduction_and_environment/introduction_to_programming/1_languages/README.md rename to intro_&_enviro/introduction_to_programming/1_languages/README.md index 833283df..19caecd3 100644 --- a/introduction_and_environment/introduction_to_programming/1_languages/README.md +++ b/intro_&_enviro/introduction_to_programming/1_languages/README.md @@ -1,18 +1,18 @@ -# Languages - -## Motivation - - -## Problem Description -A program that can execute high-level language programs. - -a) Compiler -b) Interpreter -c) Sensor -d) Circuitry - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Languages + +## Motivation + + +## Problem Description +A program that can execute high-level language programs. + +a) Compiler +b) Interpreter +c) Sensor +d) Circuitry + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/introduction_to_programming/1_languages/Solutions/solution.py b/intro_&_enviro/introduction_to_programming/1_languages/Solutions/solution.py similarity index 94% rename from introduction_and_environment/introduction_to_programming/1_languages/Solutions/solution.py rename to intro_&_enviro/introduction_to_programming/1_languages/Solutions/solution.py index ca198c24..aee07c54 100644 --- a/introduction_and_environment/introduction_to_programming/1_languages/Solutions/solution.py +++ b/intro_&_enviro/introduction_to_programming/1_languages/Solutions/solution.py @@ -1,4 +1,4 @@ -def Answer(): - return "Interpreter" - +def Answer(): + return "Interpreter" + print(Answer()) \ No newline at end of file diff --git a/introduction_and_environment/introduction_to_programming/1_languages/Solutions/test_solution.py b/intro_&_enviro/introduction_to_programming/1_languages/Solutions/test_solution.py similarity index 93% rename from introduction_and_environment/introduction_to_programming/1_languages/Solutions/test_solution.py rename to intro_&_enviro/introduction_to_programming/1_languages/Solutions/test_solution.py index dab62de8..e4c577a0 100644 --- a/introduction_and_environment/introduction_to_programming/1_languages/Solutions/test_solution.py +++ b/intro_&_enviro/introduction_to_programming/1_languages/Solutions/test_solution.py @@ -1,16 +1,16 @@ -import pytest - -ret_val= None - -def g(result): - global ret_val - ret_val = result - -def test_solution(monkeypatch): - monkeypatch.setattr('builtins.print',g) - - import solution - - assert ret_val == "Interpreter" - - +import pytest + +ret_val= None + +def g(result): + global ret_val + ret_val = result + +def test_solution(monkeypatch): + monkeypatch.setattr('builtins.print',g) + + import solution + + assert ret_val == "Interpreter" + + diff --git a/introduction_and_environment/introduction_to_programming/2_ASCII/README.md b/intro_&_enviro/introduction_to_programming/2_ASCII/README.md similarity index 94% rename from introduction_and_environment/introduction_to_programming/2_ASCII/README.md rename to intro_&_enviro/introduction_to_programming/2_ASCII/README.md index 85d1f914..48a235b0 100644 --- a/introduction_and_environment/introduction_to_programming/2_ASCII/README.md +++ b/intro_&_enviro/introduction_to_programming/2_ASCII/README.md @@ -1,18 +1,18 @@ -# ASCII - -## Motivation - - -## Problem Description -Each byte of character is stored as its ASCII value in _______ - -a) Hexadecimal -b) Binary -c) Octal -d) Decimal - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# ASCII + +## Motivation + + +## Problem Description +Each byte of character is stored as its ASCII value in _______ + +a) Hexadecimal +b) Binary +c) Octal +d) Decimal + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/introduction_to_programming/2_ASCII/Solutions/solution.py b/intro_&_enviro/introduction_to_programming/2_ASCII/Solutions/solution.py similarity index 94% rename from introduction_and_environment/introduction_to_programming/2_ASCII/Solutions/solution.py rename to intro_&_enviro/introduction_to_programming/2_ASCII/Solutions/solution.py index 6b1aa844..b076a1ce 100644 --- a/introduction_and_environment/introduction_to_programming/2_ASCII/Solutions/solution.py +++ b/intro_&_enviro/introduction_to_programming/2_ASCII/Solutions/solution.py @@ -1,4 +1,4 @@ -def Answer(): - return "Boolean" - +def Answer(): + return "Boolean" + print(Answer()) \ No newline at end of file diff --git a/introduction_and_environment/introduction_to_programming/2_ASCII/Solutions/test_solution.py b/intro_&_enviro/introduction_to_programming/2_ASCII/Solutions/test_solution.py similarity index 93% rename from introduction_and_environment/introduction_to_programming/2_ASCII/Solutions/test_solution.py rename to intro_&_enviro/introduction_to_programming/2_ASCII/Solutions/test_solution.py index a51c7cc9..a4a4d788 100644 --- a/introduction_and_environment/introduction_to_programming/2_ASCII/Solutions/test_solution.py +++ b/intro_&_enviro/introduction_to_programming/2_ASCII/Solutions/test_solution.py @@ -1,16 +1,16 @@ -import pytest - -ret_val= None - -def g(result): - global ret_val - ret_val = result - -def test_solution(monkeypatch): - monkeypatch.setattr('builtins.print',g) - - import solution - - assert ret_val == "Boolean" - - +import pytest + +ret_val= None + +def g(result): + global ret_val + ret_val = result + +def test_solution(monkeypatch): + monkeypatch.setattr('builtins.print',g) + + import solution + + assert ret_val == "Boolean" + + diff --git a/introduction_and_environment/introduction_to_programming/2_operators/README.md b/intro_&_enviro/introduction_to_programming/2_operators/README.md similarity index 94% rename from introduction_and_environment/introduction_to_programming/2_operators/README.md rename to intro_&_enviro/introduction_to_programming/2_operators/README.md index 0df46257..e51b850f 100644 --- a/introduction_and_environment/introduction_to_programming/2_operators/README.md +++ b/intro_&_enviro/introduction_to_programming/2_operators/README.md @@ -1,18 +1,18 @@ -# Operators - -## Motivation - - -## Problem Description -AND, OR and NOT are logical operators. What data type is expected for their operands? - - a) Integer - b) Boolean - c) Decimal - d) Character - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Operators + +## Motivation + + +## Problem Description +AND, OR and NOT are logical operators. What data type is expected for their operands? + + a) Integer + b) Boolean + c) Decimal + d) Character + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/introduction_to_programming/2_operators/Solutions/solution.py b/intro_&_enviro/introduction_to_programming/2_operators/Solutions/solution.py similarity index 94% rename from introduction_and_environment/introduction_to_programming/2_operators/Solutions/solution.py rename to intro_&_enviro/introduction_to_programming/2_operators/Solutions/solution.py index 1a79c7f8..56a3f351 100644 --- a/introduction_and_environment/introduction_to_programming/2_operators/Solutions/solution.py +++ b/intro_&_enviro/introduction_to_programming/2_operators/Solutions/solution.py @@ -1,4 +1,4 @@ -def Answer(): - return "Hexadecimal" - +def Answer(): + return "Hexadecimal" + print(Answer()) \ No newline at end of file diff --git a/introduction_and_environment/introduction_to_programming/2_operators/Solutions/test_solution.py b/intro_&_enviro/introduction_to_programming/2_operators/Solutions/test_solution.py similarity index 93% rename from introduction_and_environment/introduction_to_programming/2_operators/Solutions/test_solution.py rename to intro_&_enviro/introduction_to_programming/2_operators/Solutions/test_solution.py index 49c4fdee..0d0bbbc3 100644 --- a/introduction_and_environment/introduction_to_programming/2_operators/Solutions/test_solution.py +++ b/intro_&_enviro/introduction_to_programming/2_operators/Solutions/test_solution.py @@ -1,16 +1,16 @@ -import pytest - -ret_val= None - -def g(result): - global ret_val - ret_val = result - -def test_solution(monkeypatch): - monkeypatch.setattr('builtins.print',g) - - import solution - - assert ret_val == "Hexadecimal" - - +import pytest + +ret_val= None + +def g(result): + global ret_val + ret_val = result + +def test_solution(monkeypatch): + monkeypatch.setattr('builtins.print',g) + + import solution + + assert ret_val == "Hexadecimal" + + diff --git a/introduction_and_environment/introduction_to_programming/3_bitwise_operators_1/README.md b/intro_&_enviro/introduction_to_programming/3_bitwise_operators_1/README.md similarity index 95% rename from introduction_and_environment/introduction_to_programming/3_bitwise_operators_1/README.md rename to intro_&_enviro/introduction_to_programming/3_bitwise_operators_1/README.md index 866bdcdb..0b996449 100644 --- a/introduction_and_environment/introduction_to_programming/3_bitwise_operators_1/README.md +++ b/intro_&_enviro/introduction_to_programming/3_bitwise_operators_1/README.md @@ -1,19 +1,19 @@ -# Bitwise Operators 1 - -## Motivation - - -## Problem Description -Given two binary values x and y, compute the following bitwise operations on that - -1.Bitwise AND (&) -2.Bitwise OR (|) -3.Bitwise NOT (~) - -Return the solutions in objects `Answer_and`,`Answer_or` and `Answer_not` respectively and print the same. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Bitwise Operators 1 + +## Motivation + + +## Problem Description +Given two binary values x and y, compute the following bitwise operations on that + +1.Bitwise AND (&) +2.Bitwise OR (|) +3.Bitwise NOT (~) + +Return the solutions in objects `Answer_and`,`Answer_or` and `Answer_not` respectively and print the same. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/introduction_to_programming/3_bitwise_operators_1/Solutions/solution.py b/intro_&_enviro/introduction_to_programming/3_bitwise_operators_1/Solutions/solution.py similarity index 96% rename from introduction_and_environment/introduction_to_programming/3_bitwise_operators_1/Solutions/solution.py rename to intro_&_enviro/introduction_to_programming/3_bitwise_operators_1/Solutions/solution.py index 88f234a1..b3d2529b 100644 --- a/introduction_and_environment/introduction_to_programming/3_bitwise_operators_1/Solutions/solution.py +++ b/intro_&_enviro/introduction_to_programming/3_bitwise_operators_1/Solutions/solution.py @@ -1,6 +1,6 @@ -a = 0b0110 -b = 0b1000 -Answer_and = bin(a&b) -Answer_or = bin(a|b) -Answer_not = bin(~b) +a = 0b0110 +b = 0b1000 +Answer_and = bin(a&b) +Answer_or = bin(a|b) +Answer_not = bin(~b) print(Answer_and,Answer_or,Answer_not) \ No newline at end of file diff --git a/introduction_and_environment/introduction_to_programming/3_bitwise_operators_1/Solutions/test_solution.py b/intro_&_enviro/introduction_to_programming/3_bitwise_operators_1/Solutions/test_solution.py similarity index 93% rename from introduction_and_environment/introduction_to_programming/3_bitwise_operators_1/Solutions/test_solution.py rename to intro_&_enviro/introduction_to_programming/3_bitwise_operators_1/Solutions/test_solution.py index d179f969..5e964dd7 100644 --- a/introduction_and_environment/introduction_to_programming/3_bitwise_operators_1/Solutions/test_solution.py +++ b/intro_&_enviro/introduction_to_programming/3_bitwise_operators_1/Solutions/test_solution.py @@ -1,27 +1,27 @@ -import pytest - -ret_val_1= None -ret_val_2= None -ret_val_3= None - - -def g(x,x1,x2): - global ret_val_1 - global ret_val_2 - global ret_val_3 - ret_val_1 = x - ret_val_2 = x1 - ret_val_3 = x2 - -def test_solution(monkeypatch): - monkeypatch.setattr('builtins.print',g) - - import solution - - assert ret_val_1 == bin(0b0) - assert ret_val_2 == bin(0b1110) - assert ret_val_3 == bin(-0b1001) - - - - +import pytest + +ret_val_1= None +ret_val_2= None +ret_val_3= None + + +def g(x,x1,x2): + global ret_val_1 + global ret_val_2 + global ret_val_3 + ret_val_1 = x + ret_val_2 = x1 + ret_val_3 = x2 + +def test_solution(monkeypatch): + monkeypatch.setattr('builtins.print',g) + + import solution + + assert ret_val_1 == bin(0b0) + assert ret_val_2 == bin(0b1110) + assert ret_val_3 == bin(-0b1001) + + + + diff --git a/introduction_and_environment/introduction_to_programming/3_bitwise_operators_2/README.md b/intro_&_enviro/introduction_to_programming/3_bitwise_operators_2/README.md similarity index 96% rename from introduction_and_environment/introduction_to_programming/3_bitwise_operators_2/README.md rename to intro_&_enviro/introduction_to_programming/3_bitwise_operators_2/README.md index 3b9bf34e..732f04dd 100644 --- a/introduction_and_environment/introduction_to_programming/3_bitwise_operators_2/README.md +++ b/intro_&_enviro/introduction_to_programming/3_bitwise_operators_2/README.md @@ -1,19 +1,19 @@ -# Bitwise Operators 2 - -## Motivation - - -## Problem Description -Given two binary values x and y, compute the following bitwise operations on that - -1.Bitwise XOR (^) -2.Bitwise right shift (>>) -3.Bitwise left Shift (<<) - -Return the solutions in objects `Answer_Xor`,`Answer_right_shift` and `Answer_left_shift` respectively and print the same. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Bitwise Operators 2 + +## Motivation + + +## Problem Description +Given two binary values x and y, compute the following bitwise operations on that + +1.Bitwise XOR (^) +2.Bitwise right shift (>>) +3.Bitwise left Shift (<<) + +Return the solutions in objects `Answer_Xor`,`Answer_right_shift` and `Answer_left_shift` respectively and print the same. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/introduction_to_programming/3_bitwise_operators_2/Solutions/solution.py b/intro_&_enviro/introduction_to_programming/3_bitwise_operators_2/Solutions/solution.py similarity index 96% rename from introduction_and_environment/introduction_to_programming/3_bitwise_operators_2/Solutions/solution.py rename to intro_&_enviro/introduction_to_programming/3_bitwise_operators_2/Solutions/solution.py index 81c38dcd..ae870711 100644 --- a/introduction_and_environment/introduction_to_programming/3_bitwise_operators_2/Solutions/solution.py +++ b/intro_&_enviro/introduction_to_programming/3_bitwise_operators_2/Solutions/solution.py @@ -1,6 +1,6 @@ -a = 0b0110 -b = 0b1000 -Answer_Xor = bin(a^b) -Answer_right_shift = bin(a>>1) -Answer_left_shift = bin(a<<1) +a = 0b0110 +b = 0b1000 +Answer_Xor = bin(a^b) +Answer_right_shift = bin(a>>1) +Answer_left_shift = bin(a<<1) print(Answer_Xor,Answer_right_shift,Answer_left_shift) \ No newline at end of file diff --git a/introduction_and_environment/introduction_to_programming/3_bitwise_operators_2/Solutions/test_solution.py b/intro_&_enviro/introduction_to_programming/3_bitwise_operators_2/Solutions/test_solution.py similarity index 94% rename from introduction_and_environment/introduction_to_programming/3_bitwise_operators_2/Solutions/test_solution.py rename to intro_&_enviro/introduction_to_programming/3_bitwise_operators_2/Solutions/test_solution.py index 105aa907..c41a6dcd 100644 --- a/introduction_and_environment/introduction_to_programming/3_bitwise_operators_2/Solutions/test_solution.py +++ b/intro_&_enviro/introduction_to_programming/3_bitwise_operators_2/Solutions/test_solution.py @@ -1,26 +1,26 @@ -import pytest - -ret_val_1= None -ret_val_2= None -ret_val_3= None - -def g(x,x1,x2): - global ret_val_1 - global ret_val_2 - global ret_val_3 - ret_val_1 = x - ret_val_2 = x1 - ret_val_3 = x2 - -def test_solution(monkeypatch): - monkeypatch.setattr('builtins.print',g) - - import solution as s - - assert ret_val_1 == bin(0b1110) - assert ret_val_2 == bin(0b11) - assert ret_val_3 == bin(0b1100) - - - - +import pytest + +ret_val_1= None +ret_val_2= None +ret_val_3= None + +def g(x,x1,x2): + global ret_val_1 + global ret_val_2 + global ret_val_3 + ret_val_1 = x + ret_val_2 = x1 + ret_val_3 = x2 + +def test_solution(monkeypatch): + monkeypatch.setattr('builtins.print',g) + + import solution as s + + assert ret_val_1 == bin(0b1110) + assert ret_val_2 == bin(0b11) + assert ret_val_3 == bin(0b1100) + + + + diff --git a/introduction_and_environment/introduction_to_programming/3_logical_operators_1/README.md b/intro_&_enviro/introduction_to_programming/3_logical_operators_1/README.md similarity index 96% rename from introduction_and_environment/introduction_to_programming/3_logical_operators_1/README.md rename to intro_&_enviro/introduction_to_programming/3_logical_operators_1/README.md index 5b17b30c..40589a8a 100644 --- a/introduction_and_environment/introduction_to_programming/3_logical_operators_1/README.md +++ b/intro_&_enviro/introduction_to_programming/3_logical_operators_1/README.md @@ -1,13 +1,13 @@ -# Logical Operators 1 - -## Motivation - - -## Problem Description -Given `x`=`1` & `y`=`2` two values, apply logical operator `and`, by evaluating both the variables to `2` and return the boolean value. store the output in object `Answer`.print `Answer`. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Logical Operators 1 + +## Motivation + + +## Problem Description +Given `x`=`1` & `y`=`2` two values, apply logical operator `and`, by evaluating both the variables to `2` and return the boolean value. store the output in object `Answer`.print `Answer`. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/introduction_to_programming/3_logical_operators_1/Solutions/solution.py b/intro_&_enviro/introduction_to_programming/3_logical_operators_1/Solutions/solution.py similarity index 93% rename from introduction_and_environment/introduction_to_programming/3_logical_operators_1/Solutions/solution.py rename to intro_&_enviro/introduction_to_programming/3_logical_operators_1/Solutions/solution.py index 19cf0973..6b9f0d99 100644 --- a/introduction_and_environment/introduction_to_programming/3_logical_operators_1/Solutions/solution.py +++ b/intro_&_enviro/introduction_to_programming/3_logical_operators_1/Solutions/solution.py @@ -1,7 +1,7 @@ -a = 1 -b = 2 -if a == 2 and b == 2: - Answer = True -else: - Answer = False +a = 1 +b = 2 +if a == 2 and b == 2: + Answer = True +else: + Answer = False print(Answer) \ No newline at end of file diff --git a/introduction_and_environment/introduction_to_programming/3_logical_operators_1/Solutions/test_solution.py b/intro_&_enviro/introduction_to_programming/3_logical_operators_1/Solutions/test_solution.py similarity index 92% rename from introduction_and_environment/introduction_to_programming/3_logical_operators_1/Solutions/test_solution.py rename to intro_&_enviro/introduction_to_programming/3_logical_operators_1/Solutions/test_solution.py index 42cb8a6e..5613f4f9 100644 --- a/introduction_and_environment/introduction_to_programming/3_logical_operators_1/Solutions/test_solution.py +++ b/intro_&_enviro/introduction_to_programming/3_logical_operators_1/Solutions/test_solution.py @@ -1,18 +1,18 @@ -import pytest - -ret_val_1= None - -def g(x): - global ret_val_1 - ret_val_1 = x - -def test_solution(monkeypatch): - monkeypatch.setattr('builtins.print',g) - - import solution as s - - assert ret_val_1 == False - - - - +import pytest + +ret_val_1= None + +def g(x): + global ret_val_1 + ret_val_1 = x + +def test_solution(monkeypatch): + monkeypatch.setattr('builtins.print',g) + + import solution as s + + assert ret_val_1 == False + + + + diff --git a/introduction_and_environment/introduction_to_programming/3_logical_operators_2/README.md b/intro_&_enviro/introduction_to_programming/3_logical_operators_2/README.md similarity index 96% rename from introduction_and_environment/introduction_to_programming/3_logical_operators_2/README.md rename to intro_&_enviro/introduction_to_programming/3_logical_operators_2/README.md index ac9817d3..366aaecc 100644 --- a/introduction_and_environment/introduction_to_programming/3_logical_operators_2/README.md +++ b/intro_&_enviro/introduction_to_programming/3_logical_operators_2/README.md @@ -1,13 +1,13 @@ -# Logical Operators 2 - -## Motivation - - -## Problem Description -Given `x`=`1` & `y`=`2` two values, apply logical operator `and`, by evaluating both the variables to `2` and return the boolean value. store the output in object `Answer`.print `Answer`. - -## Testing -* done - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Logical Operators 2 + +## Motivation + + +## Problem Description +Given `x`=`1` & `y`=`2` two values, apply logical operator `and`, by evaluating both the variables to `2` and return the boolean value. store the output in object `Answer`.print `Answer`. + +## Testing +* done + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/introduction_to_programming/3_logical_operators_2/Solutions/solution.py b/intro_&_enviro/introduction_to_programming/3_logical_operators_2/Solutions/solution.py similarity index 93% rename from introduction_and_environment/introduction_to_programming/3_logical_operators_2/Solutions/solution.py rename to intro_&_enviro/introduction_to_programming/3_logical_operators_2/Solutions/solution.py index 48376291..086554d0 100644 --- a/introduction_and_environment/introduction_to_programming/3_logical_operators_2/Solutions/solution.py +++ b/intro_&_enviro/introduction_to_programming/3_logical_operators_2/Solutions/solution.py @@ -1,7 +1,7 @@ -a = 1 -b = 2 -if a == 2 or b == 2: - Answer = True -else: - Answer = False +a = 1 +b = 2 +if a == 2 or b == 2: + Answer = True +else: + Answer = False print(Answer) \ No newline at end of file diff --git a/introduction_and_environment/introduction_to_programming/3_logical_operators_2/Solutions/test_solution.py b/intro_&_enviro/introduction_to_programming/3_logical_operators_2/Solutions/test_solution.py similarity index 92% rename from introduction_and_environment/introduction_to_programming/3_logical_operators_2/Solutions/test_solution.py rename to intro_&_enviro/introduction_to_programming/3_logical_operators_2/Solutions/test_solution.py index fc8bd689..d8833459 100644 --- a/introduction_and_environment/introduction_to_programming/3_logical_operators_2/Solutions/test_solution.py +++ b/intro_&_enviro/introduction_to_programming/3_logical_operators_2/Solutions/test_solution.py @@ -1,18 +1,18 @@ -import pytest - -ret_val_1= None - -def g(x): - global ret_val_1 - ret_val_1 = x - -def test_solution(monkeypatch): - monkeypatch.setattr('builtins.print',g) - - import solution as s - - assert ret_val_1 == True - - - - +import pytest + +ret_val_1= None + +def g(x): + global ret_val_1 + ret_val_1 = x + +def test_solution(monkeypatch): + monkeypatch.setattr('builtins.print',g) + + import solution as s + + assert ret_val_1 == True + + + + diff --git a/introduction_and_environment/introduction_to_programming/README.md b/intro_&_enviro/introduction_to_programming/README.md similarity index 99% rename from introduction_and_environment/introduction_to_programming/README.md rename to intro_&_enviro/introduction_to_programming/README.md index 1eaff513..98f90cb1 100644 --- a/introduction_and_environment/introduction_to_programming/README.md +++ b/intro_&_enviro/introduction_to_programming/README.md @@ -1,15 +1,15 @@ -# Introduction To Programming Exercises - - -| Exercise ID | Exercise | -|:-----------:|:--------:| -| easy_e1 | [Architecture](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/1_architecture) | -| easy_e2 | [DNS](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/1_DNS) | -| easy_e3 | [Bytes](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/1_bytes) | -| easy_e4 | [Languages](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/1_languages) | -| medium_e1 | [ASCII](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/2_ASCII) | -| medium_e2 | [Operators](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/2_operators) | -| hard_e1 | [Logical Operators 1](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/3_logical_operators_1) | -| hard_e2 | [Logical Operators 2](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/3_logical_operators_2) | -| hard_e3 | [Bitwise Operators 1](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/3_bitwise_operators_1) | -| hard_e4 | [Bitwise Operators 2](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/3_bitwise_operators_2) | +# Introduction To Programming Exercises + + +| Exercise ID | Exercise | +|:-----------:|:--------:| +| easy_e1 | [Architecture](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/1_architecture) | +| easy_e2 | [DNS](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/1_DNS) | +| easy_e3 | [Bytes](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/1_bytes) | +| easy_e4 | [Languages](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/1_languages) | +| medium_e1 | [ASCII](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/2_ASCII) | +| medium_e2 | [Operators](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/2_operators) | +| hard_e1 | [Logical Operators 1](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/3_logical_operators_1) | +| hard_e2 | [Logical Operators 2](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/3_logical_operators_2) | +| hard_e3 | [Bitwise Operators 1](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/3_bitwise_operators_1) | +| hard_e4 | [Bitwise Operators 2](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/introduction_to_programming/3_bitwise_operators_2) | diff --git a/intro_&_enviro/unix_and_bash/1_basic_commands/README.md b/intro_&_enviro/unix_and_bash/1_basic_commands/README.md new file mode 100644 index 00000000..c75df63f --- /dev/null +++ b/intro_&_enviro/unix_and_bash/1_basic_commands/README.md @@ -0,0 +1,40 @@ +# Command Basics + +## Problem Description +The list below contains a number of variable names, as well as a text description of many different **bash** commands. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. + +Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! + +For example: +Variable: `ONE` +Description: command used when you remember the name of a **bash** command, but forget what it does + +In *solution.py* you would write: +```python +ONE = 'man' +``` + +Variable: `TWO` +Description: View the contents of a directory + +Variable: `THREE` +Description: Create a new directory (ignore any necessary arguments or options) + +Variable: `FOUR` +Description: Create an empty file + +Variable: `FIVE` +Description: Create a copy of a file, or with an option, copy the contents of a directory + +Variable: `SIX` +Description: Change the name of a file or directory + +Variable: `SEVEN` +Description: Delete a file, or with an additional option, a directory + + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory diff --git a/intro_&_enviro/unix_and_bash/1_basic_commands/solution/solution.py b/intro_&_enviro/unix_and_bash/1_basic_commands/solution/solution.py new file mode 100644 index 00000000..f68619da --- /dev/null +++ b/intro_&_enviro/unix_and_bash/1_basic_commands/solution/solution.py @@ -0,0 +1,10 @@ +# The first has been completed for you... +ONE = 'man' + +# Assign the correct strings below +TWO = '' +THREE = '' +FOUR = '' +FIVE = '' +SIX = '' +SEVEN = '' diff --git a/intro_&_enviro/unix_and_bash/1_basic_commands/solution/test_solution.py b/intro_&_enviro/unix_and_bash/1_basic_commands/solution/test_solution.py new file mode 100644 index 00000000..a36502a0 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/1_basic_commands/solution/test_solution.py @@ -0,0 +1,14 @@ +import solution +from hashlib import sha1 + +def test_solution(): + def hashed_output(submission): + return sha1(submission.encode()).hexdigest() + + assert hashed_output(solution.ONE) == '8175e3c8753aeb1696959f72ede260ebf3ea14c5' + assert hashed_output(solution.TWO) == 'ebfdec641529d4b59a54e18f8b0e9730f85939fb' + assert hashed_output(solution.THREE) == '90868ffdfa3a8bd99cfa9f642349e60cf84e057a' + assert hashed_output(solution.FOUR) == 'f4d1f0193879cba82d65c5752c4ba5cbb43a7188' + assert hashed_output(solution.FIVE) == '3f81e91d69a8a61ffbf19297eb0791ad54ce5690' + assert hashed_output(solution.SIX) == '362d60cb3f6f8e96c37edac670b7618963233e07' + assert hashed_output(solution.SEVEN) == '5cd7e29c88170aa3f16281e0dbf5772c137f6d8d' diff --git a/intro_&_enviro/unix_and_bash/1_commands_with_options/README.md b/intro_&_enviro/unix_and_bash/1_commands_with_options/README.md new file mode 100644 index 00000000..9674f827 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/1_commands_with_options/README.md @@ -0,0 +1,42 @@ +# Command Basics 2 + +## Problem Description +The list below contains a number of variable names, as well as a text description of many different **bash** commands. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. These are harder than the first few, as they may contain additional arguments to be included with the command name. + +Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! + +For example: +Variable: `ONE` +Description: Command used when you remember the name of a **bash** command named "test", but forget what it does + +In *solution.py* you would write: +```python +ONE = 'man test' +``` + +Variable: `ONE` +Description: Navigate from the current directory to a new directory, named "exercises" + +Variable: `TWO` +Description: View our terminal's current directory location + +Variable: `THREE` +Description: View the *entire* contents of a file named "textfile.txt" in our terminal + +Variable: `FOUR` +Description: View *only* the last 10 lines of a file named "textfile.txt" + +Variable: `FIVE` +Description: View the contents of the current directory, including hidden files + +Variable: `SIX` +Description: View *only* the first 10 lines of a file named "textfile.txt" + +Variable: `SEVEN` +Description: Create a copy of a file, named "stackdata.json" with the name "stockdata.json + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory diff --git a/intro_&_enviro/unix_and_bash/1_commands_with_options/solution/solution.py b/intro_&_enviro/unix_and_bash/1_commands_with_options/solution/solution.py new file mode 100644 index 00000000..de5c55fa --- /dev/null +++ b/intro_&_enviro/unix_and_bash/1_commands_with_options/solution/solution.py @@ -0,0 +1,9 @@ +# Assign the correct strings below + +ONE = '' +TWO = '' +THREE = '' +FOUR = '' +FIVE = '' +SIX = '' +SEVEN = '' diff --git a/intro_&_enviro/unix_and_bash/1_commands_with_options/solution/test_solution.py b/intro_&_enviro/unix_and_bash/1_commands_with_options/solution/test_solution.py new file mode 100644 index 00000000..f248dfd5 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/1_commands_with_options/solution/test_solution.py @@ -0,0 +1,14 @@ +import solution +from hashlib import sha1 + +def test_solution(): + def hashed_output(submission): + return sha1(submission.encode()).hexdigest() + + assert hashed_output(solution.ONE) == '8f7096f862f1c01437d435b1440612fc5907d76c' + assert hashed_output(solution.TWO) == '37fa265330ad83eaa879efb1e2db6380896cf639' + assert hashed_output(solution.THREE) == 'aa2ba3db8235609f178bac463e31eb01c1a9e711' + assert hashed_output(solution.FOUR) == 'e52fb413040572fbc243c74e29760dd3c9867aea' + assert hashed_output(solution.FIVE) == 'fda17aa65051cb574d5f9f1cc4c7f3ddbc931735' + assert hashed_output(solution.SIX) == '3441d7e6e51f18f214ae7f2ca9c6a87fe14deea8' + assert hashed_output(solution.SEVEN) == 'e120eb80c4d1bc2976a2176f8dd83d0a795725b6' diff --git a/intro_&_enviro/unix_and_bash/1_commands_with_options_2/README.md b/intro_&_enviro/unix_and_bash/1_commands_with_options_2/README.md new file mode 100644 index 00000000..0ac8900a --- /dev/null +++ b/intro_&_enviro/unix_and_bash/1_commands_with_options_2/README.md @@ -0,0 +1,39 @@ +# Command Basics 3 + +## Problem Description +The list below contains a number of variable names, as well as a text description of many different **bash** commands. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. These are harder than the first few, as they may contain additional arguments to be included with the command name. + +Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! + +For example: +Variable: `ONE` +Description: Command used when you remember the name of a **bash** command named "test", but forget what it does + +In *solution.py* you would write: +```python +ONE = 'man test' +``` + +Variable: `ONE` +Description: Search the contents of a file named "book.txt" for occurrences of the pattern "elephant" + +Variable: `TWO` +Description: Move a file named "notes.txt" from the current directory to a directory named "newdir" + +Variable: `THREE` +Description: Search all files in a directory named "testdir" for the pattern "string" + +Variable: `FOUR` +Description: Delete an empty directory named "empty" + +Variable: `FIVE` +Description: Navigate to our user's home directory (regardless of name) + +Variable: `SIX` +Description: Delete a non-empty directory, named "Downloads", as well as all of its contents + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory diff --git a/intro_&_enviro/unix_and_bash/1_commands_with_options_2/solution/solution.py b/intro_&_enviro/unix_and_bash/1_commands_with_options_2/solution/solution.py new file mode 100644 index 00000000..de5c55fa --- /dev/null +++ b/intro_&_enviro/unix_and_bash/1_commands_with_options_2/solution/solution.py @@ -0,0 +1,9 @@ +# Assign the correct strings below + +ONE = '' +TWO = '' +THREE = '' +FOUR = '' +FIVE = '' +SIX = '' +SEVEN = '' diff --git a/intro_&_enviro/unix_and_bash/1_commands_with_options_2/solution/test_solution.py b/intro_&_enviro/unix_and_bash/1_commands_with_options_2/solution/test_solution.py new file mode 100644 index 00000000..99154d43 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/1_commands_with_options_2/solution/test_solution.py @@ -0,0 +1,13 @@ +import solution +from hashlib import sha1 + +def test_solution(): + def hashed_output(submission): + return sha1(submission.encode()).hexdigest() + + assert hashed_output(solution.ONE) == '1efc27c5f639a389de478c3d2572063bf0b303f0' + assert hashed_output(solution.TWO) == '649b0028d6ad29d4b0099e6cd227551c19e75c68' + assert hashed_output(solution.THREE) == '3c8f2856c8f42eb101b62632788173107a857a88' + assert hashed_output(solution.FOUR) == 'e6e017e01c6c83091049d013bfad653f3fb75d27' + assert hashed_output(solution.FIVE) == '034778198a045c1ed80be271cdd029b76874f6fc' + assert hashed_output(solution.SIX) == '2c98f52bc8dc4272160f7ee35acfff3aa3f63676' diff --git a/intro_&_enviro/unix_and_bash/1_more_commands/README.md b/intro_&_enviro/unix_and_bash/1_more_commands/README.md new file mode 100644 index 00000000..9674f827 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/1_more_commands/README.md @@ -0,0 +1,42 @@ +# Command Basics 2 + +## Problem Description +The list below contains a number of variable names, as well as a text description of many different **bash** commands. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. These are harder than the first few, as they may contain additional arguments to be included with the command name. + +Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! + +For example: +Variable: `ONE` +Description: Command used when you remember the name of a **bash** command named "test", but forget what it does + +In *solution.py* you would write: +```python +ONE = 'man test' +``` + +Variable: `ONE` +Description: Navigate from the current directory to a new directory, named "exercises" + +Variable: `TWO` +Description: View our terminal's current directory location + +Variable: `THREE` +Description: View the *entire* contents of a file named "textfile.txt" in our terminal + +Variable: `FOUR` +Description: View *only* the last 10 lines of a file named "textfile.txt" + +Variable: `FIVE` +Description: View the contents of the current directory, including hidden files + +Variable: `SIX` +Description: View *only* the first 10 lines of a file named "textfile.txt" + +Variable: `SEVEN` +Description: Create a copy of a file, named "stackdata.json" with the name "stockdata.json + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory diff --git a/intro_&_enviro/unix_and_bash/1_more_commands/solution/solution.py b/intro_&_enviro/unix_and_bash/1_more_commands/solution/solution.py new file mode 100644 index 00000000..de5c55fa --- /dev/null +++ b/intro_&_enviro/unix_and_bash/1_more_commands/solution/solution.py @@ -0,0 +1,9 @@ +# Assign the correct strings below + +ONE = '' +TWO = '' +THREE = '' +FOUR = '' +FIVE = '' +SIX = '' +SEVEN = '' diff --git a/intro_&_enviro/unix_and_bash/1_more_commands/solution/test_solution.py b/intro_&_enviro/unix_and_bash/1_more_commands/solution/test_solution.py new file mode 100644 index 00000000..f248dfd5 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/1_more_commands/solution/test_solution.py @@ -0,0 +1,14 @@ +import solution +from hashlib import sha1 + +def test_solution(): + def hashed_output(submission): + return sha1(submission.encode()).hexdigest() + + assert hashed_output(solution.ONE) == '8f7096f862f1c01437d435b1440612fc5907d76c' + assert hashed_output(solution.TWO) == '37fa265330ad83eaa879efb1e2db6380896cf639' + assert hashed_output(solution.THREE) == 'aa2ba3db8235609f178bac463e31eb01c1a9e711' + assert hashed_output(solution.FOUR) == 'e52fb413040572fbc243c74e29760dd3c9867aea' + assert hashed_output(solution.FIVE) == 'fda17aa65051cb574d5f9f1cc4c7f3ddbc931735' + assert hashed_output(solution.SIX) == '3441d7e6e51f18f214ae7f2ca9c6a87fe14deea8' + assert hashed_output(solution.SEVEN) == 'e120eb80c4d1bc2976a2176f8dd83d0a795725b6' diff --git a/intro_&_enviro/unix_and_bash/2_bash_commands/README.md b/intro_&_enviro/unix_and_bash/2_bash_commands/README.md new file mode 100644 index 00000000..0ac8900a --- /dev/null +++ b/intro_&_enviro/unix_and_bash/2_bash_commands/README.md @@ -0,0 +1,39 @@ +# Command Basics 3 + +## Problem Description +The list below contains a number of variable names, as well as a text description of many different **bash** commands. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. These are harder than the first few, as they may contain additional arguments to be included with the command name. + +Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! + +For example: +Variable: `ONE` +Description: Command used when you remember the name of a **bash** command named "test", but forget what it does + +In *solution.py* you would write: +```python +ONE = 'man test' +``` + +Variable: `ONE` +Description: Search the contents of a file named "book.txt" for occurrences of the pattern "elephant" + +Variable: `TWO` +Description: Move a file named "notes.txt" from the current directory to a directory named "newdir" + +Variable: `THREE` +Description: Search all files in a directory named "testdir" for the pattern "string" + +Variable: `FOUR` +Description: Delete an empty directory named "empty" + +Variable: `FIVE` +Description: Navigate to our user's home directory (regardless of name) + +Variable: `SIX` +Description: Delete a non-empty directory, named "Downloads", as well as all of its contents + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory diff --git a/intro_&_enviro/unix_and_bash/2_bash_commands/solution/solution.py b/intro_&_enviro/unix_and_bash/2_bash_commands/solution/solution.py new file mode 100644 index 00000000..de5c55fa --- /dev/null +++ b/intro_&_enviro/unix_and_bash/2_bash_commands/solution/solution.py @@ -0,0 +1,9 @@ +# Assign the correct strings below + +ONE = '' +TWO = '' +THREE = '' +FOUR = '' +FIVE = '' +SIX = '' +SEVEN = '' diff --git a/intro_&_enviro/unix_and_bash/2_bash_commands/solution/test_solution.py b/intro_&_enviro/unix_and_bash/2_bash_commands/solution/test_solution.py new file mode 100644 index 00000000..99154d43 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/2_bash_commands/solution/test_solution.py @@ -0,0 +1,13 @@ +import solution +from hashlib import sha1 + +def test_solution(): + def hashed_output(submission): + return sha1(submission.encode()).hexdigest() + + assert hashed_output(solution.ONE) == '1efc27c5f639a389de478c3d2572063bf0b303f0' + assert hashed_output(solution.TWO) == '649b0028d6ad29d4b0099e6cd227551c19e75c68' + assert hashed_output(solution.THREE) == '3c8f2856c8f42eb101b62632788173107a857a88' + assert hashed_output(solution.FOUR) == 'e6e017e01c6c83091049d013bfad653f3fb75d27' + assert hashed_output(solution.FIVE) == '034778198a045c1ed80be271cdd029b76874f6fc' + assert hashed_output(solution.SIX) == '2c98f52bc8dc4272160f7ee35acfff3aa3f63676' diff --git a/intro_&_enviro/unix_and_bash/2_bash_operators/README.md b/intro_&_enviro/unix_and_bash/2_bash_operators/README.md new file mode 100644 index 00000000..793c46cb --- /dev/null +++ b/intro_&_enviro/unix_and_bash/2_bash_operators/README.md @@ -0,0 +1,36 @@ +# Bash Operators + +## Problem Description +The list below contains a number of variable names, as well as a text description of many different **bash** commands and operators that must be used. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. These are harder than the first few, and may need bash operators to pass data between commands or alter execution. + +Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! + +For example: +Variable: `ONE` +Description: Commands to list the contents of a directory, and then search that output for any files ending in ".py" + +In *solution.py* you would write: +```python +ONE = 'ls | grep .py' +``` + +Variable: `ONE` +Description: Commands to create a directory named "testdir" and then navigate into that directory, if creation was successful + +Variable: `TWO` +Description: Commands to view the entire contents of a file named "textfile.txt" and search that output for occurrences of the word "and" + +Variable: `THREE` +Description: Commands to view the contents of the current directory, and then *append* that output to an existing text file named "contents.txt" + +Variable: `FOUR` +Description: Commands to *either* navigate into a directory named "current", or, if that command failed, create the directory (but not bother with navigation afterwards) + +Variable: `FIVE` +Description: Commands to view our command line's current directory path, and then write that output to a *new* file called "current_path.txt" + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory diff --git a/intro_&_enviro/unix_and_bash/2_bash_operators/solution/solution.py b/intro_&_enviro/unix_and_bash/2_bash_operators/solution/solution.py new file mode 100644 index 00000000..16aafb24 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/2_bash_operators/solution/solution.py @@ -0,0 +1,7 @@ + +# Assign the correct strings below +ONE = '' +TWO = '' +THREE = '' +FOUR = '' +FIVE = '' diff --git a/intro_&_enviro/unix_and_bash/2_bash_operators/solution/test_solution.py b/intro_&_enviro/unix_and_bash/2_bash_operators/solution/test_solution.py new file mode 100644 index 00000000..4fb95a29 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/2_bash_operators/solution/test_solution.py @@ -0,0 +1,12 @@ +import solution +from hashlib import sha1 + +def test_solution(): + def hashed_output(submission): + return sha1(submission.encode()).hexdigest() + + assert hashed_output(solution.ONE) == '8d90393573522285c5d58b437885ccbb9a9daced' + assert hashed_output(solution.TWO) == '6862d5dbed79ab65cf70e169232ad10ea4575373' + assert hashed_output(solution.THREE) == 'a0d69d758be9fd8be90f83bb3c51c3539c105bdf' + assert hashed_output(solution.FOUR) == 'e31d24b0d08a712dd0c8155c15259958e43dcd04' + assert hashed_output(solution.FIVE) == 'd07f1559dea4f7fb83c1a2b0c506646542856acb' diff --git a/intro_&_enviro/unix_and_bash/2_intermediate_commands/README.md b/intro_&_enviro/unix_and_bash/2_intermediate_commands/README.md new file mode 100644 index 00000000..793c46cb --- /dev/null +++ b/intro_&_enviro/unix_and_bash/2_intermediate_commands/README.md @@ -0,0 +1,36 @@ +# Bash Operators + +## Problem Description +The list below contains a number of variable names, as well as a text description of many different **bash** commands and operators that must be used. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. These are harder than the first few, and may need bash operators to pass data between commands or alter execution. + +Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! + +For example: +Variable: `ONE` +Description: Commands to list the contents of a directory, and then search that output for any files ending in ".py" + +In *solution.py* you would write: +```python +ONE = 'ls | grep .py' +``` + +Variable: `ONE` +Description: Commands to create a directory named "testdir" and then navigate into that directory, if creation was successful + +Variable: `TWO` +Description: Commands to view the entire contents of a file named "textfile.txt" and search that output for occurrences of the word "and" + +Variable: `THREE` +Description: Commands to view the contents of the current directory, and then *append* that output to an existing text file named "contents.txt" + +Variable: `FOUR` +Description: Commands to *either* navigate into a directory named "current", or, if that command failed, create the directory (but not bother with navigation afterwards) + +Variable: `FIVE` +Description: Commands to view our command line's current directory path, and then write that output to a *new* file called "current_path.txt" + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory diff --git a/intro_&_enviro/unix_and_bash/2_intermediate_commands/solution/solution.py b/intro_&_enviro/unix_and_bash/2_intermediate_commands/solution/solution.py new file mode 100644 index 00000000..16aafb24 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/2_intermediate_commands/solution/solution.py @@ -0,0 +1,7 @@ + +# Assign the correct strings below +ONE = '' +TWO = '' +THREE = '' +FOUR = '' +FIVE = '' diff --git a/intro_&_enviro/unix_and_bash/2_intermediate_commands/solution/test_solution.py b/intro_&_enviro/unix_and_bash/2_intermediate_commands/solution/test_solution.py new file mode 100644 index 00000000..4fb95a29 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/2_intermediate_commands/solution/test_solution.py @@ -0,0 +1,12 @@ +import solution +from hashlib import sha1 + +def test_solution(): + def hashed_output(submission): + return sha1(submission.encode()).hexdigest() + + assert hashed_output(solution.ONE) == '8d90393573522285c5d58b437885ccbb9a9daced' + assert hashed_output(solution.TWO) == '6862d5dbed79ab65cf70e169232ad10ea4575373' + assert hashed_output(solution.THREE) == 'a0d69d758be9fd8be90f83bb3c51c3539c105bdf' + assert hashed_output(solution.FOUR) == 'e31d24b0d08a712dd0c8155c15259958e43dcd04' + assert hashed_output(solution.FIVE) == 'd07f1559dea4f7fb83c1a2b0c506646542856acb' diff --git a/intro_&_enviro/unix_and_bash/3_star_wars/README.md b/intro_&_enviro/unix_and_bash/3_star_wars/README.md new file mode 100644 index 00000000..a5751096 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/3_star_wars/README.md @@ -0,0 +1,49 @@ +# Command Line Workflow: Star Wars + +## Spoilers: Star Wars Episode IV: A New Hope +* This exercise contains spoilers for the 1977 film Star Wars (retitled as "Star Wars: Episode IV: A New Hope). While it has been over four decades, you have been warned. + +## Problem Description +* Navigating your computer through terminal is an extremely important, practically required skill to be a programmer. The following is an assignment where you will make / delete folders and files to help you get used to navigating your terminal and manipulating your files with bash commands. Perform all commands within the *solution* directory (there is no `solution.py` here, you'll be creating all necessary files.) + +### Use bash to perform the following commands, in order: +* Navigate into the "star_wars" folder +* Create a folder called "the_empire" +* Create a folder called "the_rebellion" +* Make the following folders + * "tatooine" + * "millenium_falcon" + * "death_star" + * "x_wing" + * "tie_fighter" +* Make the following text files (.txt) ***Make Sure to have the .txt extension on these files*** + * "luke_skywalker" + * "old_man_ben" + * "han_solo" + * "chewbacca" + * "leia_organa" + * "darth_vader" + * "emperor_palpatine" +* Open the darth_vader text file and add the text "Darth Vader" + * **Bonus points** if you add the text without opening the file +* Move the emperor and darth vader into the folder "the_empire" +* Move "luke_skywalker" and "old_man_ben" to the "tatooine" folder +* Luke has found out old man ben is actually Obi Wan Kenobi. Change the name of "old_man_ben" to "obi_wan_kenobi" +* Now they need to escape tatooine. Move "han_solo" and "chewbacca" into "tatooine" +* While all this is happening the Sith lords are sitting nice and cozy inside their giant metal moon. Move "darth_vader" and "emperor_palpatine" inside the "death_star" +* Back on tatooine the characters get on the fastest ship in the galaxy and take off to save the princess. Move all four files from tatooine into the millenium falcon +* The princess is also on the death star. Move "leia_organa" to the "death_star" +* Our heroes sneak onto the Death Star. Move all the files inside the "millenium_falcon" onto the "death_star" +* They found the princess! but in the process Obi Wan was struck down by Darth Vader. Delete the "obi_wan_kenobi" file +* Our other heroes retreat in anger. Move Luke, Leia, Han, and Chewbacca into the "millenium_falcon" +* Alright the rebels have regrouped and come up with a plan to destroy the death star. Luke gets into an x-wing to use his sweet piloting skills. Move "leia" into the "the_rebellion" directory. Move Luke into the "x_wing" +* Vader, also a legendary pilot, gets into the tie fighter to defend the death star. Move "darth_vader" out of the death_star and into the "tie_fighter" +* Luke uses those sweet farm boy desert skills and fires some torpedos into the core of the death star, destroying it. **CAREFULLY** Delete the folder "death_star" + * Remember that deletion of a directory is a high-stake operation + * **DO NOT** do this without checking your command for correctness + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory. It will use python to make sure your final directory/file structure is correct. + +## Submission +* Submit your answer in the *solution* subdirectory in this directory. Your "answer" will be the structure of the folders/files you created at the end of the exercise diff --git a/intro_&_enviro/unix_and_bash/3_star_wars/solution/test_solution.py b/intro_&_enviro/unix_and_bash/3_star_wars/solution/test_solution.py new file mode 100644 index 00000000..130ce8c9 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/3_star_wars/solution/test_solution.py @@ -0,0 +1,17 @@ +import os + +def test_solution(): + solution = {} + for dir_name, subdir_list, file_list in os.walk("star_wars"): + # dir_name, subdir_list, file_list = os.walk(".") + print(dir_name, subdir_list, file_list) + solution[dir_name] = file_list + + assert solution == {'star_wars': [], + 'star_wars/tatooine': [], + 'star_wars/tie_fighter': ['darth_vader.txt'], + 'star_wars/x_wing': ['luke_skywalker.txt'], + 'star_wars/millenium_falcon': ['han_solo.txt', 'chewbacca.txt'], + 'star_wars/the_rebellion': ['leia_organa.txt'], + 'star_wars/the_empire': [] + } diff --git a/intro_&_enviro/unix_and_bash/README.md b/intro_&_enviro/unix_and_bash/README.md new file mode 100644 index 00000000..0729899d --- /dev/null +++ b/intro_&_enviro/unix_and_bash/README.md @@ -0,0 +1,9 @@ +# Exercises for UNIX and Bash + +| Exercise ID | Exercise | +|:-----------:|:--------:| +| easy_e1 | [Basic Commands](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/unix_and_bash/1_basic_commands) | +| easy_e2 | [Commands With Options](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/unix_and_bash/1_commands_with_options) | +| easy_e3 | [Commands With Options 2](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/unix_and_bash/1_commands_with_options_2) | +| medium_e1 | [Intermediate Commands](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/unix_and_bash/2_intermediate_commands) | +| hard_e1 | [Star Wars](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/unix_and_bash/3_star_wars) | diff --git a/intro_&_enviro/unix_and_bash/basic_commands/README.md b/intro_&_enviro/unix_and_bash/basic_commands/README.md new file mode 100644 index 00000000..c75df63f --- /dev/null +++ b/intro_&_enviro/unix_and_bash/basic_commands/README.md @@ -0,0 +1,40 @@ +# Command Basics + +## Problem Description +The list below contains a number of variable names, as well as a text description of many different **bash** commands. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. + +Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! + +For example: +Variable: `ONE` +Description: command used when you remember the name of a **bash** command, but forget what it does + +In *solution.py* you would write: +```python +ONE = 'man' +``` + +Variable: `TWO` +Description: View the contents of a directory + +Variable: `THREE` +Description: Create a new directory (ignore any necessary arguments or options) + +Variable: `FOUR` +Description: Create an empty file + +Variable: `FIVE` +Description: Create a copy of a file, or with an option, copy the contents of a directory + +Variable: `SIX` +Description: Change the name of a file or directory + +Variable: `SEVEN` +Description: Delete a file, or with an additional option, a directory + + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory diff --git a/intro_&_enviro/unix_and_bash/basic_commands/solution/Commans_wi_opt.py b/intro_&_enviro/unix_and_bash/basic_commands/solution/Commans_wi_opt.py new file mode 100644 index 00000000..b550cbf7 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/basic_commands/solution/Commans_wi_opt.py @@ -0,0 +1,10 @@ +Examply = "Man Test" + +ONE = "cd excercises" +TWO= "pwd" +THREE = "cat textfile.txt" +FOUR = "tail textfile.txt" +FIVE = "ls -a" +SIX = "head textfile.txt" +SEVEN = "cd stackdata.json stockdata.json" + diff --git a/intro_&_enviro/unix_and_bash/basic_commands/solution/Intermediate_comm.py b/intro_&_enviro/unix_and_bash/basic_commands/solution/Intermediate_comm.py new file mode 100644 index 00000000..effbda48 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/basic_commands/solution/Intermediate_comm.py @@ -0,0 +1 @@ +ONE = "mkdir testdir && cd testdir" \ No newline at end of file diff --git a/intro_&_enviro/unix_and_bash/basic_commands/solution/commands_wi_opt_2.py b/intro_&_enviro/unix_and_bash/basic_commands/solution/commands_wi_opt_2.py new file mode 100644 index 00000000..b3e9b817 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/basic_commands/solution/commands_wi_opt_2.py @@ -0,0 +1,7 @@ +EXAMPLE ="man test" +ONE= "grep elephant book.txt" +TWO = "mv notes.txt newdir" +THREE= "grep -r string testdir" +FOUR = "rm -r empty" +FIVE = "cd /" +SIX = "rm -r -i Downloads" diff --git a/intro_&_enviro/unix_and_bash/basic_commands/solution/solution.py b/intro_&_enviro/unix_and_bash/basic_commands/solution/solution.py new file mode 100644 index 00000000..f68619da --- /dev/null +++ b/intro_&_enviro/unix_and_bash/basic_commands/solution/solution.py @@ -0,0 +1,10 @@ +# The first has been completed for you... +ONE = 'man' + +# Assign the correct strings below +TWO = '' +THREE = '' +FOUR = '' +FIVE = '' +SIX = '' +SEVEN = '' diff --git a/intro_&_enviro/unix_and_bash/basic_commands/solution/solutios2.py b/intro_&_enviro/unix_and_bash/basic_commands/solution/solutios2.py new file mode 100644 index 00000000..16870c91 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/basic_commands/solution/solutios2.py @@ -0,0 +1,8 @@ +ONE = "man" + +Two = "ls" +Three = "mkdir" +Four = "touch" +Five = "cp" +Six = "mv" +Seven = "rm" \ No newline at end of file diff --git a/intro_&_enviro/unix_and_bash/basic_commands/solution/test_solution.py b/intro_&_enviro/unix_and_bash/basic_commands/solution/test_solution.py new file mode 100644 index 00000000..a36502a0 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/basic_commands/solution/test_solution.py @@ -0,0 +1,14 @@ +import solution +from hashlib import sha1 + +def test_solution(): + def hashed_output(submission): + return sha1(submission.encode()).hexdigest() + + assert hashed_output(solution.ONE) == '8175e3c8753aeb1696959f72ede260ebf3ea14c5' + assert hashed_output(solution.TWO) == 'ebfdec641529d4b59a54e18f8b0e9730f85939fb' + assert hashed_output(solution.THREE) == '90868ffdfa3a8bd99cfa9f642349e60cf84e057a' + assert hashed_output(solution.FOUR) == 'f4d1f0193879cba82d65c5752c4ba5cbb43a7188' + assert hashed_output(solution.FIVE) == '3f81e91d69a8a61ffbf19297eb0791ad54ce5690' + assert hashed_output(solution.SIX) == '362d60cb3f6f8e96c37edac670b7618963233e07' + assert hashed_output(solution.SEVEN) == '5cd7e29c88170aa3f16281e0dbf5772c137f6d8d' diff --git a/intro_&_enviro/unix_and_bash/commands_with_options/README.md b/intro_&_enviro/unix_and_bash/commands_with_options/README.md new file mode 100644 index 00000000..9674f827 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/commands_with_options/README.md @@ -0,0 +1,42 @@ +# Command Basics 2 + +## Problem Description +The list below contains a number of variable names, as well as a text description of many different **bash** commands. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. These are harder than the first few, as they may contain additional arguments to be included with the command name. + +Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! + +For example: +Variable: `ONE` +Description: Command used when you remember the name of a **bash** command named "test", but forget what it does + +In *solution.py* you would write: +```python +ONE = 'man test' +``` + +Variable: `ONE` +Description: Navigate from the current directory to a new directory, named "exercises" + +Variable: `TWO` +Description: View our terminal's current directory location + +Variable: `THREE` +Description: View the *entire* contents of a file named "textfile.txt" in our terminal + +Variable: `FOUR` +Description: View *only* the last 10 lines of a file named "textfile.txt" + +Variable: `FIVE` +Description: View the contents of the current directory, including hidden files + +Variable: `SIX` +Description: View *only* the first 10 lines of a file named "textfile.txt" + +Variable: `SEVEN` +Description: Create a copy of a file, named "stackdata.json" with the name "stockdata.json + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory diff --git a/intro_&_enviro/unix_and_bash/commands_with_options/solution/solution.py b/intro_&_enviro/unix_and_bash/commands_with_options/solution/solution.py new file mode 100644 index 00000000..dae1ff7d --- /dev/null +++ b/intro_&_enviro/unix_and_bash/commands_with_options/solution/solution.py @@ -0,0 +1,9 @@ +# Assign the correct strings below + +ONE = 'cd exercises' +TWO = 'pwd' +THREE = 'cat textfile.txt' +FOUR = 'tail textfile.txt' +FIVE = 'ls -a' +SIX = 'head textfile.txt' +SEVEN = 'cp stackdata.json stockdata.json' diff --git a/intro_&_enviro/unix_and_bash/commands_with_options/solution/test_solution.py b/intro_&_enviro/unix_and_bash/commands_with_options/solution/test_solution.py new file mode 100644 index 00000000..f248dfd5 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/commands_with_options/solution/test_solution.py @@ -0,0 +1,14 @@ +import solution +from hashlib import sha1 + +def test_solution(): + def hashed_output(submission): + return sha1(submission.encode()).hexdigest() + + assert hashed_output(solution.ONE) == '8f7096f862f1c01437d435b1440612fc5907d76c' + assert hashed_output(solution.TWO) == '37fa265330ad83eaa879efb1e2db6380896cf639' + assert hashed_output(solution.THREE) == 'aa2ba3db8235609f178bac463e31eb01c1a9e711' + assert hashed_output(solution.FOUR) == 'e52fb413040572fbc243c74e29760dd3c9867aea' + assert hashed_output(solution.FIVE) == 'fda17aa65051cb574d5f9f1cc4c7f3ddbc931735' + assert hashed_output(solution.SIX) == '3441d7e6e51f18f214ae7f2ca9c6a87fe14deea8' + assert hashed_output(solution.SEVEN) == 'e120eb80c4d1bc2976a2176f8dd83d0a795725b6' diff --git a/intro_&_enviro/unix_and_bash/commands_with_options_2/README.md b/intro_&_enviro/unix_and_bash/commands_with_options_2/README.md new file mode 100644 index 00000000..0ac8900a --- /dev/null +++ b/intro_&_enviro/unix_and_bash/commands_with_options_2/README.md @@ -0,0 +1,39 @@ +# Command Basics 3 + +## Problem Description +The list below contains a number of variable names, as well as a text description of many different **bash** commands. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. These are harder than the first few, as they may contain additional arguments to be included with the command name. + +Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! + +For example: +Variable: `ONE` +Description: Command used when you remember the name of a **bash** command named "test", but forget what it does + +In *solution.py* you would write: +```python +ONE = 'man test' +``` + +Variable: `ONE` +Description: Search the contents of a file named "book.txt" for occurrences of the pattern "elephant" + +Variable: `TWO` +Description: Move a file named "notes.txt" from the current directory to a directory named "newdir" + +Variable: `THREE` +Description: Search all files in a directory named "testdir" for the pattern "string" + +Variable: `FOUR` +Description: Delete an empty directory named "empty" + +Variable: `FIVE` +Description: Navigate to our user's home directory (regardless of name) + +Variable: `SIX` +Description: Delete a non-empty directory, named "Downloads", as well as all of its contents + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory diff --git a/intro_&_enviro/unix_and_bash/commands_with_options_2/solution/solution.py b/intro_&_enviro/unix_and_bash/commands_with_options_2/solution/solution.py new file mode 100644 index 00000000..9f870190 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/commands_with_options_2/solution/solution.py @@ -0,0 +1,8 @@ +# Assign the correct strings below + +ONE = 'grep elephant book.txt' +TWO = 'mv notes.txt newdir' +THREE = 'grep -r string testdir' +FOUR = 'rm -d empty' +FIVE = 'cd' +SIX = 'rm -r Downloads' diff --git a/intro_&_enviro/unix_and_bash/commands_with_options_2/solution/test_solution.py b/intro_&_enviro/unix_and_bash/commands_with_options_2/solution/test_solution.py new file mode 100644 index 00000000..99154d43 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/commands_with_options_2/solution/test_solution.py @@ -0,0 +1,13 @@ +import solution +from hashlib import sha1 + +def test_solution(): + def hashed_output(submission): + return sha1(submission.encode()).hexdigest() + + assert hashed_output(solution.ONE) == '1efc27c5f639a389de478c3d2572063bf0b303f0' + assert hashed_output(solution.TWO) == '649b0028d6ad29d4b0099e6cd227551c19e75c68' + assert hashed_output(solution.THREE) == '3c8f2856c8f42eb101b62632788173107a857a88' + assert hashed_output(solution.FOUR) == 'e6e017e01c6c83091049d013bfad653f3fb75d27' + assert hashed_output(solution.FIVE) == '034778198a045c1ed80be271cdd029b76874f6fc' + assert hashed_output(solution.SIX) == '2c98f52bc8dc4272160f7ee35acfff3aa3f63676' diff --git a/intro_&_enviro/unix_and_bash/intermediate_commands/README.md b/intro_&_enviro/unix_and_bash/intermediate_commands/README.md new file mode 100644 index 00000000..793c46cb --- /dev/null +++ b/intro_&_enviro/unix_and_bash/intermediate_commands/README.md @@ -0,0 +1,36 @@ +# Bash Operators + +## Problem Description +The list below contains a number of variable names, as well as a text description of many different **bash** commands and operators that must be used. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. These are harder than the first few, and may need bash operators to pass data between commands or alter execution. + +Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! + +For example: +Variable: `ONE` +Description: Commands to list the contents of a directory, and then search that output for any files ending in ".py" + +In *solution.py* you would write: +```python +ONE = 'ls | grep .py' +``` + +Variable: `ONE` +Description: Commands to create a directory named "testdir" and then navigate into that directory, if creation was successful + +Variable: `TWO` +Description: Commands to view the entire contents of a file named "textfile.txt" and search that output for occurrences of the word "and" + +Variable: `THREE` +Description: Commands to view the contents of the current directory, and then *append* that output to an existing text file named "contents.txt" + +Variable: `FOUR` +Description: Commands to *either* navigate into a directory named "current", or, if that command failed, create the directory (but not bother with navigation afterwards) + +Variable: `FIVE` +Description: Commands to view our command line's current directory path, and then write that output to a *new* file called "current_path.txt" + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory diff --git a/intro_&_enviro/unix_and_bash/intermediate_commands/intermediate_commands.py b/intro_&_enviro/unix_and_bash/intermediate_commands/intermediate_commands.py new file mode 100644 index 00000000..a118f905 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/intermediate_commands/intermediate_commands.py @@ -0,0 +1,3 @@ +ONE = "mkdir testdir && cd testdir" +TWO = "cat textfile.txt && grep and textfile.txt" +THREE = "" \ No newline at end of file diff --git a/intro_&_enviro/unix_and_bash/intermediate_commands/solution/solution.py b/intro_&_enviro/unix_and_bash/intermediate_commands/solution/solution.py new file mode 100644 index 00000000..e9e48b3d --- /dev/null +++ b/intro_&_enviro/unix_and_bash/intermediate_commands/solution/solution.py @@ -0,0 +1,7 @@ + +# Assign the correct strings below +ONE = 'mkdir testdir && cd testdir' +TWO = 'cat textfile.txt | grep and' +THREE = 'ls >> contents.txt' +FOUR = 'cd current || mkdir current' +FIVE = 'pwd > current_path.txt' diff --git a/intro_&_enviro/unix_and_bash/intermediate_commands/solution/test_solution.py b/intro_&_enviro/unix_and_bash/intermediate_commands/solution/test_solution.py new file mode 100644 index 00000000..4fb95a29 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/intermediate_commands/solution/test_solution.py @@ -0,0 +1,12 @@ +import solution +from hashlib import sha1 + +def test_solution(): + def hashed_output(submission): + return sha1(submission.encode()).hexdigest() + + assert hashed_output(solution.ONE) == '8d90393573522285c5d58b437885ccbb9a9daced' + assert hashed_output(solution.TWO) == '6862d5dbed79ab65cf70e169232ad10ea4575373' + assert hashed_output(solution.THREE) == 'a0d69d758be9fd8be90f83bb3c51c3539c105bdf' + assert hashed_output(solution.FOUR) == 'e31d24b0d08a712dd0c8155c15259958e43dcd04' + assert hashed_output(solution.FIVE) == 'd07f1559dea4f7fb83c1a2b0c506646542856acb' diff --git a/intro_&_enviro/unix_and_bash/star_wars/README.md b/intro_&_enviro/unix_and_bash/star_wars/README.md new file mode 100644 index 00000000..a5751096 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/star_wars/README.md @@ -0,0 +1,49 @@ +# Command Line Workflow: Star Wars + +## Spoilers: Star Wars Episode IV: A New Hope +* This exercise contains spoilers for the 1977 film Star Wars (retitled as "Star Wars: Episode IV: A New Hope). While it has been over four decades, you have been warned. + +## Problem Description +* Navigating your computer through terminal is an extremely important, practically required skill to be a programmer. The following is an assignment where you will make / delete folders and files to help you get used to navigating your terminal and manipulating your files with bash commands. Perform all commands within the *solution* directory (there is no `solution.py` here, you'll be creating all necessary files.) + +### Use bash to perform the following commands, in order: +* Navigate into the "star_wars" folder +* Create a folder called "the_empire" +* Create a folder called "the_rebellion" +* Make the following folders + * "tatooine" + * "millenium_falcon" + * "death_star" + * "x_wing" + * "tie_fighter" +* Make the following text files (.txt) ***Make Sure to have the .txt extension on these files*** + * "luke_skywalker" + * "old_man_ben" + * "han_solo" + * "chewbacca" + * "leia_organa" + * "darth_vader" + * "emperor_palpatine" +* Open the darth_vader text file and add the text "Darth Vader" + * **Bonus points** if you add the text without opening the file +* Move the emperor and darth vader into the folder "the_empire" +* Move "luke_skywalker" and "old_man_ben" to the "tatooine" folder +* Luke has found out old man ben is actually Obi Wan Kenobi. Change the name of "old_man_ben" to "obi_wan_kenobi" +* Now they need to escape tatooine. Move "han_solo" and "chewbacca" into "tatooine" +* While all this is happening the Sith lords are sitting nice and cozy inside their giant metal moon. Move "darth_vader" and "emperor_palpatine" inside the "death_star" +* Back on tatooine the characters get on the fastest ship in the galaxy and take off to save the princess. Move all four files from tatooine into the millenium falcon +* The princess is also on the death star. Move "leia_organa" to the "death_star" +* Our heroes sneak onto the Death Star. Move all the files inside the "millenium_falcon" onto the "death_star" +* They found the princess! but in the process Obi Wan was struck down by Darth Vader. Delete the "obi_wan_kenobi" file +* Our other heroes retreat in anger. Move Luke, Leia, Han, and Chewbacca into the "millenium_falcon" +* Alright the rebels have regrouped and come up with a plan to destroy the death star. Luke gets into an x-wing to use his sweet piloting skills. Move "leia" into the "the_rebellion" directory. Move Luke into the "x_wing" +* Vader, also a legendary pilot, gets into the tie fighter to defend the death star. Move "darth_vader" out of the death_star and into the "tie_fighter" +* Luke uses those sweet farm boy desert skills and fires some torpedos into the core of the death star, destroying it. **CAREFULLY** Delete the folder "death_star" + * Remember that deletion of a directory is a high-stake operation + * **DO NOT** do this without checking your command for correctness + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory. It will use python to make sure your final directory/file structure is correct. + +## Submission +* Submit your answer in the *solution* subdirectory in this directory. Your "answer" will be the structure of the folders/files you created at the end of the exercise diff --git a/intro_&_enviro/unix_and_bash/star_wars/solution/star_wars/millenium_falcon/chewbacca.txt b/intro_&_enviro/unix_and_bash/star_wars/solution/star_wars/millenium_falcon/chewbacca.txt new file mode 100644 index 00000000..e69de29b diff --git a/intro_&_enviro/unix_and_bash/star_wars/solution/star_wars/millenium_falcon/han_solo.txt b/intro_&_enviro/unix_and_bash/star_wars/solution/star_wars/millenium_falcon/han_solo.txt new file mode 100644 index 00000000..e69de29b diff --git a/intro_&_enviro/unix_and_bash/star_wars/solution/star_wars/the_rebellion/leia_organa.txt b/intro_&_enviro/unix_and_bash/star_wars/solution/star_wars/the_rebellion/leia_organa.txt new file mode 100644 index 00000000..e69de29b diff --git a/intro_&_enviro/unix_and_bash/star_wars/solution/star_wars/tie_fighter/darth_vader.txt b/intro_&_enviro/unix_and_bash/star_wars/solution/star_wars/tie_fighter/darth_vader.txt new file mode 100644 index 00000000..e69de29b diff --git a/intro_&_enviro/unix_and_bash/star_wars/solution/star_wars/x_wing/luke_skywalker.txt b/intro_&_enviro/unix_and_bash/star_wars/solution/star_wars/x_wing/luke_skywalker.txt new file mode 100644 index 00000000..e69de29b diff --git a/intro_&_enviro/unix_and_bash/star_wars/solution/test_solution.py b/intro_&_enviro/unix_and_bash/star_wars/solution/test_solution.py new file mode 100644 index 00000000..8b761282 --- /dev/null +++ b/intro_&_enviro/unix_and_bash/star_wars/solution/test_solution.py @@ -0,0 +1,16 @@ +import os + +def test_solution(): + solution = {} + for dir_name, subdir_list, file_list in os.walk("star_wars"): + solution[dir_name] = set(file_list) + if not solution.get("star_wars/tatooine"): + solution.update({'star_wars/tatooine': set(), 'star_wars/the_empire': set()}) + assert solution == {'star_wars': set(), + 'star_wars/tatooine': set(), + 'star_wars/tie_fighter': {'darth_vader.txt'}, + 'star_wars/x_wing': {'luke_skywalker.txt'}, + 'star_wars/millenium_falcon': {'han_solo.txt', 'chewbacca.txt'}, + 'star_wars/the_rebellion': {'leia_organa.txt'}, + 'star_wars/the_empire': set() + } diff --git a/introduction_and_environment/README.md b/introduction_and_environment/README.md index a484ecbb..84ee52e3 100644 --- a/introduction_and_environment/README.md +++ b/introduction_and_environment/README.md @@ -1,8 +1,8 @@ -# Introduction and Environment - -## Overview -* Hello World -* UNIX and Bash -* Git -* Introduction to Programming -* Data Types and Control Flow +# Introduction and Environment + +## Overview +* Hello World +* UNIX and Bash +* Git +* Introduction to Programming +* Data Types and Control Flow diff --git a/introduction_and_environment/data_types_and_control_flow/1_compare_check/README.md b/introduction_and_environment/data_types_and_control_flow/1_compare_check/README.md index 94c54a5b..1b2ba11f 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_compare_check/README.md +++ b/introduction_and_environment/data_types_and_control_flow/1_compare_check/README.md @@ -1,16 +1,16 @@ -# Compare Check - -## Motivation -Python provides the `==` operator to check if the operands hold the same values, and `!=` for the inverse. - -## Problem Description -Write a python script that contains 2 integers `x` and `y`. -Use the appropriate operator to compare whether `x` and `y` are equivalent, and store that output in a variable named `result`. - -Print `result`. - -## Testing -* To test your solution, type 'pytest' within the **solutions** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory +# Compare Check + +## Motivation +Python provides the `==` operator to check if the operands hold the same values, and `!=` for the inverse. + +## Problem Description +Write a python script that contains 2 integers `x` and `y`. +Use the appropriate operator to compare whether `x` and `y` are equivalent, and store that output in a variable named `result`. + +Print `result`. + +## Testing +* To test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory diff --git a/introduction_and_environment/data_types_and_control_flow/1_compare_check/Solution/.model_solution.py b/introduction_and_environment/data_types_and_control_flow/1_compare_check/Solution/.model_solution.py index 1a29f9cd..c92a4c1d 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_compare_check/Solution/.model_solution.py +++ b/introduction_and_environment/data_types_and_control_flow/1_compare_check/Solution/.model_solution.py @@ -1,5 +1,5 @@ -# Code your solution here -x = 200 -y = 201 -result = x == y -print(result) +# Code your solution here +x = 200 +y = 201 +result = x == y +print(result) diff --git a/introduction_and_environment/data_types_and_control_flow/1_compare_check/Solution/solution.py b/introduction_and_environment/data_types_and_control_flow/1_compare_check/Solution/solution.py index ade03179..642fb0fd 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_compare_check/Solution/solution.py +++ b/introduction_and_environment/data_types_and_control_flow/1_compare_check/Solution/solution.py @@ -1 +1,4 @@ -# Code your solution here +# Code your solution here +x = 0 +y = 0 +result = x == y \ No newline at end of file diff --git a/introduction_and_environment/data_types_and_control_flow/1_compare_check/Solution/test_solution.py b/introduction_and_environment/data_types_and_control_flow/1_compare_check/Solution/test_solution.py index 71515be6..d6aab1f7 100644 --- a/introduction_and_environment/data_types_and_control_flow/1_compare_check/Solution/test_solution.py +++ b/introduction_and_environment/data_types_and_control_flow/1_compare_check/Solution/test_solution.py @@ -1,14 +1,14 @@ - -def test_solution(monkeypatch): - ret_val1= None - - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.print',g) - - import solution - assert type(solution.x) == int and type(solution.y) == int - assert solution.result == False - + +def test_solution(monkeypatch): + ret_val1= None + + def g(num1): + nonlocal ret_val1 + ret_val1=num1 + + monkeypatch.setattr('builtins.print',g) + + import solution + assert type(solution.x) == int and type(solution.y) == int + assert solution.result == False + diff --git a/introduction_and_environment/data_types_and_control_flow/2_append/Solution/solution.py b/introduction_and_environment/data_types_and_control_flow/2_append/Solution/solution.py index db2e72c8..7d38cf4b 100644 --- a/introduction_and_environment/data_types_and_control_flow/2_append/Solution/solution.py +++ b/introduction_and_environment/data_types_and_control_flow/2_append/Solution/solution.py @@ -1,4 +1,6 @@ -# Code your solution here -list_a=[True,False,False,False,False,True] -list_b=list_a.insert(3,True) -print(list_b) +# Code your solution here +list_a = [True,False,False,False,False,True] +list_b = list_a +list_a.insert(3,True) +print(list_b) +print(list_a) diff --git a/introduction_and_environment/data_types_and_control_flow/3_count_duplicate/Solution/test_solution.py b/introduction_and_environment/data_types_and_control_flow/3_count_duplicate/Solution/test_solution.py deleted file mode 100644 index 02667ae6..00000000 --- a/introduction_and_environment/data_types_and_control_flow/3_count_duplicate/Solution/test_solution.py +++ /dev/null @@ -1,13 +0,0 @@ - - -def test_solution(monkeypatch): - ret_val1=None - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.print',g) - - import solution - - diff --git a/introduction_and_environment/data_types_and_control_flow/3_set_difference/Solution/test_solution.py b/introduction_and_environment/data_types_and_control_flow/3_set_difference/Solution/test_solution.py deleted file mode 100644 index b7403fa5..00000000 --- a/introduction_and_environment/data_types_and_control_flow/3_set_difference/Solution/test_solution.py +++ /dev/null @@ -1,11 +0,0 @@ -def test_solution(monkeypatch): - ret_val1=None - def g(num1): - nonlocal ret_val1 - ret_val1=num1 - - monkeypatch.setattr('builtins.print',g) - - import solution - - diff --git a/introduction_and_environment/git/README.md b/introduction_and_environment/git/README.md index 1c63631a..4748c4e8 100644 --- a/introduction_and_environment/git/README.md +++ b/introduction_and_environment/git/README.md @@ -1,8 +1,8 @@ -# Exercises for Git - -| **Exercise ID** | **Exercise** | -|:---------------:|:-------------------:| -| easy_e1 | [Staging Area](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/git/creating_a_repository) | -| easy_e2 | [Remote Repo](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/git/update_code) | -| easy_e3 | [Updating Code](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/git/staging_area) | -| easy_e4 | [Creating a Repository](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/git/remote_repository) | +# Exercises for Git + +| **Exercise ID** | **Exercise** | +|:---------------:|:-------------------:| +| easy_e1 | [Staging Area](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/git/creating_a_repository) | +| easy_e2 | [Remote Repo](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/git/update_code) | +| easy_e3 | [Updating Code](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/git/staging_area) | +| easy_e4 | [Creating a Repository](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/git/remote_repository) | diff --git a/introduction_and_environment/git/creating_a_repository/README.md b/introduction_and_environment/git/creating_a_repository/README.md index c1256d2c..9be43293 100644 --- a/introduction_and_environment/git/creating_a_repository/README.md +++ b/introduction_and_environment/git/creating_a_repository/README.md @@ -1,12 +1,12 @@ -# Creating a repository - -## Problem Description -Which of the following commands creates a repository? - -a) `git init` -b) `git add` -c) `git commit` -d) `git push` - -## Submission -* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. +# Creating a repository + +## Problem Description +Which of the following commands creates a repository? + +a) `git init` +b) `git add` +c) `git commit` +d) `git push` + +## Submission +* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. diff --git a/introduction_and_environment/git/creating_a_repository/solution/solution.py b/introduction_and_environment/git/creating_a_repository/solution/solution.py index e7abe60c..a2b33d4f 100644 --- a/introduction_and_environment/git/creating_a_repository/solution/solution.py +++ b/introduction_and_environment/git/creating_a_repository/solution/solution.py @@ -1,2 +1,2 @@ -# Code your solution here -answer = 'a' +# Code your solution here +answer = 'a' diff --git a/introduction_and_environment/git/creating_a_repository/solution/test_solution.py b/introduction_and_environment/git/creating_a_repository/solution/test_solution.py index 0869fce0..990a2a46 100644 --- a/introduction_and_environment/git/creating_a_repository/solution/test_solution.py +++ b/introduction_and_environment/git/creating_a_repository/solution/test_solution.py @@ -1,5 +1,5 @@ - -def test_solution(): - import solution - assert solution.answer in {'a', 'A'} - + +def test_solution(): + import solution + assert solution.answer in {'a', 'A'} + diff --git a/introduction_and_environment/git/remote_repository/README.md b/introduction_and_environment/git/remote_repository/README.md index e3bd575f..5cb150e8 100644 --- a/introduction_and_environment/git/remote_repository/README.md +++ b/introduction_and_environment/git/remote_repository/README.md @@ -1,12 +1,12 @@ -# Remote Repository - -## Problem Description -Which of the following synchronizes your local repository and the remote repository? - -a) `git init` -b) `git add` -c) `git commit` -d) `git push` - -## Submission -* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. +# Remote Repository + +## Problem Description +Which of the following synchronizes your local repository and the remote repository? + +a) `git init` +b) `git add` +c) `git commit` +d) `git push` + +## Submission +* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. diff --git a/introduction_and_environment/git/remote_repository/solution/solution.py b/introduction_and_environment/git/remote_repository/solution/solution.py index 482a5499..e96d1f30 100644 --- a/introduction_and_environment/git/remote_repository/solution/solution.py +++ b/introduction_and_environment/git/remote_repository/solution/solution.py @@ -1,2 +1,2 @@ -# Code your solution here -answer = 'd' +# Code your solution here +answer = 'd' diff --git a/introduction_and_environment/git/remote_repository/solution/test_solution.py b/introduction_and_environment/git/remote_repository/solution/test_solution.py index ea906fd1..e935c53f 100644 --- a/introduction_and_environment/git/remote_repository/solution/test_solution.py +++ b/introduction_and_environment/git/remote_repository/solution/test_solution.py @@ -1,5 +1,5 @@ - -def test_solution(): - import solution - assert solution.answer in {'d', 'D'} - + +def test_solution(): + import solution + assert solution.answer in {'d', 'D'} + diff --git a/introduction_and_environment/git/staging_area/README.md b/introduction_and_environment/git/staging_area/README.md index d29a15a7..f2df36be 100644 --- a/introduction_and_environment/git/staging_area/README.md +++ b/introduction_and_environment/git/staging_area/README.md @@ -1,12 +1,12 @@ -# Staging Area - -## Problem Description -Which of the following commands syncronizes the staging area with your repository? - -a) `git init` -b) `git add` -c) `git commit` -d) `git push` - -## Submission -* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. +# Staging Area + +## Problem Description +Which of the following commands syncronizes the staging area with your repository? + +a) `git init` +b) `git add` +c) `git commit` +d) `git push` + +## Submission +* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. diff --git a/introduction_and_environment/git/staging_area/solution/solution.py b/introduction_and_environment/git/staging_area/solution/solution.py index b8eb8f57..b7e28b02 100644 --- a/introduction_and_environment/git/staging_area/solution/solution.py +++ b/introduction_and_environment/git/staging_area/solution/solution.py @@ -1,2 +1,2 @@ -# Code your solution here -answer = 'c' +# Code your solution here +answer = 'c' diff --git a/introduction_and_environment/git/staging_area/solution/test_solution.py b/introduction_and_environment/git/staging_area/solution/test_solution.py index f632b37a..ef69e5ec 100644 --- a/introduction_and_environment/git/staging_area/solution/test_solution.py +++ b/introduction_and_environment/git/staging_area/solution/test_solution.py @@ -1,5 +1,5 @@ - -def test_solution(): - import solution - assert solution.answer in {'c', 'C'} - + +def test_solution(): + import solution + assert solution.answer in {'c', 'C'} + diff --git a/introduction_and_environment/git/update_code/README.md b/introduction_and_environment/git/update_code/README.md index 994da9e9..cda1d184 100644 --- a/introduction_and_environment/git/update_code/README.md +++ b/introduction_and_environment/git/update_code/README.md @@ -1,12 +1,12 @@ -# Updating Code - -## Problem Description -Which of the following pushes changes from your working directory to your staging area? - -a) `git init` -b) `git add` -c) `git commit` -d) `git push` - -## Submission -* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. +# Updating Code + +## Problem Description +Which of the following pushes changes from your working directory to your staging area? + +a) `git init` +b) `git add` +c) `git commit` +d) `git push` + +## Submission +* Declare a variable called `answer` in *solution.py* and assign it to either 'a', 'b', 'c' or 'd'. diff --git a/introduction_and_environment/git/update_code/solution/solution.py b/introduction_and_environment/git/update_code/solution/solution.py index ca9c8ca8..86d9986c 100644 --- a/introduction_and_environment/git/update_code/solution/solution.py +++ b/introduction_and_environment/git/update_code/solution/solution.py @@ -1,2 +1,2 @@ -# Code your solution here -answer = 'b' +# Code your solution here +answer = 'b' diff --git a/introduction_and_environment/git/update_code/solution/test_solution.py b/introduction_and_environment/git/update_code/solution/test_solution.py index 6e6e4512..09e33c52 100644 --- a/introduction_and_environment/git/update_code/solution/test_solution.py +++ b/introduction_and_environment/git/update_code/solution/test_solution.py @@ -1,5 +1,5 @@ - -def test_solution(): - import solution - assert solution.answer in {'b', 'B'} - + +def test_solution(): + import solution + assert solution.answer in {'b', 'B'} + diff --git a/introduction_and_environment/hello_world/README.md b/introduction_and_environment/hello_world/README.md index b0d04453..aecf2cb3 100644 --- a/introduction_and_environment/hello_world/README.md +++ b/introduction_and_environment/hello_world/README.md @@ -1,16 +1,16 @@ -# Exercises for Hello World - - -| Exercise ID | Exercise | -|:-----------:|:--------:| -| easy_e1 | [Arithmetic](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/arithmetic) | -| easy_e2 | [Concatenation](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/concantenation) | -| easy_e3 | [Name Bindings](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/name_bindings) | -| easy_e4 | [Operators](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/operators) | -| medium_e1 | [Capture Display](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/capture_display) | -| medium_e2 | [Python Caches](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/python_caches) | -| medium_e3 | [String Arithmetic](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/string_arithmetic) | -| medium_e4 | [String Duplication](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/string_duplication) | -| medium_e5 | [Type Checking](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/type_check) | -| hard_e1 | [Type Change](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/type_change) | -| hard_e2 | [User Input](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/user_input) | +# Exercises for Hello World + + +| Exercise ID | Exercise | +|:-----------:|:--------:| +| easy_e1 | [Arithmetic](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/arithmetic) | +| easy_e2 | [Concatenation](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/concantenation) | +| easy_e3 | [Name Bindings](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/name_bindings) | +| easy_e4 | [Operators](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/operators) | +| medium_e1 | [Capture Display](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/capture_display) | +| medium_e2 | [Python Caches](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/python_caches) | +| medium_e3 | [String Arithmetic](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/string_arithmetic) | +| medium_e4 | [String Duplication](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/string_duplication) | +| medium_e5 | [Type Checking](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/type_check) | +| hard_e1 | [Type Change](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/type_change) | +| hard_e2 | [User Input](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/user_input) | diff --git a/introduction_and_environment/hello_world/arithmetic/README.md b/introduction_and_environment/hello_world/arithmetic/README.md index 1da79429..3d0bfc65 100644 --- a/introduction_and_environment/hello_world/arithmetic/README.md +++ b/introduction_and_environment/hello_world/arithmetic/README.md @@ -1,20 +1,20 @@ -# Arithmetic - -## Problem Description -The *solution.py* file contains 2 variables `x` and `y` whose values are hidden from you. They will each default to 0. Create the following variables from the chart below and set them equal to the associated values. - - Variable | Value -:----------:|:-----: -`my_sum` | `x + y` -`my_diff` | `x - y` -`my_mult` | `x * y` -`my_div` | `x / y` -`my_power` | `x ** y` -`my_quotient` | `x // y` -`my_remainder` | `x % y` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Arithmetic + +## Problem Description +The *solution.py* file contains 2 variables `x` and `y` whose values are hidden from you. They will each default to 0. Create the following variables from the chart below and set them equal to the associated values. + + Variable | Value +:----------:|:-----: +`my_sum` | `x + y` +`my_diff` | `x - y` +`my_mult` | `x * y` +`my_div` | `x / y` +`my_power` | `x ** y` +`my_quotient` | `x // y` +`my_remainder` | `x % y` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_and_environment/hello_world/arithmetic/solution/provided_code.py b/introduction_and_environment/hello_world/arithmetic/solution/provided_code.py index 632c5f31..a0c8913c 100644 --- a/introduction_and_environment/hello_world/arithmetic/solution/provided_code.py +++ b/introduction_and_environment/hello_world/arithmetic/solution/provided_code.py @@ -1,2 +1,2 @@ -x = 10 -y = 30 +x = 10 +y = 30 diff --git a/introduction_and_environment/hello_world/arithmetic/solution/solution.py b/introduction_and_environment/hello_world/arithmetic/solution/solution.py index 7e5b30b8..2c710360 100644 --- a/introduction_and_environment/hello_world/arithmetic/solution/solution.py +++ b/introduction_and_environment/hello_world/arithmetic/solution/solution.py @@ -1,9 +1,9 @@ -from provided_code import x, y - -my_sum = x + y -my_diff = x - y -my_mult = x * y -my_div = x / y -my_power = x ** y -my_quotient = x // y -my_remainder = x % y +from provided_code import x, y + +my_sum = x + y +my_diff = x - y +my_mult = x * y +my_div = x / y +my_power = x ** y +my_quotient = x // y +my_remainder = x % y diff --git a/introduction_and_environment/hello_world/arithmetic/solution/test_solution.py b/introduction_and_environment/hello_world/arithmetic/solution/test_solution.py index 1f7a2fe1..c48da514 100644 --- a/introduction_and_environment/hello_world/arithmetic/solution/test_solution.py +++ b/introduction_and_environment/hello_world/arithmetic/solution/test_solution.py @@ -1,13 +1,13 @@ -import provided_code -provided_code.x = 20 -provided_code.y = 10 -import solution - -def test_solution(): - assert solution.my_sum == 30 - assert solution.my_diff == 10 - assert solution.my_mult == 200 - assert solution.my_div == 2 - assert solution.my_power == 10240000000000 - assert solution.my_quotient == 2 - assert solution.my_remainder == 0 +import provided_code +provided_code.x = 20 +provided_code.y = 10 +import solution + +def test_solution(): + assert solution.my_sum == 30 + assert solution.my_diff == 10 + assert solution.my_mult == 200 + assert solution.my_div == 2 + assert solution.my_power == 10240000000000 + assert solution.my_quotient == 2 + assert solution.my_remainder == 0 diff --git a/introduction_and_environment/hello_world/capture_display/README.md b/introduction_and_environment/hello_world/capture_display/README.md index 9c5cec0b..39491add 100644 --- a/introduction_and_environment/hello_world/capture_display/README.md +++ b/introduction_and_environment/hello_world/capture_display/README.md @@ -1,14 +1,14 @@ -# Capture Display - -## Motivation -Python provides us with the input() method in order to capture data from the user. - -## Problem Description -Write a Python script that asks the user for name and age . Store these values in variables called `name` and `age`, respectively. -Print the values. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Capture Display + +## Motivation +Python provides us with the input() method in order to capture data from the user. + +## Problem Description +Write a Python script that asks the user for name and age . Store these values in variables called `name` and `age`, respectively. +Print the values. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_and_environment/hello_world/capture_display/solution/solution.py b/introduction_and_environment/hello_world/capture_display/solution/solution.py index d898ad34..edcf587c 100644 --- a/introduction_and_environment/hello_world/capture_display/solution/solution.py +++ b/introduction_and_environment/hello_world/capture_display/solution/solution.py @@ -1,5 +1,5 @@ -# Code your solution here -name = input("What is your name? ") -age = input("What is your age? ") - +# Code your solution here +name = input() +age = input() + print(name, age) \ No newline at end of file diff --git a/introduction_and_environment/hello_world/capture_display/solution/test.py b/introduction_and_environment/hello_world/capture_display/solution/test.py new file mode 100644 index 00000000..8b0f2f44 --- /dev/null +++ b/introduction_and_environment/hello_world/capture_display/solution/test.py @@ -0,0 +1 @@ +name = intput() \ No newline at end of file diff --git a/introduction_and_environment/hello_world/capture_display/solution/test_solution.py b/introduction_and_environment/hello_world/capture_display/solution/test_solution.py index 8ea7237a..9129774a 100644 --- a/introduction_and_environment/hello_world/capture_display/solution/test_solution.py +++ b/introduction_and_environment/hello_world/capture_display/solution/test_solution.py @@ -1,24 +1,24 @@ - -def test_solution(monkeypatch): - x = ['Charlie','100'] - index = -1 - ret_val1 = None - ret_val2 = None - - def f(): - nonlocal index - nonlocal x - index += 1 - return x[index] - - def g(num1,num2): - nonlocal ret_val1 - nonlocal ret_val2 - ret_val1 = num1 - ret_val2 = num2 - - monkeypatch.setattr('builtins.input',f) - monkeypatch.setattr('builtins.print',g) - import solution - assert solution.name == 'Charlie' - assert solution.age == '100' + +def test_solution(monkeypatch): + x = ['Charlie','100'] + index = -1 + ret_val1 = None + ret_val2 = None + + def f(): + nonlocal index + nonlocal x + index += 1 + return x[index] + + def g(num1,num2): + nonlocal ret_val1 + nonlocal ret_val2 + ret_val1 = num1 + ret_val2 = num2 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + import solution + assert solution.name == 'Charlie' + assert solution.age == '100' diff --git a/introduction_and_environment/hello_world/concantenation/README.md b/introduction_and_environment/hello_world/concantenation/README.md index 429154bd..ebdc95f0 100644 --- a/introduction_and_environment/hello_world/concantenation/README.md +++ b/introduction_and_environment/hello_world/concantenation/README.md @@ -1,15 +1,15 @@ -## Concatenate Data - -## Motivation -Concatenation in Python allows us to concatenate a string with another string, but never strings with other data types (such as integers, floats). - -## Problem Description -Write a python script that creates 2 string variables `string_1` and `string_2`. -Concatenate the 2 variables and store inside a new variable `result`. -Print the result. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +## Concatenate Data + +## Motivation +Concatenation in Python allows us to concatenate a string with another string, but never strings with other data types (such as integers, floats). + +## Problem Description +Write a python script that creates 2 string variables `string_1` and `string_2`. +Concatenate the 2 variables and store inside a new variable `result`. +Print the result. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_and_environment/hello_world/concantenation/solution/solution.py b/introduction_and_environment/hello_world/concantenation/solution/solution.py index ea6af02b..c1de7c52 100644 --- a/introduction_and_environment/hello_world/concantenation/solution/solution.py +++ b/introduction_and_environment/hello_world/concantenation/solution/solution.py @@ -1,5 +1,5 @@ -# Code your solution below -string_1 = "Good Morning " -string_2 = "Universe" -result = string_1 + string_2 +# Code your solution below +string_1 = "Good Morning " +string_2 = "Universe" +result = string_1 + string_2 print(result) \ No newline at end of file diff --git a/introduction_and_environment/hello_world/concantenation/solution/test_solution.py b/introduction_and_environment/hello_world/concantenation/solution/test_solution.py index 969b5c06..ad80c475 100644 --- a/introduction_and_environment/hello_world/concantenation/solution/test_solution.py +++ b/introduction_and_environment/hello_world/concantenation/solution/test_solution.py @@ -1,16 +1,16 @@ - - -def test_solution(monkeypatch): - x = "Good Morning " - y = "Universe" - ret_val1 = None - - def g(num1): - nonlocal ret_val1 - ret_val1 = num1 - - monkeypatch.setattr('builtins.print',g) - - import solution - assert solution.string_1 == x - assert solution.string_2 == y + + +def test_solution(monkeypatch): + x = "Good Morning " + y = "Universe" + ret_val1 = None + + def g(num1): + nonlocal ret_val1 + ret_val1 = num1 + + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.string_1 == x + assert solution.string_2 == y diff --git a/introduction_and_environment/hello_world/name_bindings/README.md b/introduction_and_environment/hello_world/name_bindings/README.md index e2ffc3dc..9591f097 100644 --- a/introduction_and_environment/hello_world/name_bindings/README.md +++ b/introduction_and_environment/hello_world/name_bindings/README.md @@ -1,10 +1,10 @@ -# Name Bindings - -## Problem Description -Create 3 variables in the *solution.py* file `x`, `y`, `z` which should hold the values 1337, `'hello world'` and 13.5 respectively. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Name Bindings + +## Problem Description +Create 3 variables in the *solution.py* file `x`, `y`, `z` which should hold the values 1337, `'hello world'` and 13.5 respectively. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_and_environment/hello_world/name_bindings/solution/solution.py b/introduction_and_environment/hello_world/name_bindings/solution/solution.py index 2ffa6cc3..9a53e73b 100644 --- a/introduction_and_environment/hello_world/name_bindings/solution/solution.py +++ b/introduction_and_environment/hello_world/name_bindings/solution/solution.py @@ -1,4 +1,4 @@ -# Code your solution below -x = 1337 -y = 'hello world' -z = 13.5 +# Code your solution below +x = 1337 +y = 'hello world' +z = 13.5 diff --git a/introduction_and_environment/hello_world/name_bindings/solution/test_solution.py b/introduction_and_environment/hello_world/name_bindings/solution/test_solution.py index ba68b723..892eff71 100644 --- a/introduction_and_environment/hello_world/name_bindings/solution/test_solution.py +++ b/introduction_and_environment/hello_world/name_bindings/solution/test_solution.py @@ -1,6 +1,6 @@ -import solution - -def test_solution(): - assert solution.x == 1337 - assert solution.y == 'hello world' - assert solution.z == 13.5 +import solution + +def test_solution(): + assert solution.x == 1337 + assert solution.y == 'hello world' + assert solution.z == 13.5 diff --git a/introduction_and_environment/hello_world/operators/README.md b/introduction_and_environment/hello_world/operators/README.md index 4d6754b4..98c7045b 100644 --- a/introduction_and_environment/hello_world/operators/README.md +++ b/introduction_and_environment/hello_world/operators/README.md @@ -1,10 +1,10 @@ -# Operators - -## Problem Description -Python provides us with floor divison `//` and modulus division `%` operators for integer types. Create 2 variables named `x` and `y`, such that `x % y` equals `x // y`. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Operators + +## Problem Description +Python provides us with floor divison `//` and modulus division `%` operators for integer types. Create 2 variables named `x` and `y`, such that `x % y` equals `x // y`. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_and_environment/hello_world/operators/solution/solution.py b/introduction_and_environment/hello_world/operators/solution/solution.py index 19f5de92..35905d2c 100644 --- a/introduction_and_environment/hello_world/operators/solution/solution.py +++ b/introduction_and_environment/hello_world/operators/solution/solution.py @@ -1,3 +1,3 @@ -# Code your solution here -x = 11 -y = 10 +# Code your solution here +x = 11 +y = 10 diff --git a/introduction_and_environment/hello_world/operators/solution/test_solution.py b/introduction_and_environment/hello_world/operators/solution/test_solution.py index 77a35f8f..36c7ec86 100644 --- a/introduction_and_environment/hello_world/operators/solution/test_solution.py +++ b/introduction_and_environment/hello_world/operators/solution/test_solution.py @@ -1,4 +1,4 @@ -import solution - -def test_solution(): - assert solution.x % solution.y == solution.x // solution.y +import solution + +def test_solution(): + assert solution.x % solution.y == solution.x // solution.y diff --git a/introduction_and_environment/hello_world/python_caches/README.md b/introduction_and_environment/hello_world/python_caches/README.md index e31822e1..c7bcc0b6 100644 --- a/introduction_and_environment/hello_world/python_caches/README.md +++ b/introduction_and_environment/hello_world/python_caches/README.md @@ -1,36 +1,36 @@ -# Python Caches - -## Motivation -The Python built-in id() function tells us the memory address of a particular variable. Python dynamically saves contents to memory each time we create a variable. -For example, if you type the following code into a Python command prompt, you will see the memory address of where x and y are stored. Notice how they change upon changing the variables - this is Python's dynamic nature of memory creation. **Note: Do not type this in an editor - reasons beyond the scope of this lesson**. -```Python ->>> x = 1 ->>> y = 1 ->>> id(x) -10914496 ->>> id(y) -10914496 ->>> x = 1234 ->>> id(x) -1400159191253392 ->>> y = 1234 ->>> id(y) -1400159191254216 -``` - -You will notice that when x and y are both 1, they are stored in the same memory address while when x and y are both 1234, they are stored in separate memory addresses. This is attributed to the fact that Python only dynamically creates integers above a certain range and stores small integers in memory as they are commonly used in a developers code. This is known as [caching](https://en.wikipedia.org/wiki/Cache_(computing)) and it improves the performance of Python code since dynamically creating memory is expensive. - -## Problem Descripton - -Your goal is to determine what range of integers Python saves in memory (caches). - -* a) What is the lower bound of the range? Store this number in variable `lower_bound` -* b) What is the upper bound of the range? Store this number in variable `upper_bound` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory -* The file contains 2 variables - `LOWER_BOUND` and `UPPER_BOUND` representing each bound respectively -* Overwrite these numbers with your answers +# Python Caches + +## Motivation +The Python built-in id() function tells us the memory address of a particular variable. Python dynamically saves contents to memory each time we create a variable. +For example, if you type the following code into a Python command prompt, you will see the memory address of where x and y are stored. Notice how they change upon changing the variables - this is Python's dynamic nature of memory creation. **Note: Do not type this in an editor - reasons beyond the scope of this lesson**. +```Python +>>> x = 1 +>>> y = 1 +>>> id(x) +10914496 +>>> id(y) +10914496 +>>> x = 1234 +>>> id(x) +1400159191253392 +>>> y = 1234 +>>> id(y) +1400159191254216 +``` + +You will notice that when x and y are both 1, they are stored in the same memory address while when x and y are both 1234, they are stored in separate memory addresses. This is attributed to the fact that Python only dynamically creates integers above a certain range and stores small integers in memory as they are commonly used in a developers code. This is known as [caching](https://en.wikipedia.org/wiki/Cache_(computing)) and it improves the performance of Python code since dynamically creating memory is expensive. + +## Problem Descripton + +Your goal is to determine what range of integers Python saves in memory (caches). + +* a) What is the lower bound of the range? Store this number in variable `lower_bound` +* b) What is the upper bound of the range? Store this number in variable `upper_bound` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +* The file contains 2 variables - `LOWER_BOUND` and `UPPER_BOUND` representing each bound respectively +* Overwrite these numbers with your answers diff --git a/introduction_and_environment/hello_world/python_caches/solution/solution.py b/introduction_and_environment/hello_world/python_caches/solution/solution.py index 4e444b15..5bb38671 100644 --- a/introduction_and_environment/hello_world/python_caches/solution/solution.py +++ b/introduction_and_environment/hello_world/python_caches/solution/solution.py @@ -1,2 +1,2 @@ -lower_bound = -5 +lower_bound = -5 upper_bound = 256 \ No newline at end of file diff --git a/introduction_and_environment/hello_world/python_caches/solution/test_solution.py b/introduction_and_environment/hello_world/python_caches/solution/test_solution.py index d85315bf..9d00a2a2 100644 --- a/introduction_and_environment/hello_world/python_caches/solution/test_solution.py +++ b/introduction_and_environment/hello_world/python_caches/solution/test_solution.py @@ -1,5 +1,5 @@ -import solution - -def test_solution(): - assert solution.lower_bound == -5, "Incorrect lower bound" - assert solution.upper_bound == 256, "Incorrect upper bound" +import solution + +def test_solution(): + assert solution.lower_bound == -5, "Incorrect lower bound" + assert solution.upper_bound == 256, "Incorrect upper bound" diff --git a/introduction_and_environment/hello_world/string_arithmetic/README.md b/introduction_and_environment/hello_world/string_arithmetic/README.md index 4ea9cc97..655f6bd3 100644 --- a/introduction_and_environment/hello_world/string_arithmetic/README.md +++ b/introduction_and_environment/hello_world/string_arithmetic/README.md @@ -1,15 +1,15 @@ -# String Arithmetic - -## Motivation -In the [Arithmetic](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/Exercises/Hello-World/1-Arithmetic) exercise we saw the 7 arithmetic operators. Only some of the 7 operators (`+`, `-`, `*`, `/`, `**`, `//`, `%`) work on strings. - -## Problem Description -Determine how many of the 7 operators listed above work on the `str` type and store that number in the variable name `str_arithmetic`. - -Hint: Don't just try arithmetic with strings and strings, try arithmetic with strings and integers as well - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# String Arithmetic + +## Motivation +In the [Arithmetic](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/Exercises/Hello-World/1-Arithmetic) exercise we saw the 7 arithmetic operators. Only some of the 7 operators (`+`, `-`, `*`, `/`, `**`, `//`, `%`) work on strings. + +## Problem Description +Determine how many of the 7 operators listed above work on the `str` type and store that number in the variable name `str_arithmetic`. + +Hint: Don't just try arithmetic with strings and strings, try arithmetic with strings and integers as well + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_and_environment/hello_world/string_arithmetic/solution/solution.py b/introduction_and_environment/hello_world/string_arithmetic/solution/solution.py index 4d5d0b20..dc572a6a 100644 --- a/introduction_and_environment/hello_world/string_arithmetic/solution/solution.py +++ b/introduction_and_environment/hello_world/string_arithmetic/solution/solution.py @@ -1,3 +1,3 @@ -# Code your solution here - +# Code your solution here + str_arithmetic = 2 \ No newline at end of file diff --git a/introduction_and_environment/hello_world/string_arithmetic/solution/test_solution.py b/introduction_and_environment/hello_world/string_arithmetic/solution/test_solution.py index 68215e43..9560e0c2 100644 --- a/introduction_and_environment/hello_world/string_arithmetic/solution/test_solution.py +++ b/introduction_and_environment/hello_world/string_arithmetic/solution/test_solution.py @@ -1,4 +1,4 @@ -import solution - -def test_solution(): - assert solution.str_arithmetic == 2 +import solution + +def test_solution(): + assert solution.str_arithmetic == 2 diff --git a/introduction_and_environment/hello_world/string_duplication/README.md b/introduction_and_environment/hello_world/string_duplication/README.md index d4026846..554fc103 100644 --- a/introduction_and_environment/hello_world/string_duplication/README.md +++ b/introduction_and_environment/hello_world/string_duplication/README.md @@ -1,15 +1,15 @@ -# String Duplicate - -## Motivation -String values can be duplicated with help of the `*` operator. - -## Problem Description -Write a Python script that asks the user for a string value and an integer value, representing the number of times the user wishs to duplicate the string. -Store the values as `string_1` and `dup_val `, respectively. Then, repeat the string `dup_val` number of times and store the result with the variable name `data`. -Print `data`. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# String Duplicate + +## Motivation +String values can be duplicated with help of the `*` operator. + +## Problem Description +Write a Python script that asks the user for a string value and an integer value, representing the number of times the user wishs to duplicate the string. +Store the values as `string_1` and `dup_val `, respectively. Then, repeat the string `dup_val` number of times and store the result with the variable name `data`. +Print `data`. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_and_environment/hello_world/string_duplication/code_demo.py b/introduction_and_environment/hello_world/string_duplication/code_demo.py new file mode 100644 index 00000000..31c5fe0e --- /dev/null +++ b/introduction_and_environment/hello_world/string_duplication/code_demo.py @@ -0,0 +1,16 @@ +#Python3 code to demonstrate +# String Split including spaces +# using list comprehension + split() + +# initializing string +test_string = "GfG is Best" + +# printing original string +print("The original string : " + str(test_string)) + +# using list comprehension + split() +# String Split including spaces +res = [i for j in test_string.split() for i in (j, ' ')][:-1] + +# print result +print("The list without omitting spaces : " + str(res)) \ No newline at end of file diff --git a/introduction_and_environment/hello_world/string_duplication/solution/solution.py b/introduction_and_environment/hello_world/string_duplication/solution/solution.py index c14ef9ae..feff16e9 100644 --- a/introduction_and_environment/hello_world/string_duplication/solution/solution.py +++ b/introduction_and_environment/hello_world/string_duplication/solution/solution.py @@ -1,5 +1,5 @@ -# Code your solution here -string_1 = input() -dup_val = int(input()) -result = string_1 * dup_val +# Code your solution here +string_1 = input() +dup_val = int(input()) +result = string_1 * dup_val print(result) \ No newline at end of file diff --git a/introduction_and_environment/hello_world/string_duplication/solution/test_solution.py b/introduction_and_environment/hello_world/string_duplication/solution/test_solution.py index a4e082c3..75c09ce7 100644 --- a/introduction_and_environment/hello_world/string_duplication/solution/test_solution.py +++ b/introduction_and_environment/hello_world/string_duplication/solution/test_solution.py @@ -1,24 +1,24 @@ - - -def test_solution(monkeypatch): - x=['Charlie',5] - index=-1 - ret_val= None - - def f(): - nonlocal x - nonlocal index - index+=1 - return x[index] - - def g(num): - nonlocal ret_val - ret_val=num - - monkeypatch.setattr('builtins.input',f) - monkeypatch.setattr('builtins.print',g) - - import solution - assert solution.string_1=='Charlie' - assert solution.dup_val==5 - + + +def test_solution(monkeypatch): + x=['Charlie',5] + index=-1 + ret_val= None + + def f(): + nonlocal x + nonlocal index + index+=1 + return x[index] + + def g(num): + nonlocal ret_val + ret_val=num + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.string_1=='Charlie' + assert solution.dup_val==5 + diff --git a/introduction_and_environment/hello_world/string_duplication/string_1 = str(input()).py b/introduction_and_environment/hello_world/string_duplication/string_1 = str(input()).py new file mode 100644 index 00000000..a36e6f0c --- /dev/null +++ b/introduction_and_environment/hello_world/string_duplication/string_1 = str(input()).py @@ -0,0 +1,9 @@ +string_1 = str(input()) +dup_val = int(input()) + +data = string_1 * dup_val + +data_2 = [i for r in data.split() for i in (r, f'\n')[:-1]] + + +print(data_2) \ No newline at end of file diff --git a/introduction_and_environment/hello_world/type_change/README.md b/introduction_and_environment/hello_world/type_change/README.md index 9bfef873..a50698c5 100644 --- a/introduction_and_environment/hello_world/type_change/README.md +++ b/introduction_and_environment/hello_world/type_change/README.md @@ -1,16 +1,16 @@ -# Type Change - -## Motivation -There are multiple methods that will change the data type of a variable's value. - -## Problem Description -Write a python script that contains 2 variables, `object_1` and `object_2`, containing a float and string representation of a number, respectively. -Convert `object_1` to a string. -Convert `object_2` to an integer. -Print `object_1` and `object_2`. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Type Change + +## Motivation +There are multiple methods that will change the data type of a variable's value. + +## Problem Description +Write a python script that contains 2 variables, `object_1` and `object_2`, containing a float and string representation of a number, respectively. +Convert `object_1` to a string. +Convert `object_2` to an integer. +Print `object_1` and `object_2`. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_and_environment/hello_world/type_change/solution/solution.py b/introduction_and_environment/hello_world/type_change/solution/solution.py index e609d6e2..81f26da2 100644 --- a/introduction_and_environment/hello_world/type_change/solution/solution.py +++ b/introduction_and_environment/hello_world/type_change/solution/solution.py @@ -1,8 +1,8 @@ -# Code your solution here -object_1 = 100.0 -object_2 = "99" - -object_change_1 = str(object_1) -object_change_2 = int(object_2) - +# Code your solution here +object_1 = 100.0 +object_2 = "99" + +object_change_1 = str(object_1) +object_change_2 = int(object_2) + print(object_change_1, object_change_2) \ No newline at end of file diff --git a/introduction_and_environment/hello_world/type_change/solution/test_solution.py b/introduction_and_environment/hello_world/type_change/solution/test_solution.py index 3fb3181c..6a92a44b 100644 --- a/introduction_and_environment/hello_world/type_change/solution/test_solution.py +++ b/introduction_and_environment/hello_world/type_change/solution/test_solution.py @@ -1,16 +1,16 @@ - -def test_solution(monkeypatch): - ret_val1 = None - ret_val2 = None - - def g(num1, num2): - nonlocal ret_val1 - nonlocal ret_val2 - ret_val1 = num1 - ret_val2 = num2 - - monkeypatch.setattr('builtins.print',g) - - import solution - assert type(solution.object_1) == float and type(solution.object_2) == str + +def test_solution(monkeypatch): + ret_val1 = None + ret_val2 = None + + def g(num1, num2): + nonlocal ret_val1 + nonlocal ret_val2 + ret_val1 = num1 + ret_val2 = num2 + + monkeypatch.setattr('builtins.print',g) + + import solution + assert type(solution.object_1) == float and type(solution.object_2) == str assert type(ret_val1) == str and type(ret_val2) == int \ No newline at end of file diff --git a/introduction_and_environment/hello_world/type_check/README.md b/introduction_and_environment/hello_world/type_check/README.md index 5212042e..99d9b6ef 100644 --- a/introduction_and_environment/hello_world/type_check/README.md +++ b/introduction_and_environment/hello_world/type_check/README.md @@ -1,15 +1,15 @@ -# Type Check - -## Motivation -Python provides us with the type() method to check the data type of a variable. - -## Problem Description -Write a Python script that asks the user to input any 2 values, and store the values in two variables, `input_1` and `input_2 `. -Check the type or each, and store the results in two new variables, `result_1` and `result_2`. -Print both results. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Type Check + +## Motivation +Python provides us with the type() method to check the data type of a variable. + +## Problem Description +Write a Python script that asks the user to input any 2 values, and store the values in two variables, `input_1` and `input_2 `. +Check the type or each, and store the results in two new variables, `result_1` and `result_2`. +Print both results. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_and_environment/hello_world/type_check/solution/first_num.py b/introduction_and_environment/hello_world/type_check/solution/first_num.py new file mode 100644 index 00000000..e8ec8186 --- /dev/null +++ b/introduction_and_environment/hello_world/type_check/solution/first_num.py @@ -0,0 +1,5 @@ +first_num = int(input()) +second_num = int(input()) +third_num = int(input()) +average = (first_num + second_num + third_num) / 3 +print(average) diff --git a/introduction_and_environment/hello_world/type_check/solution/solution.py b/introduction_and_environment/hello_world/type_check/solution/solution.py index 846ba132..bcd36479 100644 --- a/introduction_and_environment/hello_world/type_check/solution/solution.py +++ b/introduction_and_environment/hello_world/type_check/solution/solution.py @@ -1,6 +1,6 @@ -# Code your solution here -input_1 = int(input()) -input_2 = float(input()) -result_1 = type(input_1) -result_2 = type(input_2) +# Code your solution here +input_1 = int(input()) +input_2 = float(input()) +result_1 = type(input_1) +result_2 = type(input_2) print(result_1, result_2) \ No newline at end of file diff --git a/introduction_and_environment/hello_world/type_check/solution/test_solution.py b/introduction_and_environment/hello_world/type_check/solution/test_solution.py index 32f24a7c..33b41850 100644 --- a/introduction_and_environment/hello_world/type_check/solution/test_solution.py +++ b/introduction_and_environment/hello_world/type_check/solution/test_solution.py @@ -1,29 +1,29 @@ - - -def test_solution(monkeypatch): - x = [1,2.0] - index = -1 - ret_val1= None - ret_val2= None - - def f(): - nonlocal index - nonlocal x - index += 1 - return x[index] - - def g(num1,num2): - nonlocal ret_val1 - nonlocal ret_val2 - ret_val1=num1 - ret_val2=num2 - - monkeypatch.setattr('builtins.input',f) - monkeypatch.setattr('builtins.print',g) - - import solution - assert solution.input_1==1 - assert solution.input_2==2.0 - - - + + +def test_solution(monkeypatch): + x = [1,2.0] + index = -1 + ret_val1= None + ret_val2= None + + def f(): + nonlocal index + nonlocal x + index += 1 + return x[index] + + def g(num1,num2): + nonlocal ret_val1 + nonlocal ret_val2 + ret_val1=num1 + ret_val2=num2 + + monkeypatch.setattr('builtins.input',f) + monkeypatch.setattr('builtins.print',g) + + import solution + assert solution.input_1==1 + assert solution.input_2==2.0 + + + diff --git a/introduction_and_environment/hello_world/user_input/README.md b/introduction_and_environment/hello_world/user_input/README.md index 45e01090..d40256f4 100644 --- a/introduction_and_environment/hello_world/user_input/README.md +++ b/introduction_and_environment/hello_world/user_input/README.md @@ -1,11 +1,11 @@ -# User Input - -## Problem Description -Write a Python script in *solution.py* that asks the user for 3 numbers. Store these numbers in the variable names `first_num`, `second_num` and `third_num` respectively. -Print the average of these 3 numbers. - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# User Input + +## Problem Description +Write a Python script in *solution.py* that asks the user for 3 numbers. Store these numbers in the variable names `first_num`, `second_num` and `third_num` respectively. +Print the average of these 3 numbers. + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_and_environment/hello_world/user_input/solution/solution.py b/introduction_and_environment/hello_world/user_input/solution/solution.py index 6026fa45..95e78c11 100644 --- a/introduction_and_environment/hello_world/user_input/solution/solution.py +++ b/introduction_and_environment/hello_world/user_input/solution/solution.py @@ -1,6 +1,6 @@ -# Code your solution here -first_num = input() -second_num = input() -third_num = input() -average = sum(first_num, second_num, third_num) / 3 +# Code your solution here +first_num = input() +second_num = input() +third_num = input() +average = sum(first_num, second_num, third_num) / 3 print(average) \ No newline at end of file diff --git a/introduction_and_environment/hello_world/user_input/solution/test_solution.py b/introduction_and_environment/hello_world/user_input/solution/test_solution.py index 60b80b0d..77094257 100644 --- a/introduction_and_environment/hello_world/user_input/solution/test_solution.py +++ b/introduction_and_environment/hello_world/user_input/solution/test_solution.py @@ -1,10 +1,10 @@ - -def test_solution(monkeypatch): - print_val = 0 - def f(x): - nonlocal print_val - print_val = x - monkeypatch.setattr('builtins.input', lambda: 100) - monkeypatch.setattr('builtins.print', f) - import solution - assert solution.first_num == solution.second_num == solution.third_num == print_val == 100 + +def test_solution(monkeypatch): + print_val = 0 + def f(x): + nonlocal print_val + print_val = x + monkeypatch.setattr('builtins.input', lambda: 100) + monkeypatch.setattr('builtins.print', f) + import solution + assert solution.first_num == solution.second_num == solution.third_num == print_val == 100 diff --git a/introduction_and_environment/unix_and_bash/README.md b/introduction_and_environment/unix_and_bash/README.md index cc329603..b0dfe365 100644 --- a/introduction_and_environment/unix_and_bash/README.md +++ b/introduction_and_environment/unix_and_bash/README.md @@ -1,9 +1,9 @@ -# Exercises for UNIX and Bash - -| Exercise ID | Exercise | -|:-----------:|:--------:| -| easy_e1 | [Basic Commands](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/unix_and_bash/basic_commands) | -| easy_e2 | [Commands With Options](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/unix_and_bash/commands_with_options) | -| easy_e3 | [Commands With Options 2](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/unix_and_bash/commands_with_options_2) | -| medium_e1 | [Intermediate Commands](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/unix_and_bash/intermediate_commands) | -| hard_e1 | [Star Wars](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/unix_and_bash/star_wars) | +# Exercises for UNIX and Bash + +| Exercise ID | Exercise | +|:-----------:|:--------:| +| easy_e1 | [Basic Commands](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/unix_and_bash/basic_commands) | +| easy_e2 | [Commands With Options](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/unix_and_bash/commands_with_options) | +| easy_e3 | [Commands With Options 2](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/unix_and_bash/commands_with_options_2) | +| medium_e1 | [Intermediate Commands](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/unix_and_bash/intermediate_commands) | +| hard_e1 | [Star Wars](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/unix_and_bash/star_wars) | diff --git a/introduction_and_environment/unix_and_bash/basic_commands/README.md b/introduction_and_environment/unix_and_bash/basic_commands/README.md index f193339e..c75df63f 100644 --- a/introduction_and_environment/unix_and_bash/basic_commands/README.md +++ b/introduction_and_environment/unix_and_bash/basic_commands/README.md @@ -1,40 +1,40 @@ -# Command Basics - -## Problem Description -The list below contains a number of variable names, as well as a text description of many different **bash** commands. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. - -Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! - -For example: -Variable: `ONE` -Description: command used when you remember the name of a **bash** command, but forget what it does - -In *solution.py* you would write: -```python -ONE = 'man' -``` - -Variable: `TWO` -Description: View the contents of a directory - -Variable: `THREE` -Description: Create a new directory (ignore any necessary arguments or options) - -Variable: `FOUR` -Description: Create an empty file - -Variable: `FIVE` -Description: Create a copy of a file, or with an option, copy the contents of a directory - -Variable: `SIX` -Description: Change the name of a file or directory - -Variable: `SEVEN` -Description: Delete a file, or with an additional option, a directory - - -## Testing -* to test your solution, type 'pytest' within the **solutions** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory +# Command Basics + +## Problem Description +The list below contains a number of variable names, as well as a text description of many different **bash** commands. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. + +Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! + +For example: +Variable: `ONE` +Description: command used when you remember the name of a **bash** command, but forget what it does + +In *solution.py* you would write: +```python +ONE = 'man' +``` + +Variable: `TWO` +Description: View the contents of a directory + +Variable: `THREE` +Description: Create a new directory (ignore any necessary arguments or options) + +Variable: `FOUR` +Description: Create an empty file + +Variable: `FIVE` +Description: Create a copy of a file, or with an option, copy the contents of a directory + +Variable: `SIX` +Description: Change the name of a file or directory + +Variable: `SEVEN` +Description: Delete a file, or with an additional option, a directory + + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory diff --git a/introduction_and_environment/unix_and_bash/basic_commands/solution/solution.py b/introduction_and_environment/unix_and_bash/basic_commands/solution/solution.py index 0b3cb78f..3ee16c90 100644 --- a/introduction_and_environment/unix_and_bash/basic_commands/solution/solution.py +++ b/introduction_and_environment/unix_and_bash/basic_commands/solution/solution.py @@ -1,10 +1,10 @@ -# The first has been completed for you... -ONE = 'man' - -# Assign the correct strings below -TWO = 'ls' -THREE = 'mkdir' -FOUR = 'touch' -FIVE = 'cp' -SIX = 'mv' -SEVEN = 'rm' +# The first has been completed for you... +ONE = 'man' + +# Assign the correct strings below +TWO = 'ls' +THREE = 'mkdir' +FOUR = 'touch' +FIVE = 'cp' +SIX = 'mv' +SEVEN = 'rm' diff --git a/introduction_and_environment/unix_and_bash/basic_commands/solution/test_solution.py b/introduction_and_environment/unix_and_bash/basic_commands/solution/test_solution.py index 3b836482..a36502a0 100644 --- a/introduction_and_environment/unix_and_bash/basic_commands/solution/test_solution.py +++ b/introduction_and_environment/unix_and_bash/basic_commands/solution/test_solution.py @@ -1,14 +1,14 @@ -import solution -from hashlib import sha1 - -def test_solution(): - def hashed_output(submission): - return sha1(submission.encode()).hexdigest() - - assert hashed_output(solution.ONE) == '8175e3c8753aeb1696959f72ede260ebf3ea14c5' - assert hashed_output(solution.TWO) == 'ebfdec641529d4b59a54e18f8b0e9730f85939fb' - assert hashed_output(solution.THREE) == '90868ffdfa3a8bd99cfa9f642349e60cf84e057a' - assert hashed_output(solution.FOUR) == 'f4d1f0193879cba82d65c5752c4ba5cbb43a7188' - assert hashed_output(solution.FIVE) == '3f81e91d69a8a61ffbf19297eb0791ad54ce5690' - assert hashed_output(solution.SIX) == '362d60cb3f6f8e96c37edac670b7618963233e07' - assert hashed_output(solution.SEVEN) == '5cd7e29c88170aa3f16281e0dbf5772c137f6d8d' +import solution +from hashlib import sha1 + +def test_solution(): + def hashed_output(submission): + return sha1(submission.encode()).hexdigest() + + assert hashed_output(solution.ONE) == '8175e3c8753aeb1696959f72ede260ebf3ea14c5' + assert hashed_output(solution.TWO) == 'ebfdec641529d4b59a54e18f8b0e9730f85939fb' + assert hashed_output(solution.THREE) == '90868ffdfa3a8bd99cfa9f642349e60cf84e057a' + assert hashed_output(solution.FOUR) == 'f4d1f0193879cba82d65c5752c4ba5cbb43a7188' + assert hashed_output(solution.FIVE) == '3f81e91d69a8a61ffbf19297eb0791ad54ce5690' + assert hashed_output(solution.SIX) == '362d60cb3f6f8e96c37edac670b7618963233e07' + assert hashed_output(solution.SEVEN) == '5cd7e29c88170aa3f16281e0dbf5772c137f6d8d' diff --git a/introduction_and_environment/unix_and_bash/commands_with_options/README.md b/introduction_and_environment/unix_and_bash/commands_with_options/README.md index 4f318ae0..c85e56a3 100644 --- a/introduction_and_environment/unix_and_bash/commands_with_options/README.md +++ b/introduction_and_environment/unix_and_bash/commands_with_options/README.md @@ -1,42 +1,42 @@ -# Command Basics 2 - -## Problem Description -The list below contains a number of variable names, as well as a text description of many different **bash** commands. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. These are harder than the first few, as they may contain additional arguments to be included with the command name. - -Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! - -For example: -Variable: `ONE` -Description: Command used when you remember the name of a **bash** command named "test", but forget what it does - -In *solution.py* you would write: -```python -EXAMPLE = 'man test' -``` - -Variable: `ONE` -Description: Navigate from the current directory to a new directory, named "exercises" - -Variable: `TWO` -Description: View our shell's current directory location - -Variable: `THREE` -Description: View the *entire* contents of a file named "textfile.txt" in our terminal - -Variable: `FOUR` -Description: View *only* the last 10 lines of a file named "textfile.txt" - -Variable: `FIVE` -Description: View the contents of the current directory, including hidden files - -Variable: `SIX` -Description: View *only* the first 10 lines of a file named "textfile.txt" - -Variable: `SEVEN` -Description: Create a copy of a file, named "stackdata.json" with the name "stockdata.json - -## Testing -* to test your solution, type 'pytest' within the **solutions** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory +# Command Basics 2 + +## Problem Description +The list below contains a number of variable names, as well as a text description of many different **bash** commands. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. These are harder than the first few, as they may contain additional arguments to be included with the command name. + +Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! + +For example: +Variable: `ONE` +Description: Command used when you remember the name of a **bash** command named "test", but forget what it does + +In *solution.py* you would write: +```python +EXAMPLE = 'man test' +``` + +Variable: `ONE` +Description: Navigate from the current directory to a new directory, named "exercises" + +Variable: `TWO` +Description: View our shell's current directory location + +Variable: `THREE` +Description: View the *entire* contents of a file named "textfile.txt" in our terminal + +Variable: `FOUR` +Description: View *only* the last 10 lines of a file named "textfile.txt" + +Variable: `FIVE` +Description: View the contents of the current directory, including hidden files + +Variable: `SIX` +Description: View *only* the first 10 lines of a file named "textfile.txt" + +Variable: `SEVEN` +Description: Create a copy of a file, named "stackdata.json" with the name "stockdata.json + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory diff --git a/introduction_and_environment/unix_and_bash/commands_with_options/solution/solution.py b/introduction_and_environment/unix_and_bash/commands_with_options/solution/solution.py index 5109eeca..dae1ff7d 100644 --- a/introduction_and_environment/unix_and_bash/commands_with_options/solution/solution.py +++ b/introduction_and_environment/unix_and_bash/commands_with_options/solution/solution.py @@ -1,9 +1,9 @@ -# Assign the correct strings below - -ONE = 'cd exercises' -TWO = 'pwd' -THREE = 'cat textfile.txt' -FOUR = 'tail textfile.txt' -FIVE = 'ls -a' -SIX = 'head textfile.txt' -SEVEN = 'cp stackdata.json stockdata.json' +# Assign the correct strings below + +ONE = 'cd exercises' +TWO = 'pwd' +THREE = 'cat textfile.txt' +FOUR = 'tail textfile.txt' +FIVE = 'ls -a' +SIX = 'head textfile.txt' +SEVEN = 'cp stackdata.json stockdata.json' diff --git a/introduction_and_environment/unix_and_bash/commands_with_options/solution/test_solution.py b/introduction_and_environment/unix_and_bash/commands_with_options/solution/test_solution.py index 8a526669..f248dfd5 100644 --- a/introduction_and_environment/unix_and_bash/commands_with_options/solution/test_solution.py +++ b/introduction_and_environment/unix_and_bash/commands_with_options/solution/test_solution.py @@ -1,14 +1,14 @@ -import solution -from hashlib import sha1 - -def test_solution(): - def hashed_output(submission): - return sha1(submission.encode()).hexdigest() - - assert hashed_output(solution.ONE) == '8f7096f862f1c01437d435b1440612fc5907d76c' - assert hashed_output(solution.TWO) == '37fa265330ad83eaa879efb1e2db6380896cf639' - assert hashed_output(solution.THREE) == 'aa2ba3db8235609f178bac463e31eb01c1a9e711' - assert hashed_output(solution.FOUR) == 'e52fb413040572fbc243c74e29760dd3c9867aea' - assert hashed_output(solution.FIVE) == 'fda17aa65051cb574d5f9f1cc4c7f3ddbc931735' - assert hashed_output(solution.SIX) == '3441d7e6e51f18f214ae7f2ca9c6a87fe14deea8' - assert hashed_output(solution.SEVEN) == 'e120eb80c4d1bc2976a2176f8dd83d0a795725b6' +import solution +from hashlib import sha1 + +def test_solution(): + def hashed_output(submission): + return sha1(submission.encode()).hexdigest() + + assert hashed_output(solution.ONE) == '8f7096f862f1c01437d435b1440612fc5907d76c' + assert hashed_output(solution.TWO) == '37fa265330ad83eaa879efb1e2db6380896cf639' + assert hashed_output(solution.THREE) == 'aa2ba3db8235609f178bac463e31eb01c1a9e711' + assert hashed_output(solution.FOUR) == 'e52fb413040572fbc243c74e29760dd3c9867aea' + assert hashed_output(solution.FIVE) == 'fda17aa65051cb574d5f9f1cc4c7f3ddbc931735' + assert hashed_output(solution.SIX) == '3441d7e6e51f18f214ae7f2ca9c6a87fe14deea8' + assert hashed_output(solution.SEVEN) == 'e120eb80c4d1bc2976a2176f8dd83d0a795725b6' diff --git a/introduction_and_environment/unix_and_bash/commands_with_options_2/README.md b/introduction_and_environment/unix_and_bash/commands_with_options_2/README.md index 60ec42b7..983c89ad 100644 --- a/introduction_and_environment/unix_and_bash/commands_with_options_2/README.md +++ b/introduction_and_environment/unix_and_bash/commands_with_options_2/README.md @@ -1,39 +1,39 @@ -# Command Basics 3 - -## Problem Description -The list below contains a number of variable names, as well as a text description of many different **bash** commands. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. These are harder than the first few, as they may contain additional arguments to be included with the command name. - -Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! - -For example: -Variable: `ONE` -Description: Command used when you remember the name of a **bash** command named "test", but forget what it does - -In *solution.py* you would write: -```python -EXAMPLE = 'man test' -``` - -Variable: `ONE` -Description: Search the contents of a file named "book.txt" for occurrences of the pattern "elephant" - -Variable: `TWO` -Description: Move a file named "notes.txt" from the current directory to a directory named "newdir" - -Variable: `THREE` -Description: Search all files in a directory named "testdir" for the pattern "string" - -Variable: `FOUR` -Description: Delete an empty directory named "empty" - -Variable: `FIVE` -Description: Navigate to our user's home directory (regardless of user's name) - -Variable: `SIX` -Description: Delete a non-empty directory, named "Downloads", as well as all of its contents - -## Testing -* to test your solution, type 'pytest' within the **solutions** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory +# Command Basics 3 + +## Problem Description +The list below contains a number of variable names, as well as a text description of many different **bash** commands. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. These are harder than the first few, as they may contain additional arguments to be included with the command name. + +Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! + +For example: +Variable: `ONE` +Description: Command used when you remember the name of a **bash** command named "test", but forget what it does + +In *solution.py* you would write: +```python +EXAMPLE = 'man test' +``` + +Variable: `ONE` +Description: Search the contents of a file named "book.txt" for occurrences of the pattern "elephant" + +Variable: `TWO` +Description: Move a file named "notes.txt" from the current directory to a directory named "newdir" + +Variable: `THREE` +Description: Search all files in a directory named "testdir" for the pattern "string" + +Variable: `FOUR` +Description: Delete an empty directory named "empty" + +Variable: `FIVE` +Description: Navigate to our user's home directory (regardless of user's name) + +Variable: `SIX` +Description: Delete a non-empty directory, named "Downloads", as well as all of its contents + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory diff --git a/introduction_and_environment/unix_and_bash/commands_with_options_2/solution/solution.py b/introduction_and_environment/unix_and_bash/commands_with_options_2/solution/solution.py index 16560a46..9f870190 100644 --- a/introduction_and_environment/unix_and_bash/commands_with_options_2/solution/solution.py +++ b/introduction_and_environment/unix_and_bash/commands_with_options_2/solution/solution.py @@ -1,8 +1,8 @@ -# Assign the correct strings below - -ONE = 'grep elephant book.txt' -TWO = 'mv notes.txt newdir' -THREE = 'grep -r string testdir' -FOUR = 'rm -d empty' -FIVE = 'cd' -SIX = 'rm -r Downloads' +# Assign the correct strings below + +ONE = 'grep elephant book.txt' +TWO = 'mv notes.txt newdir' +THREE = 'grep -r string testdir' +FOUR = 'rm -d empty' +FIVE = 'cd' +SIX = 'rm -r Downloads' diff --git a/introduction_and_environment/unix_and_bash/commands_with_options_2/solution/test_solution.py b/introduction_and_environment/unix_and_bash/commands_with_options_2/solution/test_solution.py index b4343a1e..99154d43 100644 --- a/introduction_and_environment/unix_and_bash/commands_with_options_2/solution/test_solution.py +++ b/introduction_and_environment/unix_and_bash/commands_with_options_2/solution/test_solution.py @@ -1,13 +1,13 @@ -import solution -from hashlib import sha1 - -def test_solution(): - def hashed_output(submission): - return sha1(submission.encode()).hexdigest() - - assert hashed_output(solution.ONE) == '1efc27c5f639a389de478c3d2572063bf0b303f0' - assert hashed_output(solution.TWO) == '649b0028d6ad29d4b0099e6cd227551c19e75c68' - assert hashed_output(solution.THREE) == '3c8f2856c8f42eb101b62632788173107a857a88' - assert hashed_output(solution.FOUR) == 'e6e017e01c6c83091049d013bfad653f3fb75d27' - assert hashed_output(solution.FIVE) == '034778198a045c1ed80be271cdd029b76874f6fc' - assert hashed_output(solution.SIX) == '2c98f52bc8dc4272160f7ee35acfff3aa3f63676' +import solution +from hashlib import sha1 + +def test_solution(): + def hashed_output(submission): + return sha1(submission.encode()).hexdigest() + + assert hashed_output(solution.ONE) == '1efc27c5f639a389de478c3d2572063bf0b303f0' + assert hashed_output(solution.TWO) == '649b0028d6ad29d4b0099e6cd227551c19e75c68' + assert hashed_output(solution.THREE) == '3c8f2856c8f42eb101b62632788173107a857a88' + assert hashed_output(solution.FOUR) == 'e6e017e01c6c83091049d013bfad653f3fb75d27' + assert hashed_output(solution.FIVE) == '034778198a045c1ed80be271cdd029b76874f6fc' + assert hashed_output(solution.SIX) == '2c98f52bc8dc4272160f7ee35acfff3aa3f63676' diff --git a/introduction_and_environment/unix_and_bash/intermediate_commands/README.md b/introduction_and_environment/unix_and_bash/intermediate_commands/README.md index c0803a79..f849b1ea 100644 --- a/introduction_and_environment/unix_and_bash/intermediate_commands/README.md +++ b/introduction_and_environment/unix_and_bash/intermediate_commands/README.md @@ -1,36 +1,36 @@ -# Bash Operators - -## Problem Description -The list below contains a number of variable names, as well as a text description of many different **bash** commands and operators that must be used. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. These are harder than the first few, and may need bash operators to pass data between commands or alter execution. - -Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! - -For example: -Variable: `EXAMPLE` -Description: Commands to list the contents of a directory, and then search that output for any files ending in ".py" - -In *solution.py* you would write: -```python -EXAMPLE = 'ls | grep .py' -``` - -Variable: `ONE` -Description: Commands to create a directory named "testdir" and then navigate into that directory, if creation was successful - -Variable: `TWO` -Description: Commands to view the entire contents of a file named "textfile.txt" and search that output for occurrences of the word "and" - -Variable: `THREE` -Description: Commands to view the contents of the current directory, and then *append* that output to an existing text file named "contents.txt" - -Variable: `FOUR` -Description: Commands to *either* navigate into a directory named "current", or, if that command failed, create the directory (but not bother with navigation afterwards) - -Variable: `FIVE` -Description: Commands to view our command line's current directory path, and then write that output to a *new* file called "current_path.txt" - -## Testing -* to test your solution, type 'pytest' within the **solutions** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory +# Bash Operators + +## Problem Description +The list below contains a number of variable names, as well as a text description of many different **bash** commands and operators that must be used. Assign the name of the correct **bash** command, as a lowercase Python string, to each corresponding variable. These are harder than the first few, and may need bash operators to pass data between commands or alter execution. + +Unnecessary spaces will result in failed tests, make sure not to leave trailing spaces in the solutions! + +For example: +Variable: `EXAMPLE` +Description: Commands to list the contents of a directory, and then search that output for any files ending in ".py" + +In *solution.py* you would write: +```python +EXAMPLE = 'ls | grep .py' +``` + +Variable: `ONE` +Description: Commands to create a directory named "testdir" and then navigate into that directory, if creation was successful + +Variable: `TWO` +Description: Commands to view the entire contents of a file named "textfile.txt" and search that output for occurrences of the word "and" + +Variable: `THREE` +Description: Commands to view the contents of the current directory, and then *append* that output to an existing text file named "contents.txt" + +Variable: `FOUR` +Description: Commands to *either* navigate into a directory named "current", or, if that command failed, create the directory (but not bother with navigation afterwards) + +Variable: `FIVE` +Description: Commands to view our command line's current directory path, and then write that output to a *new* file called "current_path.txt" + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory in this directory diff --git a/introduction_and_environment/unix_and_bash/intermediate_commands/solution/solution.py b/introduction_and_environment/unix_and_bash/intermediate_commands/solution/solution.py index 30e1f6f9..e9e48b3d 100644 --- a/introduction_and_environment/unix_and_bash/intermediate_commands/solution/solution.py +++ b/introduction_and_environment/unix_and_bash/intermediate_commands/solution/solution.py @@ -1,7 +1,7 @@ - -# Assign the correct strings below -ONE = 'mkdir testdir && cd testdir' -TWO = 'cat textfile.txt | grep and' -THREE = 'ls >> contents.txt' -FOUR = 'cd current || mkdir current' -FIVE = 'pwd > current_path.txt' + +# Assign the correct strings below +ONE = 'mkdir testdir && cd testdir' +TWO = 'cat textfile.txt | grep and' +THREE = 'ls >> contents.txt' +FOUR = 'cd current || mkdir current' +FIVE = 'pwd > current_path.txt' diff --git a/introduction_and_environment/unix_and_bash/intermediate_commands/solution/test_solution.py b/introduction_and_environment/unix_and_bash/intermediate_commands/solution/test_solution.py index 510d9558..4fb95a29 100644 --- a/introduction_and_environment/unix_and_bash/intermediate_commands/solution/test_solution.py +++ b/introduction_and_environment/unix_and_bash/intermediate_commands/solution/test_solution.py @@ -1,12 +1,12 @@ -import solution -from hashlib import sha1 - -def test_solution(): - def hashed_output(submission): - return sha1(submission.encode()).hexdigest() - - assert hashed_output(solution.ONE) == '8d90393573522285c5d58b437885ccbb9a9daced' - assert hashed_output(solution.TWO) == '6862d5dbed79ab65cf70e169232ad10ea4575373' - assert hashed_output(solution.THREE) == 'a0d69d758be9fd8be90f83bb3c51c3539c105bdf' - assert hashed_output(solution.FOUR) == 'e31d24b0d08a712dd0c8155c15259958e43dcd04' - assert hashed_output(solution.FIVE) == 'd07f1559dea4f7fb83c1a2b0c506646542856acb' +import solution +from hashlib import sha1 + +def test_solution(): + def hashed_output(submission): + return sha1(submission.encode()).hexdigest() + + assert hashed_output(solution.ONE) == '8d90393573522285c5d58b437885ccbb9a9daced' + assert hashed_output(solution.TWO) == '6862d5dbed79ab65cf70e169232ad10ea4575373' + assert hashed_output(solution.THREE) == 'a0d69d758be9fd8be90f83bb3c51c3539c105bdf' + assert hashed_output(solution.FOUR) == 'e31d24b0d08a712dd0c8155c15259958e43dcd04' + assert hashed_output(solution.FIVE) == 'd07f1559dea4f7fb83c1a2b0c506646542856acb' diff --git a/introduction_and_environment/unix_and_bash/star_wars/README.md b/introduction_and_environment/unix_and_bash/star_wars/README.md index d096b655..a5751096 100644 --- a/introduction_and_environment/unix_and_bash/star_wars/README.md +++ b/introduction_and_environment/unix_and_bash/star_wars/README.md @@ -1,49 +1,49 @@ -# Command Line Workflow: Star Wars - -## Spoilers: Star Wars Episode IV: A New Hope -* This exercise contains spoilers for the 1977 film Star Wars (retitled as "Star Wars: Episode IV: A New Hope). While it has been over four decades, you have been warned. - -## Problem Description -* Navigating your computer through terminal is an extremely important, practically required skill to be a programmer. The following is an assignment where you will make / delete folders and files to help you get used to navigating your terminal and manipulating your files with bash commands. Perform all commands within the *solution* directory (there is no `solution.py` here, you'll be creating all necessary files.) - -### Use bash to perform the following commands, in order: -* Navigate into the "star_wars" folder -* Create a folder called "the_empire" -* Create a folder called "the_rebellion" -* Make the following folders - * "tatooine" - * "millenium_falcon" - * "death_star" - * "x_wing" - * "tie_fighter" -* Make the following text files (.txt) ***Make Sure to have the .txt extension on these files*** - * "luke_skywalker" - * "old_man_ben" - * "han_solo" - * "chewbacca" - * "leia_organa" - * "darth_vader" - * "emperor_palpatine" -* Open the darth_vader text file and add the text "Darth Vader" - * **Bonus points** if you add the text without opening the file -* Move the emperor and darth vader into the folder "the_empire" -* Move "luke_skywalker" and "old_man_ben" to the "tatooine" folder -* Luke has found out old man ben is actually Obi Wan Kenobi. Change the name of "old_man_ben" to "obi_wan_kenobi" -* Now they need to escape tatooine. Move "han_solo" and "chewbacca" into "tatooine" -* While all this is happening the Sith lords are sitting nice and cozy inside their giant metal moon. Move "darth_vader" and "emperor_palpatine" inside the "death_star" -* Back on tatooine the characters get on the fastest ship in the galaxy and take off to save the princess. Move all four files from tatooine into the millenium falcon -* The princess is also on the death star. Move "leia_organa" to the "death_star" -* Our heroes sneak onto the Death Star. Move all the files inside the "millenium_falcon" onto the "death_star" -* They found the princess! but in the process Obi Wan was struck down by Darth Vader. Delete the "obi_wan_kenobi" file -* Our other heroes retreat in anger. Move Luke, Leia, Han, and Chewbacca into the "millenium_falcon" -* Alright the rebels have regrouped and come up with a plan to destroy the death star. Luke gets into an x-wing to use his sweet piloting skills. Move "leia" into the "the_rebellion" directory. Move Luke into the "x_wing" -* Vader, also a legendary pilot, gets into the tie fighter to defend the death star. Move "darth_vader" out of the death_star and into the "tie_fighter" -* Luke uses those sweet farm boy desert skills and fires some torpedos into the core of the death star, destroying it. **CAREFULLY** Delete the folder "death_star" - * Remember that deletion of a directory is a high-stake operation - * **DO NOT** do this without checking your command for correctness - -## Testing -* to test your solution, type 'pytest' within the **solutions** subdirectory. It will use python to make sure your final directory/file structure is correct. - -## Submission -* Submit your answer in the *solution* subdirectory in this directory. Your "answer" will be the structure of the folders/files you created at the end of the exercise +# Command Line Workflow: Star Wars + +## Spoilers: Star Wars Episode IV: A New Hope +* This exercise contains spoilers for the 1977 film Star Wars (retitled as "Star Wars: Episode IV: A New Hope). While it has been over four decades, you have been warned. + +## Problem Description +* Navigating your computer through terminal is an extremely important, practically required skill to be a programmer. The following is an assignment where you will make / delete folders and files to help you get used to navigating your terminal and manipulating your files with bash commands. Perform all commands within the *solution* directory (there is no `solution.py` here, you'll be creating all necessary files.) + +### Use bash to perform the following commands, in order: +* Navigate into the "star_wars" folder +* Create a folder called "the_empire" +* Create a folder called "the_rebellion" +* Make the following folders + * "tatooine" + * "millenium_falcon" + * "death_star" + * "x_wing" + * "tie_fighter" +* Make the following text files (.txt) ***Make Sure to have the .txt extension on these files*** + * "luke_skywalker" + * "old_man_ben" + * "han_solo" + * "chewbacca" + * "leia_organa" + * "darth_vader" + * "emperor_palpatine" +* Open the darth_vader text file and add the text "Darth Vader" + * **Bonus points** if you add the text without opening the file +* Move the emperor and darth vader into the folder "the_empire" +* Move "luke_skywalker" and "old_man_ben" to the "tatooine" folder +* Luke has found out old man ben is actually Obi Wan Kenobi. Change the name of "old_man_ben" to "obi_wan_kenobi" +* Now they need to escape tatooine. Move "han_solo" and "chewbacca" into "tatooine" +* While all this is happening the Sith lords are sitting nice and cozy inside their giant metal moon. Move "darth_vader" and "emperor_palpatine" inside the "death_star" +* Back on tatooine the characters get on the fastest ship in the galaxy and take off to save the princess. Move all four files from tatooine into the millenium falcon +* The princess is also on the death star. Move "leia_organa" to the "death_star" +* Our heroes sneak onto the Death Star. Move all the files inside the "millenium_falcon" onto the "death_star" +* They found the princess! but in the process Obi Wan was struck down by Darth Vader. Delete the "obi_wan_kenobi" file +* Our other heroes retreat in anger. Move Luke, Leia, Han, and Chewbacca into the "millenium_falcon" +* Alright the rebels have regrouped and come up with a plan to destroy the death star. Luke gets into an x-wing to use his sweet piloting skills. Move "leia" into the "the_rebellion" directory. Move Luke into the "x_wing" +* Vader, also a legendary pilot, gets into the tie fighter to defend the death star. Move "darth_vader" out of the death_star and into the "tie_fighter" +* Luke uses those sweet farm boy desert skills and fires some torpedos into the core of the death star, destroying it. **CAREFULLY** Delete the folder "death_star" + * Remember that deletion of a directory is a high-stake operation + * **DO NOT** do this without checking your command for correctness + +## Testing +* to test your solution, type 'pytest' within the **solutions** subdirectory. It will use python to make sure your final directory/file structure is correct. + +## Submission +* Submit your answer in the *solution* subdirectory in this directory. Your "answer" will be the structure of the folders/files you created at the end of the exercise diff --git a/introduction_and_environment/unix_and_bash/star_wars/solution/test_solution.py b/introduction_and_environment/unix_and_bash/star_wars/solution/test_solution.py index 7eb4bd0e..8b761282 100644 --- a/introduction_and_environment/unix_and_bash/star_wars/solution/test_solution.py +++ b/introduction_and_environment/unix_and_bash/star_wars/solution/test_solution.py @@ -1,16 +1,16 @@ -import os - -def test_solution(): - solution = {} - for dir_name, subdir_list, file_list in os.walk("star_wars"): - solution[dir_name] = set(file_list) - if not solution.get("star_wars/tatooine"): - solution.update({'star_wars/tatooine': set(), 'star_wars/the_empire': set()}) - assert solution == {'star_wars': set(), - 'star_wars/tatooine': set(), - 'star_wars/tie_fighter': {'darth_vader.txt'}, - 'star_wars/x_wing': {'luke_skywalker.txt'}, - 'star_wars/millenium_falcon': {'han_solo.txt', 'chewbacca.txt'}, - 'star_wars/the_rebellion': {'leia_organa.txt'}, - 'star_wars/the_empire': set() - } +import os + +def test_solution(): + solution = {} + for dir_name, subdir_list, file_list in os.walk("star_wars"): + solution[dir_name] = set(file_list) + if not solution.get("star_wars/tatooine"): + solution.update({'star_wars/tatooine': set(), 'star_wars/the_empire': set()}) + assert solution == {'star_wars': set(), + 'star_wars/tatooine': set(), + 'star_wars/tie_fighter': {'darth_vader.txt'}, + 'star_wars/x_wing': {'luke_skywalker.txt'}, + 'star_wars/millenium_falcon': {'han_solo.txt', 'chewbacca.txt'}, + 'star_wars/the_rebellion': {'leia_organa.txt'}, + 'star_wars/the_empire': set() + } diff --git a/introduction_to_python/README.md b/introduction_to_python/README.md index 14a0ff41..60bec9bc 100644 --- a/introduction_to_python/README.md +++ b/introduction_to_python/README.md @@ -1,8 +1,8 @@ -# Exercise Organization - -## Exercise Sections -* Functions -* Recursive Functions -* Classes -* Class Protocols -* MVC Architecture +# Exercise Organization + +## Exercise Sections +* Functions +* Recursive Functions +* Classes +* Class Protocols +* MVC Architecture diff --git a/introduction_to_python/assessment/README.md b/introduction_to_python/assessment/README.md index 7ca00c41..67f1c862 100644 --- a/introduction_to_python/assessment/README.md +++ b/introduction_to_python/assessment/README.md @@ -1,86 +1,86 @@ -# Week 2 Project - Vending Machine Assignment - -The goal of this assessment is to put together all the concepts learned until now into a cumulative project that implements the basic software of a vending machine. - -## Problem Description - -You are hired as a software engineer at VendMachineCo, a start-up that sells vending machines. You are tasked to implement the basic functionality to allow vending machines to be deployed at university campuses. Your manager is non-technical and has described the task with the bullet points below. - -### Vending Machine -* Vending machines contain Coca-Cola, Sprite, and Mountain Dew - * Initialized to contain 5 of each type soda costing $2 each - * Vending machines can hold a maximum of 10 bottles per type of soda - -### Soda Shop -* Soda shop contains the quantity for each of the sodas they create - * Initialized to contain 10 of each soda costing $1 each -* Soda shop has the capacity to create sodas -* Soda shop has the capacity to change the cost for each of the sodas in their shop - -### Student -* A student has an ID-card with money on it - * Initialized to $10 -* A student has the capacity to add funds to their ID card -* A student has the capacity to buy sodas from a vending machine - * This money is taken from the student funds and added to the university funds - -### University Administrator -* University has funds that they receieve from students and spend on sodas - * Initialized to $100 -* University has the capacity to enroll students into the university, providing them a new ID-card -* University has the capacity to change the cost for each of the sodas in the vending machine -* University has the capacity to refill the vending machine by buying sodas from the soda shop - * This money is taken from the university funds and added to the soda shop funds - -## Specification - -Thankfully your team lead has a technical background. He has turned the description above into a formalized specification for a Python program described below. - -Write a program `vending_machine.py` that reads a file called `input.txt` that will contain a sequence of the commands below (one per line) and output corresponding messages (one per line) in `output.txt`. You are provided with the code to read and write to the files. You are also provided a command line interface to test your code. - -| Method | Input | Output | Description | -|:-----------:|:----------:|:------:|:-----------:| -| `enroll_student` | `student` | * `'{student} Enrolled.'` if `student` successfully enrolled
* `'Error: {student} Already Enrolled.'` if `student` already enrolled | Enrolls the student `student` into the university | -| `add_funds` | `student`, `funds` | * `'${funds} Added to {student}.'` if funds successfully added
* `'Error: {student} Not Enrolled.'` if `student` is not enrolled | Adds `funds` funds to the student `student` | -| `buy_soda` | `student`, `soda` | * `'{student} Bought {soda}.'` if sucessfully bought soda
* `'Error: Insufficient Funds.'` if `student` does not have enough `funds`
* `Error: {student} Not Enrolled.` if `student` is not enrolled | Buys the soda `soda` for student `student` | -| `create_soda` | `soda`, `amount` | * `'{amount} {soda} Created.'` | Creates `{amount}` `{soda}` in the soda shop. | -| `set_machine_cost` | `soda`, `cost` | * `'Vending Machine cost for {soda} is ${cost}.'` | Sets the cost of `soda` to be `cost` for the vending machine | -| `set_shop_cost` | `soda`, `cost` | * `'Soda Shop cost for {soda} is ${cost}.'` | Sets the cost of `soda` to be `cost` for the soda shop| -| `get_student_funds` | `student` | * `'{student} has ${funds}.'` if succesfully get student funds
* `'Error: {student} Not Enrolled.'` if `student` is not enrolled | Gets the `funds` from student `student` | -| `get_university_funds` | `None` | * `'University has ${funds}.'` | Gets the `funds` for the university | -| `get_vending_machine_stock` | `None` | * `'Vending Machine has {amount} Coca-Cola, {amount} Sprite, and {amount} Mountain-Dew.'` | Gets the stock remaining in the vending machine | -| `get_shop_stock` | `None` | * `'Soda Shop has {amount} Coca-Cola, {amount} Sprite, and {amount} Mountain-Dew.'` | Gets the stock remaining in the soda shop | -| `refill_vm` | `{soda} {amount}, {soda} {amount}, {soda} {amount}` | * `'Error: Shop out of soda.'` if shop is out of a specific soda
* `'Error: Insufficient Funds.'` if university does not have enough funds
* `'Error: Over Max Quantity.'` if refilling makes machine have more than 10 of any kind of `soda`
* `'Refilled Machine with {amount} {soda}, {amount} {soda}, {amount} {soda}.'` if successfully refilled machine
| Refills the vending machine with the amounts specified.
You should check each condition in the given order. | -| `quit` | `None` | * `None` | Exits the program - -### Types -| Name | Type | Description | -|:------:|:-----:|:-----------:| -| `student` | `string` | The name of the student | -| `funds` | `float` | Representing funds for a student or university | -| `cost` | `float` | Representing the cost of a soda for the university or soda shop | -| `soda` | `string` (1 of `Coca-Cola`, `Sprite`, `Mountain-Dew`) | A string specifying the kind of soda | -| `amount` | `int` | Representing the quantity of a soda for the university or soda shop | - -## Example - -| input.txt | output.txt | -|:------:|:------:| -| enroll_student Wasif | Wasif Enrolled. | -| add_funds Wasif 100 | $100.0 Added to Wasif. | -| buy_soda Wasif Sprite | Wasif Bought Sprite. | -| get_university_funds | University has $102.0. | -| get_student_funds Wasif | Wasif has $108.0. | -| get_vending_machine_stock | Vending Machine has 5 Coca-Cola, 4 Sprite, and 5 Mountain Dew. | -| quit | | - - -## Testing -We have provided 3 basic tests located in the `testing/` subdirectory called `test_1`, `test_2`, and `test_3` that test for basic functionality. These contain sample `input.txt` to run your code with, as well as `expected_output.txt` to check your answer against. Be sure to do comprehensive testing on your own as the majority of our tests are hidden from you that will test all sorts of interactions. - -## FAQ -* Can you pass in invalid types to input? - * No, you can assume only valid types will be passed in - * Ie. cannot call `add_funds Wasif some_string` or `add_funds 10 10` -* Does the output have to match *exactly*? - * Yes, incorrect capitalizations and missing punctuation will be considered errors +# Week 2 Project - Vending Machine Assignment + +The goal of this assessment is to put together all the concepts learned until now into a cumulative project that implements the basic software of a vending machine. + +## Problem Description + +You are hired as a software engineer at VendMachineCo, a start-up that sells vending machines. You are tasked to implement the basic functionality to allow vending machines to be deployed at university campuses. Your manager is non-technical and has described the task with the bullet points below. + +### Vending Machine +* Vending machines contain Coca-Cola, Sprite, and Mountain Dew + * Initialized to contain 5 of each type soda costing $2 each + * Vending machines can hold a maximum of 10 bottles per type of soda + +### Soda Shop +* Soda shop contains the quantity for each of the sodas they create + * Initialized to contain 10 of each soda costing $1 each +* Soda shop has the capacity to create sodas +* Soda shop has the capacity to change the cost for each of the sodas in their shop + +### Student +* A student has an ID-card with money on it + * Initialized to $10 +* A student has the capacity to add funds to their ID card +* A student has the capacity to buy sodas from a vending machine + * This money is taken from the student funds and added to the university funds + +### University Administrator +* University has funds that they receieve from students and spend on sodas + * Initialized to $100 +* University has the capacity to enroll students into the university, providing them a new ID-card +* University has the capacity to change the cost for each of the sodas in the vending machine +* University has the capacity to refill the vending machine by buying sodas from the soda shop + * This money is taken from the university funds and added to the soda shop funds + +## Specification + +Thankfully your team lead has a technical background. He has turned the description above into a formalized specification for a Python program described below. + +Write a program `vending_machine.py` that reads a file called `input.txt` that will contain a sequence of the commands below (one per line) and output corresponding messages (one per line) in `output.txt`. You are provided with the code to read and write to the files. You are also provided a command line interface to test your code. + +| Method | Input | Output | Description | +|:-----------:|:----------:|:------:|:-----------:| +| `enroll_student` | `student` | * `'{student} Enrolled.'` if `student` successfully enrolled
* `'Error: {student} Already Enrolled.'` if `student` already enrolled | Enrolls the student `student` into the university | +| `add_funds` | `student`, `funds` | * `'${funds} Added to {student}.'` if funds successfully added
* `'Error: {student} Not Enrolled.'` if `student` is not enrolled | Adds `funds` funds to the student `student` | +| `buy_soda` | `student`, `soda` | * `'{student} Bought {soda}.'` if sucessfully bought soda
* `'Error: Insufficient Funds.'` if `student` does not have enough `funds`
* `Error: {student} Not Enrolled.` if `student` is not enrolled | Buys the soda `soda` for student `student` | +| `create_soda` | `soda`, `amount` | * `'{amount} {soda} Created.'` | Creates `{amount}` `{soda}` in the soda shop. | +| `set_machine_cost` | `soda`, `cost` | * `'Vending Machine cost for {soda} is ${cost}.'` | Sets the cost of `soda` to be `cost` for the vending machine | +| `set_shop_cost` | `soda`, `cost` | * `'Soda Shop cost for {soda} is ${cost}.'` | Sets the cost of `soda` to be `cost` for the soda shop| +| `get_student_funds` | `student` | * `'{student} has ${funds}.'` if succesfully get student funds
* `'Error: {student} Not Enrolled.'` if `student` is not enrolled | Gets the `funds` from student `student` | +| `get_university_funds` | `None` | * `'University has ${funds}.'` | Gets the `funds` for the university | +| `get_vending_machine_stock` | `None` | * `'Vending Machine has {amount} Coca-Cola, {amount} Sprite, and {amount} Mountain-Dew.'` | Gets the stock remaining in the vending machine | +| `get_shop_stock` | `None` | * `'Soda Shop has {amount} Coca-Cola, {amount} Sprite, and {amount} Mountain-Dew.'` | Gets the stock remaining in the soda shop | +| `refill_vm` | `{soda} {amount}, {soda} {amount}, {soda} {amount}` | * `'Error: Shop out of soda.'` if shop is out of a specific soda
* `'Error: Insufficient Funds.'` if university does not have enough funds
* `'Error: Over Max Quantity.'` if refilling makes machine have more than 10 of any kind of `soda`
* `'Refilled Machine with {amount} {soda}, {amount} {soda}, {amount} {soda}.'` if successfully refilled machine
| Refills the vending machine with the amounts specified.
You should check each condition in the given order. | +| `quit` | `None` | * `None` | Exits the program + +### Types +| Name | Type | Description | +|:------:|:-----:|:-----------:| +| `student` | `string` | The name of the student | +| `funds` | `float` | Representing funds for a student or university | +| `cost` | `float` | Representing the cost of a soda for the university or soda shop | +| `soda` | `string` (1 of `Coca-Cola`, `Sprite`, `Mountain-Dew`) | A string specifying the kind of soda | +| `amount` | `int` | Representing the quantity of a soda for the university or soda shop | + +## Example + +| input.txt | output.txt | +|:------:|:------:| +| enroll_student Wasif | Wasif Enrolled. | +| add_funds Wasif 100 | $100.0 Added to Wasif. | +| buy_soda Wasif Sprite | Wasif Bought Sprite. | +| get_university_funds | University has $102.0. | +| get_student_funds Wasif | Wasif has $108.0. | +| get_vending_machine_stock | Vending Machine has 5 Coca-Cola, 4 Sprite, and 5 Mountain Dew. | +| quit | | + + +## Testing +We have provided 3 basic tests located in the `testing/` subdirectory called `test_1`, `test_2`, and `test_3` that test for basic functionality. These contain sample `input.txt` to run your code with, as well as `expected_output.txt` to check your answer against. Be sure to do comprehensive testing on your own as the majority of our tests are hidden from you that will test all sorts of interactions. + +## FAQ +* Can you pass in invalid types to input? + * No, you can assume only valid types will be passed in + * Ie. cannot call `add_funds Wasif some_string` or `add_funds 10 10` +* Does the output have to match *exactly*? + * Yes, incorrect capitalizations and missing punctuation will be considered errors diff --git a/introduction_to_python/assessment/solution/.model_solution.py b/introduction_to_python/assessment/solution/.model_solution.py index e2059f77..7f594494 100644 --- a/introduction_to_python/assessment/solution/.model_solution.py +++ b/introduction_to_python/assessment/solution/.model_solution.py @@ -1,258 +1,258 @@ -class VendingMachine: - max_cap = 10 - def __init__(self): - self._sodas = {"Coca-Cola": 5, - "Sprite": 5, - "Mountain-Dew": 5} - self._soda_costs = {"Coca-Cola": 2.0, - "Sprite": 2.0, - "Mountain-Dew": 2.0} - - def set_machine_cost(self, soda, cost): - self._soda_costs[soda] = cost - return f'Vending Machine cost for {soda} is ${cost}.' - - def get_vending_machine_stock(self): - Coca_Cola_amt = self._sodas["Coca-Cola"] - Sprite_amt = self._sodas["Sprite"] - Mountain_Dew_amt = self._sodas["Mountain-Dew"] - return f'Vending Machine has {Coca_Cola_amt} Coca-Cola, {Sprite_amt} Sprite, and {Mountain_Dew_amt} Mountain-Dew.' - - - -class SodaShop: - def __init__(self): - self._inventory = {"Coca-Cola": 10, - "Sprite": 10, - "Mountain-Dew": 10} - self._inventory_costs = {"Coca-Cola": 1.0, - "Sprite": 1.0, - "Mountain-Dew": 1.0} - - def set_shop_cost(self, soda, cost): - self._inventory_costs[soda] = cost - return f'Soda Shop cost for {soda} is ${cost}.' - - def create_soda(self, soda, amount): - self._inventory[soda] += amount - return f'{amount} {soda} Created.' - - def get_shop_stock(self): - Coca_Cola_amt = self._inventory["Coca-Cola"] - Sprite_amt = self._inventory["Sprite"] - Mountain_Dew_amt = self._inventory["Mountain-Dew"] - return f'Soda Shop has {Coca_Cola_amt} Coca-Cola, {Sprite_amt} Sprite, and {Mountain_Dew_amt} Mountain-Dew.' - -class Student: - def __init__(self, name="", id=None): - self._name = name - self._id = id - self._id_card_funds = 10 - - def __str__(self): - return self._name - -class UniversityAdministrator: - def __init__(self, institution_name=""): - self._institution_name = institution_name - self._funds = 100.0 - self._students = {} - self._student_count = 0 - self._vending_machine = VendingMachine() - - def enroll_student(self, student): - namelst = [s._name for s in self._students.values()] - if student in namelst: - return f'Error: {student} Already Enrolled.' - else: - self._student_count += 1 - new_student = Student(student, self._student_count) - self._students[self._student_count] = new_student - return f'{student} Enrolled.' - - def add_funds(self, student, funds): - for s in self._students.values(): - if s._name == student: - s._id_card_funds += funds - return f'${funds} Added to {student}.' - return f'Error: {student} Not Enrolled.' - - def buy_soda(self, student, soda): - for s in self._students.values(): - if s._name == student: - if s._id_card_funds >= self._vending_machine._soda_costs[soda]: - s._id_card_funds -= self._vending_machine._soda_costs[soda] - self._vending_machine._sodas[soda] -= 1 - self._funds += self._vending_machine._soda_costs[soda] - return f'{student} Bought {soda}.' - return f'Error: Insufficient Funds.' - return f'Error: {student} Not Enrolled.' - - def get_student_funds(self, student): - for s in self._students.values(): - if s._name == student: - funds = s._id_card_funds - return f'{student} has ${funds}.' - return f'Error: {student} Not Enrolled.' - - def get_university_funds(self): - funds = self._funds - return f'University has ${funds}.' - - def refill_vm(self, soda1, amount1, soda2, amount2, soda3, amount3, shop): - num_soda1 = self._vending_machine._sodas[soda1] + amount1 - num_soda2 = self._vending_machine._sodas[soda2] + amount2 - num_soda3 = self._vending_machine._sodas[soda3] + amount3 - cost = amount1 * shop._inventory_costs[soda1] - cost += amount2 * shop._inventory_costs[soda2] - cost += amount3 * shop._inventory_costs[soda3] - if shop._inventory[soda1] < amount1 or shop._inventory[soda2] < amount2 or shop._inventory[soda3] < amount3: - return f'Error: Shop out of soda.' - elif self._funds < cost: - return f'Error: Insufficient Funds.' - elif num_soda1 > self._vending_machine.max_cap or num_soda2 > self._vending_machine.max_cap or num_soda3 > self._vending_machine.max_cap: - return f'Error: Over Max Quantity.' - else: - self._vending_machine._sodas[soda1] = num_soda1 - self._vending_machine._sodas[soda2] = num_soda2 - self._vending_machine._sodas[soda3] = num_soda3 - - shop._inventory[soda1] -= amount1 - shop._inventory[soda2] -= amount2 - shop._inventory[soda3] -= amount3 - - self._funds -= cost - return f'Refilled Machine with {amount1} {soda1}, {amount2} {soda2}, {amount3} {soda3}.' - -# To test your code: navigate to the solution folder in your terminal -# and type 'python3 vending_machine.py ../testing/test_n/input.txt' -# where n is replaced by the number of the test. - -# You may also test your code using the command line by navigating to the -# solution folder in your terminal and typing 'python3 vending_machine.py'. - -# Do not modify this code. -if __name__ == "__main__": - from sys import argv - if len(argv) == 2 and 'input.txt' in argv[1]: - file_path = argv[1] - test_num = argv[1][-11] - input_file = open(f'{file_path}', "r") - output_file = open(f'../testing/test_{test_num}/output.txt', "w") - university = UniversityAdministrator() - shop = SodaShop() - output_lines = [] - try: - while (line := input_file.readline()) != 'quit': - words = line.split() - function = words[0] - if function == "enroll_student": - output_lines.append(university.enroll_student(words[1])) - elif function == "add_funds": - output_lines.append(university.add_funds(words[1], float(words[2]))) - elif function == "buy_soda": - output_lines.append(university.buy_soda(words[1], words[2])) - elif function == "create_soda": - output_lines.append(shop.create_soda(words[1], int(words[2]))) - elif function == "set_machine_cost": - output_lines.append(university._vending_machine.set_machine_cost(words[1], float(words[2]))) - elif function == "set_shop_cost": - output_lines.append(shop.set_shop_cost(words[1], float(words[2]))) - elif function == "get_student_funds": - output_lines.append(university.get_student_funds(words[1])) - elif function == "get_university_funds": - output_lines.append(university.get_university_funds()) - elif function == "get_vending_machine_stock": - output_lines.append(university._vending_machine.get_vending_machine_stock()) - elif function == "get_shop_stock": - output_lines.append(shop.get_shop_stock()) - elif function == "refill_vm": - output_lines.append(university.refill_vm(words[1], int(words[2]), words[3], int(words[4]), words[5], int(words[6]), shop)) - output_lines.append("\n") - output_file.writelines(output_lines[:-1]) - except: - output_lines.append("Something went wrong!") - output_file.writelines(output_lines) - - elif len(argv) == 1: - output_file = open(f'output_command_line.txt', "w") - university = UniversityAdministrator() - shop = SodaShop() - output_lines = [] - - while (function := input("Enter a command: ")) != 'quit': - try: - if function == "enroll_student": - student = input("Enter the name of the student to be enrolled: ") - ret_string = university.enroll_student(student) - output_lines.append(ret_string) - print(ret_string) - elif function == "add_funds": - student = input("Enter the name of the student to add funds to: ") - amount = input("Enter the amount of funds to add: ") - ret_string = university.add_funds(student, float(amount)) - output_lines.append(ret_string) - print(ret_string) - elif function == "buy_soda": - student = input("Enter the name of the student who wishes to buy a soda: ") - amount = input(f'Enter the type of soda {student} wishes to buy: ') - ret_string = university.buy_soda(student, amount) - output_lines.append(ret_string) - print(ret_string) - elif function == "create_soda": - soda = input("Enter the type of soda to be created: ") - amount = input(f'Enter the amount of {soda} to be created: ') - ret_string = shop.create_soda(soda, int(amount)) - output_lines.append(ret_string) - print(ret_string) - elif function == "set_machine_cost": - soda = input("Enter the type of soda: ") - cost = input(f'Enter the new cost for {soda}: ') - ret_string = university._vending_machine.set_machine_cost(soda, float(cost)) - output_lines.append(ret_string) - print(ret_string) - elif function == "set_shop_cost": - soda = input("Enter the type of soda: ") - cost = input(f'Enter the new cost for {soda}: ') - ret_string = shop.set_shop_cost(soda, float(cost)) - output_lines.append(ret_string) - print(ret_string) - elif function == "get_student_funds": - student = input("Enter the name of the student: ") - ret_string = university.get_student_funds(student) - output_lines.append(ret_string) - print(ret_string) - elif function == "get_university_funds": - ret_string = university.get_university_funds() - output_lines.append(ret_string) - print(ret_string) - elif function == "get_vending_machine_stock": - ret_string = university._vending_machine.get_vending_machine_stock() - output_lines.append(ret_string) - print(ret_string) - elif function == "get_shop_stock": - ret_string = shop.get_shop_stock() - output_lines.append(ret_string) - print(ret_string) - elif function == "refill_vm": - soda1 = input("Enter the first type of soda: ") - amount1 = input(f"Enter the amount of {soda1} you wish to refill: ") - soda2 = input("Enter the second type of soda: ") - amount2 = input(f"Enter the amount of {soda2} you wish to refill: ") - soda3 = input("Enter the third type of soda: ") - amount3 = input(f"Enter the amount of {soda3} you wish to refill: ") - if (sodas := sorted([soda1, soda2, soda3])) != ["Coca-Cola", "Mountain-Dew", "Sprite"]: - print("The given sodas are not valid. Sodas must be one of Coca-Cola, Sprite, and Mountain-Dew. Please try again!") - else: - ret_string = university.refill_vm(soda1, int(amount1), soda2, int(amount2), soda3, int(amount3), shop) - output_lines.append(ret_string) - print(ret_string) - else: - print(f'{function} is not a valid command. Please try again!') - continue - output_lines.append("\n") - except: - print("Something went wront! Please try again!") - output_file.writelines(output_lines[:-1]) - else: +class VendingMachine: + max_cap = 10 + def __init__(self): + self._sodas = {"Coca-Cola": 5, + "Sprite": 5, + "Mountain-Dew": 5} + self._soda_costs = {"Coca-Cola": 2.0, + "Sprite": 2.0, + "Mountain-Dew": 2.0} + + def set_machine_cost(self, soda, cost): + self._soda_costs[soda] = cost + return f'Vending Machine cost for {soda} is ${cost}.' + + def get_vending_machine_stock(self): + Coca_Cola_amt = self._sodas["Coca-Cola"] + Sprite_amt = self._sodas["Sprite"] + Mountain_Dew_amt = self._sodas["Mountain-Dew"] + return f'Vending Machine has {Coca_Cola_amt} Coca-Cola, {Sprite_amt} Sprite, and {Mountain_Dew_amt} Mountain-Dew.' + + + +class SodaShop: + def __init__(self): + self._inventory = {"Coca-Cola": 10, + "Sprite": 10, + "Mountain-Dew": 10} + self._inventory_costs = {"Coca-Cola": 1.0, + "Sprite": 1.0, + "Mountain-Dew": 1.0} + + def set_shop_cost(self, soda, cost): + self._inventory_costs[soda] = cost + return f'Soda Shop cost for {soda} is ${cost}.' + + def create_soda(self, soda, amount): + self._inventory[soda] += amount + return f'{amount} {soda} Created.' + + def get_shop_stock(self): + Coca_Cola_amt = self._inventory["Coca-Cola"] + Sprite_amt = self._inventory["Sprite"] + Mountain_Dew_amt = self._inventory["Mountain-Dew"] + return f'Soda Shop has {Coca_Cola_amt} Coca-Cola, {Sprite_amt} Sprite, and {Mountain_Dew_amt} Mountain-Dew.' + +class Student: + def __init__(self, name="", id=None): + self._name = name + self._id = id + self._id_card_funds = 10 + + def __str__(self): + return self._name + +class UniversityAdministrator: + def __init__(self, institution_name=""): + self._institution_name = institution_name + self._funds = 100.0 + self._students = {} + self._student_count = 0 + self._vending_machine = VendingMachine() + + def enroll_student(self, student): + namelst = [s._name for s in self._students.values()] + if student in namelst: + return f'Error: {student} Already Enrolled.' + else: + self._student_count += 1 + new_student = Student(student, self._student_count) + self._students[self._student_count] = new_student + return f'{student} Enrolled.' + + def add_funds(self, student, funds): + for s in self._students.values(): + if s._name == student: + s._id_card_funds += funds + return f'${funds} Added to {student}.' + return f'Error: {student} Not Enrolled.' + + def buy_soda(self, student, soda): + for s in self._students.values(): + if s._name == student: + if s._id_card_funds >= self._vending_machine._soda_costs[soda]: + s._id_card_funds -= self._vending_machine._soda_costs[soda] + self._vending_machine._sodas[soda] -= 1 + self._funds += self._vending_machine._soda_costs[soda] + return f'{student} Bought {soda}.' + return f'Error: Insufficient Funds.' + return f'Error: {student} Not Enrolled.' + + def get_student_funds(self, student): + for s in self._students.values(): + if s._name == student: + funds = s._id_card_funds + return f'{student} has ${funds}.' + return f'Error: {student} Not Enrolled.' + + def get_university_funds(self): + funds = self._funds + return f'University has ${funds}.' + + def refill_vm(self, soda1, amount1, soda2, amount2, soda3, amount3, shop): + num_soda1 = self._vending_machine._sodas[soda1] + amount1 + num_soda2 = self._vending_machine._sodas[soda2] + amount2 + num_soda3 = self._vending_machine._sodas[soda3] + amount3 + cost = amount1 * shop._inventory_costs[soda1] + cost += amount2 * shop._inventory_costs[soda2] + cost += amount3 * shop._inventory_costs[soda3] + if shop._inventory[soda1] < amount1 or shop._inventory[soda2] < amount2 or shop._inventory[soda3] < amount3: + return f'Error: Shop out of soda.' + elif self._funds < cost: + return f'Error: Insufficient Funds.' + elif num_soda1 > self._vending_machine.max_cap or num_soda2 > self._vending_machine.max_cap or num_soda3 > self._vending_machine.max_cap: + return f'Error: Over Max Quantity.' + else: + self._vending_machine._sodas[soda1] = num_soda1 + self._vending_machine._sodas[soda2] = num_soda2 + self._vending_machine._sodas[soda3] = num_soda3 + + shop._inventory[soda1] -= amount1 + shop._inventory[soda2] -= amount2 + shop._inventory[soda3] -= amount3 + + self._funds -= cost + return f'Refilled Machine with {amount1} {soda1}, {amount2} {soda2}, {amount3} {soda3}.' + +# To test your code: navigate to the solution folder in your terminal +# and type 'python3 vending_machine.py ../testing/test_n/input.txt' +# where n is replaced by the number of the test. + +# You may also test your code using the command line by navigating to the +# solution folder in your terminal and typing 'python3 vending_machine.py'. + +# Do not modify this code. +if __name__ == "__main__": + from sys import argv + if len(argv) == 2 and 'input.txt' in argv[1]: + file_path = argv[1] + test_num = argv[1][-11] + input_file = open(f'{file_path}', "r") + output_file = open(f'../testing/test_{test_num}/output.txt', "w") + university = UniversityAdministrator() + shop = SodaShop() + output_lines = [] + try: + while (line := input_file.readline()) != 'quit': + words = line.split() + function = words[0] + if function == "enroll_student": + output_lines.append(university.enroll_student(words[1])) + elif function == "add_funds": + output_lines.append(university.add_funds(words[1], float(words[2]))) + elif function == "buy_soda": + output_lines.append(university.buy_soda(words[1], words[2])) + elif function == "create_soda": + output_lines.append(shop.create_soda(words[1], int(words[2]))) + elif function == "set_machine_cost": + output_lines.append(university._vending_machine.set_machine_cost(words[1], float(words[2]))) + elif function == "set_shop_cost": + output_lines.append(shop.set_shop_cost(words[1], float(words[2]))) + elif function == "get_student_funds": + output_lines.append(university.get_student_funds(words[1])) + elif function == "get_university_funds": + output_lines.append(university.get_university_funds()) + elif function == "get_vending_machine_stock": + output_lines.append(university._vending_machine.get_vending_machine_stock()) + elif function == "get_shop_stock": + output_lines.append(shop.get_shop_stock()) + elif function == "refill_vm": + output_lines.append(university.refill_vm(words[1], int(words[2]), words[3], int(words[4]), words[5], int(words[6]), shop)) + output_lines.append("\n") + output_file.writelines(output_lines[:-1]) + except: + output_lines.append("Something went wrong!") + output_file.writelines(output_lines) + + elif len(argv) == 1: + output_file = open(f'output_command_line.txt', "w") + university = UniversityAdministrator() + shop = SodaShop() + output_lines = [] + + while (function := input("Enter a command: ")) != 'quit': + try: + if function == "enroll_student": + student = input("Enter the name of the student to be enrolled: ") + ret_string = university.enroll_student(student) + output_lines.append(ret_string) + print(ret_string) + elif function == "add_funds": + student = input("Enter the name of the student to add funds to: ") + amount = input("Enter the amount of funds to add: ") + ret_string = university.add_funds(student, float(amount)) + output_lines.append(ret_string) + print(ret_string) + elif function == "buy_soda": + student = input("Enter the name of the student who wishes to buy a soda: ") + amount = input(f'Enter the type of soda {student} wishes to buy: ') + ret_string = university.buy_soda(student, amount) + output_lines.append(ret_string) + print(ret_string) + elif function == "create_soda": + soda = input("Enter the type of soda to be created: ") + amount = input(f'Enter the amount of {soda} to be created: ') + ret_string = shop.create_soda(soda, int(amount)) + output_lines.append(ret_string) + print(ret_string) + elif function == "set_machine_cost": + soda = input("Enter the type of soda: ") + cost = input(f'Enter the new cost for {soda}: ') + ret_string = university._vending_machine.set_machine_cost(soda, float(cost)) + output_lines.append(ret_string) + print(ret_string) + elif function == "set_shop_cost": + soda = input("Enter the type of soda: ") + cost = input(f'Enter the new cost for {soda}: ') + ret_string = shop.set_shop_cost(soda, float(cost)) + output_lines.append(ret_string) + print(ret_string) + elif function == "get_student_funds": + student = input("Enter the name of the student: ") + ret_string = university.get_student_funds(student) + output_lines.append(ret_string) + print(ret_string) + elif function == "get_university_funds": + ret_string = university.get_university_funds() + output_lines.append(ret_string) + print(ret_string) + elif function == "get_vending_machine_stock": + ret_string = university._vending_machine.get_vending_machine_stock() + output_lines.append(ret_string) + print(ret_string) + elif function == "get_shop_stock": + ret_string = shop.get_shop_stock() + output_lines.append(ret_string) + print(ret_string) + elif function == "refill_vm": + soda1 = input("Enter the first type of soda: ") + amount1 = input(f"Enter the amount of {soda1} you wish to refill: ") + soda2 = input("Enter the second type of soda: ") + amount2 = input(f"Enter the amount of {soda2} you wish to refill: ") + soda3 = input("Enter the third type of soda: ") + amount3 = input(f"Enter the amount of {soda3} you wish to refill: ") + if (sodas := sorted([soda1, soda2, soda3])) != ["Coca-Cola", "Mountain-Dew", "Sprite"]: + print("The given sodas are not valid. Sodas must be one of Coca-Cola, Sprite, and Mountain-Dew. Please try again!") + else: + ret_string = university.refill_vm(soda1, int(amount1), soda2, int(amount2), soda3, int(amount3), shop) + output_lines.append(ret_string) + print(ret_string) + else: + print(f'{function} is not a valid command. Please try again!') + continue + output_lines.append("\n") + except: + print("Something went wront! Please try again!") + output_file.writelines(output_lines[:-1]) + else: print('Must call with valid path to "input.txt"') \ No newline at end of file diff --git a/introduction_to_python/assessment/solution/vending_machine.py b/introduction_to_python/assessment/solution/vending_machine.py index 495b07df..a5ac9a46 100644 --- a/introduction_to_python/assessment/solution/vending_machine.py +++ b/introduction_to_python/assessment/solution/vending_machine.py @@ -1,186 +1,186 @@ -class VendingMachine: - def __init__(self): - pass - - def set_machine_cost(self, soda, cost): - pass - - def get_vending_machine_stock(self): - pass - - -class SodaShop: - def __init__(self): - pass - - def set_shop_cost(self, soda, cost): - pass - - def create_soda(self, soda, amount): - pass - - def get_shop_stock(self): - pass - -class Student: - def __init__(self, name="", id=None): - pass - - def __str__(self): - pass - -class UniversityAdministrator: - def __init__(self, institution_name=""): - pass - - def enroll_student(self, student): - pass - - def add_funds(self, student, funds): - pass - - def buy_soda(self, student, soda): - pass - - def get_student_funds(self, student): - pass - - def get_university_funds(self): - pass - - def refill_vm(self, soda1, amount1, soda2, amount2, soda3, amount3, shop): - pass - - -# To test your code: navigate to the solution folder in your terminal -# and type 'python3 vending_machine.py ../testing/test_n/input.txt' -# where n is replaced by the number of the test. - -# You may also test your code using the command line by navigating to the -# solution folder in your terminal and typing 'python3 vending_machine.py'. - -# Do not modify this code. -if __name__ == "__main__": - from sys import argv - if len(argv) == 2 and 'input.txt' in argv[1]: - file_path = argv[1] - test_num = argv[1][-11] - input_file = open(f'{file_path}', "r") - output_file = open(f'../testing/test_{test_num}/output.txt', "w") - university = UniversityAdministrator() - shop = SodaShop() - output_lines = [] - try: - while (line := input_file.readline()) != 'quit': - words = line.split() - function = words[0] - if function == "enroll_student": - output_lines.append(university.enroll_student(words[1])) - elif function == "add_funds": - output_lines.append(university.add_funds(words[1], float(words[2]))) - elif function == "buy_soda": - output_lines.append(university.buy_soda(words[1], words[2])) - elif function == "create_soda": - output_lines.append(shop.create_soda(words[1], int(words[2]))) - elif function == "set_machine_cost": - output_lines.append(university._vending_machine.set_machine_cost(words[1], float(words[2]))) - elif function == "set_shop_cost": - output_lines.append(shop.set_shop_cost(words[1], float(words[2]))) - elif function == "get_student_funds": - output_lines.append(university.get_student_funds(words[1])) - elif function == "get_university_funds": - output_lines.append(university.get_university_funds()) - elif function == "get_vending_machine_stock": - output_lines.append(university._vending_machine.get_vending_machine_stock()) - elif function == "get_shop_stock": - output_lines.append(shop.get_shop_stock()) - elif function == "refill_vm": - output_lines.append(university.refill_vm(words[1], int(words[2]), words[3], int(words[4]), words[5], int(words[6]), shop)) - output_lines.append("\n") - output_file.writelines(output_lines[:-1]) - except: - output_lines.append("Something went wrong!") - output_file.writelines(output_lines) - - elif len(argv) == 1: - output_file = open(f'output_command_line.txt', "w") - university = UniversityAdministrator() - shop = SodaShop() - output_lines = [] - - while (function := input("Enter a command: ")) != 'quit': - try: - if function == "enroll_student": - student = input("Enter the name of the student to be enrolled: ") - ret_string = university.enroll_student(student) - output_lines.append(ret_string) - print(ret_string) - elif function == "add_funds": - student = input("Enter the name of the student to add funds to: ") - amount = input("Enter the amount of funds to add: ") - ret_string = university.add_funds(student, float(amount)) - output_lines.append(ret_string) - print(ret_string) - elif function == "buy_soda": - student = input("Enter the name of the student who wishes to buy a soda: ") - amount = input(f'Enter the type of soda {student} wishes to buy: ') - ret_string = university.buy_soda(student, amount) - output_lines.append(ret_string) - print(ret_string) - elif function == "create_soda": - soda = input("Enter the type of soda to be created: ") - amount = input(f'Enter the amount of {soda} to be created: ') - ret_string = shop.create_soda(soda, int(amount)) - output_lines.append(ret_string) - print(ret_string) - elif function == "set_machine_cost": - soda = input("Enter the type of soda: ") - cost = input(f'Enter the new cost for {soda}: ') - ret_string = university._vending_machine.set_machine_cost(soda, float(cost)) - output_lines.append(ret_string) - print(ret_string) - elif function == "set_shop_cost": - soda = input("Enter the type of soda: ") - cost = input(f'Enter the new cost for {soda}: ') - ret_string = shop.set_shop_cost(soda, float(cost)) - output_lines.append(ret_string) - print(ret_string) - elif function == "get_student_funds": - student = input("Enter the name of the student: ") - ret_string = university.get_student_funds(student) - output_lines.append(ret_string) - print(ret_string) - elif function == "get_university_funds": - ret_string = university.get_university_funds() - output_lines.append(ret_string) - print(ret_string) - elif function == "get_vending_machine_stock": - ret_string = university._vending_machine.get_vending_machine_stock() - output_lines.append(ret_string) - print(ret_string) - elif function == "get_shop_stock": - ret_string = shop.get_shop_stock() - output_lines.append(ret_string) - print(ret_string) - elif function == "refill_vm": - soda1 = input("Enter the first type of soda: ") - amount1 = input(f"Enter the amount of {soda1} you wish to refill: ") - soda2 = input("Enter the second type of soda: ") - amount2 = input(f"Enter the amount of {soda2} you wish to refill: ") - soda3 = input("Enter the third type of soda: ") - amount3 = input(f"Enter the amount of {soda3} you wish to refill: ") - if (sodas := sorted([soda1, soda2, soda3])) != ["Coca-Cola", "Mountain-Dew", "Sprite"]: - print("The given sodas are not valid. Sodas must be one of Coca-Cola, Sprite, and Mountain-Dew. Please try again!") - else: - ret_string = university.refill_vm(soda1, int(amount1), soda2, int(amount2), soda3, int(amount3), shop) - output_lines.append(ret_string) - print(ret_string) - else: - print(f'{function} is not a valid command. Please try again!') - continue - output_lines.append("\n") - except: - print("Something went wront! Please try again!") - output_file.writelines(output_lines[:-1]) - else: - print('Must call with valid path to "input.txt"') +class VendingMachine: + def __init__(self): + pass + + def set_machine_cost(self, soda, cost): + pass + + def get_vending_machine_stock(self): + pass + + +class SodaShop: + def __init__(self): + pass + + def set_shop_cost(self, soda, cost): + pass + + def create_soda(self, soda, amount): + pass + + def get_shop_stock(self): + pass + +class Student: + def __init__(self, name="", id=None): + pass + + def __str__(self): + pass + +class UniversityAdministrator: + def __init__(self, institution_name=""): + pass + + def enroll_student(self, student): + pass + + def add_funds(self, student, funds): + pass + + def buy_soda(self, student, soda): + pass + + def get_student_funds(self, student): + pass + + def get_university_funds(self): + pass + + def refill_vm(self, soda1, amount1, soda2, amount2, soda3, amount3, shop): + pass + + +# To test your code: navigate to the solution folder in your terminal +# and type 'python3 vending_machine.py ../testing/test_n/input.txt' +# where n is replaced by the number of the test. + +# You may also test your code using the command line by navigating to the +# solution folder in your terminal and typing 'python3 vending_machine.py'. + +# Do not modify this code. +if __name__ == "__main__": + from sys import argv + if len(argv) == 2 and 'input.txt' in argv[1]: + file_path = argv[1] + test_num = argv[1][-11] + input_file = open(f'{file_path}', "r") + output_file = open(f'../testing/test_{test_num}/output.txt', "w") + university = UniversityAdministrator() + shop = SodaShop() + output_lines = [] + try: + while (line := input_file.readline()) != 'quit': + words = line.split() + function = words[0] + if function == "enroll_student": + output_lines.append(university.enroll_student(words[1])) + elif function == "add_funds": + output_lines.append(university.add_funds(words[1], float(words[2]))) + elif function == "buy_soda": + output_lines.append(university.buy_soda(words[1], words[2])) + elif function == "create_soda": + output_lines.append(shop.create_soda(words[1], int(words[2]))) + elif function == "set_machine_cost": + output_lines.append(university._vending_machine.set_machine_cost(words[1], float(words[2]))) + elif function == "set_shop_cost": + output_lines.append(shop.set_shop_cost(words[1], float(words[2]))) + elif function == "get_student_funds": + output_lines.append(university.get_student_funds(words[1])) + elif function == "get_university_funds": + output_lines.append(university.get_university_funds()) + elif function == "get_vending_machine_stock": + output_lines.append(university._vending_machine.get_vending_machine_stock()) + elif function == "get_shop_stock": + output_lines.append(shop.get_shop_stock()) + elif function == "refill_vm": + output_lines.append(university.refill_vm(words[1], int(words[2]), words[3], int(words[4]), words[5], int(words[6]), shop)) + output_lines.append("\n") + output_file.writelines(output_lines[:-1]) + except: + output_lines.append("Something went wrong!") + output_file.writelines(output_lines) + + elif len(argv) == 1: + output_file = open(f'output_command_line.txt', "w") + university = UniversityAdministrator() + shop = SodaShop() + output_lines = [] + + while (function := input("Enter a command: ")) != 'quit': + try: + if function == "enroll_student": + student = input("Enter the name of the student to be enrolled: ") + ret_string = university.enroll_student(student) + output_lines.append(ret_string) + print(ret_string) + elif function == "add_funds": + student = input("Enter the name of the student to add funds to: ") + amount = input("Enter the amount of funds to add: ") + ret_string = university.add_funds(student, float(amount)) + output_lines.append(ret_string) + print(ret_string) + elif function == "buy_soda": + student = input("Enter the name of the student who wishes to buy a soda: ") + amount = input(f'Enter the type of soda {student} wishes to buy: ') + ret_string = university.buy_soda(student, amount) + output_lines.append(ret_string) + print(ret_string) + elif function == "create_soda": + soda = input("Enter the type of soda to be created: ") + amount = input(f'Enter the amount of {soda} to be created: ') + ret_string = shop.create_soda(soda, int(amount)) + output_lines.append(ret_string) + print(ret_string) + elif function == "set_machine_cost": + soda = input("Enter the type of soda: ") + cost = input(f'Enter the new cost for {soda}: ') + ret_string = university._vending_machine.set_machine_cost(soda, float(cost)) + output_lines.append(ret_string) + print(ret_string) + elif function == "set_shop_cost": + soda = input("Enter the type of soda: ") + cost = input(f'Enter the new cost for {soda}: ') + ret_string = shop.set_shop_cost(soda, float(cost)) + output_lines.append(ret_string) + print(ret_string) + elif function == "get_student_funds": + student = input("Enter the name of the student: ") + ret_string = university.get_student_funds(student) + output_lines.append(ret_string) + print(ret_string) + elif function == "get_university_funds": + ret_string = university.get_university_funds() + output_lines.append(ret_string) + print(ret_string) + elif function == "get_vending_machine_stock": + ret_string = university._vending_machine.get_vending_machine_stock() + output_lines.append(ret_string) + print(ret_string) + elif function == "get_shop_stock": + ret_string = shop.get_shop_stock() + output_lines.append(ret_string) + print(ret_string) + elif function == "refill_vm": + soda1 = input("Enter the first type of soda: ") + amount1 = input(f"Enter the amount of {soda1} you wish to refill: ") + soda2 = input("Enter the second type of soda: ") + amount2 = input(f"Enter the amount of {soda2} you wish to refill: ") + soda3 = input("Enter the third type of soda: ") + amount3 = input(f"Enter the amount of {soda3} you wish to refill: ") + if (sodas := sorted([soda1, soda2, soda3])) != ["Coca-Cola", "Mountain-Dew", "Sprite"]: + print("The given sodas are not valid. Sodas must be one of Coca-Cola, Sprite, and Mountain-Dew. Please try again!") + else: + ret_string = university.refill_vm(soda1, int(amount1), soda2, int(amount2), soda3, int(amount3), shop) + output_lines.append(ret_string) + print(ret_string) + else: + print(f'{function} is not a valid command. Please try again!') + continue + output_lines.append("\n") + except: + print("Something went wront! Please try again!") + output_file.writelines(output_lines[:-1]) + else: + print('Must call with valid path to "input.txt"') diff --git a/introduction_to_python/assessment/testing/hidden_tests/test_1/expected_output.txt b/introduction_to_python/assessment/testing/hidden_tests/test_1/expected_output.txt index eb54badd..529218e3 100644 --- a/introduction_to_python/assessment/testing/hidden_tests/test_1/expected_output.txt +++ b/introduction_to_python/assessment/testing/hidden_tests/test_1/expected_output.txt @@ -1,5 +1,5 @@ -Wasif Enrolled. -Vending Machine cost for Mountain-Dew is $11 -Error: Insufficent Funds. -Vending Machine cost for Mountain-Dew is $10 -Wasif Bought Mountain-Dew. +Wasif Enrolled. +Vending Machine cost for Mountain-Dew is $11 +Error: Insufficent Funds. +Vending Machine cost for Mountain-Dew is $10 +Wasif Bought Mountain-Dew. diff --git a/introduction_to_python/assessment/testing/hidden_tests/test_1/input.txt b/introduction_to_python/assessment/testing/hidden_tests/test_1/input.txt index 226d6146..327aedf9 100644 --- a/introduction_to_python/assessment/testing/hidden_tests/test_1/input.txt +++ b/introduction_to_python/assessment/testing/hidden_tests/test_1/input.txt @@ -1,5 +1,5 @@ -enroll_student Wasif -set_machine_cost Mountain-Dew 11 -buy_soda Wasif Mountain-Dew -set_machine_cost Mountain-Dew 10 -buy_soda Wasif Mountain-Dew +enroll_student Wasif +set_machine_cost Mountain-Dew 11 +buy_soda Wasif Mountain-Dew +set_machine_cost Mountain-Dew 10 +buy_soda Wasif Mountain-Dew diff --git a/introduction_to_python/assessment/testing/test_1/expected_output.txt b/introduction_to_python/assessment/testing/test_1/expected_output.txt index 38a06e5d..b536b6b7 100644 --- a/introduction_to_python/assessment/testing/test_1/expected_output.txt +++ b/introduction_to_python/assessment/testing/test_1/expected_output.txt @@ -1,6 +1,6 @@ -Wasif Enrolled. -$100.0 Added to Wasif. -Wasif Bought Sprite. -University has $102.0. -Wasif has $108.0. +Wasif Enrolled. +$100.0 Added to Wasif. +Wasif Bought Sprite. +University has $102.0. +Wasif has $108.0. Vending Machine has 5 Coca-Cola, 4 Sprite, and 5 Mountain-Dew. \ No newline at end of file diff --git a/introduction_to_python/assessment/testing/test_1/input.txt b/introduction_to_python/assessment/testing/test_1/input.txt index 9ca7efbd..8caa8117 100644 --- a/introduction_to_python/assessment/testing/test_1/input.txt +++ b/introduction_to_python/assessment/testing/test_1/input.txt @@ -1,7 +1,7 @@ -enroll_student Wasif -add_funds Wasif 100 -buy_soda Wasif Sprite -get_university_funds -get_student_funds Wasif -get_vending_machine_stock +enroll_student Wasif +add_funds Wasif 100 +buy_soda Wasif Sprite +get_university_funds +get_student_funds Wasif +get_vending_machine_stock quit \ No newline at end of file diff --git a/introduction_to_python/assessment/testing/test_2/expected_output.txt b/introduction_to_python/assessment/testing/test_2/expected_output.txt index 02ebe96b..1a9cdcdc 100644 --- a/introduction_to_python/assessment/testing/test_2/expected_output.txt +++ b/introduction_to_python/assessment/testing/test_2/expected_output.txt @@ -1,9 +1,9 @@ -Error: Wasif Not Enrolled. -Error: Wasif Not Enrolled. -Error: Over Max Quantity. -Error: Wasif Not Enrolled. -Wasif Enrolled. -Error: Wasif Already Enrolled. -Vending Machine cost for Coca-Cola is $100.0. -Wasif has $10. +Error: Wasif Not Enrolled. +Error: Wasif Not Enrolled. +Error: Over Max Quantity. +Error: Wasif Not Enrolled. +Wasif Enrolled. +Error: Wasif Already Enrolled. +Vending Machine cost for Coca-Cola is $100.0. +Wasif has $10. Error: Insufficient Funds. \ No newline at end of file diff --git a/introduction_to_python/assessment/testing/test_2/input.txt b/introduction_to_python/assessment/testing/test_2/input.txt index 5eeda4ef..f6e17fb0 100644 --- a/introduction_to_python/assessment/testing/test_2/input.txt +++ b/introduction_to_python/assessment/testing/test_2/input.txt @@ -1,10 +1,10 @@ -add_funds Wasif 10 -buy_soda Wasif Coca-Cola -refill_vm Coca-Cola 10 Sprite 10 Mountain-Dew 10 -get_student_funds Wasif -enroll_student Wasif -enroll_student Wasif -set_machine_cost Coca-Cola 100 -get_student_funds Wasif -buy_soda Wasif Coca-Cola +add_funds Wasif 10 +buy_soda Wasif Coca-Cola +refill_vm Coca-Cola 10 Sprite 10 Mountain-Dew 10 +get_student_funds Wasif +enroll_student Wasif +enroll_student Wasif +set_machine_cost Coca-Cola 100 +get_student_funds Wasif +buy_soda Wasif Coca-Cola quit \ No newline at end of file diff --git a/introduction_to_python/assessment/testing/test_3/expected_output.txt b/introduction_to_python/assessment/testing/test_3/expected_output.txt index 07c7bd00..b01cd0c8 100644 --- a/introduction_to_python/assessment/testing/test_3/expected_output.txt +++ b/introduction_to_python/assessment/testing/test_3/expected_output.txt @@ -1,15 +1,15 @@ -Wasif Enrolled. -Anton Enrolled. -Smith Enrolled. -Wasif Bought Coca-Cola. -Vending Machine cost for Mountain-Dew is $5.0. -Anton Bought Mountain-Dew. -Smith Bought Mountain-Dew. -University has $112.0. -Vending Machine has 4 Coca-Cola, 5 Sprite, and 3 Mountain-Dew. -Soda Shop cost for Mountain-Dew is $100.0. -Error: Insufficient Funds. -Refilled Machine with 5 Coca-Cola, 5 Sprite, 0 Mountain-Dew. -Wasif Bought Mountain-Dew. -Error: Insufficient Funds. +Wasif Enrolled. +Anton Enrolled. +Smith Enrolled. +Wasif Bought Coca-Cola. +Vending Machine cost for Mountain-Dew is $5.0. +Anton Bought Mountain-Dew. +Smith Bought Mountain-Dew. +University has $112.0. +Vending Machine has 4 Coca-Cola, 5 Sprite, and 3 Mountain-Dew. +Soda Shop cost for Mountain-Dew is $100.0. +Error: Insufficient Funds. +Refilled Machine with 5 Coca-Cola, 5 Sprite, 0 Mountain-Dew. +Wasif Bought Mountain-Dew. +Error: Insufficient Funds. Vending Machine has 9 Coca-Cola, 10 Sprite, and 2 Mountain-Dew. \ No newline at end of file diff --git a/introduction_to_python/assessment/testing/test_3/input.txt b/introduction_to_python/assessment/testing/test_3/input.txt index 3b4e8965..09ab805c 100644 --- a/introduction_to_python/assessment/testing/test_3/input.txt +++ b/introduction_to_python/assessment/testing/test_3/input.txt @@ -1,16 +1,16 @@ -enroll_student Wasif -enroll_student Anton -enroll_student Smith -buy_soda Wasif Coca-Cola -set_machine_cost Mountain-Dew 5 -buy_soda Anton Mountain-Dew -buy_soda Smith Mountain-Dew -get_university_funds -get_vending_machine_stock -set_shop_cost Mountain-Dew 100 -refill_vm Coca-Cola 5 Sprite 5 Mountain-Dew 2 -refill_vm Coca-Cola 5 Sprite 5 Mountain-Dew 0 -buy_soda Wasif Mountain-Dew -buy_soda Wasif Mountain-Dew -get_vending_machine_stock +enroll_student Wasif +enroll_student Anton +enroll_student Smith +buy_soda Wasif Coca-Cola +set_machine_cost Mountain-Dew 5 +buy_soda Anton Mountain-Dew +buy_soda Smith Mountain-Dew +get_university_funds +get_vending_machine_stock +set_shop_cost Mountain-Dew 100 +refill_vm Coca-Cola 5 Sprite 5 Mountain-Dew 2 +refill_vm Coca-Cola 5 Sprite 5 Mountain-Dew 0 +buy_soda Wasif Mountain-Dew +buy_soda Wasif Mountain-Dew +get_vending_machine_stock quit \ No newline at end of file diff --git a/introduction_to_python/class_protocols/1_a_vector_class_constructor/README.md b/introduction_to_python/class_protocols/1_a_vector_class_constructor/README.md index 7c6b2705..18566466 100644 --- a/introduction_to_python/class_protocols/1_a_vector_class_constructor/README.md +++ b/introduction_to_python/class_protocols/1_a_vector_class_constructor/README.md @@ -1,11 +1,11 @@ -# Class Protocols - Vector Class Definition - -## Problem Description -Define a python class `Vector3D` that is initialised with 3 integers, `x`, `y`, and `z` which have default values of `0` if no values are given to the constructor. - - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Class Protocols - Vector Class Definition + +## Problem Description +Define a python class `Vector3D` that is initialised with 3 integers, `x`, `y`, and `z` which have default values of `0` if no values are given to the constructor. + + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/class_protocols/1_a_vector_class_constructor/solution/solution.py b/introduction_to_python/class_protocols/1_a_vector_class_constructor/solution/solution.py index e69de29b..48d362b5 100644 --- a/introduction_to_python/class_protocols/1_a_vector_class_constructor/solution/solution.py +++ b/introduction_to_python/class_protocols/1_a_vector_class_constructor/solution/solution.py @@ -0,0 +1,5 @@ +class Vector3D: + def __init__(self, x = 0, y = 0, z = 0): + self.x = x + self.y = y + self.z = z \ No newline at end of file diff --git a/introduction_to_python/class_protocols/1_a_vector_class_constructor/solution/test_solution.py b/introduction_to_python/class_protocols/1_a_vector_class_constructor/solution/test_solution.py index 95a53158..52dc47fd 100644 --- a/introduction_to_python/class_protocols/1_a_vector_class_constructor/solution/test_solution.py +++ b/introduction_to_python/class_protocols/1_a_vector_class_constructor/solution/test_solution.py @@ -1,17 +1,17 @@ -def test_solution(): - from solution import Vector3D - - vector1 = Vector3D(1, 2, 3) - assert vector1.x == 1 - assert vector1.y == 2 - assert vector1.z == 3 - - vector2 = Vector3D(y=1, z=2) - assert vector2.x == 0 - assert vector2.y == 1 - assert vector2.z == 2 - - vector3 = Vector3D() - assert vector3.x == 0 - assert vector3.y == 0 - assert vector3.z == 0 +def test_solution(): + from solution import Vector3D + + vector1 = Vector3D(1, 2, 3) + assert vector1.x == 1 + assert vector1.y == 2 + assert vector1.z == 3 + + vector2 = Vector3D(y=1, z=2) + assert vector2.x == 0 + assert vector2.y == 1 + assert vector2.z == 2 + + vector3 = Vector3D() + assert vector3.x == 0 + assert vector3.y == 0 + assert vector3.z == 0 diff --git a/introduction_to_python/class_protocols/1_b_print_vector/README.md b/introduction_to_python/class_protocols/1_b_print_vector/README.md index 8edfd862..44f83be5 100644 --- a/introduction_to_python/class_protocols/1_b_print_vector/README.md +++ b/introduction_to_python/class_protocols/1_b_print_vector/README.md @@ -1,15 +1,15 @@ -# Class Protocols - Vector Class Definition - -## Problem Description -Define a python magic method `__str__` in the `Vector3D` class that can be used by python's built in `print` method to nicely print out a vector object. When printing a vector you should print out `(x = X, y = Y, z = Z`), where `X`, `Y`, and `Z` are the values in the given vector object. - -For Example: -``` -print(Vector3D(3, 4, 2)) prints out "(x = 3, y = 4, z = 2)" -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Class Protocols - Vector Class Definition + +## Problem Description +Define a python magic method `__str__` in the `Vector3D` class that can be used by python's built in `print` method to nicely print out a vector object. When printing a vector you should print out `(x = X, y = Y, z = Z`), where `X`, `Y`, and `Z` are the values in the given vector object. + +For Example: +``` +print(Vector3D(3, 4, 2)) prints out "(x = 3, y = 4, z = 2)" +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/class_protocols/1_b_print_vector/solution/solution.py b/introduction_to_python/class_protocols/1_b_print_vector/solution/solution.py index e69de29b..5714e5c0 100644 --- a/introduction_to_python/class_protocols/1_b_print_vector/solution/solution.py +++ b/introduction_to_python/class_protocols/1_b_print_vector/solution/solution.py @@ -0,0 +1,10 @@ +class Vector3D: + + def __init__(self, x = 0, y= 0, z= 0): + self.x = x + self.y = y + self.z = z + + def __str__(self): + return f'(x = {self.x}, y = {self.y}, z = {self.z})' +#print(Vector3D(3, 4, 2)) \ No newline at end of file diff --git a/introduction_to_python/class_protocols/1_b_print_vector/solution/test_solution.py b/introduction_to_python/class_protocols/1_b_print_vector/solution/test_solution.py index e8325cea..d715b77a 100644 --- a/introduction_to_python/class_protocols/1_b_print_vector/solution/test_solution.py +++ b/introduction_to_python/class_protocols/1_b_print_vector/solution/test_solution.py @@ -1,11 +1,11 @@ -def test_solution(): - from solution import Vector3D - - vector1 = Vector3D(1, 2, 3) - assert str(vector1) == "(x = 1, y = 2, z = 3)" - - vector2 = Vector3D(y=1, z=2) - assert str(vector2) == "(x = 0, y = 1, z = 2)" - - vector3 = Vector3D() - assert str(vector3) == "(x = 0, y = 0, z = 0)" +def test_solution(): + from solution import Vector3D + + vector1 = Vector3D(1, 2, 3) + assert str(vector1) == "(x = 1, y = 2, z = 3)" + + vector2 = Vector3D(y=1, z=2) + assert str(vector2) == "(x = 0, y = 1, z = 2)" + + vector3 = Vector3D() + assert str(vector3) == "(x = 0, y = 0, z = 0)" diff --git a/introduction_to_python/class_protocols/2_a_add_vectors/README.md b/introduction_to_python/class_protocols/2_a_add_vectors/README.md index 85297585..be340135 100644 --- a/introduction_to_python/class_protocols/2_a_add_vectors/README.md +++ b/introduction_to_python/class_protocols/2_a_add_vectors/README.md @@ -1,16 +1,16 @@ -# Class Protocols - Vector Class Definition - -## Problem Description -Define a python magic method `__add__` in the `Vector3D` class that adds together two vector objects. If we add together two vectors `vec1 = (x1, y1, z1)` and `vec2 = (x2, y2, z2)` the resulting vector will be the sum of the `x` components plus the sum of the `y` components plus the sum of the `z` components. - -For Exmaple: -``` -vec1 = Vector3D(1, 2, 3) -vec2 = Vector3D(4, 5, 6) -vec1 + vec2 = Vector3D(5, 7, 9) -``` -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Class Protocols - Vector Class Definition + +## Problem Description +Define a python magic method `__add__` in the `Vector3D` class that adds together two vector objects. If we add together two vectors `vec1 = (x1, y1, z1)` and `vec2 = (x2, y2, z2)` the resulting vector will be the sum of the `x` components plus the sum of the `y` components plus the sum of the `z` components. + +For Exmaple: +``` +vec1 = Vector3D(1, 2, 3) +vec2 = Vector3D(4, 5, 6) +vec1 + vec2 = Vector3D(5, 7, 9) +``` +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/class_protocols/2_a_add_vectors/solution/solution.py b/introduction_to_python/class_protocols/2_a_add_vectors/solution/solution.py index e69de29b..e2ed2b1c 100644 --- a/introduction_to_python/class_protocols/2_a_add_vectors/solution/solution.py +++ b/introduction_to_python/class_protocols/2_a_add_vectors/solution/solution.py @@ -0,0 +1,14 @@ +class Vector3D: + def __init__(self, x = 0, y = 0, z = 0): + self.x = x + self.y = y + self.z = z + + #def __str__(self): + #return f'' + + def __add__(self, other): + x = self.x + other.x + y = self.y + other.y + z = self.z + other.z + return x, y, z diff --git a/introduction_to_python/class_protocols/2_a_add_vectors/solution/test_solution.py b/introduction_to_python/class_protocols/2_a_add_vectors/solution/test_solution.py index 865b357a..d9fe4bf5 100644 --- a/introduction_to_python/class_protocols/2_a_add_vectors/solution/test_solution.py +++ b/introduction_to_python/class_protocols/2_a_add_vectors/solution/test_solution.py @@ -1,14 +1,14 @@ -def test_solution(): - from solution import Vector3D - - vec1 = Vector3D(1, 2, 3) - vec2 = Vector3D(y=1, z=2) - vec3 = Vector3D() - - assert (vec1 + vec2).x == 1 - assert (vec1 + vec2).y == 3 - assert (vec1 + vec2).z == 5 - - assert (vec1 + vec3).x == 1 - assert (vec1 + vec3).y == 2 - assert (vec1 + vec3).z == 3 +def test_solution(): + from solution import Vector3D + + vec1 = Vector3D(1, 2, 3) + vec2 = Vector3D(y=1, z=2) + vec3 = Vector3D() + + assert (vec1 + vec2).x == 1 + assert (vec1 + vec2).y == 3 + assert (vec1 + vec2).z == 5 + + assert (vec1 + vec3).x == 1 + assert (vec1 + vec3).y == 2 + assert (vec1 + vec3).z == 3 diff --git a/introduction_to_python/class_protocols/2_a_comparison_lt_gt/README.md b/introduction_to_python/class_protocols/2_a_comparison_lt_gt/README.md index 7c0b1bbd..61f3f660 100644 --- a/introduction_to_python/class_protocols/2_a_comparison_lt_gt/README.md +++ b/introduction_to_python/class_protocols/2_a_comparison_lt_gt/README.md @@ -1,22 +1,22 @@ -# Class Protocols - Vector Class Definition - -## Problem Description -Define a python magic method `__lt__` in the `Vector3D` class that compares is one vector is less than another vector by magnitude. -Define a python magic method `__gt__` in the `Vector3D` class that compares is one vector is greater than another vector by magnitude. In order to use python's buit in sqrt function, you will need to import python's math module and use `math.sqrt()`. - -For Exmaple: -``` -vec1 = Vector3D(1, 5, 3) -vec2 = Vector3D(4, 4, 1) -vec3 = Vector3D(1, 5, 2) - -vec1 < vec2 == False -vec1 < vec3 == True -vec1 > vec2 == True -vec1 > vec3 == False -``` -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Class Protocols - Vector Class Definition + +## Problem Description +Define a python magic method `__lt__` in the `Vector3D` class that compares is one vector is less than another vector by magnitude. +Define a python magic method `__gt__` in the `Vector3D` class that compares is one vector is greater than another vector by magnitude. In order to use python's buit in sqrt function, you will need to import python's math module and use `math.sqrt()`. + +For Exmaple: +``` +vec1 = Vector3D(1, 5, 3) +vec2 = Vector3D(4, 4, 1) +vec3 = Vector3D(1, 5, 2) + +vec1 < vec2 == False +vec1 < vec3 == True +vec1 > vec2 == True +vec1 > vec3 == False +``` +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/class_protocols/2_a_comparison_lt_gt/solution/solution.py b/introduction_to_python/class_protocols/2_a_comparison_lt_gt/solution/solution.py index e69de29b..f5177e63 100644 --- a/introduction_to_python/class_protocols/2_a_comparison_lt_gt/solution/solution.py +++ b/introduction_to_python/class_protocols/2_a_comparison_lt_gt/solution/solution.py @@ -0,0 +1,18 @@ +import math +class Vector3D: + + def __init__(self, x = 0, y= 0, z= 0): + self.x = x + self.y = y + self.z = z + + def magnitude(self): + return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2) + + + def __lt__(self, other): + return self.magnitude() < other.magnitude() + + + def __gt__(self, other): + return self.magnitude() > other.magnitude() \ No newline at end of file diff --git a/introduction_to_python/class_protocols/2_a_comparison_lt_gt/solution/test_solution.py b/introduction_to_python/class_protocols/2_a_comparison_lt_gt/solution/test_solution.py index c3179578..2df7cc23 100644 --- a/introduction_to_python/class_protocols/2_a_comparison_lt_gt/solution/test_solution.py +++ b/introduction_to_python/class_protocols/2_a_comparison_lt_gt/solution/test_solution.py @@ -1,16 +1,16 @@ -def test_solution(): - from solution import Vector3D - - vec1 = Vector3D(1, 5, 3) - vec2 = Vector3D(4, 4, 1) - vec3 = Vector3D(1, 5, 2) - - assert not (vec1 < vec2) - assert not (vec1 < vec3) - assert vec3 < vec1 - assert vec2 < vec1 - - assert not (vec2 > vec1) - assert not (vec3 > vec1) - assert vec1 > vec3 - assert vec1 > vec2 +def test_solution(): + from solution import Vector3D + + vec1 = Vector3D(1, 5, 3) + vec2 = Vector3D(4, 4, 1) + vec3 = Vector3D(1, 5, 2) + + assert not (vec1 < vec2) + assert not (vec1 < vec3) + assert vec3 < vec1 + assert vec2 < vec1 + + assert not (vec2 > vec1) + assert not (vec3 > vec1) + assert vec1 > vec3 + assert vec1 > vec2 diff --git a/introduction_to_python/class_protocols/2_b_dot_product/README.md b/introduction_to_python/class_protocols/2_b_dot_product/README.md index 00f9ba3f..315d613d 100644 --- a/introduction_to_python/class_protocols/2_b_dot_product/README.md +++ b/introduction_to_python/class_protocols/2_b_dot_product/README.md @@ -1,16 +1,16 @@ -# Class Protocols - Vector Class Definition - -## Problem Description -Define a python magic method `__mul__` in the `Vector3D` class that computes the dot product of two vector objects. If we multiply two vectors (take the dot product) for `vec1 = (x1, y1)` and `vec2 = (x2, y2)` the resulting vector will be `x1 * x2 * x3 + y1 * y2 * z2`. - -For Exmaple: -``` -vec1 = Vector3D(1, 5, 3) -vec2 = Vector3D(4, 4, 1) -vec1 * vec2 == 18 -``` -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Class Protocols - Vector Class Definition + +## Problem Description +Define a python magic method `__mul__` in the `Vector3D` class that computes the dot product of two vector objects. If we multiply two vectors (take the dot product) for `vec1 = (x1, y1)` and `vec2 = (x2, y2)` the resulting vector will be `x1 * x2 * x3 + y1 * y2 * z2`. + +For Exmaple: +``` +vec1 = Vector3D(1, 5, 3) +vec2 = Vector3D(4, 4, 1) +vec1 * vec2 == 18 +``` +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/class_protocols/2_b_dot_product/solution/solution.py b/introduction_to_python/class_protocols/2_b_dot_product/solution/solution.py index e69de29b..58b13d9c 100644 --- a/introduction_to_python/class_protocols/2_b_dot_product/solution/solution.py +++ b/introduction_to_python/class_protocols/2_b_dot_product/solution/solution.py @@ -0,0 +1,17 @@ +class Vector3D: + def __init__(self, x = 0, y = 0, z = 0): + self.x = x + self.y = y + self.z = z + + def __mul__(self, other): + return (self.x * other.x + self.y * other.y * self.z * other.z) + + +vec1 = Vector3D(1, 2, 3) +vec2 = Vector3D(y=1, z=3) +vec3 = Vector3D() + +print(vec1 * vec2) +print(vec1 * vec3) +print(vec1 * vec1) \ No newline at end of file diff --git a/introduction_to_python/class_protocols/2_b_dot_product/solution/test_solution.py b/introduction_to_python/class_protocols/2_b_dot_product/solution/test_solution.py index 82df16a0..51b989f4 100644 --- a/introduction_to_python/class_protocols/2_b_dot_product/solution/test_solution.py +++ b/introduction_to_python/class_protocols/2_b_dot_product/solution/test_solution.py @@ -1,10 +1,10 @@ -def test_solution(): - from solution import Vector3D - - vec1 = Vector3D(1, 2, 3) - vec2 = Vector3D(y=1, z=3) - vec3 = Vector3D() - - assert (vec1 * vec2) == 11 - assert (vec1 * vec3) == 0 - assert (vec1 * vec1) == 14 +def test_solution(): + from solution import Vector3D + + vec1 = Vector3D(1, 2, 3) + vec2 = Vector3D(y=1, z=3) + vec3 = Vector3D() + + assert (vec1 * vec2) == 11 + assert (vec1 * vec3) == 0 + assert (vec1 * vec1) == 14 diff --git a/introduction_to_python/class_protocols/2_c_equal_comparison/README.md b/introduction_to_python/class_protocols/2_c_equal_comparison/README.md index b12b01be..2fa107b9 100644 --- a/introduction_to_python/class_protocols/2_c_equal_comparison/README.md +++ b/introduction_to_python/class_protocols/2_c_equal_comparison/README.md @@ -1,19 +1,19 @@ -# Class Protocols - Vector Class Definition - -## Problem Description -Define a python magic method `__eq__` in the `Vector3D` class that checks if two vector objects are equal to each other. Two vectors `vec1` and `vec2` are equal if `x1 = x2` and `y1 = y2` and `z1 = z2`. - -For Exmaple: -``` -vec1 = Vector3D(1, 5, 3) -vec2 = Vector3D(4, 4, 1) -vec3 = Vector3D(1, 5, 3) - -vec1 == vec2 == False -vec1 == vec3 == True -``` -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Class Protocols - Vector Class Definition + +## Problem Description +Define a python magic method `__eq__` in the `Vector3D` class that checks if two vector objects are equal to each other. Two vectors `vec1` and `vec2` are equal if `x1 = x2` and `y1 = y2` and `z1 = z2`. + +For Exmaple: +``` +vec1 = Vector3D(1, 5, 3) +vec2 = Vector3D(4, 4, 1) +vec3 = Vector3D(1, 5, 3) + +vec1 == vec2 == False +vec1 == vec3 == True +``` +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/class_protocols/2_c_equal_comparison/solution/solution.py b/introduction_to_python/class_protocols/2_c_equal_comparison/solution/solution.py index e69de29b..d1956bab 100644 --- a/introduction_to_python/class_protocols/2_c_equal_comparison/solution/solution.py +++ b/introduction_to_python/class_protocols/2_c_equal_comparison/solution/solution.py @@ -0,0 +1,8 @@ +class Vector3D: + def __init__(self, x = 0, y = 0, z = 0): + self.x = x + self.y = y + self.z = z + + def __eq__(self, other): + return self.x == other.x and self.y == other.y and self.z == other.z \ No newline at end of file diff --git a/introduction_to_python/class_protocols/2_c_equal_comparison/solution/test_solution.py b/introduction_to_python/class_protocols/2_c_equal_comparison/solution/test_solution.py index e6a330d4..b8998aca 100644 --- a/introduction_to_python/class_protocols/2_c_equal_comparison/solution/test_solution.py +++ b/introduction_to_python/class_protocols/2_c_equal_comparison/solution/test_solution.py @@ -1,11 +1,11 @@ -def test_solution(): - from solution import Vector3D - - vec1 = Vector3D(-4, -4, 1) - vec2 = Vector3D(4, 4, 1) - vec3 = Vector3D(4, 4, 1) - - assert not (vec1 == vec2) - assert not (vec1 == vec3) - assert vec3 == vec3 - assert vec1 == vec1 +def test_solution(): + from solution import Vector3D + + vec1 = Vector3D(-4, -4, 1) + vec2 = Vector3D(4, 4, 1) + vec3 = Vector3D(4, 4, 1) + + assert not (vec1 == vec2) + assert not (vec1 == vec3) + assert vec3 == vec3 + assert vec1 == vec1 diff --git a/introduction_to_python/class_protocols/2_d_magnitude/README.md b/introduction_to_python/class_protocols/2_d_magnitude/README.md index 58c15137..cab89c69 100644 --- a/introduction_to_python/class_protocols/2_d_magnitude/README.md +++ b/introduction_to_python/class_protocols/2_d_magnitude/README.md @@ -1,20 +1,20 @@ -# Class Protocols - Vector Class Definition - -## Problem Description -Define a python magic method `__abs__` in the `Vector3D` class that computes the magnitude of a vector. We compute the magnitude of a 3D vector `vect` using the formula `magnitude = sqrt(x^2 + y^2 + z^2)`. In order to use python's buit in sqrt function, you will need to import python's math module and use `math.sqrt()`. - -For Exmaple: -``` -vec1 = Vector3D(1, 5, 3) -vec2 = Vector3D(4, 4, 1) -vec3 = Vector3D(1, 5, 2) - -vec1.magnitude() == sqrt(35) -vec2.magnitude() == sqrt(33) -vec3.magnitude() == sqrt(30) -``` -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Class Protocols - Vector Class Definition + +## Problem Description +Define a python magic method `__abs__` in the `Vector3D` class that computes the magnitude of a vector. We compute the magnitude of a 3D vector `vect` using the formula `magnitude = sqrt(x^2 + y^2 + z^2)`. In order to use python's buit in sqrt function, you will need to import python's math module and use `math.sqrt()`. + +For Exmaple: +``` +vec1 = Vector3D(1, 5, 3) +vec2 = Vector3D(4, 4, 1) +vec3 = Vector3D(1, 5, 2) + +vec1.magnitude() == sqrt(35) +vec2.magnitude() == sqrt(33) +vec3.magnitude() == sqrt(30) +``` +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/class_protocols/2_d_magnitude/solution/solution.py b/introduction_to_python/class_protocols/2_d_magnitude/solution/solution.py index e69de29b..72ea357e 100644 --- a/introduction_to_python/class_protocols/2_d_magnitude/solution/solution.py +++ b/introduction_to_python/class_protocols/2_d_magnitude/solution/solution.py @@ -0,0 +1,9 @@ +import math +class Vector3D: + def __init__(self, x = 0, y = 0, z = 0): + self.x = x + self.y = y + self.z = z + + def __abs__(self): + return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2) \ No newline at end of file diff --git a/introduction_to_python/class_protocols/2_d_magnitude/solution/test_solution.py b/introduction_to_python/class_protocols/2_d_magnitude/solution/test_solution.py index b870faf6..9ec4da59 100644 --- a/introduction_to_python/class_protocols/2_d_magnitude/solution/test_solution.py +++ b/introduction_to_python/class_protocols/2_d_magnitude/solution/test_solution.py @@ -1,11 +1,11 @@ -def test_solution(): - from solution import Vector3D - import math - - vec1 = Vector3D(1, 5, 3) - vec2 = Vector3D(4, 4, 1) - vec3 = Vector3D(1, 5, 2) - - assert abs(vec1) == math.sqrt(35) - assert abs(vec2) == math.sqrt(33) - assert abs(vec3) == math.sqrt(30) +def test_solution(): + from solution import Vector3D + import math + + vec1 = Vector3D(1, 5, 3) + vec2 = Vector3D(4, 4, 1) + vec3 = Vector3D(1, 5, 2) + + assert abs(vec1) == math.sqrt(35) + assert abs(vec2) == math.sqrt(33) + assert abs(vec3) == math.sqrt(30) diff --git a/introduction_to_python/class_protocols/2_e_sub_vectors/README.md b/introduction_to_python/class_protocols/2_e_sub_vectors/README.md index 12a8402d..605cde81 100644 --- a/introduction_to_python/class_protocols/2_e_sub_vectors/README.md +++ b/introduction_to_python/class_protocols/2_e_sub_vectors/README.md @@ -1,16 +1,16 @@ -# Class Protocols - Vector Class Definition - -## Problem Description -Define a python magic method `__sub__` in the `Vector3D` class that subtracts two vector objects. If we subtract two vectors `vec1 = (x1, y1, z1)` and `vec2 = (x2, y2, z2)` the resulting vector will be `(x1 - x2, y1 - y2, z1 - z2)`. - -For Exmaple: -``` -vec1 = Vector3D(1, 5, 3) -vec2 = Vector3D(4, 4, 1) -vec1 - vec2 == Vector3D(-3, 1, 2) -``` -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Class Protocols - Vector Class Definition + +## Problem Description +Define a python magic method `__sub__` in the `Vector3D` class that subtracts two vector objects. If we subtract two vectors `vec1 = (x1, y1, z1)` and `vec2 = (x2, y2, z2)` the resulting vector will be `(x1 - x2, y1 - y2, z1 - z2)`. + +For Exmaple: +``` +vec1 = Vector3D(1, 5, 3) +vec2 = Vector3D(4, 4, 1) +vec1 - vec2 == Vector3D(-3, 1, 2) +``` +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/class_protocols/2_e_sub_vectors/solution/solution.py b/introduction_to_python/class_protocols/2_e_sub_vectors/solution/solution.py index e69de29b..f6e24e56 100644 --- a/introduction_to_python/class_protocols/2_e_sub_vectors/solution/solution.py +++ b/introduction_to_python/class_protocols/2_e_sub_vectors/solution/solution.py @@ -0,0 +1,11 @@ +class Vector3D: + def __init__(self, x = 0, y = 0, z = 0): + self.x = x + self.y = y + self.z = z + + #def __str__(self): + #return f"({self.x - other.x}{self.y - other.y}{self.z - other.z})" + + def __sub__(self, other): + return Vector3D(self.x - other.x, self.y - other.y, self.z - other.z) \ No newline at end of file diff --git a/introduction_to_python/class_protocols/2_e_sub_vectors/solution/test_solution.py b/introduction_to_python/class_protocols/2_e_sub_vectors/solution/test_solution.py index f89de6f1..ba304994 100644 --- a/introduction_to_python/class_protocols/2_e_sub_vectors/solution/test_solution.py +++ b/introduction_to_python/class_protocols/2_e_sub_vectors/solution/test_solution.py @@ -1,14 +1,14 @@ -def test_solution(): - from solution import Vector3D - - vec1 = Vector3D(1, 2, 0) - vec2 = Vector3D(y=1, z=3) - vec3 = Vector3D() - - assert (vec1 - vec2).x == 1 - assert (vec1 - vec2).y == 1 - assert (vec1 - vec2).z == -3 - - assert (vec1 - vec3).x == 1 - assert (vec1 - vec3).y == 2 +def test_solution(): + from solution import Vector3D + + vec1 = Vector3D(1, 2, 0) + vec2 = Vector3D(y=1, z=3) + vec3 = Vector3D() + + assert (vec1 - vec2).x == 1 + assert (vec1 - vec2).y == 1 + assert (vec1 - vec2).z == -3 + + assert (vec1 - vec3).x == 1 + assert (vec1 - vec3).y == 2 assert (vec1 - vec3).z == 0 \ No newline at end of file diff --git a/introduction_to_python/class_protocols/3_b_sort_vectors/README.md b/introduction_to_python/class_protocols/3_b_sort_vectors/README.md index 4eb6f45f..01243247 100644 --- a/introduction_to_python/class_protocols/3_b_sort_vectors/README.md +++ b/introduction_to_python/class_protocols/3_b_sort_vectors/README.md @@ -1,20 +1,20 @@ -# Class Protocols - Vector Class Definition - -## Problem Description -Define a python function `sort_vectors` that consumes a list of `Vector3D` objects `vect_lst` and sorts the vectors in increasing order by magnitude. You may use Python's built in sort. - -For Exmaple: -``` -vec1 = Vector3D(1, 5, 3) -vec2 = Vector3D(4, 4, 1) -vec3 = Vector3D(1, 5, 2) -vec4 = Vector3D(4, 4, 1) - -vect_lst = [vec1, vec2, vec3, vec4] -sort_vectors(vect_lst) == [vec3, vec2, vec4, vec1] -``` -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Class Protocols - Vector Class Definition + +## Problem Description +Define a python function `sort_vectors` that consumes a list of `Vector3D` objects `vect_lst` and sorts the vectors in increasing order by magnitude. You may use Python's built in sort. + +For Exmaple: +``` +vec1 = Vector3D(1, 5, 3) +vec2 = Vector3D(4, 4, 1) +vec3 = Vector3D(1, 5, 2) +vec4 = Vector3D(4, 4, 1) + +vect_lst = [vec1, vec2, vec3, vec4] +sort_vectors(vect_lst) == [vec3, vec2, vec4, vec1] +``` +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/class_protocols/3_b_sort_vectors/solution/solution.py b/introduction_to_python/class_protocols/3_b_sort_vectors/solution/solution.py index e69de29b..f00f2691 100644 --- a/introduction_to_python/class_protocols/3_b_sort_vectors/solution/solution.py +++ b/introduction_to_python/class_protocols/3_b_sort_vectors/solution/solution.py @@ -0,0 +1,23 @@ +import math +class Vector3D: + def __init__(self, x = 0, y = 0, z = 0): + self.x = x + self.y = y + self.z = z + + def magnitude(self): + return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2) + + def __lt__(self, other): + return self.magnitude() < other.magnitude() + + def __gt__(self, other): + return self.magnitude() > other.magnitude() + + def __eq__(self, other): + return self.magnitude() == other.magnitude() + +def sort_vectors(vect_lst): + return sorted(vect_lst) + + \ No newline at end of file diff --git a/introduction_to_python/class_protocols/3_b_sort_vectors/solution/test_solution.py b/introduction_to_python/class_protocols/3_b_sort_vectors/solution/test_solution.py index 8f254034..7013ba34 100644 --- a/introduction_to_python/class_protocols/3_b_sort_vectors/solution/test_solution.py +++ b/introduction_to_python/class_protocols/3_b_sort_vectors/solution/test_solution.py @@ -1,13 +1,13 @@ -def test_solution(): - from solution import Vector3D, sort_vectors - - vec1 = Vector3D(1, 5, 3) - vec2 = Vector3D(4, 4, 1) - vec3 = Vector3D(1, 5, 2) - vec4 = Vector3D(4, 4, 1) - vect_lst = [vec1, vec2, vec3, vec4] - sorted_lst = [vec3, vec2, vec4, vec1] - ret_lst = sort_vectors(vect_lst) - - for r, s in zip(ret_lst, sorted_lst): - assert str(r) == str(s) +def test_solution(): + from solution import Vector3D, sort_vectors + + vec1 = Vector3D(1, 5, 3) + vec2 = Vector3D(4, 4, 1) + vec3 = Vector3D(1, 5, 2) + vec4 = Vector3D(4, 4, 1) + vect_lst = [vec1, vec2, vec3, vec4] + sorted_lst = [vec3, vec2, vec4, vec1] + ret_lst = sort_vectors(vect_lst) + + for r, s in zip(ret_lst, sorted_lst): + assert str(r) == str(s) diff --git a/introduction_to_python/class_protocols/3_c_multiplication/README.md b/introduction_to_python/class_protocols/3_c_multiplication/README.md index 93bd5674..331e969d 100644 --- a/introduction_to_python/class_protocols/3_c_multiplication/README.md +++ b/introduction_to_python/class_protocols/3_c_multiplication/README.md @@ -1,20 +1,20 @@ -# Class Protocols - Vector Class Definition - -## Problem Description -Redefine your python magic method `__mul__` as well as the magic methos `__rmul__` in the `Vector3D` to handle both scaler multiplication and vector multipliation. `__rmul__` is the right hand multiplication `other * self`. By defining both `__mul__` and `__rmul__`, this allows you to multiply by a value on either side of the `*` operator. -If we multiply two vectors (take the dot product) for `vec1 = (x1, y1)` and `vec2 = (x2, y2)` the resulting vector will be `x1 * x2 * x3 + y1 * y2 * z2`. If we multiply a vector by an integer `c`, `c * (x1, x2, x3)` or `(x1, x2, x3) * c` the resulting vetor will be `cx1, c2x, cx3`. - -For Exmaple: -``` -vec1 = Vector3D(1, 5, 3) -vec2 = Vector3D(4, 4, 1) -vec1 * vec2 == 18 - -3 * vec1 == Vector3D(3, 15, 9) -vec2 * 2 == Vector3D(8, 8, 2) -``` -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Class Protocols - Vector Class Definition + +## Problem Description +Redefine your python magic method `__mul__` as well as the magic methos `__rmul__` in the `Vector3D` to handle both scaler multiplication and vector multipliation. `__rmul__` is the right hand multiplication `other * self`. By defining both `__mul__` and `__rmul__`, this allows you to multiply by a value on either side of the `*` operator. +If we multiply two vectors (take the dot product) for `vec1 = (x1, y1)` and `vec2 = (x2, y2)` the resulting vector will be `x1 * x2 * x3 + y1 * y2 * z2`. If we multiply a vector by an integer `c`, `c * (x1, x2, x3)` or `(x1, x2, x3) * c` the resulting vetor will be `cx1, c2x, cx3`. + +For Exmaple: +``` +vec1 = Vector3D(1, 5, 3) +vec2 = Vector3D(4, 4, 1) +vec1 * vec2 == 18 + +3 * vec1 == Vector3D(3, 15, 9) +vec2 * 2 == Vector3D(8, 8, 2) +``` +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/class_protocols/3_c_multiplication/solution/solution.py b/introduction_to_python/class_protocols/3_c_multiplication/solution/solution.py index e69de29b..2af1802c 100644 --- a/introduction_to_python/class_protocols/3_c_multiplication/solution/solution.py +++ b/introduction_to_python/class_protocols/3_c_multiplication/solution/solution.py @@ -0,0 +1,15 @@ +class Vector3D: + def __init__(self, x = 0, y = 0, z = 0): + self.x = x + self.y = y + self.z = z + + def __str__(self): + return (f"{self.x}") + + def __mul__(self, other): + return + + def __rmul__(self, other): + return + \ No newline at end of file diff --git a/introduction_to_python/class_protocols/3_c_multiplication/solution/test_solution.py b/introduction_to_python/class_protocols/3_c_multiplication/solution/test_solution.py index 5861eea2..1845c0c0 100644 --- a/introduction_to_python/class_protocols/3_c_multiplication/solution/test_solution.py +++ b/introduction_to_python/class_protocols/3_c_multiplication/solution/test_solution.py @@ -1,16 +1,16 @@ -def test_solution(): - from solution import Vector3D - - vec1 = Vector3D(1, 2, 3) - vec2 = Vector3D(y=1, z=3) - vec3 = Vector3D() - rvec1 = vec1 * 3 - rvec2 = vec2 * 2 - lvec1 = 3 * vec1 - - assert (vec1 * vec2) == 11 - assert (vec1 * vec3) == 0 - assert (vec1 * vec1) == 14 - assert rvec1.x == 3 and rvec1.y == 6 and rvec1.z == 9 - assert rvec2.x == 0 and rvec2.y == 2 and rvec2.z == 6 - assert lvec1.x == 3 and lvec1.y == 6 and lvec1.z == 9 +def test_solution(): + from solution import Vector3D + + vec1 = Vector3D(1, 2, 3) + vec2 = Vector3D(y=1, z=3) + vec3 = Vector3D() + rvec1 = vec1 * 3 + rvec2 = vec2 * 2 + lvec1 = 3 * vec1 + + assert (vec1 * vec2) == 11 + assert (vec1 * vec3) == 0 + assert (vec1 * vec1) == 14 + assert rvec1.x == 3 and rvec1.y == 6 and rvec1.z == 9 + assert rvec2.x == 0 and rvec2.y == 2 and rvec2.z == 6 + assert lvec1.x == 3 and lvec1.y == 6 and lvec1.z == 9 diff --git a/introduction_to_python/class_protocols/README.md b/introduction_to_python/class_protocols/README.md index 16518136..df650993 100644 --- a/introduction_to_python/class_protocols/README.md +++ b/introduction_to_python/class_protocols/README.md @@ -1,14 +1,14 @@ -# Exercises for Class Protocols - -| Exercise ID | Exercise | -|:-----------:|:--------:| -| easy_e1 | [Vector Class Constructor](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/vector_class_constructor) | -| easy_e2 | [Print Vector](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/print_vector) | -| medium_e1 | [Add Vectors](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/add_vectors) | -| medium_e2 | [Dot Product](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/dot_product) | -| medium_e3 | [Equal Comparison](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/equal_comparison) | -| medium_e4 | [Magnitude](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/magnitude) | -| medium_e5 | [Sub vectors](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/sub_vectors) | -| hard_e1 | [Comparison LT GT](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/comparison_lt_gt) | -| hard_e2 | [Sort Vectors](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/sort_vectors) | -| hard_e3 | [Multiplication](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/multiplication) | +# Exercises for Class Protocols + +| Exercise ID | Exercise | +|:-----------:|:--------:| +| easy_e1 | [Vector Class Constructor](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/vector_class_constructor) | +| easy_e2 | [Print Vector](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/print_vector) | +| medium_e1 | [Add Vectors](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/add_vectors) | +| medium_e2 | [Dot Product](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/dot_product) | +| medium_e3 | [Equal Comparison](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/equal_comparison) | +| medium_e4 | [Magnitude](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/magnitude) | +| medium_e5 | [Sub vectors](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/sub_vectors) | +| hard_e1 | [Comparison LT GT](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/comparison_lt_gt) | +| hard_e2 | [Sort Vectors](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/sort_vectors) | +| hard_e3 | [Multiplication](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/class_protocols/multiplication) | diff --git a/introduction_to_python/classes/1_a_employee_class/README.md b/introduction_to_python/classes/1_a_employee_class/README.md index 22ddb82e..2efc8a1a 100644 --- a/introduction_to_python/classes/1_a_employee_class/README.md +++ b/introduction_to_python/classes/1_a_employee_class/README.md @@ -1,16 +1,16 @@ -# Employee Class Definition - -## Problem Description -Define a Python class Employee with the following attributes: -* `name` - a string -* `employee_id` - an integer -* `salaray` - an integer between 20,000 - 200,000 -* `years_at_company` - an integer -Create an employee object with name `Cosette Rodger`, having an employee ID of `1`, a salary of `100000`, and having been at the company for `4` years. Assign the person object to the variable name `cosette`. - - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory +# Employee Class Definition + +## Problem Description +Define a Python class Employee with the following attributes: +* `name` - a string +* `employee_id` - an integer +* `salaray` - an integer between 20,000 - 200,000 +* `years_at_company` - an integer +Create an employee object with name `Cosette Rodger`, having an employee ID of `1`, a salary of `100000`, and having been at the company for `4` years. Assign the person object to the variable name `cosette`. + + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory diff --git a/introduction_to_python/classes/1_a_employee_class/solution/solution.py b/introduction_to_python/classes/1_a_employee_class/solution/solution.py index e69de29b..2f198892 100644 --- a/introduction_to_python/classes/1_a_employee_class/solution/solution.py +++ b/introduction_to_python/classes/1_a_employee_class/solution/solution.py @@ -0,0 +1,13 @@ +class employee(): + num_employee = 0 + def__init__(self, name, employee_id, salaray, years_at_company): + self.name = name + self.employee_id = employee_id + self.salaray = salaray + self.years_at_company = years_at_company + employee.num_employee += 1 + + 'pytest' + + + \ No newline at end of file diff --git a/introduction_to_python/classes/1_a_employee_class/solution/solution_2.py b/introduction_to_python/classes/1_a_employee_class/solution/solution_2.py new file mode 100644 index 00000000..8bb305fd --- /dev/null +++ b/introduction_to_python/classes/1_a_employee_class/solution/solution_2.py @@ -0,0 +1,8 @@ +class Employee(): + def __init__(self, name, employee_id = 0, salary = 0, years_at_company = 0): + self.name = name + self.employee_id = employee_id + self.salary = salary + self.years_at_company = years_at_company + +cosette = Employee("Cosette Rodger", 1, 100000, 4) \ No newline at end of file diff --git a/introduction_to_python/classes/1_a_employee_class/solution/test_solution.py b/introduction_to_python/classes/1_a_employee_class/solution/test_solution.py index 2cffe128..e108e265 100644 --- a/introduction_to_python/classes/1_a_employee_class/solution/test_solution.py +++ b/introduction_to_python/classes/1_a_employee_class/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - from solution import cosette - - assert cosette.name == "Cosette Rodger" - assert cosette.employee_id == 1 - assert cosette.salary == 100000 - assert cosette.years_at_company == 4 +def test_solution(): + from solution_2 import cosette + + assert cosette.name == "Cosette Rodger" + assert cosette.employee_id == 1 + assert cosette.salary == 100000 + assert cosette.years_at_company == 4 diff --git a/introduction_to_python/classes/1_b_employee_raise/README.md b/introduction_to_python/classes/1_b_employee_raise/README.md index a33af34d..266ea232 100644 --- a/introduction_to_python/classes/1_b_employee_raise/README.md +++ b/introduction_to_python/classes/1_b_employee_raise/README.md @@ -1,27 +1,27 @@ -# Employee Class - Give Raises - -# Problem Description -Define a function `give_raises` that consumes `employee_lst`, a list of employee objects as defined in the previous question, and mutates each employee object in the list such that each employee is given a raise to their salary according to the following criteria: -* An employee gets a raise of $5,000 if they have been at the company for <= 5 years. -* An employee gets a raise of $8,000 if they have been at the company for > 5 and < 10 years. -* An employee gets a raise of $10,000 if they have been at the company for >= 10 years. - -## Example -``` -emp1 = Employee("John", 1, 45000, 8) -emp2 = Employee("Jane", 2, 22000, 1) -emp3 = Employee("Marie", 3, 90000, 10) - -give_raises([emp1, emp2, emp3]) == None -emp1.salary == 53000 -emp2.salary == 27000 -emp3.salary == 100000 - -``` - - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission +# Employee Class - Give Raises + +# Problem Description +Define a function `give_raises` that consumes `employee_lst`, a list of employee objects as defined in the previous question, and mutates each employee object in the list such that each employee is given a raise to their salary according to the following criteria: +* An employee gets a raise of $5,000 if they have been at the company for <= 5 years. +* An employee gets a raise of $8,000 if they have been at the company for > 5 and < 10 years. +* An employee gets a raise of $10,000 if they have been at the company for >= 10 years. + +## Example +``` +emp1 = Employee("John", 1, 45000, 8) +emp2 = Employee("Jane", 2, 22000, 1) +emp3 = Employee("Marie", 3, 90000, 10) + +give_raises([emp1, emp2, emp3]) == None +emp1.salary == 53000 +emp2.salary == 27000 +emp3.salary == 100000 + +``` + + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/classes/1_b_employee_raise/solution/solution.py b/introduction_to_python/classes/1_b_employee_raise/solution/solution.py index e69de29b..e740f2d0 100644 --- a/introduction_to_python/classes/1_b_employee_raise/solution/solution.py +++ b/introduction_to_python/classes/1_b_employee_raise/solution/solution.py @@ -0,0 +1,21 @@ +class Employee: + def __init__(self, name, employee_id, salary, years_at_company): + self.name = name + self.employee_id = employee_id + self.salary = salary + self.years_at_company = years_at_company + + def give_raise(self): + if self.years_at_company <= 5: + self.salary += 5000 + elif self.years_at_company >= 10: + self.salary += 10000 + else: + self.salary += 8000 + + +def give_raises(employee_lst): + for emp in employee_lst: + emp.give_raise() + + \ No newline at end of file diff --git a/introduction_to_python/classes/1_b_employee_raise/solution/test_solution.py b/introduction_to_python/classes/1_b_employee_raise/solution/test_solution.py index b969ef96..7b939496 100644 --- a/introduction_to_python/classes/1_b_employee_raise/solution/test_solution.py +++ b/introduction_to_python/classes/1_b_employee_raise/solution/test_solution.py @@ -1,16 +1,16 @@ -def test_solution(): - from solution import Employee, give_raises - - emp1 = Employee("John", 1, 45000, 8) - emp2 = Employee("Jane", 2, 22000, 1) - emp3 = Employee("Marie", 3, 90000, 10) - - give_raises([emp1, emp2, emp3]) - - emp4 = Employee("Mark", 3, 90000, 5) - give_raises([emp4]) - - assert emp1.salary == 53000 - assert emp2.salary == 27000 - assert emp3.salary == 100000 - assert emp4.salary == 95000 +def test_solution(): + from solution import Employee, give_raises + + emp1 = Employee("John", 1, 45000, 8) + emp2 = Employee("Jane", 2, 22000, 1) + emp3 = Employee("Marie", 3, 90000, 10) + + give_raises([emp1, emp2, emp3]) + + emp4 = Employee("Mark", 3, 90000, 5) + give_raises([emp4]) + + assert emp1.salary == 53000 + assert emp2.salary == 27000 + assert emp3.salary == 100000 + assert emp4.salary == 95000 diff --git a/introduction_to_python/classes/1_c_employee_sort/README.md b/introduction_to_python/classes/1_c_employee_sort/README.md index d6b5df5e..6d159a53 100644 --- a/introduction_to_python/classes/1_c_employee_sort/README.md +++ b/introduction_to_python/classes/1_c_employee_sort/README.md @@ -1,20 +1,20 @@ -# Employee Class - Sort Employees - -# Problem Description -Define a function `sort_employees` that consumes `employee_lst`, a list of employee objects as defined in the previous question, and returns a list of employee names sorted in alphabetical order. -Hint: `from operator import attrgetter` - -## Example -``` -emp1 = Employee("John", 1, 45,000, 8) -emp2 = Employee("Jane", 2, 22,000, 1) -emp3 = Employee("Marie", 3, 90,000, 10) - -sort_employees([emp1, emp2, emp3]) == ["Jane", "John", "Marie"] -``` - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission +# Employee Class - Sort Employees + +# Problem Description +Define a function `sort_employees` that consumes `employee_lst`, a list of employee objects as defined in the previous question, and returns a list of employee names sorted in alphabetical order. +Hint: `from operator import attrgetter` + +## Example +``` +emp1 = Employee("John", 1, 45,000, 8) +emp2 = Employee("Jane", 2, 22,000, 1) +emp3 = Employee("Marie", 3, 90,000, 10) + +sort_employees([emp1, emp2, emp3]) == ["Jane", "John", "Marie"] +``` + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/classes/1_c_employee_sort/solution/solution.py b/introduction_to_python/classes/1_c_employee_sort/solution/solution.py index e69de29b..d4ce0efa 100644 --- a/introduction_to_python/classes/1_c_employee_sort/solution/solution.py +++ b/introduction_to_python/classes/1_c_employee_sort/solution/solution.py @@ -0,0 +1,11 @@ +from operator import attrgetter +class Employee(): + def __init__(self, name, employee_id, salary, years_at_company): + self.name = name + self.employee_id = employee_id + self.salary = salary + self.years_at_company = years_at_company + +def sort_employees(employee_lst): + emp_lst = sorted(employee_lst, key=attrgetter("name")) + return [emp.name for emp in emp_lst] \ No newline at end of file diff --git a/introduction_to_python/classes/1_c_employee_sort/solution/test_solution.py b/introduction_to_python/classes/1_c_employee_sort/solution/test_solution.py index 63df05c1..4146b880 100644 --- a/introduction_to_python/classes/1_c_employee_sort/solution/test_solution.py +++ b/introduction_to_python/classes/1_c_employee_sort/solution/test_solution.py @@ -1,11 +1,11 @@ -def test_solution(): - from solution import Employee, sort_employees - - emp1 = Employee("John", 1, 45000, 8) - emp2 = Employee("Jane", 2, 22000, 1) - emp3 = Employee("Marie", 3, 90000, 10) - emp4 = Employee("Mark", 3, 90000, 5) - - assert sort_employees([emp1, emp2, emp3, emp4]) == ["Jane", "John", "Marie", "Mark"] - assert sort_employees([emp1]) == ["John"] - assert sort_employees([]) == [] +def test_solution(): + from solution import Employee, sort_employees + + emp1 = Employee("John", 1, 45000, 8) + emp2 = Employee("Jane", 2, 22000, 1) + emp3 = Employee("Marie", 3, 90000, 10) + emp4 = Employee("Mark", 3, 90000, 5) + + assert sort_employees([emp1, emp2, emp3, emp4]) == ["Jane", "John", "Marie", "Mark"] + assert sort_employees([emp1]) == ["John"] + assert sort_employees([]) == [] diff --git a/introduction_to_python/classes/2_a_person_child/README.md b/introduction_to_python/classes/2_a_person_child/README.md index 36263d67..1748ff83 100644 --- a/introduction_to_python/classes/2_a_person_child/README.md +++ b/introduction_to_python/classes/2_a_person_child/README.md @@ -1,24 +1,24 @@ -# Person and Child Class Definitions - -## Problem Description -Define a Python class Person. The constructor function should take in the following attributes: -* `name` - a string -* `age` - a non-negative integer -* `spouse` - either `None` or a `Person` object. -* `children` - a list of `Child` objects. -Define a Python class Child which inherits from the `Person` class. The constructor function should take in the following attributes: -* `name` - a string -* `age` - a non-negative integer -* `spouse` - either `None` or a `Person` object. -* `children` - a list of `Child` objects. -* `parents` - a list of `Person` objects. - -Define two person objects assigned to variables `jim` and `suzy` respectively, where `jim` has the name `Jim Brown`, an age of `45`, with `suzy` as his spouse and one child `martha`. `suzy` has the name `Suzy Brown`, an age of `42`, with `jim` as her spouse, and one child `martha`. -Define a child object assined to the variable `martha` with the name `Martha Brown`, aged `18`, having no spouse and no children, and having parents `jim` and `suzy`. - - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission +# Person and Child Class Definitions + +## Problem Description +Define a Python class Person. The constructor function should take in the following attributes: +* `name` - a string +* `age` - a non-negative integer +* `spouse` - either `None` or a `Person` object. +* `children` - a list of `Child` objects. +Define a Python class Child which inherits from the `Person` class. The constructor function should take in the following attributes: +* `name` - a string +* `age` - a non-negative integer +* `spouse` - either `None` or a `Person` object. +* `children` - a list of `Child` objects. +* `parents` - a list of `Person` objects. + +Define two person objects assigned to variables `jim` and `suzy` respectively, where `jim` has the name `Jim Brown`, an age of `45`, with `suzy` as his spouse and one child `martha`. `suzy` has the name `Suzy Brown`, an age of `42`, with `jim` as her spouse, and one child `martha`. +Define a child object assined to the variable `martha` with the name `Martha Brown`, aged `18`, having no spouse and no children, and having parents `jim` and `suzy`. + + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/classes/2_a_person_child/solution/solution.py b/introduction_to_python/classes/2_a_person_child/solution/solution.py index e69de29b..c117cc00 100644 --- a/introduction_to_python/classes/2_a_person_child/solution/solution.py +++ b/introduction_to_python/classes/2_a_person_child/solution/solution.py @@ -0,0 +1,18 @@ +class Person: + def __init__(self, name, age, spouse = None, children = []): + self.name = name + self.age = age + self.spouse = spouse + self.children = children + +class Child(Person): + def __init__(self, name, age, spouse, children, parents): + Person.__init__(self, name, age, spouse, children) + self.parents = parents + +jim = Person("Jim Brown", 45) +suzy = Person("Suzy Brown", 42, jim) +jim.spouse = suzy +martha = Child("Martha Brown", 18, None, [], [jim, suzy]) +jim.children.append(martha) +suzy.children.append(martha) \ No newline at end of file diff --git a/introduction_to_python/classes/2_a_person_child/solution/test_solution.py b/introduction_to_python/classes/2_a_person_child/solution/test_solution.py index dd65ea49..43831d7c 100644 --- a/introduction_to_python/classes/2_a_person_child/solution/test_solution.py +++ b/introduction_to_python/classes/2_a_person_child/solution/test_solution.py @@ -1,19 +1,19 @@ -def test_solution(): - from solution import jim, suzy, martha - - assert jim.name == "Jim Brown" - assert jim.age == 45 - assert jim.spouse == suzy - assert jim.children[0] == martha - - assert suzy.name == "Suzy Brown" - assert suzy.age == 42 - assert suzy.spouse == jim - assert suzy.children[0] == martha - - assert martha.name == "Martha Brown" - assert martha.age == 18 - assert martha.spouse == None - assert martha.children == [] - assert martha.parents[0] == jim - assert martha.parents[1] == suzy +def test_solution(): + from solution import jim, suzy, martha + + assert jim.name == "Jim Brown" + assert jim.age == 45 + assert jim.spouse == suzy + assert jim.children[0] == martha + + assert suzy.name == "Suzy Brown" + assert suzy.age == 42 + assert suzy.spouse == jim + assert suzy.children[0] == martha + + assert martha.name == "Martha Brown" + assert martha.age == 18 + assert martha.spouse == None + assert martha.children == [] + assert martha.parents[0] == jim + assert martha.parents[1] == suzy diff --git a/introduction_to_python/classes/2_b_person_get_sibilings/README.md b/introduction_to_python/classes/2_b_person_get_sibilings/README.md index 09ede32b..f67a2700 100644 --- a/introduction_to_python/classes/2_b_person_get_sibilings/README.md +++ b/introduction_to_python/classes/2_b_person_get_sibilings/README.md @@ -1,21 +1,21 @@ -# Person Class Method - Give Birth - -# Problem Description -Using your `Person` class and `Child` class you defined in a previous question, define a method inside the child class, `get_siblings`, that returns a list of names of all the siblings of the child object sorted in increasing order by age. -Hint: Note that a child can have a half sibling which is a child of one parent but not the other. - - ## Example - ``` - Jonny = Person("Jonny", 32, Beth, [Max, Annie, Ron]) - Beth = Person("Beth", 28, Jonny, [Max, Annie, Ron]) - Max = Child("Max", 5, None, [], [Beth, Jonny]) - Annie = Child("Annie", 10, None, [], [Beth, Jonny]) - Ron = Child("Ron", 7, None, [], [Beth, Jonny]) - Max.get_siblings() == ["Ron", "Annie"] - ``` - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission +# Person Class Method - Give Birth + +# Problem Description +Using your `Person` class and `Child` class you defined in a previous question, define a method inside the child class, `get_siblings`, that returns a list of names of all the siblings of the child object sorted in increasing order by age. +Hint: Note that a child can have a half sibling which is a child of one parent but not the other. + + ## Example + ``` + Jonny = Person("Jonny", 32, Beth, [Max, Annie, Ron]) + Beth = Person("Beth", 28, Jonny, [Max, Annie, Ron]) + Max = Child("Max", 5, None, [], [Beth, Jonny]) + Annie = Child("Annie", 10, None, [], [Beth, Jonny]) + Ron = Child("Ron", 7, None, [], [Beth, Jonny]) + Max.get_siblings() == ["Ron", "Annie"] + ``` + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/classes/2_b_person_get_sibilings/solution/test_solution.py b/introduction_to_python/classes/2_b_person_get_sibilings/solution/test_solution.py index de53b4ef..d9941c10 100644 --- a/introduction_to_python/classes/2_b_person_get_sibilings/solution/test_solution.py +++ b/introduction_to_python/classes/2_b_person_get_sibilings/solution/test_solution.py @@ -1,28 +1,28 @@ -def test_solution(): - from solution import Person, Child - - Jonny = Person("Jonny", 32, None, []) - Beth = Person("Beth", 28, Jonny, []) - Jonny.spouse = Beth - Max = Child("Max", 5, None, [], [Jonny]) - Annie = Child("Annie", 10, None, [], [Beth]) - Ron = Child("Ron", 7, None, [], [Beth, Jonny]) - Jonny.children.extend([Max, Ron]) - Beth.children.extend([Annie, Ron]) - - Jack = Person("Jack", 32, None, []) - Donna = Person("Donna", 28, Jack, []) - Jack.spouse = Donna - Alex = Child("Alex", 10, None, [], [Jack, Donna]) - Bob = Child("Bob", 12, None, [], [Jack, Donna]) - Emily = Child("Emily", 1, None, [], [Jack, Donna]) - Jack.children.extend([Alex, Bob, Emily]) - Donna.children.extend([Alex, Bob, Emily]) - - Ken = Person("Ken", 32, None, []) - Chloe = Child("Chloe", 5, None, [], [Ken]) - Ken.children.append(Chloe) - - assert Ron.get_siblings() == ["Max", "Annie"] - assert Alex.get_siblings() == ["Emily", "Bob"] - assert Chloe.get_siblings() == [] +def test_solution(): + from solution import Person, Child + + Jonny = Person("Jonny", 32, None, []) + Beth = Person("Beth", 28, Jonny, []) + Jonny.spouse = Beth + Max = Child("Max", 5, None, [], [Jonny]) + Annie = Child("Annie", 10, None, [], [Beth]) + Ron = Child("Ron", 7, None, [], [Beth, Jonny]) + Jonny.children.extend([Max, Ron]) + Beth.children.extend([Annie, Ron]) + + Jack = Person("Jack", 32, None, []) + Donna = Person("Donna", 28, Jack, []) + Jack.spouse = Donna + Alex = Child("Alex", 10, None, [], [Jack, Donna]) + Bob = Child("Bob", 12, None, [], [Jack, Donna]) + Emily = Child("Emily", 1, None, [], [Jack, Donna]) + Jack.children.extend([Alex, Bob, Emily]) + Donna.children.extend([Alex, Bob, Emily]) + + Ken = Person("Ken", 32, None, []) + Chloe = Child("Chloe", 5, None, [], [Ken]) + Ken.children.append(Chloe) + + assert Ron.get_siblings() == ["Max", "Annie"] + assert Alex.get_siblings() == ["Emily", "Bob"] + assert Chloe.get_siblings() == [] diff --git a/introduction_to_python/classes/2_c_person_get_married/README.md b/introduction_to_python/classes/2_c_person_get_married/README.md index 85402a6c..e5c750f6 100644 --- a/introduction_to_python/classes/2_c_person_get_married/README.md +++ b/introduction_to_python/classes/2_c_person_get_married/README.md @@ -1,20 +1,20 @@ -# Person Class Method - Get Married - -# Problem Description -Using your `Person` class and `Child` class you defined in a previous question, define a method, `get_married`, that consumes `self` and `other` and sets the spouse of both person objects to be the other person. - - ## Example - ``` - Anton = Person("Anton", 29, None, []) - Nell = Person("Nell", 26, None, []) - Anton.get_married(Nell) == None - Anton.spouse == Nell - Nell.spouse == Anton - ``` - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - - -## Submission +# Person Class Method - Get Married + +# Problem Description +Using your `Person` class and `Child` class you defined in a previous question, define a method, `get_married`, that consumes `self` and `other` and sets the spouse of both person objects to be the other person. + + ## Example + ``` + Anton = Person("Anton", 29, None, []) + Nell = Person("Nell", 26, None, []) + Anton.get_married(Nell) == None + Anton.spouse == Nell + Nell.spouse == Anton + ``` + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/classes/2_c_person_get_married/solution/test_solution.py b/introduction_to_python/classes/2_c_person_get_married/solution/test_solution.py index 47a32c65..b994fe61 100644 --- a/introduction_to_python/classes/2_c_person_get_married/solution/test_solution.py +++ b/introduction_to_python/classes/2_c_person_get_married/solution/test_solution.py @@ -1,9 +1,9 @@ -def test_solution(): - from solution import Person, Child - - Anton = Person("Anton", 29, None, []) - Nell = Person("Nell", 26, None, []) - Anton.get_married(Nell) - - assert Anton.spouse.name == "Nell" - assert Nell.spouse.name == "Anton" +def test_solution(): + from solution import Person, Child + + Anton = Person("Anton", 29, None, []) + Nell = Person("Nell", 26, None, []) + Anton.get_married(Nell) + + assert Anton.spouse.name == "Nell" + assert Nell.spouse.name == "Anton" diff --git a/introduction_to_python/classes/2_calendar_clock/README.md b/introduction_to_python/classes/2_calendar_clock/README.md index b9d79590..4c0a8864 100644 --- a/introduction_to_python/classes/2_calendar_clock/README.md +++ b/introduction_to_python/classes/2_calendar_clock/README.md @@ -1,28 +1,28 @@ -# Multiple Inheritance Implementation - -# Problem Description - Write a Python program to implement Multiple Inheritance. Write two base classes `Clock` and `Calendar` and a derived class `CalendarClock` which derives from the base classes `Clock` and `Calendar`. - In the `Clock` class: - * The constructor function should take in `hrs` an integer between `0-23`, `mins` and integer between `0-59`, and `secs` an integer between `0-59` and set the values in the constructor. - * Use the `__str__` magic method to create a string representation for the clock in the format `hrs:mins:secs`. Hint: Use `"{0:02d}:{1:02d}:{2:02d}".format()` - - In the `Calendar` class: - * The constructor function should take in `day` an integer between `1-31`, `month` and integer between `1-12`, and `year` an integer between `1900-2020` and set the values in the constructor. For the sake of this question, we will not worry about checking if the day is a valid day for a given month. - * Use the `__str__` magic method to create a string representation for the calendar in the format `day/month/year`. Hint: Use `"{0:02d}/{1:02d}/{2:4d}".format()` - - In the `CalendarClock` derived class: - * The constructor function should take in `day`, `month`, `year`, `hrs`, `mins`, `secs` and set the values using the base class constructors in its constructor. - * Use the `__str__` magic method to create a string representation for the calendar in the format `day/month/year hrs:mins:secs`. - - For Example: - ``` - str(Clock(10, 30, 5)) == "10:30:05" - str(Calendar(20, 10, 2020)) == "20/10/2020" - str(CalendarClock(20, 10, 2020, 10, 30, 5)) == "20/10/2020, 10:30:05" - ``` - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission +# Multiple Inheritance Implementation + +# Problem Description + Write a Python program to implement Multiple Inheritance. Write two base classes `Clock` and `Calendar` and a derived class `CalendarClock` which derives from the base classes `Clock` and `Calendar`. + In the `Clock` class: + * The constructor function should take in `hrs` an integer between `0-23`, `mins` and integer between `0-59`, and `secs` an integer between `0-59` and set the values in the constructor. + * Use the `__str__` magic method to create a string representation for the clock in the format `hrs:mins:secs`. Hint: Use `"{0:02d}:{1:02d}:{2:02d}".format()` + + In the `Calendar` class: + * The constructor function should take in `day` an integer between `1-31`, `month` and integer between `1-12`, and `year` an integer between `1900-2020` and set the values in the constructor. For the sake of this question, we will not worry about checking if the day is a valid day for a given month. + * Use the `__str__` magic method to create a string representation for the calendar in the format `day/month/year`. Hint: Use `"{0:02d}/{1:02d}/{2:4d}".format()` + + In the `CalendarClock` derived class: + * The constructor function should take in `day`, `month`, `year`, `hrs`, `mins`, `secs` and set the values using the base class constructors in its constructor. + * Use the `__str__` magic method to create a string representation for the calendar in the format `day/month/year hrs:mins:secs`. + + For Example: + ``` + str(Clock(10, 30, 5)) == "10:30:05" + str(Calendar(20, 10, 2020)) == "20/10/2020" + str(CalendarClock(20, 10, 2020, 10, 30, 5)) == "20/10/2020, 10:30:05" + ``` + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/classes/2_calendar_clock/solution/solution.py b/introduction_to_python/classes/2_calendar_clock/solution/solution.py index 94b01652..1cfba770 100644 --- a/introduction_to_python/classes/2_calendar_clock/solution/solution.py +++ b/introduction_to_python/classes/2_calendar_clock/solution/solution.py @@ -1,27 +1,27 @@ -class Clock(object): - def __init__(self, hrs=0, mins=0, secs=0): - self.hrs = hrs - self.mins = mins - self.secs = secs - - def __str__(self): - return "{0:02d}:{1:02d}:{2:02d}".format(self.hrs, self.mins, self.secs) - - -class Calendar(object): - def __init__(self, day=1, month=1, year=2020): - self.day = day - self.month = month - self.year = year - - def __str__(self): - return "{0:02d}/{1:02d}/{2:4d}".format(self.day, self.month, self.year) - - -class CalendarClock(Clock, Calendar): - def __init__(self, day, month, year, hrs, mins, secs): - Clock.__init__(self, hrs, mins, secs) - Calendar.__init__(self, day, month, year) - - def __str__(self): - return Calendar.__str__(self) + ", " + Clock.__str__(self) +class Clock(object): + def __init__(self, hrs=0, mins=0, secs=0): + self.hrs = hrs + self.mins = mins + self.secs = secs + + def __str__(self): + return "{0:02d}:{1:02d}:{2:02d}".format(self.hrs, self.mins, self.secs) + + +class Calendar(object): + def __init__(self, day=1, month=1, year=2020): + self.day = day + self.month = month + self.year = year + + def __str__(self): + return "{0:02d}/{1:02d}/{2:4d}".format(self.day, self.month, self.year) + + +class CalendarClock(Clock, Calendar): + def __init__(self, day, month, year, hrs, mins, secs): + Clock.__init__(self, hrs, mins, secs) + Calendar.__init__(self, day, month, year) + + def __str__(self): + return Calendar.__str__(self) + ", " + Clock.__str__(self) diff --git a/introduction_to_python/classes/2_calendar_clock/solution/test_solution.py b/introduction_to_python/classes/2_calendar_clock/solution/test_solution.py index 5beece9f..12f681ee 100644 --- a/introduction_to_python/classes/2_calendar_clock/solution/test_solution.py +++ b/introduction_to_python/classes/2_calendar_clock/solution/test_solution.py @@ -1,6 +1,6 @@ -def test_solution(): - from solution import Clock, Calendar, CalendarClock - - assert str(Clock(10, 30, 5)) == "10:30:05" - assert str(Calendar(20, 10, 2020)) == "20/10/2020" - assert str(CalendarClock(20, 10, 2020, 10, 30, 5)) == "20/10/2020, 10:30:05" +def test_solution(): + from solution import Clock, Calendar, CalendarClock + + assert str(Clock(10, 30, 5)) == "10:30:05" + assert str(Calendar(20, 10, 2020)) == "20/10/2020" + assert str(CalendarClock(20, 10, 2020, 10, 30, 5)) == "20/10/2020, 10:30:05" diff --git a/introduction_to_python/classes/2_d_person_get_divorced/README.md b/introduction_to_python/classes/2_d_person_get_divorced/README.md index 8ada83e4..4f00c1d3 100644 --- a/introduction_to_python/classes/2_d_person_get_divorced/README.md +++ b/introduction_to_python/classes/2_d_person_get_divorced/README.md @@ -1,20 +1,20 @@ -# Person Class Method - Get Divorced - -# Problem Description -Using your `Person` class and `Child` class you defined in a previous question, define a method, `get_divorced`, and if the person is married,sets the spouse of the person and their spouse to be `None`. - - ## Example - ``` - John = Person("John", 31, Kathy, []) - Kathy = Person("Kathy", 29, John, []) - John.get_divorced() == None - John.spouse == None - Kathy.spouse == None - ``` - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - - -## Submission +# Person Class Method - Get Divorced + +# Problem Description +Using your `Person` class and `Child` class you defined in a previous question, define a method, `get_divorced`, and if the person is married,sets the spouse of the person and their spouse to be `None`. + + ## Example + ``` + John = Person("John", 31, Kathy, []) + Kathy = Person("Kathy", 29, John, []) + John.get_divorced() == None + John.spouse == None + Kathy.spouse == None + ``` + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/classes/2_d_person_get_divorced/solution/test_solution.py b/introduction_to_python/classes/2_d_person_get_divorced/solution/test_solution.py index 7e36d4fd..4b074327 100644 --- a/introduction_to_python/classes/2_d_person_get_divorced/solution/test_solution.py +++ b/introduction_to_python/classes/2_d_person_get_divorced/solution/test_solution.py @@ -1,17 +1,17 @@ -def test_solution(): - from solution import Person - from solution import Child - - jim = Person("Jim Brown", 45) - suzy = Person("Suzy Brown", 42, jim) - jim.spouse = suzy - martha = Child("Martha Brown", 18, None, [], [jim, suzy]) - jim.children.append(martha) - suzy.children.append(martha) - - jim.get_divorced() - martha.get_divorced() - - assert jim.spouse == None - assert suzy.spouse == None - assert martha.spouse == None +def test_solution(): + from solution import Person + from solution import Child + + jim = Person("Jim Brown", 45) + suzy = Person("Suzy Brown", 42, jim) + jim.spouse = suzy + martha = Child("Martha Brown", 18, None, [], [jim, suzy]) + jim.children.append(martha) + suzy.children.append(martha) + + jim.get_divorced() + martha.get_divorced() + + assert jim.spouse == None + assert suzy.spouse == None + assert martha.spouse == None diff --git a/introduction_to_python/classes/3_a_person_give_birth/README.md b/introduction_to_python/classes/3_a_person_give_birth/README.md index de73a495..9b4c1919 100644 --- a/introduction_to_python/classes/3_a_person_give_birth/README.md +++ b/introduction_to_python/classes/3_a_person_give_birth/README.md @@ -1,19 +1,19 @@ -# Person Class Method - Give Birth - -# Problem Description -Using your `Person` class and `Child` class you defined in a previous question, define a method, `give_birth`, that consumes `self` and a string `name` and updates the child lists of self and their spouse, if they have a spouse, to contain a new child object with name `name`, age `0`, having no spouse and no children, with parents `self` and the spouse of self, if they have a spouse or None as the second parent. - - ## Example - ``` - Jonny = Person("Jonny", 32, None, []) - Beth = Person("Beth", 28, Jonny, []) - Jonny.spouse = Beth - Beth.give_birth("Sam") == None - Beth.children = [Child("Sam", 0, None, [], (Beth, Jonny))] - ``` - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission +# Person Class Method - Give Birth + +# Problem Description +Using your `Person` class and `Child` class you defined in a previous question, define a method, `give_birth`, that consumes `self` and a string `name` and updates the child lists of self and their spouse, if they have a spouse, to contain a new child object with name `name`, age `0`, having no spouse and no children, with parents `self` and the spouse of self, if they have a spouse or None as the second parent. + + ## Example + ``` + Jonny = Person("Jonny", 32, None, []) + Beth = Person("Beth", 28, Jonny, []) + Jonny.spouse = Beth + Beth.give_birth("Sam") == None + Beth.children = [Child("Sam", 0, None, [], (Beth, Jonny))] + ``` + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/classes/3_a_person_give_birth/solution/test_solution.py b/introduction_to_python/classes/3_a_person_give_birth/solution/test_solution.py index dbff01a4..6095d9fc 100644 --- a/introduction_to_python/classes/3_a_person_give_birth/solution/test_solution.py +++ b/introduction_to_python/classes/3_a_person_give_birth/solution/test_solution.py @@ -1,23 +1,23 @@ -def test_solution(): - from solution import Person, Child - - Jonny = Person("Jonny", 32, None, []) - Beth = Person("Beth", 28, Jonny, []) - Jonny.spouse = Beth - Beth.give_birth("Sam") - - Jane = Person("Jane", 32, None, []) - Max = Child("Max", 2, None, [], [Jane]) - Jane.children.append(Max) - Jane.give_birth("Annie") - - assert Beth.children[0].name == "Sam" - assert Jonny.children[0].name == "Sam" - assert Beth.children[0].parents[0].name == "Beth" - assert Jonny.children[0].parents[1].name == "Jonny" - - assert Jane.children[1].name == "Annie" - assert Jane.children[1].parents[0].name == "Jane" - assert Jane.children[1].age == 0 - assert Jane.children[1].spouse == None - assert Jane.children[1].children == [] +def test_solution(): + from solution import Person, Child + + Jonny = Person("Jonny", 32, None, []) + Beth = Person("Beth", 28, Jonny, []) + Jonny.spouse = Beth + Beth.give_birth("Sam") + + Jane = Person("Jane", 32, None, []) + Max = Child("Max", 2, None, [], [Jane]) + Jane.children.append(Max) + Jane.give_birth("Annie") + + assert Beth.children[0].name == "Sam" + assert Jonny.children[0].name == "Sam" + assert Beth.children[0].parents[0].name == "Beth" + assert Jonny.children[0].parents[1].name == "Jonny" + + assert Jane.children[1].name == "Annie" + assert Jane.children[1].parents[0].name == "Jane" + assert Jane.children[1].age == 0 + assert Jane.children[1].spouse == None + assert Jane.children[1].children == [] diff --git a/introduction_to_python/classes/3_student_highest_average/README.md b/introduction_to_python/classes/3_student_highest_average/README.md index 92ed9f4e..e757af08 100644 --- a/introduction_to_python/classes/3_student_highest_average/README.md +++ b/introduction_to_python/classes/3_student_highest_average/README.md @@ -1,19 +1,19 @@ -# Student Class - Highest Average - -# Problem Description -Define a class `Student` with attributes `name` - a string, `age` - a non-negative integer, and `grades` - a list of integers between 0-100. -Define a function, `highest_avg`, that consumes a non-empty list of student objects `stud_lst`, and returns the name of the sudent with the highest average. If two students have the same average, return the name of the student who's name comes first alphabetically. - - ## Example - ``` - Anton = Student("Anton", 29, [75, 82, 96, 100, 50]) - Nell = Student("Nell", 26, [98, 95, 89, 92, 100, 90]) - Cosette = Student("Cosette", 20, [85, 72, 96, 99, 92]) - highest_avg([Anton, Nell, Cosette]) == "Nell" - ``` - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission +# Student Class - Highest Average + +# Problem Description +Define a class `Student` with attributes `name` - a string, `age` - a non-negative integer, and `grades` - a list of integers between 0-100. +Define a function, `highest_avg`, that consumes a non-empty list of student objects `stud_lst`, and returns the name of the sudent with the highest average. If two students have the same average, return the name of the student who's name comes first alphabetically. + + ## Example + ``` + Anton = Student("Anton", 29, [75, 82, 96, 100, 50]) + Nell = Student("Nell", 26, [98, 95, 89, 92, 100, 90]) + Cosette = Student("Cosette", 20, [85, 72, 96, 99, 92]) + highest_avg([Anton, Nell, Cosette]) == "Nell" + ``` + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/classes/3_student_highest_average/solution/test_solution.py b/introduction_to_python/classes/3_student_highest_average/solution/test_solution.py index 2169ec94..c8dc065e 100644 --- a/introduction_to_python/classes/3_student_highest_average/solution/test_solution.py +++ b/introduction_to_python/classes/3_student_highest_average/solution/test_solution.py @@ -1,11 +1,11 @@ -def test_solution(): - from solution import Student, highest_avg - - Anton = Student("Anton", 29, [75, 82, 96, 100, 50]) - Nell = Student("Nell", 26, [98, 95, 89, 92, 100, 90]) - Cosette = Student("Cosette", 20, [85, 72, 96, 99, 92]) - Cam = Student("Cam", 25, [85, 72, 96, 99, 92]) - - assert highest_avg([Anton, Nell, Cosette]) == "Nell" - assert highest_avg([Cam, Anton, Cosette]) == "Cam" - assert highest_avg([Anton]) == "Anton" +def test_solution(): + from solution import Student, highest_avg + + Anton = Student("Anton", 29, [75, 82, 96, 100, 50]) + Nell = Student("Nell", 26, [98, 95, 89, 92, 100, 90]) + Cosette = Student("Cosette", 20, [85, 72, 96, 99, 92]) + Cam = Student("Cam", 25, [85, 72, 96, 99, 92]) + + assert highest_avg([Anton, Nell, Cosette]) == "Nell" + assert highest_avg([Cam, Anton, Cosette]) == "Cam" + assert highest_avg([Anton]) == "Anton" diff --git a/introduction_to_python/classes/README.md b/introduction_to_python/classes/README.md index 2031dda9..82d6bc53 100644 --- a/introduction_to_python/classes/README.md +++ b/introduction_to_python/classes/README.md @@ -1,15 +1,15 @@ -# Exercises for Classes - - -| Exercise ID | Exercise | -|:-----------:|:--------:| -| easy_e1 | [Employee Class](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/employee_class) | -| easy_e2 | [Employee Raise](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/employee_raise) | -| easy_e3 | [Employee Sort](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/employee_sort) | -| medium_e1 | [Calendar Clock](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/calendar_clock) | -| medium_e2 | [Person Child](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/person_child) | -| medium_e2 | [Person Get Sibilings](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/person_get_sibilings) | -| medium_e3 | [Person Get Married](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/2_string_parenthesis) | -| medium_e4 | [Person Get Divorced](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/person_get_divorced) | -| hard_e1 | [Person Give Birth](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/person_give_birth) | -| hard_e2 | [Student Highest Average](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/student_highest_average) | +# Exercises for Classes + + +| Exercise ID | Exercise | +|:-----------:|:--------:| +| easy_e1 | [Employee Class](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/employee_class) | +| easy_e2 | [Employee Raise](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/employee_raise) | +| easy_e3 | [Employee Sort](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/employee_sort) | +| medium_e1 | [Calendar Clock](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/calendar_clock) | +| medium_e2 | [Person Child](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/person_child) | +| medium_e2 | [Person Get Sibilings](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/person_get_sibilings) | +| medium_e3 | [Person Get Married](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/2_string_parenthesis) | +| medium_e4 | [Person Get Divorced](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/person_get_divorced) | +| hard_e1 | [Person Give Birth](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/person_give_birth) | +| hard_e2 | [Student Highest Average](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/classes/student_highest_average) | diff --git a/introduction_to_python/functions/1_below_100/README.md b/introduction_to_python/functions/1_below_100/README.md index dd115299..e95a60e8 100644 --- a/introduction_to_python/functions/1_below_100/README.md +++ b/introduction_to_python/functions/1_below_100/README.md @@ -1,20 +1,20 @@ -# Range - -## Motivation -Python function definition allows the developer to construct a block of code which performs certain functionality. - -## Problem Description -Write a Python function `below_100` that consumes an integer `n`. -If `n` is less than equal to 100 return `"less than 100"`, otherwise return `"greater than 100"`. - -## Example -``` -below_100(200) == "greater than 100" -below_100(50) == "less than 100" -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Range + +## Motivation +Python function definition allows the developer to construct a block of code which performs certain functionality. + +## Problem Description +Write a Python function `below_100` that consumes an integer `n`. +If `n` is less than equal to 100 return `"less than 100"`, otherwise return `"greater than 100"`. + +## Example +``` +below_100(200) == "greater than 100" +below_100(50) == "less than 100" +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_to_python/functions/1_below_100/solution/solution.py b/introduction_to_python/functions/1_below_100/solution/solution.py index aeb50baa..c1322166 100644 --- a/introduction_to_python/functions/1_below_100/solution/solution.py +++ b/introduction_to_python/functions/1_below_100/solution/solution.py @@ -1 +1,14 @@ -# Write your solution here +# Write your solution here +def below_100(*args): +n = + + + + + + + +#if n in num == 100: + #print('Greater than 100') + #elif n in num != 100 + #print('Lower than 100') diff --git a/introduction_to_python/functions/1_below_100/solution/test_solution.py b/introduction_to_python/functions/1_below_100/solution/test_solution.py index da8dd313..8b745573 100644 --- a/introduction_to_python/functions/1_below_100/solution/test_solution.py +++ b/introduction_to_python/functions/1_below_100/solution/test_solution.py @@ -1,7 +1,7 @@ -import solution - - -def test_solution(): - assert solution.below_100(100) == "greater than 100" - assert solution.below_100(200) == "greater than 100" - assert solution.below_100(55) == "less than 100" +import solution + + +def test_solution(): + assert solution.below_100(100) == "greater than 100" + assert solution.below_100(200) == "greater than 100" + assert solution.below_100(55) == "less than 100" diff --git a/introduction_to_python/functions/1_concat_args/README.md b/introduction_to_python/functions/1_concat_args/README.md index 409ef39e..051100cd 100644 --- a/introduction_to_python/functions/1_concat_args/README.md +++ b/introduction_to_python/functions/1_concat_args/README.md @@ -1,19 +1,19 @@ -# Concat Args - -## Motivation -Python function definition allows the developer to construct a block of code which performs certain functionality. - -## Problem Description -Write a Python function `concat_input` that consumes 2 arguements, `val_1` and `val_2` which are both strings and returns a string which -is the concatenation of the two strings. - -## Example -``` -concat_input("hi ", "there!") == "hi there!" -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Concat Args + +## Motivation +Python function definition allows the developer to construct a block of code which performs certain functionality. + +## Problem Description +Write a Python function `concat_input` that consumes 2 arguements, `val_1` and `val_2` which are both strings and returns a string which +is the concatenation of the two strings. + +## Example +``` +concat_input("hi ", "there!") == "hi there!" +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_to_python/functions/1_concat_args/solution/test_solution.py b/introduction_to_python/functions/1_concat_args/solution/test_solution.py index d836a977..c1a61fb4 100644 --- a/introduction_to_python/functions/1_concat_args/solution/test_solution.py +++ b/introduction_to_python/functions/1_concat_args/solution/test_solution.py @@ -1,6 +1,6 @@ -import solution - - -def test_solution(): - assert solution.concat_input("hello ", "world") == "hello world" - assert solution.concat_input("hello", "") == "hello" +import solution + + +def test_solution(): + assert solution.concat_input("hello ", "world") == "hello world" + assert solution.concat_input("hello", "") == "hello" diff --git a/introduction_to_python/functions/1_return_hello/README.md b/introduction_to_python/functions/1_return_hello/README.md index 24c84d42..63c2c412 100644 --- a/introduction_to_python/functions/1_return_hello/README.md +++ b/introduction_to_python/functions/1_return_hello/README.md @@ -1,19 +1,19 @@ -# Return Hello - -## Motivation -Python function definition allows the developer to construct a block of code which performs certain functionality. - -## Problem Description -Write a Python function `hello` that consumes a string `name`. -Your goal is to concatinate the prefix `"Hello "` to the object `name` and output the resulting string. - -## Example -``` -hello("Dorthy") == "Hello Dorthy" -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Return Hello + +## Motivation +Python function definition allows the developer to construct a block of code which performs certain functionality. + +## Problem Description +Write a Python function `hello` that consumes a string `name`. +Your goal is to concatinate the prefix `"Hello "` to the object `name` and output the resulting string. + +## Example +``` +hello("Dorthy") == "Hello Dorthy" +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_to_python/functions/1_return_hello/solution/test_solution.py b/introduction_to_python/functions/1_return_hello/solution/test_solution.py index 3c38d873..ad300b03 100644 --- a/introduction_to_python/functions/1_return_hello/solution/test_solution.py +++ b/introduction_to_python/functions/1_return_hello/solution/test_solution.py @@ -1,7 +1,7 @@ -import solution - - -def test_solution(): - assert solution.hello("Nell") == "Hello Nell" - assert solution.hello("Anton") == "Hello Anton" - assert solution.hello("Wasif") == "Hello Wasif" +import solution + + +def test_solution(): + assert solution.hello("Nell") == "Hello Nell" + assert solution.hello("Anton") == "Hello Anton" + assert solution.hello("Wasif") == "Hello Wasif" diff --git a/introduction_to_python/functions/2_max_value/README.md b/introduction_to_python/functions/2_max_value/README.md index e70505c6..74d0fbf1 100644 --- a/introduction_to_python/functions/2_max_value/README.md +++ b/introduction_to_python/functions/2_max_value/README.md @@ -1,19 +1,19 @@ -# Max Value - -## Motivation -In Python every variable name is a reference. When we pass a variable to a function, a new reference to the object is created. - -## Problem Description -Write a Python function `max_val` that consumes 3 integer `a`, `b` ,`c`. -The function should return the maximum value of `a`, `b`, and `c`. - -## Example -``` -max_val(1, 4, 2) == 2 -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Max Value + +## Motivation +In Python every variable name is a reference. When we pass a variable to a function, a new reference to the object is created. + +## Problem Description +Write a Python function `max_val` that consumes 3 integer `a`, `b` ,`c`. +The function should return the maximum value of `a`, `b`, and `c`. + +## Example +``` +max_val(1, 4, 2) == 2 +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_to_python/functions/2_max_value/solution/solution.py b/introduction_to_python/functions/2_max_value/solution/solution.py index aeb50baa..e323a46e 100644 --- a/introduction_to_python/functions/2_max_value/solution/solution.py +++ b/introduction_to_python/functions/2_max_value/solution/solution.py @@ -1 +1 @@ -# Write your solution here +# Write your solution here diff --git a/introduction_to_python/functions/2_max_value/solution/test_solution.py b/introduction_to_python/functions/2_max_value/solution/test_solution.py index ec5c7a72..0f4f4b6c 100644 --- a/introduction_to_python/functions/2_max_value/solution/test_solution.py +++ b/introduction_to_python/functions/2_max_value/solution/test_solution.py @@ -1,8 +1,8 @@ -import solution - - -def test_solution(): - assert solution.max_val(5, 3, 1) == 5 - assert solution.max_val(5, 5, 5) == 5 - assert solution.max_val(1, 3, 1) == 3 - assert solution.max_val(2, 1, 6) == 6 +import solution + + +def test_solution(): + assert solution.max_val(5, 3, 1) == 5 + assert solution.max_val(5, 5, 5) == 5 + assert solution.max_val(1, 3, 1) == 3 + assert solution.max_val(2, 1, 6) == 6 diff --git a/introduction_to_python/functions/2_shut_down/README.md b/introduction_to_python/functions/2_shut_down/README.md index c41d5cfc..a452190d 100644 --- a/introduction_to_python/functions/2_shut_down/README.md +++ b/introduction_to_python/functions/2_shut_down/README.md @@ -1,20 +1,20 @@ -# Shut Down - -## Motivation -A Boolean Value is either `True` or `False`. We can compute certain logic -within a function conditional on some boolean value. - -## Problem Description -Write a Python function `shut_down` that consumes a boolean value `x`. -If `x` is the boolean value `True` return the string `"SHUTDOWN"`, otherwise return the string `"SHUTDOWN ABORTED"`. - -## Example: -``` -shut_down(True) == "SHUTDOWN" -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Shut Down + +## Motivation +A Boolean Value is either `True` or `False`. We can compute certain logic +within a function conditional on some boolean value. + +## Problem Description +Write a Python function `shut_down` that consumes a boolean value `x`. +If `x` is the boolean value `True` return the string `"SHUTDOWN"`, otherwise return the string `"SHUTDOWN ABORTED"`. + +## Example: +``` +shut_down(True) == "SHUTDOWN" +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_to_python/functions/2_shut_down/solution/test_solution.py b/introduction_to_python/functions/2_shut_down/solution/test_solution.py index 5cfb7dd5..cba9fb58 100644 --- a/introduction_to_python/functions/2_shut_down/solution/test_solution.py +++ b/introduction_to_python/functions/2_shut_down/solution/test_solution.py @@ -1,6 +1,6 @@ -from solution import shut_down - - -def test_solution(): - assert shut_down(True) == "SHUTDOWN" - assert shut_down(False) == "SHUTDOWN ABORTED" +from solution import shut_down + + +def test_solution(): + assert shut_down(True) == "SHUTDOWN" + assert shut_down(False) == "SHUTDOWN ABORTED" diff --git a/introduction_to_python/functions/2_variable_arguments/README.md b/introduction_to_python/functions/2_variable_arguments/README.md index 44096c19..a3f024e9 100644 --- a/introduction_to_python/functions/2_variable_arguments/README.md +++ b/introduction_to_python/functions/2_variable_arguments/README.md @@ -1,18 +1,18 @@ -# Variable Arguments - -## Motivation -Variable length argument is a feature that allows a function to receive any number of arguments. There are situations where we want a function to handle variable number of arguments according to requirement (*args) (*Behaves like a list) - -## Problem Description -Write a Python function `concat_args` that takes a variable length arguement `*args` which contains string objects and returns the concatination the variables. If `*args` is empty output the empty string. - -## Example -``` -concat_args("Hello ", "There") == "Hello There" -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission +# Variable Arguments + +## Motivation +Variable length argument is a feature that allows a function to receive any number of arguments. There are situations where we want a function to handle variable number of arguments according to requirement (*args) (*Behaves like a list) + +## Problem Description +Write a Python function `concat_args` that takes a variable length arguement `*args` which contains string objects and returns the concatination the variables. If `*args` is empty output the empty string. + +## Example +``` +concat_args("Hello ", "There") == "Hello There" +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/functions/2_variable_arguments/solution/test_solution.py b/introduction_to_python/functions/2_variable_arguments/solution/test_solution.py index 6c983208..cab243ae 100644 --- a/introduction_to_python/functions/2_variable_arguments/solution/test_solution.py +++ b/introduction_to_python/functions/2_variable_arguments/solution/test_solution.py @@ -1,7 +1,7 @@ -from solution import concat_args - - -def test_solution(): - assert concat_args("Hello ", "There") == "Hello There" - assert concat_args() == "" - assert concat_args("COZY") == "COZY" +from solution import concat_args + + +def test_solution(): + assert concat_args("Hello ", "There") == "Hello There" + assert concat_args() == "" + assert concat_args("COZY") == "COZY" diff --git a/introduction_to_python/functions/3_count_even/README.md b/introduction_to_python/functions/3_count_even/README.md index 7ebd6f8e..e189a266 100644 --- a/introduction_to_python/functions/3_count_even/README.md +++ b/introduction_to_python/functions/3_count_even/README.md @@ -1,18 +1,18 @@ -# Count Even - -## Motivation -Functions can take in a variable length argument `*args` which can contain any number of arguments passed into a function. - -## Problem Description -Write a python function `count_even` with a variable-length argument `*args` of integers. Return the number of even integers are in `*args`. - -## Example -``` -count_even(1, 2, 3, 4) == 2 -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Count Even + +## Motivation +Functions can take in a variable length argument `*args` which can contain any number of arguments passed into a function. + +## Problem Description +Write a python function `count_even` with a variable-length argument `*args` of integers. Return the number of even integers are in `*args`. + +## Example +``` +count_even(1, 2, 3, 4) == 2 +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_to_python/functions/3_count_even/solution/test_solution.py b/introduction_to_python/functions/3_count_even/solution/test_solution.py index a513108a..36b8d37a 100644 --- a/introduction_to_python/functions/3_count_even/solution/test_solution.py +++ b/introduction_to_python/functions/3_count_even/solution/test_solution.py @@ -1,8 +1,8 @@ -from solution import count_even - - -def test_solution(): - assert count_even(1, 2, 3, 4) == 2 - assert count_even(1, 3, 5) == 0 - assert count_even() == 0 - assert count_even(2, 4, 6, 8, 10) == 5 +from solution import count_even + + +def test_solution(): + assert count_even(1, 2, 3, 4) == 2 + assert count_even(1, 3, 5) == 0 + assert count_even() == 0 + assert count_even(2, 4, 6, 8, 10) == 5 diff --git a/introduction_to_python/functions/3_divisible_by_3/README.md b/introduction_to_python/functions/3_divisible_by_3/README.md index 8d0f10a7..7f934afb 100644 --- a/introduction_to_python/functions/3_divisible_by_3/README.md +++ b/introduction_to_python/functions/3_divisible_by_3/README.md @@ -1,19 +1,19 @@ -# Divisible By 3 - Variable Length Arguments - -## Motivation -Functions can take in a variable length argument `*args` which can contain any number of arguments passed into a function. - -## Problem Description -Write a python function `divisible_by_3` with a variable-length arguement `*args` of integers, and returns a list of all the numbers in `*args` divisible by three. - -## Example -``` -div_by_3(2, 3, 5, 6, 9) == [3, 6, 9] -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory - +# Divisible By 3 - Variable Length Arguments + +## Motivation +Functions can take in a variable length argument `*args` which can contain any number of arguments passed into a function. + +## Problem Description +Write a python function `divisible_by_3` with a variable-length arguement `*args` of integers, and returns a list of all the numbers in `*args` divisible by three. + +## Example +``` +div_by_3(2, 3, 5, 6, 9) == [3, 6, 9] +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory + diff --git a/introduction_to_python/functions/3_divisible_by_3/solution/solution.py b/introduction_to_python/functions/3_divisible_by_3/solution/solution.py index fabb9be6..1237bb3b 100644 --- a/introduction_to_python/functions/3_divisible_by_3/solution/solution.py +++ b/introduction_to_python/functions/3_divisible_by_3/solution/solution.py @@ -1 +1 @@ -# Write your code here +# Write your code here diff --git a/introduction_to_python/functions/3_divisible_by_3/solution/test_solution.py b/introduction_to_python/functions/3_divisible_by_3/solution/test_solution.py index 7c702cee..98881fad 100644 --- a/introduction_to_python/functions/3_divisible_by_3/solution/test_solution.py +++ b/introduction_to_python/functions/3_divisible_by_3/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - from solution import divisible_by_3 - - assert divisible_by_3(2, 3, 5, 6, 9) == [3, 6, 9] - assert divisible_by_3(1, 2, 4) == [] - assert divisible_by_3(9) == [9] - assert divisible_by_3() == [] +def test_solution(): + from solution import divisible_by_3 + + assert divisible_by_3(2, 3, 5, 6, 9) == [3, 6, 9] + assert divisible_by_3(1, 2, 4) == [] + assert divisible_by_3(9) == [9] + assert divisible_by_3() == [] diff --git a/introduction_to_python/functions/3_factorial/README.md b/introduction_to_python/functions/3_factorial/README.md index 0f59e45e..bfd6d2cf 100644 --- a/introduction_to_python/functions/3_factorial/README.md +++ b/introduction_to_python/functions/3_factorial/README.md @@ -1,20 +1,20 @@ -# Factorial - -## Motivation -The factorial, symbolized by an exclamation mark (!), is a quantity defined for all integers greater than or equal to 0. For an integer n greater than or equal to 1, the factorial is the product of all integers less than or equal to n but greater than or equal to 1. The factorial of 0 is defined to be 1. - -## Problem Description -Write a Python function `factorial` that consumes a non-negative integer `n`, and returns the factorial of `n`. - -**DO NOT USE factorial() built in method** - -## Example -``` -factorial(3) == 6 -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Factorial + +## Motivation +The factorial, symbolized by an exclamation mark (!), is a quantity defined for all integers greater than or equal to 0. For an integer n greater than or equal to 1, the factorial is the product of all integers less than or equal to n but greater than or equal to 1. The factorial of 0 is defined to be 1. + +## Problem Description +Write a Python function `factorial` that consumes a non-negative integer `n`, and returns the factorial of `n`. + +**DO NOT USE factorial() built in method** + +## Example +``` +factorial(3) == 6 +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_to_python/functions/3_factorial/solution/test_solution.py b/introduction_to_python/functions/3_factorial/solution/test_solution.py index a8e542b4..dd1c6bed 100644 --- a/introduction_to_python/functions/3_factorial/solution/test_solution.py +++ b/introduction_to_python/functions/3_factorial/solution/test_solution.py @@ -1,9 +1,9 @@ -from solution import factorial - - -def test_solution(): - assert factorial(1) == 1 - assert factorial(0) == 1 - assert factorial(10) == 3628800 - assert factorial(3) == 6 - assert factorial(2) == 2 +from solution import factorial + + +def test_solution(): + assert factorial(1) == 1 + assert factorial(0) == 1 + assert factorial(10) == 3628800 + assert factorial(3) == 6 + assert factorial(2) == 2 diff --git a/introduction_to_python/functions/3_total/README.md b/introduction_to_python/functions/3_total/README.md index 6ab94708..2652f33e 100644 --- a/introduction_to_python/functions/3_total/README.md +++ b/introduction_to_python/functions/3_total/README.md @@ -1,21 +1,21 @@ -# Total - -## Motivation -Collective data types such as lists and dictionaries have a collection of data. - - -## Problem Description -Write a Python function `sum_data` that consumes a list of integers `lst` and returns the sum of all the integers in `lst`. Try doing this exercise without using the built in sum() function. - - ***DO NOT USE THE BUILT-IN SUM()*** - -## Example -``` -sum_data([2, 4, 6, 8]) == 20 -``` - -## Testing -* To test your solution, type 'pytest' within the **solution** subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory +# Total + +## Motivation +Collective data types such as lists and dictionaries have a collection of data. + + +## Problem Description +Write a Python function `sum_data` that consumes a list of integers `lst` and returns the sum of all the integers in `lst`. Try doing this exercise without using the built in sum() function. + + ***DO NOT USE THE BUILT-IN SUM()*** + +## Example +``` +sum_data([2, 4, 6, 8]) == 20 +``` + +## Testing +* To test your solution, type 'pytest' within the **solution** subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solution* subdirectory within this directory diff --git a/introduction_to_python/functions/3_total/solution/test_solution.py b/introduction_to_python/functions/3_total/solution/test_solution.py index e5e3a8dd..7ee402ea 100644 --- a/introduction_to_python/functions/3_total/solution/test_solution.py +++ b/introduction_to_python/functions/3_total/solution/test_solution.py @@ -1,8 +1,8 @@ -from solution import sum_data - - -def test_solution(): - assert sum_data([]) == 0 - assert sum_data([1]) == 1 - assert sum_data([1, 2, 3]) == 6 - assert sum_data([2, 4, 6, 8]) == 20 +from solution import sum_data + + +def test_solution(): + assert sum_data([]) == 0 + assert sum_data([1]) == 1 + assert sum_data([1, 2, 3]) == 6 + assert sum_data([2, 4, 6, 8]) == 20 diff --git a/introduction_to_python/functions/README.md b/introduction_to_python/functions/README.md index d3f6693a..7aa4e1bf 100644 --- a/introduction_to_python/functions/README.md +++ b/introduction_to_python/functions/README.md @@ -1,14 +1,14 @@ -# Exercises for Functions - -| Exercise ID | Exercise | -|:-----------:|:--------:| -| easy_e1 | [Concat Args](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/1_arithmetic) | -| easy_e2 | [Below 100](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/1_concantenation) | -| easy_e3 | [Return Hello](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/1_name_bindings) | -| medium_e1 | [Max Value](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/1_operators) | -| medium_e2 | [Shut Down](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/2_capture_display) | -| medium_e3 | [Variable Arguments](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/2_python_caches) | -| hard_e1 | [Divisible by 3](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/2_string_arithmetic) | -| hard_e2 | [Count Even](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/2_string_duplication) | -| hard_e3 | [Factorial](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/2_type_check) | -| hard_e4 | [Total](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/3_type_change) | +# Exercises for Functions + +| Exercise ID | Exercise | +|:-----------:|:--------:| +| easy_e1 | [Concat Args](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/1_arithmetic) | +| easy_e2 | [Below 100](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/1_concantenation) | +| easy_e3 | [Return Hello](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/1_name_bindings) | +| medium_e1 | [Max Value](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/1_operators) | +| medium_e2 | [Shut Down](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/2_capture_display) | +| medium_e3 | [Variable Arguments](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/2_python_caches) | +| hard_e1 | [Divisible by 3](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/2_string_arithmetic) | +| hard_e2 | [Count Even](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/2_string_duplication) | +| hard_e3 | [Factorial](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/2_type_check) | +| hard_e4 | [Total](https://github.com/ByteAcademyCo/Introduction-And-Environment/tree/master/exercises/hello_world/3_type_change) | diff --git a/introduction_to_python/recursive_functions/1_array_sum/README.md b/introduction_to_python/recursive_functions/1_array_sum/README.md index ed2d6cc6..549a0051 100644 --- a/introduction_to_python/recursive_functions/1_array_sum/README.md +++ b/introduction_to_python/recursive_functions/1_array_sum/README.md @@ -1,15 +1,15 @@ -# Array_sum - -## Problem Description -Define a recursive Python function named `sum_array` that consumes one parameter `num_list` and returns the sum of the the numbers within the list. Do not use iteration or any built-in functions of any form for this question. - -## Example -``` -sum_array([1, 2, 3, 4]) == 10 -``` - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory +# Array_sum + +## Problem Description +Define a recursive Python function named `sum_array` that consumes one parameter `num_list` and returns the sum of the the numbers within the list. Do not use iteration or any built-in functions of any form for this question. + +## Example +``` +sum_array([1, 2, 3, 4]) == 10 +``` + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory diff --git a/introduction_to_python/recursive_functions/1_array_sum/solution/solution.py b/introduction_to_python/recursive_functions/1_array_sum/solution/solution.py index e69de29b..d711198f 100644 --- a/introduction_to_python/recursive_functions/1_array_sum/solution/solution.py +++ b/introduction_to_python/recursive_functions/1_array_sum/solution/solution.py @@ -0,0 +1,2 @@ +def sum_array(num_list): + return 0 if num_list == [] else num_list[0] + sum_array(num_list[1:]) \ No newline at end of file diff --git a/introduction_to_python/recursive_functions/1_array_sum/solution/test_solution.py b/introduction_to_python/recursive_functions/1_array_sum/solution/test_solution.py index 32c81a74..3a65a151 100644 --- a/introduction_to_python/recursive_functions/1_array_sum/solution/test_solution.py +++ b/introduction_to_python/recursive_functions/1_array_sum/solution/test_solution.py @@ -1,6 +1,6 @@ -def test_solution(monkeypatch): - from solution import sum_array - - assert sum_array(num_list=[1, 2, 3]) == 6 - assert sum_array(num_list=[1, -2, 3.5]) == 2.5 - assert sum_array(num_list=[]) == 0 +def test_solution(monkeypatch): + from solution import sum_array + + assert sum_array(num_list=[1, 2, 3]) == 6 + assert sum_array(num_list=[1, -2, 3.5]) == 2.5 + assert sum_array(num_list=[]) == 0 diff --git a/introduction_to_python/recursive_functions/1_count_down/README.md b/introduction_to_python/recursive_functions/1_count_down/README.md index d020e607..b70a70b0 100644 --- a/introduction_to_python/recursive_functions/1_count_down/README.md +++ b/introduction_to_python/recursive_functions/1_count_down/README.md @@ -1,22 +1,22 @@ -# Count Down - -## Problem Description -Define a recursive Python function named `count_down_from` that consumes one argument `num`. The function prints the numbers from `1` to `num` (inclusive) in descending order, one on each line. Do not use iteration of any form for this question. - -## Example -``` -count_down_from(5) -prints -5 -4 -3 -2 -1 -``` - - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory +# Count Down + +## Problem Description +Define a recursive Python function named `count_down_from` that consumes one argument `num`. The function prints the numbers from `1` to `num` (inclusive) in descending order, one on each line. Do not use iteration of any form for this question. + +## Example +``` +count_down_from(5) +prints +5 +4 +3 +2 +1 +``` + + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory diff --git a/introduction_to_python/recursive_functions/1_count_down/solution/solution.py b/introduction_to_python/recursive_functions/1_count_down/solution/solution.py index e69de29b..39695833 100644 --- a/introduction_to_python/recursive_functions/1_count_down/solution/solution.py +++ b/introduction_to_python/recursive_functions/1_count_down/solution/solution.py @@ -0,0 +1,11 @@ +#def count_down_from(num): + #if num >= 1: + #print(num) + #count_down_from(num - 1) + +#list = [1, 1, 2, 3, 5, 8, 13] +#print(list[list[list[4]]]) + +for i in range(10): + if not i % 2 == 0: + print(i+1) \ No newline at end of file diff --git a/introduction_to_python/recursive_functions/1_count_down/solution/test_solution.py b/introduction_to_python/recursive_functions/1_count_down/solution/test_solution.py index 4f44398a..691e16f5 100644 --- a/introduction_to_python/recursive_functions/1_count_down/solution/test_solution.py +++ b/introduction_to_python/recursive_functions/1_count_down/solution/test_solution.py @@ -1,16 +1,16 @@ -def test_solution(monkeypatch): - ret_val = [] - - def g(num): - ret_val.append(num) - - monkeypatch.setattr("builtins.print", g) - - from solution import count_down_from - - count_down_from(3) - - assert ret_val[0] == 3 - assert ret_val[1] == 2 - assert ret_val[2] == 1 - assert len(ret_val) == 3 +def test_solution(monkeypatch): + ret_val = [] + + def g(num): + ret_val.append(num) + + monkeypatch.setattr("builtins.print", g) + + from solution import count_down_from + + count_down_from(3) + + assert ret_val[0] == 3 + assert ret_val[1] == 2 + assert ret_val[2] == 1 + assert len(ret_val) == 3 diff --git a/introduction_to_python/recursive_functions/1_find_power/README.md b/introduction_to_python/recursive_functions/1_find_power/README.md index 7fb44c6e..fe8a0a71 100644 --- a/introduction_to_python/recursive_functions/1_find_power/README.md +++ b/introduction_to_python/recursive_functions/1_find_power/README.md @@ -1,15 +1,15 @@ -# Find Power - -## Problem Description -Define a recursive Python function named `power` that consumes two parameters `a` and `b`. The function returns `a` to the power of `b`. Do not use the `**` operator or iteration in this question. - -## Example -``` -power(2, 3) == 8 -``` - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory +# Find Power + +## Problem Description +Define a recursive Python function named `power` that consumes two parameters `a` and `b`. The function returns `a` to the power of `b`. Do not use the `**` operator or iteration in this question. + +## Example +``` +power(2, 3) == 8 +``` + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory diff --git a/introduction_to_python/recursive_functions/1_find_power/solution/test_solution.py b/introduction_to_python/recursive_functions/1_find_power/solution/test_solution.py index 1a873495..c62dbef0 100644 --- a/introduction_to_python/recursive_functions/1_find_power/solution/test_solution.py +++ b/introduction_to_python/recursive_functions/1_find_power/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - from solution import power - - assert power(1, 3) == 1 - assert power(2, 4) == 16 - assert power(0, 1) == 0 - assert power(5, 2) == 25 +def test_solution(): + from solution import power + + assert power(1, 3) == 1 + assert power(2, 4) == 16 + assert power(0, 1) == 0 + assert power(5, 2) == 25 diff --git a/introduction_to_python/recursive_functions/1_multiply/README.md b/introduction_to_python/recursive_functions/1_multiply/README.md index f692c3cc..706f8315 100644 --- a/introduction_to_python/recursive_functions/1_multiply/README.md +++ b/introduction_to_python/recursive_functions/1_multiply/README.md @@ -1,15 +1,15 @@ -# Reursive Multiply - -## Problem Description -Define a recursive Python function named `multiply` that consumes two parameters `a` and `b`. The function returns `a` multiplied `b`. Do not use the `*` operator or iteration in this question. - -## Example -``` -multiply(2, 3) == 6 -``` - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission +# Reursive Multiply + +## Problem Description +Define a recursive Python function named `multiply` that consumes two parameters `a` and `b`. The function returns `a` multiplied `b`. Do not use the `*` operator or iteration in this question. + +## Example +``` +multiply(2, 3) == 6 +``` + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/recursive_functions/1_multiply/solution/test_solution.py b/introduction_to_python/recursive_functions/1_multiply/solution/test_solution.py index 26dd7528..1e0dabd7 100644 --- a/introduction_to_python/recursive_functions/1_multiply/solution/test_solution.py +++ b/introduction_to_python/recursive_functions/1_multiply/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - from solution import multiply - - assert multiply(2, 3) == 6 - assert multiply(6, 5) == 30 - assert multiply(0, 1) == 0 - assert multiply(5, 0) == 0 +def test_solution(): + from solution import multiply + + assert multiply(2, 3) == 6 + assert multiply(6, 5) == 30 + assert multiply(0, 1) == 0 + assert multiply(5, 0) == 0 diff --git a/introduction_to_python/recursive_functions/2_count_ways/README.md b/introduction_to_python/recursive_functions/2_count_ways/README.md index 7c1c40c9..4b29174c 100644 --- a/introduction_to_python/recursive_functions/2_count_ways/README.md +++ b/introduction_to_python/recursive_functions/2_count_ways/README.md @@ -1,16 +1,16 @@ -# Count ways - -## Problem Description -Assume you are climbing a stair case and it takes `n` steps to reach to the top. Each time you can either climb 1 or 2 steps. -Write a recursive Python function named `count_ways` that consumes a number `steps`. The function returns the number of distinct ways to climb to the top. Hint: Make sure you attempt the question before trying this one! - -* For Example -``` -countways(4) == 5 # (1, 1, 1, 1), (1, 1, 2), (2, 1, 1), (1, 2, 1), (2, 2) -``` -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory - +# Count ways + +## Problem Description +Assume you are climbing a stair case and it takes `n` steps to reach to the top. Each time you can either climb 1 or 2 steps. +Write a recursive Python function named `count_ways` that consumes a number `steps`. The function returns the number of distinct ways to climb to the top. Hint: Make sure you attempt the question before trying this one! + +* For Example +``` +countways(4) == 5 # (1, 1, 1, 1), (1, 1, 2), (2, 1, 1), (1, 2, 1), (2, 2) +``` +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory + diff --git a/introduction_to_python/recursive_functions/2_count_ways/solution/test_solution.py b/introduction_to_python/recursive_functions/2_count_ways/solution/test_solution.py index 1e973ee5..79edf6b4 100644 --- a/introduction_to_python/recursive_functions/2_count_ways/solution/test_solution.py +++ b/introduction_to_python/recursive_functions/2_count_ways/solution/test_solution.py @@ -1,8 +1,8 @@ -def test_solution(): - from solution import count_ways - - assert count_ways(steps=2) == 2 - assert count_ways(steps=10) == 89 - assert count_ways(steps=20) == 10946 - assert count_ways(steps=0) == 1 - assert count_ways(steps=1) == 1 +def test_solution(): + from solution import count_ways + + assert count_ways(steps=2) == 2 + assert count_ways(steps=10) == 89 + assert count_ways(steps=20) == 10946 + assert count_ways(steps=0) == 1 + assert count_ways(steps=1) == 1 diff --git a/introduction_to_python/recursive_functions/2_fibonacci/README.md b/introduction_to_python/recursive_functions/2_fibonacci/README.md index 8f7ee81f..64e79e50 100644 --- a/introduction_to_python/recursive_functions/2_fibonacci/README.md +++ b/introduction_to_python/recursive_functions/2_fibonacci/README.md @@ -1,15 +1,15 @@ -# Fibonacci - -## Problem Description -Define a recursive Python function named `fibonacci` that consumes one argument `n`. The function returns the `n`th fibonacci number or `-1` if `n <= 0`. To understand what a fibonacci number is, please reference [wikipedia](https://en.wikipedia.org/wiki/Fibonacci_number). Do not use iteration for this question. - -## Example -``` -fibonacci(4) == 3 -``` - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory +# Fibonacci + +## Problem Description +Define a recursive Python function named `fibonacci` that consumes one argument `n`. The function returns the `n`th fibonacci number or `-1` if `n <= 0`. To understand what a fibonacci number is, please reference [wikipedia](https://en.wikipedia.org/wiki/Fibonacci_number). Do not use iteration for this question. + +## Example +``` +fibonacci(4) == 3 +``` + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory diff --git a/introduction_to_python/recursive_functions/2_fibonacci/solution/.test_private/test_private.py b/introduction_to_python/recursive_functions/2_fibonacci/solution/.test_private/test_private.py index a3c6d8e6..f550e352 100644 --- a/introduction_to_python/recursive_functions/2_fibonacci/solution/.test_private/test_private.py +++ b/introduction_to_python/recursive_functions/2_fibonacci/solution/.test_private/test_private.py @@ -1,24 +1,24 @@ -from recursive_functions.fibonacci.solution.solution import fibonacci -import pytest -import pytest_dependency -import solution -import time - - -def test_invalid_input(): - assert fibonacci(n=0) == -1 - assert fibonacci(n=-10) == -1 - - -@pytest.mark.dependency() -def test_efficiency(): - start = time.time() - fibonacci(37) - efficiency = time.time() - start - assert efficiency < 0.001 - - -@pytest.mark.xfail(raises=RecursionError, reason="not allowed to use iteration") -@pytest.mark.dependency(depends=["test_efficiency"]) -def test_iterative_solution(): - assert fibonacci(10000) +from recursive_functions.fibonacci.solution.solution import fibonacci +import pytest +import pytest_dependency +import solution +import time + + +def test_invalid_input(): + assert fibonacci(n=0) == -1 + assert fibonacci(n=-10) == -1 + + +@pytest.mark.dependency() +def test_efficiency(): + start = time.time() + fibonacci(37) + efficiency = time.time() - start + assert efficiency < 0.001 + + +@pytest.mark.xfail(raises=RecursionError, reason="not allowed to use iteration") +@pytest.mark.dependency(depends=["test_efficiency"]) +def test_iterative_solution(): + assert fibonacci(10000) diff --git a/introduction_to_python/recursive_functions/2_fibonacci/solution/solution.py b/introduction_to_python/recursive_functions/2_fibonacci/solution/solution.py index 8b137891..d3f5a12f 100644 --- a/introduction_to_python/recursive_functions/2_fibonacci/solution/solution.py +++ b/introduction_to_python/recursive_functions/2_fibonacci/solution/solution.py @@ -1 +1 @@ - + diff --git a/introduction_to_python/recursive_functions/2_fibonacci/solution/test_solution.py b/introduction_to_python/recursive_functions/2_fibonacci/solution/test_solution.py index 67f78ec3..52662cad 100644 --- a/introduction_to_python/recursive_functions/2_fibonacci/solution/test_solution.py +++ b/introduction_to_python/recursive_functions/2_fibonacci/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - from solution import fibonacci - - assert fibonacci(n=5) == 5 - assert fibonacci(n=10) == 55 - assert fibonacci(n=15) == 610 - assert fibonacci(n=1) == 1 +def test_solution(): + from solution import fibonacci + + assert fibonacci(n=5) == 5 + assert fibonacci(n=10) == 55 + assert fibonacci(n=15) == 610 + assert fibonacci(n=1) == 1 diff --git a/introduction_to_python/recursive_functions/2_reverse_string/README.md b/introduction_to_python/recursive_functions/2_reverse_string/README.md index b57b1aa1..9c67c219 100644 --- a/introduction_to_python/recursive_functions/2_reverse_string/README.md +++ b/introduction_to_python/recursive_functions/2_reverse_string/README.md @@ -1,15 +1,15 @@ -# Reverse String - -## Problem Description -Define a recursive Python function named `reverse` that consumes one argument `string`. The function returns the a string whos contents is the reverse of `string` Do not use iteration of any form for this question. - -## Example -``` -reverse("hello") == "olleh" -``` - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory +# Reverse String + +## Problem Description +Define a recursive Python function named `reverse` that consumes one argument `string`. The function returns the a string whos contents is the reverse of `string` Do not use iteration of any form for this question. + +## Example +``` +reverse("hello") == "olleh" +``` + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory diff --git a/introduction_to_python/recursive_functions/2_reverse_string/solution/test_solution.py b/introduction_to_python/recursive_functions/2_reverse_string/solution/test_solution.py index 33f27e71..724cedac 100644 --- a/introduction_to_python/recursive_functions/2_reverse_string/solution/test_solution.py +++ b/introduction_to_python/recursive_functions/2_reverse_string/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - from solution import reverse - - assert reverse("hello") == "olleh" - assert reverse("") == "" - assert reverse("h") == "h" - assert reverse("yes") == "sey" +def test_solution(): + from solution import reverse + + assert reverse("hello") == "olleh" + assert reverse("") == "" + assert reverse("h") == "h" + assert reverse("yes") == "sey" diff --git a/introduction_to_python/recursive_functions/3_binomial_coefficients/README.md b/introduction_to_python/recursive_functions/3_binomial_coefficients/README.md index 35f5c26d..b75552a5 100644 --- a/introduction_to_python/recursive_functions/3_binomial_coefficients/README.md +++ b/introduction_to_python/recursive_functions/3_binomial_coefficients/README.md @@ -1,19 +1,19 @@ -# Binomial Coefficients - -## Motivation -A binomial coefficient `B(n, k)` represents the number of ways to choose `k` elements from a set of `n` elements. This is a commonly used mathematical concept in probability and statistics. The formula for computing `B(n,k)` can be written as `B(n, k) = n choose k = n!/(k (n-k)!)`. However, using this formula, we may get an integer overflow because the factorials can grow large very quickly. Another way to define `B(n, k)` is `n choose k = (n-1 choose k-1) + (n-1 choose k)`. - -## Problem Description -Define a recursive Python function named `binomial_coeff`, that consumes two non-negative integers, `n` and `k`, where `n >= k`, which returns the binomial coefficient `B(n,k)`. - -## Examples -``` -B(5,1) == 5 -B(6,2) == 15 -B(2,0) == 1 -``` -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory +# Binomial Coefficients + +## Motivation +A binomial coefficient `B(n, k)` represents the number of ways to choose `k` elements from a set of `n` elements. This is a commonly used mathematical concept in probability and statistics. The formula for computing `B(n,k)` can be written as `B(n, k) = n choose k = n!/(k (n-k)!)`. However, using this formula, we may get an integer overflow because the factorials can grow large very quickly. Another way to define `B(n, k)` is `n choose k = (n-1 choose k-1) + (n-1 choose k)`. + +## Problem Description +Define a recursive Python function named `binomial_coeff`, that consumes two non-negative integers, `n` and `k`, where `n >= k`, which returns the binomial coefficient `B(n,k)`. + +## Examples +``` +B(5,1) == 5 +B(6,2) == 15 +B(2,0) == 1 +``` +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory diff --git a/introduction_to_python/recursive_functions/3_binomial_coefficients/solution/test_solution.py b/introduction_to_python/recursive_functions/3_binomial_coefficients/solution/test_solution.py index d9dd9fac..ec1a5ae5 100644 --- a/introduction_to_python/recursive_functions/3_binomial_coefficients/solution/test_solution.py +++ b/introduction_to_python/recursive_functions/3_binomial_coefficients/solution/test_solution.py @@ -1,9 +1,9 @@ -def test_solution(): - from solution import binomial_coefficient - - assert binomial_coefficient(6, 2) == 15 - assert binomial_coefficient(5, 0) == 1 - assert binomial_coefficient(4, 3) == 4 - assert binomial_coefficient(0, 0) == 1 - assert binomial_coefficient(18, 1) == 18 - assert binomial_coefficient(20, 5) == 15504 +def test_solution(): + from solution import binomial_coefficient + + assert binomial_coefficient(6, 2) == 15 + assert binomial_coefficient(5, 0) == 1 + assert binomial_coefficient(4, 3) == 4 + assert binomial_coefficient(0, 0) == 1 + assert binomial_coefficient(18, 1) == 18 + assert binomial_coefficient(20, 5) == 15504 diff --git a/introduction_to_python/recursive_functions/3_factorial/README.md b/introduction_to_python/recursive_functions/3_factorial/README.md index 8064c0fc..57546216 100644 --- a/introduction_to_python/recursive_functions/3_factorial/README.md +++ b/introduction_to_python/recursive_functions/3_factorial/README.md @@ -1,15 +1,15 @@ -# Find Factorial - -## Problem Description -Define a recursive Python function named `factorial_recursive` that consumes a number `n` and returns the factorial `n!` of `n`. - -## Example -``` -factorial_recursive(4) == 24 -``` - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission -* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory +# Find Factorial + +## Problem Description +Define a recursive Python function named `factorial_recursive` that consumes a number `n` and returns the factorial `n!` of `n`. + +## Example +``` +factorial_recursive(4) == 24 +``` + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission +* Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory diff --git a/introduction_to_python/recursive_functions/3_factorial/solution/test_solution.py b/introduction_to_python/recursive_functions/3_factorial/solution/test_solution.py index 74db9833..84b0b7ae 100644 --- a/introduction_to_python/recursive_functions/3_factorial/solution/test_solution.py +++ b/introduction_to_python/recursive_functions/3_factorial/solution/test_solution.py @@ -1,7 +1,7 @@ -def test_solution(): - from solution import factorial_recursive - - assert factorial_recursive(5) == 120 - assert factorial_recursive(10) == 3628800 - assert factorial_recursive(1) == 1 - assert factorial_recursive(0) == 1 +def test_solution(): + from solution import factorial_recursive + + assert factorial_recursive(5) == 120 + assert factorial_recursive(10) == 3628800 + assert factorial_recursive(1) == 1 + assert factorial_recursive(0) == 1 diff --git a/introduction_to_python/recursive_functions/3_hofstader_sequence/README.md b/introduction_to_python/recursive_functions/3_hofstader_sequence/README.md index 29410738..48ec1774 100644 --- a/introduction_to_python/recursive_functions/3_hofstader_sequence/README.md +++ b/introduction_to_python/recursive_functions/3_hofstader_sequence/README.md @@ -1,23 +1,23 @@ -# Hofstader Sequence - -## Problem Description -Define a two mutually recursive Python function named `hofstaderA` and `hofstaderB` that both consume a non-negative integer `n`. `hofstaderF` will return `A(n)` and `hofstaderB` will return `B(n)` where `A(n)` and `B(n)` are defined as follows: -``` -A(0) = 1 -A(n) = n - B(A(n-1)), n > 0 -B(0) = 0 -B(n) = n - A(B(n-1)), n > 0 -``` - - -## Example -``` -hofstaderA(4) == 3 -hofstaderB(6) == 4 -``` - -## Testing -* To test your solution, type 'pytest' within the solution subdirectory - -## Submission +# Hofstader Sequence + +## Problem Description +Define a two mutually recursive Python function named `hofstaderA` and `hofstaderB` that both consume a non-negative integer `n`. `hofstaderF` will return `A(n)` and `hofstaderB` will return `B(n)` where `A(n)` and `B(n)` are defined as follows: +``` +A(0) = 1 +A(n) = n - B(A(n-1)), n > 0 +B(0) = 0 +B(n) = n - A(B(n-1)), n > 0 +``` + + +## Example +``` +hofstaderA(4) == 3 +hofstaderB(6) == 4 +``` + +## Testing +* To test your solution, type 'pytest' within the solution subdirectory + +## Submission * Submit your answers in the *solution.py* file within the *solutions* subdirectory within this directory \ No newline at end of file diff --git a/introduction_to_python/recursive_functions/3_hofstader_sequence/solution/test_solution.py b/introduction_to_python/recursive_functions/3_hofstader_sequence/solution/test_solution.py index 48d0fc35..b377249a 100644 --- a/introduction_to_python/recursive_functions/3_hofstader_sequence/solution/test_solution.py +++ b/introduction_to_python/recursive_functions/3_hofstader_sequence/solution/test_solution.py @@ -1,9 +1,9 @@ -def test_solution(): - from solution import hofstaderA, hofstaderB - - assert hofstaderA(4) == 3 - assert hofstaderB(4) == 2 - assert hofstaderA(0) == 1 - assert hofstaderB(0) == 0 - assert hofstaderA(6) == 4 +def test_solution(): + from solution import hofstaderA, hofstaderB + + assert hofstaderA(4) == 3 + assert hofstaderB(4) == 2 + assert hofstaderA(0) == 1 + assert hofstaderB(0) == 0 + assert hofstaderA(6) == 4 assert hofstaderB(6) == 4 \ No newline at end of file diff --git a/introduction_to_python/recursive_functions/README.md b/introduction_to_python/recursive_functions/README.md index 9f32e864..84fa5f86 100644 --- a/introduction_to_python/recursive_functions/README.md +++ b/introduction_to_python/recursive_functions/README.md @@ -1,15 +1,15 @@ -# Exercises for Recursive Functions - - -| Exercise ID | Exercise | -|:-----------:|:--------:| -| easy_e1 | [Array Sum](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/array_sum) | -| easy_e2 | [Find Power](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/find_power) | -| easy_e3 | [Count Down](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/count_down) | -| easy_e4 | [Multiply](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/multiply) | -| medium_e1 | [Count Ways](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/count_ways) | -| medium_e2 | [Fibonacci](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/fibonacci) | -| medium_e3 | [Factorial](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/find_factorial) | -| medium_e4 | [Reverse String](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/reverse_string) | -| hard_e1 | [Holfstader Sequence](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/hofstader_sequence) | -| hard_e2 | [Binomial Coefficient](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/binomial_coefficient) | +# Exercises for Recursive Functions + + +| Exercise ID | Exercise | +|:-----------:|:--------:| +| easy_e1 | [Array Sum](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/array_sum) | +| easy_e2 | [Find Power](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/find_power) | +| easy_e3 | [Count Down](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/count_down) | +| easy_e4 | [Multiply](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/multiply) | +| medium_e1 | [Count Ways](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/count_ways) | +| medium_e2 | [Fibonacci](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/fibonacci) | +| medium_e3 | [Factorial](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/find_factorial) | +| medium_e4 | [Reverse String](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/reverse_string) | +| hard_e1 | [Holfstader Sequence](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/hofstader_sequence) | +| hard_e2 | [Binomial Coefficient](https://github.com/ByteAcademyCo/Introduction-To-Python/tree/master/exercises/recursive_functions/binomial_coefficient) | diff --git a/software_theory/README.md b/software_theory/README.md index 4828c053..b2c8ffe7 100644 --- a/software_theory/README.md +++ b/software_theory/README.md @@ -1,9 +1,9 @@ -# Exercise Organization - -| Section ID | Section Name | -|:-----------:|:--------:| -| 1 | [Databases](https://github.com/ByteAcademyCo/Exercises/tree/master/algorithms/graph_traversal) | -| 2 | [SQL](https://github.com/ByteAcademyCo/Exercises/tree/master/algorithms/sorting) | -| 3 | [Networks](https://github.com/ByteAcademyCo/Exercises/tree/master/algorithms/bit_manipultion) | -| 4 | [Testing](https://github.com/ByteAcademyCo/Exercises/tree/master/algorithms/string_manipulation) | -| 5 | [Python Libraries](https://github.com/ByteAcademyCo/Exercises/tree/master/algorithms/dynamic_programming) | +# Exercise Organization + +| Section ID | Section Name | +|:-----------:|:--------:| +| 1 | [Databases](https://github.com/ByteAcademyCo/Exercises/tree/master/algorithms/graph_traversal) | +| 2 | [SQL](https://github.com/ByteAcademyCo/Exercises/tree/master/algorithms/sorting) | +| 3 | [Networks](https://github.com/ByteAcademyCo/Exercises/tree/master/algorithms/bit_manipultion) | +| 4 | [Testing](https://github.com/ByteAcademyCo/Exercises/tree/master/algorithms/string_manipulation) | +| 5 | [Python Libraries](https://github.com/ByteAcademyCo/Exercises/tree/master/algorithms/dynamic_programming) | diff --git a/software_theory/databases/README.md b/software_theory/databases/README.md index e8ff656e..8fa5894e 100644 --- a/software_theory/databases/README.md +++ b/software_theory/databases/README.md @@ -1,8 +1,8 @@ -# Exercises for databases - -* 1_databases1 -* 1_databases2 -* 1_databases3 -* 2_databases1 -* 2_databases2 -* 3_databases1 +# Exercises for databases + +* 1_databases1 +* 1_databases2 +* 1_databases3 +* 2_databases1 +* 2_databases2 +* 3_databases1 diff --git a/software_theory/networks/README.md b/software_theory/networks/README.md index ac8664a6..9f44b35a 100644 --- a/software_theory/networks/README.md +++ b/software_theory/networks/README.md @@ -1,8 +1,8 @@ -# Exercises for networks - -* 1_networks1 -* 1_networks2 -* 1_networks3 -* 2_networks1 -* 2_networks2 -* 3_networks1 +# Exercises for networks + +* 1_networks1 +* 1_networks2 +* 1_networks3 +* 2_networks1 +* 2_networks2 +* 3_networks1 diff --git a/software_theory/python_libraries/README.md b/software_theory/python_libraries/README.md index e12e406d..2d0b3d9b 100644 --- a/software_theory/python_libraries/README.md +++ b/software_theory/python_libraries/README.md @@ -1,8 +1,8 @@ -# Exercises for Python libraries - -* 1_python_libraries1 -* 1_python_libraries2 -* 1_python_libraries3 -* 2_python_libraries1 -* 2_python_libraries2 -* 3_python_libraries1 +# Exercises for Python libraries + +* 1_python_libraries1 +* 1_python_libraries2 +* 1_python_libraries3 +* 2_python_libraries1 +* 2_python_libraries2 +* 3_python_libraries1 diff --git a/software_theory/sql/README.md b/software_theory/sql/README.md index 5729daa1..d75a760f 100644 --- a/software_theory/sql/README.md +++ b/software_theory/sql/README.md @@ -1,8 +1,8 @@ -# Exercises for sql - -* 1_sql1 -* 1_sql2 -* 1_sql3 -* 2_sql1 -* 2_sql2 -* 3_sql1 +# Exercises for sql + +* 1_sql1 +* 1_sql2 +* 1_sql3 +* 2_sql1 +* 2_sql2 +* 3_sql1 diff --git a/software_theory/testing/README.md b/software_theory/testing/README.md index 190fbd88..f6afdf3e 100644 --- a/software_theory/testing/README.md +++ b/software_theory/testing/README.md @@ -1,8 +1,8 @@ -# Exercises for testing - -* 1_testing1 -* 1_testing2 -* 1_testing3 -* 2_testing1 -* 2_testing2 -* 3_testing1 +# Exercises for testing + +* 1_testing1 +* 1_testing2 +* 1_testing3 +* 2_testing1 +* 2_testing2 +* 3_testing1 diff --git a/test.py b/test.py new file mode 100644 index 00000000..4f1cc7c6 --- /dev/null +++ b/test.py @@ -0,0 +1,2 @@ +print('hello world') +print('i dont know but w/e')