DEV Community

Durga Pokharel
Durga Pokharel

Posted on

2

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

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,

exec("""
def  sum(a,b):
    return a+b
""")
sum(5,4)
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):
    exec(f'v=f{i}(n)')
    sol[f"f{i}"]=v
print(sol)
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

Day 52 Of #100DaysOfCode and #Python
* Algorithmic Toolbox
* Completed Some Assignment
* Python exec( ) function#womenintech #DEVCommunity #CodeNewbie pic.twitter.com/USBO43P1Ni

— Durga Pokharel (@mathdurga) February 15, 2021

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay