Python: Measure the execution time of small python code

The “timeit” module lets you measure the execution time of small bits of Python code. This can help you find the execution time of your code and thus help in a quick performance improvement of your code. A tiny example follows.

>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)

0.2938678440004878

>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)

0.26015590599854477

>>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)

0.26461737899808213

Please note that every time, the execution time varies for the same snippet. in the first two cases. The third one does the same thing but has a different execution time. This profiling helps with performant code going to your production.

Also, this different execution time for the same exact code depends on a lot of factors, the major one being how busy your CPU was at the time of executing this code. The module function timeit.timeit(stmt, setup, timer, number) accepts four arguments:

  • stmt which is the statement you want to measure; it defaults to ‘pass’.
  • setup which is the code that you run before running the stmt; it defaults to ‘pass’.
    We generally use this to import the required modules for our code.
  • timer which is a timeit.Timer object; it usually has a sensible default value so you don’t have to worry about it.
  • number which is the number of executions you’d like to run the stmt.

https://docs.python.org/2/library/timeit.html
https://www.geeksforgeeks.org/timeit-python-examples/

Python: Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

This post is one of my new series solving one problem per day.

For those of you solving coding challenges for your next software engineering job, here is one more problem.

This problem was asked by Uber.

Problem Statement

Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].

Here is a solution I came up with

def product_ar(arr):
	new_arr = []
	for i in range(0,len(arr)):
		new_arr.append(multiply_all(arr[0:i], arr[i+1:len(arr)]) )	
	
	return new_arr

def multiply_all(arr1, arr2):
	product = 1
	for item in arr1:
		product *= item		
	for item in arr2:
		product *= item	

	return product

# Some tests 

print(product_ar([1, 2, 3, 4, 5]) == [120, 60, 40, 30, 24])
print(product_ar([3,2,1]) == [2,3,6])

Follow-up: what if you can’t use division?

How to sort a Python dictionary by value

# How to sort a Python dict by value
# (== get a representation sorted by value)

>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}

>>> sorted(xs.items(), key=lambda x: x[1])
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

# Or:

>>> import operator
>>> sorted(xs.items(), key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

Python: Different ways to test multiple flags at once

# Different ways to test multiple
# flags at once in Python
x, y, z = 0, 1, 0

if x == 1 or y == 1 or z == 1:
    print('passed')

if 1 in (x, y, z):
    print('passed')

# These only test for truthiness:
if x or y or z:
    print('passed')

if any((x, y, z)):
    print('passed')