Exemplo n.º 1
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests


def array_maximal_adjacent_difference(arr):
    """ A function that returns the max difference between any of the elements in the array

  Arguments:
      arr { number[] } -- An array of numbers 

  Returns:
      number -- The max difference between any of its adjacent element
  """
    length = len(arr) - 1
    diffs = [abs(arr[i] - arr[i + 1]) for i in range(length)]
    return max(diffs)


run_tests(array_maximal_adjacent_difference)
Exemplo n.º 2
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests

def count_jewels( jewels_and_stones ):
  """ A function that counts the number of jewels, given a list of jewel types and the available stones

  Arguments:
      jewels_and_stones { string[] } -- An array of strings. First string represents the list of jewels, and the second string represents stones available

  Returns:
      number --  the number of available jewels
  """
  [J, S] = jewels_and_stones
  return sum( s in J for s in S )

run_tests( count_jewels )
Exemplo n.º 3
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests


def max_product(nums):
    """ A function that given the array of integers nums, 
  returns the maximum value that can be obtain for multiplying two different elements in the array

  Args:
      nums ( number[] )

  Returns:
      number
  """
    n1 = max(nums)
    nums.pop(nums.index(n1))
    n2 = max(nums)
    return (n1 - 1) * (n2 - 1)


run_tests(max_product)
Exemplo n.º 4
0
import sys

sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests

import re


def determine_if_number(str):
    """ A function that scans a string to determine if it represents a valid number, which could be integer, 
  negative, floating, scientific notation, etc

  Arguments:
      str { string } -- The string to scan

  Returns:
      boolean -- A boolean determining if the string represents a valid number
  """
    return re.search("^-?\d*\.?\d+[e?\d+]?\d*$", str) is not None


run_tests(determine_if_number)
Exemplo n.º 5
0
  Args:
      strings ( string[] ): An array with two strings to calculate its editing distance

  Returns:
      number: The editing distance of the two given arrays
  """

    s1 = strings[0]
    s2 = strings[1]
    s1_length = len(s1) + 1
    s2_length = len(s2) + 1
    matrix = [[0] * s2_length for x in range(s1_length)]

    for i in range(s1_length):
        for j in range(s2_length):
            if i == 0:
                matrix[i][j] = j
            elif j == 0:
                matrix[i][j] = i
            elif s1[i - 1] == s2[j - 1]:
                matrix[i][j] = matrix[i - 1][j - 1]
            else:
                matrix[i][j] = 1 + min(matrix[i][j - 1], matrix[i - 1][j],
                                       matrix[i - 1][j - 1])

    return matrix[s1_length - 1][s2_length - 1]


run_tests(editing_distance)
Exemplo n.º 6
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests

FIRST_ASCII = 96


def decryptString(s):
    msg = ""
    i = 0

    while i < len(s):
        if i + 2 < len(s) and s[i + 2] == '#':
            encrypted = s[i:i + 2]
            i += 3
        else:
            encrypted = s[i]
            i += 1

        asciiValue = int(encrypted) + FIRST_ASCII
        msg += chr(asciiValue)

    return msg


run_tests(decryptString)
Exemplo n.º 7
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests


def kid_with_max_candies(arr):
    """ A function that for each kid check if there is a way to distribute extraCandies among 
  the kids such that he or she can have the greatest number of candies among them
  
  Args:
      arr ( number[] ): An array representing the candies each kid has, and the last element being the amount of extra candies

  Returns:
      bool[]: An array determining if each could have the max number of candies, given some extra candies
  """
    extra_candies = arr.pop()
    max_candies = max(arr)
    return [candy + extra_candies >= max_candies for candy in arr]


run_tests(kid_with_max_candies)
Exemplo n.º 8
0
  Returns:
      number -- The square root of the given number, rounded to three decimals
  """
    x = number
    y = 1
    precision = 0.0001

    while (get_relative_error(x, y) > precision):
        x = (x + y) / 2
        y = number / x

    return round(x, 3)


def get_relative_error(x, y):
    """
  A function that calculates the relative margin of error between two numbers 

  Arguments:
      x { number } -- The first number to get the margin of error
      y { number } -- The second number to get the margin of error

  Returns:
      number -- The margin or error between the two numbers
  """
    return (x - y) / x


run_tests(square_root)
Exemplo n.º 9
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests


def binary_reverse(string):
    """ A function that receives a stringified positive integer and returns its binary reversal integer representation

  Arguments:
      string { str } -- The string representing a positive integer 

  Returns:
      [integer] -- The integer which correspond to the binary reversal of the input
  """
    n = bin(int(string))[2:]
    missing_zeroes = 8 - (len(n) % 8) if len(n) % 8 != 0 else 0
    k = (('0' * missing_zeroes) + n)[::-1]
    return int(k, 2)


run_tests(binary_reverse)
Exemplo n.º 10
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests

brackets = ['()', '[]', '{}']


def balanced_brackets(input_string):
    """
  A function that checks if the brackets of a given string are balanced, using string replacement for each match

  Arguments:
      input_string { string } -- The string to validate

  Returns:
      boolean -- True or false if the string has balanced brackets
  """
    sanitized_input = ''.join(input_string.split())
    while any(match in sanitized_input for match in brackets):
        for bracket in brackets:
            sanitized_input = sanitized_input.replace(bracket, '')
    return not sanitized_input


run_tests(balanced_brackets)
Exemplo n.º 11
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests


def maximum_69_number(num):
    """ A function that returns the maximum number you can get by changing at most one digit of a given number consisting of 6 and 9

  Args:
      num ( number ): A number consisting only of 6 and 9

  Returns:
      number:  The highest number that can be made given the input, just by changing one digit
  """
    adjusted = str(num).replace('6', '9', 1)
    return int(adjusted)


run_tests(maximum_69_number)
Exemplo n.º 12
0
from run_test import run_tests

def is_number_palindrome( num ):
  """ A function that checks if an integer is also a palindrome, without parsing it to string

  Args:
      num ( number ): An integer

  Returns:
      boolean: True or false if the given integer is a palindrome
  """
  digits = number_to_array( num )
  return digits == digits[::-1]

def number_to_array( num ):
  """ Helper function that parses an integer number into an array of numbers

  Args:
      num ( number ): An integer

  Returns:
      number[]: The given integer, parsed into a list of digits
  """
  digits = []
  while num != 0:
    num, digit = divmod( num, 10 )
    digits.append( digit )
  return digits

run_tests( is_number_palindrome )
Exemplo n.º 13
0

def letter_changes(str):
    """ A function that shifts all the letters of a string to its next letter in the alphabet, and then uppercase all the vowels

  Arguments:
      str { string } -- The string to convert

  Returns:
      [ string ] -- The converted string
  """
    return ''.join(map(shift_and_parse, str))


def shift_and_parse(char):
    """ A helper function to shift and capitalize a letter 

  Arguments:
      char { chr } -- The letter to be shifted and capitalized

  Returns:
      [ chr ] -- The shifted and capitalized letter
  """
    if char in ascii_lowercase:
        char = ascii_lowercase[0] if char == ascii_lowercase[-1] else chr(
            ord(char) + 1)
    return char.upper() if char in vowels else char


run_tests(letter_changes)
Exemplo n.º 14
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests


def first_factorial(n):
    """ A recursive function that calculates the factorial of a given number

  Arguments:
      n { number } -- The given number to calculate its factorial

  Returns:
      [ number ] -- The product of the current number times the previous number. Defaulted to 1 when n equals zero
  """
    return 1 if n == 0 else n * first_factorial(n - 1)


run_tests(first_factorial)
Exemplo n.º 15
0
def find_intersection(str_array):
    """ A function that scans two stringified arrays and returns a new string with all the matches between the two arrays

  Arguments:
      str_array { string[] } -- An array of strings with two elements. Each element is a stringified array of numbers

  Returns:
      [ string ] -- A string with all the matching elements that the two arrays share
  """
    array_1 = parse_string_array(str_array[0])
    array_2 = parse_string_array(str_array[1])
    matches = set(array_1) & set(array_2)
    sorted_matches = repr(sorted(matches))
    return sorted_matches.replace(' ', '').replace('[', '').replace(
        ']', '') if matches else False


def parse_string_array(string_array):
    """ A function that receives a stringified array of numbers, and parses it into a proper number array

  Arguments:
      string_array { string } -- A stringified array of numbers

  Returns:
      [ nubmer[]  -- An array of numbers
  """
    return map(int, string_array.split(', '))


run_tests(find_intersection)
Exemplo n.º 16
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests


def array_plus_one(arr):
    """  A function that receives an array of integers. Each element in the array represent a digit in a larger number.
  The function returns an array representing the number after adding one

  Arguments:
      arr { int[] } --  An array of numbers that represent a larger integer

  Returns:
      int[] -- An array of numbers that represent the given large number after adding one
  """
    number = int(''.join(map(str, arr))) + 1
    return [int(i) for i in str(number)]


run_tests(array_plus_one)
Exemplo n.º 17
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests


def reverse_string(str):
    """ A function that receives a string and reverses it

  Arguments:
      str { string } -- The string to reverse

  Returns:
      [string ] -- The reversed string
  """
    return str[::-1]


run_tests(reverse_string)
Exemplo n.º 18
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests

import math


def product_minus_sum(n):
    """ A function that scans each digit of a number then sums then and also multiplies them, and finally returns the substraction of both

  Args:
      n ( number ): The number to process

  Returns:
      number: The substraction of the product minus the sum
  """
    p = 1
    s = 0
    while n > 0:
        c = n % 10
        p = p * c
        s = s + c
        n = math.floor(n / 10)
    return p - s


run_tests(product_minus_sum)
Exemplo n.º 19
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests


def array_xor(params):
    """ A function which given an integer n and an integer start, 
     defines an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length, 
     and then returns the bitwise XOR of all elements of nums.
  Args:
      params ( number[]): An array of two elements, First element is the length of the array and the second is the start

  Returns:
      number: The resulting value after the operation
  """
    n = params[0]
    start = params[1]
    res = 0
    for i in range(n):
        res ^= start + 2 * i
    return res


run_tests(array_xor)
Exemplo n.º 20
0
  """ A function that calculates the product of all the elements in the array except itself and returns it an a new array

  Args:
      arr ( number[] ): A list of integers

  Returns:
      number[]: A list of integers
  """
  N = len(arr)
  res   = [1] * N
  left  = [1] * N
  right = [1] * N

  product_left = 1
  product_right = 1

  for i in range( 0, N ):
    j = N - 1 - i
    left[i] = product_left 
    right[j] = product_right
    product_left *= arr[i]
    product_right *= arr[j]

  for i in range( 0, N ):
    res[i] = left[i] * right[i]

  return res
  

run_tests( product_of_array )
Exemplo n.º 21
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests

def my_function():
  # Fill this..
  return

run_tests( my_function )
Exemplo n.º 22
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests


def defang_address(address):
    """ A function that receives an ip address and returns its defanged version

  Args:
      address ( string ): An ip address

  Returns:
      string: The defanged ip address
  """
    return address.replace('.', '[.]')


run_tests(defang_address)
Exemplo n.º 23
0
  removes the outermost parentheses of every primitive string in the primitive decomposition of S.

  Args:
      S (string ): a valid parentheses string 

  Returns:
      string: the string S the outermost parentheses of every primitive string
  """

    result_string = ""
    current_primitive_string = ""
    current_primitive_stack = []

    for char in S:

        last_char = current_primitive_stack[
            -1] if current_primitive_stack else char
        current_primitive_stack.append(
            char) if last_char == char else current_primitive_stack.pop()

        if current_primitive_stack:
            current_primitive_string += char
        else:
            result_string += current_primitive_string[1:]
            current_primitive_string = ""

    return result_string


run_tests(removeOuterParenthesis)
Exemplo n.º 24
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests

def minTimeToVisitAllPoints( points ):
  """ A function that finds the minimum time in seconds to visit all points in a given array of coordinates

  Args:
      points ( number[] ): An array of points in a plain

  Returns:
      number: The amount of seconds needed to go from the first point to the last
  """

  seconds = 0
  for i in range(1, len(points), 1):
    diffX = abs( points[i][0] - points[i-1][0])
    diffY = abs( points[i][1] - points[i-1][1])
    seconds += max( diffX, diffY)
  return seconds

run_tests( minTimeToVisitAllPoints )
Exemplo n.º 25
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests


def decompress_encoded_list(nums):
    """ A function that decompressed a run-length encoded lists and returns it

  Args:
      nums ( number[] ): A list compressed with run-length encoding

  Returns:
      number[]: The list after being decompressed
  """
    decompressed = []

    for i in range(0, len(nums), 2):
        freq = nums[i]
        val = nums[i + 1]
        decompressed.extend([val] * freq)

    return decompressed


run_tests(decompress_encoded_list)
Exemplo n.º 26
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests


def transpose_matrix(matrix):
    """ 
  A function that transposes a matrix. 
  Transposing a matrix means the rows are now the column and vice-versa.

  Arguments:
      matrix { list[] } -- A list of lists, representing a matrix

  Returns:
      list[] -- A list of lists, representing the transpose of the given matrix
  """
    return [list(a) for a in zip(*matrix)]


run_tests(transpose_matrix)
Exemplo n.º 27
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests

from string import ascii_lowercase


def is_beautiful_string(input_string):
    """
  Determine if a given string is beautiful

  Arguments:
      input_string {string} -- A string to analyze if its beautiful or not

  Returns:
      boolean -- Indicating if the string is beautiful or not
  """
    for i, char in enumerate(ascii_lowercase[1:], 1):
        if input_string.count(char) > input_string.count(
                ascii_lowercase[i - 1]):
            return False
    return True


run_tests(is_beautiful_string)
Exemplo n.º 28
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests


def maximum_balanced_strings(s):

    count = 0
    maximum_strings = 0

    for char in s:
        count += 1 if char == 'L' else -1
        if count == 0:
            maximum_strings += 1

    return maximum_strings


run_tests(maximum_balanced_strings)
Exemplo n.º 29
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests

import itertools


def running_sum(numbers):
    """ A function that given an array, returns the sum of each element until i

  Args:
      numbers ( number[] ):  An array of integers

  Returns:
      number[]: An array of integers with the running sum of the given array
  """
    return list(itertools.accumulate(numbers))


run_tests(running_sum)
Exemplo n.º 30
0
import sys
sys.path.insert(1, sys.path[0] + '/../../../RunTests/Python')
from run_test import run_tests


def find_single(numbers):
    """ A function that scans an array of numbers with duplicated items to find the one item without a duplicate value

  Arguments:
      numbers { num[]} -- An array of numbers

  Returns:
      num -- A number from the array that has no duplicate
  """
    return [n for n in numbers if numbers.count(n) == 1][0]


run_tests(find_single)