UNIT 3 Flashcards
Recursion and how to exit the function
recursion is implemented using _________ , ISA example of recursion
a function calls itself to solve smaller instances of the same problem. This process continues until it reaches a stopping condition known as the base case.
Base Case: the simplest subproblem can be the problem can be reduced to
Recursive case: the part of the recurssion function where function calls itself to solve a simpler program
recursive step: performs repeating action until the subproblem cant be broken down anymore
it breaks down the prob ex factorial if input is 5 is goes in reverse until base condition and finds 0! then
then uses the value returned and then adds it from ex 0 or other functions like 1!… till 4!*5 =120, possible to iterate each value (Fibonacci series)
if value is added outside the recurring function it adds that value to lets say the returned value of 0 or u can directly input function values it will start from first and go to end
calling the function inside the function until it repeatedly until it reaches base case, else goes into an infinite loop
where is it use:
Solving problems with repeated patterns
simplify complex problems into smaller, easier problems
Handling unknown levels of depth (number of steps to a problem) to exit a function u can press return
using stack because activation records are
to be stored in LIFO order (last in first out).
activation record: arguments, return
address and local variables of the function
Stack is a linear data structure in which elements are inserted to the bottom and deleted from the top.
STACK MEMORY ALLOCATION:
contiguous blocks of memory (Function call Stack)
size of memory known to compiler, and memory is allocated when function is called
local memory such as variable intil. inside functions are stored as temp on function call stack and deleted once function returns
allocation of memory is handled by compiler using predefined routines
example of recursion:
def fact(n): #Recursive Function
if n == 0 : #BASE CASE
res = 1
else:
res = n * fact(n - 1)
return res
Recursion V Iteration
Recursion
Function calls itself
Implemented using Function calls
Termination condition is defined within
the recursive function
Leads to infinite recursion, if does not
meet termination condition
It is slower than iteration
Uses more memory than iteration
ITERATION
Set of program statements executed
repeatedly
Implemented using Loops
Termination condition is defined in the
definition of the loop
Leads to infinite loop, if the condition in
the loop never becomes false
It is faster than recursion
Uses less memory compared to recursion
callback function, and code example adv and dis and built in function, and calling multiple functions
a function passed to another function as an argument
Calling function (outer function) can call the callback function as many times as required
* Calling function can pass appropriate parameters according to the task to the called functions. This allows information hiding.
* Improves code modularity and reusability
* Allows you to dynamically change the working of a function without changing its core implementation
example code
def add(a,b):
print(a+b)
def mul(a,b):
print(a+b)
def divide(a,b)
print(a/b)
def compute(func, a,b)
func(a,b)
compute(add, 5,3)
the func can be any name
function is called inside an other function and its calculation is done
EXAMPLE built in function= li.sort(key=len)
MULTIPLE FUNCTIONS CALLED ONCE USING LIST
similar to function of decorator
def function(func_list, x, y):
print(“Inside function”)
for func in func_list:
def add(x,y):
z = x+y
print(‘Sum =’,z)
def divide(x,y):
z = x/y
print(‘Quotient =’,z)
cb_list=[add, divide]
function(cb_list, 10, 5)
the func is called into function and then for loop is used to go throu all the functions, and then cb_list is used to add all the funcs into a list and then call the function which has all the funcs with values
what is closure with example
a nested function which has access to a free variable from an enclosing function that has finished its execution.
a nested function which
inner function is defined inside another function,
the inner function has access to variables and of the outer function
- It has access to a free variable in outer scope
- It is returned from the enclosing function
- A free variable - a variable that is not bound in the local scope.
Closures with immutable variables such as numbers and strings - use the nonlocal keyword.
even if u del the outer fun u can still do the same function using the inner function
python example:
def outer(msg): #outer function
def inner(): # This is the nested function
print(msg) msg=free var
return inner # returns the nested function
another example:
def division(y): #outer function
def divide(x): #inner function
return x/y
return divide
Output:
10.0
32.0
return divide
d1=division(2) #refers to divide
d2=division(3) #refers to divide
print(d1(20))
print(d2(96))
free var is accessed by outer hence thats used
THUS,
IMP: ID of both outer function and inner function is the same
Not all nested functions are closures
for it to be closure:
The inner function has access to the non-local variables or local
variables of the outer function.
2. The outer function must return the inner function.
NON LOCAL VARIABLE
def f1(): #outer function
x=0
def f2(): #inner function
nonlocal x # x - that belongs to scope of outer function is made non-local
x=x+1
return x
return f2
when when var is not declared on the outside variable, u have to use non local, to describe the var so that its non local and can be used in the outer function
Decorators
it allows to modify the behavior of function or class. without modifying the base function/source code or When we need to run the same code on multiple functions. This avoids writing duplicate code.
Eg: logging, test performance, verify permissions and so on
A Decorator is just a function that takes another function as an
argument and extends its behavior without explicitly modifying
it.
Decorators wrap a function and modify its behavior in one or the other way, without changing the source code of the function being decorated.
functions are taken as the argument into another function and then called inside the wrapper function.
multiple decorators can be used in a single function= chaining
example code
def add_sprinkles(func):
def wrapper():
print(“*You add sprinkles *”)
func()
return wrapper
@add_sprinkles
def get_ice_cream():
print(“Here is your ice cream”)
Normal code without @
def func_decorator(func):
def inner_func():
print(“Hello, before the function is called”)
func()
print(“Hello, after the function is called”)
return inner_func
def func_hello():
print(“Inside Hello function”)
hello = func_decorator(func_hello)
hello()
what is a generator
Code to check above generator function
is a function that returns an iterator that produces a sequence of values when iterated over
Iterator - an object that can be iterated upon, like a list
it returns an iterator object with a sequence of values.
A yield statement is used instead of the return statement. the function doesn’t immediately execute and print the value. Instead, it pauses execution and produces a value that can be accessed later.
When the generator function is called, it does not execute the function body immediately. Instead, it returns a generator object that can be iterated over to produce the values.
Generator functions return a generator object that is iterable (used as an iterator).
Generator objects are accessed
* by calling the next method of the generator object
* using the generator object in a “for” loop(generator expression)
def generator_function_name(arg): ………………………
………………………
………………………
yield statement
FOR LOOP
Generator function
def generator_func():
yield 1
yield 2
yield 3
for value in generator_func():
print(value)
CALLING THE NEXT METHOD
Generator function
def generator_func():
yield 10
yield 20
Output:
10
yield 30
#obj is a generator object
obj=generator_func()
when u print obj u get:
<generator object gen at 0x7f43eda29170>
# Iterating over the generator object using next
print(next(obj))
print(next(obj))
print(next(obj))
Generator expression aka for loops and pipeline
Generator function - square
- is another way of writing the generator function.
*Similar to list comprehension technique but instead instead of storing the elements in a list in memory, it creates generator objects. - Syntax:
for element in iterable)
allows for the declaration of a function that behaves like an iterator, making it a faster, cleaner ,easier way to create an iterator.
* are useful to produce a large sequence of values, but don’t want to store all of them in memory at once.
* The simplification of code is a result of generator function and generator expression support provided by Python.
EXAMPLE CODE
generator_exp=(i**2 for i in range(5) if i%2==0)
for i in generator_exp:
print(i)
Pipe line Generators:
Multiple generators can be used to pipeline a series of operations
Generator function - fibonacci_numbers
def fibonacci_numbers(nums):
x,y=0,1
for i in range(nums):
x,y=y,x+y
yield x
def square(nums):
for num in nums:
yield num**2
print(sum(square(fibonacci_numbers(3))))
here
multiple decorators chaining decorators
Chaining Decorators - Decorating a function with multiple decorators.
def decorator_x(func):
def inner_func():
print(“X”20) #Printing X 20 times
func()
print(“X”20) #Printing X 20 times
return inner_func
def decorator_y(func):
def inner_func():
print(“Y”20) #Printing Y 20 times
func()
print(“Y”20) #Printing Y 20 times
return inner_func
def func_hello():
print(“Hello”)
hello = decorator_y(decorator_x(func_hello)) #Chaining Decorators
hello()
Output:
YYYYYYYYYYYYYYYYYYYY
XXXXXXXXXXXXXXXXXXXX
Hello
XXXXXXXXXXXXXXXXXXXX
YYYYYYYYYYYYYYYYYYYY
yield vs return
YIELD
Returns a value and pauses the execution
while maintaining the internal states
Used to convert a regular Python function into a generator
Used when the generator returns an
intermediate result to the caller
Code written after yield statement
execute in next function call
It can run multiple times
RETURN
Returns a value and terminates the
execution of the function
Used to return the result to the caller statement
Used when a function is ready to send a
value
Code written after return statement
won’t execute
It only runs a single time
We can’t include return inside a generator function. If we do, it will terminate the
function.
what are GUI and tkinter
syntax GUI
provide an intuitive and visual method of interacting with software applications.
import tkinter
root = tkinter.Tk() #creates window
root.mainloop() #loops continuously until we close the window
mainloop()
* A function that continuously loops and displays the window till we
close it or an action closes the window.
until the user exits
the program by closing the window, or by terminating the program
can track the movements of the mouse on the window because it
constantly loops
syntax of GUI
import tkinter —> imports tkinter
root.tkinter.Tk() —> creates a new window
root.title(“ “) —>used for writes title
root.geometry(‘ ‘) —> used for defining dimensions of the window
what are widgets
After creating window, we need to add elements to make it more
interactive.
Those are called widgets
Each element in tkinter is a widget
Each separate widget is a Python object.
in widget, we must pass its parent as a parameter to the widget creation function.
* The ‘root’ window is an exception as it is the top-level window that will
contain everything else and does not have a parent.
types of widgets and basic syntax
Steps to add widget to the Window
1. Create widget
2. Add it to the Window
To display it we need:
pack() - packs widgets in rows or columns (stacking layout)
2. grid() - position widgets using rows and column table like layout
3. place() - explicitly set the position and size of a window, either in
absolute terms, or relative to another window. can place anywhere unlike grid and pack() and grid()
button
cavnas —> To draw a complex layout and pictures (like graphics, text etc.)
Checkbutton—> To display a number of options as checkboxes
Entry—-> To display a single-line text field that accepts values from the user
Frame —> To group and organize other widgets
Label —> To provide a single-line caption, can contain images also.
Listbox —> To provide a user with a list of options
Menu —> Creates all kinds of menus required in the application
Menubutton —> To display the menu items to the user
Spinbox->“entry” widget in which value can be input just by selecting a fixed value of numbers
Panned window: A container widget that is mainly used to handle different panes
button
b=Button(parent,options)
from tkinter import *
win =Tk() => button syntax
win.title(“TITLE”)
win.geometry(‘300x200’)
b=Button(win, text=’Submit’)
b.pack()
=> adds the button to the window
win.mainloop()
BUTTON FUNCTIONS
from tkinter import messagebox
#message box
def click():
messagebox.showinfo(“Message”, “Green”)
(message box appears)
=> pady = height of button
activeforeground=”yellow”
@color of text when clicked
activebackground=”orange
@color of button when u clicked
=>side=LEFT direction of side
=> command=click
when u click action can happen, its a function name, can be any name
EXAMPLE OF BUTTON SYNTAX
c=Button(win,text=”Green”, command=click,
activeforeground = “green”,activebackground=”orange”, pady=10)
CANVAS
W=Canvas(parent,option
=value)
cv=Canvas(win, bg = “red”, height =”300”)
=> win= parent name
cv.pack()
win.mainloop()
creating arcs
coord = 10, 10, 300, 300
#boundary of circle
x1,y1,x2,y2
arc1=cv.create_arc(coord, start=0, extent=150, fill=”pink”)
arc2=cv.create_arc(coord, start=150, extent=215, fill=”green”)
IMPORT PICTURE
filename=PhotoImage(file=”nature.png”)
image=cv.create_image(20, 20, anchor=NW, image=filename)
This creates an image on the canvas cv at the coordinates (20, 20),
anchor=NW: This means the top-left corner of the image will be anchored at the coordinates (20, 20). NW stands for the “North-West” corner (top-left).
image=filename: specifies the image
functions of checkbutton, and radio button
W = Checkbutton(parent,option=value)
from tkinter import *
cb1=Checkbutton(win,text=”Yes”, varible=1)
cb1.pack()
k= IntVar() print the boolean val, with the help of a button, when checked(1), unchecked(0)
String(var) also used
.get(): Retrieves the current value stored in the var or IntVar().
onvalue= can be int or string use String(var)
offvalue=same thing normal OUT=bool
RADIO BUTTON:
allows u to click only one option
Radiobutton(funcname, option)
1)deselect() – to turn off the checkbutton
2) flash(): The checkbutton is flashed between the active and normal colors.
3) invoke(): invoke the method associated with the checkbutton.
4) select(): to turn on the checkbutton.
5) toggle(): to toggle between the different Checkbuttons.