Ejemplo n.º 1
0
        determines if target[i:i+len(stamp)] matches stamp
        note that all stars don't match stamp
        """
        j = 0
        is_letter = False
        while j < len(self.stamp) and self.target[i +
                                                  j] in self.stamp_pattern[j]:
            if self.target[i + j] != "*":
                is_letter = True
            j += 1
        return j == len(self.stamp) and is_letter

    def find_matching_stamp(self) -> int:
        """
        returns the index where stamp matches target or -1 if there is no match
        """
        i = 0
        while i <= len(self.target) - len(
                self.stamp) and not self.match_stamp(i):
            i += 1
        return i if i <= len(self.target) - len(self.stamp) else -1


if __name__ == "__main__":
    from run_tests import run_tests

    correct_answers = [["abc", "ababc", [0, 2]],
                       ["abca", "aabcaca", [3, 0, 1]]]
    print(f"Running tests for movesToStamp")
    run_tests(Solution().movesToStamp, correct_answers)
Ejemplo n.º 2
0
            # note that all values in root.right are greater than root.val,
            # so they are greater than high
            # exclude all of them, so we need to process root.left only
            return self.trimBST(root.left, low, high)

        else:
            # we keep root node. Let us processs root.left and root.right
            root.left = self.trimBST(root.left, low, high)
            root.right = self.trimBST(root.right, low, high)
            return root


if __name__ == '__main__':
    from run_tests import run_tests

    correct_answers = [[[1, 0, 2], 1, 2, [1, None, 2]],
                       [[3, 0, 4, None, 2, None, None, 1], 1, 3,
                        [3, 2, None, 1]], [[1], 1, 2, [1]],
                       [[1, None, 2], 1, 3, [1, None, 2]],
                       [[1, None, 2], 2, 4, [2]]]
    for i in range(len(correct_answers)):
        correct_answers[i][0] = TreeNode.to_treenode(correct_answers[i][0])
        correct_answers[i][-1] = TreeNode.to_treenode(correct_answers[i][-1])

    methods = [
        'trimBST',
    ]
    for method in methods:
        print(f'Running tests for {method}')
        run_tests(getattr(Solution(), method), correct_answers)
Ejemplo n.º 3
0
            right_sum = (self.n - 1 - i) * x - ((self.n - 1 - i) *
                                                (self.n - i) // 2)
        # print(x, left_sum, right_sum)
        return left_sum + x + right_sum

    def maxValue(self, n: int, index: int, maxSum: int) -> int:
        self.n = n
        self.index = index
        maxSum -= n
        self.maxSum = maxSum
        min_ = 0
        max_ = maxSum
        while min_ + 1 < max_:
            guess = (min_ + max_) // 2
            if self.total(guess) <= maxSum:
                min_ = guess
            else:
                max_ = guess

        if self.total(max_) <= maxSum:
            return max_ + 1
        else:
            return min_ + 1


if __name__ == '__main__':
    from run_tests import run_tests

    correct_answers = [[4, 2, 6, 2], [6, 1, 10, 3]]
    run_tests(Solution().maxValue, correct_answers)
Ejemplo n.º 4
0
        Runtime complexity: O(n)
        Space complexity: O(1)
        """
        if s1 == s2:
            return True

        swap = []
        swapped = False
        for char1, char2 in zip(s1, s2):
            if char1 != char2 and not swap:
                swap = [char1, char2]

            elif char1 != char2 and not swapped and swap[0] == char2 and swap[
                    1] == char1:
                swapped = True

            elif char1 != char2:
                return False

        return swapped


if __name__ == '__main__':
    from run_tests import run_tests

    correct_answers = [["bank", "kanb", True], ["kelb", "kelb", True],
                       ["abcd", "bcda", False], ["abcd", "abce", False],
                       ["bbcd", "aacd", False]]
    print(f'Running tests for areAlmostEqual')
    run_tests(Solution().areAlmostEqual, correct_answers)
Ejemplo n.º 5
0
    if (lab == "lab1"):
        from lab1 import lab1_topology
        net = lab1_topology()
    if (lab == "lab1_ext"):
        from lab1 import lab1_extended_topology
        net = lab1_extended_topology()
    if (lab == "lab2_parta"):
        from network import lab2_topology
        net = lab2_topology(full=False)
    if (lab == "lab2_partb"):
        from network import lab2_topology
        net = lab2_topology(full=True)
    if (lab == "lab3_part1"):
        from lab3_topology import dumbbell_topology
        net = dumbbell_topology()

    run_commands(net, tree, "startup")

    # Check if we need to run CLI
    if (options.cli):
        CLI(net)
    else:
        (max, accrued) = run_tests(net, tree, options.failstop)

    info("\n****************** Stopping the network\n")
    net.stop()
    run_commands(None, tree, "cleanup")

    if 'max' in locals():
        info("\n****************** YOUR SCORE: (%d/%d)\n" % (accrued, max))
Ejemplo n.º 6
0
 def run(self):
     run_tests()
Ejemplo n.º 7
0

class Solution:
    def maxAscendingSum(self, nums: List[int]) -> int:
        max_sum = max(nums)
        prev = float('inf')
        cur_sum = 0
        for n in nums:
            if n > 0:
                if prev < n:
                    cur_sum += n
                else:
                    if cur_sum > 0:
                        max_sum = max(max_sum, cur_sum)
                    cur_sum = n
            prev = n
        if cur_sum > 0:
            max_sum = max(max_sum, cur_sum)
        return max_sum


if __name__ == '__main__':
    from run_tests import run_tests

    correct_answers = [[[10, 20, 30, 5, 10, 50], 65],
                       [[10, 20, 30, 40, 50], 150],
                       [[12, 17, 15, 13, 10, 11, 12], 33], [[100, 10, 1], 100],
                       [[-1, 0, 1], 1], [[-3, -2, -1], -1]]
    print(f'Running tests for maxAscendingSum')
    run_tests(Solution().maxAscendingSum, correct_answers)
Ejemplo n.º 8
0
            ans += self.countEvenPali(center)
        return ans

    def countOddPali(self, center: int) -> int:
        max_l = 1
        while center - max_l >= 0 and center + max_l < len(self.string) and self.string[center - max_l] == self.string[
            center + max_l]:
            max_l += 1
        return max_l

    def countEvenPali(self, center: int) -> int:
        max_l = 0
        while center - max_l >= 0 and center + 1 + max_l < len(self.string) and self.string[center - max_l] == \
                self.string[center + 1 + max_l]:
            max_l += 1
        return max_l


if __name__ == "__main__":
    import run_tests

    correct_answers = [
        ["abc", 3],
        ["aaa", 6],
        ["abab", 6],
        ["abba", 6],
        ["abbb", 7]
    ]
    print(f"Running tests for countSubstrings")
    run_tests.run_tests(Solution().countSubstrings, correct_answers)
Ejemplo n.º 9
0
                ans.next = ListNode(0)
            ans = ans.next
            l1 = l1.next

        while l2 is not None:
            sum_ = l2.val + over
            if sum_ < 10:
                ans.next = ListNode(sum_)
                over = 0
            else:
                ans.next = ListNode(0)
                over = 1
            ans = ans.next
            l2 = l2.next

        if over:
            ans.next = ListNode(1)

        return head.next


if __name__ == "__main__":
    corr_answers = [
        ([2, 4, 3], [5, 6, 4], [7, 0, 8]),
        ([0], [0], [0]),
        ([9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9], [8, 9, 9, 9, 0, 0, 0, 1]),
    ]
    corr_answers = [[ListNode.to_linkedlist(l) for l in args]
                    for args in corr_answers]
    run_tests(Solution().addTwoNumbers, corr_answers)
Ejemplo n.º 10
0
# constants
N_CHANNELS = 1

RESULTS_ROOT_DIR = "../resources/results"
VERSION_LIST = [
    "feature_engine_benchmark", "python_vanilla", "matlab_vanilla",
    "python_nobb"
]
N_NODES_COMPUTED = [1]

DATASET_ID = "Example"
SOUND_IDS = ["Example0", "Example1"]

SEGMENT_SIZE = 1500
WINDOW_SIZE = 256
WINDOW_OVERLAP = 128
NFFT = 256

RUN_ID = DATASET_ID + "_" + "_".join(
    [str(p) for p in [SEGMENT_SIZE, WINDOW_SIZE, WINDOW_OVERLAP, NFFT]])

if __name__ == "__main__":
    for n_nodes in N_NODES_COMPUTED:
        results_dict_dfs = read_results.read(RESULTS_ROOT_DIR, n_nodes, RUN_ID,
                                             VERSION_LIST)

        print("Beginning tests on {} nodes results:".format(n_nodes))

        run_tests(results_dict_dfs)
Ejemplo n.º 11
0
            dp_incr.append((n, max_incr_seq))

            # add the seq that ends on n to dp_mtn
            max_mtn = 0
            # (a) extend existing mtn
            for last_number, l in dp_mtn:
                if last_number > n:
                    max_mtn = max(max_mtn, l + 1)
            # (b) converting increasing seq to mtn
            for last_number, l in dp_incr:
                if last_number > n:
                    max_mtn = max(max_mtn, l + 1)
            if max_mtn >= 3:
                dp_mtn.append((n, max_mtn))

        if not dp_mtn:
            return None
        else:
            return len(nums) - max(dp_mtn, key=lambda x: x[1])[1]


if __name__ == '__main__':
    from run_tests import run_tests

    correct_answers = [[[1, 3, 1], 0], [[2, 1, 1, 5, 6, 2, 3, 1], 3],
                       [[4, 3, 2, 1, 1, 2, 3, 1], 4],
                       [[1, 2, 3, 4, 4, 3, 2, 1], 1]]

    print(f'Runnging tests for minimumMountainRemovals')
    run_tests(Solution().minimumMountainRemovals, correct_answers)
Ejemplo n.º 12
0
(*) words[i] consists of only lowercase letters.
"""
from typing import List


class Solution:
    def minimumLengthEncoding(self, words: List[str]) -> int:
        """
        Time complexity: O(n)
        Space complexity: O(n)
        """
        words.sort(key=lambda x: len(x), reverse=True)
        total_length = 0
        encoded_words = set()
        for i, word in enumerate(words):
            if all(not encoded.endswith(word) for encoded in encoded_words):
                encoded_words.add(word)
                total_length += len(word) + 1

        return total_length


if __name__ == '__main__':
    from run_tests import run_tests

    correct_answers = [[["time", "me", "bell"], 10],
                       [["time", "me", "bell", "cell"], 15],
                       [["me", "time", "bell"], 10]]
    print(f'Running tests for minimumLengthEncoding')
    run_tests(Solution().minimumLengthEncoding, correct_answers)
Ejemplo n.º 13
0
        Space complexity: O(1)
        """
        x = sum(nums) - x # sum of values inside the array
        if not x:
            return len(nums)

        nums = list(itertools.accumulate(nums))
        min_steps = float('inf')  # dynamically compute min steps required
        lo = 0
        for i, n in enumerate(nums):
            if n == x:
                # subarray nums[:i] works
                min_steps = min(min_steps, len(nums) - 1 - i)
            else:
                candidate = bisect.bisect_left(nums, n - x, lo=lo, hi=i)
                # check is subarray nums[candidate+1:i] works
                if candidate + 1 < len(nums) and n - nums[candidate] == x:
                    min_steps = min(min_steps, candidate + len(nums) - i)
        return min_steps if min_steps < float('inf') else -1


if __name__ == "__main__":
    corr_answers = [
        [[1,1,4,2,3], 5, 2],
        [[5,6,7,8,9], 4, -1],
        [[3,2,20,1,1,3], 10, 5]
    ]
    print(f'Tests for minOperations started...')
    run_tests(Solution().minOperations, corr_answers)
    print(f'Tests for minOperationsNoSpace started...')
    run_tests(Solution().minOperationsNoSpace, corr_answers)
Ejemplo n.º 14
0
        while head is not None:
            length += 1
            head = head.next
        return length

    def getNode(self, head: ListNode, k: int) -> ListNode:
        """
        Time complexity: O(n)
        Space complexity: O(1)
        """
        for _ in range(k):
            head = head.next
        return head


if __name__ == '__main__':
    import run_tests

    correct_answers = [
        [[1,2,3,4,5], 2, [1,4,3,2,5]],
        [[7,9,6,6,7,8,3,0,9,5], 5, [7,9,6,6,8,7,3,0,9,5]],
        [[1], 1, [1]],
        [[1,2], 2, [2, 1]],
        [[1,2,3], 2, [1,2,3]]
    ]
    for i in range(len(correct_answers)):
        correct_answers[i][0] = ListNode.to_linkedlist(correct_answers[i][0])
        correct_answers[i][-1] = ListNode.to_linkedlist(correct_answers[i][-1])
    print(f'Running tests for swapNodes')
    run_tests.run_tests(Solution().swapNodes, correct_answers)
Ejemplo n.º 15
0
    """
    if len(sys.argv) == 2:
        restrict_to_path = os.path.join(BASE_DIR, sys.argv[1])
        if not os.path.exists(restrict_to_path):
            print("-- file does not exist:", restrict_to_path)
            sys.exit(-1)
    """
    #restrict_to_program = ["Python 2.7.10", "Python 3.5.2"]

    asdf_config = "Mir Ion Parser"

    run_tests.programs[ion_config] = {
        "url": "https://github.com/libmir/ion",
        "commands":
        [os.path.join(run_tests.PARSERS_DIR, "../../test_json-ion")]
    }

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('restrict_to_path', nargs='?', type=str, default=None)

    args = parser.parse_args()
    run_tests.run_tests(args.restrict_to_path, [ion_config])

    run_tests.generate_report(os.path.join(run_tests.BASE_DIR,
                                           "results/parsing.html"),
                              keep_only_first_result_in_set=False)
    run_tests.generate_report(os.path.join(run_tests.BASE_DIR,
                                           "results/parsing_pruned.html"),
                              keep_only_first_result_in_set=True)
Ejemplo n.º 16
0
                rec.append((x + 1, y))
                attainable.add((x + 1, y))
            # left
            if y > 0 and abs(self.heights[x][y - 1] - h) <= effort and (
                    x, y - 1) not in attainable:
                rec.append((x, y - 1))
                attainable.add((x, y - 1))
            # right
            if y + 1 < len(self.heights[0]) and abs(self.heights[x][y + 1] -
                                                    h) <= effort and (
                                                        x, y +
                                                        1) not in attainable:
                rec.append((x, y + 1))
                attainable.add((x, y + 1))
            if (len(self.heights) - 1, len(self.heights[0]) - 1) in attainable:
                return True
        return False


if __name__ == '__main__':
    from run_tests import run_tests

    correct_answers = [[[[1, 2, 2], [3, 8, 2], [5, 3, 5]], 2],
                       [[[1, 2, 3], [3, 8, 4], [5, 3, 5]], 1],
                       [[[1, 2, 1, 1, 1], [1, 2, 1, 2, 1], [1, 2, 1, 2, 1],
                         [1, 2, 1, 2, 1], [1, 1, 1, 2, 1]], 0],
                       [[[1, 2, 1, 1, 1], [1, 2, 1, 2, 1], [1, 2, 1, 2, 1],
                         [1, 2, 1, 2, 1], [1, 1, 1, 2, 2]], 1]]
    print('Running tests for minimumEffortPath')
    run_tests(Solution().minimumEffortPath, correct_answers)
Ejemplo n.º 17
0
        """
        if root is None:
            return None

        if root.right is not None:
            self.convertBST(root.right, greater_sum)
            greater_sum = root.right.val
            node = root.right
            while node is not None:
                greater_sum = node.val
                node = node.left

        root.val += greater_sum
        self.convertBST(root.left, root.val)
        return root


if __name__ == '__main__':
    from run_tests import run_tests

    correct_answers = [[[
        4, 1, 6, 0, 2, 5, 7, None, None, None, 3, None, None, None, 8
    ], [30, 36, 21, 36, 35, 26, 15, None, None, None, 33, None, None, None,
        8]], [[0, None, 1], [1, None, 1]], [[1, 0, 2], [3, 3, 2]],
                       [[3, 2, 4, 1], [7, 9, 4, 10]]]
    for i in range(len(correct_answers)):
        correct_answers[i][0] = TreeNode.to_treenode(correct_answers[i][0])
        correct_answers[i][1] = TreeNode.to_treenode(correct_answers[i][1])
    print(f'Running tests for convertBST')
    run_tests(Solution().convertBST, correct_answers)
Ejemplo n.º 18
0
Example 5:
Input: s = "0000000001011100", k = 4
Output: false


Constraints:
1 <= s.length <= 5 * 10^5
s consists of 0's and 1's only.
1 <= k <= 20
"""


class Solution:
    def hasAllCodes(self, s: str, k: int) -> bool:
        substrings = set()
        subs = s[:k]
        for i in range(k, len(s)):
            substrings.add(subs)
            subs = subs[1:] + s[i]
        substrings.add(subs)
        return len(substrings) == 1 << k


if __name__ == '__main__':
    from run_tests import run_tests

    correct_answers = [['01100', 2, True], ['1110', 1, True],
                       ['0110', 2, False], ['010101001', 2, False]]
    print(f'Running tests for hasAllCodes')
    run_tests(Solution().hasAllCodes, correct_answers)
Ejemplo n.º 19
0
import os.path

if __name__ == '__main__':

    restrict_to_path = None
    """
    if len(sys.argv) == 2:
        restrict_to_path = os.path.join(BASE_DIR, sys.argv[1])
        if not os.path.exists(restrict_to_path):
            print("-- file does not exist:", restrict_to_path)
            sys.exit(-1)
    """
    #restrict_to_program = ["Python 2.7.10", "Python 3.5.2"]

    asdf_config = "D ASDF Parser";

    run_tests.programs[asdf_config] = {
       "url":"https://github.com/libmir/asdf",
       "commands":[os.path.join(run_tests.PARSERS_DIR, "../../test_json-asdf")]
   }

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('restrict_to_path', nargs='?', type=str, default=None)

    args = parser.parse_args()
    run_tests.run_tests(args.restrict_to_path, [asdf_config])

    run_tests.generate_report(os.path.join(run_tests.BASE_DIR, "results/parsing.html"), keep_only_first_result_in_set = False)
    run_tests.generate_report(os.path.join(run_tests.BASE_DIR, "results/parsing_pruned.html"), keep_only_first_result_in_set = True)
Ejemplo n.º 20
0
Constraints:
(*) 2 <= nums.length <= 10^4
(*) 1 <= nums[i] <= 10^4
"""
from typing import List


class Solution:
    def findErrorNums(self, nums: List[int]) -> List[int]:
        repeated = None
        for i in range(len(nums)):
            n = abs(nums[i]) - 1
            if nums[n] < 0:
                repeated = n + 1
            else:
                nums[n] = -nums[n]

        for i in range(len(nums)):
            if nums[i] > 0:
                return [repeated, i + 1]


if __name__ == '__main__':
    from run_tests import run_tests

    correct_answers = [[[1, 2, 2, 4], [2, 3]], [[1, 1, 2, 4], [1, 3]],
                       [[1, 2, 3, 4, 5, 3], [3, 6]]]
    print(f'Running tests for findErrorNums')
    run_tests(Solution().findErrorNums, correct_answers)