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

Simple Python Programs for Beginners

The document contains a series of Python programming tasks demonstrating various concepts such as linear search, insertion in sorted lists, object-oriented programming, data manipulation with Pandas, NumPy operations, data visualization with Matplotlib and Seaborn, and regression models. Each task is accompanied by code snippets and example outputs. The tasks cover a wide range of topics including encapsulation, overloading, data cleaning, time series analysis, and different types of graphs.

Uploaded by

Ranjitha Bhaskar
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)
17 views20 pages

Simple Python Programs for Beginners

The document contains a series of Python programming tasks demonstrating various concepts such as linear search, insertion in sorted lists, object-oriented programming, data manipulation with Pandas, NumPy operations, data visualization with Matplotlib and Seaborn, and regression models. Each task is accompanied by code snippets and example outputs. The tasks cover a wide range of topics including encapsulation, overloading, data cleaning, time series analysis, and different types of graphs.

Uploaded by

Ranjitha Bhaskar
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

#1. Write a Python program to perform linear search.

a=[]
n= int(input("Enter how many elements: "))
print("Enter array elements: ")
for i in range(n):
x = int(input())
[Link](x)
key = int(input("Enter an element to be searched: "))
f = 0
for i in a:
if i == key:
f=1
break
if f == 1:
print("Key found")
else:
print("Key not found")

OUTPUT:

Enter how many elements: 5


Enter array elements:
3
8
9
1
4
Enter an element to be searched: 8
Key found
#2. Write a Python program to insert an element into a sorted list

import bisect as b
lst = []
n = int(input("Enter n:"))
print("Enter list elements in sorted order:")
for i in range(n):
x = int(input())
[Link](x)
[Link]()
key = int(input("Enter element to be inserted: "))
[Link](lst,key)
print("Contents of list after insertion:")
for i in lst:
print(i,end=" ")

OUTPUT:

Enter list elements in sorted order:


1
3
4
5
6
Enter element to be inserted: 2
Contents of list after insertion:
1 2 3 4 5 6
#3. Write a python program using object oriented programming to demonstrate
encapsulation, overloading and inheritance
class A:
def __init__(self):
self.a = 0
self.b = 0
def getdata(self):
self.a = int(input("Enter a :"))
self.b = int(input("Enter b :"))
def putdata(self):
print("a=",self.a,"b=",self.b)

class B(A):
def __init__(self):
self.c = 0
def sum(self):
self.c = self.a + self.b
print(self.c)
def add(self,m,n):
s = m + n
return s
x = B()
[Link]()
[Link]()
[Link]()
y = [Link](10,20)
print("After adding :",y)
z = [Link]("Hello" , "World")
print("After Concatentation:",z)

OUTPUT:

Enter a :23
Enter b :56
a= 23 b= 56
79
After adding : 30
After Concatentation: HelloWorld
#4. Implement a python program to demonstrate 1) Importing Datasets 2) Cleaning the Data
3) Data frame manipulation using Numpy
import pandas as pd
#importing Datasets
df=pd.read_csv('C:\\Users\\bikas\\Downloads\\[Link]')
df
[Link]()
[Link]()

#print no of rows and cols in csv file


print(len([Link][0]))
print(len([Link][1]))

#printing missing values


print([Link]().mean())
print("Total missing Values:",[Link]().[Link]())

#dealing the missing values


[Link](0, inplace=True)

#after replacing missing value


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

#printing duplicated rows


print(df[[Link]()])

OUTPUT:
1436
11

Unnamed: 0 0.000000
Price 0.000000
Age 0.069638
KM 0.000000
FuelType 0.069638
HP 0.000000
MetColor 0.104457
Automatic 0.000000
CC 0.000000
Doors 0.000000
Weight 0.000000
dtype: float64
Total missing Values: 350

0
Empty DataFrame
Columns: [Unnamed: 0, Price, Age, KM, FuelType, HP, MetColor, Automatic, CC, Doors, Weight]
Index: [ ]
#5. Implement a python program to demonstrate the following using NumPy a) Array
manipulation, Searching, Sorting and splitting. b) broadcasting and Plotting NumPy arrays
# (a)

import numpy as np
arr1 = [Link]([[1,2,3],[4,5,6]])
arr2 = [Link]([[7,8,9],[10,11,12]])
print("Concatenation of array =",[Link]([arr1,arr2]))
print("Concatenation of array =",[Link]([arr1,arr2],axis =1))
print("Vertical stack =",[Link]((arr1,arr2)))
print("Horizontal stack =",[Link]((arr1,arr2)))

# seaching ,Sorting

arr3 = [Link]([1,2,3,4,5,4])
x = [Link](arr3 == 4)
print(x)
arr4 = [Link]([6,7,8])
x = [Link](arr4,8)
print(x)
arr5 = [Link]([4,3,5,2,1])
print("Sorted Array :",[Link](arr5))

# Splitting

arr6 = [Link]([1,2,3,4,5,6,7,8])
print([Link](arr6,2))
arr7 = [Link]([[1,2,3,4],[5,6,7,8]])
print([Link](arr7,2))
print([Link](arr7,2))

#(b)
# Broadcasting

arr8 = [Link]([1, 2, 3])


arr9 = [Link]([4, 5])
print("Broadcasting:")
print("arr8 * arr9 = ", [Link](arr8, (3, 1)) * arr9)
arr10 = [Link]([[1, 2, 3], [4, 5, 6]])
arr11 = [Link]([[1, 2], [3, 4], [5, 6]])
print("arr10 + arr11 =", [Link](arr11, (2,3)) + arr10)

# Plotting

import numpy as np
import [Link] as plt
x = [Link](0,3*[Link],0.1)
y_sin = [Link](x)
y_cos = [Link](x)
[Link](x,y_sin)
[Link](x,y_cos)
[Link]("x axis label")
[Link]("y axis label")
[Link]("sine and cosine")
[Link](['sine','cosine'])
[Link]()

OUTPUT:
#6. Implement a python program to demonstrate Data visualization with various Types of
Graphs using Numpy

import numpy as np
import [Link] as plt
# Line plot
# Generating sample data
x = [Link]([1,2,3,4,5])
y = x*2
[Link](figsize=(10, 6))
[Link](x,y)
[Link]('Line Plot')
[Link]('x-axis')
[Link]('y-axis')
[Link](True)
[Link]()

# Scatter plot
x1=[1,2,3,4,5]
y1=[2,5,2,6,8]
x2=[1,2,3,4,5]
y2=[4,5,8,9,19]
[Link](figsize=(10, 6))
[Link](x1,y1)
[Link](x2,y2)
[Link]('Scatter Plot')
[Link]('x-axis')
[Link]('y-axis')
[Link](x2,y2)
[Link](True)
[Link]()
# Histogram
data = [Link](0, 1, 1000)
[Link](figsize=(10, 6))
[Link](data, bins=30, color='green', edgecolor='black')
[Link]('Histogram')
[Link]('Value')
[Link]('Frequency')
[Link](True)
[Link]()
# Bar plot
categories = ['A', 'B', 'C', 'D', 'E']
values = [7, 13, 5, 17, 10]
[Link](figsize=(10, 6))
[Link](categories, values, color='blue')
[Link]('Bar Plot')
[Link]('Category')
[Link]('Value')
[Link](True)
[Link]()
# Pie chart
sizes = [15, 30, 45, 10]
labels = ['A', 'B', 'C', 'D']
[Link](figsize=(10, 6))
[Link](sizes, labels=labels,autopct='%1.1f%%') #The '%1.1f%%' format means percentages will
be displayed with 1 decimal place.
[Link]('Pie Chart')
[Link]('equal')
[Link]()

OUTPUT:
#7. Write a Python program that creates a mxn integer array and Prints its attributes using
matplotlib
import numpy as np
arr= [Link]([[10,20,30],[40,50,60]],int)
print(arr)
print("Dimension attribute=",[Link])
print("Shape attribute=",[Link])
print("Size attribute=",[Link])
print("Itemsize attribute=",[Link])
print("Dtype attribute=",[Link])
print("Nbytes attribute=",[Link])

OUTPUT:
[[10 20 30]
[40 50 60]]
Dimension attribute= 2
Shape attribute= (2, 3)
Size attribute= 6
Itemsize attribute= 4
Dtype attribute= int32
Nbytes attribute= 24
# 8. Write a Python program to demonstrate the generation of linear regression models.
import numpy as np
import [Link] as plt
from sklearn.linear_model import LinearRegression

# Define array x and reshape it into a column vector and array y with corresponding target
values
x = [Link]([1, 2, 3, 4, 5]).reshape(-1, 1)
y = [Link]([3, 5, 7, 9, 11])

# Creating and training the linear regression model


model = LinearRegression().fit(x, y)

# Print the model coefficients and intercept


print('Coefficients:', model.coef_)
print('Intercept:', model.intercept_)

# Plotting the data and the linear regression line


[Link](x, y, color='red', label='Data')
[Link](x, [Link](x),label='Linear Regression')
[Link]('x')
[Link]('y')
[Link]('Linear Regression Model')
[Link]()
[Link]()

OUTPUT:
Coefficients: [2.]
Intercept: 1.0
# 9. Write a Python program to demonstrate the generation of logistic regression models.
import numpy as np
import [Link] as plt
from sklearn.linear_model import LogisticRegression

# Define array x and reshape it into a column vector and array y with corresponding target
values
x = [Link]([1, 2, 3, 4, 5]).reshape(-1, 1)
y = [Link]([0, 0, 1, 1, 1]) # Binary classification, so using 0 and 1 as target labels

# Creating and training the logistic regression model


model = LogisticRegression().fit(x, y)

# Print the model coefficients and intercept


print('Coefficients:', model.coef_)
print('Intercept:', model.intercept_)

# Plotting the data and the logistic regression line


[Link](x, y, color='red', label='Data')
[Link](x, model.predict_proba(x)[:, 1], label='Logistic Regression')
[Link]('x')
[Link]('y')
[Link]('Logistic Regression Model')
[Link]()
[Link]()

OUTPUT:
Coefficients: [[1.04696432]]
Intercept: [-2.53376385]
#10. Write a Python program to demonstrate Time series analysis with Pandas.
import pandas as pd
import numpy as np
import [Link] as plt

# Generating sample data - time series of temperature readings with random values
[Link](0)
dates = pd.date_range(start='2024-01-01', periods=10)
data = {'Temperature': [Link](0, 30, size=10)}

# Create a DataFrame from the sample data


df = [Link](data, index=dates)
df

# Calculate rolling mean (moving average) for temperature readings


rolling_mean = df['Temperature'].rolling(window=2).mean()

#Calculate percentage change in temperature readings


percentage_change = df['Temperature'].pct_change() * 100

# Resample data to monthly frequency


monthly_resampled = [Link]('M').mean()

# Plot temperature readings


[Link](figsize=(10, 5))
[Link]('Temperature Readings Over Time')
[Link]('Date')
[Link]('Temperature (°C)')
[Link](True)
[Link]()

OUTPUT:

Temperature
2024-01-01 12
2024-01-02 15
2024-01-03 21
2024-01-04 0
2024-01-05 3
2024-01-06 27
2024-01-07 3
2024-01-08 7
2024-01-09 9
2024-01-10 19
#11. Write a Python program to demonstrate Data Visualization using Seaborn
import seaborn as sns
import pandas as pd
sns.get_dataset_names()

tips = sns.load_dataset('tips')
data = [Link](tips)

[Link](x="tip",y='total_bill',data=data)

[Link](x="tip",y='total_bill',data=data,hue='day')

[Link](data['tip'],kde=True)

[Link](x="day",y='tip',data=data,hue='sex')

OUTPUT:

['anagrams',
'anscombe',
'attention',
'brain_networks',
'car_crashes',
'diamonds',
'dots',
'dowjones',
'exercise',
'flights',
'fmri',
'geyser',
'glue',
'healthexp',
'iris',
'mpg',
'penguins',
'planets',
'seaice',
'taxis',
'tips',
'titanic']

Common questions

Powered by AI

Encapsulation in Python is used to restrict access to methods and variables, providing a means to bundle the data and methods that operate on the data within a class. Overloading allows the same function name to have different implementations. Inheritance allows a class to inherit properties and methods from another class. For example, class A provides basic data encapsulation with variables 'a' and 'b'. Class B inherits from A, adding a new method and demonstrating overloading by having a 'add' method with different behaviors depending on arguments .

Missing data in pandas can be handled by using methods such as 'fillna()' to replace missing values with specified values, and 'dropna()' to remove rows or columns with missing values. In the provided program, missing values are replaced with 0 using 'fillna(0, inplace=True)', effectively reducing the count of missing data to zero, which facilitates analysis without biasing results due to missing entries .

Linear regression models in scikit-learn are generated by defining the input feature array 'x', reshaping it into a column vector, and the target array 'y'. The 'LinearRegression()' class is used to fit a model, outputting coefficients and intercept that define the model equation. Coefficients represent the feature's weight, and intercept is the constant term, leading to the equation of a line for predictive analysis .

The 'bisect' module in Python provides a way to insert an element into a sorted list while maintaining the list's order. This method is advantageous because it performs a binary search to find the correct insertion point, thereby making the insertion operation more efficient, with a time complexity of O(log n). The process uses the 'insort()' function from the 'bisect' module .

Printing array attributes such as dimension, shape, size, itemsize, dtype, and nbytes allows a deeper understanding of the array's structure and memory usage, which is critical for optimizing performance and debugging during data analysis. For example, understanding an array's shape helps in reshaping or broadcasting operations, while dtype reveals data type, ensuring compatibility in computations .

Broadcasting in NumPy is a method that allows operations on arrays of different shapes by virtually expanding the smaller array(s) without making copies of data. It simplifies codes and reduces memory usage for operations like arithmetic on arrays of differing dimensions. For instance, the expression 'arr8 * arr9' broadcasts the smaller array across the larger shape to perform element-wise multiplication .

Time series analysis with pandas involves techniques such as resampling data for different frequencies, computing rolling means for smoothing, and percentage change calculations for trend analysis. Resampling adjusts data granularity (e.g., daily to monthly), rolling means remove noise, and percentage changes highlight relative shifts, thereby revealing underlying trends, seasonality, and correlations over time .

Matplotlib can generate several types of plots, including line plots for trends over time, scatter plots for relationships between variables, histograms for frequency distributions, bar plots for categorical comparisons, and pie charts for visualizing parts of a whole. Each serves different purposes; line plots show changes over time, scatter plots show variable relationships, histograms represent distributions, bar plots are useful for comparisons, and pie charts show proportions .

Linear search can be implemented in Python by iterating through the elements of a list to find a specific element and using a flag to determine its presence . Its time complexity is O(n) because it may require checking through all n elements in the worst case .

Logistic regression models constructed using scikit-learn involve defining feature and target arrays, fitting them with LogisticRegression(). It outputs coefficients and an intercept, creating a model that predicts probabilities of binary outcomes. The 'predict_proba()' function provides probabilities across classes, indicating confidence in classification, with coefficients showing feature impact on the log-odds scale .

You might also like