0% found this document useful (0 votes)
3 views18 pages

Question

The document contains various Python programs and concepts related to data structures, algorithms, and object-oriented programming (OOP). It includes code snippets for tasks such as reversing numbers, checking for prime numbers, and implementing data structures like stacks and queues. Additionally, it explains OOP principles like classes, objects, inheritance, encapsulation, and polymorphism.

Uploaded by

Rajitha Dondleti
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)
3 views18 pages

Question

The document contains various Python programs and concepts related to data structures, algorithms, and object-oriented programming (OOP). It includes code snippets for tasks such as reversing numbers, checking for prime numbers, and implementing data structures like stacks and queues. Additionally, it explains OOP principles like classes, objects, inheritance, encapsulation, and polymorphism.

Uploaded by

Rajitha Dondleti
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

2) #NUMBER REVERSE"

n=int(input())
s=0
while n>0:
digit=n%10
s=s*10+digit
n=n//10
print(s)

4) 987=> 9+8+7=24=>2+4=6
n=int(input())
while n>9:
s=0
while n>0:
d=n%10
s=s+d
n=n//10
n=s
print(n)

5. Count Digits
n=int(input())
s=0
c=0
while n>0:
digit=n%10
s=s*10+digit
n=n//10
c=c+1
print(c)

6. Product of Digits
n=int(input())
s=1
while n>0:
d=n%10
s=s*d
n=n//10
print(s)
7. Armstrong Number

n=int(input())
length=len(str(n))
t=n
s=0
while n>0:
digit=n%10
s=s+digit**length
n=n//10
if t==s:print("Amstrong")
else:print("NOt Amstrong")

8. Strong Number
n=int(input())
t=n
s=0
while n>0:
d=n%10
fact=1

for i in range(1,d+1):
fact=fact*i
s=s+fact
n=n//10

if t==s:print("strong number")
else:print("not strong number")

9. Spy Number
n=int(input())
s,p=0,1
while n>0:
d=n%10
s=s+d
p=p*d
n=n//10
if s==p :print("Spy number ")
else:print("not spy umber")
OOP’S:
Class:
A class is a blueprint or template for creating objects.
It defines the data (attributes) and behavior (methods) of the objects.
Memory for the data is allocated only when an object is created, not
when the class is defined.
Classes help group related methods and data into a single unit.

Object:
An object is an instance of a class.
It represents a real-world entity and holds its own data (state) and can
perform operations using the class’s methods (behavior).
Each object has its own copy of attributes, so multiple objects can exist
independently.
Ex:
class Car:
def __init__(self, brand):
[Link] = brand
c = Car("Toyota")
print([Link]) # Output: Toyota

Polymorphism
Polymorphism is the ability of a method, function, or operator to take
many forms and behave differently depending on the type of object or
data it is working on.
It allows the same interface to be used for different underlying forms of
data, making code more flexible and reusable.

Ex:
class Bird:
def sound(self):
print("Some sound")

class Parrot(Bird):
def sound(self):
print("Squawk")
p = Parrot()
s=Bird()
[Link]()# some sound
[Link]() # Output: Squawk

Compile-time polymorphism happens when the same method or operator behaves


differently based on input types or number of arguments, and this is decided
before the program runs.

Run-time polymorphism happens when a child class method overrides a parent


class method, and the program decides which method to call only when it runs.

Inheritance

Inheritance allows a class (child class) to acquire properties and


methods of another class (parent class). It supports hierarchical
classification and promotes code reuse.
EX:
class Vehicle:
def info(self):
print("This is a vehicle")

class Car(Vehicle):
def car_info(self):
print("This is a car")

c = Car()
[Link]() # Inherited method
c.car_info() # Own method

Encapsulation
Encapsulation is an OOP concept where data (variables) and methods
are kept together in a class, and sensitive data is hidden by making it
private. Access or modification is controlled through special methods
(getters and setters), making the code secure, organized, and easier to
maintain.
“Encapsulation is like keeping all the tools and materials in a locked
toolbox. You can only access them in the way the owner allows — this
protects the tools and ensures correct usage.”
EX:
class Person:
def __init__(self, name):
self.__name = name # private

def get_name(self):
return self.__name

p = Person("Raj")
print(p.get_name()) # Output: Raj

Abstraction – Definition (Simple Words)

Abstraction is the concept of hiding the internal


implementation details and showing only the essential
functionality to the user.
It allows the user to use the methods without worrying
about how they work internally.

Key Points:

Focus on what an object does, not how it does it

Achieved in Python using abstract classes and abstract method

EX:

from abc import ABC, abstractmethod

class Vehicle(ABC):

@abstractmethod

def start(self):

pass

class Car(Vehicle):

def start(self):

print("Car started")
c = Car()

[Link]() # Output: Car started

What is DSA?
DSA (Data Structures and Algorithms) is the study of how
to organize data efficiently (Data Structures) and how
to process or solve problems using that data
(Algorithms).

In simple words:

Data Structure → How data is stored

Algorithm → How data is used to solve a problem

Linked List
Linked List is a linear data structure where elements, called nodes, are
stored in a sequence. Each node contains two parts: the data and a
reference (or link) to the next node in the sequence. The last node points
to None, indicating the end of the list. Linked List allows for efficient
insertions and deletions, especially when elements need to be added or
removed from the beginning or middle of the list, as no shifting of
elements is required.

Queue
Queue is a data structure that follows the First-In, First-Out (FIFO)
principle, meaning the first element added is the first one to be removed.
The insert and delete operations are often called enqueue and dequeue.

Stack
Stack is a linear data structure that stores items in a Last-In/First-Out
(LIFO) manner. In stack, a new element is added at one end and an
element is removed from that end only. The insert and delete operations
are often called push and pop. In Python, we can implement Stack using
List Data Structure.
Tree

Tree Data Structure is a non-linear data structure in which a collection


of elements known as nodes are connected to each other via edges such
that there exists exactly one path between any two nodes. Trees are used
in many areas of computer science, including file systems, databases
and even artificial intelligence.
A tree is a special type of graph that is connected and does not
contain any cycles

Graphs

Graph is a non-linear data structure consisting of a collection of nodes


(or vertices) and edges (or connection between the nodes). More
formally a Graph can be defined as a Graph consisting of a finite set of
vertices(or nodes) and a set of edges that connect a pair of nodes.
a graph may contain cycles (closed paths) and may or may not be
connected.

CREATION OF NODE
class Node:
def __init__(self, data):
[Link] = data # Stores value
[Link] = None # Points to next node

# Creating a node
n1 = Node(10)
n2=Node(20)
[Link]=n2
print([Link]) # Output: 10
print([Link]) # Output: None
print([Link])
1 Factorial

✅ Q: Write a program to find factorial of a number.

✅ Answer:

def fact(n):
f=1
for i in range(1, n+1):
f *= i
return f

print(fact(5)) # 120

2 Reverse a String

✅ Q: Reverse a given string.

✅ Answer:

s = input()
rev = ""
for i in s:
rev = i + rev
print(rev)

3 Remove Duplicates from List

✅ Q: Remove duplicates from a list.

✅ Answer:

n = [1,1,2,2,3,4]
l = []
for i in n:
if i not in l:
[Link](i)
print(l)

4 Check Prime Number

✅ Q: Check whether a number is prime.


✅ Answer:

def is_prime(n):
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True

print(is_prime(5))

5 Fibonacci Series

✅ Q: Print Fibonacci series up to n terms.

✅ Answer:

n = int(input())
a, b = 0, 1
for i in range(n):
print(a, end=" ")
a, b = b, a + b

6 Check Palindrome (Number)

✅ Q: Check whether a number is palindrome.

✅ Answer:

n = int(input())
temp = n
rev = 0

while n > 0:
d = n % 10
rev = rev * 10 + d
n //= 10

if temp == rev:
print("Palindrome")
else:
print("Not Palindrome")

7 Find Missing Number in List

✅ Q: Find missing number in list from 1 to n.

✅ Answer:

n = [1,2,4,5]
total = (len(n)+1)*(len(n)+2)//2
print(total - sum(n))

8 Count Frequency of Elements

✅ Q: Count frequency of elements in list.

✅ Answer:

n = [1,3,4,4,3,2,1]
freq = {}

for i in n:
if i in freq:
freq[i] += 1
else:
freq[i] = 1

print(freq)

9 Armstrong Number

✅ Q: Check Armstrong number.

✅ Answer:

n = int(input())
temp = n
power = len(str(n))
sum = 0
while n > 0:
d = n % 10
sum += d ** power
n //= 10

if temp == sum:
print("Armstrong")
else:
print("Not Armstrong")

Strong Number

✅ Q: Check Strong number.

✅ Answer:

n = int(input())
temp = n
sum = 0

while n > 0:
d = n % 10
fact = 1
for i in range(1, d+1):
fact *= i
sum += fact
n //= 10

if temp == sum:
print("Strong Number")
else:
print("Not Strong Number")

1 Node Creation (Linked List)

✅ Q: Create a basic node in linked list.

✅ Answer:

class Node:
def __init__(self, data):
[Link] = data
[Link] = None

n1 = Node(10)
n2 = Node(20)
[Link] = n2

print([Link])
print([Link])

2 Find Largest Element in List

n = [10, 25, 5, 40, 15]


largest = n[0]

for i in n:
if i > largest:
largest = i

print("Largest:", largest)

3 Linear Search

arr = [10, 20, 30, 40]


key = 30

for i in range(len(arr)):
if arr[i] == key:
print("Found at index", i)
break
else:
print("Not Found")

4 Bubble Sort

arr = [5, 2, 9, 1]

for i in range(len(arr)):
for j in range(0, len(arr)-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]

print(arr)
5 Check Even or Odd

n = int(input())

if n % 2 == 0:
print("Even")
else:
print("Odd")

6 Count Vowels in String

s = input().lower()
count = 0

for i in s:
if i in "aeiou":
count += 1

print("Vowels:", count)

7 Sum of Digits

n = int(input())
sum = 0

while n > 0:
sum += n % 10
n //= 10

print("Sum:", sum)

8 Stack Implementation (Using List)

stack = []

[Link](10)
[Link](20)
[Link](30)

print("Popped:", [Link]())
print("Stack:", stack)
9 Queue Implementation (Using List)

queue = []

[Link](10)
[Link](20)
[Link](30)

print("Removed:", [Link](0))
print("Queue:", queue)

Simple Class Example (OOP)

class Student:
def __init__(self, name, marks):
[Link] = name
[Link] = marks

def display(self):
print([Link], [Link])

s1 = Student("Raj", 85)
[Link]()

1 Reverse a List

arr = [1, 2, 3, 4]
rev = []
for i in arr:
rev = [i] + rev

print(rev)

2 Simple Recursion Example (Factorial)

def fact(n):
if n == 1:
return 1
return n * fact(n-1)

print(fact(5))
Check Leap Year
year = int(input())

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):


print("Leap Year")
else:
print("Not Leap Year")

Find Second Largest Element

arr = [10, 20, 5, 40, 30]

first = second = float('-inf')

for num in arr:


if num > first:
second = first
first = num
elif num > second and num != first:
second = num

print("Second Largest:", second)

Binary Search (Sorted List Required)

arr = [10, 20, 30, 40, 50]


key = 30

low = 0
high = len(arr) - 1

while low <= high:


mid = (low + high) // 2
if arr[mid] == key:
print("Found at index", mid)
break
elif arr[mid] < key:
low = mid + 1
else:
high = mid - 1
else:
print("Not Found")
Selection Sort

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

for i in range(len(arr)):
min_index = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]

print(arr)

Check Anagram

s1 = input()
s2 = input()

if sorted(s1) == sorted(s2):
print("Anagram")
else:
print("Not Anagram")

Find GCD (Greatest Common Divisor)

a = int(input())
b = int(input())

while b:
a, b = b, a % b

print("GCD:", a)

Matrix Addition

A = [[1,2],
[3,4]]

B = [[5,6],
[7,8]]
result = [[0,0],[0,0]]

for i in range(2):
for j in range(2):
result[i][j] = A[i][j] + B[i][j]

print(result)

Count Words in Sentence

s = input()
words = [Link]()
print("Word Count:", len(words))

Find Duplicate Elements in List

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

for i in arr:
if [Link](i) > 1 and i not in duplicates:
[Link](i)

print("Duplicates:", duplicates)

Decimal to Binary

n = int(input())
binary = ""

while n > 0:
binary = str(n % 2) + binary
n //= 2

print("Binary:", binary)

Simple Linked List Traversal

class Node:
def __init__(self, data):
[Link] = data
[Link] = None

# Create nodes
n1 = Node(10)
n2 = Node(20)
n3 = Node(30)

# Link nodes
[Link] = n2
[Link] = n3

# Traverse
temp = n1
while temp:
print([Link])
temp = [Link]

Simple Stack Using Class

class Stack:
def __init__(self):
[Link] = []

def push(self, x):


[Link](x)

def pop(self):
if [Link]:
return [Link]()
return "Empty Stack"

s = Stack()
[Link](10)
[Link](20)
print([Link]())

You might also like