Experiment 1: Write A Python Program To Find Sum of Series (1+ (1+2) + (1+2+3) +-+ (1+2+3+ - +N) )
Experiment 1: Write A Python Program To Find Sum of Series (1+ (1+2) + (1+2+3) +-+ (1+2+3+ - +N) )
Experiment 1:
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.
= 1/2 Σ [ n^2 ] + Σ [ n ]
= 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
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
print(“The list is “)
print(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
def countvowel(str1):
c=0
s="aeiouAEIOU"
v = set(s)
# If alphabet is present
# in set vowel
if alpha in v:
c=c+1
# Driver code
countvowel(str1)
Output
Enter the string ::> pythonprogram
No. of vowels ::> 3
4
Experiment 5:
import itertools
## initializing a string
string = "XYZ"
## itertools.permutations method
permutaion_list = list(itertools.permutations(string))
print(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
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:
HEAP SORT:
# n is size of heap
largest = l
largest = r
if largest != i:
heapify(arr, n, largest)
def heapSort(arr):
n = len(arr)
heapify(arr, n, i)
heapify(arr, i, 0)
# Driver code
heapSort(arr)
n = len(arr)
for i in range(n):
print("%d" % arr[i]),
Output
Sorted array is
5 6 7 11 12 13
Experiment 8:
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:
Experiment 9:
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
Output
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
Output
10
Experiment 10:
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.
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,
)
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
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.
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:
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:
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
# Numeric data
s = pd.Series(Data)
si = pd.Series(Data, Index)
Output:
a = pd.DataFrame(Data)
# Define series 1
s1 = pd.Series([1, 3, 4, 5, 6, 2, 9])
# Define series 3
# Define Data
# Create DataFrame
dfseries = pd.DataFrame(Data)
Output:
16
# plot a histogram
df['Observation Value'].hist(bins=10)
x = df["Observation Value"]
y = df["Time period"]
# x-axis label
plt.xlabel('Observation Value')
# frequency label
plt.ylabel('Time period')
plt.show()
17
18
Experiment 16:
In [4]: ts = ts.cumsum()
In [5]: ts.plot();
19
In [21]: df2.plot.bar();
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.