0% found this document useful (0 votes)
8 views

Document (1)

The document provides an overview of various Python programming concepts including identity operators, searching techniques, object-oriented features, data types, and linked lists. It contains code examples for operations like factorial calculation, dictionary manipulation, and sorting algorithms, along with explanations of standard packages like NumPy, Matplotlib, and Pandas. Additionally, it covers tree structures, graph theory, and methods for handling arrays and queues in Python.

Uploaded by

priyankasakpal72
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)
8 views

Document (1)

The document provides an overview of various Python programming concepts including identity operators, searching techniques, object-oriented features, data types, and linked lists. It contains code examples for operations like factorial calculation, dictionary manipulation, and sorting algorithms, along with explanations of standard packages like NumPy, Matplotlib, and Pandas. Additionally, it covers tree structures, graph theory, and methods for handling arrays and queues in Python.

Uploaded by

priyankasakpal72
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
You are on page 1/ 16

### Identity Operators:

1. `is`

2. `is not`

### Searching Techniques:

1. Linear Search

2. Binary Search

### Use of Operators in Python:

- `//`: Floor Division (Quotient of the division rounded down to the nearest integer)

- `**`: Exponentiation (e.g., 2**3 = 8)

- `%`: Modulus (Remainder of the division)

### Object Oriented Features in Python:

1. Encapsulation

2. Inheritance

3. Polymorphism

4. Abstraction

### Types of Linked Lists:

1. Singly Linked List

2. Doubly Linked List

### Definitions:

- **Data Hiding:** Restricting access to certain details of an object and preventing the direct
modification of internal state.

- **Data Abstraction:** Presenting only the essential features of an object, hiding its implementation
details.
### Tree Terms:

- **Leaf Nodes:** Nodes in a tree that have no children.

- **Siblings:** Nodes in a tree that share the same parent.

### Data Types in Python:

1. **Integer (`int`):** Represents whole numbers (e.g., `x = 5`).

2. **List (`list`):** Ordered, mutable collection (e.g., `my_list = [1, 2, 3]`).

### List Methods in Python:

1. `append()`: Adds an element to the end of the list.

2. `remove()`: Removes the first occurrence of a specified element.

3. `sort()`: Sorts the elements of a list in ascending order.

### Standard Packages in Python:

1. **NumPy:** Numerical computing library.

2. **Matplotlib:** Plotting library for creating visualizations.

3. **Pandas:** Data manipulation and analysis library.

### Single Linked List:

A singly linked list is a linear data structure where each element points to the next element in the
sequence. Example: `1 -> 2 -> 3 -> None`.

### Directed vs. Undirected Graph:

1. **Direction:** Directed graph edges have a direction, while undirected graph edges do not.

2. **Connections:** In directed graphs, edges have a source and a destination. In undirected graphs,
edges connect nodes without a specific direction.

### Python Program for Factorial Calculation:

```python
N=5

Factorial = 1

For I in range(1, n + 1):

Factorial *= i

Print(factorial)

```

### Python Program for Dictionary Operations:

```python

Students = {1: ‘Alice’, 2: ‘Bob’, 3: ‘Charlie’}

# Adding students

Students[4] = ‘David’

Students[5] = ‘Eve’

Students[6] = ‘Frank’

# Deleting student with Roll No = 1

Del students[1]

Print(students)

```

### Binary Trees with Example:

A binary tree is a hierarchical data structure in which each node has at most two children, referred to as
the left child and the right child. Example:

```

/\
2 3

/\

4 5

```

### Array Types with Example:

1. **Numeric Array:**

```python

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

```

2. **Character Array:**

```python

Char_array = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

```

### Insertion Sort in Python:

```python

Def insertion_sort(arr):

For I in range(1, len(arr)):

Key = arr[i]

J=I–1

While j >= 0 and key < arr[j]:

Arr[j + 1] = arr[j]

J -= 1

Arr[j + 1] = key

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

Insertion_sort(my_list)
Print(“Sorted array:”, my_list)

```

### Tuple Operations:

```python

My_tuple = (3, 7, 1, 8, 2)

# Finding minimum and maximum

Min_value = min(my_tuple)

Max_value = max(my_tuple)

Print(“Minimum:”, min_value)

Print(“Maximum:”, max_value)

```

### Pre-order Tree Traversal:

```python

Class Node:

Def __init__(self, data):

Self.data = data

Self.left = None

Self.right = None

Def pre_order_traversal(root):

If root:

Print(root.data, end=” “)

Pre_order_traversal(root.left)

Pre_order_traversal(root.right)
# Example

# Constructing a simple binary tree

Root = Node(1)

Root.left = Node(2)

Root.right = Node(3)

Root.left.left = Node(4)

Root.left.right = Node(5)

# Pre-order traversal

Print(“Pre-order Traversal:”, end=” “)

Pre_order_traversal(root)

```

### Importing Module for Addition and Subtraction:

```python

From mymodule import add, subtract

A=8

B=3

Result_add = add(a, b)

Result_subtract = subtract(a, b)

Print(“Addition:”, result_add)

Print(“Subtraction:”, result_subtract)

```

### Method Overloading in Python:

```python
Class Geometry:

Def calculate_area(self, side):

Return side * side

Def calculate_area(self, length, breadth):

Return length * breadth

# Example

Geometry_obj = Geometry()

Area_square = geometry_obj.calculate_area(5)

Area_rectangle = geometry_obj.calculate_area(4, 6)

Print(“Area of Square:”, area_square)

Print(“Area of Rectangle:”, area_rectangle)

```

### Implementing Queues in Python:

```python

Class Queue:

Def __init__(self):

Self.items = []

Def enqueue(self, item):

Self.items.insert(0, item)

Def dequeue(self):

If not self.is_empty():
Return self.items.pop()

Def is_empty(self):

Return len(self.items) == 0

# Example

My_queue = Queue()

My_queue.enqueue(1)

My_queue.enqueue(2)

My_queue.enqueue(3)

Print(“Dequeued:”, my_queue.dequeue())

Print(“Dequeued:”, my_queue.dequeue())

```

### Reversing a Given Number:

```python

Def reverse_number(number):

Reversed_num = 0

While number > 0:

Digit = number % 10

Reversed_num = (reversed_num * 10) + digit

Number = number // 10

Return reversed_num

# Example

Original_number = 12345

Reversed_number = reverse_number(original_number)

Print(“Original Number:”, original_number)


Print(“Reversed Number:”, reversed_number)

```

### User Defined Package in Python:

**mymodule.py:**

```python

Class Rectangle:

Def __init__(self, length, breadth):

Self.length = length

Self.breadth = breadth

Def calculate_area(self):

Return self.length * self.breadth

```

**main_program.py:**

```python

From mymodule import Rectangle

# Creating objects of the Rectangle class

Rectangle1 = Rectangle(5, 8)

Rectangle2 = Rectangle(3, 6)

# Printing area and perimeter

Print(“Area of Rectangle 1:”, rectangle1.calculate_area())

Print(“Area of Rectangle 2:”, rectangle2.calculate_area())

```

### Handling Arrays in Python:


```python

# Array Declaration

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

# Insertion

Numeric_array.append(6)

Print(“Updated Array:”, numeric_array)

```

### Shortest Path in a Graph:

*(Assuming you have a graph represented as an adjacency matrix or list)*

```python

Import networkx as nx

# Create a directed graph

G = nx.DiGraph()

G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1)])

# Find shortest path between nodes 1 and 3

Shortest_path = nx.shortest_path(G, source=1, target=3)

Print(“Shortest Path:”, shortest_path)

```

### Outputs of Given Python Code:

i)

```python

A = [2, 5, 1, 3, 6, 9, 7]
A[2:6] = [2, 4, 9, 0]

Print(a)

```

Output: `[2, 5, 2, 4, 9, 0, 7]`

ii)

```python

B = [‘Hello’, ‘Good’]

b.append(‘Data Structure’)

print(b)

```

Output: `[‘Hello’, ‘Good’, ‘Data Structure’]`

iii)

```python

T1 = [3, 5, 6, 8]

Print(t1[2])

Print(t1[-1])

Print(t1[2:])

Print(t1[:])

```

Output:

```

[6, 8]

[3, 5, 6, 8]

```
### Explaining Methods of Packages:

#### Numpy Package:

1. **`numpy.array()`:** Creates a NumPy array.

```python

Import numpy as np

Arr = np.array([1, 2, 3])

```

2. **`numpy.mean()`:** Calculates the mean of elements in an array.

```python

Mean_value = np.mean(arr)

```

3. **`numpy.reshape()`:** Changes the shape of an array.

```python

Reshaped_arr = np.reshape(arr, (3, 1))

```

#### Matplotlib Package:

1. **`matplotlib.pyplot.plot()`:** Plots a graph.

```python

Import matplotlib.pyplot as plt

X = [1, 2, 3]
Y = [2, 4, 6]

Plt.plot(x, y)

```

2. **`matplotlib.pyplot.xlabel()`:** Sets the label for the x-axis.

```python

Plt.xlabel(‘X-axis’)

```

3. **`matplotlib.pyplot.show()`:** Displays the plot.

```python

Plt.show()

```

#### Pandas Package:

1. **`pandas.DataFrame()`:** Creates a Pandas DataFrame.

```python

Import pandas as pd

Df = pd.DataFrame({‘Name’: [‘Alice’, ‘Bob’], ‘Age’: [25, 30]})

```

2. **`DataFrame.head()`:** Displays the first few rows of the DataFrame.

```python

First_rows = df.head()

```

3. **`DataFrame.describe()`:** Generates descriptive statistics of the DataFrame.

```python

Statistics = df.describe()
```

### Binary Search Program in Python:

```python

Def binary_search(arr, target):

Low, high = 0, len(arr) – 1

While low <= high:

Mid = (low + high) // 2

If arr[mid] == target:

Return mid

Elif arr[mid] < target:

Low = mid + 1

Else:

High = mid – 1

Return -1 # Not found

# Example

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

Target_value = 5

Result = binary_search(my_list, target_value)

Print(“Index of”, target_value, “:”, result)

```

### Output of Given Python Code (6 Marks):

i)
```python

A = [2, 5, 1, 3, 6, 9, 7]

A[2:6] = [2, 4, 9, 0]

Print(a)

```

Output: `[2, 5, 2, 4, 9, 0, 7]`

ii)

```python

B = [‘Hello’, ‘Good’]

b.append(‘Data Structure’)

print(b)

```

Output: `[‘Hello’, ‘Good’, ‘Data Structure’]`

iii)

```python

T1 = [3, 5, 6, 8]

Print(t1[2])

Print(t1[-1])

Print(t1[2:])

Print(t1[:])

```

Output:

```

[6, 8]

[3, 5, 6, 8]

You might also like