0% found this document useful (0 votes)
15 views28 pages

AI Lab2

lab 2

Uploaded by

Muhammad Umair
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)
15 views28 pages

AI Lab2

lab 2

Uploaded by

Muhammad Umair
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/ 28

Lab 2-A

Lists:
Lists are what they seem - a list of values. Each one of them is numbered, starting from zero.
You can remove values from the list, and add new values to the end. Example: Your many cats'
names. Compound data types, used to group together other values. The most versatile is the list,
which can be written as a list of comma-separated values (items) between square brackets. List
items need not all have the same type.

cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester']

print (cats[2])
cats.append(‘Oscar’)

#Remove 2nd cat, Snappy.


del cats[1]

Compound datatype:
>>> a = ['spam', 'eggs', 100, 1234]

>>> a[1:-1] #start at element at index 1, end before last element


['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boo!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']

>>> a= ['spam', 'eggs', 100, 1234]


>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]

Replace some items:


>>> a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]

Remove some:
>>> a[0:2] = []
>>> a
[123, 1234]

Clear the list: replace all items with an empty list:


>>> a[:] = []
>>> a
[]

Length of list:
>>> a = ['a', 'b', 'c', 'd']
>>> len(a)
4

Nested lists:
>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]

Functions of lists:
list.append(x): Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L): Extend the list by appending all the items in the given list; equivalent to a[len(a):]
= L.

list.insert(i, x): Insert an item at a given position. The first argument is the index of the element
before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is
equivalent to a.append(x).

list.remove(x): Remove the first item from the list whose value is x. It is an error if there is no
such item.

list.pop(i): Remove the item at the given position in the list, and return it. If no index is
specified, a.pop() removes and returns the last item in the list.

list.count(x): Return the number of times x appears in the list.

list.sort(): Sort the items of the list, in place.

list.reverse(): Reverse the elements of the list, in place.

Tuples:
Tuples are just like lists, but you can't change their values. Again, each value is numbered
starting from zero, for easy reference. Example: the names of the months of the year.

months = ('January' , 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December')

Index Value
0 January
1 February
2 March
3 April
4 May
5 June
6 July
7 August
8 September
9 October
10 November
11 December

We can have easy membership tests in Tuples using the keyword in.
>>> 'December' in months # fast membership testing

True

Access Tuple Elements using Indexes:

names = ('Jeff', 'Bill', 'Steve', 'Yash')


print(names[0]) # prints 'Jeff'
print(names[1]) # prints 'Bill'
print(names[2]) # prints 'Steve'
print(names[3]) # prints 'Yash'

nums = (1, 2, 3, 4, 5)
print(nums[0]) # prints 1
print(nums[1]) # prints 2
print(nums[4]) # prints 5

names = ('Jeff', 'Bill', 'Steve', 'Yash')


print(names[-4]) # prints 'Jeff'
print(names[-3]) # prints 'Bill'
print(names[-2]) # prints 'Steve'
print(names[-1]) # prints 'Yash'

names = ('Jeff', 'Bill', 'Steve', 'Yash')


a, b, c, d = names # unpack tuple
print(a, b, c, d)

Update or Delete Tuple:

>> names = ('Jeff', 'Bill', 'Steve', 'Yash')


>>> names[0] = 'Swati'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> del names[0]


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion

Sets:
A set is an unordered collection with no duplicate elements. Basic uses include membership
testing and eliminating duplicate entries. Set objects also support mathematical operations like
union, intersection, difference, and symmetric difference.
Curly braces or the set() function can be used to create sets. Note: to create an empty set you
have to use set(), not {}; the latter creates an empty dictionary.
Example 1:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']

>>> fruit = set(basket) # create a set without duplicates

>>> fruit

{'banana', 'orange', 'pear', 'apple' }

>>> 'orange' in fruit # fast membership testing

True

>>> 'crabgrass' in fruit

False

Example 2:

>>> # Demonstrate set operations on unique letters from two words

>>> a = set('abracadabra')

>>> b = set('alacazam')

>>> a # unique letters in a

{'a', 'r', 'b', 'c', 'd'}

>>> a - b # letters in a but not in b

{'r', 'd', 'b'}


>>> a | b # letters in either a or b

{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}

>>> a & b # letters in both a and b

{'a', 'c'}

>>> a ^ b # letters in a or b but not both

{'r', 'd', 'b', 'm', 'z', 'l'}

Set comprehensions are also supported:

>>> a = {x for x in 'abracadabra' if x not in 'abc'}

>>> a

{'r', 'd'}

Dictionaries:
Dictionaries are similar to what their name suggests - a dictionary. In a dictionary, you have an
'index' of words, and for each of them a definition.

In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't
numbered - they aren't in any specific order, either - the key does the same thing.

You can add, remove, and modify the values in dictionaries. Example: telephone book.

The main operations on a dictionary are storing a value with some key and extracting the value
given the key. It is also possible to delete a key:value pair with del. If you store using a key that
is already in use, the old value associated with that key is forgotten. It is an error to extract a
value using a non-existent key.

Performing list(d.keys()) on a dictionary returns a list of all the keys used in the dictionary, in
arbitrary order (if you want it sorted, just use sorted(d.keys()) instead). To check whether a single
key is in the dictionary, use the in keyword.

At one time, only one value may be stored against a particular key. Storing a new value for an
existing key overwrites its old value. If you need to store more than one value for a particular
key, it can be done by storing a list as the value for a key.

phonebook = {'ali':8806336, 'omer':6784346,'shoaib':7658344, 'saad':1122345 }


#Add the person '' to the phonebook:
phonebook['waqas'] = 1234567
print("Original Phonebook")
print(phonebook)
# Remove the person 'shoaib' from the phonebook:
del phonebook['shoaib']

print("'shoaib' deleted from phonebook")


print(phonebook)

phonebook = {'Andrew Parson':8806336, \


'Emily Everett':6784346, 'Peter Power':7658344, \
'Louis Lane':1122345}

print("New phonebook")
print(phonebook)

#Add the person 'Gingerbread Man' to the phonebook:


phonebook['Gingerbread Man'] = 1234567

list(phonebook.keys())

sorted(phonebook.keys())

print( 'waqas' in phonebook)


print( 'Emily Everett' in phonebook)

#Delete the person 'Gingerbread Man' from the phonebook:


del phonebook['Gingerbread Man']

Lab Task 2A:


1. Create list of Fibonacci numbers after calculating Fibonacci series up to the number n
which you will pass to a function as an argument. The number n must be input by the
user.
They are calculated using the following formula: The first two numbers of the series is
always equal to 1, and each consecutive number returned is the sum of the last two
numbers. Hint: Can you use only two variables in the generator function?
a = 1
b = 2
a, b = b, a
will simultaneously switch the values of a and b.
The first number in the series should be 1. (The output will start like 1,1,2,3,5,8,…)

def fib(n):
a = 1
b = 1
result = [a, b]
for i in range(2, n):
next_num = a + b
result.append(next_num)
a = b
b = next_num
print(result)
num = int(input("Enter length of fibonacci sequence: "))
fib(num)

2. Write a program that lets the user enter some English text, then converts the text to Pig-
Latin. To review, Pig-Latin takes the first letter of a word, puts it at the end, and appends
“ay”. The only exception is if the first letter is a vowel, in which case we keep it as it is
and append “hay” to the end. For example: “hello” -> “ellohay”, and “image” ->
“imagehay”
It will be useful to define a list or tuple at the top called VOWELS. This way, you can
check if a letter x is a vowel with the expression x in VOWELS.
It’s tricky for us to deal with punctuation and numbers with what we know so far, so
instead, ask the user to enter only words and spaces. You can convert their input from a
string to a list of strings by calling split on the string:
“My name is John Smith”.split(“ ”) -> [“My”, “name”, “is”, “John”, “Smith”]

def pig_latin(text):
VOWELS = ("a", "e", "i", "o", "u")
words = text.split(" ")
pig_latin_words = []

for word in words:


if word[0].lower() in VOWELS:
pig_latin_word = word + "hay"
else:
pig_latin_word = word[1:] + word[0] + "ay"
pig_latin_words.append(pig_latin_word)

return " ".join(pig_latin_words)

text = input("Enter some English text: ")


pig_latin_text = pig_latin(text)
print("Text in Pig-Latin:", pig_latin_text)
Lab 2-B
Numpy Array:
Numerical Python (Numpy) is used for performing various numerical computation in python.
Calculations using Numpy arrays are faster than the normal python array. Further, pandas are
build over numpy array, therefore better understanding of python can help us to use pandas more
effectively.
Boolean Indexing is very important feature of numpy, used frequently in pandas.
Reshaping Arrays
Concatenating Data

Pandas:
Before loading the data, lets understand the 2 key data structures in Pandas – Series and
DataFrames

o Series can be understood as a 1 dimensional labelled / indexed array. You can access
individual elements of this series through these labels.
o A dataframe is similar to Excel workbook – you have column names referring to columns
and you have rows, which can be accessed with use of row numbers. The essential
difference being that column names and row numbers are known as column and row
index, in case of dataframes.

Reading Data Using Pandas:


Exploring Data Frames:

Datatypes in Pandas:

Dataframe Datatypes:
Dataframe Attributes:

Dataframe Methods:
Dataframe Group by Method:
Dataframe: Filtering

Dataframe: Slicing
Dataframe: Method loc
Dataframe: Method iloc

Dataframe: sorting
Missing Values:
Aggregation Function in Pandas: computing a summary statistic about each group, i.e.

• compute group sums or means


• compute group sizes/counts

Common aggregation functions: min, max, count, sum, prod, mean, median, mode, mad, std, var
Creating a Histogram Using Pandas:

Lab Journal 2B:


1. Write a Pandas program to compute the Euclidean distance between two given series. The
Euclidean distance or Euclidean metric is the "ordinary" straight-line distance between two
points in Euclidean space. With this distance, Euclidean space becomes a metric space.

Series-1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


Series-2: [11, 8, 7, 5, 6, 5, 3, 4, 7, 1]
# Define two series
series1 = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
series2 = pd.Series([11, 8, 7, 5, 6, 5, 3, 4, 7, 1])

# Calculate Euclidean distance


euclidean_distance = np.sqrt(np.sum((series1 - series2) ** 2))
print("Euclidean Distance between the two series: ", euclidean_distance)

2. Import onlineretail.csv dataset (https://www.kaggle.com/vijayuv/onlineretail )


o display data

data = pd.read_csv("E:\\Code Playground\\Python Workspace\\6th semester\\


lab2\customers-100.csv")
print(data)

o display summary of numerical fields

print(data.describe())
o display first and last column

# Display the first and last column of the dataset


first_and_last_columns = data.iloc[:, [0, -1]]

print(first_and_last_columns)

o Analyze data by plotting boxplot and histogram

# Plot boxplot for a numerical field (e.g., 'Quantity')


plt.figure(figsize=(10, 6))
sns.boxplot(x=data["discount_percentage"])
plt.title("Boxplot of Quantity")
plt.show()
# Plot histogram for another numerical field (e.g., 'UnitPrice')
plt.figure(figsize=(10, 6))
plt.hist(data["discount_percentage"], bins=50, color="skyblue",
edgecolor="black")
plt.title("Histogram of Unit Price")
plt.xlabel("product_name")
plt.ylabel("discount_percentage")
plt.show()
Lab 2-C
Graphs:

Data Visualization is very much important task in machine learning. For data visualization in
python we use matplotlib and sklearn modules. With the usage of these modules we can have
clear view of how data points are rendered in 2D space. Below are some exercises which would
help you to plot graphs in an easier way.
Example-1: Line Plot in Python.

import matplotlib.pyplot as plt

import numpy as np

# Prepare the data

# Generates 100 samples between 0 to 10

x = np.linspace(0, 10, 100)

# Plot the data

plt.plot(x, x, label='linear')

# Add a legend

plt.legend()

# Show the plot

plt.show()

Example-2: Scatter Plot in Python.

import matplotlib.pyplot as plt

plt.plot([0, 1, 2, 3, 4, 5], [10, 15,


20, 25, 30, 35], color='lightblue',
linewidth=3)

plt.scatter([0.3, 3.8, 1.2, 2.5], [15,


25, 9, 26], color='darkgreen',
marker='o')

plt.show()

Example-3: Sub Plots in Python.


import matplotlib.pyplot as plt

fig = plt.figure()

# Set up Axes

sub1 = fig.add_subplot(221)

sub2 = fig.add_subplot(222)

sub3 = fig.add_subplot(223)

sub4 = fig.add_subplot(224)

# Scatter the data

sub1.scatter(np.linspace(0, 1, 5), np.linspace(0, 5, 5))

sub2.scatter(np.linspace(0, 1, 5), np.linspace(0, 5, 5))

sub3.scatter(np.linspace(0, 1, 5), np.linspace(0, 5, 5))

sub4.scatter(np.linspace(0, 1, 5), np.linspace(0, 5, 5))

# Show the plot

plt.show()

Example-4: Iris Dataset with 2 Features.


from sklearn import datasets

import matplotlib.pyplot as plt

iris = datasets.load_iris()

plt.scatter(iris.data[:,0],iris.data[:,1],
c=iris.target)

plt.colorbar(ticks=[0, 1, 2])

plt.show()

Example-4: 3D Plots in Python.

from mpl_toolkits import mplot3d

from sklearn import datasets

import numpy as np

import matplotlib.pyplot as plt

fig = plt.figure()

ax = plt.axes(projection='3d')

iris = datasets.load_iris()

ax.scatter(iris.data[:,0],

iris.data[:,1],iris.data[:,2],
c=iris.target)

ax.set_xlabel('Petal width')

ax.set_ylabel('Sepal length')

ax.set_zlabel('Petal length')

Lab Journal 2C:


Visualize the following data in python. Please provide the reason for the choice of graph.

Feature 1 Feature 2
12 4

11 5

8 1

6 4

9 3

6 6

10 2

You might also like