diff --git a/CondaPlugins/README.md b/CondaPlugins/README.md index 9e27c13..9cc88d0 100644 --- a/CondaPlugins/README.md +++ b/CondaPlugins/README.md @@ -19,8 +19,7 @@ In the Python portion of the plugin (_i.e._, `CondaPlugins/c_plugins/temp_conver ### References -**Calling C Functions from Python** -https://www.digitalocean.com/community/tutorials/calling-c-functions-from-python +[**Calling C Functions from Python**](https://www.digitalocean.com/community/tutorials/calling-c-functions-from-python) ## Python Plugins @@ -49,11 +48,8 @@ $ maturin develop ### References -**Maturin** -https://github.com/PyO3/maturin +[**Maturin**](https://github.com/PyO3/maturin) -**PyO3 User Guide** -https://pyo3.rs/v0.14.2/index.html +[**PyO3 User Guide**](https://pyo3.rs/v0.14.2/index.html) -**Calling Rust from Python Using PyO3** -https://saidvandeklundert.net/learn/2021-11-18-calling-rust-from-python-using-pyo3/ +[**Calling Rust from Python Using PyO3**](https://saidvandeklundert.net/learn/2021-11-18-calling-rust-from-python-using-pyo3/) diff --git a/Puzzles/PracticeMay2023/01_merge_strings_alternately.py b/Puzzles/PracticeMay2023/01_merge_strings_alternately.py new file mode 100644 index 0000000..d942c3e --- /dev/null +++ b/Puzzles/PracticeMay2023/01_merge_strings_alternately.py @@ -0,0 +1,48 @@ +# You are given two strings word1 and word2. Merge the strings by adding +# letters in alternating order, starting with word1. If a string is +# longer than the other, append the additional letters onto the end of +# the merged string. + +# Return the merged string. + +from itertools import zip_longest + +class Solution: + def mergeAlternately(self, word1: str, word2: str) -> str: + """ + :type word1: str + :type word2: str + :rtype: str + """ + word1_list = list(word1.strip(" ")) + word2_list = list(word2.strip(" ")) + merged_list = [] + while len(word1_list) or len(word2_list) > 0: + if len(word1_list) == 0: + # merged_list.append(word2_list[:]) + for x in range(len(word2_list)): + merged_list.append(word2_list.pop(0)) + break + elif len(word2_list) == 0: + # merged_list.append(word1_list[:]) + for x in range(len(word1_list)): + merged_list.append(word1_list.pop(0)) + break + merged_list.append(word1_list.pop(0)) + merged_list.append(word2_list.pop(0)) + word = "".join(map(str, merged_list)) + return word + + +class BetterSolution: + # A way more efficient solution than the above 🤯 + def mergeAlternately(self, word1, word2): + return ''.join(a + b for a, b in zip_longest(word1, word2, fillvalue='')) + +print(BetterSolution.mergeAlternately(BetterSolution, "abc", "pqr")) + +# Runtime: 32 ms, faster than 63.64% of Python3 online submissions for Merge Strings Alternately. +# Memory Usage: 14.3 MB, less than 42.42% of Python3 online submissions for Merge Strings Alternately. + +# Read about zip_longest here: +# https://docs.python.org/3/library/itertools.html#itertools.zip_longest diff --git a/Puzzles/PracticeMay2023/02_greatest_common_str_divisor.py b/Puzzles/PracticeMay2023/02_greatest_common_str_divisor.py new file mode 100644 index 0000000..eb182f6 --- /dev/null +++ b/Puzzles/PracticeMay2023/02_greatest_common_str_divisor.py @@ -0,0 +1,33 @@ +# For two strings s and t, we say "t divides s" if and only if s = t + ... + t +# (i.e., t is concatenated with itself one or more times). + +# Given two strings str1 and str2, return the largest string x such that x divides +# both str1 and str2. + +import math + +class Solution: + def gcdOfStrings(self, str1: str, str2: str) -> str: + if len(str1)<=len(str2): + temp = str1 + else: + temp = str2 + m = len(temp) + x = 1 + res=[""] + while x <= m: + if m % x == 0 and temp[:x] * (len(str1)//x) == str1 and temp[:x] * (len(str2)//x) == str2: + res.append(temp[:x]) + x+=1 + return res[-1] + + +class BetterSolution: + # A better version of the above + def gcdOfStrings(self, str1: str, str2: str) -> str: + if str1 + str2 != str2 + str1: return '' + # Take the greatest common divisor of the lengths of the two strings + # and return that slice of string 🤯 + return str1[:math.gcd(len(str1), len(str2))] + +# Read more about math.gcd() here: https://docs.python.org/3/library/math.html#math.gcd diff --git a/Puzzles/PracticeMay2023/03_most_candies.py b/Puzzles/PracticeMay2023/03_most_candies.py new file mode 100644 index 0000000..9231859 --- /dev/null +++ b/Puzzles/PracticeMay2023/03_most_candies.py @@ -0,0 +1,33 @@ +# There are n kids with candies. You are given an integer array of candies, +# where each candies[i] represents the number of candies the ith kid has, +# and an integer extraCandies, denoting the number of extra candies that +# you have. + +# Return a boolean array result of length n, where result[i] is true if, +# after giving the ith kid all the extraCandies, they will have the greatest +# number of candies among all the kids, or false otherwise. + +# Note that multiple kids can have the greatest number of candies. + +import numpy as np +from types import List + +class Solution: + def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: + sorted_list = sorted(candies) + highest_number = sorted_list[-1] + determination = [] + for i in range(len(candies)): + if (candies[i] + extraCandies) >= highest_number: + determination.append(True) + continue + if (candies[i] + extraCandies) < highest_number: + determination.append(False) + continue + return determination + + +class BetterSolution: + # A better solution than the above 🤯 + def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: + return np.array(candies) + extraCandies >= np.array(candies).max() diff --git a/Puzzles/PracticeMay2023/04_can_place_flowers.py b/Puzzles/PracticeMay2023/04_can_place_flowers.py new file mode 100644 index 0000000..64e4158 --- /dev/null +++ b/Puzzles/PracticeMay2023/04_can_place_flowers.py @@ -0,0 +1,63 @@ +# You have a long flowerbed in which some of the plots are planted, +# and some are not. However, flowers cannot be planted in adjacent plots. + +# Given an integer array flowerbed containing 0's and 1's, where 0 means +# empty and 1 means not empty, and an integer n, return true if n new flowers +# can be planted in the flowerbed without violating the no-adjacent-flowers +# rule and false otherwise. + +import numpy as np +from types import List + +class Solution: + def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: + if n <= 0: + return True + elif len(flowerbed) == 1: + if flowerbed == [0]: + return True + else: + return False + # Create an array that is 1 where a is 0, and pad each end with an extra 0. + iszero = np.concatenate(([0], np.equal(flowerbed, 0).view(np.int8), [0])) + absdiff = np.abs(np.diff(iszero)) + # Runs start and end where absdiff is 1. + ranges = np.where(absdiff == 1)[0].reshape(-1, 2) + for [x, y] in ranges: + difference = y - x + if difference == 2: + # if the plot size is 2 but at either edge, then a flower + # can be planted there + if x == 0 or y == len(flowerbed): + n = n - 1 + else: + pass + elif difference <= 2: + # if the potential plot is 2 or smaller but not at the edge, + # the automatic answer is "can't plant a flower here" + pass + elif (difference % 2) == 0: + # this takes care of even-numbered cases larger than 4 + if x == 0 or y == len(flowerbed): + d = difference // 2 + n = n - d + else: + d = difference // 2 + d = d - 1 + n -= d + elif (difference % 2) != 0: + # this takes care of odd-numbered cases larger than 3 + if x == 0 or y == len(flowerbed): + d = difference // 2 + d = d + 1 + n -= d + else: + d = difference // 2 + n -= d + else: + d = difference // 2 + n -= d + if n <= 0: + return True + else: + return False diff --git a/Puzzles/PracticeMay2023/05_reverse_vowels.py b/Puzzles/PracticeMay2023/05_reverse_vowels.py new file mode 100644 index 0000000..a9e7298 --- /dev/null +++ b/Puzzles/PracticeMay2023/05_reverse_vowels.py @@ -0,0 +1,26 @@ +class Solution: + def reverseVowels(self, s: str) -> str: + """ + Given a string s, reverse only all the vowels in the string and return it. + """ + # list all possible vowels (in lower case) + vowels = ['a', 'e', 'i', 'o', 'u'] + # make input string lower case so it can be validated against the list + to_replace = [] + index = [] + # iterate over every letter in s to see if it's a vowel; + # if it is, store it in reverse order in a placeholder list + for i in range(len(s)): + if s[i].lower() in vowels: + to_replace.append(s[i]) + index.append(i) + else: + pass + # reverse the list of vowels + to_replace.reverse() + # iterate over the list of vowels and replace the vowels in s + # with the reversed vowels + for i in range(len(to_replace)): + s = s[:index[i]] + to_replace[i] + s[index[i]+1:] + return s + \ No newline at end of file diff --git a/Puzzles/PracticeMay2023/06_reverse_words.py b/Puzzles/PracticeMay2023/06_reverse_words.py new file mode 100644 index 0000000..294239a --- /dev/null +++ b/Puzzles/PracticeMay2023/06_reverse_words.py @@ -0,0 +1,17 @@ +class Solution: + def reverseWords(self, s: str) -> str: + word_list = s.split(" ") + reversed = [] + reversed_string = "" + for word in word_list: + if word: + reversed.append(word) + reversed.reverse() + for i in reversed: + reversed_string = reversed_string + " " + i + return reversed_string.strip() + +# This is a better solution than the above 🤯 +class BetterSolution: + def reverseWords(self, s: str) -> str: + return " ".join(s.split()[::-1]) \ No newline at end of file diff --git a/Puzzles/PracticeMay2023/07_product_of_array.py b/Puzzles/PracticeMay2023/07_product_of_array.py new file mode 100644 index 0000000..6a68ada --- /dev/null +++ b/Puzzles/PracticeMay2023/07_product_of_array.py @@ -0,0 +1,10 @@ +from functools import reduce + +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + target_list = [] + list_size = len(nums) + if list_size: + for index in range(list_size): + target_list.append(reduce((lambda x, y: x * y), nums[:index] + nums[index + 1:])) + return target_list diff --git a/Puzzles/PracticeMay2023/08_move_zeroes.py b/Puzzles/PracticeMay2023/08_move_zeroes.py new file mode 100644 index 0000000..39ac67f --- /dev/null +++ b/Puzzles/PracticeMay2023/08_move_zeroes.py @@ -0,0 +1,9 @@ +class Solution: + def moveZeroes(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + for x in nums: + if x == 0: + nums.remove(x) + nums.append(x) diff --git a/Puzzles/PracticeMay2023/09_is_subsequence.py b/Puzzles/PracticeMay2023/09_is_subsequence.py new file mode 100644 index 0000000..51dea62 --- /dev/null +++ b/Puzzles/PracticeMay2023/09_is_subsequence.py @@ -0,0 +1,48 @@ +class Solution: + def isSubsequence(self, s: str, t: str) -> bool: + m = len(s) + n = len(t) + if m == 0: + return True + elif n == 0: + return False + elif m == n: + if s == t: + return True + else: + return False + + index = 0 + for l in s: + new_index = t.find(l) + if new_index > 0 and new_index == index: + return False + elif new_index >= index: + index = new_index + continue + elif index > new_index: + new_index = t[slice(index, len(t), 1)].find(l) + if new_index < 0: + return False + else: + continue + else: + return False + if index: + return True + else: + return False + + +class BetterSolution: + def isSubsequence(self, s: str, t: str) -> bool: + if not s: + return True + + s_index = 0 + for l in t: + if l == s[s_index]: + s_index += 1 + if s_index == len(s): + return True + return False diff --git a/Puzzles/PracticeMay2023/10_max_avg_subarray.py b/Puzzles/PracticeMay2023/10_max_avg_subarray.py new file mode 100644 index 0000000..507381f --- /dev/null +++ b/Puzzles/PracticeMay2023/10_max_avg_subarray.py @@ -0,0 +1,45 @@ +class Solution: + def findMaxAverage(self, nums: List[int], k: int) -> float: + if k > len(nums): + return 0 + if k == 0: + return 0 + if not nums: + return 0 + get_max = [] + index1 = 0 + index2 = k + while index2 <= len(nums): + get_max.append(sum(nums[index1:index2])) + index1 += 1 + index2 += 1 + if get_max: + biggest = max(get_max) + print(biggest) + result = (biggest / k) + print(result) + return result + else: + return 0 + +class BetterSolution: + def findMaxAverage(self, nums: List[int], k: int) -> float: + if k > len(nums): + return 0 + if k == 0: + return 0 + if not nums: + return 0 + index1 = 0 + index2 = k + biggest = sum(nums[index1:index2]) + while index2 <= len(nums): + if sum(nums[index1:index2]) > biggest: + biggest = sum(nums[index1:index2]) + index1 += 1 + index2 += 1 + if biggest: + result = (biggest / k) + return result + else: + return 0 diff --git a/Puzzles/PracticeMay2023/11_find_max_altitude.py b/Puzzles/PracticeMay2023/11_find_max_altitude.py new file mode 100644 index 0000000..1c8f9d9 --- /dev/null +++ b/Puzzles/PracticeMay2023/11_find_max_altitude.py @@ -0,0 +1,6 @@ +class Solution: + def largestAltitude(self, gain: List[int]) -> int: + starting = [0] + for a in gain: + starting.append(starting[-1] + a) + return max(starting) diff --git a/Puzzles/PracticeMay2023/README.md b/Puzzles/PracticeMay2023/README.md new file mode 100644 index 0000000..0460b19 --- /dev/null +++ b/Puzzles/PracticeMay2023/README.md @@ -0,0 +1,337 @@ +# Practice Exercises! + +## 1. Merge Strings Alternately + +### Status: ✅ + +You are given two strings, `word1` and `word2`. Merge the strings by adding letters +in alternating order, starting with `word1`. If a string is longer than the other, +append the additional letters onto the end of the merged string. + +_Return the merged string._ + +### Example 1: +``` +Input: word1 = "abc", word2 = "pqr" +Output: "apbqcr" +``` +Explanation: The merged string will be merged as so: +``` +word1: a b c +word2: p q r +merged: a p b q c r +``` + +### Example 2: +``` +Input: word1 = "ab", word2 = "pqrs" +Output: "apbqrs" +``` +Explanation: Notice that as `word2` is longer, "rs" is appended to the end. +``` +word1: a b +word2: p q r s +merged: a p b q r s +``` + +### Example 3: + +``` +Input: word1 = "abcd", word2 = "pq" +Output: "apbqcd" +``` +Explanation: Notice that as `word1` is longer, "cd" is appended to the end. +``` +word1: a b c d +word2: p q +merged: a p b q c d +``` + +### Constraints: + +* `1 <= word1.length`, `word2.length <= 100` +* `word1` and `word2` consist of lowercase English letters. + +### Acceptance Rate: +`82.8%` + + +* * * + + +## 2. Greatest Common Divisor of Strings + +### Status: ✅ + +For two strings `s` and `t`, we say "`t` divides `s`" if and only if `s = t + ... + t` (_i.e._, `t` is concatenated with itself one or more times). + +Given two strings `str1` and `str2`, _return the largest string `x` such that `x` divides both `str1` and `str2`_. + +### Example 1: +``` +Input: str1 = "ABCABC", str2 = "ABC" +Output: "ABC" +``` + +### Example 2: +``` +Input: str1 = "ABABAB"`, `str2 = "ABAB" +Output: "AB" +``` + +### Example 3: +``` +Input: str1 = "LEET", str2 = "CODE" +Output: "" +``` + +### Constraints: + +* `1 <= str1.length`, `str2.length <= 1000` +* `str1` and `str2` consist of English uppercase letters. + +### Acceptance Rate +`56.5%` + + +* * * + + +## 3. Kids With the Greatest Number of Candies + +### Status: ✅ + +There are `n` kids with candies. You are given an integer array of candies, where each `candies[i]` represents the number of candies the `i`th kid has, and an integer `extraCandies`, denoting the number of extra candies that you have. + +_Return a boolean array result of length `n`, where `result[i]` is true if, after giving the ith kid all the `extraCandies`, they will have the greatest number of candies among all the kids, or false otherwise._ + +> Note that multiple kids can have the greatest number of candies. + +### Example 1: +``` +Input: candies = [2,3,5,1,3], extraCandies = 3 +Output: [true,true,true,false,true] +``` +Explanation: If you give all `extraCandies` to: +- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids. +- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids. +- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids. +- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids. +- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids. + +### Example 2: +``` +Input: candies = [4,2,1,1,2], extraCandies = 1 +Output: [true,false,false,false,false] +``` +Explanation: There is only 1 extra candy. + +Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy. + +### Example 3: +``` +Input: candies = [12,1,12], extraCandies = 10 +Output: [true,false,true] +``` + +### Constraints: +* `n == candies.length` +* `2 <= n <= 100` +* `1 <= candies[i] <= 100` +* `1 <= extraCandies <= 50` + +### Acceptance Rate +`88.0%` + + +* * * + + +## 4. Can Place Flowers + +### Status: ✅ + +You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. + +Given an integer array `flowerbed` containing `0`'s and `1`'s, where `0` means empty and `1` means not empty, and an integer `n`, return true if `n` new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise. + +### Example 1: +``` +Input: flowerbed = [1,0,0,0,1], n = 1 +Output: true +``` + +### Example 2: +``` +Input: flowerbed = [1,0,0,0,1], n = 2 +Output: false +``` + +### Constraints: + +* `1 <= flowerbed.length <= 2 * 104` +* `flowerbed[i]` is `0` or `1`. +* There are no two adjacent flowers in `flowerbed`. +* `0 <= n <= flowerbed.length` + +### Acceptance Rate +`32.7%` + +* * * + + +## 5. Reverse Vowels of a String + +### Status: ✅ + +Given a string `s`, reverse only all the vowels in the string and return it. + +The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once. + +### Example 1: +``` +Input: s = "hello" +Output: "holle" +``` + +### Example 2: +``` +Input: s = "leetcode" +Output: "leotcede" +``` + +### Constraints: + +* `1 <= s.length <= 3 * 105` +* `s` consist of printable ASCII characters + +### Acceptance Rate +`50.3%` + + +* * * + + +## 6. Reverse Words in a String + +### Status: ✅ + +Given an input string `s`, reverse the order of the words. + +A word is defined as a sequence of non-space characters. The words in `s` will be separated by at least one space. + +Return a string of the words in reverse order concatenated by a single space. + +Note that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. + +### Example 1: +``` +Input: s = "the sky is blue" +Output: "blue is sky the" +``` + +### Example 2: +``` +Input: s = " hello world " +Output: "world hello" +``` +**Explanation:** Your reversed string should not contain leading or trailing spaces. + +### Example 3: +``` +Input: s = "a good example" +Output: "example good a" +``` +**Explanation:** You need to reduce multiple spaces between two words to a single space in the reversed string. + +### Constraints: + +* `1 <= s.length <= 104` +* `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`. +* There is at least one word in `s`. + +**Follow-up:** If the string data type is mutable in your language, can you solve it in-place with `O(1)` extra space? + +### Acceptance Rate +`33.3%` + + +* * * + + +## 7. Product of Array Except Self + +### Status: ❌ + +Given an input string `s`, reverse the order of the words. + +A word is defined as a sequence of non-space characters. The words in `s` will be separated by at least one space. + +Return a string of the words in reverse order concatenated by a single space. + +Note that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. + +### Example 1: +``` +Input: s = "the sky is blue" +Output: "blue is sky the" +``` + +### Example 2: +``` +Input: s = " hello world " +Output: "world hello" +``` +**Explanation:** Your reversed string should not contain leading or trailing spaces. + +### Example 3: +``` +Input: s = "a good example" +Output: "example good a" +``` +**Explanation:** You need to reduce multiple spaces between two words to a single space in the reversed string. + +### Constraints: + +* `1 <= s.length <= 104` +* `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`. +* There is at least one word in `s`. + +**Follow-up:** If the string data type is mutable in your language, can you solve it in-place with `O(1)` extra space? + +### Acceptance Rate +`33.3%` + + +* * * + + +## 8. Move Zeroes + +### Status: ✅ + +Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. + +Note that you must do this in-place without making a copy of the array. + +### Example 1: +``` +Input: nums = [0,1,0,3,12] +Output: [1,3,12,0,0] +``` + +### Example 2: +``` +Input: nums = [0] +Output: [0] +``` + +### Constraints: + +* `1 <= nums.length <= 104` +* `-231 <= nums[i] <= 231 - 1` + +**Follow-up:** Could you minimize the total number of operations done? + +### Acceptance Rate +`61.4%`