├── README.md └── old_practice_problems ├── arcade ├── intro-problems │ ├── easy │ │ ├── add.py │ │ ├── addBorder.py │ │ ├── adjacent_elements_product.py │ │ ├── all_the_longest_strings.py │ │ ├── almost_increasing_sequence.py │ │ ├── alphabeticShift.py │ │ ├── alternating_sums.py │ │ ├── areEquallyStrong.py │ │ ├── arrayMaxConsecutiveSum.py │ │ ├── arrayMaxConsecutiveSum_2.py │ │ ├── arrayMaximalAdjacentDifference.py │ │ ├── arrayReplace.py │ │ ├── array_change.py │ │ ├── avoidObstacles.py │ │ ├── bishopAndPawn.py │ │ ├── calculate_shape_area.py │ │ ├── century_from_year.py │ │ ├── check_Palindrome.py │ │ ├── chessBoardCellColor.py │ │ ├── circleOfNumbers.py │ │ ├── common_character_count.py │ │ ├── differentSymbolsNaive.py │ │ ├── evenDigitsOnly.py │ │ ├── exploring_the_waters.py │ │ ├── extractEachKth.py │ │ ├── firstDigit.py │ │ ├── growingPlant.py │ │ ├── isDigit.py │ │ ├── isLucky.py │ │ ├── knapsackLight.py │ │ ├── longestDigitsPrefix.py │ │ ├── longestWord.py │ │ ├── make_array_consecutive.py │ │ ├── partial_matrix_elements_sum.py │ │ ├── sort_by_height.py │ │ ├── validTime.py │ │ └── variableName.py │ └── medium │ │ ├── absoluteValuesSumMinimization.py │ │ ├── are_similar.py │ │ ├── box_blur.py │ │ ├── buildPalendrome.py │ │ ├── chessKnight.py │ │ ├── deepestProfit.py │ │ ├── deleteDigit.py │ │ ├── differentRightMostBit.py │ │ ├── differentSquares.py │ │ ├── differentSquares_faster.py │ │ ├── digitDegree.py │ │ ├── digitsProduct.py │ │ ├── digitsProduct_codesignal.py │ │ ├── digitsProduct_codesignal_2.py │ │ ├── electionWinners.py │ │ ├── fileNaming.py │ │ ├── findEmailDomain.py │ │ ├── isBeautifulString.py │ │ ├── isIPv4Address.py │ │ ├── isMAC48Address.py │ │ ├── lineEncoding.py │ │ ├── messageFromBinaryCode.py │ │ ├── mineSweeper.py │ │ ├── palindromeRearranging.py │ │ ├── reverse_in_parenthesis.py │ │ ├── spiralNumbers.py │ │ ├── stringsRearrangement.py │ │ ├── sudoku.py │ │ └── sumUpNumbers.py └── the-core │ ├── easy │ ├── addTwoDigits.py │ ├── additionWithoutCarrying.py │ ├── appleBoxes.py │ ├── arithmeticExpression.py │ ├── arrayReplace.py │ ├── candies.py │ ├── candles.py │ ├── circleOfNumbers.py │ ├── comfortableNumbers.py │ ├── concatenateArrays.py │ ├── countSumOfTwoRepresentations2.py │ ├── createArray.py │ ├── extraNumber_XOR.py │ ├── firstReverseTry.py │ ├── increaseNumberRoundness.py │ ├── isInfiniteProcess.py │ ├── isPower.py │ ├── isSmooth.py │ ├── killKthBit.py │ ├── knapsackLight.py │ ├── largestNumber.py │ ├── lastRide.py │ ├── leastFactorial.py │ ├── lineUp.py │ ├── makeArrayConsecutive2.py │ ├── maxMultiple.py │ ├── metroCard.py │ ├── phoneCall.py │ ├── rangeBitcount.py │ ├── reachNextLevel.py │ ├── removeArrayPart.py │ ├── replaceMiddle.py │ ├── rounders.py │ ├── seatsInTheater.py │ ├── secondRightmostZeroBit.py │ ├── swapAdjacentBits.py │ ├── tennisSet.py │ ├── untitled2.py │ ├── weakNumbers.py │ └── willYou.py │ └── medium │ ├── arrayPacking.py │ ├── countBlackCells.py │ ├── countBlackCells_efficient.py │ ├── differentRightMostBit.py │ ├── equalPairOfBits.py │ ├── isSumOfConsecutive2.py │ ├── pagesNumberingWithInk.py │ └── squareDigitsSequence.py ├── daily-challenges └── stringPermutations.py ├── data-structures ├── arrays │ ├── first-non-repeating-character.py │ ├── firstDuplicate.py │ ├── intro-questions.py │ ├── isCryptSolution.py │ ├── rotate-image.py │ └── sudoku2.py ├── hash-tables │ ├── areFollowingPatterns.py │ ├── containsCloseNums.py │ ├── groupingDishes.py │ ├── hash_table_intro.py │ ├── possibleSums.py │ ├── possibleSums_fast.py │ ├── possibleSums_faster.py │ └── swapLexOrder.py ├── linked-lists │ ├── addTwoHugeNumbers.py │ ├── example_batch_reversal.py │ ├── linked_lists_learning.py │ ├── list_palendrome.py │ ├── merge_two_linked_lists.py │ ├── rearrange_last_N.py │ └── remove_K_from_list.py ├── trees │ ├── binary_search_trees.py │ ├── binary_trees.py │ ├── hasPathWithGivenSum.py │ ├── hasPathWithGivenSum2.py │ ├── isTreeSymmetric.py │ └── trees_intro.py └── trie.py └── other └── recursive-practice ├── knapsackRecursive.py └── knapsackRecursiveSolution.py /old_practice_problems/arcade/intro-problems/easy/add.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 9 16:14:05 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Write a function that returns the sum of two numbers. 8 | """ 9 | 10 | def add(param1, param2): 11 | return(param1+param2) 12 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/addBorder.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 00:22:32 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given a rectangular matrix of characters, add a border of asterisks(*) to it. 8 | 9 | Example 10 | 11 | For 12 | 13 | picture = ["abc", 14 | "ded"] 15 | the output should be 16 | 17 | addBorder(picture) = ["*****", 18 | "*abc*", 19 | "*ded*", 20 | "*****"] 21 | Input/Output 22 | 23 | [execution time limit] 4 seconds (py3) 24 | 25 | [input] array.string picture 26 | 27 | A non-empty array of non-empty equal-length strings. 28 | 29 | Guaranteed constraints: 30 | 1 ≤ picture.length ≤ 100, 31 | 1 ≤ picture[i].length ≤ 100. 32 | 33 | [output] array.string 34 | 35 | The same matrix of characters, framed with a border of asterisks of width 1. 36 | """ 37 | import numpy as np 38 | def addBorder_arr(picture): 39 | picture=np.array(picture) 40 | width=len(picture[0]) 41 | height=len(picture) 42 | 43 | #let us make a new array that is the known size of the bordered picture 44 | #so as to conserve memory 45 | new_picture=np.full((height+2,width+2),'*') 46 | 47 | #Fill the inside with the original picture 48 | new_picture[1:-1,1:-1]=picture 49 | 50 | return(new_picture) 51 | 52 | ''' 53 | We are given a list not a matrix so below is the solution used 54 | to satisfy CodeSignal 55 | ''' 56 | 57 | def addBorder(picture): 58 | width=len(picture[0])+2 59 | 60 | new_picture=['*'*width] 61 | for row in picture: 62 | new_picture.append('*'+row+'*') 63 | new_picture.append('*'*width) 64 | 65 | return(new_picture) 66 | 67 | if __name__=='__main__': 68 | picture=['abc','def'] 69 | 70 | for i in picture: 71 | print(i) 72 | 73 | print() 74 | 75 | for i in addBorder(picture): 76 | print(i) 77 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/adjacent_elements_product.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 9 16:17:06 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given an array of integers, find the pair of adjacent elements that has the largest product and return that product. 8 | 9 | Example 10 | 11 | For inputArray = [3, 6, -2, -5, 7, 3], the output should be 12 | adjacentElementsProduct(inputArray) = 21. 13 | 14 | 7 and 3 produce the largest product. 15 | 16 | Input/Output 17 | 18 | [execution time limit] 4 seconds (py3) 19 | 20 | [input] array.integer inputArray 21 | 22 | An array of integers containing at least two elements. 23 | 24 | Guaranteed constraints: 25 | 2 ≤ inputArray.length ≤ 10, 26 | -1000 ≤ inputArray[i] ≤ 1000. 27 | 28 | [output] integer 29 | 30 | The largest product of adjacent elements 31 | """ 32 | 33 | def adjacentElementsProduct(arr): 34 | if len(list(arr))<2: 35 | return 0 36 | prod=[arr[i]*arr[i+1] for i in range(len(list(arr))-1)] 37 | return max(prod) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/all_the_longest_strings.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 9 17:24:15 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given an array of strings, return another array containing all of its longest strings. 8 | 9 | Example 10 | 11 | For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be 12 | allLongestStrings(inputArray) = ["aba", "vcd", "aba"]. 13 | 14 | Input/Output 15 | 16 | [execution time limit] 4 seconds (py3) 17 | 18 | [input] array.string inputArray 19 | 20 | A non-empty array. 21 | 22 | Guaranteed constraints: 23 | 1 ≤ inputArray.length ≤ 10, 24 | 1 ≤ inputArray[i].length ≤ 10. 25 | 26 | [output] array.string 27 | 28 | Array of the longest strings, stored in the same order as in the inputArray. 29 | """ 30 | 31 | def allLongestStrings(inputArray): 32 | #Find the longest string in the input array 33 | L=[len(string) for string in inputArray] 34 | L=max(L) 35 | 36 | #Make a new array consisting of the longest strings in the initial array 37 | new_L=[string for string in inputArray if len(string)==L] 38 | 39 | return(new_L) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/alphabeticShift.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 22:23:31 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given a string, your task is to replace each of its characters by the next 8 | one in the English alphabet; i.e. replace a with b, replace b with c, etc 9 | (z would be replaced by a). 10 | 11 | Example 12 | 13 | For inputString = "crazy", the output should be alphabeticShift(inputString) = "dsbaz". 14 | 15 | Input/Output 16 | 17 | [execution time limit] 4 seconds (py3) 18 | 19 | [input] string inputString 20 | 21 | A non-empty string consisting of lowercase English characters. 22 | 23 | Guaranteed constraints: 24 | 1 ≤ inputString.length ≤ 1000. 25 | 26 | [output] string 27 | 28 | The resulting string after replacing each of its characters. 29 | """ 30 | 31 | import string 32 | 33 | def alphabeticShift(inputString): 34 | alphabet=string.ascii_lowercase 35 | alphabet_shifted=alphabet[-1]+alphabet[:-1] 36 | 37 | alphabet_dict={} 38 | for (i,j) in zip(alphabet,alphabet_shifted): 39 | alphabet_dict[j]=i 40 | 41 | outputString=''.join([alphabet_dict[letter] for letter in inputString]) 42 | 43 | return outputString 44 | 45 | print(alphabeticShift('crazy')) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/alternating_sums.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 00:17:02 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Several people are standing in a row and need to be divided into two teams. The first person goes into team 1, the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and so on. 8 | 9 | You are given an array of positive integers - the weights of the people. Return an array of two integers, where the first element is the total weight of team 1, and the second element is the total weight of team 2 after the division is complete. 10 | 11 | Example 12 | 13 | For a = [50, 60, 60, 45, 70], the output should be 14 | alternatingSums(a) = [180, 105]. 15 | 16 | Input/Output 17 | 18 | [execution time limit] 4 seconds (py3) 19 | 20 | [input] array.integer a 21 | 22 | Guaranteed constraints: 23 | 1 ≤ a.length ≤ 105, 24 | 45 ≤ a[i] ≤ 100. 25 | 26 | [output] array.integer 27 | """ 28 | 29 | def alternatingSums(a): 30 | index=0 31 | team_weight_1,team_weight_2=0,0 32 | 33 | #Update team weights alternating teams 34 | for weight in a: 35 | if index%2==0: 36 | team_weight_1+=weight 37 | else: 38 | team_weight_2+=weight 39 | index+=1 40 | 41 | return([team_weight_1,team_weight_2]) 42 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/areEquallyStrong.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 01:03:45 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Call two arms equally strong if the heaviest weights they each are able to lift are equal. 8 | 9 | Call two people equally strong if their strongest arms are equally strong 10 | (the strongest arm can be both the right and the left), and so are their weakest arms. 11 | 12 | Given your and your friend's arms' lifting capabilities find out if you two are 13 | equally strong. 14 | 15 | Example 16 | 17 | For yourLeft = 10, yourRight = 15, friendsLeft = 15, and friendsRight = 10, 18 | the output should be 19 | areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = true; 20 | For yourLeft = 15, yourRight = 10, friendsLeft = 15, and friendsRight = 10, 21 | the output should be 22 | areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = true; 23 | For yourLeft = 15, yourRight = 10, friendsLeft = 15, and friendsRight = 9, 24 | the output should be 25 | areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = false. 26 | Input/Output 27 | 28 | [execution time limit] 4 seconds (py3) 29 | 30 | [input] integer yourLeft 31 | 32 | A non-negative integer representing the heaviest weight you can lift with your left arm. 33 | 34 | Guaranteed constraints: 35 | 0 ≤ yourLeft ≤ 20. 36 | 37 | [input] integer yourRight 38 | 39 | A non-negative integer representing the heaviest weight you can lift with your right arm. 40 | 41 | Guaranteed constraints: 42 | 0 ≤ yourRight ≤ 20. 43 | 44 | [input] integer friendsLeft 45 | 46 | A non-negative integer representing the heaviest weight your friend can lift 47 | with his or her left arm. 48 | 49 | Guaranteed constraints: 50 | 0 ≤ friendsLeft ≤ 20. 51 | 52 | [input] integer friendsRight 53 | 54 | A non-negative integer representing the heaviest weight your friend can lift 55 | with his or her right arm. 56 | 57 | Guaranteed constraints: 58 | 0 ≤ friendsRight ≤ 20. 59 | 60 | [output] boolean 61 | 62 | true if you and your friend are equally strong, false otherwise. 63 | """ 64 | 65 | def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight): 66 | 67 | if max(yourLeft,yourRight)==max(friendsLeft,friendsRight) and min(yourLeft,yourRight)==min(friendsLeft,friendsRight): 68 | return True 69 | else: 70 | return False -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/arrayMaxConsecutiveSum.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Feb 11 16:23:20 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given array of integers, find the maximal possible sum of some of its k 8 | consecutive elements. 9 | 10 | Example 11 | 12 | For inputArray = [2, 3, 5, 1, 6] and k = 2, the output should be 13 | arrayMaxConsecutiveSum(inputArray, k) = 8. 14 | All possible sums of 2 consecutive elements are: 15 | 16 | 2 + 3 = 5; 17 | 3 + 5 = 8; 18 | 5 + 1 = 6; 19 | 1 + 6 = 7. 20 | Thus, the answer is 8. 21 | Input/Output 22 | 23 | [execution time limit] 4 seconds (py3) 24 | 25 | [input] array.integer inputArray 26 | 27 | Array of positive integers. 28 | 29 | Guaranteed constraints: 30 | 3 ≤ inputArray.length ≤ 105, 31 | 1 ≤ inputArray[i] ≤ 1000. 32 | 33 | [input] integer k 34 | 35 | An integer (not greater than the length of inputArray). 36 | 37 | Guaranteed constraints: 38 | 1 ≤ k ≤ inputArray.length. 39 | 40 | [output] integer 41 | 42 | The maximal possible sum. 43 | """ 44 | 45 | def arrayMaxConsecutiveSum(inputArray, k): 46 | sums=[sum(inputArray[idx:idx+k]) for idx in range(len(inputArray))] 47 | return(max(sums)) 48 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/arrayMaxConsecutiveSum_2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Feb 11 16:27:34 2020 4 | 5 | @author: Logan Rowe 6 | Given array of integers, find the maximal possible sum of some of its k 7 | consecutive elements. 8 | 9 | Example 10 | 11 | For inputArray = [2, 3, 5, 1, 6] and k = 2, the output should be 12 | arrayMaxConsecutiveSum(inputArray, k) = 8. 13 | All possible sums of 2 consecutive elements are: 14 | 15 | 2 + 3 = 5; 16 | 3 + 5 = 8; 17 | 5 + 1 = 6; 18 | 1 + 6 = 7. 19 | Thus, the answer is 8. 20 | Input/Output 21 | 22 | [execution time limit] 4 seconds (py3) 23 | 24 | [input] array.integer inputArray 25 | 26 | Array of positive integers. 27 | 28 | Guaranteed constraints: 29 | 3 ≤ inputArray.length ≤ 105, 30 | 1 ≤ inputArray[i] ≤ 1000. 31 | 32 | [input] integer k 33 | 34 | An integer (not greater than the length of inputArray). 35 | 36 | Guaranteed constraints: 37 | 1 ≤ k ≤ inputArray.length. 38 | 39 | [output] integer 40 | 41 | The maximal possible sum. 42 | """ 43 | 44 | import numpy as np 45 | 46 | def arrayMaxConsecutiveSum(inputArray, k): 47 | max_sum=sum(inputArray[:k]) 48 | 49 | curr_sum=sum(inputArray[:k]) 50 | print(curr_sum) 51 | for first_value,new_value in zip(inputArray,inputArray[k:]): 52 | #instead of adding all three numbers every time, just update previous summation 53 | curr_sum+=new_value-first_value 54 | 55 | if curr_sum>max_sum: 56 | max_sum=curr_sum 57 | return(max_sum) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/arrayMaximalAdjacentDifference.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 01:12:01 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given an array of integers, find the maximal absolute difference between any 8 | two of its adjacent elements. 9 | 10 | Example 11 | 12 | For inputArray = [2, 4, 1, 0], the output should be 13 | arrayMaximalAdjacentDifference(inputArray) = 3. 14 | 15 | Input/Output 16 | 17 | [execution time limit] 4 seconds (py3) 18 | 19 | [input] array.integer inputArray 20 | 21 | Guaranteed constraints: 22 | 3 ≤ inputArray.length ≤ 10, 23 | -15 ≤ inputArray[i] ≤ 15. 24 | 25 | [output] integer 26 | 27 | The maximal absolute difference. 28 | """ 29 | 30 | import numpy as np 31 | 32 | def arrayMaximalAdjacentDifference(inputArray): 33 | inputArray=np.array(inputArray) 34 | diff=inputArray[1:]-inputArray[:-1] 35 | 36 | minimum=min(diff) 37 | maximum=max(diff) 38 | 39 | if -minimum>maximum: 40 | return(-minimum) 41 | else: 42 | return(maximum) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/arrayReplace.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 20:13:26 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given an array of integers, replace all the occurrences of elemToReplace with 8 | substitutionElem. 9 | 10 | Example 11 | 12 | For inputArray = [1, 2, 1], elemToReplace = 1, and substitutionElem = 3, 13 | the output should be 14 | arrayReplace(inputArray, elemToReplace, substitutionElem) = [3, 2, 3]. 15 | 16 | Input/Output 17 | 18 | [execution time limit] 4 seconds (py3) 19 | 20 | [input] array.integer inputArray 21 | 22 | Guaranteed constraints: 23 | 0 ≤ inputArray.length ≤ 104, 24 | 0 ≤ inputArray[i] ≤ 109. 25 | 26 | [input] integer elemToReplace 27 | 28 | Guaranteed constraints: 29 | 0 ≤ elemToReplace ≤ 109. 30 | 31 | [input] integer substitutionElem 32 | 33 | Guaranteed constraints: 34 | 0 ≤ substitutionElem ≤ 109. 35 | 36 | [output] array.integer 37 | """ 38 | 39 | import numpy as np 40 | def arrayReplace(inputArray, elemToReplace, substitutionElem): 41 | inputArray=np.array(inputArray) 42 | inputArray[inputArray==elemToReplace]=substitutionElem 43 | return(inputArray) 44 | 45 | if __name__=='__main__': 46 | inputArray=np.array([1,2,1]) 47 | elemToReplace=1 48 | substitutionElem=3 49 | print(arrayReplace(inputArray,elemToReplace,substitutionElem)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/array_change.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 00:51:01 2020 4 | 5 | @author: Logan Rowe 6 | 7 | You are given an array of integers. On each move you are allowed to increase 8 | exactly one of its element by one. Find the minimal number of moves required 9 | to obtain a strictly increasing sequence from the input. 10 | 11 | Example 12 | 13 | For inputArray = [1, 1, 1], the output should be 14 | arrayChange(inputArray) = 3. 15 | 16 | Input/Output 17 | 18 | [execution time limit] 4 seconds (py3) 19 | 20 | [input] array.integer inputArray 21 | 22 | Guaranteed constraints: 23 | 3 ≤ inputArray.length ≤ 105, 24 | -105 ≤ inputArray[i] ≤ 105. 25 | 26 | [output] integer 27 | 28 | The minimal number of moves needed to obtain a strictly increasing 29 | sequence from inputArray. 30 | It's guaranteed that for the given test cases the answer always fits signed 31 | 32-bit integer type. 32 | """ 33 | 34 | ''' 35 | Thoughts: 36 | 37 | lets pass once through the array storing theminimum previous value as prev 38 | and the increments to reach that value will be added to a counter 39 | 40 | ''' 41 | 42 | def arrayChange(inputArray): 43 | moves=0 44 | 45 | prev=inputArray[0] 46 | for value in inputArray[1:]: 47 | if value [7,2] 57 | bishop[0] and bishop[1] must change by the same ammount to be valid 58 | bishop[0] and bishop[1] must be in [1:8,1:8] 59 | ''' 60 | 61 | location_dict={ 62 | 'a':1, 63 | 'b':2, 64 | 'c':3, 65 | 'd':4, 66 | 'e':5, 67 | 'f':6, 68 | 'g':7, 69 | 'h':8 70 | } 71 | 72 | bishop=[location_dict[bishop[0]],int(bishop[1])] 73 | pawn=[location_dict[pawn[0]],int(pawn[1])] 74 | 75 | bishop_potential=[] 76 | for i in range(1,9): 77 | for j in range(1,9): 78 | if abs(i-bishop[0])==abs(j-bishop[1]): 79 | bishop_potential.append((i,j)) 80 | 81 | if (pawn[0],pawn[1]) in bishop_potential: 82 | return True 83 | else: 84 | return False 85 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/calculate_shape_area.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 9 16:18:05 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Below we will define an n-interesting polygon. Your task is to find the area of a polygon for a given n. 8 | 9 | A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the n - 1-interesting polygon and appending 1-interesting polygons to its rim, side by side. You can see the 1-, 2-, 3- and 4-interesting polygons in the picture below. 10 | 11 | 12 | 13 | Example 14 | 15 | For n = 2, the output should be 16 | shapeArea(n) = 5; 17 | For n = 3, the output should be 18 | shapeArea(n) = 13. 19 | Input/Output 20 | 21 | [execution time limit] 4 seconds (py3) 22 | 23 | [input] integer n 24 | 25 | Guaranteed constraints: 26 | 1 ≤ n < 104. 27 | 28 | [output] integer 29 | 30 | The area of the n-interesting polygon. 31 | """ 32 | 33 | def shapeArea(n): 34 | return(n**2+(n-1)**2) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/century_from_year.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 9 16:15:58 2020 4 | 5 | @author: Logan Rowe 6 | 7 | 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 - from the year 101 up to and including the year 200, etc. 8 | 9 | Example 10 | 11 | For year = 1905, the output should be 12 | centuryFromYear(year) = 20; 13 | For year = 1700, the output should be 14 | centuryFromYear(year) = 17. 15 | """ 16 | 17 | def centuryFromYear(year): 18 | year=str(year) 19 | L=len(year) 20 | if L==4: 21 | if year[-2:]=='00': 22 | cent=int(year[:2]) 23 | else: 24 | cent=int(year[:2])+1 25 | elif L==3: 26 | if year[-2:]=='00': 27 | cent=int(year[:1]) 28 | else: 29 | cent=int(year[:1])+1 30 | else: 31 | cent=1 32 | return cent 33 | 34 | 35 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/check_Palindrome.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 9 16:16:29 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given the string, check if it is a palindrome. 8 | 9 | Example 10 | 11 | For inputString = "aabaa", the output should be 12 | checkPalindrome(inputString) = true; 13 | For inputString = "abac", the output should be 14 | checkPalindrome(inputString) = false; 15 | For inputString = "a", the output should be 16 | checkPalindrome(inputString) = true. 17 | Input/Output 18 | 19 | [execution time limit] 4 seconds (py3) 20 | 21 | [input] string inputString 22 | 23 | A non-empty string consisting of lowercase characters. 24 | 25 | Guaranteed constraints: 26 | 1 ≤ inputString.length ≤ 105. 27 | 28 | [output] boolean 29 | 30 | true if inputString is a palindrome, false otherwise. 31 | """ 32 | 33 | def checkPalindrome(inputString): 34 | 35 | if len(inputString)==1: 36 | return True 37 | for i in range(int(len(inputString)/2)+1): 38 | if inputString[i]!=inputString[-1-i]: 39 | return False 40 | return True -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/chessBoardCellColor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 22:44:51 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given two cells on the standard chess board, determine whether they have the 8 | same color or not. 9 | 10 | Example 11 | 12 | For cell1 = "A1" and cell2 = "C3", the output should be 13 | chessBoardCellColor(cell1, cell2) = true. 14 | 15 | 16 | 17 | For cell1 = "A1" and cell2 = "H3", the output should be 18 | chessBoardCellColor(cell1, cell2) = false. 19 | 20 | 21 | 22 | Input/Output 23 | 24 | [execution time limit] 4 seconds (py3) 25 | 26 | [input] string cell1 27 | 28 | Guaranteed constraints: 29 | cell1.length = 2, 30 | 'A' ≤ cell1[0] ≤ 'H', 31 | 1 ≤ cell1[1] ≤ 8. 32 | 33 | [input] string cell2 34 | 35 | Guaranteed constraints: 36 | cell2.length = 2, 37 | 'A' ≤ cell2[0] ≤ 'H', 38 | 1 ≤ cell2[1] ≤ 8. 39 | 40 | [output] boolean 41 | 42 | true if both cells have the same color, false otherwise. 43 | """ 44 | 45 | def chessBoardCellColor(cell1, cell2): 46 | #let us use an odd or even method here 47 | 48 | #if letter and number are both odd or both even then dark 49 | #but if one is odd and the other even then light 50 | 51 | letter_to_number={ 52 | 'A':1, 53 | 'B':2, 54 | 'C':1, 55 | 'D':2, 56 | 'E':1, 57 | 'F':2, 58 | 'G':1, 59 | 'H':2 60 | } 61 | 62 | if letter_to_number[cell1[0]]%2==int(cell1[1])%2: 63 | cell1='dark' 64 | else: 65 | cell1='light' 66 | 67 | if letter_to_number[cell2[0]]%2==int(cell2[1])%2: 68 | cell2='dark' 69 | else: 70 | cell2='light' 71 | 72 | if cell1==cell2: 73 | return True 74 | else: 75 | return False -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/circleOfNumbers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 22:57:00 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Consider integer numbers from 0 to n - 1 written down along the circle in such 8 | a way that the distance between any two neighboring numbers is equal 9 | (note that 0 and n - 1 are neighboring, too). 10 | 11 | Given n and firstNumber, find the number which is written in the radially 12 | opposite position to firstNumber. 13 | 14 | Example 15 | 16 | For n = 10 and firstNumber = 2, the output should be 17 | circleOfNumbers(n, firstNumber) = 7. 18 | 19 | 20 | 21 | Input/Output 22 | 23 | [execution time limit] 4 seconds (py3) 24 | 25 | [input] integer n 26 | 27 | A positive even integer. 28 | 29 | Guaranteed constraints: 30 | 4 ≤ n ≤ 20. 31 | 32 | [input] integer firstNumber 33 | 34 | Guaranteed constraints: 35 | 0 ≤ firstNumber ≤ n - 1. 36 | 37 | [output] integer 38 | """ 39 | 40 | def circleOfNumbers(n, firstNumber): 41 | opposite=int(n/2)+firstNumber 42 | if opposite>=n: 43 | opposite-=(n) 44 | return(opposite) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/common_character_count.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 9 17:32:19 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given two strings, find the number of common characters between them. 8 | 9 | Example 10 | 11 | For s1 = "aabcc" and s2 = "adcaa", the output should be 12 | commonCharacterCount(s1, s2) = 3. 13 | 14 | Strings have 3 common characters - 2 "a"s and 1 "c". 15 | 16 | Input/Output 17 | 18 | [execution time limit] 4 seconds (py3) 19 | 20 | [input] string s1 21 | 22 | A string consisting of lowercase English letters. 23 | 24 | Guaranteed constraints: 25 | 1 ≤ s1.length < 15. 26 | 27 | [input] string s2 28 | 29 | A string consisting of lowercase English letters. 30 | 31 | Guaranteed constraints: 32 | 1 ≤ s2.length < 15. 33 | 34 | [output] integer 35 | """ 36 | 37 | def commonCharacterCount(s1, s2): 38 | ''' 39 | keep track of how many characters are in both s1 and s2 where s1 and s2 are both strings 40 | 41 | ex: 42 | s1='aabcc' 43 | s2='adcaa' 44 | 45 | commonCharacterCount(s1,s2) 46 | 3 47 | ''' 48 | 49 | #If either list has no length then return 0 50 | if len(s1)==0 or len(s2)==0: 51 | return 0 52 | 53 | common_character_counter=0 54 | 55 | #track of letters already accounted for 56 | letters=[] 57 | 58 | #For each letter that appears in s1 and s2 increase the common_character_count 59 | #by N where N is the smaller of how many times the letter appeared in s1 and s2 60 | for letter in s1: 61 | #increase count by the minimum number of times the letter occurs in either s1 or s2 62 | if (letter in s2) and (letter not in letters): 63 | common_character_counter+=min(s1.count(letter),s2.count(letter)) 64 | letters.append(letter) 65 | 66 | return(common_character_counter) 67 | 68 | 69 | if __name__=='__main__': 70 | s1='aabcc' 71 | s2='adcaa' 72 | print(commonCharacterCount(s1,s2)) 73 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/differentSymbolsNaive.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Feb 11 16:22:22 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given a string, find the number of different characters in it. 8 | 9 | Example 10 | 11 | For s = "cabca", the output should be 12 | differentSymbolsNaive(s) = 3. 13 | 14 | There are 3 different characters a, b and c. 15 | 16 | Input/Output 17 | 18 | [execution time limit] 4 seconds (py3) 19 | 20 | [input] string s 21 | 22 | A string of lowercase English letters. 23 | 24 | Guaranteed constraints: 25 | 3 ≤ s.length ≤ 1000. 26 | 27 | [output] integer 28 | """ 29 | 30 | def differentSymbolsNaive(s): 31 | return(len(set(s))) 32 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/evenDigitsOnly.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 22:09:37 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Check if all digits of the given integer are even. 8 | 9 | Example 10 | 11 | For n = 248622, the output should be 12 | evenDigitsOnly(n) = true; 13 | For n = 642386, the output should be 14 | evenDigitsOnly(n) = false. 15 | Input/Output 16 | 17 | [execution time limit] 4 seconds (py3) 18 | 19 | [input] integer n 20 | 21 | Guaranteed constraints: 22 | 1 ≤ n ≤ 109. 23 | 24 | [output] boolean 25 | 26 | true if all digits of n are even, false otherwise. 27 | [Python3] Syntax Tips 28 | """ 29 | 30 | def evenDigitsOnly(n): 31 | n=str(n) 32 | for integer in n: 33 | if integer%2!=0: 34 | return False 35 | return Truedef evenDigitsOnly(n): 36 | n=str(n) 37 | for integer in n: 38 | if int(integer)%2!=0: 39 | return False 40 | return True -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/exploring_the_waters.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 00:17:02 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Several people are standing in a row and need to be divided into two teams. The first person goes into team 1, the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and so on. 8 | 9 | You are given an array of positive integers - the weights of the people. Return an array of two integers, where the first element is the total weight of team 1, and the second element is the total weight of team 2 after the division is complete. 10 | 11 | Example 12 | 13 | For a = [50, 60, 60, 45, 70], the output should be 14 | alternatingSums(a) = [180, 105]. 15 | 16 | Input/Output 17 | 18 | [execution time limit] 4 seconds (py3) 19 | 20 | [input] array.integer a 21 | 22 | Guaranteed constraints: 23 | 1 ≤ a.length ≤ 105, 24 | 45 ≤ a[i] ≤ 100. 25 | 26 | [output] array.integer 27 | """ 28 | 29 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/extractEachKth.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Feb 11 16:07:30 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given array of integers, remove each kth element from it. 8 | 9 | Example 10 | 11 | For inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and k = 3, the output should be 12 | extractEachKth(inputArray, k) = [1, 2, 4, 5, 7, 8, 10]. 13 | 14 | Input/Output 15 | 16 | [execution time limit] 4 seconds (py3) 17 | 18 | [input] array.integer inputArray 19 | 20 | Guaranteed constraints: 21 | 5 ≤ inputArray.length ≤ 15, 22 | -20 ≤ inputArray[i] ≤ 20. 23 | 24 | [input] integer k 25 | 26 | Guaranteed constraints: 27 | 1 ≤ k ≤ 10. 28 | 29 | [output] array.integer 30 | 31 | inputArray without elements k - 1, 2k - 1, 3k - 1 etc. 32 | """ 33 | import numpy as np 34 | 35 | def extractEachKth(inputArray, k): 36 | mask=[idx%k!=0 for idx in range(1,len(inputArray)+1)] 37 | 38 | inputArray=np.array(inputArray) 39 | outputArray=inputArray[mask] 40 | 41 | return outputArray -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/firstDigit.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Feb 11 16:19:30 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Find the leftmost digit that occurs in a given string. 8 | 9 | Example 10 | 11 | For inputString = "var_1__Int", the output should be 12 | firstDigit(inputString) = '1'; 13 | For inputString = "q2q-q", the output should be 14 | firstDigit(inputString) = '2'; 15 | For inputString = "0ss", the output should be 16 | firstDigit(inputString) = '0'. 17 | Input/Output 18 | 19 | [execution time limit] 4 seconds (py3) 20 | 21 | [input] string inputString 22 | 23 | A string containing at least one digit. 24 | 25 | Guaranteed constraints: 26 | 3 ≤ inputString.length ≤ 10. 27 | 28 | [output] char 29 | """ 30 | 31 | import string 32 | 33 | def firstDigit(inputString): 34 | digits=string.digits 35 | for character in inputString: 36 | if character in digits: 37 | return character -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/growingPlant.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Feb 11 16:58:38 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Caring for a plant can be hard work, but since you tend to it regularly, 8 | you have a plant that grows consistently. Each day, its height increases 9 | by a fixed amount represented by the integer upSpeed. But due to lack of sunlight, 10 | the plant decreases in height every night, by an amount represented by downSpeed. 11 | 12 | Since you grew the plant from a seed, it started at height 0 initially. 13 | Given an integer desiredHeight, your task is to find how many days it'll 14 | take for the plant to reach this height. 15 | 16 | Example 17 | 18 | For upSpeed = 100, downSpeed = 10, and desiredHeight = 910, the output should be 19 | growingPlant(upSpeed, downSpeed, desiredHeight) = 10. 20 | 21 | # Day Night 22 | 1 100 90 23 | 2 190 180 24 | 3 280 270 25 | 4 370 360 26 | 5 460 450 27 | 6 550 540 28 | 7 640 630 29 | 8 730 720 30 | 9 820 810 31 | 10 910 900 32 | The plant first reaches a height of 910 on day 10. 33 | 34 | Input/Output 35 | 36 | [execution time limit] 4 seconds (py3) 37 | 38 | [input] integer upSpeed 39 | 40 | A positive integer representing the daily growth of the plant. 41 | 42 | Guaranteed constraints: 43 | 3 ≤ upSpeed ≤ 100. 44 | 45 | [input] integer downSpeed 46 | 47 | A positive integer representing the nightly decline of the plant. 48 | 49 | Guaranteed constraints: 50 | 2 ≤ downSpeed < upSpeed. 51 | 52 | [input] integer desiredHeight 53 | 54 | A positive integer representing the goal height. 55 | 56 | Guaranteed constraints: 57 | 4 ≤ desiredHeight ≤ 1000. 58 | 59 | [output] integer 60 | 61 | The number of days that it will take for the plant to reach / pass desiredHeight. 62 | """ 63 | 64 | def growingPlant(upSpeed, downSpeed, desiredHeight): 65 | day=0 66 | height=0 67 | while True: 68 | day+=1 69 | height+=upSpeed 70 | if height>=desiredHeight: 71 | return day 72 | height-=downSpeed -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/isDigit.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 14:21:16 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Determine if the given character is a digit or not. 8 | 9 | Example 10 | 11 | For symbol = '0', the output should be 12 | isDigit(symbol) = true; 13 | For symbol = '-', the output should be 14 | isDigit(symbol) = false. 15 | Input/Output 16 | 17 | [execution time limit] 4 seconds (py3) 18 | 19 | [input] char symbol 20 | 21 | A character which is either a digit or not. 22 | 23 | [output] boolean 24 | 25 | true if symbol is a digit, false otherwise. 26 | [Python3] Syntax Tips 27 | """ 28 | 29 | import string 30 | 31 | def isDigit(symbol): 32 | if symbol in string.digits: 33 | return True 34 | return False -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/isLucky.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 9 22:46:03 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Ticket numbers usually consist of an even number of digits. A ticket number is 8 | considered lucky if the sum of the first half of the digits is equal to the sum 9 | of the second half. 10 | 11 | Given a ticket number n, determine if it's lucky or not. 12 | 13 | Example 14 | 15 | For n = 1230, the output should be 16 | isLucky(n) = true; 17 | For n = 239017, the output should be 18 | isLucky(n) = false. 19 | Input/Output 20 | 21 | [execution time limit] 4 seconds (py3) 22 | 23 | [input] integer n 24 | 25 | A ticket number represented as a positive integer with an even number of digits. 26 | 27 | Guaranteed constraints: 28 | 10 ≤ n < 106. 29 | 30 | [output] boolean 31 | 32 | true if n is a lucky ticket number, false otherwise. 33 | """ 34 | 35 | def isLucky(n): 36 | n=str(n) 37 | 38 | #split n into first and second half and make a list containing each number 39 | first_half=[int(i) for i in n[:int(len(n)/2)]] 40 | second_half=[int(i) for i in n[int(len(n)/2):]] 41 | 42 | #Check if the sum of the first_half numbers equals the sum of the second_half numbers 43 | if sum(first_half)==sum(second_half): 44 | return True 45 | else: 46 | return False 47 | 48 | if __name__=='__main__': 49 | n=1230 50 | isLucky(n) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/knapsackLight.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Feb 11 17:05:17 2020 4 | 5 | @author: Logan Rowe 6 | 7 | You found two items in a treasure chest! The first item weighs weight1 and is 8 | worth value1, and the second item weighs weight2 and is worth value2. What is 9 | the total maximum value of the items you can take with you, assuming that your 10 | max weight capacity is maxW and you can't come back for the items later? 11 | 12 | Note that there are only two items and you can't bring more than one item of 13 | each type, i.e. you can't take two first items or two second items. 14 | 15 | Example 16 | 17 | For value1 = 10, weight1 = 5, value2 = 6, weight2 = 4, and maxW = 8, the output 18 | should be 19 | knapsackLight(value1, weight1, value2, weight2, maxW) = 10. 20 | 21 | You can only carry the first item. 22 | 23 | For value1 = 10, weight1 = 5, value2 = 6, weight2 = 4, and maxW = 9, the output 24 | should be 25 | knapsackLight(value1, weight1, value2, weight2, maxW) = 16. 26 | 27 | You're strong enough to take both of the items with you. 28 | 29 | For value1 = 5, weight1 = 3, value2 = 7, weight2 = 4, and maxW = 6, the output 30 | should be 31 | knapsackLight(value1, weight1, value2, weight2, maxW) = 7. 32 | 33 | You can't take both items, but you can take any of them. 34 | 35 | Input/Output 36 | 37 | [execution time limit] 4 seconds (py3) 38 | 39 | [input] integer value1 40 | 41 | Guaranteed constraints: 42 | 2 ≤ value1 ≤ 20. 43 | 44 | [input] integer weight1 45 | 46 | Guaranteed constraints: 47 | 2 ≤ weight1 ≤ 10. 48 | 49 | [input] integer value2 50 | 51 | Guaranteed constraints: 52 | 2 ≤ value2 ≤ 20. 53 | 54 | [input] integer weight2 55 | 56 | Guaranteed constraints: 57 | 2 ≤ weight2 ≤ 10. 58 | 59 | [input] integer maxW 60 | 61 | Guaranteed constraints: 62 | 1 ≤ maxW ≤ 20. 63 | 64 | [output] integer 65 | """ 66 | 67 | def knapsackLight(value1, weight1, value2, weight2, maxW): 68 | if maxW>=weight1+weight2: 69 | #Bring Both! 70 | return(value1+value2) 71 | elif maxW=weight1 and value1>=value2: 75 | return(value1) 76 | elif maxW>=weight2: 77 | return(value2) 78 | elif value2>=value1 and weight2>maxW and weight1<=maxW: 79 | return(value1) 80 | elif value1>=value2 and weight1>maxW and weight2<=maxW: 81 | return(value2) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/longestDigitsPrefix.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Feb 11 17:19:34 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given a string, output its longest prefix which contains only digits. 8 | 9 | Example 10 | 11 | For inputString = "123aa1", the output should be 12 | longestDigitsPrefix(inputString) = "123". 13 | 14 | Input/Output 15 | 16 | [execution time limit] 4 seconds (py3) 17 | 18 | [input] string inputString 19 | 20 | Guaranteed constraints: 21 | 3 ≤ inputString.length ≤ 100. 22 | 23 | [output] string 24 | 25 | [Python3] Syntax Tips 26 | """ 27 | import string 28 | 29 | def longestDigitsPrefix(inputString): 30 | idx=0 31 | digits=string.digits 32 | for character in inputString: 33 | if character in digits: 34 | idx+=1 35 | else: 36 | break 37 | 38 | return(inputString[:idx]) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/longestWord.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 15:12:12 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Define a word as a sequence of consecutive English letters. 8 | Find the longest word from the given string. 9 | 10 | Example 11 | 12 | For text = "Ready, steady, go!", the output should be 13 | longestWord(text) = "steady". 14 | 15 | Input/Output 16 | 17 | [execution time limit] 4 seconds (py3) 18 | 19 | [input] string text 20 | 21 | Guaranteed constraints: 22 | 4 ≤ text.length ≤ 50. 23 | 24 | [output] string 25 | 26 | The longest word from text. It's guaranteed that there is a unique output. 27 | """ 28 | 29 | import string 30 | 31 | def longestWord(text): 32 | letters=string.ascii_letters 33 | 34 | words='' 35 | for letter in text: 36 | if letter in letters: 37 | words+=letter 38 | else: 39 | words+=',' 40 | 41 | longest_word=max(words.split(','),key=len) 42 | return(longest_word) 43 | 44 | 45 | 46 | if __name__=='__main__': 47 | s="You are the best!!!!!!!!!!!! CodeFighter ever!" 48 | print(longestWord(s)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/make_array_consecutive.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 9 16:18:48 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Ratiorg got statues of different sizes as a present from CodeMaster for his 8 | birthday, each statue having an non-negative integer size. Since he likes to 9 | make things perfect, he wants to arrange them from smallest to largest so that 10 | each statue will be bigger than the previous one exactly by 1. He may need some 11 | additional statues to be able to accomplish that. Help him figure out the 12 | minimum number of additional statues needed. 13 | 14 | Example 15 | 16 | For statues = [6, 2, 3, 8], the output should be 17 | makeArrayConsecutive2(statues) = 3. 18 | 19 | Ratiorg needs statues of sizes 4, 5 and 7. 20 | 21 | Input/Output 22 | 23 | [execution time limit] 4 seconds (py3) 24 | 25 | [input] array.integer statues 26 | 27 | An array of distinct non-negative integers. 28 | 29 | Guaranteed constraints: 30 | 1 ≤ statues.length ≤ 10, 31 | 0 ≤ statues[i] ≤ 20. 32 | 33 | [output] integer 34 | 35 | The minimal number of statues that need to be added to existing statues such 36 | that it contains every integer size from an interval [L, R] (for some L, R) 37 | and no other sizes. 38 | """ 39 | 40 | def makeArrayConsecutive2(statues): 41 | statues=sorted(statues) 42 | count=0 43 | for i in range(min(statues),max(statues)): 44 | if i not in statues: 45 | count+=1 46 | return count -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/partial_matrix_elements_sum.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 9 17:10:14 2020 4 | 5 | @author: Logan Rowe 6 | 7 | After becoming famous, the CodeBots decided to move into a new building 8 | together. Each of the rooms has a different cost, and some of them are free, 9 | but there's a rumour that all the free rooms are haunted! Since the CodeBots 10 | are quite superstitious, they refuse to stay in any of the free rooms, or any 11 | of the rooms below any of the free rooms. 12 | 13 | Given matrix, a rectangular matrix of integers, where each value represents 14 | the cost of the room, your task is to return the total sum of all rooms that 15 | are suitable for the CodeBots (ie: add up all the values that don't appear 16 | below a 0). 17 | 18 | Example 19 | 20 | For 21 | 22 | matrix = [[0, 1, 1, 2], 23 | [0, 5, 0, 0], 24 | [2, 0, 3, 3]] 25 | the output should be 26 | matrixElementsSum(matrix) = 9. 27 | 28 | example 1 29 | 30 | There are several haunted rooms, so we'll disregard them as well as any rooms 31 | beneath them. Thus, the answer is 1 + 5 + 1 + 2 = 9. 32 | 33 | For 34 | 35 | matrix = [[1, 1, 1, 0], 36 | [0, 5, 0, 1], 37 | [2, 1, 3, 10]] 38 | the output should be 39 | matrixElementsSum(matrix) = 9. 40 | 41 | example 2 42 | 43 | Note that the free room in the final column makes the full column unsuitable 44 | for bots (not just the room directly beneath it). Thus, the answer 45 | is 1 + 1 + 1 + 5 + 1 = 9. 46 | 47 | Input/Output 48 | 49 | [execution time limit] 4 seconds (py3) 50 | 51 | [input] array.array.integer matrix 52 | 53 | A 2-dimensional array of integers representing the cost of each room in the 54 | building. A value of 0 indicates that the room is haunted. 55 | 56 | Guaranteed constraints: 57 | 1 ≤ matrix.length ≤ 5, 58 | 1 ≤ matrix[i].length ≤ 5, 59 | 0 ≤ matrix[i][j] ≤ 10. 60 | 61 | [output] integer 62 | 63 | The total price of all the rooms that are suitable for the CodeBots to live in. 64 | """ 65 | 66 | def matrixElementsSum(matrix): 67 | #track the sum of the cost of the non-haunted rooms 68 | net_cost=0 69 | 70 | #track haunted columns for which rooms below will not be considered 71 | haunted_columns=[] 72 | for row in matrix: 73 | column=0 74 | for room_cost in row: 75 | if room_cost==0: 76 | haunted_columns.append(column) 77 | elif column not in haunted_columns: 78 | net_cost+=room_cost 79 | column+=1 80 | 81 | return net_cost 82 | 83 | 84 | 85 | if __name__=='__main__': 86 | matrix =np.array([[1, 1, 1, 0], 87 | [0, 5, 0, 1], 88 | [2, 1, 3, 10]]) 89 | print(matrix) 90 | print(matrixElementsSum(matrix)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/sort_by_height.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 9 22:56:07 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall! 8 | 9 | Example 10 | 11 | For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be 12 | sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190]. 13 | 14 | Input/Output 15 | 16 | [execution time limit] 4 seconds (py3) 17 | 18 | [input] array.integer a 19 | 20 | If a[i] = -1, then the ith position is occupied by a tree. Otherwise a[i] is the height of a person standing in the ith position. 21 | 22 | Guaranteed constraints: 23 | 1 ≤ a.length ≤ 1000, 24 | -1 ≤ a[i] ≤ 1000. 25 | 26 | [output] array.integer 27 | 28 | Sorted array a with all the trees untouched. 29 | """ 30 | 31 | def sortByHeight(a): 32 | #First let us figure out the best order for the people to stand in using a list 33 | b=[i for i in a if i!=-1] 34 | 35 | #let us sort b in reverse so we can use pop method when filling a 36 | b=sorted(b,reverse=True) 37 | 38 | #now lets us replace all people heights in a skipping over trees 39 | idx=0 40 | for i in a: 41 | if a[idx]==-1: 42 | idx+=1 43 | else: 44 | a[idx]=b.pop() 45 | idx+=1 46 | 47 | return(a) 48 | 49 | if __name__=='__main__': 50 | a = [-1, 150, 190, 170, -1, -1, 160, 180] 51 | print(sortByHeight(a)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/validTime.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 15:17:23 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Check if the given string is a correct time representation of the 24-hour clock. 8 | 9 | Example 10 | 11 | For time = "13:58", the output should be 12 | validTime(time) = true; 13 | For time = "25:51", the output should be 14 | validTime(time) = false; 15 | For time = "02:76", the output should be 16 | validTime(time) = false. 17 | Input/Output 18 | 19 | [execution time limit] 4 seconds (py3) 20 | 21 | [input] string time 22 | 23 | A string representing time in HH:MM format. It is guaranteed that the first 24 | two characters, as well as the last two characters, are digits. 25 | 26 | [output] boolean 27 | 28 | true if the given representation is correct, false otherwise. 29 | """ 30 | 31 | def validTime(time): 32 | hour,minute=time.split(':') 33 | hour,minute=int(hour),int(minute) 34 | 35 | if 0<=hour and hour<=23 and 0<=minute and minute<=59: 36 | return True 37 | return False 38 | 39 | 40 | 41 | 42 | 43 | 44 | if __name__=='__main__': 45 | times=['13:58','25:51'] 46 | for time in times: 47 | print(validTime(time)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/easy/variableName.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 22:12:30 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Correct variable names consist only of English letters, 8 | digits and underscores and they can't start with a digit. 9 | 10 | Check if the given string is a correct variable name. 11 | 12 | Example 13 | 14 | For name = "var_1__Int", the output should be 15 | variableName(name) = true; 16 | For name = "qq-q", the output should be 17 | variableName(name) = false; 18 | For name = "2w2", the output should be 19 | variableName(name) = false. 20 | Input/Output 21 | 22 | [execution time limit] 4 seconds (py3) 23 | 24 | [input] string name 25 | 26 | Guaranteed constraints: 27 | 1 ≤ name.length ≤ 10. 28 | 29 | [output] boolean 30 | 31 | true if name is a correct variable name, false otherwise. 32 | """ 33 | 34 | def variableName(name): 35 | #Check if the first character is an integer 36 | if name[0].isdigit(): 37 | return False 38 | 39 | for letter in name: 40 | if letter.isalpha() or letter.isnumeric() or letter=='_': 41 | continue 42 | else: 43 | return False 44 | 45 | return True 46 | 47 | 48 | 49 | 50 | if __name__=='__main__': 51 | names=["var_1__Int","qq-q","2w2"] 52 | results=[True,False,False] 53 | for (name,result) in zip(names,results): 54 | if variableName(name)==result: 55 | print('passed test') 56 | else: 57 | print(name) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/absoluteValuesSumMinimization.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 23:11:04 2020 4 | 5 | @author: Logan Rowe 6 | Given a sorted array of integers a, your task is to determine which element of 7 | a is closest to all other values of a. In other words, find the element x in a, 8 | which minimizes the following sum: 9 | 10 | abs(a[0] - x) + abs(a[1] - x) + ... + abs(a[a.length - 1] - x) 11 | (where abs denotes the absolute value) 12 | 13 | If there are several possible answers, output the smallest one. 14 | 15 | Example 16 | 17 | For a = [2, 4, 7], the output should be absoluteValuesSumMinimization(a) = 4. 18 | 19 | for x = 2, the value will be abs(2 - 2) + abs(4 - 2) + abs(7 - 2) = 7. 20 | for x = 4, the value will be abs(2 - 4) + abs(4 - 4) + abs(7 - 4) = 5. 21 | for x = 7, the value will be abs(2 - 7) + abs(4 - 7) + abs(7 - 7) = 8. 22 | The lowest possible value is when x = 4, so the answer is 4. 23 | 24 | For a = [2, 3], the output should be absoluteValuesSumMinimization(a) = 2. 25 | 26 | for x = 2, the value will be abs(2 - 2) + abs(3 - 2) = 1. 27 | for x = 3, the value will be abs(2 - 3) + abs(3 - 3) = 1. 28 | Because there is a tie, the smallest x between x = 2 and x = 3 is the answer. 29 | 30 | Input/Output 31 | 32 | [execution time limit] 4 seconds (py3) 33 | 34 | [input] array.integer a 35 | 36 | A non-empty array of integers, sorted in ascending order. 37 | 38 | Guaranteed constraints: 39 | 1 ≤ a.length ≤ 1000, 40 | -106 ≤ a[i] ≤ 106. 41 | 42 | [output] integer 43 | 44 | An integer representing the element from a that minimizes the sum of its 45 | absolute differences with all other elements. 46 | """ 47 | 48 | import numpy as np 49 | 50 | def fcn(a,idx): 51 | ''' 52 | evalutate function at a[idx] 53 | ''' 54 | f=0 55 | x=a[idx] 56 | for element in a: 57 | f+=abs(element-x) 58 | return(f) 59 | 60 | def absoluteValuesSumMinimization(a): 61 | #all functions evaluated at a[idx] 62 | sums=[fcn(a,idx) for idx in range(len(a))] 63 | 64 | #convert to an array because a will likely be given as a list 65 | a=np.array(a) 66 | 67 | #return the smallest value in array a that minimizes the function 68 | return(np.min(a[np.where(sums==np.min(sums))])) 69 | 70 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/are_similar.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 00:36:15 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Two arrays are called similar if one can be obtained from another by swapping 8 | at most one pair of elements in one of the arrays. 9 | 10 | Given two arrays a and b, check whether they are similar. 11 | 12 | Example 13 | 14 | For a = [1, 2, 3] and b = [1, 2, 3], the output should be 15 | areSimilar(a, b) = true. 16 | 17 | The arrays are equal, no need to swap any elements. 18 | 19 | For a = [1, 2, 3] and b = [2, 1, 3], the output should be 20 | areSimilar(a, b) = true. 21 | 22 | We can obtain b from a by swapping 2 and 1 in b. 23 | 24 | For a = [1, 2, 2] and b = [2, 1, 1], the output should be 25 | areSimilar(a, b) = false. 26 | 27 | Any swap of any two elements either in a or in b won't make a and b equal. 28 | 29 | Input/Output 30 | 31 | [execution time limit] 4 seconds (py3) 32 | 33 | [input] array.integer a 34 | 35 | Array of integers. 36 | 37 | Guaranteed constraints: 38 | 3 ≤ a.length ≤ 105, 39 | 1 ≤ a[i] ≤ 1000. 40 | 41 | [input] array.integer b 42 | 43 | Array of integers of the same length as a. 44 | 45 | Guaranteed constraints: 46 | b.length = a.length, 47 | 1 ≤ b[i] ≤ 1000. 48 | 49 | [output] boolean 50 | 51 | true if a and b are similar, false otherwise. 52 | """ 53 | 54 | ''' 55 | Thoughts: 56 | 57 | If a and b are similar then at most 2 indexed components will be unequal 58 | 59 | 1) check to see if this is met if all equal return True 60 | 61 | 2) if only 1 does not match return False (no switching across arrays) 62 | 63 | 3) if exactly 2 do not match, check to see if they are the same two in 64 | both a and b, if so then return True, else return false 65 | 66 | ''' 67 | 68 | def areSimilar(a,b): 69 | mismatch=0 70 | mis_a=[] 71 | mis_b=[] 72 | for (i,j) in zip(a,b): 73 | if i!=j: 74 | mismatch+=1 75 | mis_a.append(i) 76 | mis_b.append(j) 77 | 78 | if mismatch==0: 79 | return True 80 | 81 | if mismatch==1 or mismatch>2: 82 | return False 83 | 84 | 85 | if mismatch==2: 86 | #check to see if the same two mismatched elements exist in a and b 87 | if mis_a[0]==mis_b[1] and mis_b[0]==mis_a[1]: 88 | return True 89 | else: 90 | return False 91 | 92 | if __name__=='__main__': 93 | a=[2,3,1] 94 | b=[1,3,2] 95 | print(areSimilar(a,b)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/buildPalendrome.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 13:31:39 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given a string, find the shortest possible string which can be achieved by 8 | adding characters to the end of initial string to make it a palindrome. 9 | 10 | Example 11 | 12 | For st = "abcdc", the output should be 13 | buildPalindrome(st) = "abcdcba". 14 | 15 | Input/Output 16 | 17 | [execution time limit] 4 seconds (py3) 18 | 19 | [input] string st 20 | 21 | A string consisting of lowercase English letters. 22 | 23 | Guaranteed constraints: 24 | 3 ≤ st.length ≤ 10. 25 | 26 | [output] string 27 | """ 28 | 29 | ''' 30 | Thoughts: 31 | 32 | First I want to find the longest existing internal palendrome that ends at string[-1] 33 | i.e. for 'abcdc' --> 'cdc' 34 | 35 | Second I want to append the reverse of the non-palendrome portion of the string 36 | i.d. 'abcdc' --> 'abcdc'+'ba' 37 | 38 | ''' 39 | 40 | def isPalendrome(s): 41 | rev_s=s[::-1] 42 | half_length=int(len(s)/2) 43 | 44 | for (letter_forward,letter_backward) in zip(s[:half_length],rev_s[:half_length]): 45 | if letter_forward!=letter_backward: 46 | #mismatching letter found, s is not a palindrome 47 | return False 48 | 49 | #if it is a palendrome then 50 | return True 51 | 52 | def buildPalendrome(s): 53 | #Check to see if s is already a palendrome 54 | if isPalendrome(s): 55 | return s 56 | 57 | #initially assume only the last letter in s is palendromic 58 | longest_palendrome=s[-1] 59 | 60 | #check to see if a longer palendrome exists within s, ending at s[-1] 61 | idx=1 62 | while idx0 and position[1]<=8 and position[1]>0]) 65 | return(valid_end_cells) 66 | 67 | if __name__=='__main__': 68 | print(chessKnight('a2')) 69 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/deepestProfit.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 23:02:43 2020 4 | 5 | @author: Logan Rowe 6 | 7 | You have deposited a specific amount of money into your bank account. 8 | Each year your balance increases at the same growth rate. With the assumption 9 | that you don't make any additional deposits, find out how long it would take 10 | for your balance to pass a specific threshold. 11 | 12 | Example 13 | 14 | For deposit = 100, rate = 20, and threshold = 170, the output should be 15 | depositProfit(deposit, rate, threshold) = 3. 16 | 17 | Each year the amount of money in your account increases by 20%. So throughout 18 | the years, your balance would be: 19 | 20 | year 0: 100; 21 | year 1: 120; 22 | year 2: 144; 23 | year 3: 172.8. 24 | 25 | Thus, it will take 3 years for your balance to pass the threshold, so the 26 | answer is 3. 27 | 28 | Input/Output 29 | 30 | [execution time limit] 4 seconds (py3) 31 | 32 | [input] integer deposit 33 | 34 | The initial deposit, guaranteed to be a positive integer. 35 | 36 | Guaranteed constraints: 37 | 1 ≤ deposit ≤ 100. 38 | 39 | [input] integer rate 40 | 41 | The rate of increase. Each year the balance increases by the rate percent of 42 | the current sum. 43 | 44 | Guaranteed constraints: 45 | 1 ≤ rate ≤ 100. 46 | 47 | [input] integer threshold 48 | 49 | The target balance. 50 | 51 | Guaranteed constraints: 52 | deposit < threshold ≤ 200. 53 | 54 | [output] integer 55 | 56 | The number of years it would take to hit the threshold. 57 | """ 58 | 59 | def depositProfit(deposit, rate, threshold): 60 | year=0 61 | total=deposit 62 | while total 1 + 0 = 1. 23 | Input/Output 24 | 25 | [execution time limit] 4 seconds (py3) 26 | 27 | [input] integer n 28 | 29 | Guaranteed constraints: 30 | 5 ≤ n ≤ 109. 31 | 32 | [output] integer 33 | """ 34 | 35 | def digitDegree(n): 36 | if len(str(n))==1: 37 | return(0) 38 | 39 | cycle=0 40 | while len(str(n))>1: 41 | n=sum([int(digit) for digit in str(n)]) 42 | cycle+=1 43 | 44 | return(cycle) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/digitsProduct.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 16:18:50 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given an integer product, find the smallest positive (i.e. greater than 0) 8 | integer the product of whose digits is equal to product. If there is no such 9 | integer, return -1 instead. 10 | 11 | Example 12 | 13 | For product = 12, the output should be 14 | digitsProduct(product) = 26; 15 | For product = 19, the output should be 16 | digitsProduct(product) = -1. 17 | Input/Output 18 | 19 | [execution time limit] 4 seconds (py3) 20 | 21 | [input] integer product 22 | 23 | Guaranteed constraints: 24 | 0 ≤ product ≤ 600. 25 | 26 | [output] integer 27 | """ 28 | 29 | ''' 30 | Thoughts: 31 | 32 | Let us start with a brute force approach and look for simplifications along the way 33 | 34 | 1) find all combinations numbers that multiply to equal the given product 35 | 2) concatenate the values in each combination 36 | 3) return the smallest int(combination)) 37 | 38 | 39 | This question has a 70% disapproval rating. Likely because of the way it is worded. 40 | 41 | digitsProduct_codesignal will try to meet codesignals interpretation of the question 42 | 43 | in my test example below: code signal says 243 should go to 399 instead of 279 44 | furthermore that 450 should go to 2559 instead of 509 45 | 46 | these are in direct violation of their example 12 --> 26 which should be 223 according 47 | to codesignal 48 | 49 | ''' 50 | 51 | def findProducts(product): 52 | combinations=[] 53 | for i in range(2,int(product/2)+1): 54 | if product/i==int(product/i): 55 | combinations.append((i,int(product/i))) 56 | 57 | return combinations 58 | 59 | def digitsProduct(product): 60 | 61 | #this is an edge case that would be overlooked by findProducts above 62 | if product is 0: 63 | return 10 64 | 65 | combinations=findProducts(product) 66 | 67 | #if the number is prime return -1 68 | if len(combinations)==0: 69 | return -1 70 | 71 | #otherwise concatenate the numbers that multiply to product and convert to integers 72 | combinations=[int(''.join([str(num[0]),str(num[1])])) for num in combinations] 73 | 74 | 75 | return(min(combinations)) 76 | 77 | 78 | if __name__=='__main__': 79 | numbers=[12,19,243,450] 80 | for number in numbers: 81 | print(str(number),':',digitsProduct(number)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/digitsProduct_codesignal.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 16:18:50 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given an integer product, find the smallest positive (i.e. greater than 0) 8 | integer the product of whose digits is equal to product. If there is no such 9 | integer, return -1 instead. 10 | 11 | Example 12 | 13 | For product = 12, the output should be 14 | digitsProduct(product) = 26; 15 | For product = 19, the output should be 16 | digitsProduct(product) = -1. 17 | Input/Output 18 | 19 | [execution time limit] 4 seconds (py3) 20 | 21 | [input] integer product 22 | 23 | Guaranteed constraints: 24 | 0 ≤ product ≤ 600. 25 | 26 | [output] integer 27 | """ 28 | 29 | ''' 30 | Thoughts: 31 | 32 | Let us start with a brute force approach and look for simplifications along the way 33 | 34 | 1) find all combinations numbers that multiply to equal the given product 35 | 2) concatenate the values in each combination 36 | 3) return the smallest int(combination)) 37 | 38 | 39 | This question has a 70% disapproval rating. Likely because of the way it is worded. 40 | 41 | digitsProduct_codesignal will try to meet codesignals interpretation of the question 42 | 43 | in my test example below: code signal says 243 should go to 399 instead of 279 44 | furthermore that 450 should go to 2559 instead of 509 45 | 46 | these are in direct violation of their example 12 --> 26 which should be 223 according 47 | to codesignal 48 | 49 | ''' 50 | 51 | def primeFactors(product): 52 | combination=[] 53 | 54 | while product%2==0: 55 | combination.append(2) 56 | product=product/2 57 | 58 | for value in range(3,int(product)+1,2): 59 | while product%value==0: 60 | combination.append(value) 61 | product=product/value 62 | 63 | if len(combination)==0: 64 | return([1,product]) 65 | 66 | return(combination) 67 | 68 | def digitsProduct(product): 69 | 70 | #this is an edge case that would be overlooked by findProducts above 71 | if product is 0: 72 | return 10 73 | 74 | combinations=primeFactors(product) 75 | combinations=[str(i) for i in combinations] 76 | 77 | #if the number is prime return -1 78 | if len(combinations)==1: 79 | return -1 80 | 81 | combinations=''.join(combinations) 82 | 83 | 84 | return(combinations) 85 | 86 | 87 | if __name__=='__main__': 88 | numbers=[12,19,243,450] 89 | for number in numbers: 90 | print(str(number),':',digitsProduct(number)) 91 | print() -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/digitsProduct_codesignal_2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 16:18:50 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given an integer product, find the smallest positive (i.e. greater than 0) 8 | integer the product of whose digits is equal to product. If there is no such 9 | integer, return -1 instead. 10 | 11 | Example 12 | 13 | For product = 12, the output should be 14 | digitsProduct(product) = 26; 15 | For product = 19, the output should be 16 | digitsProduct(product) = -1. 17 | Input/Output 18 | 19 | [execution time limit] 4 seconds (py3) 20 | 21 | [input] integer product 22 | 23 | Guaranteed constraints: 24 | 0 ≤ product ≤ 600. 25 | 26 | [output] integer 27 | """ 28 | 29 | ''' 30 | Thoughts: 31 | 32 | Let us start with a brute force approach and look for simplifications along the way 33 | 34 | 1) find all combinations numbers that multiply to equal the given product 35 | 2) concatenate the values in each combination 36 | 3) return the smallest int(combination)) 37 | 38 | 39 | This question has a 70% disapproval rating. Likely because of the way it is worded. 40 | 41 | digitsProduct_codesignal will try to meet codesignals interpretation of the question 42 | 43 | in my test example below: code signal says 243 should go to 399 instead of 279 44 | furthermore that 450 should go to 2559 instead of 509 45 | 46 | these are in direct violation of their example 12 --> 26 which should be 223 according 47 | to codesignal 48 | 49 | props to bandorthild for this solution 50 | ''' 51 | 52 | def digitsProduct(product): 53 | if product == 0: 54 | return 10 55 | 56 | for i in range(3600): 57 | a = 1 58 | for j in str(i): 59 | a *= int(j) 60 | if a == p: 61 | return i 62 | 63 | return -1 64 | 65 | 66 | if __name__=='__main__': 67 | numbers=[12,19,243,450] 68 | for number in numbers: 69 | print(str(number),':',digitsProduct(number)) 70 | print() -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/electionWinners.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 13:59:59 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Elections are in progress! 8 | 9 | Given an array of the numbers of votes given to each of the candidates so far, 10 | and an integer k equal to the number of voters who haven't cast their vote yet, 11 | find the number of candidates who still have a chance to win the election. 12 | 13 | The winner of the election must secure strictly more votes than any other 14 | candidate. If two or more candidates receive the same (maximum) number of votes, 15 | assume there is no winner at all. 16 | 17 | Example 18 | 19 | For votes = [2, 3, 5, 2] and k = 3, the output should be 20 | electionsWinners(votes, k) = 2. 21 | 22 | The first candidate got 2 votes. Even if all of the remaining 3 candidates vote 23 | for him, he will still have only 5 votes, i.e. the same number as the third 24 | candidate, so there will be no winner. 25 | The second candidate can win if all the remaining candidates vote for him (3 + 3 = 6 > 5). 26 | The third candidate can win even if none of the remaining candidates vote for 27 | him. For example, if each of the remaining voters cast their votes for each of 28 | his opponents, he will still be the winner (the votes array will thus be [3, 4, 5, 3]). 29 | The last candidate can't win no matter what (for the same reason as the first candidate). 30 | Thus, only 2 candidates can win (the second and the third), which is the answer. 31 | 32 | Input/Output 33 | 34 | [execution time limit] 4 seconds (py3) 35 | 36 | [input] array.integer votes 37 | 38 | A non-empty array of non-negative integers. Its ith element denotes the number 39 | of votes cast for the ith candidate. 40 | 41 | Guaranteed constraints: 42 | 4 ≤ votes.length ≤ 105, 43 | 0 ≤ votes[i] ≤ 104. 44 | 45 | [input] integer k 46 | 47 | The number of voters who haven't cast their vote yet. 48 | 49 | Guaranteed constraints: 50 | 0 ≤ k ≤ 105. 51 | 52 | [output] integer 53 | """ 54 | import numpy as np 55 | 56 | def electionsWinners(votes, k): 57 | #If all the votes are in return 0 if tie and 1 if there is a winner 58 | if k==0: 59 | if votes.count(max(votes))==1: 60 | return 1 61 | else: 62 | return 0 63 | 64 | #Return how many candidates (sum of True values) can win if they receive all of the votes 65 | votes=np.array(votes) 66 | min_to_maybe_win=np.max(votes)+1-k 67 | return(sum(votes>=min_to_maybe_win)) 68 | 69 | 70 | if __name__=="__main__": 71 | print(electionsWinners([2,3,5,2],3)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/fileNaming.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 18:22:37 2020 4 | 5 | @author: Logan Rowe 6 | 7 | You are given an array of desired filenames in the order of their creation. 8 | Since two files cannot have equal names, the one which comes later will have 9 | an addition to its name in a form of (k), where k is the smallest positive 10 | integer such that the obtained name is not used yet. 11 | 12 | Return an array of names that will be given to the files. 13 | 14 | Example 15 | 16 | For names = ["doc", "doc", "image", "doc(1)", "doc"], the output should be 17 | fileNaming(names) = ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"]. 18 | 19 | Input/Output 20 | 21 | [execution time limit] 4 seconds (py3) 22 | 23 | [input] array.string names 24 | 25 | Guaranteed constraints: 26 | 5 ≤ names.length ≤ 1000, 27 | 1 ≤ names[i].length ≤ 15. 28 | 29 | [output] array.string 30 | """ 31 | 32 | def fileNaming(names): 33 | 34 | #Iterate through names and check to see if name is pre-existing (at an earlier index) 35 | index=0 36 | for name in names: 37 | count=0 38 | if name in names[:index]: 39 | #Since a name is preexisting, count how many times it pre-exists 40 | count+=names[:index].count(name) 41 | while names[index]+'('+str(count)+')' in names[:index]: 42 | count+=1 43 | 44 | #update the files name 45 | names[index]=names[index]+'('+str(count)+')' 46 | index+=1 47 | 48 | return(names) 49 | 50 | 51 | if __name__=='__main__': 52 | names = ["doc", "doc", "image", "doc(1)", "doc"] 53 | output= ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"] 54 | for (new_name,name_out) in zip(fileNaming(names),output): 55 | print(new_name,name_out) 56 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/findEmailDomain.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 13:26:09 2020 4 | 5 | @author: Logan Rowe 6 | 7 | An email address such as "John.Smith@example.com" is made up of a local 8 | part ("John.Smith"), an "@" symbol, then a domain part ("example.com"). 9 | 10 | The domain name part of an email address may only consist of letters, digits, 11 | hyphens and dots. The local part, however, also allows a lot of different 12 | special characters. Here you can look at several examples of correct and 13 | incorrect email addresses. 14 | 15 | Given a valid email address, find its domain part. 16 | 17 | Example 18 | 19 | For address = "prettyandsimple@example.com", the output should be 20 | findEmailDomain(address) = "example.com"; 21 | For address = "fully-qualified-domain@codesignal.com", the output should be 22 | findEmailDomain(address) = "codesignal.com". 23 | Input/Output 24 | 25 | [execution time limit] 4 seconds (py3) 26 | 27 | [input] string address 28 | 29 | Guaranteed constraints: 30 | 10 ≤ address.length ≤ 50. 31 | 32 | [output] string 33 | """ 34 | 35 | def findEmailDomain(address): 36 | #find the index of the @ symbol closest to the end (although there should be only one) 37 | idx=address.rfind('@') 38 | return(address[idx+1:]) 39 | 40 | 41 | if __name__=='__main__': 42 | addresses=["fully-qualified-domain@codesignal.com","prettyandsimple@example.com"] 43 | for address in addresses: 44 | print(findEmailDomain(address)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/isBeautifulString.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 12:22:27 2020 4 | 5 | @author: Logan Rowe 6 | 7 | A string is said to be beautiful if each letter in the string appears at most 8 | as many times as the previous letter in the alphabet within the string; ie: 9 | b occurs no more times than a; c occurs no more times than b; etc. 10 | 11 | Given a string, check whether it is beautiful. 12 | 13 | Example 14 | 15 | For inputString = "bbbaacdafe", the output should be 16 | isBeautifulString(inputString) = true; 17 | 18 | This string contains 3 as, 3 bs, 1 c, 1 d, 1 e, and 1 f 19 | (and 0 of every other letter), so since there aren't any letters that appear 20 | more frequently than the previous letter, this string qualifies as beautiful. 21 | 22 | For inputString = "aabbb", the output should be 23 | isBeautifulString(inputString) = false; 24 | 25 | Since there are more bs than as, this string is not beautiful. 26 | 27 | For inputString = "bbc", the output should be 28 | isBeautifulString(inputString) = false. 29 | 30 | Although there are more bs than cs, this string is not beautiful because there 31 | are no as, so therefore there are more bs than as. 32 | 33 | Input/Output 34 | 35 | [execution time limit] 4 seconds (py3) 36 | 37 | [input] string inputString 38 | 39 | A string of lowercase English letters. 40 | 41 | Guaranteed constraints: 42 | 3 ≤ inputString.length ≤ 50. 43 | 44 | [output] boolean 45 | 46 | Return true if the string is beautiful, false otherwise. 47 | """ 48 | 49 | ''' 50 | thoughts... 51 | 52 | this was a poorly phrased problem because it did not state wheter the alphabet 53 | was a continuous loop. i.e. whether 'aaz' is beautiful. 54 | 55 | thought process is annotated within the function below 56 | ''' 57 | 58 | import string 59 | 60 | def isBeautifulString(inputString): 61 | #Use a dictionary to track how many times each letter is found in inputString 62 | letter_count={} 63 | for letter in string.ascii_lowercase: 64 | letter_count[letter]=0 65 | 66 | for letter in inputString: 67 | if letter_count[letter]==0: 68 | letter_count[letter]=inputString.count(letter) 69 | 70 | #Use another dictionary to see which letter precedes any given letter alphavetically 71 | alphabet=string.ascii_lowercase 72 | previous='z'+string.ascii_lowercase[:-1] 73 | previous_letter={alphabet[idx]:previous[idx] for idx in range(len(alphabet))} 74 | 75 | #check if the prevoius is in the word, it is in the word more times than the current letter 76 | for letter in set(inputString): 77 | if letter_count[letter]>letter_count[previous_letter[letter]] and letter!='a': 78 | return False 79 | 80 | return True 81 | 82 | 83 | if __name__=='__main__': 84 | inputStrings=["bbbaacdafe",'bbc'] 85 | for s in inputStrings: print(isBeautifulString(s)) 86 | 87 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/isIPv4Address.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 01:19:10 2020 4 | 5 | @author: Logan Rowe 6 | 7 | An IP address is a numerical label assigned to each device 8 | (e.g., computer, printer) participating in a computer network that uses the 9 | Internet Protocol for communication. There are two versions of the Internet 10 | protocol, and thus two versions of addresses. One of them is the IPv4 address. 11 | 12 | Given a string, find out if it satisfies the IPv4 address naming rules. 13 | 14 | Example 15 | 16 | For inputString = "172.16.254.1", the output should be 17 | isIPv4Address(inputString) = true; 18 | 19 | For inputString = "172.316.254.1", the output should be 20 | isIPv4Address(inputString) = false. 21 | 22 | 316 is not in range [0, 255]. 23 | 24 | For inputString = ".254.255.0", the output should be 25 | isIPv4Address(inputString) = false. 26 | 27 | There is no first number. 28 | 29 | Input/Output 30 | 31 | [execution time limit] 4 seconds (py3) 32 | 33 | [input] string inputString 34 | 35 | A string consisting of digits, full stops and lowercase English letters. 36 | 37 | Guaranteed constraints: 38 | 1 ≤ inputString.length ≤ 30. 39 | 40 | [output] boolean 41 | 42 | true if inputString satisfies the IPv4 address naming rules, false otherwise. 43 | 44 | 45 | 46 | Notes: 47 | IPv4 address is a string with the following structure: a.b.c.d, where 48 | a, b, c and d are integers in range [0, 255]. For example, 0.0.0.0, 49 | 255.255.255.255 or 252.0.128.32 are correct IPv4 addresses, and 0.0.0.256, 50 | -1.1.1.1, 0.0.0.0.0 are incorrect. 51 | 52 | a.b is named network part and c.d is named host part. 53 | """ 54 | 55 | ''' 56 | Thoughts: 57 | 58 | 1) split IP by '.' 59 | 2) convert each item to integer and check if it is between 0 and 255 inclusive 60 | 3) ensure list is only 4 items long 61 | 62 | ''' 63 | 64 | def isIPv4Address(inputString): 65 | components=inputString.split('.') 66 | 67 | for i in components: 68 | try: 69 | int(i) 70 | except: 71 | return False 72 | if int(i)>255 or int(i)<0: 73 | return False 74 | if len(components)!=4: 75 | return False 76 | 77 | return True 78 | 79 | 80 | if __name__=='__main__': 81 | IPs=["172.16.254.1","172.316.254.1",".254.255.0"] 82 | output=[True,False,False] 83 | 84 | for (i,j) in zip(IPs,output): 85 | if isIPv4Address(i)==j: 86 | print("passed test") 87 | else: 88 | print('failed:',i) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/isMAC48Address.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 14:12:26 2020 4 | 5 | @author: Logan Rowe 6 | 7 | A media access control address (MAC address) is a unique identifier assigned 8 | to network interfaces for communications on the physical network segment. 9 | 10 | The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly 11 | form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by 12 | hyphens (e.g. 01-23-45-67-89-AB). 13 | 14 | Your task is to check by given string inputString whether it corresponds to 15 | MAC-48 address or not. 16 | 17 | Example 18 | 19 | For inputString = "00-1B-63-84-45-E6", the output should be 20 | isMAC48Address(inputString) = true; 21 | For inputString = "Z1-1B-63-84-45-E6", the output should be 22 | isMAC48Address(inputString) = false; 23 | For inputString = "not a MAC-48 address", the output should be 24 | isMAC48Address(inputString) = false. 25 | Input/Output 26 | 27 | [execution time limit] 4 seconds (py3) 28 | 29 | [input] string inputString 30 | 31 | Guaranteed constraints: 32 | 15 ≤ inputString.length ≤ 20. 33 | 34 | [output] boolean 35 | 36 | true if inputString corresponds to MAC-48 address naming rules, false otherwise. 37 | """ 38 | 39 | import string 40 | 41 | def isMAC48Address(inputString): 42 | #First let us check that the input is in 6 groups of 2 characters separated by '-' 43 | sub_strings=inputString.split('-') 44 | if len(sub_strings)!=6: 45 | return False 46 | for s in sub_strings: 47 | if len(s)!=2: 48 | return False 49 | 50 | #Now lets check whether the substring consists of all valid characters 51 | valid_characters=string.hexdigits 52 | 53 | for character in inputString: 54 | if character not in valid_characters and character!='-': 55 | return False 56 | 57 | return True 58 | 59 | 60 | 61 | if __name__=="__main__": 62 | inputs=["00-1B-63-84-45-E6","Z1-1B-63-84-45-E6"] 63 | for s in inputs: 64 | print(isMAC48Address(s)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/lineEncoding.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 14:23:10 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given a string, return its encoding defined as follows: 8 | 9 | First, the string is divided into the least possible number of disjoint 10 | substrings consisting of identical characters 11 | for example, "aabbbc" is divided into ["aa", "bbb", "c"] 12 | Next, each substring with length greater than one is replaced with a 13 | concatenation of its length and the repeating character 14 | for example, substring "bbb" is replaced by "3b" 15 | Finally, all the new strings are concatenated together in the same order 16 | and a new string is returned. 17 | Example 18 | 19 | For s = "aabbbc", the output should be 20 | lineEncoding(s) = "2a3bc". 21 | 22 | Input/Output 23 | 24 | [execution time limit] 4 seconds (py3) 25 | 26 | [input] string s 27 | 28 | String consisting of lowercase English letters. 29 | 30 | Guaranteed constraints: 31 | 4 ≤ s.length ≤ 15. 32 | 33 | [output] string 34 | 35 | Encoded version of s. 36 | """ 37 | 38 | def lineEncoding(s): 39 | split_letters='' 40 | 41 | prev_letter=s[0] 42 | for letter in s: 43 | if letter==prev_letter: 44 | split_letters+=letter 45 | else: 46 | split_letters+=','+letter 47 | prev_letter=letter 48 | 49 | encoded_list=[str(len(i))+i[0] for i in split_letters.split(',')] 50 | 51 | idx=0 52 | for i in encoded_list: 53 | if i[0]=='1' and len(i)==2: 54 | encoded_list[idx]=i[1] 55 | idx+=1 56 | 57 | encoded_string=''.join(encoded_list) 58 | 59 | return(encoded_string) 60 | 61 | 62 | 63 | if __name__=='__main__': 64 | strings = ["aabbbc",'ccccccccccccccc'] 65 | for s in strings: 66 | print(lineEncoding(s)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/messageFromBinaryCode.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 18:39:07 2020 4 | 5 | @author: Logan Rowe 6 | 7 | You are taking part in an Escape Room challenge designed specifically for 8 | programmers. In your efforts to find a clue, you've found a binary code written 9 | on the wall behind a vase, and realized that it must be an encrypted message. 10 | After some thought, your first guess is that each consecutive 8 bits of the 11 | code stand for the character with the corresponding extended ASCII code. 12 | 13 | Assuming that your hunch is correct, decode the message. 14 | 15 | Example 16 | 17 | For code = "010010000110010101101100011011000110111100100001", the output should be 18 | messageFromBinaryCode(code) = "Hello!". 19 | 20 | The first 8 characters of the code are 01001000, which is 72 in the binary 21 | numeral system. 72 stands for H in the ASCII-table, so the first letter is H. 22 | Other letters can be obtained in the same manner. 23 | 24 | Input/Output 25 | 26 | [execution time limit] 4 seconds (py3) 27 | 28 | [input] string code 29 | 30 | A string, the encrypted message consisting of characters '0' and '1'. 31 | 32 | Guaranteed constraints: 33 | 0 < code.length < 800. 34 | 35 | [output] string 36 | 37 | The decrypted message. 38 | """ 39 | 40 | 41 | def messageFromBinaryCode(code): 42 | elements=[int(code[index*8:(index+1)*8],2) for index in range(int(len(code)/8))] 43 | elements=[chr(element) for element in elements] 44 | return(''.join(elements)) 45 | 46 | 47 | 48 | if __name__=='__main__': 49 | code = "010010000110010101101100011011000110111100100001" 50 | print(messageFromBinaryCode(code)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/mineSweeper.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 18:02:16 2020 4 | 5 | @author: Logan Rowe 6 | 7 | In the popular Minesweeper game you have a board with some mines and those 8 | cells that don't contain a mine have a number in it that indicates the total 9 | number of mines in the neighboring cells. Starting off with some arrangement 10 | of mines we want to create a Minesweeper game setup. 11 | 12 | Example 13 | 14 | For 15 | 16 | matrix = [[true, false, false], 17 | [false, true, false], 18 | [false, false, false]] 19 | the output should be 20 | 21 | minesweeper(matrix) = [[1, 2, 1], 22 | [2, 1, 1], 23 | [1, 1, 1]] 24 | Check out the image below for better understanding: 25 | 26 | 27 | 28 | Input/Output 29 | 30 | [execution time limit] 4 seconds (py3) 31 | 32 | [input] array.array.boolean matrix 33 | 34 | A non-empty rectangular matrix consisting of boolean values - true if the 35 | corresponding cell contains a mine, false otherwise. 36 | 37 | Guaranteed constraints: 38 | 2 ≤ matrix.length ≤ 100, 39 | 2 ≤ matrix[0].length ≤ 100. 40 | 41 | [output] array.array.integer 42 | 43 | Rectangular matrix of the same size as matrix each cell of which contains an 44 | integer equal to the number of mines in the neighboring cells. Two cells are 45 | called neighboring if they share at least one corner. 46 | """ 47 | 48 | ''' 49 | Thoughts: 50 | 51 | 1) Lets make a duplicate matrix with a border of 0 (False) values 52 | 2) Fill output_matrix with the sum of true values in the 8 closest squares 53 | 3) return output_matrix 54 | ''' 55 | 56 | import numpy as np 57 | 58 | def minesweeper(matrix): 59 | matrix=np.array(matrix) 60 | 61 | #input is true and false so lets make it python readable 62 | matrix[matrix=='true']=True 63 | matrix[matrix=='false']=False 64 | 65 | temp=np.full((matrix.shape[0]+2,matrix.shape[1]+2),False) 66 | 67 | #fill central squares in temp with given matrix 68 | temp[1:-1,1:-1]=matrix 69 | 70 | output_matrix=np.full(matrix.shape,0) 71 | 72 | row=0 73 | while row < output_matrix.shape[0]: 74 | column=0 75 | while column < output_matrix.shape[1]: 76 | 77 | #calculate the blurred pixel value from the old image 78 | mine_count=np.sum(temp[row:row+3,column:column+3]) 79 | 80 | #If the square itself is a mine subtract 1 so it doesnt count itself 81 | if matrix[row,column]==True: 82 | mine_count-=1 83 | 84 | #insert blurred pixel into new_image 85 | output_matrix[row,column]=mine_count 86 | column+=1 87 | row+=1 88 | 89 | return(output_matrix) 90 | 91 | if __name__=='__main__': 92 | matrix = [[True, False, False], 93 | [False, True, False], 94 | [False, False, False]] 95 | print(minesweeper(matrix)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/palindromeRearranging.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 00:57:59 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given a string, find out if its characters can be rearranged to form a palindrome. 8 | 9 | Example 10 | 11 | For inputString = "aabb", the output should be 12 | palindromeRearranging(inputString) = true. 13 | 14 | We can rearrange "aabb" to make "abba", which is a palindrome. 15 | 16 | Input/Output 17 | 18 | [execution time limit] 4 seconds (py3) 19 | 20 | [input] string inputString 21 | 22 | A string consisting of lowercase English letters. 23 | 24 | Guaranteed constraints: 25 | 1 ≤ inputString.length ≤ 50. 26 | 27 | [output] boolean 28 | 29 | true if the characters of the inputString can be rearranged to form a 30 | palindrome, false otherwise. 31 | """ 32 | 33 | ''' 34 | thoughts: 35 | 36 | this one seems faily straight forward: 37 | 38 | 1) check each character to see if it occurs an even number of times 39 | 2) up to 1 character may occur an odd numer of times 40 | 41 | ''' 42 | 43 | def palindromeRearranging(inputString): 44 | 45 | #track how many characters occur an odd number of times 46 | odd_char=0 47 | 48 | #track letters already checked 49 | letters=[] 50 | 51 | for letter in inputString: 52 | 53 | if letter in letters: 54 | continue 55 | 56 | if inputString.count(letter)%2==1: 57 | odd_char+=1 58 | letters.append(letter) 59 | else: 60 | letters.append(letter) 61 | 62 | if odd_char>1: 63 | return False 64 | else: 65 | return True -------------------------------------------------------------------------------- /old_practice_problems/arcade/intro-problems/medium/sumUpNumbers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 15:22:54 2020 4 | 5 | @author: Logan Rowe 6 | 7 | CodeMaster has just returned from shopping. He scanned the check of the items 8 | he bought and gave the resulting string to Ratiorg to figure out the total 9 | number of purchased items. Since Ratiorg is a bot he is definitely going to 10 | automate it, so he needs a program that sums up all the numbers which appear 11 | in the given input. 12 | 13 | Help Ratiorg by writing a function that returns the sum of numbers that appear 14 | in the given inputString. 15 | 16 | Example 17 | 18 | For inputString = "2 apples, 12 oranges", the output should be 19 | sumUpNumbers(inputString) = 14. 20 | 21 | Input/Output 22 | 23 | [execution time limit] 4 seconds (py3) 24 | 25 | [input] string inputString 26 | 27 | Guaranteed constraints: 28 | 0 ≤ inputString.length ≤ 105. 29 | 30 | [output] integer 31 | """ 32 | 33 | import string 34 | 35 | def sumUpNumbers(inputString): 36 | #Let us filter out all non-digit values without breaking up the given numbers 37 | numbers='' 38 | for character in inputString: 39 | if character in string.digits: 40 | numbers+=character 41 | else: 42 | numbers+=',' 43 | 44 | #now lets convert all numbers to integers and add them up 45 | total=sum([int(char) for char in numbers.split(',') if char!='']) 46 | 47 | return(total) 48 | 49 | if __name__=='__main__': 50 | print(sumUpNumbers("2 apples, 12 oranges")) -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/addTwoDigits.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 14 01:05:58 2020 4 | 5 | @author: Logan Rowe 6 | 7 | You are given a two-digit integer n. Return the sum of its digits. 8 | 9 | Example 10 | 11 | For n = 29, the output should be 12 | addTwoDigits(n) = 11. 13 | 14 | Input/Output 15 | 16 | [execution time limit] 4 seconds (py3) 17 | 18 | [input] integer n 19 | 20 | A positive two-digit integer. 21 | 22 | Guaranteed constraints: 23 | 10 ≤ n ≤ 99. 24 | 25 | [output] integer 26 | 27 | The sum of the first and second digits of the input number. 28 | """ 29 | 30 | def addTwoDigits(n): 31 | return(sum([int(i) for i in str(n)])) -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/additionWithoutCarrying.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Feb 25 23:48:34 2020 4 | 5 | @author: Logan Rowe 6 | 7 | A little boy is studying arithmetics. He has just learned how to add two integers, written one below another, column by column. But he always forgets about the important part - carrying. 8 | 9 | Given two integers, your task is to find the result which the little boy will get. 10 | 11 | Note: The boy had learned from this site, so feel free to check it out too if you are not familiar with column addition. 12 | 13 | Example 14 | 15 | For param1 = 456 and param2 = 1734, the output should be 16 | additionWithoutCarrying(param1, param2) = 1180. 17 | 18 | 456 19 | 1734 20 | + ____ 21 | 1180 22 | The boy performs the following operations from right to left: 23 | 24 | 6 + 4 = 10 but he forgets about carrying the 1 and just writes down the 0 in the last column 25 | 5 + 3 = 8 26 | 4 + 7 = 11 but he forgets about the leading 1 and just writes down 1 under 4 and 7. 27 | There is no digit in the first number corresponding to the leading digit of the second one, so the boy imagines that 0 is written before 456. Thus, he gets 0 + 1 = 1. 28 | Input/Output 29 | 30 | [execution time limit] 4 seconds (py3) 31 | 32 | [input] integer param1 33 | 34 | A non-negative integer. 35 | 36 | Guaranteed constraints: 37 | 0 ≤ param1 < 105. 38 | 39 | [input] integer param2 40 | 41 | A non-negative integer. 42 | 43 | Guaranteed constraints: 44 | 0 ≤ param2 < 6 · 104. 45 | 46 | [output] integer 47 | 48 | The result that the little boy will get by using column addition without carrying. 49 | """ 50 | 51 | def additionWithoutCarrying(param1,param2): 52 | if param1>param2: 53 | lz='0'*int(len(str(param1))-len(str(param2))) 54 | param1=str(param1)[::-1] 55 | param2=str(lz+str(param2))[::-1] 56 | else: 57 | lz='0'*(len(str(param2))-len(str(param1))) 58 | param2=str(param2)[::-1] 59 | param1=str(lz+str(param1))[::-1] 60 | 61 | param3=str(''.join([str((int(i)+int(j))%10) for (i,j) in zip(param1,param2)]))[::-1] 62 | 63 | return int(param3) 64 | 65 | print(additionWithoutCarrying(456,1734)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/appleBoxes.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 26 23:33:01 2020 4 | 5 | @author: Logan Rowe 6 | 7 | You have k apple boxes full of apples. Each square box of size m contains m × m apples. You just noticed two interesting properties about the boxes: 8 | 9 | The smallest box is size 1, the next one is size 2,..., all the way up to size k. 10 | Boxes that have an odd size contain only yellow apples. Boxes that have an even size contain only red apples. 11 | Your task is to calculate the difference between the number of red apples and the number of yellow apples. 12 | 13 | Example 14 | 15 | For k = 5, the output should be 16 | appleBoxes(k) = -15. 17 | 18 | There are 1 + 3 * 3 + 5 * 5 = 35 yellow apples and 2 * 2 + 4 * 4 = 20 red apples, making the answer 20 - 35 = -15. 19 | 20 | Input/Output 21 | 22 | [execution time limit] 4 seconds (py3) 23 | 24 | [input] integer k 25 | 26 | A positive integer. 27 | 28 | Guaranteed constraints: 29 | 1 ≤ k ≤ 40. 30 | 31 | [output] integer 32 | 33 | The difference between the two types of apples. 34 | """ 35 | 36 | def appleBoxes(k): 37 | diff=0 38 | for i in range(1,k+1): 39 | if i%2==1: 40 | diff-=i**2 41 | else: 42 | diff+=i**2 43 | return diff 44 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/arithmeticExpression.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat Feb 15 14:07:43 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Consider an arithmetic expression of the form a#b=c. Check whether it is possible to replace # with one of the four signs: +, -, * or / to obtain a correct expression. 8 | 9 | Example 10 | 11 | For a = 2, b = 3, and c = 5, the output should be 12 | arithmeticExpression(a, b, c) = true. 13 | 14 | We can replace # with a + to obtain 2 + 3 = 5, so the answer is true. 15 | 16 | For a = 8, b = 2, and c = 4, the output should be 17 | arithmeticExpression(a, b, c) = true. 18 | 19 | We can replace # with a / to obtain 8 / 2 = 4, so the answer is true. 20 | 21 | For a = 8, b = 3, and c = 2, the output should be 22 | arithmeticExpression(a, b, c) = false. 23 | 24 | 8 + 3 = 11 ≠ 2; 25 | 8 - 3 = 5 ≠ 2; 26 | 8 * 3 = 24 ≠ 2; 27 | 8 / 3 = 2.(6) ≠ 2. 28 | So the answer is false. 29 | 30 | Input/Output 31 | 32 | [execution time limit] 4 seconds (py3) 33 | 34 | [input] integer a 35 | 36 | Guaranteed constraints: 37 | 1 ≤ a ≤ 20. 38 | 39 | [input] integer b 40 | 41 | Guaranteed constraints: 42 | 1 ≤ b ≤ 20. 43 | 44 | [input] integer c 45 | 46 | Guaranteed constraints: 47 | 0 ≤ c ≤ 20. 48 | 49 | [output] boolean 50 | 51 | true if the desired replacement is possible, false otherwise. 52 | """ 53 | 54 | def arithmeticExpression(a, b, c): 55 | return (a+b==c or a-b==c or a/b==c or a*b==c) 56 | 57 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/arrayReplace.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 27 23:49:32 2020 4 | 5 | @author: Logan Rowe 6 | 7 | 8 | Given an array of integers, replace all the occurrences of elemToReplace with substitutionElem. 9 | 10 | Example 11 | 12 | For inputArray = [1, 2, 1], elemToReplace = 1, and substitutionElem = 3, the output should be 13 | arrayReplace(inputArray, elemToReplace, substitutionElem) = [3, 2, 3]. 14 | 15 | Input/Output 16 | 17 | [execution time limit] 4 seconds (py3) 18 | 19 | [input] array.integer inputArray 20 | 21 | Guaranteed constraints: 22 | 0 ≤ inputArray.length ≤ 104, 23 | 0 ≤ inputArray[i] ≤ 109. 24 | 25 | [input] integer elemToReplace 26 | 27 | Guaranteed constraints: 28 | 0 ≤ elemToReplace ≤ 109. 29 | 30 | [input] integer substitutionElem 31 | 32 | Guaranteed constraints: 33 | 0 ≤ substitutionElem ≤ 109. 34 | 35 | [output] array.integer 36 | 37 | [Python3] Syntax Tips 38 | """ 39 | import numpy as np 40 | def arrayReplace(inputArray, elemToReplace, substitutionElem): 41 | inputArray=np.array(inputArray) 42 | inputArray[inputArray==elemToReplace]=substitutionElem 43 | return inputArray 44 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/candies.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 14 01:10:22 2020 4 | 5 | @author: Logan Rowe 6 | 7 | n children have got m pieces of candy. They want to eat as much candy as they can, but each child must eat exactly the same amount of candy as any other child. Determine how many pieces of candy will be eaten by all the children together. Individual pieces of candy cannot be split. 8 | 9 | Example 10 | 11 | For n = 3 and m = 10, the output should be 12 | candies(n, m) = 9. 13 | 14 | Each child will eat 3 pieces. So the answer is 9. 15 | 16 | Input/Output 17 | 18 | [execution time limit] 4 seconds (py3) 19 | 20 | [input] integer n 21 | 22 | The number of children. 23 | 24 | Guaranteed constraints: 25 | 1 ≤ n ≤ 10. 26 | 27 | [input] integer m 28 | 29 | The number of pieces of candy. 30 | 31 | Guaranteed constraints: 32 | 2 ≤ m ≤ 100. 33 | 34 | [output] integer 35 | 36 | The total number of pieces of candy the children will eat provided they eat as much as they can and all children eat the same amount. 37 | """ 38 | 39 | def candies(n, m): 40 | return(int(n*int(m/n))) -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/candles.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 26 23:55:09 2020 4 | 5 | @author: Logan Rowe 6 | 7 | When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover. 8 | 9 | You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles as soon as you have enough leftovers? 10 | 11 | Example 12 | 13 | For candlesNumber = 5 and makeNew = 2, the output should be 14 | candles(candlesNumber, makeNew) = 9. 15 | 16 | Here is what you can do to burn 9 candles: 17 | 18 | burn 5 candles, obtain 5 leftovers; 19 | create 2 more candles, using 4 leftovers (1 leftover remains); 20 | burn 2 candles, end up with 3 leftovers; 21 | create another candle using 2 leftovers (1 leftover remains); 22 | burn the created candle, which gives another leftover (2 leftovers in total); 23 | create a candle from the remaining leftovers; 24 | burn the last candle. 25 | Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer. 26 | 27 | Input/Output 28 | 29 | [execution time limit] 4 seconds (py3) 30 | 31 | [input] integer candlesNumber 32 | 33 | The number of candles you have in your possession. 34 | 35 | Guaranteed constraints: 36 | 1 ≤ candlesNumber ≤ 15. 37 | 38 | [input] integer makeNew 39 | 40 | The number of leftovers that you can use up to create a new candle. 41 | 42 | Guaranteed constraints: 43 | 2 ≤ makeNew ≤ 5. 44 | 45 | [output] integer 46 | """ 47 | 48 | def candles(candlesNumber,makeNew): 49 | candles=[1]*candlesNumber 50 | count=0 51 | for candle in candles: 52 | count+=1 53 | if count%makeNew==0: 54 | candles.append(1) 55 | return(sum(candles)) 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | print(candles(5,2)) 65 | print('True Value: 9') 66 | 67 | print(candles(11,3)) 68 | print('True Value: 16') 69 | 70 | print(candles(13,5)) 71 | print('True Value: 16') 72 | 73 | print(candles(12,2)) 74 | print('True Value: 23') -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/circleOfNumbers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 14 01:20:09 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Consider integer numbers from 0 to n - 1 written down along the circle in such a way that the distance between any two neighboring numbers is equal (note that 0 and n - 1 are neighboring, too). 8 | 9 | Given n and firstNumber, find the number which is written in the radially opposite position to firstNumber. 10 | 11 | Example 12 | 13 | For n = 10 and firstNumber = 2, the output should be 14 | circleOfNumbers(n, firstNumber) = 7. 15 | 16 | 17 | 18 | Input/Output 19 | 20 | [execution time limit] 4 seconds (py3) 21 | 22 | [input] integer n 23 | 24 | A positive even integer. 25 | 26 | Guaranteed constraints: 27 | 4 ≤ n ≤ 20. 28 | 29 | [input] integer firstNumber 30 | 31 | Guaranteed constraints: 32 | 0 ≤ firstNumber ≤ n - 1. 33 | 34 | [output] integer 35 | """ 36 | 37 | def circleOfNumbers(n, firstNumber): 38 | if firstNumber+int(n/2)>=n: 39 | return(firstNumber-int(n/2)) 40 | return firstNumber+int(n/2) 41 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/comfortableNumbers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Mar 3 10:48:29 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Let's say that number a feels comfortable with number b if a ≠ b and b lies in the segment [a - s(a), a + s(a)], where s(x) is the sum of x's digits. 8 | 9 | How many pairs (a, b) are there, such that a < b, both a and b lie on the segment [l, r], and each number feels comfortable with the other (so a feels comfortable with b and b feels comfortable with a)? 10 | 11 | Example 12 | 13 | For l = 10 and r = 12, the output should be 14 | comfortableNumbers(l, r) = 2. 15 | 16 | Here are all values of s(x) to consider: 17 | 18 | s(10) = 1, so 10 is comfortable with 9 and 11; 19 | s(11) = 2, so 11 is comfortable with 9, 10, 12 and 13; 20 | s(12) = 3, so 12 is comfortable with 9, 10, 11, 13, 14 and 15. 21 | Thus, there are 2 pairs of numbers comfortable with each other within the segment [10; 12]: (10, 11) and (11, 12). 22 | 23 | Input/Output 24 | 25 | [execution time limit] 4 seconds (py3) 26 | 27 | [input] integer l 28 | 29 | Guaranteed constraints: 30 | 1 ≤ l ≤ r ≤ 1000. 31 | 32 | [input] integer r 33 | 34 | Guaranteed constraints: 35 | 1 ≤ l ≤ r ≤ 1000. 36 | 37 | [output] integer 38 | 39 | The number of pairs satisfying all the above conditions. 40 | """ 41 | 42 | def comfortablePairs(a,l,r): 43 | xr = sum([int(i) for i in str(a)]) 44 | ub = a + xr 45 | lb = a - xr 46 | return [i for i in range(max(lb,l),min(ub+1,r+1))] 47 | 48 | def mutuallyComfortable(a,b,comfortable_dict): 49 | try: 50 | return ((a in comfortable_dict[b]) and (b in comfortable_dict[a]) and a1 find all a+s(a) and ignore all a-s(a) 58 | for num in range(l, r+1): 59 | comfortable_dict[num] = comfortablePairs(num,l,r) 60 | 61 | comfortable_pairs=0 62 | for key in comfortable_dict: 63 | for val in comfortable_dict[key]: 64 | if mutuallyComfortable(key,val,comfortable_dict): 65 | comfortable_pairs+=1 66 | return comfortable_pairs 67 | 68 | 69 | 70 | print(comfortableNumbers(10,12)) 71 | print(comfortableNumbers(12,108)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/concatenateArrays.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 27 23:56:31 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given two arrays of integers a and b, obtain the array formed by the elements of a followed by the elements of b. 8 | 9 | Example 10 | 11 | For a = [2, 2, 1] and b = [10, 11], the output should be 12 | concatenateArrays(a, b) = [2, 2, 1, 10, 11]. 13 | 14 | Input/Output 15 | 16 | [execution time limit] 4 seconds (py3) 17 | 18 | [input] array.integer a 19 | 20 | Guaranteed constraints: 21 | 1 ≤ a.length ≤ 10, 22 | 1 ≤ a[i] ≤ 15. 23 | 24 | [input] array.integer b 25 | 26 | Guaranteed constraints: 27 | 0 ≤ b.length ≤ 10, 28 | 1 ≤ b[i] ≤ 15. 29 | 30 | [output] array.integer 31 | """ 32 | def concatenateArrays(a, b): 33 | c=a+b 34 | return c -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/countSumOfTwoRepresentations2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Feb 23 00:57:29 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given integers n, l and r, find the number of ways to represent n as a sum of two integers A and B such that l ≤ A ≤ B ≤ r. 8 | 9 | Example 10 | 11 | For n = 6, l = 2, and r = 4, the output should be 12 | countSumOfTwoRepresentations2(n, l, r) = 2. 13 | 14 | There are just two ways to write 6 as A + B, where 2 ≤ A ≤ B ≤ 4: 6 = 2 + 4 and 6 = 3 + 3. 15 | 16 | Input/Output 17 | 18 | [execution time limit] 4 seconds (py3) 19 | 20 | [input] integer n 21 | 22 | A positive integer. 23 | 24 | Guaranteed constraints: 25 | 5 ≤ n ≤ 109. 26 | 27 | [input] integer l 28 | 29 | A positive integer. 30 | 31 | Guaranteed constraints: 32 | 1 ≤ l ≤ r. 33 | 34 | [input] integer r 35 | 36 | A positive integer. 37 | 38 | Guaranteed constraints: 39 | l ≤ r ≤ 109, 40 | r - l ≤ 106. 41 | 42 | [output] integer 43 | """ 44 | 45 | def countSumOfTwoRepresentations2(n, l, r): 46 | if n<2*l or n>2*r: 47 | return 0 48 | if n==2*l or n==2*r: 49 | return 1 50 | 51 | middle=int(0.5*l+r) 52 | if n>l+r: 53 | while l+r!=n: 54 | l+=1 55 | else: 56 | while l+r!=n: 57 | r-=1 58 | return(int(0.5*(r-l))+1) 59 | 60 | 61 | 62 | if __name__=='__main__': 63 | n_=[6,6] 64 | l_=[4,3] 65 | r_=[2,3] 66 | a_=[2,1] 67 | for (n,l,r,a) in zip(n_,l_,r_,a_): 68 | print(countSumOfTwoRepresentations2(n,l,r)) 69 | 70 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/createArray.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 27 23:47:49 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given an integer size, return array of length size filled with 1s. 8 | 9 | Example 10 | 11 | For size = 4, the output should be 12 | createArray(size) = [1, 1, 1, 1]. 13 | 14 | Input/Output 15 | 16 | [execution time limit] 4 seconds (py3) 17 | 18 | [input] integer size 19 | 20 | A positive integer. 21 | 22 | Guaranteed constraints: 23 | 1 ≤ size ≤ 1000. 24 | 25 | [output] array.integer 26 | 27 | [Python3] Syntax Tips 28 | """ 29 | 30 | def createArray(size): 31 | return [1]*size -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/extraNumber_XOR.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 14 01:49:52 2020 4 | 5 | @author: Logan Rowe 6 | 7 | You're given three integers, a, b and c. It is guaranteed that two of these integers are equal to each other. What is the value of the third integer? 8 | 9 | Example 10 | 11 | For a = 2, b = 7, and c = 2, the output should be 12 | extraNumber(a, b, c) = 7. 13 | 14 | The two equal numbers are a and c. The third number (b) equals 7, which is the answer. 15 | 16 | Input/Output 17 | 18 | [execution time limit] 4 seconds (py3) 19 | 20 | [input] integer a 21 | 22 | Guaranteed constraints: 23 | 1 ≤ a ≤ 109. 24 | 25 | [input] integer b 26 | 27 | Guaranteed constraints: 28 | 1 ≤ b ≤ 109. 29 | 30 | [input] integer c 31 | 32 | Guaranteed constraints: 33 | 1 ≤ c ≤ 109. 34 | 35 | [output] integer 36 | """ 37 | 38 | def extraNumber(a, b, c): 39 | return a^b^c -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/firstReverseTry.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 27 23:52:04 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Reversing an array can be a tough task, especially for a novice programmer. Mary just started coding, so she would like to start with something basic at first. Instead of reversing the array entirely, she wants to swap just its first and last elements. 8 | 9 | Given an array arr, swap its first and last elements and return the resulting array. 10 | 11 | Example 12 | 13 | For arr = [1, 2, 3, 4, 5], the output should be 14 | firstReverseTry(arr) = [5, 2, 3, 4, 1]. 15 | 16 | Input/Output 17 | 18 | [execution time limit] 4 seconds (py3) 19 | 20 | [input] array.integer arr 21 | 22 | Guaranteed constraints: 23 | 0 ≤ arr.length ≤ 50, 24 | -104 ≤ arr[i] ≤ 104. 25 | 26 | [output] array.integer 27 | 28 | Array arr with its first and its last elements swapped. 29 | [Python3] Syntax Tips 30 | """ 31 | 32 | def firstReverseTry(arr): 33 | if arr==[]: 34 | return arr 35 | arr[-1],arr[0]=arr[0],arr[-1] 36 | return arr -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/increaseNumberRoundness.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 26 23:36:31 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Define an integer's roundness as the number of trailing zeroes in it. 8 | 9 | Given an integer n, check if it's possible to increase n's roundness by swapping some pair of its digits. 10 | 11 | Example 12 | 13 | For n = 902200100, the output should be 14 | increaseNumberRoundness(n) = true. 15 | 16 | One of the possible ways to increase roundness of n is to swap digit 1 with digit 0 preceding it: roundness of 902201000 is 3, and roundness of n is 2. 17 | 18 | For instance, one may swap the leftmost 0 with 1. 19 | 20 | For n = 11000, the output should be 21 | increaseNumberRoundness(n) = false. 22 | 23 | Roundness of n is 3, and there is no way to increase it. 24 | 25 | Input/Output 26 | 27 | [execution time limit] 4 seconds (py3) 28 | 29 | [input] integer n 30 | 31 | A positive integer. 32 | 33 | Guaranteed constraints: 34 | 100 ≤ n ≤ 109. 35 | 36 | [output] boolean 37 | 38 | true if it's possible to increase n's roundness, false otherwise. 39 | """ 40 | 41 | def increaseNumberRoundness(n): 42 | n=str(n) 43 | return n.find('0')!=n.rfind('0') 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | print(increaseNumberRoundness(902200100)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/isInfiniteProcess.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat Feb 15 14:07:14 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given integers a and b, determine whether the following pseudocode results in an infinite loop 8 | 9 | while a is not equal to b do 10 | increase a by 1 11 | decrease b by 1 12 | Assume that the program is executed on a virtual machine which can store arbitrary long numbers and execute forever. 13 | 14 | Example 15 | 16 | For a = 2 and b = 6, the output should be 17 | isInfiniteProcess(a, b) = false; 18 | For a = 2 and b = 3, the output should be 19 | isInfiniteProcess(a, b) = true. 20 | Input/Output 21 | 22 | [execution time limit] 4 seconds (py3) 23 | 24 | [input] integer a 25 | 26 | Guaranteed constraints: 27 | 0 ≤ a ≤ 20. 28 | 29 | [input] integer b 30 | 31 | Guaranteed constraints: 32 | 0 ≤ b ≤ 20. 33 | 34 | [output] boolean 35 | 36 | true if the pseudocode will never stop, false otherwise. 37 | """ 38 | 39 | def isInfiniteProcess(a, b): 40 | if a>b: 41 | return True 42 | if (a-b)%2==1: 43 | return True 44 | return False -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/isPower.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 28 23:27:44 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Determine if the given number is a power of some non-negative integer. 8 | 9 | Example 10 | 11 | For n = 125, the output should be 12 | isPower(n) = true; 13 | For n = 72, the output should be 14 | isPower(n) = false. 15 | Input/Output 16 | 17 | [execution time limit] 4 seconds (py3) 18 | 19 | [input] integer n 20 | 21 | A positive integer. 22 | 23 | Guaranteed constraints: 24 | 1 ≤ n ≤ 400. 25 | 26 | [output] boolean 27 | 28 | true if n can be represented in the form ab (a to the power of b) where a and b are some non-negative integers and b ≥ 2, false otherwise. 29 | """ 30 | 31 | ''' 32 | 33 | Thoughts: 34 | 35 | n<=400 so lets check all possible powers from 2 to 20 36 | 37 | 38 | ''' 39 | 40 | def isPower(n): 41 | for pow in range(2,21): 42 | if round(n**(pow**-1),10)==int(round(n**(pow**-1),10)): 43 | return True 44 | return False 45 | 46 | print(isPower(125)) 47 | print(isPower(72)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/isSmooth.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 28 00:00:52 2020 4 | 5 | @author: Logan Rowe 6 | 7 | We define the middle of the array arr as follows: 8 | 9 | if arr contains an odd number of elements, its middle is the element whose index number is the same when counting from the beginning of the array and from its end; 10 | if arr contains an even number of elements, its middle is the sum of the two elements whose index numbers when counting from the beginning and from the end of the array differ by one. 11 | An array is called smooth if its first and its last elements are equal to one another and to the middle. Given an array arr, determine if it is smooth or not. 12 | 13 | Example 14 | 15 | For arr = [7, 2, 2, 5, 10, 7], the output should be 16 | isSmooth(arr) = true. 17 | 18 | The first and the last elements of arr are equal to 7, and its middle also equals 2 + 5 = 7. Thus, the array is smooth and the output is true. 19 | 20 | For arr = [-5, -5, 10], the output should be 21 | isSmooth(arr) = false. 22 | 23 | The first and middle elements are equal to -5, but the last element equals 10. Thus, arr is not smooth and the output is false. 24 | 25 | Input/Output 26 | 27 | [execution time limit] 4 seconds (py3) 28 | 29 | [input] array.integer arr 30 | 31 | The given array. 32 | 33 | Guaranteed constraints: 34 | 2 ≤ arr.length ≤ 105, 35 | -109 ≤ arr[i] ≤ 109. 36 | 37 | [output] boolean 38 | 39 | true if arr is smooth, false otherwise. 40 | [Python3] Syntax Tips 41 | """ 42 | 43 | import numpy as np 44 | def isSmooth(arr): 45 | if arr[0]!=arr[-1]: 46 | return False 47 | if arr==[]: 48 | return True 49 | elif len(arr)%2==1: 50 | if arr[0]==arr[-1] and arr[0]==arr[int(0.5*len(arr))]: 51 | return True 52 | elif len(arr)%2==0: 53 | if arr[0]==arr[-1] and arr[0]==int(np.sum(arr[int(0.5*len(arr))-1:int(0.5*len(arr))+1])): 54 | return True 55 | return False -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/killKthBit.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat Feb 15 14:29:19 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Implement the missing code, denoted by ellipses. You may not modify the pre-existing code. 8 | In order to stop the Mad Coder evil genius you need to decipher the encrypted message he sent to his minions. The message contains several numbers that, when typed into a supercomputer, will launch a missile into the sky blocking out the sun, and making all the people on Earth grumpy and sad. 9 | 10 | You figured out that some numbers have a modified single digit in their binary representation. More specifically, in the given number n the kth bit from the right was initially set to 0, but its current value might be different. It's now up to you to write a function that will change the kth bit of n back to 0. 11 | 12 | Example 13 | 14 | For n = 37 and k = 3, the output should be 15 | killKthBit(n, k) = 33. 16 | 17 | 3710 = 1001012 ~> 1000012 = 3310. 18 | 19 | For n = 37 and k = 4, the output should be 20 | killKthBit(n, k) = 37. 21 | 22 | The 4th bit is 0 already (looks like the Mad Coder forgot to encrypt this number), so the answer is still 37. 23 | 24 | Input/Output 25 | 26 | [execution time limit] 4 seconds (py3) 27 | 28 | [input] integer n 29 | 30 | Guaranteed constraints: 31 | 0 ≤ n ≤ 231 - 1. 32 | 33 | [input] integer k 34 | 35 | The 1-based index of the changed bit (counting from the right). 36 | 37 | Guaranteed constraints: 38 | 1 ≤ k ≤ 31. 39 | 40 | [output] integer 41 | """ 42 | 43 | def killKthBit(n,k): 44 | return (n if (k>len(bin(n)[2:]) or bin(n)[-k]=='0') else int(bin(n)[:-k]+'0'+bin(n)[-k+1:],2)) 45 | 46 | if __name__=='__main__': 47 | print(killKthBit(0,4)) 48 | print(killKthBit(37,3)) 49 | 50 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/knapsackLight.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 14 01:44:29 2020 4 | 5 | @author: Logan Rowe 6 | 7 | You found two items in a treasure chest! The first item weighs weight1 and is worth value1, and the second item weighs weight2 and is worth value2. What is the total maximum value of the items you can take with you, assuming that your max weight capacity is maxW and you can't come back for the items later? 8 | 9 | Note that there are only two items and you can't bring more than one item of each type, i.e. you can't take two first items or two second items. 10 | 11 | Example 12 | 13 | For value1 = 10, weight1 = 5, value2 = 6, weight2 = 4, and maxW = 8, the output should be 14 | knapsackLight(value1, weight1, value2, weight2, maxW) = 10. 15 | 16 | You can only carry the first item. 17 | 18 | For value1 = 10, weight1 = 5, value2 = 6, weight2 = 4, and maxW = 9, the output should be 19 | knapsackLight(value1, weight1, value2, weight2, maxW) = 16. 20 | 21 | You're strong enough to take both of the items with you. 22 | 23 | For value1 = 5, weight1 = 3, value2 = 7, weight2 = 4, and maxW = 6, the output should be 24 | knapsackLight(value1, weight1, value2, weight2, maxW) = 7. 25 | 26 | You can't take both items, but you can take any of them. 27 | 28 | Input/Output 29 | 30 | [execution time limit] 4 seconds (py3) 31 | 32 | [input] integer value1 33 | 34 | Guaranteed constraints: 35 | 2 ≤ value1 ≤ 20. 36 | 37 | [input] integer weight1 38 | 39 | Guaranteed constraints: 40 | 2 ≤ weight1 ≤ 10. 41 | 42 | [input] integer value2 43 | 44 | Guaranteed constraints: 45 | 2 ≤ value2 ≤ 20. 46 | 47 | [input] integer weight2 48 | 49 | Guaranteed constraints: 50 | 2 ≤ weight2 ≤ 10. 51 | 52 | [input] integer maxW 53 | 54 | Guaranteed constraints: 55 | 1 ≤ maxW ≤ 20. 56 | 57 | [output] integer 58 | """ 59 | 60 | def knapsackLight(value1, weight1, value2, weight2, maxW): 61 | if weight1+weight2<=maxW: 62 | return value1+value2 63 | elif weight1<=maxW and weight2<=maxW: 64 | return max(value1,value2) 65 | elif weight1<=maxW or weight2<=maxW: 66 | d={weight1:value1,weight2:value2} 67 | return(d[min(weight1,weight2)]) 68 | else: 69 | return 0 70 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/largestNumber.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 14 01:07:50 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given an integer n, return the largest number that contains exactly n digits. 8 | 9 | Example 10 | 11 | For n = 2, the output should be 12 | largestNumber(n) = 99. 13 | 14 | Input/Output 15 | 16 | [execution time limit] 4 seconds (py3) 17 | 18 | [input] integer n 19 | 20 | Guaranteed constraints: 21 | 1 ≤ n ≤ 9. 22 | 23 | [output] integer 24 | 25 | The largest integer of length n. 26 | """ 27 | 28 | def largestNumber(n): 29 | return(int('9'*n)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/lastRide.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 14 01:22:56 2020 4 | 5 | @author: Logan Rowe 6 | 7 | One night you go for a ride on your motorcycle. At 00:00 you start your engine, and the built-in timer automatically begins counting the length of your ride, in minutes. Off you go to explore the neighborhood. 8 | 9 | When you finally decide to head back, you realize there's a chance the bridges on your route home are up, leaving you stranded! Unfortunately, you don't have your watch on you and don't know what time it is. All you know thanks to the bike's timer is that n minutes have passed since 00:00. 10 | 11 | Using the bike's timer, calculate the current time. Return an answer as the sum of digits that the digital timer in the format hh:mm would show. 12 | 13 | Example 14 | 15 | For n = 240, the output should be 16 | lateRide(n) = 4. 17 | 18 | Since 240 minutes have passed, the current time is 04:00. The digits sum up to 0 + 4 + 0 + 0 = 4, which is the answer. 19 | 20 | For n = 808, the output should be 21 | lateRide(n) = 14. 22 | 23 | 808 minutes mean that it's 13:28 now, so the answer should be 1 + 3 + 2 + 8 = 14. 24 | 25 | Input/Output 26 | 27 | [execution time limit] 4 seconds (py3) 28 | 29 | [input] integer n 30 | 31 | The duration of your ride, in minutes. It is guaranteed that you've been riding for less than a day (24 hours). 32 | 33 | Guaranteed constraints: 34 | 0 ≤ n < 60 · 24. 35 | 36 | [output] integer 37 | 38 | The sum of the digits the digital timer would show. 39 | """ 40 | 41 | def lateRide(n): 42 | hours=sum([int(i) for i in str(n//60)]) 43 | minutes=sum([int(i) for i in str(n%60)]) 44 | return(hours+minutes) 45 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/leastFactorial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 21 23:28:48 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given an integer n, find the minimal k such that 8 | 9 | k = m! (where m! = 1 * 2 * ... * m) for some integer m; 10 | k >= n. 11 | In other words, find the smallest factorial which is not less than n. 12 | 13 | Example 14 | 15 | For n = 17, the output should be 16 | leastFactorial(n) = 24. 17 | 18 | 17 < 24 = 4! = 1 * 2 * 3 * 4, while 3! = 1 * 2 * 3 = 6 < 17). 19 | 20 | Input/Output 21 | 22 | [execution time limit] 4 seconds (py3) 23 | 24 | [input] integer n 25 | 26 | A positive integer. 27 | 28 | Guaranteed constraints: 29 | 1 ≤ n ≤ 120. 30 | 31 | [output] integer 32 | """ 33 | 34 | def leastFactorial(n): 35 | i=1 36 | val=1 37 | while val=threshold-experience 43 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/removeArrayPart.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 27 23:58:56 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Remove a part of a given array between given 0-based indexes l and r (inclusive). 8 | 9 | Example 10 | 11 | For inputArray = [2, 3, 2, 3, 4, 5], l = 2, and r = 4, the output should be 12 | removeArrayPart(inputArray, l, r) = [2, 3, 5]. 13 | 14 | Input/Output 15 | 16 | [execution time limit] 4 seconds (py3) 17 | 18 | [input] array.integer inputArray 19 | 20 | Guaranteed constraints: 21 | 2 ≤ inputArray.length ≤ 104, 22 | -105 ≤ inputArray[i] ≤ 105. 23 | 24 | [input] integer l 25 | 26 | Left index of the part to be removed (0-based). 27 | 28 | Guaranteed constraints: 29 | 0 ≤ l ≤ r. 30 | 31 | [input] integer r 32 | 33 | Right index of the part to be removed (0-based). 34 | 35 | Guaranteed constraints: 36 | l ≤ r < inputArray.length. 37 | 38 | [output] array.integer 39 | """ 40 | 41 | def removeArrayPart(inputArray, l, r): 42 | return inputArray[:l]+inputArray[r+1:] -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/replaceMiddle.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 28 00:11:53 2020 4 | 5 | @author: Logan Rowe 6 | 7 | We define the middle of the array arr as follows: 8 | 9 | if arr contains an odd number of elements, its middle is the element whose index number is the same when counting from the beginning of the array and from its end; 10 | if arr contains an even number of elements, its middle is the sum of the two elements whose index numbers when counting from the beginning and from the end of the array differ by one. 11 | Given array arr, your task is to find its middle, and, if it consists of two elements, replace those elements with the value of middle. Return the resulting array as the answer. 12 | 13 | Example 14 | 15 | For arr = [7, 2, 2, 5, 10, 7], the output should be 16 | replaceMiddle(arr) = [7, 2, 7, 10, 7]. 17 | 18 | The middle consists of two elements, 2 and 5. These two elements should be replaced with their sum, i.e. 7. 19 | 20 | For arr = [-5, -5, 10], the output should be 21 | replaceMiddle(arr) = [-5, -5, 10]. 22 | 23 | The middle is defined as a single element -5, so the initial array with no changes should be returned. 24 | 25 | Input/Output 26 | 27 | [execution time limit] 4 seconds (py3) 28 | 29 | [input] array.integer arr 30 | 31 | The given array. 32 | 33 | Guaranteed constraints: 34 | 2 ≤ arr.length ≤ 104, 35 | -103 ≤ arr[i] ≤ 103. 36 | 37 | [output] array.integer 38 | 39 | arr with its middle replaced by a single element, or the initial array if the middle consisted of a single element to begin with. 40 | """ 41 | 42 | import numpy as np 43 | def replaceMiddle(arr): 44 | return arr[:int(0.5*len(arr))-1]+[np.sum(arr[int(0.5*len(arr))-1:int(0.5*len(arr))+1])]+arr[int(0.5*len(arr))+1:] if len(arr)%2==0 else arr -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/rounders.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 26 23:42:50 2020 4 | 5 | @author: Logan Rowe 6 | 7 | We want to turn the given integer into a number that has only one non-zero digit using a tail rounding approach. This means that at each step we take the last non 0 digit of the number and round it to 0 or to 10. If it's less than 5 we round it to 0 if it's larger than or equal to 5 we round it to 10 (rounding to 10 means increasing the next significant digit by 1). The process stops immediately once there is only one non-zero digit left. 8 | 9 | Example 10 | 11 | For n = 15, the output should be 12 | rounders(n) = 20; 13 | 14 | For n = 1234, the output should be 15 | rounders(n) = 1000. 16 | 17 | 1234 -> 1230 -> 1200 -> 1000. 18 | 19 | For n = 1445, the output should be 20 | rounders(n) = 2000. 21 | 22 | 1445 -> 1450 -> 1500 -> 2000. 23 | 24 | Input/Output 25 | 26 | [execution time limit] 4 seconds (py3) 27 | 28 | [input] integer n 29 | 30 | A positive integer. 31 | 32 | Guaranteed constraints: 33 | 1 ≤ value ≤ 108. 34 | 35 | [output] integer 36 | 37 | The rounded number. 38 | """ 39 | 40 | def rounders(n): 41 | count=-1 42 | n=[str(i) for i in str(n)] 43 | while len(n)>n.count('0')+1: 44 | if int(n[count])>=5: 45 | n[count]='0' 46 | n[count-1]=str(int(n[count-1])+1) 47 | else: 48 | n[count]='0' 49 | count-=1 50 | return(int(''.join(n))) 51 | 52 | print(rounders(1445)) 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/seatsInTheater.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 14 01:12:33 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Your friend advised you to see a new performance in the most popular theater in the city. He knows a lot about art and his advice is usually good, but not this time: the performance turned out to be awfully dull. It's so bad you want to sneak out, which is quite simple, especially since the exit is located right behind your row to the left. All you need to do is climb over your seat and make your way to the exit. 8 | 9 | The main problem is your shyness: you're afraid that you'll end up blocking the view (even if only for a couple of seconds) of all the people who sit behind you and in your column or the columns to your left. To gain some courage, you decide to calculate the number of such people and see if you can possibly make it to the exit without disturbing too many people. 10 | 11 | Given the total number of rows and columns in the theater (nRows and nCols, respectively), and the row and column you're sitting in, return the number of people who sit strictly behind you and in your column or to the left, assuming all seats are occupied. 12 | 13 | Example 14 | 15 | For nCols = 16, nRows = 11, col = 5, and row = 3, the output should be 16 | seatsInTheater(nCols, nRows, col, row) = 96. 17 | 18 | Here is what the theater looks like: 19 | 20 | 21 | Input/Output 22 | 23 | [execution time limit] 4 seconds (py3) 24 | 25 | [input] integer nCols 26 | 27 | An integer, the number of theater's columns. 28 | 29 | Guaranteed constraints: 30 | 1 ≤ nCols ≤ 1000. 31 | 32 | [input] integer nRows 33 | 34 | An integer, the number of theater's rows. 35 | 36 | Guaranteed constraints: 37 | 1 ≤ nRows ≤ 1000. 38 | 39 | [input] integer col 40 | 41 | An integer, the column number of your own seat (1-based). 42 | 43 | Guaranteed constraints: 44 | 1 ≤ col ≤ nCols. 45 | 46 | [input] integer row 47 | 48 | An integer, the row number of your own seat (1-based). 49 | 50 | Guaranteed constraints: 51 | 1 ≤ row ≤ nRows. 52 | 53 | [output] integer 54 | 55 | The number of people who sit strictly behind you and in your column or to the left. 56 | """ 57 | 58 | def seatsInTheater(nCols, nRows, col, row): 59 | blocked_col=nCols-col+1 60 | blocked_row=nRows-row 61 | return(blocked_col*blocked_row) 62 | 63 | if __name__=='__main__': 64 | nCols=16 65 | nRows=11 66 | col=5 67 | row=3 68 | 69 | print(seatsInTheater(nCols,nRows,col,row)) -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/secondRightmostZeroBit.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Feb 18 12:40:20 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Implement the missing code, denoted by ellipses. You may not modify the pre-existing code. 8 | Presented with the integer n, find the 0-based position of the second rightmost zero bit in its binary representation (it is guaranteed that such a bit exists), counting from right to left. 9 | 10 | Return the value of 2position_of_the_found_bit. 11 | 12 | Example 13 | 14 | For n = 37, the output should be 15 | secondRightmostZeroBit(n) = 8. 16 | 17 | 3710 = 1001012. The second rightmost zero bit is at position 3 (0-based) from the right in the binary representation of n. 18 | Thus, the answer is 23 = 8. 19 | 20 | Input/Output 21 | 22 | [execution time limit] 4 seconds (py3) 23 | 24 | [input] integer n 25 | 26 | Guaranteed constraints: 27 | 4 ≤ n ≤ 230. 28 | 29 | [output] integer 30 | """ 31 | 32 | 33 | 34 | def secondRightmostZeroBit(n): 35 | n=bin(n)[2:][::-1] 36 | string1=n[:n.find('0')+1] 37 | n2=n[len(string1):] 38 | string2=n2[:n2.find('0')+1] 39 | power=len(string1)+len(string2)-1 40 | return 2**power 41 | 42 | def secondRightmostZeroBit_oneLine(n): 43 | return 2**(len(bin(n)[2:][::-1][:bin(n)[2:][::-1].find('0')+1])+len(bin(n)[2:][::-1][len(bin(n)[2:][::-1][:bin(n)[2:][::-1].find('0')+1]):][:bin(n)[2:][::-1][len(bin(n)[2:][::-1][:bin(n)[2:][::-1].find('0')+1]):].find('0')+1])-1) 44 | 45 | if __name__=='__main__': 46 | n=[37,1073741824,4] 47 | for val in n: 48 | print(secondRightmostZeroBit_oneLine(val)) 49 | print() -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/swapAdjacentBits.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 19 11:32:55 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Implement the missing code, denoted by ellipses. You may not modify the pre-existing code. 8 | You're given an arbitrary 32-bit integer n. Take its binary representation, split bits into it in pairs (bit number 0 and 1, bit number 2 and 3, etc.) and swap bits in each pair. Then return the result as a decimal number. 9 | 10 | Example 11 | 12 | For n = 13, the output should be 13 | swapAdjacentBits(n) = 14. 14 | 15 | 1310 = 11012 ~> {11}{01}2 ~> 11102 = 1410. 16 | 17 | For n = 74, the output should be 18 | swapAdjacentBits(n) = 133. 19 | 20 | 7410 = 010010102 ~> {01}{00}{10}{10}2 ~> 100001012 = 13310. 21 | Note the preceding zero written in front of the initial number: since both numbers are 32-bit integers, they have 32 bits in their binary representation. The preceding zeros in other cases don't matter, so they are omitted. Here, however, it does make a difference. 22 | 23 | Input/Output 24 | 25 | [execution time limit] 4 seconds (py3) 26 | 27 | [input] integer n 28 | 29 | Guaranteed constraints: 30 | 0 ≤ n < 230. 31 | 32 | [output] integer 33 | """ 34 | 35 | def swapAdjacentBits_multiline(n): 36 | pref=bin(n).split('b')[0]+'b' 37 | suff=bin(n).split('b')[1][::-1]+'0'*len(bin(n).split('b')[1]) 38 | val=pref+''.join([suff[2*idx:2*idx+2][::-1] for idx in range(int(0.5*len(bin(n))))])[::-1] 39 | return int(val,2) 40 | 41 | def swapAdjacentBits(n): 42 | return int(bin(n).split('b')[0]+'b'+''.join([str(bin(n).split('b')[1][::-1]+'0'*len(bin(n).split('b')[1]))[2*idx:2*idx+2][::-1] for idx in range(int(0.5*len(bin(n))))])[::-1],2) 43 | 44 | if __name__=='__main__': 45 | vals=[13,74] 46 | output=[14,133] 47 | for n,out in zip(vals,output): 48 | print(swapAdjacentBits(n)) 49 | print(swapAdjacentBits(n)==out) 50 | print() 51 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/tennisSet.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat Feb 15 14:08:07 2020 4 | 5 | @author: Logan Rowe 6 | 7 | In tennis, the winner of a set is based on how many games each player wins. The first player to win 6 games is declared the winner unless their opponent had already won 5 games, in which case the set continues until one of the players has won 7 games. 8 | 9 | Given two integers score1 and score2, your task is to determine if it is possible for a tennis set to be finished with a final score of score1 : score2. 10 | 11 | Example 12 | 13 | For score1 = 3 and score2 = 6, the output should be 14 | tennisSet(score1, score2) = true. 15 | 16 | Since player 1 hadn't reached 5 wins, the set ends once player 2 has won 6 games. 17 | 18 | For score1 = 8 and score2 = 5, the output should be 19 | tennisSet(score1, score2) = false. 20 | 21 | Since both players won at least 5 games, the set would've ended once one of them won the 7th one. 22 | 23 | For score1 = 6 and score2 = 5, the output should be 24 | tennisSet(score1, score2) = false. 25 | 26 | This set will continue until one of these players wins their 7th game, so this can't be the final score. 27 | 28 | Input/Output 29 | 30 | [execution time limit] 4 seconds (py3) 31 | 32 | [input] integer score1 33 | 34 | Number of games won by the 1st player, non-negative integer. 35 | 36 | Guaranteed constraints: 37 | 0 ≤ score1 ≤ 10. 38 | 39 | [input] integer score2 40 | 41 | Number of games won by the 2nd player, non-negative integer. 42 | 43 | Guaranteed constraints: 44 | 0 ≤ score2 ≤ 10. 45 | 46 | [output] boolean 47 | 48 | true if score1 : score2 represents a possible score for an ended set, false otherwise. 49 | """ 50 | 51 | def tennisSet(score1, score2): 52 | if score1>7 or score2>7 or (score1>6 and score2<5) or (score2>6 and score1<5): 53 | return False 54 | if (score1==5 and score2==6) or (score1==6 and score2==5) or score1==score2==7 or (score1<6 and score2<6) or score1==score2==6: 55 | return False 56 | return True 57 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/untitled2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 27 23:52:04 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Reversing an array can be a tough task, especially for a novice programmer. Mary just started coding, so she would like to start with something basic at first. Instead of reversing the array entirely, she wants to swap just its first and last elements. 8 | 9 | Given an array arr, swap its first and last elements and return the resulting array. 10 | 11 | Example 12 | 13 | For arr = [1, 2, 3, 4, 5], the output should be 14 | firstReverseTry(arr) = [5, 2, 3, 4, 1]. 15 | 16 | Input/Output 17 | 18 | [execution time limit] 4 seconds (py3) 19 | 20 | [input] array.integer arr 21 | 22 | Guaranteed constraints: 23 | 0 ≤ arr.length ≤ 50, 24 | -104 ≤ arr[i] ≤ 104. 25 | 26 | [output] array.integer 27 | 28 | Array arr with its first and its last elements swapped. 29 | [Python3] Syntax Tips 30 | """ 31 | 32 | def firstReverseTry(arr): 33 | if arr==[]: 34 | return arr 35 | arr[-1],arr[0]=arr[0],arr[-1] 36 | return arr -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/easy/weakNumbers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Mar 3 11:57:56 2020 4 | 5 | @author: Logan Rowe 6 | 7 | We define the weakness of number x as the number of positive integers smaller than x that have more divisors than x. 8 | 9 | It follows that the weaker the number, the greater overall weakness it has. For the given integer n, you need to answer two questions: 10 | 11 | what is the weakness of the weakest numbers in the range [1, n]? 12 | how many numbers in the range [1, n] have this weakness? 13 | Return the answer as an array of two elements, where the first element is the answer to the first question, and the second element is the answer to the second question. 14 | 15 | Example 16 | 17 | For n = 9, the output should be 18 | weakNumbers(n) = [2, 2]. 19 | 20 | Here are the number of divisors and the specific weakness of each number in range [1, 9]: 21 | 22 | 1: d(1) = 1, weakness(1) = 0; 23 | 2: d(2) = 2, weakness(2) = 0; 24 | 3: d(3) = 2, weakness(3) = 0; 25 | 4: d(4) = 3, weakness(4) = 0; 26 | 5: d(5) = 2, weakness(5) = 1; 27 | 6: d(6) = 4, weakness(6) = 0; 28 | 7: d(7) = 2, weakness(7) = 2; 29 | 8: d(8) = 4, weakness(8) = 0; 30 | 9: d(9) = 3, weakness(9) = 2. 31 | As you can see, the maximal weakness is 2, and there are 2 numbers with that weakness level. 32 | 33 | Input/Output 34 | 35 | [execution time limit] 4 seconds (py3) 36 | 37 | [input] integer n 38 | 39 | Guaranteed constraints: 40 | 1 ≤ n ≤ 1000. 41 | 42 | [output] array.integer 43 | 44 | Array of two elements: the weakness of the weakest number, and the number of integers in range [1, n] with this weakness. 45 | """ 46 | 47 | import numpy as np 48 | 49 | def divisors(n): 50 | return sum([n//i==n/i for i in range(1,n//2+1)]) 51 | 52 | def weakness(div,idx): 53 | div_n=div[idx] 54 | weakness=sum([div_n=fcn(n,m,x2): 80 | black_box_count+=1 81 | 82 | return black_box_count 83 | 84 | 85 | n_vals=[3,3,66666] 86 | m_vals=[4,3,88888] 87 | results=[6,7,177774] 88 | 89 | for (n,m,r) in zip(n_vals,m_vals,results): 90 | print(countBlackCells(n,m)) 91 | print(r) 92 | print() 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/medium/countBlackCells_efficient.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 27 00:19:23 2020 4 | 5 | @author: Logan Rowe 6 | 7 | magine a white rectangular grid of n rows and m columns divided into two parts by a diagonal line running from the upper left to the lower right corner. Now let's paint the grid in two colors according to the following rules: 8 | 9 | A cell is painted black if it has at least one point in common with the diagonal; 10 | Otherwise, a cell is painted white. 11 | Count the number of cells painted black. 12 | 13 | Example 14 | 15 | For n = 3 and m = 4, the output should be 16 | countBlackCells(n, m) = 6. 17 | 18 | There are 6 cells that have at least one common point with the diagonal and therefore are painted black. 19 | 20 | 21 | 22 | For n = 3 and m = 3, the output should be 23 | countBlackCells(n, m) = 7. 24 | 25 | 7 cells have at least one common point with the diagonal and are painted black. 26 | 27 | 28 | 29 | Input/Output 30 | 31 | [execution time limit] 4 seconds (py3) 32 | 33 | [input] integer n 34 | 35 | The number of rows. 36 | 37 | Guaranteed constraints: 38 | 1 ≤ n ≤ 105. 39 | 40 | [input] integer m 41 | 42 | The number of columns. 43 | 44 | Guaranteed constraints: 45 | 1 ≤ m ≤ 105. 46 | 47 | [output] integer 48 | 49 | The number of black cells. 50 | """ 51 | 52 | ''' 53 | This approach works... and i thought it was neatly done 54 | 55 | However, for very large inputs the use of itertools product function 56 | takes a long time to run, I will find a more efficient solution. 57 | ''' 58 | 59 | from math import gcd 60 | 61 | def countBlackCells(n, m): 62 | return m+n+gcd(m,n)-2 63 | 64 | 65 | n_vals=[3,3,66666] 66 | m_vals=[4,3,88888] 67 | results=[6,7,177774] 68 | 69 | for (n,m,r) in zip(n_vals,m_vals,results): 70 | print(countBlackCells(n,m)) 71 | print(r) 72 | print() 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/medium/differentRightMostBit.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 20 00:53:53 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Implement the missing code, denoted by ellipses. You may not modify the pre-existing code. 8 | You're given two integers, n and m. Find position of the rightmost bit in which they differ in their binary representations (it is guaranteed that such a bit exists), counting from right to left. 9 | 10 | Return the value of 2position_of_the_found_bit (0-based). 11 | 12 | Example 13 | 14 | For n = 11 and m = 13, the output should be 15 | differentRightmostBit(n, m) = 2. 16 | 17 | 1110 = 10112, 1310 = 11012, the rightmost bit in which they differ is the bit at position 1 (0-based) from the right in the binary representations. 18 | So the answer is 21 = 2. 19 | 20 | For n = 7 and m = 23, the output should be 21 | differentRightmostBit(n, m) = 16. 22 | 23 | 710 = 1112, 2310 = 101112, i.e. 24 | 25 | 00111 26 | 10111 27 | So the answer is 24 = 16. 28 | 29 | Input/Output 30 | 31 | [execution time limit] 4 seconds (py3) 32 | 33 | [input] integer n 34 | 35 | Guaranteed constraints: 36 | 0 ≤ n ≤ 230. 37 | 38 | [input] integer m 39 | 40 | Guaranteed constraints: 41 | 0 ≤ m ≤ 230, 42 | n ≠ m. 43 | 44 | [output] integer 45 | """ 46 | 47 | def differentRightmostBit_long(n, m): 48 | n=bin(n)[2:][::-1] 49 | m=bin(m)[2:][::-1] 50 | p=[int(i[0])^int(i[1]) for i in zip(m,n)] 51 | 52 | 53 | return 2**p.index(1) if 1 in p else 2**min(len(n)+1,len(m)+1) 54 | 55 | def differentRightmostBit(n, m): 56 | return 2**[int(i[0])^int(i[1]) for i in zip(bin(m)[2:][::-1],bin(n)[2:][::-1])].index(1) if 1 in [int(i[0])^int(i[1]) for i in zip(bin(m)[2:][::-1],bin(n)[2:][::-1])] else 2**min(len(bin(n)[2:][::-1])+1,len(bin(m)[2:][::-1])+1) 57 | 58 | 59 | if __name__=='__main__': 60 | n=[11,7,1] 61 | m=[13,23,0] 62 | ans=[2,16,1] 63 | for (i,j) in zip(n,m): 64 | print(differentRightmostBit(i,j)) 65 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/medium/equalPairOfBits.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 21 01:26:30 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Implement the missing code, denoted by ellipses. You may not modify the pre-existing code. 8 | You're given two integers, n and m. Find position of the rightmost pair of equal bits in their binary representations (it is guaranteed that such a pair exists), counting from right to left. 9 | 10 | Return the value of 2position_of_the_found_pair (0-based). 11 | 12 | Example 13 | 14 | For n = 10 and m = 11, the output should be 15 | equalPairOfBits(n, m) = 2. 16 | 17 | 1010 = 10102, 1110 = 10112, the position of the rightmost pair of equal bits is the bit at position 1 (0-based) from the right in the binary representations. 18 | So the answer is 21 = 2. 19 | 20 | Input/Output 21 | 22 | [execution time limit] 4 seconds (py3) 23 | 24 | [input] integer n 25 | 26 | Guaranteed constraints: 27 | 0 ≤ n ≤ 230. 28 | 29 | [input] integer m 30 | 31 | Guaranteed constraints: 32 | 0 ≤ m ≤ 230. 33 | 34 | [output] integer 35 | """ 36 | 37 | def equalPairOfBits(n, m): 38 | return 2**[int(i[0])&int(i[1]) for i in zip(bin(m)[2:][::-1],bin(n)[2:][::-1])].index(1) if 1 in [int(i[0])&int(i[1]) for i in zip(bin(m)[2:][::-1],bin(n)[2:][::-1])] else 2**min(len(bin(n)[2:][::-1])+1,len(bin(m)[2:][::-1])+1) 39 | -------------------------------------------------------------------------------- /old_practice_problems/arcade/the-core/medium/isSumOfConsecutive2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 28 23:40:11 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Find the number of ways to express n as sum of some (at least two) consecutive positive integers. 8 | 9 | Example 10 | 11 | For n = 9, the output should be 12 | isSumOfConsecutive2(n) = 2. 13 | 14 | There are two ways to represent n = 9: 2 + 3 + 4 = 9 and 4 + 5 = 9. 15 | 16 | For n = 8, the output should be 17 | isSumOfConsecutive2(n) = 0. 18 | 19 | There are no ways to represent n = 8. 20 | 21 | Input/Output 22 | 23 | [execution time limit] 4 seconds (py3) 24 | 25 | [input] integer n 26 | 27 | A positive integer. 28 | 29 | Guaranteed constraints: 30 | 1 ≤ n ≤ 104. 31 | 32 | [output] integer 33 | """ 34 | 35 | def isSumOfConsecutive2(n): 36 | possible_combinations=0 37 | start=int(n/2)+2 38 | tail=start 39 | numbers=[] 40 | while start>=0: 41 | if sum(numbers)>n or tail<=0: 42 | numbers=[] 43 | start-=1 44 | tail=start 45 | elif sum(numbers)0: 53 | if numberOfDigits 10 -> 1 -> 1, 4 elements altogether. 33 | 34 | Input/Output 35 | 36 | [execution time limit] 4 seconds (py3) 37 | 38 | [input] integer a0 39 | 40 | First element of a sequence, positive integer. 41 | 42 | Guaranteed constraints: 43 | 1 ≤ a0 ≤ 105. 44 | 45 | [output] integer 46 | """ 47 | 48 | def squareDigitsSequence(a0): 49 | elements=[a0] 50 | a=a0 51 | while True: 52 | a=sum([int(i)**2 for i in str(a)]) 53 | elements.append(a) 54 | if elements.count(a)>1: 55 | break 56 | 57 | return len(elements) 58 | -------------------------------------------------------------------------------- /old_practice_problems/daily-challenges/stringPermutations.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 21 22:33:03 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Avoid using C++'s std::next_permutation or similar features in other languages 8 | to solve this challenge. Implement the algorithm yourself, since this is what 9 | you would be asked to do during a real interview. 10 | 11 | Given a string s, find all its potential permutations. The output should be 12 | sorted in lexicographical order. 13 | 14 | Example 15 | 16 | For s = "CBA", the output should be 17 | stringPermutations(s) = ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]; 18 | For s = "ABA", the output should be 19 | stringPermutations(s) = ["AAB", "ABA", "BAA"]. 20 | Input/Output 21 | 22 | [execution time limit] 4 seconds (py3) 23 | 24 | [input] string s 25 | 26 | A string containing only capital letters. 27 | 28 | Guaranteed constraints: 29 | 1 ≤ s.length ≤ 5. 30 | 31 | [output] array.string 32 | 33 | All permutations of s, sorted in lexicographical order. 34 | """ 35 | 36 | def stringPermutations(s): 37 | 38 | s=list(s) 39 | 40 | #Lock each letter in s at the front of the list 41 | for idx in range(len(s)): 42 | t=s[idx]+s[:idx]+s[idx+1:] 43 | 44 | #swap the second letter with all letters that come after it in s 45 | for idx2 in range(len(s)-1): 46 | t=t[:idx2]+t[idx2+1:] 47 | 48 | 49 | if __name__=='__main__': 50 | stringPermutations('ABC') 51 | 52 | for permutation in stringPermutations('ABC'): 53 | print(permutation) -------------------------------------------------------------------------------- /old_practice_problems/data-structures/arrays/first-non-repeating-character.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 5 23:14:34 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Find the index of the first non-repeating character in a string 8 | 9 | example strings: 10 | 'aaabccc' --> b 11 | 'aabbaazaa' --> z 12 | 13 | only lowercase alphabetical characters no numbers or symbols. 14 | 15 | net coding time: 5 minutes 16 | """ 17 | 18 | def first_nonsequential_repeat_char(string): 19 | previous_letter=string[0] 20 | count=1 21 | for letter in string[0:]: 22 | if letter==previous_letter or (letter!=previous_letter and letter==string[count+1]): 23 | previous_letter=letter 24 | count+=1 25 | else: 26 | return(letter+' : '+str(count-1)) 27 | 28 | ''' 29 | A little more difficult: 30 | 31 | Find the first non-repeating character including all characters in the string. 32 | 33 | example strings: 34 | 'aaabcccdeeef' --> b 35 | 'abcbad' --> c 36 | 'abcabcabc' --> None 37 | 38 | net coding time: 15 minutes 39 | ''' 40 | 41 | #build a dictionary {'letter':# of appearances} 42 | def first_non_repeat_char(string): 43 | letter_dict={} 44 | for letter in string: 45 | if letter not in letter_dict: 46 | letter_dict[letter]=1 47 | else: 48 | letter_dict[letter]+=1 49 | 50 | #Cycle through string once to find first occurence of non-repeating letter 51 | non_repeats=[letter for letter in letter_dict if letter_dict[letter]==1] 52 | for letter in string: 53 | if letter in non_repeats: 54 | return(letter+' : '+str(string.index(letter))) 55 | 56 | if __name__ == '__main__': 57 | strings=['aaaajiiiidddduuuufgggjkk','aaabbbcccdeeed'] 58 | for string in strings: 59 | print(first_nonsequential_repeat_char(string)) 60 | print(first_non_repeat_char(string)) 61 | print() -------------------------------------------------------------------------------- /old_practice_problems/data-structures/arrays/firstDuplicate.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 6 00:03:30 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given an array a that contains only numbers in the range from 1 to a.length, 8 | find the first duplicate number for which the second occurrence has the minimal index. 9 | In other words, if there are more than 1 duplicated numbers, 10 | return the number for which the second occurrence has a smaller index than the 11 | second occurrence of the other number does. If there are no such elements, return -1. 12 | 13 | For a = [2, 1, 3, 5, 3, 2], the output should be firstDuplicate(a) = 3. 14 | 15 | net coding time: 5 minutes 16 | """ 17 | 18 | import numpy as np 19 | 20 | def firstDuplicate(a): 21 | number_dictionary={} 22 | for number in a: 23 | if number not in number_dictionary: 24 | number_dictionary[number]=1 25 | elif number in number_dictionary: 26 | #first duplicate found 27 | return(number) 28 | #no duplicates found 29 | return(-1) 30 | 31 | if __name__ == '__main__': 32 | a=np.array([2,1,3,5,3,2]) 33 | print(firstDuplicate(a)) -------------------------------------------------------------------------------- /old_practice_problems/data-structures/arrays/intro-questions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 5 23:58:44 2020 4 | 5 | @author: Logan Rowe 6 | """ 7 | 8 | #Write a function that returns the sum of two numbers 9 | def add(param1,param2): 10 | return(param1+param2) -------------------------------------------------------------------------------- /old_practice_problems/data-structures/arrays/rotate-image.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 6 00:17:31 2020 4 | 5 | @author: Logan Rowe 6 | """ 7 | 8 | ''' 9 | Note: Try to solve this task in-place (with O(1) additional memory), 10 | since this is what you'll be asked to do during an interview. 11 | 12 | You are given an n x n 2D matrix that represents an image. 13 | Rotate the image by 90 degrees (clockwise). 14 | 15 | For 16 | 17 | a = [[1, 2, 3], 18 | [4, 5, 6], 19 | [7, 8, 9]] 20 | the output should be 21 | 22 | rotateImage(a) = 23 | [[7, 4, 1], 24 | [8, 5, 2], 25 | [9, 6, 3]] 26 | ''' 27 | 28 | ''' 29 | Thoughts: 30 | 31 | we know it is a square matrix (n x n) so lets see if we can find a pattern 32 | that uses the dimensions of the matrix to relate the start index to the 33 | rotated index 34 | 35 | 0,0 --> 0,2 36 | 0,1 --> 1,2 37 | 2,0 --> 0,0 38 | 1,1 --> 1,1 39 | 1,2 --> 2,1 40 | 41 | 42 | rule is ( start_index[1] , (n-1)-start_index[0] ) 43 | (a[column] , (n-1)-a[row]) 44 | 45 | net coding time: 15 minutes 46 | ''' 47 | 48 | import numpy as np 49 | 50 | def rotateImage(a): 51 | n=a.shape[0] 52 | b=np.full((n,n),0) 53 | r=0 54 | while r < n: 55 | c=0 56 | while c < n: 57 | b[c,(n-1)-r]=a[r,c] 58 | c+=1 59 | r+=1 60 | return(b) 61 | 62 | 63 | 64 | 65 | 66 | if __name__ == '__main__': 67 | a=np.array([[1, 2, 3], 68 | [4, 5, 6], 69 | [7, 8, 9]]) 70 | 71 | print(a) 72 | print() 73 | print(rotateImage(a)) 74 | print('\nyay') -------------------------------------------------------------------------------- /old_practice_problems/data-structures/hash-tables/areFollowingPatterns.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 13 18:51:26 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given an array strings, determine whether it follows the sequence given in the 8 | patterns array. In other words, there should be no i and j for which 9 | strings[i] = strings[j] and patterns[i] ≠ patterns[j] or for which 10 | strings[i] ≠ strings[j] and patterns[i] = patterns[j]. 11 | 12 | Example 13 | 14 | For strings = ["cat", "dog", "dog"] and patterns = ["a", "b", "b"], the output should be 15 | areFollowingPatterns(strings, patterns) = true; 16 | For strings = ["cat", "dog", "doggy"] and patterns = ["a", "b", "b"], the output should be 17 | areFollowingPatterns(strings, patterns) = false. 18 | Input/Output 19 | 20 | [execution time limit] 4 seconds (py3) 21 | 22 | [input] array.string strings 23 | 24 | An array of strings, each containing only lowercase English letters. 25 | 26 | Guaranteed constraints: 27 | 1 ≤ strings.length ≤ 105, 28 | 1 ≤ strings[i].length ≤ 10. 29 | 30 | [input] array.string patterns 31 | 32 | An array of pattern strings, each containing only lowercase English letters. 33 | 34 | Guaranteed constraints: 35 | patterns.length = strings.length, 36 | 1 ≤ patterns[i].length ≤ 10. 37 | 38 | [output] boolean 39 | 40 | Return true if strings follows patterns and false otherwise. 41 | """ 42 | 43 | def areFollowingPatterns(strings, patterns): 44 | if len(set(patterns))!=len(set(strings)): 45 | return False 46 | 47 | d={} 48 | for s,p in zip(strings,patterns): 49 | if s in d and d[s]!=p: 50 | print(s,d[s],p) 51 | return False 52 | d[s]=p 53 | 54 | 55 | return True 56 | 57 | if __name__=='__main__': 58 | strings=["cat", 59 | "dog", 60 | "doggy"] 61 | patterns=["a", 62 | "b", 63 | "b"] 64 | 65 | print(areFollowingPatterns(strings,patterns)) -------------------------------------------------------------------------------- /old_practice_problems/data-structures/hash-tables/containsCloseNums.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 13 19:10:19 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given an array of integers nums and an integer k, determine whether there are 8 | two distinct indices i and j in the array where nums[i] = nums[j] and the 9 | absolute difference between i and j is less than or equal to k. 10 | 11 | Example 12 | 13 | For nums = [0, 1, 2, 3, 5, 2] and k = 3, the output should be 14 | containsCloseNums(nums, k) = true. 15 | 16 | There are two 2s in nums, and the absolute difference between their positions is exactly 3. 17 | 18 | For nums = [0, 1, 2, 3, 5, 2] and k = 2, the output should be 19 | containsCloseNums(nums, k) = false. 20 | 21 | The absolute difference between the positions of the two 2s is 3, which is more than k. 22 | 23 | Input/Output 24 | 25 | [execution time limit] 4 seconds (py3) 26 | 27 | [input] array.integer nums 28 | 29 | Guaranteed constraints: 30 | 0 ≤ nums.length ≤ 55000, 31 | -231 - 1 ≤ nums[i] ≤ 231 - 1. 32 | 33 | [input] integer k 34 | 35 | Guaranteed constraints: 36 | 0 ≤ k ≤ 35000. 37 | 38 | [output] boolean 39 | """ 40 | 41 | ''' 42 | convert nums to a dictionary where d={number:[indices],number2:[indices],...} 43 | ''' 44 | 45 | def absDiff(int_list): 46 | absDiff=[] 47 | for index in range(len(int_list)): 48 | start=int_list[index] 49 | end=int_list[:index]+int_list[index+1:] 50 | for value in end: 51 | absDiff.append(abs(start-value)) 52 | 53 | return(min(absDiff)) 54 | 55 | def containsCloseNums(nums, k): 56 | 57 | num_dict={num:[] for num in nums} 58 | 59 | index=0 60 | for num in nums: 61 | num_dict[num].append(index) 62 | index+=1 63 | 64 | #iterate throug heach key in the dictionary 65 | for num in num_dict: 66 | #if there was more than one occurence of the number check the distance between indices 67 | if len(num_dict[num])>1: 68 | if absDiff(num_dict[num])<=k: 69 | return True 70 | return False 71 | 72 | 73 | 74 | 75 | if __name__=='__main__': 76 | nums = [[0, 1, 2, 3, 5, 2], [0, 1, 2, 3, 5, 2]] 77 | ks=[3,2] 78 | for (num,k) in zip(nums,ks): 79 | print(containsCloseNums(num,k)) 80 | 81 | int_list=[1,2,3] 82 | print(absDiff(int_list)) 83 | -------------------------------------------------------------------------------- /old_practice_problems/data-structures/hash-tables/groupingDishes.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 13 01:16:34 2020 4 | 5 | @author: Logan Rowe 6 | """ 7 | def groupingDishes(dishes): 8 | dish_dict={} 9 | for dish in dishes: 10 | dish_dict[dish[0]]=dish[1:] 11 | 12 | ingredients=[] 13 | for value in dish_dict.values(): 14 | ingredients.extend(value) 15 | 16 | #Lets narrow our list down to only ingredients that are in 2 or more dishes 17 | ingredient_dict={ingredient:[] for (ingredient,count) in zip(set(ingredients),[ingredients.count(ingredient) for ingredient in set(ingredients)]) if count>1} 18 | 19 | for key in [*dish_dict.keys()]: 20 | for value in dish_dict[key]: 21 | for ingredient in ingredient_dict: 22 | if ingredient == value: 23 | ingredient_dict[ingredient]=[*ingredient_dict[ingredient],key] 24 | 25 | ingredient_dict=[[key]+[*sorted(ingredient_dict[key])] for key in ingredient_dict] 26 | ingredient_dict=sorted(ingredient_dict) 27 | 28 | return(ingredient_dict) 29 | 30 | 31 | 32 | 33 | 34 | if __name__=='__main__': 35 | dishes=[["Pasta","Tomato Sauce","Onions","Garlic"], 36 | ["Chicken Curry","Chicken","Curry Sauce"], 37 | ["Fried Rice","Rice","Onions","Nuts"], 38 | ["Salad","Spinach","Nuts"], 39 | ["Sandwich","Cheese","Bread"], 40 | ["Quesadilla","Chicken","Cheese"]] 41 | 42 | print(groupingDishes(dishes)) -------------------------------------------------------------------------------- /old_practice_problems/data-structures/hash-tables/hash_table_intro.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Feb 12 23:16:54 2020 4 | 5 | @author: Logan Rowe 6 | 7 | methods: 8 | hash 9 | insert 10 | find 11 | remove 12 | """ 13 | 14 | INITIAL_CAPACITY=50 15 | 16 | class Node: 17 | def __init__(self,key,value): 18 | self.key=key 19 | self.value=value 20 | self.next=None 21 | 22 | class HashTable: 23 | def __init__(self): 24 | self.capacity=INITIAL_CAPACITY 25 | self.size=0 26 | self.buckets=[None]*self.capacity 27 | 28 | def hash(self,key): 29 | hashsum=0 30 | for idx,c in enumerate(key): 31 | hashsum +=(idx+len(key))**ord(c) 32 | hashsum = hashsum%self.capacity 33 | return(hashsum) 34 | 35 | def insert(self,key,value): 36 | self.size+=1 #because we added an element 37 | index=self.hash(key) 38 | node=self.buckets[index] 39 | 40 | if node is None: 41 | self.buckets[index]=Node(key,value) 42 | return 43 | 44 | prev=node 45 | while node!=None: 46 | prev=node 47 | node=node.next 48 | 49 | prev.next=Node(key,value) 50 | 51 | def find(self,key): 52 | index=self.hash(key) 53 | node=self.buckets[index] 54 | while node is not None and node.key!=key: 55 | node=node.next 56 | 57 | #key was not found 58 | if node is None: 59 | return None 60 | else: 61 | return node.value 62 | 63 | def remove(self,key): 64 | index=self.hash(key) 65 | node=self.buckets[index] 66 | 67 | prev=node 68 | while node and node.key!=key: 69 | prev=node 70 | node=node.next 71 | 72 | if node is None: 73 | return None 74 | else: 75 | self.size-=1 #update size of table 76 | result=node.value 77 | if prev is not None: 78 | prev.next=prev.next.next 79 | else: 80 | node=None 81 | 82 | #return the removed node 83 | return result 84 | 85 | def inspect(self,buckets): 86 | ''' 87 | Return all elements in a bucket 88 | ''' 89 | elements={} 90 | for index in buckets: 91 | node=self.buckets[index] 92 | while node is not None: 93 | elements[node.key]=node.value 94 | node=node.next 95 | return elements 96 | 97 | if __name__=='__main__': 98 | hash_table=HashTable() 99 | hash_table.insert('ada',{'age':87,'profession':'mathematics'}) 100 | print(hash_table.find('ada')) 101 | print(hash_table.inspect([i for i in range(50)])) -------------------------------------------------------------------------------- /old_practice_problems/data-structures/hash-tables/possibleSums.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 13 19:39:08 2020 4 | 5 | @author: Logan Rowe 6 | 7 | You have a collection of coins, and you know the values of the coins and the 8 | quantity of each type of coin in it. You want to know how many distinct sums 9 | you can make from non-empty groupings of these coins. 10 | 11 | Example 12 | 13 | For coins = [10, 50, 100] and quantity = [1, 2, 1], the output should be 14 | possibleSums(coins, quantity) = 9. 15 | 16 | Here are all the possible sums: 17 | 18 | 50 = 50; 19 | 10 + 50 = 60; 20 | 50 + 100 = 150; 21 | 10 + 50 + 100 = 160; 22 | 50 + 50 = 100; 23 | 10 + 50 + 50 = 110; 24 | 50 + 50 + 100 = 200; 25 | 10 + 50 + 50 + 100 = 210; 26 | 10 = 10; 27 | 100 = 100; 28 | 10 + 100 = 110. 29 | As you can see, there are 9 distinct sums that can be created from non-empty 30 | groupings of your coins. 31 | 32 | 33 | Input/Output 34 | 35 | [execution time limit] 4 seconds (py3) 36 | 37 | [input] array.integer coins 38 | 39 | An array containing the values of the coins in your collection. 40 | 41 | Guaranteed constraints: 42 | 1 ≤ coins.length ≤ 20, 43 | 1 ≤ coins[i] ≤ 104. 44 | 45 | [input] array.integer quantity 46 | 47 | An array containing the quantity of each type of coin in your collection. 48 | quantity[i] indicates the number of coins that have a value of coins[i]. 49 | 50 | Guaranteed constraints: 51 | quantity.length = coins.length, 52 | 1 ≤ quantity[i] ≤ 105, 53 | (quantity[0] + 1) * (quantity[1] + 1) * ... * (quantity[quantity.length - 1] + 1) <= 106. 54 | 55 | [output] integer 56 | 57 | The number of different possible sums that can be created from non-empty groupings of your coins. 58 | """ 59 | 60 | 61 | ''' 62 | This approach is too slow... see possibleSums_fast 63 | ''' 64 | from itertools import combinations 65 | 66 | def possibleSums(coins, quantity): 67 | total_coins=[] 68 | for (coin,quant) in zip(coins,quantity): 69 | total_coins.extend([coin]*quant) 70 | 71 | sums=[] 72 | for r in range(1,len(total_coins)): 73 | sums.extend([sum(values) for values in combinations(total_coins,r)]) 74 | 75 | return(len(set(sums))+1) 76 | 77 | 78 | if __name__=='__main__': 79 | coins = [10, 50, 100] 80 | quantity = [1, 2, 1] 81 | print(possibleSums(coins,quantity)) -------------------------------------------------------------------------------- /old_practice_problems/data-structures/hash-tables/possibleSums_fast.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 13 19:39:08 2020 4 | 5 | @author: Logan Rowe 6 | 7 | You have a collection of coins, and you know the values of the coins and the 8 | quantity of each type of coin in it. You want to know how many distinct sums 9 | you can make from non-empty groupings of these coins. 10 | 11 | Example 12 | 13 | For coins = [10, 50, 100] and quantity = [1, 2, 1], the output should be 14 | possibleSums(coins, quantity) = 9. 15 | 16 | Here are all the possible sums: 17 | 18 | 50 = 50; 19 | 10 + 50 = 60; 20 | 50 + 100 = 150; 21 | 10 + 50 + 100 = 160; 22 | 50 + 50 = 100; 23 | 10 + 50 + 50 = 110; 24 | 50 + 50 + 100 = 200; 25 | 10 + 50 + 50 + 100 = 210; 26 | 10 = 10; 27 | 100 = 100; 28 | 10 + 100 = 110. 29 | As you can see, there are 9 distinct sums that can be created from non-empty 30 | groupings of your coins. 31 | 32 | 33 | Input/Output 34 | 35 | [execution time limit] 4 seconds (py3) 36 | 37 | [input] array.integer coins 38 | 39 | An array containing the values of the coins in your collection. 40 | 41 | Guaranteed constraints: 42 | 1 ≤ coins.length ≤ 20, 43 | 1 ≤ coins[i] ≤ 104. 44 | 45 | [input] array.integer quantity 46 | 47 | An array containing the quantity of each type of coin in your collection. 48 | quantity[i] indicates the number of coins that have a value of coins[i]. 49 | 50 | Guaranteed constraints: 51 | quantity.length = coins.length, 52 | 1 ≤ quantity[i] ≤ 105, 53 | (quantity[0] + 1) * (quantity[1] + 1) * ... * (quantity[quantity.length - 1] + 1) <= 106. 54 | 55 | [output] integer 56 | 57 | The number of different possible sums that can be created from non-empty groupings of your coins. 58 | """ 59 | 60 | 61 | ''' 62 | This approach is too slow... see possibleSums_fast 63 | ''' 64 | from itertools import combinations 65 | 66 | def possibleSums(coins, quantity): 67 | total_coins=[] 68 | for (coin,quant) in zip(coins,quantity): 69 | total_coins.extend([coin]*quant) 70 | 71 | combos=set() 72 | for r in range(1,len(total_coins)): 73 | combos=combos.union(set(sum(i) for i in combinations(total_coins,r))) 74 | print(combos) 75 | 76 | 77 | return(len(combos)+1) 78 | 79 | 80 | if __name__=='__main__': 81 | coins = [10, 50, 100] 82 | quantity = [1, 2, 1] 83 | print(possibleSums(coins,quantity)) -------------------------------------------------------------------------------- /old_practice_problems/data-structures/hash-tables/possibleSums_faster.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 13 19:39:08 2020 4 | 5 | @author: Logan Rowe 6 | 7 | You have a collection of coins, and you know the values of the coins and the 8 | quantity of each type of coin in it. You want to know how many distinct sums 9 | you can make from non-empty groupings of these coins. 10 | 11 | Example 12 | 13 | For coins = [10, 50, 100] and quantity = [1, 2, 1], the output should be 14 | possibleSums(coins, quantity) = 9. 15 | 16 | Here are all the possible sums: 17 | 18 | 50 = 50; 19 | 10 + 50 = 60; 20 | 50 + 100 = 150; 21 | 10 + 50 + 100 = 160; 22 | 50 + 50 = 100; 23 | 10 + 50 + 50 = 110; 24 | 50 + 50 + 100 = 200; 25 | 10 + 50 + 50 + 100 = 210; 26 | 10 = 10; 27 | 100 = 100; 28 | 10 + 100 = 110. 29 | As you can see, there are 9 distinct sums that can be created from non-empty 30 | groupings of your coins. 31 | 32 | 33 | Input/Output 34 | 35 | [execution time limit] 4 seconds (py3) 36 | 37 | [input] array.integer coins 38 | 39 | An array containing the values of the coins in your collection. 40 | 41 | Guaranteed constraints: 42 | 1 ≤ coins.length ≤ 20, 43 | 1 ≤ coins[i] ≤ 104. 44 | 45 | [input] array.integer quantity 46 | 47 | An array containing the quantity of each type of coin in your collection. 48 | quantity[i] indicates the number of coins that have a value of coins[i]. 49 | 50 | Guaranteed constraints: 51 | quantity.length = coins.length, 52 | 1 ≤ quantity[i] ≤ 105, 53 | (quantity[0] + 1) * (quantity[1] + 1) * ... * (quantity[quantity.length - 1] + 1) <= 106. 54 | 55 | [output] integer 56 | 57 | The number of different possible sums that can be created from non-empty groupings of your coins. 58 | """ 59 | 60 | 61 | def possibleSums(coins, quantity): 62 | 63 | sums = set([0]) 64 | 65 | for index in range(len(coins)): 66 | for total in list(sums): 67 | for quant in range(1, quantity[index]+1): 68 | sums.add(total + coins[index]*quant) 69 | 70 | 71 | sums.remove(0) 72 | return len(sums) 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | if __name__=='__main__': 82 | coins = [[10, 50, 100],[1,2]] 83 | quantity = [[1, 2, 1],[50000,2]] 84 | for coin,quant in zip(coins,quantity): 85 | print(possibleSums(coin,quant)) 86 | 87 | -------------------------------------------------------------------------------- /old_practice_problems/data-structures/linked-lists/example_batch_reversal.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Feb 7 23:40:08 2020 4 | 5 | @author: Logan Rowe 6 | """ 7 | 8 | # Python program to reverse a linked list in group of given size 9 | 10 | # Node class 11 | class Node: 12 | 13 | # Constructor to initialize the node object 14 | def __init__(self, data): 15 | self.data = data 16 | self.next = None 17 | 18 | class LinkedList: 19 | 20 | # Function to initialize head 21 | def __init__(self): 22 | self.head = None 23 | 24 | def reverse(self, head, k): 25 | current = head 26 | next = None 27 | prev = None 28 | count = 0 29 | 30 | # Reverse first k nodes of the linked list 31 | while(current is not None and count < k): 32 | next = current.next 33 | current.next = prev 34 | prev = current 35 | current = next 36 | count += 1 37 | 38 | # next is now a pointer to (k+1)th node 39 | # recursively call for the list starting 40 | # from current. And make rest of the list as 41 | # next of first node 42 | if next is not None: 43 | head.next = self.reverse(next, k) 44 | 45 | # prev is new head of the input list 46 | return prev 47 | 48 | # Function to insert a new node at the beginning 49 | def push(self, new_data): 50 | new_node = Node(new_data) 51 | new_node.next = self.head 52 | self.head = new_node 53 | 54 | # Utility function to print the linked LinkedList 55 | def printList(self): 56 | temp = self.head 57 | while(temp): 58 | print(temp.data,) 59 | temp = temp.next 60 | 61 | 62 | # Driver program 63 | llist = LinkedList() 64 | llist.push(9) 65 | llist.push(8) 66 | llist.push(7) 67 | llist.push(6) 68 | llist.push(5) 69 | llist.push(4) 70 | llist.push(3) 71 | llist.push(2) 72 | llist.push(1) 73 | 74 | print("Given linked list") 75 | llist.printList() 76 | llist.head = llist.reverse(llist.head, 3) 77 | 78 | print("\nReversed Linked list") 79 | llist.printList() -------------------------------------------------------------------------------- /old_practice_problems/data-structures/linked-lists/list_palendrome.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 6 15:33:52 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Note: Try to solve this task in O(n) time using O(1) additional space, 8 | where n is the number of elements in l, since this is what you'll be asked to 9 | do during an interview. 10 | 11 | Given a singly linked list of integers, determine whether or not it's a palindrome. 12 | 13 | Note: in examples below and tests preview linked lists are presented as arrays 14 | just for simplicity of visualization: in real data you will be given a head 15 | node l of the linked list 16 | 17 | For l = [0, 1, 0], the output should be 18 | isListPalindrome(l) = true; 19 | 20 | For l = [1, 2, 2, 3], the output should be 21 | isListPalindrome(l) = false. 22 | """ 23 | import linked_lists_learning as lll 24 | 25 | def isListPalindrome(l): 26 | #extract values from linked list 27 | values=[] 28 | current_node=l.head 29 | while current_node.next!=None: 30 | current_node=current_node.next 31 | values.append(current_node.data) 32 | 33 | for idx in range(int(len(values)/2)): #using int here will self hanlde the case that len(values is odd) 34 | if values[idx]!=values[-(idx+1)]: 35 | return False 36 | 37 | return True 38 | 39 | 40 | 41 | 42 | 43 | if __name__=='__main__': 44 | l1=[0,1,0] 45 | l2=[1,2,2,3] 46 | 47 | link1=lll.linked_list() 48 | link2=lll.linked_list() 49 | for i in l1: 50 | link1.fastAppend(i) 51 | 52 | for i in l2: 53 | link2.fastAppend(i) 54 | 55 | print(link1.display()) 56 | print(isListPalindrome(link1)) 57 | print() 58 | print(link2.display()) 59 | print(isListPalindrome(link2)) 60 | -------------------------------------------------------------------------------- /old_practice_problems/data-structures/linked-lists/merge_two_linked_lists.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 6 17:58:48 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Note: Your solution should have O(l1.length + l2.length) time complexity, 8 | since this is what you will be asked to accomplish in an interview. 9 | 10 | Given two singly linked lists sorted in non-decreasing order, 11 | your task is to merge them. In other words, return a singly linked list, also 12 | sorted in non-decreasing order, that contains the elements from both original lists. 13 | 14 | Example 15 | 16 | For l1 = [1, 2, 3] and l2 = [4, 5, 6], the output should be 17 | mergeTwoLinkedLists(l1, l2) = [1, 2, 3, 4, 5, 6]; 18 | For l1 = [1, 1, 2, 4] and l2 = [0, 3, 5], the output should be 19 | mergeTwoLinkedLists(l1, l2) = [0, 1, 1, 2, 3, 4, 5]. 20 | """ 21 | 22 | import numpy as np 23 | 24 | class ListNode(object): 25 | def __init__(self, x): 26 | self.value = x 27 | self.next = None 28 | 29 | def mergeTwoLinkedLists(l1, l2): 30 | sorted_list=ListNode(None) 31 | curr=sorted_list 32 | while l1 and l2: 33 | if l1.value <= l2.value: 34 | curr.next=l1 35 | l1=l1.next 36 | else: 37 | curr.next=l2 38 | l2=l2.next 39 | curr=curr.next 40 | 41 | #once one of the lists is depleted we will break out of while loop 42 | #Take all remaining values from whichever list remains 43 | while l1: 44 | curr.next=l1 45 | l1=l1.next 46 | while l2: 47 | curr.next=l2 48 | l2=l2.next 49 | 50 | return(sorted_list.next) -------------------------------------------------------------------------------- /old_practice_problems/data-structures/linked-lists/rearrange_last_N.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Feb 10 18:53:06 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Note: Try to solve this task in O(list size) time using O(1) additional space, 8 | since this is what you'll be asked during an interview. 9 | 10 | Given a singly linked list of integers l and a non-negative integer n, 11 | move the last n list nodes to the beginning of the linked list. 12 | 13 | Example 14 | 15 | For l = [1, 2, 3, 4, 5] and n = 3, the output should be 16 | rearrangeLastN(l, n) = [3, 4, 5, 1, 2]; 17 | For l = [1, 2, 3, 4, 5, 6, 7] and n = 1, the output should be 18 | rearrangeLastN(l, n) = [7, 1, 2, 3, 4, 5, 6]. 19 | Input/Output 20 | 21 | [execution time limit] 4 seconds (py3) 22 | 23 | [input] linkedlist.integer l 24 | 25 | A singly linked list of integers. 26 | 27 | Guaranteed constraints: 28 | 0 ≤ list size ≤ 105, 29 | -1000 ≤ element value ≤ 1000. 30 | 31 | [input] integer n 32 | 33 | A non-negative integer. 34 | 35 | Guaranteed constraints: 36 | 0 ≤ n ≤ list size. 37 | 38 | [output] linkedlist.integer 39 | 40 | Return l with the n last elements moved to the beginning. 41 | """ 42 | 43 | class ListNode(object): 44 | def __init__(self, x): 45 | self.value = x 46 | self.next = None 47 | 48 | def rearrangeLastN(l, n): 49 | #Edge Case if n is <=0 just return the original linked list 50 | if n<=0: 51 | return l 52 | 53 | #Find the length of the list 54 | ll_len=0 55 | head=l 56 | curr=head 57 | while curr!=None: 58 | ll_len+=1 59 | curr=curr.next 60 | 61 | #Edge Cases: If len(l)==0 or len(l)>=n return the original linked list 62 | if ll_len<=n or ll_len==0: 63 | return l 64 | 65 | #Edge Case: If len(l) is 2 then reverse the list and return 66 | if ll_len==2: 67 | head=l 68 | curr=head 69 | prev=curr 70 | new_head=curr.next 71 | new_head.next=prev 72 | prev.next=None 73 | return(new_head) 74 | 75 | #make new_head in the list at ll_len-n and old tail point to old head 76 | index=0 77 | old_head=l 78 | curr=old_head 79 | while curr and curr.next!=None: 80 | curr=curr.next 81 | index+=1 82 | 83 | if index==ll_len-n: 84 | new_head=curr 85 | 86 | if index==ll_len-n-1: 87 | new_tail=curr 88 | 89 | #After passing to the last item in the list, point it towards the original head 90 | curr.next=old_head 91 | 92 | new_tail.next=None 93 | 94 | l=new_head 95 | 96 | return(l) 97 | 98 | if __name__=='__main__': 99 | l = [1, 2, 3, 4, 5] 100 | head=ListNode(None) 101 | curr=head 102 | for value in l: 103 | curr.next=ListNode(value) 104 | curr=curr.next 105 | print(value) 106 | 107 | print() 108 | 109 | rearranged_ll=rearrangeLastN(head.next,3) 110 | curr=rearranged_ll 111 | while curr!=None: 112 | print(curr.value) 113 | curr=curr.next -------------------------------------------------------------------------------- /old_practice_problems/data-structures/linked-lists/remove_K_from_list.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 6 13:52:50 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Note: Try to solve this task in O(n) time using O(1) additional space, where n is the number of elements in the list, since this is what you'll be asked to do during an interview. 8 | 9 | Given a singly linked list of integers l and an integer k, remove all elements from list l that have a value equal to k. 10 | 11 | Example 12 | 13 | For l = [3, 1, 2, 3, 4, 5] and k = 3, the output should be 14 | removeKFromList(l, k) = [1, 2, 4, 5]; 15 | For l = [1, 2, 3, 4, 5, 6, 7] and k = 10, the output should be 16 | removeKFromList(l, k) = [1, 2, 3, 4, 5, 6, 7]. 17 | 18 | 19 | # Singly-linked lists are already defined with this interface: 20 | # class ListNode(object): 21 | # def __init__(self, x): 22 | # self.value = x 23 | # self.next = None 24 | # 25 | """ 26 | 27 | 28 | ''' 29 | thoughts: 30 | 31 | we are provided with a list, but are supposed to be working with a linked list 32 | 33 | I will create a linked list from the list but only include the values that 34 | are not equal to given k 35 | 36 | then I will return a list formed from the newly created linked list 37 | ''' 38 | class ListNode(object): 39 | def __init__(self, data=None): 40 | self.data = data 41 | self.next = None 42 | 43 | class LinkedList: 44 | def __init__(self): 45 | self.head=ListNode() 46 | 47 | def removeKFromList(l,k): 48 | my_list=LinkedList() 49 | current_node=my_list.head 50 | for value in l: 51 | if value != k: 52 | current_node.next=ListNode(value) 53 | current_node=current_node.next 54 | 55 | new_list=[] 56 | current_node=my_list.head 57 | while current_node.next!=None: 58 | current_node=current_node.next 59 | new_list.append(current_node.data) 60 | return(new_list) 61 | 62 | 63 | ''' 64 | If the input is in fact a linked list and not a list 65 | props to metawrench for tips 66 | ''' 67 | 68 | def removeKFromLinkedList(l,k): 69 | current_node=l 70 | while current_node: 71 | if current_node.next and current_node.next.data==k: 72 | current_node.next=current_node.next.next 73 | else: 74 | current_node=current_node.next 75 | return l.next if l and l.value==k else l 76 | 77 | 78 | 79 | 80 | if __name__=='__main__': 81 | l=[3, 1, 2, 3, 4, 5] 82 | k=3 83 | print(removeKFromList(l,k)) 84 | -------------------------------------------------------------------------------- /old_practice_problems/data-structures/trees/hasPathWithGivenSum.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Feb 25 22:40:25 2020 4 | 5 | @author: Logan Rowe 6 | """ 7 | 8 | def sum_each_path(start,val,count,s,sum=[]): 9 | if s in sum: 10 | return s 11 | 12 | if not start: 13 | return 0 14 | 15 | val+=start.value 16 | 17 | if not start.left and not start.right: 18 | sum.append(val) 19 | if val==s: 20 | count+=1 21 | if count>0: 22 | val=s 23 | print(sum) 24 | return val 25 | 26 | if s in sum: 27 | return s 28 | 29 | return sum_each_path(start.left,val,count,s,sum=[])+sum_each_path(start.right,val,count,s,sum=[]) 30 | 31 | def hasPathWithGivenSum(t, s): 32 | return sum_each_path(t,0,0,s)==s -------------------------------------------------------------------------------- /old_practice_problems/data-structures/trees/isTreeSymmetric.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat Feb 29 11:50:41 2020 4 | 5 | @author: Logan Rowe 6 | 7 | 8 | Given a binary tree t, determine whether it is symmetric around its center, i.e. each side mirrors the other. 9 | 10 | Example 11 | 12 | For 13 | 14 | t = { 15 | "value": 1, 16 | "left": { 17 | "value": 2, 18 | "left": { 19 | "value": 3, 20 | "left": null, 21 | "right": null 22 | }, 23 | "right": { 24 | "value": 4, 25 | "left": null, 26 | "right": null 27 | } 28 | }, 29 | "right": { 30 | "value": 2, 31 | "left": { 32 | "value": 4, 33 | "left": null, 34 | "right": null 35 | }, 36 | "right": { 37 | "value": 3, 38 | "left": null, 39 | "right": null 40 | } 41 | } 42 | } 43 | the output should be isTreeSymmetric(t) = true. 44 | 45 | Here's what the tree in this example looks like: 46 | 47 | 1 48 | / \ 49 | 2 2 50 | / \ / \ 51 | 3 4 4 3 52 | As you can see, it is symmetric. 53 | 54 | For 55 | 56 | t = { 57 | "value": 1, 58 | "left": { 59 | "value": 2, 60 | "left": null, 61 | "right": { 62 | "value": 3, 63 | "left": null, 64 | "right": null 65 | } 66 | }, 67 | "right": { 68 | "value": 2, 69 | "left": null, 70 | "right": { 71 | "value": 3, 72 | "left": null, 73 | "right": null 74 | } 75 | } 76 | } 77 | the output should be isTreeSymmetric(t) = false. 78 | 79 | Here's what the tree in this example looks like: 80 | 81 | 1 82 | / \ 83 | 2 2 84 | \ \ 85 | 3 3 86 | As you can see, it is not symmetric. 87 | 88 | Input/Output 89 | 90 | [execution time limit] 4 seconds (py3) 91 | 92 | [input] tree.integer t 93 | 94 | A binary tree of integers. 95 | 96 | Guaranteed constraints: 97 | 0 ≤ tree size < 5 · 104, 98 | -1000 ≤ node value ≤ 1000. 99 | 100 | [output] boolean 101 | 102 | Return true if t is symmetric and false otherwise. 103 | 104 | 105 | """ 106 | 107 | ''' 108 | Thoughts: This is equivalent to asking if the in-order traversal is a palendrome 109 | ''' 110 | 111 | def isTreeSymmetric(t): 112 | if not t: 113 | return True 114 | 115 | traversal=[] 116 | if t: 117 | traversal.append(isTreeSymmetric(t.left)) 118 | traversal.append(t.value) 119 | traversal.append(isTreeSymmetric(t.right)) 120 | 121 | print(traversal) 122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /old_practice_problems/data-structures/trie.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu May 21 23:19:21 2020 4 | 5 | @author: rowe1 6 | """ 7 | 8 | class Node(object): 9 | def __init__(self, val): 10 | self.val = val 11 | self.children = {} 12 | self.tail = False #redundant since we also use '*' to denote word end, but good practice 13 | 14 | class TrieTree(object): 15 | def __init__(self, val = ''): 16 | self.root = Node(val) 17 | self.root.tail=True 18 | 19 | def add(self, word): 20 | ''' 21 | Adds word to trie 22 | ''' 23 | curr = self.root 24 | for letter in word: 25 | 26 | #CHECK IF LETTER IS IN CHILDREN 27 | if letter in curr.children: 28 | curr = curr.children[letter] 29 | 30 | else: #IF LETTER IS NOT IN CHILDREN THEN APPEND LETTER TO CHILDREN 31 | curr.children[letter] = Node(letter) 32 | curr = curr.children[letter] 33 | 34 | if curr.tail: #CHECK IF WORD WAS ALREADY IN THE TRIE 35 | print(word,'already exists') 36 | else: #OTHERWISE MAKE NOTE THAT THIS IS THE END OF A WORD 37 | curr.tail = True 38 | 39 | 40 | return None 41 | 42 | def find(self, word): 43 | ''' 44 | Locates word within trie, returns: (Existence as Prefix, Existence as Complete Word) 45 | 46 | True, True if word appears as a full word 47 | 48 | True, False if it appears in the trie, but only as a prefix 49 | 50 | False, False if it is not in the trie as a prefix or a word 51 | ''' 52 | curr = self.root 53 | for letter in word: 54 | #SEE IF LETTER IS IN CHILDREN OF CURRENT NODE 55 | if letter in curr.children: 56 | curr = curr.children[letter] 57 | else: 58 | return False, False #WORD IS NOT IN TREE 59 | 60 | if curr.tail: 61 | return True, True #WORD IS A PREFIX AND A FULL WORD 62 | else: 63 | return True, False #PREFIX BUT NOT A FULL WORD 64 | 65 | 66 | 67 | 68 | if __name__ == '__main__': 69 | root = TrieTree() 70 | 71 | words = ['wait', 'waiter', 'shop', 'shopper', 'wait'] 72 | 73 | for word in words: 74 | root.add(word) 75 | 76 | for word in ['','wait','waits','shopp','wai','shop','shopping','shoppings','shipping']: 77 | print(word,root.find(word)) 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /old_practice_problems/other/recursive-practice/knapsackRecursive.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 20 14:39:25 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given a knapsack that can only hold 10 kg 8 | 9 | Decide which items to bring to maximize the value 10 | 11 | items{item_number:[weight,value],...} 12 | """ 13 | 14 | import numpy as np 15 | 16 | def packKnapsackNaive(item_number,knapsack_weight): 17 | if item_number==0 or knapsack_weight>=10: 18 | result=0 19 | elif items[item_number][0]>10-knapsack_weight: 20 | result=packKnapsack(item_number-1,knapsack_weight) 21 | else: 22 | temp1=packKnapsack(item_number-1,knapsack_weight) 23 | temp2=items[item_number][1]+packKnapsack(item_number-1,knapsack_weight+items[item_number][0]) 24 | print(temp1) 25 | print(temp2) 26 | result=max(temp1,temp2) 27 | return result 28 | 29 | empty=np.full((5,10),None) 30 | def packKnapsack(item_number,knapsack_weight): 31 | global empty 32 | if empty[item_number][knapsack_weight]!=None: 33 | return empty[item_number][knapsack_weight] 34 | if item_number==0 or knapsack_weight>=10: 35 | result=0 36 | elif items[item_number][0]>10-knapsack_weight: 37 | result=packKnapsack(item_number-1,knapsack_weight) 38 | else: 39 | temp1=packKnapsack(item_number-1,knapsack_weight) 40 | temp2=items[item_number][1]+packKnapsack(item_number-1,knapsack_weight+items[item_number][0]) 41 | print(temp1) 42 | print(temp2) 43 | result=max(temp1,temp2) 44 | empty[item_number][knapsack_weight]=result 45 | return result 46 | 47 | 48 | 49 | if __name__=='__main__': 50 | 51 | items={ 52 | 0:[1,5], 53 | 1:[2,3], 54 | 2:[4,5], 55 | 3:[2,3], 56 | 4:[5,2] 57 | } 58 | 59 | print(packKnapsack(4,0)) -------------------------------------------------------------------------------- /old_practice_problems/other/recursive-practice/knapsackRecursiveSolution.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Feb 20 14:24:55 2020 4 | 5 | @author: Logan Rowe 6 | 7 | Given a knapsack that can only hold 5 kg 8 | 9 | Decide which items to bring to maximize the value 10 | 11 | items{item_number:[weight,value],...} 12 | """ 13 | 14 | 15 | def pack_knapsack(items,knapsack_weight): 16 | global knap_sack_items 17 | 18 | item=items.pop() 19 | 20 | for item in items: 21 | if items[item][0]<=5-knapsack_weight: 22 | knapsack_items[item]=item 23 | items.pop(item) 24 | knapsack_weight+=items[item][0] 25 | pack_knapsack(items,knapsack_weight) 26 | elif item[item][0] 27 | 28 | 29 | 30 | 31 | if __name__=='__main__': 32 | 33 | items={ 34 | 1:[1,5], 35 | 2:[2,3], 36 | 3:[4,5], 37 | 4:[2,3], 38 | 5:[5,2] 39 | } 40 | 41 | knapsack_items=[0]*len(items) 42 | --------------------------------------------------------------------------------