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

Python exps questions

The document contains various Python code snippets demonstrating different programming tasks, including reversing words in a string, counting character frequencies, managing a contact book with a dictionary, file operations, and basic NumPy and Pandas functionalities. It covers creating and manipulating arrays, performing arithmetic operations, and accessing data in DataFrames. Each section provides example code and expected outputs for clarity.

Uploaded by

shreyruparel1290
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 views

Python exps questions

The document contains various Python code snippets demonstrating different programming tasks, including reversing words in a string, counting character frequencies, managing a contact book with a dictionary, file operations, and basic NumPy and Pandas functionalities. It covers creating and manipulating arrays, performing arithmetic operations, and accessing data in DataFrames. Each section provides example code and expected outputs for clarity.

Uploaded by

shreyruparel1290
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/ 10

1)Reverse Each Word in a String

sentence = input("Enter a sentence: ")


words = sentence.split()
for word in words:
print(word[::-1], end=" ")

2) Character Frequency Counter


string = input("Enter a string: ")
freq = {}

for char in string:


if char != " ":
if char in freq:
freq[char] += 1
else:
freq[char] = 1

for char, count in freq.items():


print(char, count)

3) Python program that simulates a contact book using a


dictionary, allowing for adding, removing, updating, and
searching contacts:

contacts = {}

def add_contact(name, phone):


contacts[name] = phone

def remove_contact(name):
if name in contacts:
del contacts[name]

def update_contact(name, phone):


if name in contacts:
contacts[name] = phone
def search_contact(name):
if name in contacts:
print(name, contacts[name])

def show_contacts():
for name, phone in contacts.items():
print(name, phone)

# Example usage
add_contact("Alice", "1234567890")
add_contact("Bob", "9876543210")
show_contacts()

update_contact("Bob", "1112223333")
search_contact("Bob")

remove_contact("Alice")
show_contacts()

4) Append data to an existing file and display the entire file

file_name = 'sample.txt'
data_to_append = "\nThis is some new data to append to the file."

with open(file_name, 'a') as file:


file.write(data_to_append)

with open(file_name, 'r') as file:


content = file.read()

print(content)

5) Count the number of lines, words, and characters in a file

file_name = 'sample.txt'
with open(file_name, 'r') as file:
lines = file.readlines()

num_lines = len(lines)
num_words = sum(len(line.split()) for line in lines)
num_chars = sum(len(line) for line in lines)

print(num_lines, num_words, num_chars)

6)Display files available in the current directory

import os

files = os.listdir(os.getcwd())

for file in files:


print(file)

7)Creating a NumPy Array

import numpy as np

# Creating a 1D NumPy array

arr = np.array([1, 2, 3, 4, 5])

print("NumPy Array:", arr)

print("Array Type:", type(arr))

Output:

NumPy Array: [1 2 3 4 5]

Array Type: <class 'numpy.ndarray'>


8) Basic NumPy Methods

(a) Creating Different Types of Arrays

import numpy as np

# Creating an array of zeros

zeros_array = np.zeros((3,3))

print("Zeros Array:\n", zeros_array)

# Creating an array of ones

ones_array = np.ones((2,2))

print("Ones Array:\n", ones_array)

# Creating an identity matrix

identity_matrix = np.eye(3)

print("Identity Matrix:\n", identity_matrix)

(b) Array Indexing & Slicing

arr = np.array([10, 20, 30, 40, 50])

print("Element at index 2:", arr[2]) # Accessing an element

print("Slice from index 1 to 3:", arr[1:4]) # Slicing

Output:

Element at index 2: 30

Slice from index 1 to 3: [20 30 40]


(c) Reshaping an Array

arr = np.array([1, 2, 3, 4, 5, 6])

reshaped_arr = arr.reshape(2, 3)

print("Reshaped Array:\n", reshaped_arr)

Output:

Reshaped Array:

[[1 2 3]

[4 5 6]]

(d) Mathematical Operations in NumPy

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

arr2 = np.array([4, 5, 6])

# Element-wise addition

print("Addition:", arr1 + arr2)

# Element-wise multiplication

print("Multiplication:", arr1 * arr2)

# Mean of an array

print("Mean:", np.mean(arr1))

(e) Generating Random Numbers using NumPy

random_array = np.random.randint(1, 100, (3,3))

print("Random Array:\n", random_array)


9)Creating NumPy Arrays

import numpy as np

# Creating a 1D array

arr1 = np.array([1, 2, 3, 4, 5])

print("1D Array:", arr1)

# Creating a 2D array

arr2 = np.array([[1, 2, 3], [4, 5, 6]])

print("2D Array:\n", arr2)

# Creating a 3D array

arr3 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print("3D Array:\n", arr3)

Output:

1D Array: [1 2 3 4 5]

2D Array:

[[1 2 3]

[4 5 6]]

3D Array:

[[[1 2]

[3 4]]

[[5 6]

[7 8]]]
10) Indexing and Slicing Arrays

# Indexing

print("First element of arr1:", arr1[0])

print("Element at row 1, column 2 in arr2:", arr2[1, 2])

# Slicing

print("Slice of arr1:", arr1[1:4]) # Elements from index 1 to 3

print("First row of arr2:", arr2[0, :])

print("First column of arr2:", arr2[:, 0])

Output:

First element of arr1: 1

Element at row 1, column 2 in arr2: 6

Slice of arr1: [2 3 4]

First row of arr2: [1 2 3]

First column of arr2: [1 4]

11) Reshaping Arrays

# Reshaping a 1D array into a 2D array

reshaped_arr = arr1.reshape(5, 1)

print("Reshaped Array:\n", reshaped_arr)

# Flattening a 2D array to 1D

flattened_arr = arr2.flatten()

print("Flattened Array:", flattened_arr)


Output:

Reshaped Array:

[[1]

[2]

[3]

[4]

[5]]

Flattened Array: [1 2 3 4 5 6]

12) Performing Arithmetic Operations

arr_a = np.array([10, 20, 30, 40])

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

print("Addition:", arr_a + arr_b)

print("Subtraction:", arr_a - arr_b)

print("Multiplication:", arr_a * arr_b)

print("Division:", arr_a / arr_b)

Output:

Addition: [11 22 33 44]

Subtraction: [ 9 18 27 36]

Multiplication: [10 40 90 160]

Division: [10. 10. 10. 10.]


13)Creating a Pandas Series

import pandas as pd

# Creating a Series from a list

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

series = pd.Series(data)

print("Pandas Series:\n", series)

Output:

Pandas Series:

0 10

1 20

2 30

3 40

4 50

dtype: int64

13) Creating a Pandas DataFrame

import pandas as pd

# Creating a DataFrame from a dictionary

data = {'Name': ['Alice', 'Bob', 'Charlie'],

'Age': [25, 30, 35],

'City': ['New York', 'Los Angeles', 'Chicago']}

df = pd.DataFrame(data)
print("Pandas DataFrame:\n", df)

Output:

Pandas DataFrame:

Name Age City

0 Alice 25 New York

1 Bob 30 Los Angeles

2 Charlie 35 Chicago

14) Accessing Data from a DataFrame

# Selecting a single column

print("Age Column:\n", df['Age'])

# Selecting a specific row

print("First Row:\n", df.iloc[0])

# Filtering Data

filtered_df = df[df['Age'] > 25]

print("Filtered DataFrame:\n", filtered_df)

You might also like