DEV Community


Day 52 Of 100DaysOfCode: exec( ) Function in Python

iamdurga profile image Durga Pokharel ・2 min read

This is my 52th day of #100daysof code and python. Like yesterday today also continued to learn more about algorithm. Tried to write effective algorithm for Fibonacci numbers, Greatest common devisor. Defintion of Big-O ,types of Big-O and used of Big-O from Coursera.

Here is one python code today I wrote for sorting different function in ascending order.

Python Code

exec() function

exec() function is used for the dynamic execution of Python program which can either be a string or object code. If it is a string, the string is parsed as a suite of Python statements which is then executed unless a syntax error occurs and if it is an object code, it is simply executed.

exec is a built in function which allows us to run dynamic pyton code on runtime. For example,

def  sum(a,b):
    return a+b
Enter fullscreen mode Exit fullscreen mode

I tried to write following code to kept the function in ascending order.

import numpy as np
n = 10
value = np.e
base = np.e
f1 = lambda n: 3**n
f2 = lambda n: n* (np.log(n)/np.log(2))
f3 = lambda n: np.log(n)/np.log(4)
f4 = lambda n: n
f5 = lambda n: 5**(np.log(n)/np.log(2))
f6 = lambda n:n **2
f7 = lambda n:n **0.5
f8 = lambda n:2**(2*n)

sol = {}
for i in range(1,9):
x = sol.copy()
dict(sorted(x.items(), key=lambda item: item[1]))
Enter fullscreen mode Exit fullscreen mode

Output of above code is,

{'f1': 59049, 'f2': 33.219280948873624, 'f3': 1.6609640474436813, 'f4': 10, 'f5': 209.8592395866664, 'f6': 100, 'f7': 3.1622776601683795, 'f8': 1048576}
{'f3': 1.6609640474436813,
 'f7': 3.1622776601683795,
 'f4': 10,
 'f2': 33.219280948873624,
 'f6': 100,
 'f5': 209.8592395866664,
 'f1': 59049,
 'f8': 1048576}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Editor guide