0% found this document useful (0 votes)
4 views71 pages

Python Notes Unrestricted

The document provides comprehensive notes on Python programming, covering its key features, syntax, data types, variable naming rules, control flow statements, and various programming examples. It includes detailed explanations of lists and tuples, their methods, and common operations such as appending, sorting, and accessing elements. Additionally, it presents a variety of number-related programming tasks, demonstrating Python's capabilities in handling mathematical operations.

Uploaded by

Charan Deep . R
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views71 pages

Python Notes Unrestricted

The document provides comprehensive notes on Python programming, covering its key features, syntax, data types, variable naming rules, control flow statements, and various programming examples. It includes detailed explanations of lists and tuples, their methods, and common operations such as appending, sorting, and accessing elements. Additionally, it presents a variety of number-related programming tasks, demonstrating Python's capabilities in handling mathematical operations.

Uploaded by

Charan Deep . R
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON PROGRAMMING NOTES

Python is a high-level, interpreted programming language known for its simplicity and readability. It
is widely used in a variety of fields, including web development, data science, artificial intelligence,
scientific computing, automation, and more. Here are some key features of Python:

Easy Syntax

Interpreted Language

Object-Oriented programming

Extensive Libraries

Cross-Platform.

Basic Python Syntax

print("Hello, World!")

Comment Line Statement

Single-line comment: # This is a comment

Multi-line comment:

"""

This is a

Multi-line comment.

"""

Data Types

It Indicate Which Type of Data the Value Will Representing

Basic Data Types:

String (str): Sequence of characters.

Integer (int): Whole numbers.

Float (float): Decimal numbers.

Boolean (bool): True or False.

Variable

variable is a container to store a value

variable is nothing but it will have a unique name for value

Rule For Naming A Variable

Valid Characters:

Variable names can consist of letters (both uppercase and lowercase), digits (0-9), and
underscores (_).

The first character must be a letter or an underscore. It cannot start with a digit.

■ No Special Characters:

Variable names cannot include special characters such as @, $, %, #, etc.


■ Case Sensitivity:

Variable names are case-sensitive. For example, variable, Variable, and VARIABLE are considered
three different variables.

■ Length:

While there is no strict limit on the length of variable names, it’s best practice to keep them
reasonably short yet descriptive for readability.

■ No Reserved Keywords:

Variable names cannot be the same as C reserved keywords (e.g., int, return, if, while, etc.).

EXAMPLE

■ age

■ total_sum

■ username

■ score1

INVALID EXAMPLE

■ 1stPlace (starts with a digit)

■ total# (contains a special character)

■ int (a reserved keyword)

Variable Decleration

Syntax

Variable=value

Example:

name = "Alice" # String

age = 30 # Integer

height = 5.6 # Float

is_student = True # Boolean

Operators

Here's a summary of Python operators presented in a tabular format:

(condition) ? : ;

if (condition) else

Control Flow Statements

Conditional Statement:

if statement

Executes a block of code if the condition is true.


Example

x=5

if x > 0:

print("x is positive") # This will print because 5 is greater than 0

elif statement (else if)

Used when you have multiple conditions to check.

Example

x=0

if x > 0:

print("x is positive")

elif x == 0:

print("x is zero") # This will print because x is equal to 0

else statement

Executes a block of code if none of the previous conditions are true.

Example

x = -1

if x > 0:

print("x is positive")

elif x == 0:

print("x is zero")

else:

print("x is negative") # This will print because x is less than 0

Looping Statements:

while loop

Repeats a block of code as long as a condition is true.

Example

# Print numbers 1 to 5

x=1

while x <= 5:

print(x)

x += 1 # Increment x by 1 each time

for loop:

Used to iterate over a sequence (like a list, tuple, string, etc.)


Example:

for i in range(1, 11):

print(i)

Break, continue, and pass:

These are used within loops to control the flow of execution.

Example:

Break

for x in range(10):

if x == 5:

break # Exit the loop when x equals 5

print(x)

continue

for x in range(5):

if x == 3:

continue # Skip when x is 3

print(x)

pass

for x in range(5):

if x == 3:

pass # Do nothing when x is 3

else:

print(x)

Nested if:

x=5

if x > 0:

if x == 5:

print("x is 5") # This will print because x equals 5

Number programming

1. Reverse of Number

number = 12345

reversed_number = 0

while number > 0:


digit = number % 10 # Get the last digit

reversed_number = reversed_number * 10 + digit # Add the digit to the reversed number

number = number // 10 # Remove the last digit from the number

print("Reversed number:", reversed_number)

[Link] Number

number = 5

result = 1

for i in range(1, number + 1):

result *= i # Multiply result by each number from 1 to n

print("Factorial of", number, "is:", result)

[Link] of n numbers

n = 5 # Change this to any value for 'n'

sum_of_numbers = 0

for i in range(1, n + 1):

sum_of_numbers += i # Add each number from 1 to n to the sum

print("Sum of the first", n, "numbers is:", sum_of_numbers)

[Link] series

a = -1

b=1

for i in range(1, 6):

c = a + b # Calculate c as the sum of a and b

print(c)

a = b # Update a to the value of b

b = c # Update b to the value of c

[Link] of loop

# Original range

n=5

# Reversing the range using a for loop

for i in range(n, 0, -1): # Start from n and go down to 1

print(i, end=" ")

[Link] first and last number

n = 12345
# Last digit (using modulus)

last_digit = n % 10

# First digit (by repeatedly dividing n by 10 until it is less than 10)

first_digit = n

while first_digit >= 10:

first_digit = first_digit // 10

print("First digit:", first_digit)

print("Last digit:", last_digit)

[Link] or even number program

n = 12345 # You can replace this with any number

# Check if the number is even or odd

if n % 2 == 0:

print(f"{n} is even")

else:

print(f"{n} is odd")

[Link] number program

n = 29 # Replace with any number you want to check

is_prime = True # Assume the number is prime

if n <= 1:

is_prime = False

else:

for i in range(2, int(n**0.5) + 1):

if n % i == 0:

is_prime = False

break # No need to check further if we find a divisor

if is_prime:

print(f"{n} is a prime number.")

else:

print(f"{n} is not a prime number.")

[Link] program

n = 12321
original_n = n

reversed_n = 0

while n > 0:

reversed_n = reversed_n * 10 + n % 10

n //= 10

if original_n == reversed_n:

print(f"{original_n} is a palindrome number.")

else:

print(f"{original_n} is not a palindrome number.")

[Link] number

Example:

6=1+2+3

n = 28 # Replace with any number you want to check

divisors_sum = 0

# Calculate the sum of divisors

for i in range(1, n):

if n % i == 0:

divisors_sum += i

if divisors_sum == n:

print(f"{n} is a perfect number.")

else:

print(f"{n} is not a perfect number.")

[Link] Square number

n = 16 # Replace with any number you want to check

# Initialize a variable to track if the number is a perfect square

is_perfect_square = False

# Loop through possible values from 1 to n // 2 to find the square root

for i in range(1, n + 1):

if i * i == n:

is_perfect_square = True

break # No need to continue if we find the perfect square

if is_perfect_square:
print(f"{n} is a perfect square.")

else:

print(f"{n} is not a perfect square.")

[Link] of PrimeNumbers

start = 10 # Starting number of the range

end = 50 # Ending number of the range

# Loop through the range and check for prime numbers

for n in range(start, end + 1):

if n <= 1:

continue # Skip numbers less than or equal to 1

is_prime = True

for i in range(2, int(n**0.5) + 1):

if n % i == 0:

is_prime = False

break

if is_prime:

print(n, end=" ")

[Link] Number

Example:

N=3

N+1=4 check weather it is perfect square or not

n = 3 # Replace with any number you want to check

# Check if the successor (n + 1) is a perfect square

successor = n + 1

is_perfect_square = False

# Loop to check if successor is a perfect square

for i in range(1, successor + 1):

if i * i == successor:

is_perfect_square = True

break

if is_perfect_square:

print(f"{n} is a Sunny Number.")


else:

print(f"{n} is not a Sunny Number.")

[Link] number

Example:

1!+4!+5!=1+24+120=145

n = 145 # Replace with the number you want to check

original_n = n

sum_of_factorials = 0

# Loop through the digits of the number

while n > 0:

digit = n % 10 # Extract the last digit

factorial = 1 # Calculate factorial of the digit

for i in range(1, digit + 1):

factorial *= i

sum_of_factorials += factorial

n //= 10 # Remove the last digit

# Check if the sum of factorials equals the original number

if sum_of_factorials == original_n:

print(f"{original_n} is a Peterson Number.")

else:

print(f"{original_n} is not a Peterson Number.")

[Link] Number

For example: 18 is a Nive Number because 1+8=9 and 18%9=0.

n = 18 # Replace with any number

original_n = n

digit_sum = 0

while n > 0:

digit_sum += n % 10

n //= 10

if original_n % digit_sum == 0:

print(f"{original_n} is a Harshad Number.")

else:
print(f"{original_n} is not a Harshad Number.")

[Link] number

A Spy Number is a number where the sum of its digits equals the product of its digits. For example:
1124 is a Spy Number because 1+1+2+4=8 and 1×1×2x4=8

n = 1124 # Replace with any number

digit_sum = 0

digit_product = 1

while n > 0:

digit = n % 10

digit_sum += digit

digit_product *= digit

n //= 10

if digit_sum == digit_product:

print(f"{n} is a Spy Number.")

else:

print(f"{n} is not a Spy Number.")

LIST

# LIST IS MUTABLE

[Link] OF LIST

list1 = ["apple", "banana", "cherry"]

list2 = [1, 5, 7, 9, 3,9]

list3 = [True, False, False]

list4 = ["abc", 34, True, 40, "male"]

[Link] FIND A TYPE

mylist = ["apple", "banana", "cherry"]

print(type(mylist))

[Link] FIND A LENGTH

thislist = ["apple", "banana", "cherry"]

print(len(thislist))

[Link] ACCESS THE LIST ITEM

thislist = ["apple", "banana", "cherry"]


print(thislist[1])

[Link] BY USING NEGATIVE INDEX

thislist = ["apple", "banana", "cherry"]

print(thislist[-1])

[Link] RANGING FUNCTION

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[2:5])

6.1

#IT WILL RETURN FROM 0 T0 4

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[:4])

6.2

#IT WILL RETURN FROM 2 TO TILL END

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[2:])

[Link] RANGING BY USING NEGATIVE INDEX

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[-4:-1])

[Link] THE LIST ELEMENT

thislist = ["apple", "banana", "cherry"]

thislist[1] = "blackcurrant"

print(thislist)

8.1

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]

thislist[1:3] = ["blackcurrant", "watermelon"]

print(thislist)

[Link] IN FUNCTIONS IN LIST

9.1 INSERT FUNCTION

thislist = ["apple", "banana", "cherry"]

[Link](2, "watermelon")

print(thislist)
[Link] FUNCTION

# add at end of the list

thislist = ["apple", "banana", "cherry"]

[Link]("orange")

print(thislist)

[Link] FUNCTION

a = ["apple", "banana", "cherry"]

b= ["mango", "pineapple", "papaya"]

[Link](b)

print(a)

[Link] FUNCTION

thislist = ["apple", "banana", "cherry"]

[Link]("banana")

print(thislist)

[Link] FUNCTION

# USE INDEXING VALUE FOR POP

thislist = ["apple", "banana", "cherry"]

[Link](1)

print(thislist)

[Link] FUNCTION

# USE INDEXING VALUE FOR DEL

thislist = ["apple", "banana", "cherry"]

del thislist[0]

print(thislist)

[Link] FUNCTION

#IT WILL THE WHOLE LIST AND RETURN EMPTY LIST

thislist = ["apple", "banana", "cherry"]

[Link]()

print(thislist)

[Link] THROUGH LIST

thislist = ["apple", "banana", "cherry"]

for x in thislist:
print(x)

[Link] THE LIST

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = []

for x in fruits:

if "a" in x:

[Link](x)

print(newlist)

[Link] OF LIST

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]

[Link]()

print(thislist)

[Link] OF LIST

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]

[Link]()

print(thislist)

[Link] OF LIST

thislist = ["apple", "banana", "cherry"]

mylist = [Link]()

print(mylist)

[Link] OF LIST

list1 = ["a", "b", "c"]

list2 = [1, 2, 3]

list3 = list1 + list2

print(list3)

LIST METHODS

append()- Adds an element at the end of the list

clear()-Removes all the elements from the list

copy()-Returns a copy of the list

count()-Returns the number of elements with the specified value

extend()-Add the elements of a list (or any iterable), to the end of the current list
index()-Returns the index of the first element with the specified value

insert()-Adds an element at the specified position

pop()-Removes the element at the specified position

remove()-Removes the item with the specified value

reverse()-Reverses the order of the list

sort()-Sorts the list

TUPLES

#TUBLE IS IMMUTABLE

[Link] OF TUPLES

tuple1 = ("apple", "banana", "cherry")

tuple2 = (1, 5, 7, 9, 3)

tuple3 = (True, False, False)

tuple4 = ("abc", 34, True, 40, "male")

1.1 TO PRINT TUPLE

print(tuple)

[Link] FIND TYPE OF TUPLE

mytuple = ("apple", "banana", "cherry")

print(type(mytuple))

[Link] LENGTH OF TUPLE

thistuple = ("apple", "banana", "cherry")

print(len(thistuple))

[Link] TUPLE ITEM

thistuple = ("apple", "banana", "cherry")

print(thistuple[1])

#ACCESSING

[Link]

[Link] INDEXING

[Link]

[Link] THROUGH IN KEYWORD

thistuple = ("apple", "banana", "cherry")

if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

[Link] TUPLE

Change Tuple Values

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it
also is called.

But there is a workaround. You can convert the tuple into a list, change the list, and convert the list
back into a tuple.

Convert the tuple into a list to be able to change it:

x = ("apple", "banana", "cherry")

y = list(x)

y[1] = "kiwi"

x = tuple(y)

print(x)

[Link] FUNCTION

thistuple = ("apple", "banana", "cherry")

y = list(thistuple)

[Link]("orange")

thistuple = tuple(y)

[Link] OF TUPLE

tuple1 = ("a", "b" , "c")

tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2

print(tuple3)

8.1 MULTIPLYING TUPLES

fruits = ("apple", "banana", "cherry")

mytuple = fruits * 2

print(mytuple)

[Link] FUNCTION

thistuple = ("apple", "banana", "cherry")

y = list(thistuple)

[Link]("apple")

thistuple = tuple(y)
[Link] FUNCTION

thistuple = ("apple", "banana", "cherry")

del thistuple

print(thistuple)

[Link] TUPLE

#e are also allowed to extract the values back into variables. This is called "unpacking":

fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)

print(yellow)

print(red)

9.1 USING *(ASTRICK) IN UNPACKING

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits

print(green)

print(yellow)

print(red)

[Link] THROUGH TUPLE

thistuple = ("apple", "banana", "cherry")

for x in thistuple:

print(x)

[Link] METHOD

count()-Returns the number of times a specified value occurs in a tuple

index()-Searches the tuple for a specified value and returns the position of where it was found

SET

#SET WILL NOT ALLOW DUPLICATE

[Link] OF SET

set1 = {"apple", "banana", "cherry"}

set2 = {1, 5, 7, 9, 3}

set3 = {True, False, False}


set4= {"abc", 34, True, 40, "male"}

[Link] FIND TYPE

myset = {"apple", "banana", "cherry"}

print(type(myset))

[Link] IN SET OR NOT

thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)

OR

thisset = {"apple", "banana", "cherry"}

print("banana" not in thisset)

[Link] ELEMENT IN SET

thisset = {"apple", "banana", "cherry"}

[Link]("orange")

print(thisset)

[Link] CONCATINATE THE SET

thisset = {"apple", "banana", "cherry"}

tropical = {"pineapple", "mango", "papaya"}

[Link](tropical)

print(thisset)

[Link] REMOVE A SET ELEMENT

thisset = {"apple", "banana", "cherry"}

[Link]("banana")

print(thisset)

[Link] DISCARD A SET ELEMENT

thisset = {"apple", "banana", "cherry"}

[Link]("banana")

print(thisset)

[Link] FUNCTION

thisset = {"apple", "banana", "cherry"}

x = [Link]()

print(x) #removed item


print(thisset) #the set after removal

[Link] FUNCTION

thisset = {"apple", "banana", "cherry"}

[Link]()

print(thisset)

[Link] FUNCTION

thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)

[Link] IN SET

thisset = {"apple", "banana", "cherry"}

for x in thisset:

print(x)

[Link] SETS

12.1 UNION

#UNION OPERATOR--> |

set1 = {"a", "b", "c"}

set2 = {1, 2, 3}

set3 = {"John", "Elena"}

set4 = {"apple", "bananas", "cherry"}

myset = [Link](set2, set3, set4)

12.1.1 UNION USING OPERATOR

set1 = {"a", "b", "c"}

set2 = {1, 2, 3}

set3 = {"John", "Elena"}

set4 = {"apple", "bananas", "cherry"}

myset = set1 | set2 | set3 |set4

print(myset)

print(myset)

12.2 INTERSECTION

#INTERSECTION OPERATOR--->&

set1 = {"apple", "banana", "cherry"}

set2 = {"google", "microsoft", "apple"}


set3 = [Link](set2)

print(set3)

12.2 INTERSECTION USING OPERATOR

set1 = {"apple", "banana", "cherry"}

set2 = {"google", "microsoft", "apple"}

set3 = set1 & set2

print(set3)

12.3 DIFFERENCE

#DIFFERENCE OPERATOR-->-

set1 = {"apple", "banana", "cherry"}

set2 = {"google", "microsoft", "apple"}

set3 = [Link](set2)

print(set3)

12.3.1 DIFFERENCE USING OPERATOR

set1 = {"apple", "banana", "cherry"}

set2 = {"google", "microsoft", "apple"}

set3 = set1 - set2

print(set3)

12.4 SYMMETIC DIFFERENCE

#SYMMETIC DIFFERENCE SYMBOL--->^

set1 = {"apple", "banana", "cherry"}

set2 = {"google", "microsoft", "apple"}

set3 = set1.symmetric_difference(set2)

print(set3)

12.4.1 SYMMETRIC DIFFERENCE USING SYMBOL

set1 = {"apple", "banana", "cherry"}

set2 = {"google", "microsoft", "apple"}

set3 = set1 ^ set2

print(set3)

[Link] METHOD

add()-Adds an element to the set

clear()-Removes all the elements from the set


copy()-Returns a copy of the set

difference()-Returns a set containing the difference between two or more sets

DICTIONARIES

[Link] OF DICTIONARIES

thisdict = {

"brand": "Ford",

"electric": False,

"year": 1964,

"colors": ["red", "white", "blue"]

print(thisdict)

[Link] OF DICT

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

print(type(thisdict))

[Link] OF DICT

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

print(thisdict["brand"])

[Link] FIND LENGTH OF DICT

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964,

"year": 2020

print(len(thisdict))
[Link] GET A KEY IN DICT

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = [Link]()

print(x)

[Link] KEY VALUE AFTER SOME CHANGES

car = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = [Link]()

print(x) #before the change

car["color"] = "white"

print(x) #after the change

[Link] THE VALUES IN DICT

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict["year"] = 2018

print(thisdict)

[Link] FUNCTION

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964
}

[Link]({"year": 2020})

print(thisdict)

[Link] FUNCTION

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

[Link]("model")

print(thisdict)

[Link] FUNCTION

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

[Link]()

print(thisdict)

[Link] FUNCTION

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

del thisdict["model"]

print(thisdict)

[Link] FUNCTION

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964
}

[Link]()

print(thisdict)

[Link] IN DICT

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x in thisdict:

print(x)

[Link] GET A KEY USING LOOP

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x in [Link]():

print(x)

[Link] GET A VALUE USING A LOOP

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x in [Link]():

print(x)

[Link] DICT

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

}
mydict = [Link]()

print(mydict)

[Link] DICT

myfamily = {

"child1" : {

"name" : "Emil",

"year" : 2004

},

"child2" : {

"name" : "Tobias",

"year" : 2007

},

"child3" : {

"name" : "Linus",

"year" : 2011

print(myfamily)

ARRAY

[Link] OF ARRAY

cars = ["Ford", "Volvo", "BMW"]

print(cars)

[Link] THE ELEMENT OF ARRAY

cars = [" Ford", "Volvo", "BMW"]

x = cars[0]

print(x)

[Link] FIND LENGTH

cars = ["Ford", "Volvo", "BMW"]

x = len(cars)

print(x)

[Link] IN ARRAY
cars = ["Ford", "Volvo", "BMW"]

for x in cars:

print(x)

[Link] FUNCTION

cars = ["Ford", "Volvo", "BMW"]

[Link]("Honda")

print(cars)

[Link] FUNCTION

cars = ["Ford", "Volvo", "BMW"]

[Link](1)

print(cars)

[Link] FUNCTION

cars = ["Ford", "Volvo", "BMW"]

[Link]("Volvo")

print(cars)

[Link] METHODS

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Array programming

Reverse of Array

# Example array (list)

arr = [1, 2, 3, 4, 5]

# Reversing the array using slicing

reversed_arr = arr[::-1]
print("Reversed array using slicing:", reversed_arr)

Reverse of Array using logic

# Example array

arr = [1, 2, 3, 4, 5]

# Reversing the array manually using a temporary variable

start = 0

end = len(arr) - 1

# Swap elements from start to end

while start < end:

# Normal swap using a temporary variable

temp = arr[start] # Store the element at start

arr[start] = arr[end] # Place the element at end to start

arr[end] = temp # Place the element at start to end

# Move the pointers towards the center

start += 1

end -= 1

# Print the reversed array

print("Reversed array (manual swap):", arr)

Sum of Array

# Example array

arr = [1, 2, 3, 4, 5]

# Manually calculating the sum

total_sum = 0

for num in arr:

total_sum += num # Add each element to total_sum

print("Sum of the array (manual method):", total_sum)

Maximum and minimum number in Array

# Example array

arr = [1, 2, 3, 4, 5, -1, -2]

# Initializing max and min

max_val = arr[0]

min_val = arr[0]

# Iterating through the array


for num in arr:

if num > max_val:

max_val = num

if num < min_val:

min_val = num

# Printing the result

print("Maximum Value:", max_val)

print("Minimum Value:", min_val)

Remove Duplicate element from a array

# Example array with duplicates

arr = [1, 2, 2, 3, 4, 4, 5, 5]

# Create an empty list for unique elements

unique_arr = []

# Iterate through the original array

for num in arr:

if num not in unique_arr:

unique_arr.append(num)

# Print the result

print("Array after removing duplicates:", unique_arr)

Sum of All odd numbers

# Example array

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Variable to store the sum of odd numbers

sum_odds = 0

# Iterate through the array

for num in arr:

if num % 2 != 0: # Check if the number is odd

sum_odds += num

# Print the result

print("Sum of all odd numbers:", sum_odds)

kth largest number

# Example array

arr = [12, 3, 5, 7, 19, 1]


k=3

n = len(arr)

# Step 1: Sort the array using bubble sort

for i in range(n):

for j in range(0, n-i-1):

if arr[j] > arr[j+1]:

arr[j], arr[j+1] = arr[j+1], arr[j] # Swap elements

# Step 2: The kth largest element is at index (n-k)

print(f"The {k}th largest element is:", arr[n-k])

Move All Negative Numbers to the End

# Example array

arr = [1, -2, 3, -4, 5, -6]

n = len(arr)

# Step 1: Create a new array to hold positive numbers

positive_index = 0

for i in range(n):

if arr[i] >= 0:

arr[positive_index] = arr[i]

positive_index += 1

# Step 2: Add the negative numbers at the end of the array

for i in range(n):

if arr[i] < 0:

arr[positive_index] = arr[i]

positive_index += 1

print("Array after moving negatives to the end:", arr)

Rotate a array by kth position

# Example array

arr = [1, 2, 3, 4, 5]

k=2

n = len(arr)

# Step 1: Normalize k to be within array length

k=k%n
# Step 2: Rotate the array using a simple loop

for _ in range(k):

last_element = arr[n-1]

for i in range(n-1, 0, -1):

arr[i] = arr[i-1]

arr[0] = last_element

print("Array after rotating right by", k, "positions:", arr)

Majority of element in a Array

def majority_element(arr):

# Initialize variables

arr_dict = {}

majority_element = None

# Create a dictionary for each candidate and its count

for i in arr:

arr_dict[i] = arr_dict.get(i, 0) + 1

# Check if there is no majority element

if len(set(arr_dict.values())) == 1:

return None

# Find the majority element

for key in arr_dict:

if majority_element is None:

majority_element = key

continue

elif arr_dict[key] > arr_dict[majority_element]:

majority_element = key

return majority_element

# Example array

#arr = [1, 2, 3, 4, 1, 1, 1, 1]

arr = [3, 3, 4, 2, 4, 4, 2, 4, 4, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]

major_element = majority_element(arr)

if major_element:

# Print the majority element


print("The majority element is:", major_element)

else:

print("There is no majority element.")

STRING

print("Hello")

print('Hello')

ASSIGN A STRING TO VARIABLE

a = "Hello"

print(a)

STRING QUOTES

print("It's alright")

print("He is called 'Johnny'")

print('He is called "Johnny"')

MULTILINE STRING

a = """Lorem ipsum dolor sit amet,

consectetur adipiscing elit,

sed do eiusmod tempor incididunt

ut labore et dolore magna aliqua."""

print(a)

OR

a = '''Lorem ipsum dolor sit amet,

consectetur adipiscing elit,

sed do eiusmod tempor incididunt

ut labore et dolore magna aliqua.'''

print(a)

ACCESSING OF STRING

a = "Hello, World!"

print(a[6])

LOOP THROUGH A STRING

for x in "banana":

print(x)
CHECK WEATHER STRING IS PRESENT OR NOT

INFUNCTION

txt = "The best things in life are free!"

if "free" in txt:

print("Yes, 'free' is present.")

NOT IN FUNCTION

txt = "The best things in life are free!"

if "expensive" not in txt:

print("No, 'expensive' is NOT present.")

STRING SLICING

b = "Hello, World!"

print(b[:5])

[Link] INDEXING

2. NEGATIVE INDEXING

STRING FUNCTIONS INBUILD FUNCTIONS

[Link] FUNCTION

a = "Hello, World!"

print([Link]())

[Link] FUNCTION

a = "Hello, World!"

print([Link]())

[Link] FUNCTION

#TO REMOVE A WHITE SPACE

a = " Hello, World! "

print([Link]()) # returns "Hello, World!"

[Link] FUNCTION

a = "Hello, World!"

print([Link]("H", "J"))

[Link] FUNCTION

a = "Hello, World!"

print([Link](",")) # returns ['Hello', ' World!']


CONCATINATION OF STRING

a = "Hello"

b = "World"

c=a+""+b

print(c)

STRING FORMAT

age = 36

txt = "My name is John, I am " + age

print(txt)

1. FORMAT

age = 36

txt = f"My name is John, I am {age}"

print(txt)

[Link] HOLDER AND MODIFIER

price = 59

txt = f"The price is {price} dollars"

print(txt)

2.1

txt = f"The price is {20 * 59} dollars"

print(txt)

ESCAPE CHARACTER

txt = "We are the so-called \"Vikings\" from the north."

print(txt)

String Programming

Length of the String

# Calculate length of a string

s = "Hello"

length = 0

for char in s:

length += 1

print("Length of the string:", length) # Output: 5


Check if a Character is in a String

# Check if a string contains a specific character

s = "Hello"

char_to_search = "o"

found = False

for char in s:

if char == char_to_search:

found = True

break

print("Does the string contain '{}'? {}".format(char_to_search, found)) # Output: True

String Slicing (Substring Extraction)

# Slice a string (extract substring from start to end)

s = "Hello"

start = 1

end = 4

substring = ' '

for i in range(start, end):

substring += s[i]

print("Sliced string:", substring) # Output: ell

Count Occurrences of a Character

# Count occurrences of a character in a string

s = "Hello World"

char_to_count = "o"

count = 0

for char in s:

if char == char_to_count:

count += 1

print("Occurrences of '{}' in the string:".format(char_to_count), count) # Output: 2

Replace All Occurrences of a Character

# Replace all occurrences of a character in a string

s = "Hello World"

old_char = "o"
new_char = "x"

result = ' '

for char in s:

if char == old_char:

result += new_char

else:

result += char

print("Replaced string:", result) # Output: Hellx Wxrld

Converting Uppercase

# Convert string to uppercase

s = "hello"

result = ''

for char in s:

if 'a' <= char <= 'z': # Check if it's a lowercase letter

result += chr(ord(char) - 32) # Convert to uppercase by adjusting ASCII value

else:

result += char

print("Uppercase string:", result) # Output: HELLO

Converting Lowercase

# Convert string to lowercase

s = "HELLO"

result = ''

for char in s:

if 'A' <= char <= 'Z': # Check if it's an uppercase letter

result += chr(ord(char) + 32) # Convert to lowercase by adjusting ASCII value

else:

result += char

print("Lowercase string:", result) # Output: hello

String palindrome

s = "madam"

left, right = 0, len(s) - 1


is_palindrome = True

while left < right:

if s[left] != s[right]:

is_palindrome = False

break

left += 1

right -= 1

print("Is the string a palindrome?", is_palindrome) # Output: True

String Palindrome

s = "madam"

if s == s[::-1]:

print("Is the string a palindrome?", True) # Output: True

else:

print("Is the string a palindrome?", False)

Split Function

# Split a string into words (based on spaces)

s = "Hello World"

words = []

word = ' '

for char in s:

if char == ' ':

if word:

[Link](word)

word = ' '

else:

word += char

if word: # Append the last word if any

[Link](word)

print("Split words:", words) # Output: ['Hello', 'World']


String is Equal or Not

# Check if two strings are equal

s1 = "Hello"

s2 = "hello"

are_equal = True

if len(s1) != len(s2):

are_equal = False

else:

for i in range(len(s1)):

if s1[i] != s2[i]:

are_equal = False

break

print("Are the strings equal?", are_equal) # Output: False

FUNCTIONS

1.1 NO RETURN NO ARGS FUNCTION

def print_hello():

print("Hello!")

# Calling the function

print_hello()

1.2 WITH RETURN NO ARGS

def get_five():

return 5

# Calling the function

result = get_five()

print(result) # Output: 5

1.3 WITH RETURN WITH ARGS

def multiply(a, b):

return a * b

# Calling the function

result = multiply(3, 4)

print(result) # Output: 12
1.4 NO RETURN WITH ARGS

def greet_person(name):

"""Greets the person by name."""

print(f"Hello, {name}!")

# Calling the function

greet_person("Alice") # Output: Hello, Alice!

LAMBDA

Syntax

lambda arguments : expression

EXAMPLE:

x = lambda a: a + 10

print(x(5))

[Link] MULTIPLE VALUES IN LAMBDA

x = lambda a, b : a * b

print(x(5, 6))

[Link] Use Lambda Functions?

The power of lambda is better shown when you use them as an anonymous function inside another
function.

Say you have a function definition that takes one argument, and that argument will be multiplied
with an unknown number

EXAMPLE:

def myfunc(n):

return lambda a : a * n

x = myfunc(2)

print(x(11))

[Link] EXAMPLE

def myfunc(n):

return lambda a : a * n

mydoubler = myfunc(2)

mytripler = myfunc(3)

print(mydoubler(11))

print(mytripler(11))

OBJECT ORIENTED PROGRAMMING (OOPS)


Oops is used to code Code Reusability

Modularity:

Modularity: OOP allows you to break down a complex problem into smaller, manageable pieces by
creating classes and objects

Maintainability: Code is more organized and easier to manage, making updates and maintenance
simpler.

Scalability: OOP systems are easier to extend as new objects and functionalities can be added
without affecting existing code.

Oops is safe and Secure

CLASS

A class is a blueprint or template for creating objects. It defines the properties (also called attributes
or fields) and behaviors (also called methods or functions) that the class will have.

Syntax:

class class_name:

OBJECT

Object is an instance of class

Any thing which will have a Existence is also called object

There Two Are Properties

[Link] or attributes

[Link] or methods

There Two Rules To Create a Object

[Link] a blue print ---->class

[Link] a object according to blue print--->object creation

Rule 2:

Syntax:

object_name = ClassName(arguments)

Example :

class MyClass:

x=5

print(MyClass) # This prints the class definition

print(MyClass.x)

obj = MyClass()

print(obj.x)
Constructor

a constructor is a special method that is automatically called when an object (instance) of a class is
created. The constructor is used to initialize the object's attributes (properties) and set up any
necessary state for the object.

In Python, the constructor method is called __init__.

Syntax:

class ClassName:

def __init__(self, arguments):

self.attribute1 = value1

self.attribute2 = value2

Example:

class Car:

def __init__(self, brand, model, year):

[Link] = brand # Assigning brand to the object

[Link] = model # Assigning model to the object

[Link] = year # Assigning year to the object

def display_info(self):

print(f"Car Brand: {[Link]}, Model: {[Link]}, Year: {[Link]}")

car1 = Car("Toyota", "Camry", 2020)

car2 = Car("Honda", "Civic", 2021)

car1.display_info() # Output: Car Brand: Toyota, Model: Camry, Year: 2020

car2.display_info() # Output: Car Brand: Honda, Model: Civic, Year: 2021

Destructor in Python

A destructor is a special method that is called when an object is about to be destroyed. It allows you
to clean up any resources (like closing files or releasing connections) before the object is deleted.

The destructor method in Python is __del__(self).

It is automatically called when an object’s reference count reaches zero, which happens when there
are no more references to that object.

Example of Destructor

class Person:

def __init__(self, name, age):

[Link] = name

[Link] = age

print(f"Person {[Link]} is created.")

def __del__(self):
print(f"Person {[Link]} is being destroyed.")

# Creating and deleting the object

person1 = Person("Bob", 25)

del person1 # This will invoke the destructor

In this example:

The __del__ method is the destructor. It prints a message when the object is being destroyed.

The del statement explicitly deletes the object, triggering the destructor.

What is self keyword

Self is a reference to the current instance of the class. This means when you create an object from
a class, self allows you to access the object's attributes and methods.

Why selfkeyword

Distinguishing Between Instance and Local Variables: self distinguishes between instance variables
(those tied to the object) and local variables in methods. Without self, Python would treat any
variable defined within the method as a local variable that is not tied to an instance.

Access modifiers

Public: Accessible from anywhere (outside the class).

Private: Accessible only from within the class.

Protected: Accessible within the class and its subclasses.

Four Fundamental principles of object-oriented programming (OOP)

Encapsulation

Inheritance

Polymorphism

Abstraction

Encapsulation

Encapsulation is nothing but hideing or binding a data from the user or wraping data from the user
to achive encapsulation we must use class as private by using private keyword we are going to hide
a data from the user if suppose some other classes want to use a private hided data there is two
method

Two Method

Getter function

Setter function

The process of using the getter method and setter method is called data binding method

The process of using the private keyword is called data hiding

Real Time Example


REAL TIME EXAMPLE:

[Link] BAG

[Link]

[Link] is a capsule. Basically, capsule encapsulates several combinations of medicine.

If combinations of medicine are variables and methods then the capsule will act as a class and the
whole process is called Encapsulation

Example:

class Person:

def __init__(self, name, age):

self.__name = name # Private attribute (name)

self.__age = age # Private attribute (age)

# Getter method for name

def get_name(self):

return self.__name

# Setter method for name

def set_name(self, name):

if len(name) > 0:

self.__name = name

else:

print("Name cannot be empty")

# Getter method for age

def get_age(self):

return self.__age

# Setter method for age

def set_age(self, age):

if age >= 0:

self.__age = age

else:

print("Age cannot be negative")

# Creating an object of Person

person1 = Person("Alice", 30)

# Accessing and modifying the attributes using getters and setters


print(person1.get_name()) # Outputs: Alice

print(person1.get_age()) # Outputs: 30

# Modifying attributes through setter methods

person1.set_name("Bob")

person1.set_age(35)

# Accessing modified values

print(person1.get_name()) # Outputs: Bob

print(person1.get_age()) # Outputs: 35

# Attempt to set invalid data

person1.set_name("") # Outputs: Name cannot be empty

person1.set_age(-5) # Outputs: Age cannot be negative

Inheritance

Inheritance allows a class to inherit attributes and methods from another class.

It promotes code reusability and establishes a natural hierarchy between classes.

Types:

Single Inheritance: A class inherits from one base class.

Multiple Inheritance: A class inherits from more than one base class.

Multilevel Inheritance: A class inherits from another class, which is derived from another class.

Hierarchical Inheritance: Multiple classes inherit from a single base class.

Hybrid Inheritance: combination of others two

5.1

Single Inheritance

A class inherits from one base class.

EXAMPLE:

class Animal:

def speak(self):

return "Animal sound"

class Dog(Animal):

def weak(self):

return "Woof!"

dog = Dog()
print([Link]()) # Output: Woof!

5.2

Multiple Inheritance

A class inherits from more than one base class. The derived class has access to the methods and
attributes of all its parent classes.

EXAMPLE:

class Animal:

def speak(self):

return "Animal sound"

class Pet:

def play(self):

return "Playing"

class Dog(Animal, Pet):

def speak(self):

return "Woof!"

dog = Dog()

print([Link]()) # Output: Woof!

print([Link]()) # Output: Playing

5.3

Multilevel Inheritance

A class inherits from a base class, and another class inherits from this derived class.

EXAMPLE:

class Animal:

def speak(self):

return "Animal sound"

class Mammal(Animal):

def has_hair(self):

return True

class Dog(Mammal):

def speak(self):

return "Woof!"

dog = Dog()

print([Link]()) # Output: Woof!


print(dog.has_hair()) # Output: True

5.4

Hierarchical Inheritance

Multiple classes inherit from a single base class. Each derived class can have its own additional
methods and attributes.

EXAMPLE:

class Animal:

def speak(self):

return "Animal sound"

class Dog(Animal):

def speak(self):

return "Woof!"

class Cat(Animal):

def speak(self):

return "Meow!"

dog = Dog()

cat = Cat()

print([Link]()) # Output: Woof!

print([Link]()) # Output: Meow!

Super Function

The super() function is used to call methods from a parent class from within a method in a child
class.

It’s especially useful in complex inheritance hierarchies.

EXAMPLE:

class Base:

def __init__(self):

print("Base init")

class Derived(Base):

def __init__(self):

super().__init__() # Call Base class constructor

print("Derived init")
d = Derived()

# Output:

# Base init

# Derived init

POLYMORPHISM

Polymorphism allows methods to do different things based on the object it is acting upon. It means
"many forms" and can be implemented using method overriding or method overloading.

Polymorphism ---> Many Forms

1. Method Overloading ---> Same Function name and Different

Arguments [Direct Not using For Overloading Programs]

2. Method Overriding [ Same Function Name and Same Arguments ]

3. Operator Overloading

Method Overriding

Method overriding occurs when a subclass provides a specific implementation for a method that is
already defined in its superclass. The new implementation in the subclass replaces the one in the
superclass. This is useful when you want to modify or extend the behavior of a method inherited
from a parent class.

EXAMPLE:

class Animal:

def make_sound(self):

print("Some generic sound")

class Dog(Animal):

def make_sound(self):

print("Woof!")

class Cat(Animal):

def make_sound(self):

print("Meow!")

# Create instances

animal = Animal()

dog = Dog()

cat = Cat()

# Call the methods

animal.make_sound() # Output: Some generic sound


dog.make_sound() # Output: Woof!

cat.make_sound() # Output: Meow!

Method Overloading

Method overloading refers to defining multiple methods with the same name but with different
parameters (e.g., different number of arguments or different types of arguments). Unlike some other
programming languages like Java or C++, Python does not support method overloading directly.
Instead, you can use default arguments, variable-length argument lists, or keyword arguments to
achieve similar functionality.

Example:

#01 Example - Two or Three Arguments Using

class MethodOverloading:

def fun(self,a=None,b=None,c=None):

if a!=None and b!=None and c!=None:

return a+b+c

elif a!=None and b!=None:

return a+b

else:

return a

object=MethodOverloading()

print("Result : ", [Link](30,50))

# 02 Example - Multiple Arguments using ---> *args Multiple arguments using

class MethodOverloading:

def fun(self,*args):

sum=0

for i in args:

sum+=i

print("Sum Value : ",sum)

object=MethodOverloading()

[Link](10)

[Link](10,20)

[Link](10,20,30)

[Link](10,20,30,40)
Abstraction

Abstraction involves hiding the complex implementation details and showing only the essential
features of an object.

In Python, abstraction can be achieved using abstract base classes (ABCs) from the abc module.

Abstract Base Class: A class that contains one or more abstract methods. An abstract method is a
method that is declared but contains no implementation. Subclasses must implement these
methods.

Example:

from abc import ABC, abstractmethod

class Shape(ABC):

@abstractmethod

def area(self):

pass

class Rectangle(Shape):

def __init__(self, width, height):

[Link] = width

[Link] = height

def area(self):

return [Link] * [Link]

# Creating an instance

rect = Rectangle(5, 10)

print([Link]()) # Output: 50

Working on Python Abstract classes

# Python program showing

# abstract base class work

from abc import ABC, abstractmethod

class Polygon(ABC):

@abstractmethod

def noofsides(self):

pass

class Triangle(Polygon):

# overriding abstract method


def noofsides(self):

print("I have 3 sides")

class Pentagon(Polygon):

# overriding abstract method

def noofsides(self):

print("I have 5 sides")

class Hexagon(Polygon):

# overriding abstract method

def noofsides(self):

print("I have 6 sides")

class Quadrilateral(Polygon):

# overriding abstract method

def noofsides(self):

print("I have 4 sides")

# Driver code

R = Triangle()

[Link]()

K = Quadrilateral()

[Link]()

R = Pentagon()

[Link]()

K = Hexagon()

[Link]()

Summary

OOP is used because it helps:

Organize code better (modularity)

Reuse existing code (inheritance)

Ensure data integrity and security (encapsulation)

Make the code more flexible and scalable (polymorphism)

Easily maintain and extend large systems

EXCEPTION HANDLING

#The finally block gets executed no matter if the try block raises any errors or not:

try:
print(x)

except:

print("Something went wrong")

finally:

print("The 'try except' is finished")

Full Structure of Exception handling

try:

# Code that might raise an exception

except SomeExceptionType:

# Code that runs if the exception occurs

else:

# Code that runs if no exception occurs

finally:

# Code that runs no matter what (for cleanup tasks)

Example:

try:

x = 10 / 0 # This will raise a ZeroDivisionError

except ZeroDivisionError:

print("Cannot divide by zero")

except TypeError:

print("Type error occurred")

Example:

try:

# Code that might raise an exception

x = int("hello") # This will raise a ValueError

except (ValueError, TypeError):

print("ValueError or TypeError occurred")

Types of Error

In Python, errors can be broadly categorized into two types:

1. Syntax Errors

2. Exceptions (Runtime Errors)


1. Syntax Errors

Example of a Syntax Error:

print("Hello, World!" # Missing closing parenthesis

2. Exceptions (Runtime Errors)

1. ZeroDivisionError

Raised when dividing by zero.

x = 10 / 0 # Raises ZeroDivisionError

2. IndexError

lst = [1, 2, 3]

print(lst[5]) # Raises IndexError

3. ValueError

Raised when a function receives an argument of the right type but inappropriate value.

int("hello") # Raises ValueError because "hello" can't be converted to an integer

4. KeyError

Raised when a dictionary key is not found.

my_dict = {"a": 1}

print(my_dict["b"]) # Raises KeyError

5. TypeError

Raised when an operation or function is applied to an object of inappropriate type.

"hello" + 5 # Raises TypeError because you can't add a string and an integer

6. FileNotFoundError

Raised when trying to open a file that does not exist.

open("non_existing_file.txt", "r") # Raises FileNotFoundError

7. AttributeError

Raised when an invalid attribute reference or assignment is made.

x = 10

[Link](5) # Raises AttributeError because integers do not have an append method

8. NameError

Raised when a local or global name is not found.

print(undeclared_variable) # Raises NameError because undeclared_variable is not defined


10. TypeError

- Raised when an operation is performed on an object of inappropriate type.

a = "hello" + 10 # TypeError

3. Handling Errors

Errors can be caught and handled using exception handling mechanisms like `try`, `except`, `else`,
and `finally`. This allows the program to continue running even if an error occurs.

try:

result = 10 / 0

except ZeroDivisionError:

print("You cannot divide by zero!")

ADVANCE PYTHON

Map function

the map() function is a built-in function that allows you to apply a given function to all items in an
iterable (like a list or a tuple) and return a map object (which is an iterator).

This can be useful for transforming data in a concise and readable way.

the result of map() is an iterator, so you need to convert it to a list (or another iterable type) to see
the results.

the map() function is a powerful tool for functional programming in python, allowing for clean and
efficient transformations of data within iterables.

SYNTAX:

map(function, iterable, ...)

EXAMPLE:

def square(x):

return x ** 2

numbers = [1, 2, 3, 4, 5]

squared_numbers = map(square, numbers)

# Convert the map object to a list to see the results

squared_numbers_list = list(squared_numbers)

print(squared_numbers_list) # Output: [1, 4, 9, 16, 25]

[Link]

itertools is a Python module that provides a collection of fast, memory-efficient tools for working with
iterators.

It includes functions that create iterators for efficient looping,


which can be particularly useful for handling large datasets or for building complex data processing
pipelines.

ITERTOOLS FUNCTIONS

2.1 REPEAT

repeat_example = [Link]('Hello', 3)

print(list(repeat_example)) # Output: ['Hello', 'Hello', 'Hello']

2.2 CHAIN FUNCTION

chain_example = [Link]([1, 2, 3], ['A', 'B', 'C'])

print(list(chain_example)) # Output: [1, 2, 3, 'A', 'B', 'C']

2.3 COMBINATION

from itertools import combinations

combo_example = combinations(['A', 'B', 'C'], 2)

print(list(combo_example)) # Output: [('A', 'B'), ('A', 'C'), ('B', 'C')]

2.4 PERMUTATION

from itertools import permutations

perm_example = permutations(['A', 'B', 'C'], 2)

print(list(perm_example)) # Output: [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]

2.5 PRODUCT

from itertools import product

prod_example = product([1, 2], ['A', 'B'])

print(list(prod_example)) # Output: [(1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]

DECORATORS

Decorators in Python are a powerful and expressive way to modify or enhance functions or
methods.

They allow you to wrap another function to extend its behavior without permanently modifying it.

Decorators are often used for logging, access control, caching, and other cross-cutting concerns.

EXAMPLE:

def greet_decorator(func):

def wrapper(*args, **kwargs):

print("Hello!")

return func(*args, **kwargs)


return wrapper

@greet_decorator

def say_name(name):

print(f"My name is {name}")

say_name("Alice")

GENERATORS

Generators are a powerful feature in Python that allow for efficient iteration over sequences of data.

They provide a convenient way to handle large datasets, lazy evaluation, and simpler code
structures.

By using yield, you can create functions that generate values on the fly, making your programs
more efficient and responsive. If you have any specific questions or need further examples, feel free
to ask!

EXAMPLE:

def square_numbers(n):

for i in range(n):

yield i ** 2 # Yield the square of i

# Create a generator object

squares = square_numbers(5)

# Iterate through the generator

for x in squares:

print(x)

COLLECTIONS

[Link]:

from collections import Counter

# Example

text = "hello world"

counter = Counter(text)

print(counter) # Output: Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

[Link] DICT:

from collections import defaultdict

# Example

d = defaultdict(int)
d['a'] += 1

print(d['a']) # Output: 1

print(d['b']) # Output: 0 (default int value)

[Link] DICT:

from collections import OrderedDict

# Example

od = OrderedDict()

od['a'] = 1

od['b'] = 2

print(od) # Output: OrderedDict([('a', 1), ('b', 2)])

DEQUE (Double Ended Queue)

from collections import deque

# Example

dq = deque()

[Link]('a')

[Link]('b')

[Link]('c')

print(dq) # Output: deque(['c', 'a', 'b'])

[Link]()

print(dq) # Output: deque(['c', 'a'])

CHAIN MAP:

from collections import ChainMap

# Example

dict1 = {'a': 1, 'b': 2}

dict2 = {'b': 3, 'c': 4}

chain = ChainMap(dict1, dict2)

print(chain['b']) # Output: 2 (from dict1)

print(chain['c']) # Output: 4 (from dict2)

Named Tuple:

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])

p = Point(1, 2)
print(p) # Output: Point(x=1, y=2)

print(p.x) # Output: 1

Stack (LIFO)

class Stack:

def __init__(self):

[Link] = []

def push(self, item):

[Link](item)

def pop(self):

if not self.is_empty():

return [Link]()

return None

def peek(self):

return [Link][-1] if not self.is_empty() else None

def is_empty(self):

return len([Link]) == 0

# Usage example

stack = Stack()

[Link](1)

[Link](2)

print([Link]()) # Output: 2

THREAD

import threading

import time

class MyThread([Link]):

def run(self):

for i in range(5):

print(f"Thread {[Link]} - Count {i}")

[Link](1)

thread = MyThread()

[Link]()

[Link]() # Wait for the thread to finish


Data Structure & algorithm

Data Structures and Algorithms (DSA) is a fundamental part of Computer Science that teaches you
how to think and solve complex problems systematically.

Using the right data structure and algorithm makes your program run faster, especially when
working with lots of data.

Although Data Structures and Algorithms is actually not specific to any programming language, you
should have a basic understanding of programming in one of programming languages:

What is Data Structure

A data structure is a way to store data.

We structure data in different ways depending on what data we have, and what we want to do with
it.

Data structures give us the possibility to manage large amounts of data efficiently for uses such as
large databases and internet indexing services.

Eg: Family Tree

Type of Data Structure

Primitive Data Structures are basic data structures provided by programming languages to
represent single values, such as integers, floating-point numbers, characters, and booleans.

Abstract Data Structures are higher-level data structures that are built using primitive data types
and provide more complex and specialized operations. Some common examples of abstract data
structures include arrays, linked lists, stacks, queues, trees, and graphs.

Algorithm

An algorithm is a set of step-by-step instructions to solve a given problem or achieve a specific


goal.

Algorithm examples:

Finding the fastest route in a GPS navigation system

Navigating an airplane or a car (cruise control)

Finding what users search for (search engine)

Sorting, for example sorting movies by rating

Array

We already learned

Bubble Sort

Step 1: We start with an unsorted array.

[7, 12, 9, 11, 3]

Step 2: We look at the two first values. Does the lowest value come first? Yes, so we don't need to
swap them.

[7, 12, 9, 11, 3]

Step 3: Take one step forward and look at values 12 and 9. Does the lowest value come first? No.
[7, 12, 9, 11, 3]

Step 4: So we need to swap them so that 9 comes first.

[7, 9, 12, 11, 3]

Step 5: Taking one step forward, looking at 12 and 11.

[7, 9, 12, 11, 3]

Step 6: We must swap so that 11 comes before 12.

[7, 9, 11, 12, 3]

Step 7: Looking at 12 and 3, do we need to swap them? Yes.

[7, 9, 11, 12, 3]

Step 8: Swapping 12 and 3 so that 3 comes first.

[7, 9, 11, 3, 12]

Example:

my_array = [64, 34, 25, 12, 22, 11, 90, 5]

n = len(my_array)

for i in range(n-1):

for j in range(n-i-1):

if my_array[j] > my_array[j+1]:

my_array[j], my_array[j+1] = my_array[j+1], my_array[j]

print("Sorted array:", my_array)

Selection Sort

Step 1: We start with an unsorted array.

[ 7, 12, 9, 11, 3]

Step 2: Go through the array, one value at a time. Which value is the lowest? 3, right?

[ 7, 12, 9, 11, 3]

Step 3: Move the lowest value 3 to the front of the array.

[ 3, 7, 12, 9, 11]

Step 4: Look through the rest of the values, starting with 7. 7 is the lowest value, and already at the
front of the array, so we don't need to move it.

[ 3, 7, 12, 9, 11]

Step 5: Look through the rest of the array: 12, 9 and 11. 9 is the lowest value.

[ 3, 7, 12, 9, 11]

Step 6: Move 9 to the front.

[ 3, 7, 9, 12, 11]
Step 7: Looking at 12 and 11, 11 is the lowest.

[ 3, 7, 9, 12, 11]

Step 8: Move it to the front.

[ 3, 7, 9, 11, 12]

Example:

my_array = [64, 34, 25, 5, 22, 11, 90, 12]

n = len(my_array)

for i in range(n-1):

min_index = i

for j in range(i+1, n):

if my_array[j] < my_array[min_index]:

min_index = j

min_value = my_array.pop(min_index)

my_array.insert(i, min_value)

print("Sorted array:", my_array)

Linked List

A linked list consists of nodes with some sort of data, and a pointer, or link, to the next node.

Example:

class Node:

def __init__(self, data):

[Link] = data

[Link] = None

node1 = Node(3)

node2 = Node(5)

node3 = Node(13)

node4 = Node(2)

[Link] = node2

[Link] = node3

[Link] = node4

currentNode = node1

while currentNode:

print([Link], end=" -> ")


currentNode = [Link]

print("null")

Types of Linked Lists

Singly linked lists

Doubly linked lists

Circular linked lists

Singly Linked List Implementation

The above example is reference for Singly linked list

[Link] Linked List Implementation

Example

class Node:

def __init__(self, data):

[Link] = data

[Link] = None

[Link] = None

node1 = Node(3)

node2 = Node(5)

node3 = Node(13)

node4 = Node(2)

[Link] = node2

[Link] = node1

[Link] = node3

[Link] = node2

[Link] = node4

[Link] = node3

print("\nTraversing forward:")

currentNode = node1
while currentNode:

print([Link], end=" -> ")

currentNode = [Link]

print("null")

print("\nTraversing backward:")

currentNode = node4

while currentNode:

print([Link], end=" -> ")

currentNode = [Link]

print("null")

[Link] Singly Linked List Implementation

Example:

class Node:

def __init__(self, data):

[Link] = data

[Link] = None

node1 = Node(3)

node2 = Node(5)

node3 = Node(13)

node4 = Node(2)

[Link] = node2

[Link] = node3

[Link] = node4

[Link] = node1 # Circular link

currentNode = node1

startNode = node1

print([Link], end=" -> ")

currentNode = [Link]

while currentNode != startNode:

print([Link], end=" -> ")

currentNode = [Link]

print("...") # Indicating the list loops back


Circular Doubly Linked List Implementation

class Node:

def __init__(self, data):

[Link] = data

[Link] = None

[Link] = None

node1 = Node(3)

node2 = Node(5)

node3 = Node(13)

node4 = Node(2)

[Link] = node2

[Link] = node4 # Circular link

[Link] = node1

[Link] = node3

[Link] = node2

[Link] = node4

[Link] = node3

[Link] = node1 # Circular link

print("\nTraversing forward:")

currentNode = node1

startNode = node1

print([Link], end=" -> ")

currentNode = [Link]

while currentNode != startNode:

print([Link], end=" -> ")

currentNode = [Link]

print("...") # Indicating it's circular

print("\nTraversing backward:")

currentNode = node4

startNode = node4

print([Link], end=" -> ")

currentNode = [Link]
while currentNode != startNode:

print([Link], end=" -> ")

currentNode = [Link]

print("...") # Indicating it's circular

Stack(LIFO)

A stack is a data structure that can hold many elements.

Basic operations we can do on a stack are:

Push: Adds a new element on the stack.

Pop: Removes and returns the top element from the stack.

Peek: Returns the top element on the stack.

isEmpty: Checks if the stack is empty.

Size: Finds the number of elements in the stack.

Example:

stack = []

# Push

[Link]('A')

[Link]('B')

[Link]('C')

print("Stack: ", stack)

# Pop

element = [Link]()

print("Pop: ", element)

# Peek

topElement = stack[-1]

print("Peek: ", topElement)

# isEmpty

isEmpty = not bool(stack)

print("isEmpty: ", isEmpty)

# Size

print("Size: ",len(stack))

Queues(FIFO)
A queue is a data structure that can hold many elements.

Basic operations we can do on a queue are:

Enqueue: Adds a new element to the queue.

Dequeue: Removes and returns the first (front) element from the queue.

Peek: Returns the first element in the queue.

isEmpty: Checks if the queue is empty.

Size: Finds the number of elements in the queue

Example:

queue = []

# Enqueue

[Link]('A')

[Link]('B')

[Link]('C')

print("Queue: ", queue)

# Dequeue

element = [Link](0)

print("Dequeue: ", element)

# Peek

frontElement = queue[0]

print("Peek: ", frontElement)

# isEmpty

isEmpty = not bool(queue)

print("isEmpty: ", isEmpty)

# Size

print("Size: ", len(queue))

#Python

Dequeue

from collections import deque

# Example

dq = deque()

[Link]('a')

[Link]('b')

[Link]('c')
print(dq) # Output: deque(['c', 'a', 'b'])

[Link]()

print(dq) # Output: deque(['c', 'a'])

Hash Table

A Hash Table is a data structure designed to be fast to work with.

The reason Hash Tables are sometimes preferred instead of arrays or linked lists is because
searching for, adding, and deleting data can be done really quickly, even for large amounts of data.

In a Linked List, finding a person "Bob" takes time because we would have to go from one node to
the next, checking each node, until the node with "Bob" is found.

And finding "Bob" in an Array could be fast if we knew the index, but when we only know the name
"Bob", we need to compare each element (like with Linked Lists), and that takes time.

With a Hash Table however, finding "Bob" is done really fast because there is a way to go directly to
where "Bob" is stored, using something called a hash function.

Example:

def hash_function(value):

sum_of_chars = 0

for char in value:

sum_of_chars += ord(char)

return sum_of_chars % 10

print("'Bob' has hash code:",hash_function('Bob'))

Heap

A heap is a binary tree used to represent a priority queue. You can use the heapq module in Python
to implement heaps.

import heapq

# Example of a heap (min-heap)

heap = [1, 3, 2, 5, 4]

[Link](heap)

# Adding an element

[Link](heap, 0)

# Popping the smallest element

print([Link](heap)) # Output: 0

Searching Algorithm

Linear Search
def linear_search(arr, target):

for index, value in enumerate(arr):

if value == target:

return index # Element found

return -1 # Element not found

arr = [5, 3, 8, 6, 7]

result = linear_search(arr, 8)

print(result) # Output: 2

Binary Search

def binary_search(arr, target):

low, high = 0, len(arr) - 1

while low <= high:

mid = (low + high) // 2

if arr[mid] == target:

return mid # Element found

elif arr[mid] < target:

low = mid + 1 # Search the right half

else:

high = mid - 1 # Search the left half

return -1 # Element not found

arr = [1, 3, 5, 7, 9]

result = binary_search(arr, 7)

print(result) # Output: 3

Depth-First Search (DFS)

# DFS in a graph using recursion

def dfs(graph, node, visited=None):

if visited is None:

visited = set()

[Link](node)

print(node, end=" ")

for neighbor in graph[node]:


if neighbor not in visited:

dfs(graph, neighbor, visited)

# Example Graph represented as adjacency list

graph = {

'A': ['B', 'C'],

'B': ['A', 'D', 'E'],

'C': ['A', 'F'],

'D': ['B'],

'E': ['B', 'F'],

'F': ['C', 'E']

dfs(graph, 'A') # Output: A B D E F C

Breadth-First Search (BFS)

from collections import deque

def bfs(graph, start):

visited = set()

queue = deque([start])

[Link](start)

while queue:

node = [Link]()

print(node, end=" ")

for neighbor in graph[node]:

if neighbor not in visited:

[Link](neighbor)

[Link](neighbor)

# Example Graph represented as adjacency list

graph = {

'A': ['B', 'C'],

'B': ['A', 'D', 'E'],


'C': ['A', 'F'],

'D': ['B'],

'E': ['B', 'F'],

'F': ['C', 'E']

bfs(graph, 'A') # Output: A B C D E F

Sorting Algorithms

Bubble Sort

def bubble_sort(arr):

n = len(arr)

for i in range(n):

swapped = False

for j in range(0, n-i-1):

if arr[j] > arr[j+1]:

arr[j], arr[j+1] = arr[j+1], arr[j] # Swap

swapped = True

if not swapped:

break # No swaps, array is sorted

return arr

arr = [5, 1, 4, 2, 8]

print(bubble_sort(arr)) # Output: [1, 2, 4, 5, 8]

Selection Sort

def selection_sort(arr):

n = len(arr)

for i in range(n):

min_idx = i

for j in range(i+1, n):

if arr[j] < arr[min_idx]:

min_idx = j

arr[i], arr[min_idx] = arr[min_idx], arr[i]

return arr

arr = [64, 25, 12, 22, 11]


print(selection_sort(arr)) # Output: [11, 12, 22, 25, 64]

Insertion Sort

def insertion_sort(arr):

for i in range(1, len(arr)):

key = arr[i]

j = i-1

while j >= 0 and arr[j] > key:

arr[j+1] = arr[j]

j -= 1

arr[j+1] = key

return arr

arr = [12, 11, 13, 5, 6]

print(insertion_sort(arr)) # Output: [5, 6, 11, 12, 13]

4. Merge Sort

def merge_sort(arr):

if len(arr) > 1:

mid = len(arr) // 2

left_half = arr[:mid]

right_half = arr[mid:]

merge_sort(left_half)

merge_sort(right_half)

i=j=k=0

while i < len(left_half) and j < len(right_half):

if left_half[i] < right_half[j]:

arr[k] = left_half[i]

i += 1

else:

arr[k] = right_half[j]

j += 1

k += 1

while i < len(left_half):

arr[k] = left_half[i]
i += 1

k += 1

while j < len(right_half):

arr[k] = right_half[j]

j += 1

k += 1

return arr

arr = [38, 27, 43, 3, 9, 82, 10]

print(merge_sort(arr)) # Output: [3, 9, 10, 27, 38, 43, 82]

Quick Sort

def quick_sort(arr):

if len(arr) <= 1:

return arr

pivot = arr[len(arr) // 2]

left = [x for x in arr if x < pivot]

middle = [x for x in arr if x == pivot]

right = [x for x in arr if x > pivot]

return quick_sort(left) + middle + quick_sort(right)

arr = [3, 6, 8, 10, 1, 2, 1]

print(quick_sort(arr)) # Output: [1, 1, 2, 3, 6, 8, 10]

6. Heap Sort

import heapq

def heap_sort(arr):

[Link](arr) # Convert list into a heap

return [[Link](arr) for _ in range(len(arr))]

arr = [5, 3, 8, 6, 7]

print(heap_sort(arr)) # Output: [3, 5, 6, 7, 8]

Tree Algorithm

Binary tree

class Node:

def __init__(self, key):


[Link] = None

[Link] = None

[Link] = key

def inorder(root):

if root:

inorder([Link])

print([Link], end=" ")

inorder([Link])

root = Node(1)

[Link] = Node(2)

[Link] = Node(3)

[Link] = Node(4)

[Link] = Node(5)

inorder(root) # Output: 4 2 5 1 3

Binary Search Tree (BST)

class BSTNode:

def __init__(self, key):

[Link] = None

[Link] = None

[Link] = key

def insert(root, key):

if not root:

return BSTNode(key)

if key < [Link]:

[Link] = insert([Link], key)

else:

[Link] = insert([Link], key)

return root

root = BSTNode(50)

insert(root, 30)

insert(root, 20)
insert(root, 40)

insert(root, 70)

insert(root, 60)

insert(root, 80)

You might also like