0% found this document useful (0 votes)
902 views20 pages

Experiment 1: Write A Python Program To Find Sum of Series (1+ (1+2) + (1+2+3) +-+ (1+2+3+ - +N) )

The document describes several Python programming experiments involving data structures, algorithms, and file handling. It includes examples of programs to find sums of series, split and rearrange arrays, create tuples of numbers and squares, count vowels, generate permutations, sort lists of dictionaries, implement quicksort and heapsort, reverse strings recursively, count words in text files, and read file contents in reverse order. The last part provides an example of merging and joining DataFrames using Pandas.

Uploaded by

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

Experiment 1: Write A Python Program To Find Sum of Series (1+ (1+2) + (1+2+3) +-+ (1+2+3+ - +N) )

The document describes several Python programming experiments involving data structures, algorithms, and file handling. It includes examples of programs to find sums of series, split and rearrange arrays, create tuples of numbers and squares, count vowels, generate permutations, sort lists of dictionaries, implement quicksort and heapsort, reverse strings recursively, count words in text files, and read file contents in reverse order. The last part provides an example of merging and joining DataFrames using Pandas.

Uploaded by

jai gera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

1

Experiment 1:

Write a Python Program to Find Sum of Series [1+(1+2)+(1+2+3)+–+(1+2+3+–


+n)].

Example:
Input: n=10
Output: 220
We can solve this series using two approaches one by using a loop and another by using
direct formula. Let’s see both the methods.

Method 1- Using Loop and List Comprehension


Each nth term of the series is the sum of the n terms i.e n*(n+1)/2. So we need to loop
from 1 to n (i) and find the sum of i*(i+1)/2.

n = int(input("Enter value of n: "))

sum = sum([i*(i+1)/2 for i in range(1, n+1)])


print(sum)
Output
Enter value of n: 10
220.0

Method 2- Using Formula


nth = n*(n + 1)/2 = (n^2 + n)/2

Sum of n-terms of series


Σnth a = Σ(n^2 + n)/2

= 1/2 Σ [ n^2 ] + Σ [ n ]

= 1/2 * n(n + 1)(2n + 1)/6 + 1/2 * n(n+1)/2

= n(n+1)(2n+4)/12

So using the following formula  n(n+1)(2n+4)/12  we can find the sum of the same series
in python.
n = int(input("Enter value of n: "))

sum = n*(n+1)*(2*n+4)/12
print(sum)
Output
Enter value of n: 10
220.0
2

Experiment 2:

Write a Python Program to Split the array and add the first part to the end

# Python program to split array and move first part to end.


 
def splitArr(arr, n, k): 
    for i in range(0, k): 
        x = arr[0]
        for j in range(0, n-1):
            arr[j] = arr[j + 1]
         
        arr[n-1] = x
         
 
# main
arr = [12, 10, 5, 6, 52, 36]
n = len(arr)
position = 2
 
splitArr(arr, n, position)
 
for i in range(0, n): 
    print(arr[i], end = ' ')
 
#    
Output:
5 6 52 36 12 10

Experiment 3:
Write a Python Program to Create a List of Tuples with the First Element as the
Number and Second Element as the Square of the Number
 Live Demo

my_list = [23, 42, 67, 89, 11, 32]

print(“The list is “)

print(my_list)

print(“The resultant tuple is :”)

my_result = [(val, pow(val, 2)) for val in my_list]

print(my_result)

Output
3

The list is
[23, 42, 67, 89, 11, 32]
The resultant tuple is :
[(23, 529), (42, 1764), (67, 4489), (89, 7921), (11, 121), (32, 1024)]

Experiment 4:
Write a Python program to count number of vowels using sets in given string

Example Code

# Program to count vowel in

# a string using set

def countvowel(str1):

c=0

# Creating a set of vowels

s="aeiouAEIOU"

v = set(s)

# Loop to traverse the alphabet

# in the given string

for alpha in str1:

# If alphabet is present

# in set vowel

if alpha in v:

c=c+1

print("No. of vowels ::>", c)

# Driver code

str1 = input("Enter the string ::>")

countvowel(str1)

Output
Enter the string ::> pythonprogram
No. of vowels ::> 3
4

Experiment 5:

Write a program to implement permutation of a given string using inbuilt function

## importing the module

import itertools

## initializing a string

string = "XYZ"

## itertools.permutations method

permutaion_list = list(itertools.permutations(string))

## printing the obj in list

print("-----------Permutations Of String In Tuples----------------")

print(permutaion_list)

## converting the tuples to string using 'join' method

print("-------------Permutations In String Format-----------------")

for tup in permutaion_list:

   print("".join(tup))

Output
-----------Permutations Of String In Tuples----------------
[('X', 'Y', 'Z'), ('X', 'Z', 'Y'), ('Y', 'X', 'Z'), ('Y', 'Z', 'X'), ('Z', 'X', 'Y'), ('Z', 'Y', 'X')]
-------------Permutations In String Format-----------------
XYZ
XZY
YXZ
YZX
ZXY
ZYX

Experiment 6:

Write a python program to sort list of dictionaries by values in Python – Using lambda
function

from operator import itemgetter

my_list = [{ "name" : "Will", "age" : 56},


5

{ "name" : "Rob", "age" : 20 },

{ "name" : "Mark" , "age" : 34 },

{ "name" : "John" , "age" : 24 }]

print("The list sorted by age is : ")

print(sorted(my_list, key=lambda i: i['age']))

print("The list sorted by age and name is : ")

print(sorted(my_list, key=lambda i: (i['age'], i['name'])))

print("The list sorted by age in descending order is : ")

print(sorted(my_list, key=lambda i: i['age'],reverse=True))

Output
The list sorted by age is :
[{'name': 'Rob', 'age': 20}, {'name': 'John', 'age': 24}, {'name': 'Mark', 'age': 34}, {'name': 'Will',
'age': 56}]
The list sorted by age and name is :
[{'name': 'Rob', 'age': 20}, {'name': 'John', 'age': 24}, {'name': 'Mark', 'age': 34}, {'name': 'Will',
'age': 56}]
The list sorted by age in descending order is :
[{'name': 'Will', 'age': 56}, {'name': 'Mark', 'age': 34}, {'name': 'John', 'age': 24}, {'name': 'Rob',
'age': 20}]

Experiment 7:
Write a Python Program for following sorting:
i. Quick Sort
ii. HeapSort
Implementing Quicksort in Python
Here’s a fairly compact implementation of Quicksort:

1from random import randint


2
3def quicksort(array):
4 # If the input array contains fewer than two elements,
5 # then return it as the result of the function
6 if len(array) < 2:
7 return array
8 low, same, high = [], [], []
6

9 # Select your `pivot` element randomly


10 pivot = array[randint(0, len(array) - 1)]
11 for item in array:
12 # Elements that are smaller than the `pivot` go to
13 # the `low` list. Elements that are larger than
14 # `pivot` go to the `high` list. Elements that are
15 # equal to `pivot` go to the `same` list.
16 if item < pivot:
17 low.append(item)
18 elif item == pivot:
19 same.append(item)
20 elif item > pivot:
21 high.append(item)
22 # The final result combines the sorted `low` list
23 # with the `same` list and the sorted `high` list
24 return quicksort(low) + same + quicksort(high)

HEAP SORT:

# Python program for implementation of heap Sort

 # To heapify subtree rooted at index i.

# n is size of heap

 def heapify(arr, n, i):

    largest = i  # Initialize largest as root

    l = 2 * i + 1     # left = 2*i + 1

    r = 2 * i + 2     # right = 2*i + 2

     # See if left child of root exists and is

    # greater than root


7

    if l < n and arr[largest] < arr[l]:

        largest = l

     # See if right child of root exists and is

    # greater than root

    if r < n and arr[largest] < arr[r]:

        largest = r 

    # Change root, if needed

    if largest != i:

        arr[i], arr[largest] = arr[largest], arr[i]  # swap

         # Heapify the root.

        heapify(arr, n, largest)

 # The main function to sort an array of given size

 def heapSort(arr):

    n = len(arr)

     # Build a maxheap.

    for i in range(n//2 - 1, -1, -1):

        heapify(arr, n, i)

     # One by one extract elements

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

        arr[i], arr[0] = arr[0], arr[i]  # swap


8

        heapify(arr, i, 0)

 # Driver code

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

heapSort(arr)

n = len(arr)

print("Sorted array is")

for i in range(n):

    print("%d" % arr[i]),

# This code is contributed by Mohit Kumra

Output
Sorted array is
5 6 7 11 12 13

Experiment 8:

Write a Python Program to Reverse a String Using Recursion

def reverse(string):
if len(string) == 0:
return string
else:
return reverse(string[1:]) + string[0]
a = str(input("Enter the string to be reversed: "))
print(reverse(a))

OUTPUT:

Runtime Test Cases


 Case 1:
Enter the string to be reversed: hello world
dlrow olleh
 
Case 2:
9

Enter the string to be reversed: first


tsrif

Experiment 9:

Write a Python Program to Count the Number of Words in a Text File

Example 1: Count Number of Words

In this Python Example, we will read a text file and count the number of words in it. Consider the following text
file.

Text File

Welcome to pythonexamples.org. Here, you will find python programs for all general use
cases.

Python Program

file = open("C:\data.txt", "rt")


data = file.read()
words = data.split()

print('Number of words in text file :', len(words))

Output

Number of words in text file : 14

Example 2: Count Number of Words in Text File with Multiple Lines


In this Python Example, we will read a text file with multiple lines and count the number of words in it. Consider the following text
file.

Text File – data.txt

Welcome to www.pythonexamples.org. Here, you will find python programs for all general
use cases.
This is another line with some words.

Python Program

file = open("C:\data.txt", "rt")


data = file.read()
words = data.split()

print('Number of words in text file :', len(words))

Output
10

Number of words in text file : 21

Experiment 10:

Write a Python Program to Read the Contents of a File in Reverse Order

Source Code
Here is source code of the Python Program to read the contents of the file in reverse order. The
program output is also shown below.

filename=input("Enter file name: ")


for line in reversed(list(open(filename))):
print(line.rstrip())
Runtime Test Cases
 
Case 1:
Contents of file:
hello world
hello
 
Output:
Enter file name: read.txt
hello
hello word
 
Case 2:
Contents of file:
line1
line2
line3
 
Output:
Enter file name: read2.txt
line3
line2
line1

EXP 11 and 12:

Write a program to Merge and Join DataFrames with Pandas in Python

pandas provides a single function, merge(), as the entry point for all standard database join
operations between DataFrame or named Series objects:

pd.merge(
11

left,
right,
how="inner",
on=None,
left_on=None,
right_on=None,
left_index=False,
right_index=False,
sort=True,
suffixes=("_x", "_y"),
copy=True,
indicator=False,
validate=None,
)

In [39]: left = pd.DataFrame(


....: {
....: "key": ["K0", "K1", "K2", "K3"],
....: "A": ["A0", "A1", "A2", "A3"],
....: "B": ["B0", "B1", "B2", "B3"],
....: }
....: )
....:

In [40]: right = pd.DataFrame(


....: {
....: "key": ["K0", "K1", "K2", "K3"],
....: "C": ["C0", "C1", "C2", "C3"],
....: "D": ["D0", "D1", "D2", "D3"],
....: }
....: )
....:

In [41]: result = pd.merge(left, right, on="key")

JOINS:

Here is a more complicated example with multiple join keys. Only the keys appearing
in left and right are present (the intersection), since how='inner' by default.
12

In [42]: left = pd.DataFrame(


....: {
....: "key1": ["K0", "K0", "K1", "K2"],
....: "key2": ["K0", "K1", "K0", "K1"],
....: "A": ["A0", "A1", "A2", "A3"],
....: "B": ["B0", "B1", "B2", "B3"],
....: }
....: )
....:

In [43]: right = pd.DataFrame(


....: {
....: "key1": ["K0", "K1", "K1", "K2"],
....: "key2": ["K0", "K0", "K0", "K0"],
....: "C": ["C0", "C1", "C2", "C3"],
....: "D": ["D0", "D1", "D2", "D3"],
....: }
....: )
....:

In [44]: result = pd.merge(left, right, on=["key1", "key2"])

Experiment 13:

Write a Python Program to Append the Contents of One File to Another File

Here is source code of the Python Program to append the contents of one file to another file. The
program output is also shown below.

name1 = input("Enter file to be read from: ")


name2 = input("Enter file to be appended to: ")
fin = open(name1, "r")
data2 = fin.read()
fin.close()
fout = open(name2, "a")
fout.write(data2)
fout.close()

Runtime Test Cases


 
Case 1:
13

 
Output:
Enter file to be read from: test.txt
Enter file to be appended to: test1.txt
 
Contents of file test.txt:
Appending!!
 
Contents of file test1.txt (before appending):
Original
 
Contents of file test1.txt (after appending):
Original Appending!!
 
Case 2:
Enter file to be read from: out.txt
Enter file to be appended to: out1.txt
 
Contents of file test.txt:
world
Contents of file test1.txt (before appending):
Hello
 
Contents of file test1.txt (after appending):
Hello world

Experiment 14:

How to install and Load CSV files to Python Pandas

The basic process of loading data from a CSV file into a Pandas DataFrame (with all going
well) is achieved using the “read_csv” function in Pandas:

# Load the Pandas libraries with alias 'pd'


import pandas as pd
# Read data from file 'filename.csv'
# (in the same directory that your python process is based)
# Control delimiters, rows, column names with read_csv (see later)
data = pd.read_csv("filename.csv")
# Preview the first 5 lines of the loaded data
data.head()
14

Experiment 15:

Write a program to implement Data analysis and Visualization with Python using
pandas.

Pandas is the most popular python library that is used for data analysis. It provides highly
optimized performance with back-end source code is purely written in C or Python.
We can analyze data in pandas with:

1. Series
2. DataFrames

# Program to Create series with scalar values 

 # Numeric data

Data =[1, 3, 4, 5, 6, 2, 9]  

  # Creating series with default index values

s = pd.Series(Data) 

# predefined index values

Index =['a', 'b', 'c', 'd', 'e', 'f', 'g'] 

# Creating series with predefined index values

si = pd.Series(Data, Index) 

Output:

Scalar Data with default Index


15

Scalar Data with Index

# Program to Create DataFrame


  
# Import Library
import pandas as pd   
  
# Create DataFrame with Data

a = pd.DataFrame(Data)  

# Program to create Dataframe of three series 

import pandas as pd  

# Define series 1

s1 = pd.Series([1, 3, 4, 5, 6, 2, 9]) 

# Define series 2       

s2 = pd.Series([1.1, 3.5, 4.7, 5.8, 2.9, 9.3])   

# Define series 3

s3 = pd.Series(['a', 'b', 'c', 'd', 'e'])       

# Define Data

Data ={'first':s1, 'second':s2, 'third':s3}   

# Create DataFrame

dfseries = pd.DataFrame(Data)              

Output:
16

DataFrame with three series

# import the required module 

import matplotlib.pyplot as plt

# plot a histogram 

df['Observation Value'].hist(bins=10)  

# shows presence of a lot of outliers/extreme values

df.boxplot(column='Observation Value', by = 'Time period')  

# plotting points as a scatter plot

x = df["Observation Value"]

y = df["Time period"]

plt.scatter(x, y, label= "stars", color= "m", marker= "*", s=30)

# x-axis label

plt.xlabel('Observation Value')

# frequency label

plt.ylabel('Time period')

# function to show the plot

plt.show()
17
18

Experiment 16:

Write a program to Implement Plotting Functions in python pandas

The plot method on Series and DataFrame is just a simple wrapper around plt.plot():

In [3]: ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))

In [4]: ts = ts.cumsum()

In [5]: ts.plot();
19

In [20]: df2 = pd.DataFrame(np.random.rand(10, 4), columns=["a", "b", "c", "d"])

In [21]: df2.plot.bar();

Histograms can be drawn by using the DataFrame.plot.hist() and Series.plot.hist() methods.

In [24]: df4 = pd.DataFrame(


....: {
....: "a": np.random.randn(1000) + 1,
....: "b": np.random.randn(1000),
....: "c": np.random.randn(1000) - 1,
....: },
....: columns=["a", "b", "c"],
....: )
....:

In [25]: plt.figure();

In [26]: df4.plot.hist(alpha=0.5);
20

Scatter plot
Scatter plot can be drawn by using the DataFrame.plot.scatter() method. Scatter plot requires
numeric columns for the x and y axes. These can be specified by the x and y keywords.

In [63]: df = pd.DataFrame(np.random.rand(50, 4), columns=["a", "b", "c", "d"])

In [64]: df["species"] = pd.Categorical(


....: ["setosa"] * 20 + ["versicolor"] * 20 + ["virginica"] * 10
....: )
....:

In [65]: df.plot.scatter(x="a", y="b");

You might also like