Do you even Refactor? 003

codr

Ilya Nevolin

Posted on February 14, 2021

Do you even Refactor? 003

Code refactoring is crucial but often overlooked. It can improve the design and performance of existing code.

The Python code below takes about 14 seconds to complete. Refactor the getData function to make it run in less than 10 seconds. Post your answer in the comments.

import time

def getData():
  arr = []
  for i in range(1000*1000*50):
    arr.append(i)
  lo, hi = 0, 0
  for x in arr:
    if x < lo:
      lo = x
    if x > hi:
      hi = x
  print(lo, hi)
  return arr

def timed(func):
  def run():
    Tstart = time.time()
    func()  
    Tend = time.time()
    Tdt = round(Tend - Tstart, 2)
    print(Tdt, 'seconds')
  return run

@timed
def main():
  data = getData()
  print('len:', len(data), 'sum:', sum(data))

main()
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
codr
Ilya Nevolin

Posted on February 14, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

DRY Out with Loops
beginners DRY Out with Loops

December 29, 2021

Do you even Refactor? 003
beginners Do you even Refactor? 003

February 14, 2021