Back to Freecodecamp

Challenge 234: Prank Number

curriculum/challenges/english/blocks/daily-coding-challenges-python/69b1028d6e265413d0198a2d.md

latest2.8 KB
Original Source

--description--

Given an array of numbers where all but one number follow a pattern, return a new array with the one number that doesn't follow the pattern fixed.

The pattern will be one of:

  • The numbers increase from one to the next by a fixed amount (addition).
  • The numbers decrease from one to the next by a fixed amount (subtraction).

For example, given [2, 4, 7, 8, 10] return [2, 4, 6, 8, 10].

--hints--

fix_prank_number([2, 4, 7, 8, 10]) should return [2, 4, 6, 8, 10].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(fix_prank_number([2, 4, 7, 8, 10]), [2, 4, 6, 8, 10])`)
}})

fix_prank_number([10, 10, 8, 7, 6]) should return [10, 9, 8, 7, 6].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(fix_prank_number([10, 10, 8, 7, 6]), [10, 9, 8, 7, 6])`)
}})

fix_prank_number([12, 24, 36, 48, 61, 72, 84, 96]) should return [12, 24, 36, 48, 60, 72, 84, 96].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(fix_prank_number([12, 24, 36, 48, 61, 72, 84, 96]), [12, 24, 36, 48, 60, 72, 84, 96])`)
}})

fix_prank_number([4, 1, -2, -5, -8, -5]) should return [4, 1, -2, -5, -8, -11].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(fix_prank_number([4, 1, -2, -5, -8, -5]), [4, 1, -2, -5, -8, -11])`)
}})

fix_prank_number([0, 100, 200, 300, 150, 500]) should return [0, 100, 200, 300, 400, 500].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(fix_prank_number([0, 100, 200, 300, 150, 500]), [0, 100, 200, 300, 400, 500])`)
}})

fix_prank_number([400, 425, 400, 375, 350, 325, 300]) should return [450, 425, 400, 375, 350, 325, 300].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(fix_prank_number([400, 425, 400, 375, 350, 325, 300]), [450, 425, 400, 375, 350, 325, 300])`)
}})

fix_prank_number([-5, 5, 10, 15, 20]) should return [0, 5, 10, 15, 20].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(fix_prank_number([-5, 5, 10, 15, 20]), [0, 5, 10, 15, 20])`)
}})

--seed--

--seed-contents--

py
def fix_prank_number(arr):

    return arr

--solutions--

py
def fix_prank_number(arr):
    diffs = [arr[i + 1] - arr[i] for i in range(len(arr) - 1)]

    step = diffs[0]
    for i in range(len(diffs) - 1):
        if diffs[i] == diffs[i + 1]:
            step = diffs[i]
            break

    result = arr[:]

    for i in range(len(result) - 1):
        if result[i + 1] - result[i] != step:
            if i == 0 and result[2] - result[1] == step:
                result[0] = result[1] - step
            else:
                result[i + 1] = result[i] + step
            break

    return result