Skip to content

Instantly share code, notes, and snippets.

@tyler-austin
Created June 2, 2017 21:12
Show Gist options
  • Save tyler-austin/f5bd074f2eb0c538d76dace5a6eecbb5 to your computer and use it in GitHub Desktop.
Save tyler-austin/f5bd074f2eb0c538d76dace5a6eecbb5 to your computer and use it in GitHub Desktop.
Code Fights - arrayReplace

Given an array of integers, replace all the occurrences of elemToReplace with substitutionElem.

Example

For inputArray = [1, 2, 1], elemToReplace = 1 and substitutionElem = 3, the output should be
arrayReplace(inputArray, elemToReplace, substitutionElem) = [3, 2, 3].

Input/Output

  • [time limit] 4000ms (py3)

  • [input] array.integer inputArray

    Guaranteed constraints:

    2 ≤ inputArray.length ≤ 10,
    0 ≤ inputArray[i] ≤ 10.
    
  • [input] integer elemToReplace

    Guaranteed constraints:

    0 ≤ elemToReplace ≤ 10.
    
  • [input] integer substitutionElem

    Guaranteed constraints:

    0 ≤ substitutionElem ≤ 10.
    
  • [output] array.integer

from typing import List
class ArrayReplace:
@classmethod
def array_replace(cls, input_array: List[int], elem_to_replace: int, substitution_elem: int) -> List[int]:
return [substitution_elem if d == elem_to_replace else d for d in input_array]
def arrayReplace(input_array: list, elem_to_replace: int, substitution_elem: int) -> list:
return [substitution_elem if d == elem_to_replace else d for d in input_array]
import unittest
from array_replace import ArrayReplace
class TestArrayReplace(unittest.TestCase):
def test_1(self):
input_array = [1, 2, 1]
elem_to_replace = 1
substitution_elem = 3
solution = [3, 2, 3]
result = ArrayReplace.array_replace(input_array, elem_to_replace, substitution_elem)
self.assertEqual(result, solution)
def test_2(self):
input_array = [1, 2, 3, 4, 5]
elem_to_replace = 3
substitution_elem = 0
solution = [1, 2, 0, 4, 5]
result = ArrayReplace.array_replace(input_array, elem_to_replace, substitution_elem)
self.assertEqual(result, solution)
def test_3(self):
input_array = [1, 1, 1]
elem_to_replace = 1
substitution_elem = 10
solution = [10, 10, 10]
result = ArrayReplace.array_replace(input_array, elem_to_replace, substitution_elem)
self.assertEqual(result, solution)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment