Posts

Showing posts with the label functions

Map(), Filter() and Reduce() - Higher Order Functions

 Basically, all these high-order functions apply a function to an iterable. from functools import reduce def square ( n ): return n ** 2 def greaterThan ( n ): return n > 2 def addAll ( n , m ): return n + m mylist =[ 1 , 2 , 3 , 4 , 5 ] print ( list ( map ( square , mylist ))) print ( list ( filter ( greaterThan , mylist ))) print ( reduce ( addAll , mylist ))

Functions and the various types of arguments they can take

This code snippet is about functions, its parameters and the various types of arguments a function can take. def funct(): print("I am a function that takes no value as input.") def country(countryname="Pakistan"): #parameter with default value print("The name of my country is", countryname) def greet(fname, lname): # fuction takes NMT and NLT 2 parameters print("Good evening", fname, lname) def person(*args): # accepts variable number of positional arguments print(args) # returns result with quotes, commas and brackets print(*args) # returns result without quotes, commas and brackets print(len(args)) # returns number of arguments given print(type(args)) # returns type of data which is tuple def personData(**kwargs): # accepts variable number of keyword arguments print(kwargs) # returns result with quotes, commas and brackets print(*kwargs) # returns only keys (without quotes, commas and brackets)

Fraud Checker Program in Python

Rohan is a cheater who created a function to print multiplication tables for input numbers. We created a function that validates Rohan tables and tells whether Rohan is a fraud or not. Enjoy! # FRAUD Checker: This program checks whether Rohan Das is a fraud or not. # whether Rohan Das function returns the multiplication tables correctly or not import random def rohanTables(n): tabletList = [] for i in range(1, 11): randomNumber = random.randint(3,9) if i == randomNumber: result=(randomNumber*n) + random.randint(1, 4) else: result=i*n tabletList.append(result) return tabletList def validateRohandTables(n): tabletList = [] for i in range(1, 11): result=i*n tabletList.append(result) return tabletList whichTable = int(input("Which table do you want: ")) conclusions = [] for i in range(5): r = rohanTables(whichTable) print(r) v = validateRohandTables(whichTable) p

Recursion in Python

The recursion concept in Python is explained through the factorial and the Fibonacci sequence. # factorial(0) = 1 # factorial(1) = 1 # factorial(7) = 7*6*5*4*3*2*1 # factorial(7) = 7*factorial(6) # factorial(7) = 7*6*factorial(5) # factorial(7) = 7*6*5*factorial(4) # factorial(7) = 7*6*5*4*factorial(3) # factorial(7) = 7*6*5*4*3*factorial(2) # factorial(7) = 7*6*5*4*3*2*factorial(1) # factorial(7) = 7*6*5*4*3*2*1 # factorial(4) = 4*3*2*1 # factorial(n) = n*factorial(n-1) def findFactorial(n): if n==0 or n==1: return 1 else: return n * findFactorial(n-1) print(findFactorial(5)) # fibonachi numbers sequence = 0 1 1 2 3 5 8 13 .... def findFibonachiNo(n): if n==0: return 0 elif n==1: return 1 else: return findFibonachiNo(n-1) + findFibonachiNo(n-2) print(findFibonachiNo(6))

Function in Python that Reverse a given List

 The following function in python will return the reverse of the given list. def reverseList(n): reverseL = uList[:] for i in range(len(reverseL)//2): reverseL[i], reverseL[len(reverseL)-i-1] = reverseL[len(reverseL)-i-1], reverseL[i] print(f"The reverse of the original list {uList} is {reverseL}") uList = [45,66,7,1,333] reverseList(uList)

Text to Speech conversion in Python

from win32com.client import Dispatch speak_it = Dispatch("SAPI.SpVoice") string = input("Enter the text and we will speak it: ") speak_it.Speak(string)

Function Caching in Python

import time from functools import lru_cache @lru_cache(maxsize=1) def add_work(n, m): time.sleep(3) return n + m print(add_work(3,4)) # takes 3 secs to print print(add_work(3,5)) # takes 3 secs to print print(add_work(3,4)) # takes 3 secs to print print(add_work(3,5)) # takes 3 secs to print print(add_work(3,5)) # this and rest takes no time to print print(add_work(3,5)) print(add_work(3,5)) print(add_work(3,5)) ###############################################3 # Following takes user input for defining maxsize import time from functools import lru_cache @lru_cache(maxsize=int(input("Enter maxsize for lru_cache: "))) def some_work(n, m): time.sleep(3) return n + m print(some_work(3,4)) print(some_work(3,5)) print(some_work(3,4)) print(some_work(3,5)) print(some_work(3,4)) print(some_work(3,5))

Lambda function or Anonymous function

a , b = 3 , 4 d = lambda a , b : a + b c = d ( a , b ) print ( c ) Result = 7

Making a Function in Python that converts centimeters into inches

Image
Functions in Python are very convenient. The tasks that are to be performed multiple times in Python programming can become very tedious. Fort this reason 'functions' are employed.  We simply put some repetitive task into a function and after that, we have just to recall the defined function and the result will be thrown at us in an instant. That is the beauty of python functions. Below we have defined a function for converting centimeters into inches. Now we don't need to write the formula again and again in our code to convert centimeters into inches. We just have to call the function and put our value in centimeters and the same function will convert it into inches. That's all! Syntax of Functions: def ----------> define inches--------> function name ()--------------> parameter that takes an argument return ---------> keyword in python that returns the result formula---------> the body of function Centimeters into Inches Function Definition def inches

The First Ever Python Program - Learning print() function

Image
Hi Everyone! This is the first-ever Python program that I learned in my life and the same is true I bet pretty much about every absolute beginner like me. Anybody who newly steps into programming will encounter this program learning.  This is indeed a baby program but it matters much as far as the absolute newbie is concerned.  This program is learning to use the print function, i.e.  print() Let's learn how to use this function! This is actually a built-in function in Python and is used to print anything that we want to display to the user.  It is very simple to use. Just type in the round parenthesis of print function your desired text that you want to be shown at the terminal or displayed to the end-user. And don't forget to quote-unquote your text.  Let's understand this with an example; Let's say I want to print 'Good morning' to the user. All I have to do is the following; print("Good morning") . . .and the user should see the message   'Good