└── Codesignal Arcade - Intro ├── 01 - add.py ├── 02 - centuryFromYear.py ├── 03 - checkPalindrome.py ├── 04 - adjacentElementsProduct.py ├── 05 - shapeArea.py ├── 06 - makeArrayConsecutive2.py ├── 07 - almostIncreasingSequence.py ├── 08 - matrixElementsSum.py ├── 09 - allLongestStrings.py ├── 10 - commonCharacterCount.py ├── 11 - isLucky.py ├── 12 - sortByHeight.py ├── 13 - reverseInParentheses.py ├── 14 - alternatingSums.py ├── 15 - addBorder.py ├── 16 - areSimilar.py ├── 17 - arrayChange.py ├── 18 - palindromeRearranging.py ├── 19 - areEquallyStrong.py ├── 20 - arrayMaximalAdjacentDifference.py ├── 21 - isIPv4Address.py ├── 22 - avoidObstacles.py ├── 23 - boxBlur.py ├── 24 - minesweeper.py ├── 25 - arrayReplace.py ├── 26 - evenDigitsOnly.py ├── 27 - variableName.py ├── 28 - alphabeticShift.py ├── 29 - chessBoardCellColor.py ├── 30 - circleOfNumbers.py ├── 31 - depositProfit.py ├── 32 - absoluteValuesSumMinimization.py ├── 33 - stringsRearrangement.py ├── 34 - extractEachKth.py ├── 35 - firstDigit.py ├── 36 - differentSymbolsNaive.py ├── 37 - arrayMaxConsecutiveSum.py ├── 38 - growingPlant.py ├── 39 - knapsackLight.py ├── 40 - longestDigitsPrefix.py ├── 41 - digitDegree.py ├── 42 - bishopAndPawn.py ├── 43 - isBeautifulString.py ├── 44 - findEmailDomain.py ├── 45 - buildPalindrome.py ├── 46 - electionWinners.py ├── 47 - isMAC48Address.py ├── 48 - isDigit.py ├── 49 - lineEncoding.py ├── 50 - chessKnight.py ├── 51 - deleteDigit.py ├── 52 - longestWord.py ├── 53 - validTime.py ├── 54 - sumUpNumbers.py ├── 55 - differentSquares.py ├── 56 - digitsProduct.py ├── 57 - fileNaming.py ├── 58 - messageFromBinaryCode.py ├── 59 - spiralNumbers.py └── 60 - Sudoku.py /Codesignal Arcade - Intro/01 - add.py: -------------------------------------------------------------------------------- 1 | """ Write a function that returns the sum of two numbers. 2 | 3 | Example: 4 | For param1 = 1 and param2 = 2, the output should be add(param1, param2) = 3. """ 5 | def add(param1, param2): 6 | # A pretty straightforward exercise. A function including 2 parameters, which are summed together, returning the sum as the result. 7 | sum = param1 + param2 8 | return sum 9 | -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/02 - centuryFromYear.py: -------------------------------------------------------------------------------- 1 | """Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second - 2 | from the year 101 up to and including the year 200, etc. 3 | 4 | Example: 5 | - For year = 1905, the output should be centuryFromYear(year) = 20; 6 | - For year = 1700, the output should be centuryFromYear(year) = 17. """ 7 | def centuryFromYear(year): 8 | # We begin by getting the INTEGER quotient of the division of the year given by 100. 9 | # This will give us the first two digits, which would be the century. 10 | cen = int(year/100) 11 | # However, we should keep in mind that we refer to years between e.g. 1701 - 1800 12 | # as the "18th century". Hence, we implement a while loop, where the condition is 13 | # that the year is a positive integer (which is always true). If the remainder of the 14 | # division of the year by 100 is 0, then the two first digits of the division represent 15 | # the century. Otherwise, if the remainder is non-zero, the century is found by adding 1 16 | # to the result of the division (i.e. "cen"). 17 | while year >= 1: 18 | if year % 100 == 0: 19 | return year / 100 20 | else: 21 | return cen + 1 22 | -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/03 - checkPalindrome.py: -------------------------------------------------------------------------------- 1 | """Given the string, check if it is a palindrome. 2 | 3 | Example: 4 | - For inputString = "aabaa", the output should be checkPalindrome(inputString) = true; 5 | - For inputString = "abac", the output should be checkPalindrome(inputString) = false; 6 | - For inputString = "a", the output should be checkPalindrome(inputString) = true.""" 7 | def checkPalindrome(inputString): 8 | # Step 1: We turn all letters in our given string into lower case. 9 | inp = inputString.lower() 10 | # Step 2: Also, we discard all space between words or letters. 11 | # It is important to store the result in the same variable as in step 1. 12 | # Think of it as only dealing with discarding the spaces. 13 | inp = inp.replace(" ","") 14 | # The first two steps help us end up with a long, uniform (in terms of letter size) string. 15 | # Step 3: We define a variable called "reverse" as the reversed counterpart of the input string. 16 | reverse = inp[::-1] 17 | # Step 4: The outcome will be "True" only if the original string and its reversed counterpart are the same. 18 | if (reverse == inp): 19 | return True 20 | else: 21 | return False 22 | -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/04 - adjacentElementsProduct.py: -------------------------------------------------------------------------------- 1 | """Given an array of integers, find the pair of adjacent elements that has the largest product and return that product. 2 | 3 | Example: 4 | For inputArray = [3, 6, -2, -5, 7, 3], the output should be adjacentElementsProduct(inputArray) = 21. 5 | 7 and 3 produce the largest product.""" 6 | def adjacentElementsProduct(inputArray): 7 | # Step 1: Initially, define an empty array where we will store the products of adjacent elements from the input array. 8 | ArrayEnd = [] 9 | # Step 2: Using a for-loop, we go over all entries of the input array, calculating the products of adjacent elements 10 | # and appending them to the empty array from step 1. 11 | for i in range(len(inputArray) - 1): 12 | ArrayEnd.append(inputArray[i]*inputArray[i+1]) 13 | #Step 3: We seek the largest entry in "ArrayEnd" from step 1, using the max() function. 14 | maximum = max(ArrayEnd) 15 | return maximum 16 | -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/05 - shapeArea.py: -------------------------------------------------------------------------------- 1 | """Below we will define an n-interesting polygon. Your task is to find the area of a polygon for a given n. 2 | A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the 3 | (n - 1)-interesting polygon and appending 1-interesting polygons to its rim, side by side. 4 | You can see the 1-, 2-, 3- and 4-interesting polygons in the picture below. (PICTURE PROVIDED AT:WWW.CODESIGNAL.COM) 5 | 6 | Example: 7 | - For n = 2, the output should be shapeArea(n) = 5; 8 | - For n = 3, the output should be shapeArea(n) = 13.""" 9 | def shapeArea(n): 10 | # Case 1: If the polygon is 0-interesting, it has an area equal to zero. 11 | if n == 0: 12 | return None 13 | # Case 2: If the polygon is 1-interesting, it has an area equal to one. 14 | elif n == 1: 15 | return 1 16 | # Case 3: If the polygon is n-interesting, it has an area equal to the sum of the square of n 17 | # and the square of n-1. A way that I thought of it (based on the picture provided) is the following: 18 | # - n**2: Counted the number of the blue squares from the middle line upwards (INCLUDING the blue squares of the middle line). 19 | # - (n-1)**2: Counted the number of the blue squares from the middle line downwards (EXCLUDING the blue squares of the middle line). 20 | # Of course, you can easily check that the terms "upwards/downwards" could be inverted, without affecting the validity of your counting. 21 | elif n > 1: 22 | result = (n ** 2) + ((n - 1) ** 2) 23 | return result 24 | -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/06 - makeArrayConsecutive2.py: -------------------------------------------------------------------------------- 1 | """Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. 2 | Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the 3 | previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of 4 | additional statues needed. 5 | 6 | Example: 7 | For statues = [6, 2, 3, 8], the output should be makeArrayConsecutive2(statues) = 3. 8 | Ratiorg needs statues of sizes 4, 5 and 7.""" 9 | def makeArrayConsecutive2(statues): 10 | # Step 1: We begin by creating a new array called "stat_arr", which will accommodate the sorted version of the original "statues" array. 11 | stat_arr = sorted(statues) 12 | # Step 2: Furthermore, we use the first element of the sorted array as our index (that will be used in the following steps). 13 | i = stat_arr[0] 14 | # Step 3: We create an empty list called "result" to store our (numbered) missing statues. 15 | result = list() 16 | # Step 4: We initiate a while-loop with the condition that the index from Step 2 is not equal to the last (hence largest) entry of 17 | # the stat_arr. You must make sure that you add the "incrementation by 1" part to make the while loop proceed to the next element. 18 | while i != stat_arr[-1]: 19 | i += 1 20 | # Step 5: Here, using a simple if statement, we examine whether the i-th (integer) element is included in the stat_arr. 21 | # If it is not, we append it to the result list. Otherwise, the loop continues. 22 | if i not in stat_arr: 23 | result.append(i) 24 | else: 25 | continue 26 | # Step 6: Finally, we return the length/size of the result list, i.e. the number of our "missing" statues. 27 | return len(result) 28 | -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/07 - almostIncreasingSequence.py: -------------------------------------------------------------------------------- 1 | """Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence 2 | by removing no more than one element from the array. 3 | 4 | Note: sequence a0, a1, ..., an is considered to be a strictly increasing if a0 < a1 < ... < an. 5 | Sequence containing only one element is also considered to be strictly increasing. 6 | 7 | Example: 8 | - For sequence = [1, 3, 2, 1], the output should be almostIncreasingSequence(sequence) = false. 9 | There is no one element in this array that can be removed in order to get a strictly increasing sequence. 10 | - For sequence = [1, 3, 2], the output should be almostIncreasingSequence(sequence) = true. 11 | You can remove 3 from the array to get the strictly increasing sequence [1, 2]. 12 | Alternately, you can remove 2 to get the strictly increasing sequence [1, 3].""" 13 | def almostIncreasingSequence(sequence): 14 | # Step 1: We begin by assigning the length of the given sequence to the variable n. 15 | n = len(sequence) 16 | # Step 2: By definition, if the sequence contains up to 1 elements, it is considered to be strictly increasing. 17 | if n <= 2: 18 | return True 19 | # Step 3: We set up two counters, namely c1 and c2, so that we count how many elements should be removed. 20 | # NOTE THAT c1 refers ONLY to adjacent elements whilst c2 refers to elements just before and just after the i-th element. 21 | c1 = 0 22 | c2 = 0 23 | # Step 4: This for-loop (and its content) is a tricky part. The range of the for-loop starts from 1 and goes all the way to (n-1)th element. 24 | # BE CAREFUL: We set n-1 to avoid getting our index out of range in the second if statement inside the for-loop. 25 | for i in range(1, n-1): 26 | # Step 5: If the element prior to the index element i has a bigger value than i, we add 1 hit to the first counter. 27 | if sequence[i-1] >= sequence[i]: 28 | c1 += 1 29 | # Step 6: If the element just before the index element i has a bigger value than the element just after i, 30 | # we add 1 hit to the second counter. 31 | if sequence[i-1] >= sequence[i+1]: 32 | c2 += 1 33 | # Step 7: If the element two places to the left of the index element i has a bigger value than the element prior to i, 34 | # we add 1 hit to the first counter. 35 | if sequence[n-1] <= sequence[n-2]: 36 | c1 += 1 37 | # Step 8: If BOTH of the counters have up to 1 hit (that means 0 or 1 EACH), then the sequence is almost increasing. 38 | if c1 <= 1 and c2 <= 1: 39 | return True 40 | else: 41 | return False 42 | -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/08 - matrixElementsSum.py: -------------------------------------------------------------------------------- 1 | """After becoming famous, the CodeBots decided to move into a new building together. 2 | Each of the rooms has a different cost, and some of them are free, but there's a rumour that all the free rooms are haunted! 3 | Since the CodeBots are quite superstitious, they refuse to stay in any of the free rooms, or any of the rooms below any of the free rooms. 4 | 5 | Given matrix, a rectangular matrix of integers, where each value represents the cost of the room, your task is to return 6 | the total sum of all rooms that are suitable for the CodeBots (ie: add up all the values that don't appear below a 0). 7 | 8 | Example: 9 | For 10 | matrix = [[0, 1, 1, 2], 11 | [0, 5, 0, 0], 12 | [2, 0, 3, 3]] 13 | the output should be matrixElementsSum(matrix) = 9. 14 | 15 | example 1: There are several haunted rooms, so we'll disregard them as well as any rooms beneath them. 16 | Thus, the answer is 1 + 5 + 1 + 2 = 9. (PICTURE PROVIDED AT:WWW.CODESIGNAL.COM) 17 | 18 | For 19 | matrix = [[1, 1, 1, 0], 20 | [0, 5, 0, 1], 21 | [2, 1, 3, 10]] 22 | the output should be matrixElementsSum(matrix) = 9. 23 | 24 | example 2: 25 | Note that the free room in the final column makes the full column unsuitable for bots (not just the room directly beneath it). 26 | Thus, the answer is 1 + 1 + 1 + 5 + 1 = 9. (PICTURE PROVIDED AT:WWW.CODESIGNAL.COM)""" 27 | def matrixElementsSum(matrix): 28 | # Step 1: We begin by defining the number of rows and columns inside our given matrix. 29 | # You can conceive the number of rows as the number of nested arrays inside the main array and 30 | # the number of columns as the number of elements in the first nested array. 31 | # Feel free to convince yourself that this is the case by referring to the examples of matrices shown above. 32 | rows = len(matrix) 33 | cols = len(matrix[0]) 34 | # Step 2: Furthermore, create a new variable called "summ" (from summation) and set it equal to zero. 35 | # It will be used in the following for-loop. 36 | summ = 0 37 | # Step 3: Here we have an unusual for-inside-a-for loop (compared to the one that we usually observe when dealing with matrices). 38 | # As we are interested in the position of elements in columns (elements BELOW 0s), the outside for-loop works across all columns 39 | # whilst the nested for-loop works across all rows. 40 | for j in range(cols): 41 | for i in range(rows): 42 | # Step 4: If, while counting, the loop meets an element whose value is zero, the counting stops. 43 | # Otherwise, it continues counting, each time adding the value of the i-th / j-th element to the "summ" variable, defined in step 2. 44 | if matrix[i][j] == 0: 45 | break 46 | summ += matrix[i][j] 47 | # Step 5: Therefore, we end up with the total sum of non-zero elements whose position in a column is not 48 | # below an element of value zero. 49 | return summ 50 | -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/09 - allLongestStrings.py: -------------------------------------------------------------------------------- 1 | """Given an array of strings, return another array containing all of its longest strings. 2 | 3 | Example: 4 | For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be allLongestStrings(inputArray) = ["aba", "vcd", "aba"].""" 5 | def allLongestStrings(inputArray): 6 | # Step 1: We begin by defining an empty array called "max_arr", where we will store the longest strings from the given array. 7 | max_arr = [] 8 | # Step 2: The next step is to define the maximum string length inside our given array. 9 | # BE CAREFUL: Variable max_len should be defined as follows. If we break it into its components, we can see that: 10 | # max(inputArray, key = len) locates ONLY ONE of the strings that satisfies the maximum value in terms of the key parameter 11 | # provided (which, in this case, is the string's length) and the outside len() function defines the value of this maximum length. 12 | # You are free to test it on a random input array containing various random strings, using a Python compiler online. 13 | max_len = len(max(inputArray, key = len)) 14 | # Step 3: Now, we go over all strings inside the input array checking if their individual length is equal to the 15 | # maximum length value defined in step 2. If it is, then we append the respective string to the "max_arr" defined above. 16 | for i in inputArray: 17 | if len(i) == max_len: 18 | max_arr.append(i) 19 | # Step 4: We conclude by returning the max_arr. 20 | return max_arr 21 | -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/10 - commonCharacterCount.py: -------------------------------------------------------------------------------- 1 | """Given two strings, find the number of common characters between them. 2 | 3 | Example: 4 | For s1 = "aabcc" and s2 = "adcaa", the output should be commonCharacterCount(s1, s2) = 3. 5 | Strings have 3 common characters - 2 "a"s and 1 "c".""" 6 | def commonCharacterCount(s1, s2): 7 | # Step 1: We create two lists, namely s1_l and s2_l, where we store the characters of strings s1 and s2 respectively. 8 | s1_l = list(s1) 9 | s2_l = list(s2) 10 | # Step 2: We also create an empty list, where we are going to store all common characters. 11 | common = [] 12 | # Step 3: Using a for-loop, we investigate the list of the first string, element by element. 13 | for i in s1_l: 14 | # Step 4: If the i-th element from the list of the first string is also present in the list of the second string, 15 | # we append it to the common array. BE CAREFUL: We must implement the s2_l.remove(i) to avoid double-counting. 16 | # I checked myself and I can assure you that you can substitute s1_l for s2_l and vice versa (in the for-loop, 17 | # the if statement and the double-counting term), without affecting the validity of your code. 18 | if i in s2_l: 19 | common.append(i) 20 | s2_l.remove(i) 21 | # Step 5: Finally, we return the length of the common list, to find the number of the common characters 22 | # between the two strings given. 23 | return len(common) 24 | -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/11 - isLucky.py: -------------------------------------------------------------------------------- 1 | """Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky 2 | if the sum of the first half of the digits is equal to the sum of the second half. 3 | Given a ticket number n, determine if it's lucky or not. 4 | 5 | Example 6 | - For n = 1230, the output should be isLucky(n) = true; 7 | - For n = 239017, the output should be isLucky(n) = false.""" 8 | def isLucky(n): 9 | # Step 1: We begin by creating an empty array, called "digits_of_n", 10 | # where we will store the digits of the given number n, as individual elements. 11 | digits_of_n = [] 12 | # Step 2: We also create a new variable, called "summ" (from summation), and set its value to zero. 13 | # It will be useful in one of the later steps. 14 | summ = 0 15 | # Step 3: I have personally seen this while-loop trick being used to split numbers into their individual digits. 16 | # As it will take quite a long text to explain this comprehensively, I'd suggest you use the print() function in each 17 | # step to see what how each of these steps works. The important thing to mention is the "appending" step where each 18 | # digit, where each digit is stored as an elememnt in "digits_of_n" array. 19 | while n > 0: 20 | rem = n % 10 21 | digits_of_n.append(rem) 22 | n = int(n / 10) 23 | # Step 4: Furthermore, we implement a for-loop that goes over all elements inside the "digits_of_n" array, one by one. 24 | # If the element's index is up to the middle of the length of the array, we add the element's numeric value to "summ". 25 | # Otherwise, we subtract it. NOTE THAT for arrays of even length, you can find the "middle" by dividing the length by 2 26 | # (i.e. for arrays of length 4, the 2nd element is the "middle), whilst for array of odd length, the "middle" is the 27 | # element having equal numbers of elements on both its sides. 28 | for i in range(len(digits_of_n)): 29 | if i < len(digits_of_n)/2: 30 | summ += digits_of_n[i] 31 | else: 32 | summ -= digits_of_n[i] 33 | # Step 5: Finally, we check if the summation is zero or not. If the sum is zero, then the ticket number is lucky, 34 | # according to the definition of the exercise. 35 | if summ == 0: 36 | return True 37 | return False 38 | -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/12 - sortByHeight.py: -------------------------------------------------------------------------------- 1 | """Some people are standing in a row in a park. There are trees between them which cannot be moved. 2 | Your task is to rearrange the people by their heights in a non-descending order without moving the trees. 3 | People can be very tall! 4 | 5 | Example: 6 | - For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190].""" 7 | def sortByHeight(a): 8 | # Step 1: We begin by creating a counter, starting from 0, that will be used in the subsequent for-loop. 9 | j = 0 10 | # Step 2: We also create a new array, called "a_sort", where we sort (in ascending order) all elements of the given array "a" 11 | # that are not "trees" (i.e. do not have a value of -1). 12 | a_sort = sorted([i for i in a if i != -1]) 13 | # Step 3: By implementing a for-loop, we investigate all elements of the given array "a" (NOT a_sort!) and check: 14 | # if the element i in array "a" is equal to -1, the for-loop continues. Otherwise, the element i in array "a" should be 15 | # the same as element j in array "a_sort" (starting from 0 index, as defined in step 1). 16 | # You can think of it as working through elements of array "a", disregarding the "trees" (-1s) and sorting the rest 17 | # of the elements in ascending order (as in a_sort). 18 | for i in range(len(a)): 19 | if a[i] == -1: 20 | pass 21 | else: 22 | a[i] = a_sort[j] 23 | j += 1 24 | # Step 4: The final step is the return of the modified array "a". 25 | return a 26 | -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/13 - reverseInParentheses.py: -------------------------------------------------------------------------------- 1 | """Write a function that reverses characters in (possibly nested) parentheses in the input string. 2 | Input strings will always be well-formed with matching ()s. 3 | 4 | Example: 5 | - For inputString = "(bar)", the output should be reverseInParentheses(inputString) = "rab"; 6 | - For inputString = "foo(bar)baz", the output should be reverseInParentheses(inputString) = "foorabbaz"; 7 | - For inputString = "foo(bar)baz(blim)", the output should be reverseInParentheses(inputString) = "foorabbazmilb"; 8 | - For inputString = "foo(bar(baz))blim", the output should be reverseInParentheses(inputString) = "foobazrabblim". 9 | Because "foo(bar(baz))blim" becomes "foo(barzab)blim" and then "foobazrabblim".""" 10 | def reverseInParentheses(inputString): 11 | # Step 1: We create a for-loop that goes over all elements of the input string. If element i is an opening bracket, then i 12 | # is defined as "start". In a similar manner, if element i is a closing bracket, i is defined as "end". NOTE THAT 13 | # if you write it as "i = start" or "i = end", an error will pop up (tested) as you would have not defined any variables 14 | # under those names, whilst the way that is written now you define as "start" and "end" elements that are 15 | # "(" and ")" respectively. 16 | for i in range(len(inputString)): 17 | if inputString[i] == "(": 18 | start = i 19 | if inputString[i] == ")": 20 | end = i 21 | # Step 2: Furthermore, we apply the function inside itself and concatenate the individual modified parts: 22 | # the part of the input string up to (and NOT including) the "starting" point (i.e. opening bracket) is left intact. 23 | # The same goes for the part of the input string one element AFTER the "ending" point (i.e. closing bracket) 24 | # till the actual end of the input string. The part of the input string that is located one element after 25 | # the starting point ("start"+1 included) and up to the "ending" point NOT included is reversed. 26 | return reverseInParentheses(inputString[:start] + inputString[start+1:end][::-1] + inputString[end+1:]) 27 | # Step 3: To conclude, we return the modified input string. 28 | return inputString 29 | -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/14 - alternatingSums.py: -------------------------------------------------------------------------------- 1 | """Several people are standing in a row and need to be divided into two teams. The first person goes into team 1, 2 | the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and so on. 3 | 4 | You are given an array of positive integers - the weights of the people. Return an array of two integers, 5 | where the first element is the total weight of team 1, and the second element is the total weight 6 | of team 2 after the division is complete. 7 | 8 | Example: 9 | - For a = [50, 60, 60, 45, 70], the output should be alternatingSums(a) = [180, 105].""" 10 | def alternatingSums(a): 11 | # Step 1: We begin by creating an array, called "alt_sum", that includes only two elements of value 0. 12 | alt_sum = [0, 0] 13 | # Step 2: Moreover, we define the variable "length", which is the numerical value of the length of input array a. 14 | length = len(a) 15 | # Step 3: Starting from the first element of input array "a" and working all the way through its length, 16 | # we check whether the element's index is even or odd. If the element i is even, we add its value to the 17 | # first element of the "alt_sum" array, whilst if it is odd we add it to the second element. 18 | for i in range(0, length): 19 | if i % 2 == 0: 20 | alt_sum[0] += a[i] 21 | else: 22 | alt_sum[1] += a[i] 23 | # Step 4: To conclude, we return the alt_sum array. 24 | return alt_sum 25 | -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/15 - addBorder.py: -------------------------------------------------------------------------------- 1 | def addBorder(picture): 2 | new_pic = [] 3 | border = "" 4 | pic_len = len(picture) 5 | for i in range(0, len(picture[0])+2): 6 | border += "*" 7 | new_pic.append(border) 8 | for i in range(0, pic_len): 9 | new_pic.append("*" + picture[i] + "*") 10 | new_pic.append(border) 11 | return new_pic -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/16 - areSimilar.py: -------------------------------------------------------------------------------- 1 | def areSimilar(a, b): 2 | check_a = [] 3 | check_b = [] 4 | count = 0 5 | for i in range(len(a)): 6 | if a[i] != b[i]: 7 | count += 1 8 | check_a.append(a[i]) 9 | check_b.append(b[i]) 10 | if count == 0: 11 | return True 12 | elif count == 2: 13 | return set(check_a) == set(check_b) 14 | else: 15 | return False -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/17 - arrayChange.py: -------------------------------------------------------------------------------- 1 | def arrayChange(inputArray): 2 | first = inputArray[0] 3 | count = 0 4 | for i in inputArray[1:]: 5 | if i <= first: 6 | count += first - i + 1 7 | first = first + 1 8 | else: 9 | first = i 10 | return count -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/18 - palindromeRearranging.py: -------------------------------------------------------------------------------- 1 | def palindromeRearranging(inputString): 2 | odd_count = 0 3 | char_set = set(inputString) 4 | for i in char_set: 5 | char_count = inputString.count(i) 6 | if char_count % 2 != 0: 7 | odd_count += 1 8 | if odd_count <= 1: 9 | return True 10 | return False -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/19 - areEquallyStrong.py: -------------------------------------------------------------------------------- 1 | def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight): 2 | personal_max = max(yourLeft, yourRight) 3 | friend_max = max(friendsLeft, friendsRight) 4 | sum1 = yourLeft + yourRight 5 | sum2 = friendsLeft + friendsRight 6 | if sum1 == sum2 and personal_max == friend_max: 7 | return True 8 | return False -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/20 - arrayMaximalAdjacentDifference.py: -------------------------------------------------------------------------------- 1 | def arrayMaximalAdjacentDifference(inputArray): 2 | return max((abs(inputArray[i+1]-inputArray[i]) for i in range(0,len(inputArray)-1))) -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/21 - isIPv4Address.py: -------------------------------------------------------------------------------- 1 | def isIPv4Address(inputString): 2 | str_split = inputString.split(".") 3 | count = 0 4 | if len(str_split) != 4: 5 | return False 6 | for i in range(0,4): 7 | if str_split[i] == "" or str_split[i] == "00" or str_split[i] == "01": 8 | return False 9 | if re.search('[a-zA-Z]', str_split[i]): 10 | count += 1 11 | if count > 0: 12 | return False 13 | if str_split[i].isnumeric(): 14 | if int(str_split[i]) < 0: 15 | return False 16 | if int(str_split[i]) > 255: 17 | return False 18 | return True -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/22 - avoidObstacles.py: -------------------------------------------------------------------------------- 1 | def avoidObstacles(inputArray): 2 | for i in range(2, max(inputArray)+2): 3 | if i not in inputArray and all(j%i != 0 for j in inputArray): 4 | return i -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/23 - boxBlur.py: -------------------------------------------------------------------------------- 1 | def boxBlur(image): 2 | def pixels(matrix, i, j): 3 | summ = 0 4 | for x in range(i - 1, i + 2): 5 | for y in range(j - 1, j + 2): 6 | summ += matrix[x][y] 7 | mean = summ // 9 8 | return mean 9 | 10 | output = [] 11 | row = len(image) 12 | col = len(image[0]) 13 | for i in range(1, row - 1): 14 | arr = [] 15 | for j in range(1, col - 1): 16 | arr.append(pixels(image, i, j)) 17 | output.append(arr) 18 | return output -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/24 - minesweeper.py: -------------------------------------------------------------------------------- 1 | def minesweeper(matrix): 2 | row = len(matrix) 3 | col = len(matrix[0]) 4 | def neighbouring_squares(i,j): 5 | return (sum(matrix[x][y] for x in range(i-1,i+2) if 0 <= x < row 6 | for y in range(j-1,j+2) if 0 <= y < col 7 | if i != x or j != y)) 8 | return [[neighbouring_squares(i,j) for j in range(col)] for i in range(row)] -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/25 - arrayReplace.py: -------------------------------------------------------------------------------- 1 | def arrayReplace(inputArray, elemToReplace, substitutionElem): 2 | new = [] 3 | for i in range(len(inputArray)): 4 | if inputArray[i] == elemToReplace: 5 | new.append(substitutionElem) 6 | else: 7 | new.append(inputArray[i]) 8 | return new -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/26 - evenDigitsOnly.py: -------------------------------------------------------------------------------- 1 | def evenDigitsOnly(n): 2 | digits_of_n = [] 3 | while n > 0: 4 | rem = n % 10 5 | digits_of_n.append(rem) 6 | n = int(n / 10) 7 | for i in range(len(digits_of_n)): 8 | if digits_of_n[i] % 2 != 0: 9 | return False 10 | return True -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/27 - variableName.py: -------------------------------------------------------------------------------- 1 | def variableName(name): 2 | str_name = [i for i in str(name)] 3 | non_acc_chars = [" ", ">", "<", ":", "-", "|", ".", ",", "!", "[", "]", "'", "/", "@", "#", "&", "%", "?", "*"] 4 | if str_name[0] in str([0,1,2,3,4,5,6,7,8,9]): 5 | return False 6 | for j in range(len(str_name)): 7 | if str_name[j] in non_acc_chars: 8 | return False 9 | return True -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/28 - alphabeticShift.py: -------------------------------------------------------------------------------- 1 | def alphabeticShift(inputString): 2 | return "".join(chr(ord(i)+1) if i != "z" else "a" for i in inputString) -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/29 - chessBoardCellColor.py: -------------------------------------------------------------------------------- 1 | def chessBoardCellColor(cell1, cell2): 2 | cell1_elm = ord(cell1[0])+int(cell1[1]) 3 | cell2_elm = ord(cell2[0])+int(cell2[1]) 4 | return (cell1_elm + cell2_elm)%2 == 0 -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/30 - circleOfNumbers.py: -------------------------------------------------------------------------------- 1 | def circleOfNumbers(n, firstNumber): 2 | return ((n/2) + firstNumber) % n -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/31 - depositProfit.py: -------------------------------------------------------------------------------- 1 | def depositProfit(deposit, rate, threshold): 2 | year_count = 0 3 | while deposit < threshold: 4 | deposit = deposit + (deposit * (rate/100)) 5 | year_count += 1 6 | return year_count -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/32 - absoluteValuesSumMinimization.py: -------------------------------------------------------------------------------- 1 | def absoluteValuesSumMinimization(a): 2 | sums = [] 3 | for i in range(len(a)): 4 | sum = 0 5 | for j in range(len(a)): 6 | sum += abs(a[i] - a[j]) 7 | sums.append(sum) 8 | return a[sums.index(min(sums))] -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/33 - stringsRearrangement.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations as p 2 | def stringsRearrangement(inputArray): 3 | p_list = list(p(inputArray)) 4 | for i in range(len(p_list)): 5 | count1 = 0 6 | for j in range(len(p_list[0])-1): 7 | count2 = 0 8 | for k in range(len(p_list[0][0])): 9 | if p_list[i][j][k] != p_list[i][j+1][k]: 10 | count2 +=1 11 | if count2 == 1: 12 | count1 +=1 13 | if count1 >= (len(p_list[0])) - 1: 14 | return True 15 | return False -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/34 - extractEachKth.py: -------------------------------------------------------------------------------- 1 | def extractEachKth(inputArray, k): 2 | inp = [] 3 | for i in range(len(inputArray)): 4 | if (i+1)%k == 0: 5 | pass 6 | else: 7 | inp.append(inputArray[i]) 8 | return inp -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/35 - firstDigit.py: -------------------------------------------------------------------------------- 1 | def firstDigit(inputString): 2 | c = [ i for i in inputString if i.isdigit() ] 3 | return c[0] -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/36 - differentSymbolsNaive.py: -------------------------------------------------------------------------------- 1 | def differentSymbolsNaive(s): 2 | return len(set(s)) -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/37 - arrayMaxConsecutiveSum.py: -------------------------------------------------------------------------------- 1 | def arrayMaxConsecutiveSum(inputArray, k): 2 | arr = [sum(inputArray[:k])] 3 | for i in range(1, len(inputArray) - (k-1)): 4 | arr.append(arr[i-1] - inputArray[i-1] + inputArray[i + k - 1]) 5 | sort_arr = sorted(arr) 6 | return sort_arr[-1] -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/38 - growingPlant.py: -------------------------------------------------------------------------------- 1 | def growingPlant(upSpeed, downSpeed, desiredHeight): 2 | day_count = 0 3 | height = 0 4 | while height <= desiredHeight: 5 | height = height + upSpeed 6 | day_count += 1 7 | if height < desiredHeight: 8 | height = height - downSpeed 9 | else: 10 | return day_count -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/39 - knapsackLight.py: -------------------------------------------------------------------------------- 1 | def knapsackLight(value1, weight1, value2, weight2, maxW): 2 | if weight1 > maxW and weight2 > maxW and weight1 + weight2 > maxW: 3 | return 0 4 | if weight1 + weight2 <= maxW: 5 | return value1 + value2 6 | if value1 < value2: 7 | if weight2 > maxW: 8 | return value1 9 | else: 10 | return value2 11 | if value2 < value1: 12 | if weight1 > maxW: 13 | return value2 14 | else: 15 | return value1 16 | if value1 == value2: 17 | if weight1 > maxW: 18 | return value2 19 | else: 20 | return value1 -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/40 - longestDigitsPrefix.py: -------------------------------------------------------------------------------- 1 | def longestDigitsPrefix(inputString): 2 | count = 0 3 | for i in range(len(inputString)): 4 | if inputString[i].isdigit(): 5 | count += 1 6 | else: 7 | return inputString[0:count] 8 | return inputString -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/41 - digitDegree.py: -------------------------------------------------------------------------------- 1 | def digitDegree(n): 2 | degree = 0 3 | while 10 <= n: 4 | num = str(n) 5 | n = sum(int(i) for i in num) 6 | degree += 1 7 | return degree -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/42 - bishopAndPawn.py: -------------------------------------------------------------------------------- 1 | def bishopAndPawn(bishop, pawn): 2 | if ord(bishop[0]) == ord(pawn[0]): 3 | return False 4 | else: 5 | bishop_elm = ord(bishop[0])+int(bishop[1]) 6 | pawn_elm = ord(pawn[0])+int(pawn[1]) 7 | return (bishop_elm + pawn_elm)%2 == 0 -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/43 - isBeautifulString.py: -------------------------------------------------------------------------------- 1 | def isBeautifulString(inputString): 2 | counter = [inputString.count(i) for i in string.ascii_lowercase] 3 | return counter[::-1] == sorted(counter) -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/44 - findEmailDomain.py: -------------------------------------------------------------------------------- 1 | def findEmailDomain(address): 2 | address_spl = address.split("@") 3 | c = [ i for i in address_spl ] 4 | if len(address_spl) == 2: 5 | return c[1] 6 | if len(address_spl) == 3: 7 | return c[2] -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/45 - buildPalindrome.py: -------------------------------------------------------------------------------- 1 | def buildPalindrome(st): 2 | for i in range(len(st)): 3 | sub = st[i:len(st)] 4 | if sub[::-1] == sub: 5 | missing = st[0:i] 6 | return st + missing[::-1] 7 | return st -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/46 - electionWinners.py: -------------------------------------------------------------------------------- 1 | def electionsWinners(votes, k): 2 | max_vote = max(votes) 3 | len_vote = len(votes) 4 | if k == 0 and votes.count(max_vote) == 1: 5 | return 1 6 | return len([ i for i in range(len_vote) if votes[i] + k > max_vote ]) -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/47 - isMAC48Address.py: -------------------------------------------------------------------------------- 1 | def isMAC48Address(inputString): 2 | str_split = inputString.split("-") 3 | count = 0 4 | if len(inputString) != 17: 5 | return False 6 | if len(str_split) != 6: 7 | return False 8 | for i in range(0,6): 9 | if str_split[i] == "": 10 | return False 11 | if re.search('[a-zG-Z]', str_split[i]): 12 | count += 1 13 | if count > 0: 14 | return False 15 | return True -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/48 - isDigit.py: -------------------------------------------------------------------------------- 1 | # Solution 1: Analytic 2 | def isDigit(symbol): 3 | if symbol.isdigit(): 4 | return True 5 | return False 6 | 7 | # Solution 2: One-liner 8 | def isDigit(symbol): 9 | return symbol.isdigit() -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/49 - lineEncoding.py: -------------------------------------------------------------------------------- 1 | from itertools import groupby 2 | def lineEncoding(s): 3 | s2 = "" 4 | for k,g in groupby(s): 5 | l = len(list(g)) 6 | if l == 1: 7 | s2 += k 8 | else: 9 | s2 += str(l) + k 10 | return s2 -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/50 - chessKnight.py: -------------------------------------------------------------------------------- 1 | import itertools as t 2 | def chessKnight(cell): 3 | knight_dir = list(t.permutations([1,2,-1,-2],2)) 4 | knight_dir1 = [] 5 | valid_moves = 0 6 | for i in range(len(knight_dir)): 7 | if sum(knight_dir[i]) != 0: 8 | knight_dir1.append(knight_dir[i]) 9 | for x,y in knight_dir1: 10 | if (97 <= ord(cell[0]) + x <= 104) and (1 <= int(cell[1]) + y <= 8): 11 | valid_moves += 1 12 | return valid_moves -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/51 - deleteDigit.py: -------------------------------------------------------------------------------- 1 | def deleteDigit(n): 2 | num = str(n) 3 | result = list(int(''.join(num[:i]+num[1+i:])) for i in range(len(num))) 4 | return max(result) -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/52 - longestWord.py: -------------------------------------------------------------------------------- 1 | def longestWord(text): 2 | word_split = re.findall(r"[\w']+", text) 3 | longest_word = '' 4 | for word in word_split: 5 | if len(word) > len(longest_word) and word.isalpha(): 6 | longest_word = word 7 | return longest_word -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/53 - validTime.py: -------------------------------------------------------------------------------- 1 | def validTime(time): 2 | time_split = time.split(":") 3 | if 00 <= int(time_split[0]) <= 23 and 00 <= int(time_split[1]) <= 59: 4 | return True 5 | return False -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/54 - sumUpNumbers.py: -------------------------------------------------------------------------------- 1 | def sumUpNumbers(inputString): 2 | def getNumbers(str): 3 | nums = re.findall(r'[0-9]+', str) 4 | return nums 5 | numbers = getNumbers(inputString) 6 | total = 0 7 | for i in numbers: 8 | total += int(i) 9 | return total -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/55 - differentSquares.py: -------------------------------------------------------------------------------- 1 | def differentSquares(matrix): 2 | rows = len(matrix) 3 | cols = len(matrix[0]) 4 | sq_arr = [] 5 | sq_count = 0 6 | for i in range(rows-1): 7 | for j in range(cols-1): 8 | sq_2x2 = [ matrix[i][j], matrix[i][j+1], matrix[i+1][j], matrix[i+1][j+1] ] 9 | if sq_2x2 not in sq_arr: 10 | sq_arr.append(sq_2x2) 11 | sq_count += 1 12 | return sq_count -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/56 - digitsProduct.py: -------------------------------------------------------------------------------- 1 | def digitsProduct(product): 2 | if product == 0: 3 | return 10 4 | if product == 1: 5 | return 1 6 | for i in range(0, 4000): 7 | p = 1 8 | for j in str(i): 9 | p *= int(j) 10 | if p == product: 11 | return i 12 | return -1 -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/57 - fileNaming.py: -------------------------------------------------------------------------------- 1 | def fileNaming(names): 2 | if names == []: 3 | return [] 4 | new_names = [] 5 | for name in names: 6 | if name not in new_names: 7 | new_names.append(name) 8 | else: 9 | for i in range(1,1000): 10 | new_name = name + '(' + str(i) + ')' 11 | if new_name not in new_names: 12 | new_names.append(new_name) 13 | break 14 | return new_names -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/58 - messageFromBinaryCode.py: -------------------------------------------------------------------------------- 1 | def messageFromBinaryCode(code): 2 | phrase = "" 3 | bits = [int(code[i*8:i*8+8],2) for i in range(len(code)//8)] 4 | for j in range(len(bits)): 5 | phrase += chr(bits[j]) 6 | return phrase -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/59 - spiralNumbers.py: -------------------------------------------------------------------------------- 1 | def spiralNumbers(n): 2 | dims = n 3 | elem = 1 4 | matrix = [ [0]*n for x in range(n) ] 5 | while 0 < dims: 6 | i = n - dims 7 | # you can sub i = n - dims ONLY in the first 2 parts 8 | # where n - dims is in the starting parameter of the range 9 | for j in range(n - dims, dims): 10 | matrix[i][j] = elem 11 | elem += 1 12 | for i in range(n - dims + 1, dims): 13 | matrix[i][j] = elem 14 | elem += 1 15 | for j in range(dims - 2, n - dims - 1, -1): 16 | matrix[i][j] = elem 17 | elem += 1 18 | for i in range(dims - 2, n - dims, -1): 19 | matrix[i][j] = elem 20 | elem += 1 21 | dims -= 1 22 | return matrix -------------------------------------------------------------------------------- /Codesignal Arcade - Intro/60 - Sudoku.py: -------------------------------------------------------------------------------- 1 | # Solution 1: using only for-loops 2 | def sudoku(grid): 3 | for i in range(0,9): 4 | if sorted(grid[i]) != list(range(1,10)): 5 | return False 6 | for j in range(0,9): 7 | if sorted(grid[y][j] for y in range(9)) != list(range(1,10)): 8 | return False 9 | for i in range(0,9,3): 10 | for j in range(0,9,3): 11 | if sorted(grid[x][y] for x in range(i,i+3) for y in range(j,j+3)) != list(range(1,10)): 12 | return False 13 | return True 14 | 15 | # Solution 2: using sub-functions and for loops 16 | def sudoku(grid): 17 | def invalid_rows(x): 18 | return sorted(grid[x]) != list(range(1,10)) 19 | def invalid_cols(y): 20 | return sorted(grid[x][y] for x in range(9)) != list(range(1,10)) 21 | def invalid_subgr(a,b): 22 | return sorted(grid[x][y] for x in range(a,a+3) for y in range(b,b+3)) != list(range(1,10)) 23 | for i in range(0,9): 24 | if invalid_rows(i) or invalid_cols(i): 25 | return False 26 | for i in range(0,9,3): 27 | for j in range(0,9,3): 28 | if invalid_subgr(i,j): 29 | return False 30 | return True --------------------------------------------------------------------------------