Python Lab Assignment - Google Docs 1
Python Lab Assignment - Google Docs 1
VVP
EN
GINEERING
COLLEGE
1
12
123
1234
12345
Code:
for i in range(1,6):
for j in range(1,i+1):
print(j,end="")
print()
Output:
1
12
123
1234
12345
1
2 1
4 2 1
8 4 2 1
16 8 4 2 1
32 16 8 4 2 1
64 32 16 8 4 2 1
128 64 32 16 8 4 2 1
Code:
n = 8
for i in range(n):
num = 2 ** i
while num >= 1:
print(num,end=" ")
num = num / 2
print()
Output:
1
2 1.0
4 2.0 1.0
8 4.0 2.0 1.0
16 8.0 4.0 2.0 1.0
32 16.0 8.0 4.0 2.0 1.0
64 32.0 16.0 8.0 4.0 2.0 1.0
128 64.0 32.0 16.0 8.0 4.0 2.0 1.0
. Each new term in the Fibonacci sequence is generated by adding the previous two
3
terms. By starting with 1 and 2, the first 10 terms will be:
y considering the terms in the Fibonacci sequence whose values do not exceed four
B
million, find the sum of the even-valued terms.
Code:
a, b = 1, 2
total = 0
while a <= 4000000:
if a % 2 == 0:
total += a
a, b = b, a + b
print("Sum of even Fibonacci numbers under 4 million is:", total)
Output:
Sum of even Fibonacci numbers under 4 million is: 4613732
Code:
# Sample string
text = "Python Programming"
# 1. Length of string
print("Length:", len(text))
# 2. Convert to uppercase
print("Uppercase:", [Link]())
# 3. Convert to lowercase
print("Lowercase:", [Link]())
# 4. Replace a word
print("Replace 'Python' with 'Java':", [Link]("Python", "Java"))
# 5. Check if string starts with a word
print("Starts with 'Python'?", [Link]("Python"))
# 6. Check if string ends with a word
print("Ends with 'ing'?", [Link]("ing"))
# 7. Split the string
print("Split words:", [Link]())
# 8. Reverse the string
print("Reversed:", text[::-1])
Output:
Length: 18
Uppercase: PYTHON PROGRAMMING
Lowercase: python programming
Replace 'Python' with 'Java': Java Programming
Starts with 'Python'? True
Ends with 'ing'? True
Split words: ['Python', 'Programming']
Reversed: gnimmargorP nohtyP
Quiz-1
1. What type of language is python? Programming orscripting?
Python is a general-purpose programming language that can be used for both scripting
and larger application development. It is often used as a scripting language for
automating tasks, but it is also powerful enough to build full-scale applications.
Functions in Python are blocks of reusable code that perform a specific task. They are
defined using the def keyword. Example:
def greet(name):
print("Hello", name)
__ init __ is a constructor method in Python classes. It is automatically called when an
object is created and is used to initialize instance variables.
class Person:
def __init__(self, name):
[Link] = name
Output:
0
1
2
continue skips the current iteration of a loop and jumps to the next one.
for i in range(5):
if i == 3:
continue
print(i)
Output:
0
1
2
4
pass is a placeholder statement that does nothing. It’s used when a statement is
syntactically required but no action is needed.
for i in range(5):
pass # Will not raise an error even if body is empty
• Pickling: Converting a Python object into a byte stream for storage or transmission.
• Unpickling: Reversing the byte stream back into a Python object.
Used for saving data using the pickle module.
8. What are the differences between Python 2.x and Python 3.x?
4. Unicode – In Python 2, strings are ASCII by default and need a u prefix for
Unicode (u"Hello"), while in Python 3, all strings are Unicode by default.
5. range/xrange – Python 2 has range() (returns a list) and xrange() (returns an
iterator). Python 3 removes xrange() and makes range() return an iterator.
6. Input – Python 2 has raw_input() (string) and input() (evaluates expression). Python
3 only has input() which always returns a string.
7. Exceptions – In Python 2, exception syntax is except Exception, e:. In Python 3, it is
except Exception as e:.
8. Dictionary methods – In Python 2, .keys(), .values(), .items() return lists. In Python 3,
they return iterable views for better memory efficiency.
9. Libraries – Many standard libraries have been reorganized or renamed in Python 3
(e.g., ConfigParser is now configparser).
. List
1
Code:
my_list = [10, 20, 30, 40]
my_list.append(50)
my_list.remove(20)
my_list[1] = 35
print("List:", my_list)
utput:
O
List: [10, 35, 40, 50]
. Tuple
2
Code:
my_tuple = (1, 2, 3, 4)
print("Tuple Element at index 2:", my_tuple[2])
utput:
O
Tuple Element at index 2: 3
. Set
3
Code:
my_set = {1, 2, 3}
my_set.add(4)
my_set.discard(2)
print("Set:", my_set)
Output:
Set: {1, 3, 4}
. Dictionary
4
Code:
my_dict = {'name': 'John', 'age': 25}
my_dict['age'] = 26
my_dict['city'] = 'New York'
del my_dict['name']
print("Dictionary:", my_dict)
utput:
O
Dictionary: {'age': 26, 'city': 'New York'}
2. L ittle Robert likes mathematics. Today his teacher has given him two integers and asked
to find out how many integers can divide both the numbers. Would you like to help him
in completing his school assignment?
Code:
import math
. Given a string which contains lower alphabetic characters, we need to remove at most
3
one character from this string in such a way that frequency of each distinct character
becomes same in the string.
Input : abbccdd
Output : Yes , We can remove 'a' from above string to make the frequency of each
character same.
Input : abcdd
Output : Yes , We can remove 'd' from above string to make the frequency of each
character same.
Input : aabbbcccdddd
Output : No , We can't remove any character from above string to make the frequency
of each character same.
Code:
freq_counter = Counter(freq_values)
if len(freq_counter) == 1:
return "Yes"
elif len(freq_counter) == 2:
keys = list(freq_counter.keys())
if freq_counter[min(keys)] == 1 and min(keys) == 1:
return "Yes"
elif freq_counter[max(keys)] == 1 and max(keys) - min(keys) == 1:
return "Yes"
return "No"
print(can_equalize_frequency("abbccdd"))
print(can_equalize_frequency("abcdd"))
print(can_equalize_frequency("aabbbcccdddd"))
Output:
Yes
Yes
No
. Lapindrome is defined as a string which when split in the middle, gives two halves having
4
the same characters and same frequency of each character. If there are odd number of
characters in the string, we ignore the middle character and check for lapindrome.
For example , abccab, rotor and xyzxy are a few examples of lapindromes.
ote that abbaab is NOT a lapindrome. The two halves contain the same characters
N
but their frequencies do not match.
Code:
print(is_lapindrome("abccab"))
print(is_lapindrome("rotor"))
print(is_lapindrome("xyzxy"))
print(is_lapindrome("abbaab"))
Output:
YES
YES
YES
NO
Quiz-2
. To shuffle the list(say list1) what function do we use ?
1
a) [Link]()
b) shuffle(list1)
c) [Link](list1)
d) [Link](list1)
Ans: c) [Link](list1)
. What will be the output of the following Python code? a=[13,56,17] [Link]([87])
3
[Link]([45,67]) print(a)
a. 13, 56, 17, [87], 45, 67]
b. [13, 56, 17, 87, 45, 67]
c. [13, 56, 17, 87,[ 45, 67]]
d. [13, 56, 17, [87], [45, 67]]
Ans: a. 13, 56, 17, [87], 45, 67]
. Find the output of the following program: nameList = ['abc', 'xyz', 'pqr', 'def'] pos =
4
[Link]("Dip") print (pos * 3)
a. Dip Dip Dip
b. abc abc abc
c. xyz xyz xyz
d. ValueError: 'Dipesh' is not in list
Ans: d. ValueError: 'Dipesh' is not in list
5. Find the output of the following program: a = {i: i * i for i in range(6)} print (a)
a. Dictionary comprehension doesn’t exist
b. {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6:36}
c. {0: 0, 1: 1, 4: 4, 9: 9, 16: 16, 25: 25}
d. {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Ans: d. {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
2. Y
ou are given two integer arrays of size N X P and M X P ( N & M are rows, and P is the
column). Your task is to concatenate the arrays along axis .
Input Format:
The first line contains space separated integers N,M and P.
The next N lines contains the space separated elements of the P columns.
After that, the next M lines contains the space separated elements of the P columns.
3 2
4
1 2
1 2
1 2
1 2
3 4
3 4
3 4
Sample Output
[ [1 2]
[1 2]
[1 2]
[1 2]
[3 4]
[3 4]
[3 4]]
Code:
Quiz-3
1. Why NumPy is used in Python?
NumPy is used in Python for efficient numerical and scientific computing. It provides support for
large multidimensional arrays and matrices, along with mathematical functions to operate on
these arrays faster than standard Python lists.
4. The most important object defined in NumPy is an N-dimensional array type called?
a. ndarray
b. narray
c. nd_array
d. darray
Ans: a. ndarray
. The ________ function returns its argument with a modified shape, whereas the ________
6
method modifies the array itself.
a. reshape, resize
b. resize, reshape
c. reshape2, resize
d. None of the mentioned
Ans: a. reshape, resize
7. what is the use of the zeros() function in Numpy array in python ?
a. To make a Matrix with all element 0
b. To make a Matrix with all diagonal element 0
c. To make a Matrix with first row 0
es, NumPy is better than lists for numerical operations because it is faster, uses less memory,
Y
supports multi-dimensional arrays, and provides many built-in mathematical and statistical
functions.
Assignment 4To Perform data importing & conditioning using Numpy and
Pandas.
1. Create txt file and perform file operation.
Code:
import numpy as np
import pandas as pd
import os
import shutil
# Read again
df_updated = pd.read_csv("[Link]")
print("\n Updated Data after appending:")
print(df_updated)
utput:
O
File created successfully!
. Use pandas library to create series and dataframe from various format(Structured data
2
form)
Code:
import pandas as pd
import numpy as np
# Dictionary to DataFrame
data_dict = {
"ID": [1, 2, 3],
"Name": ["Pradyumna", "Amit", "Ravi"],
"Age": [21, 22, 23],
"City": ["Rajkot", "Ahmedabad", "Surat"]
}
df_from_dict = [Link](data_dict)
print("\n DataFrame from Dictionary:\n")
print(df_from_dict)
# NumPy 2D array
np_matrix = [Link]([[1, "Laptop", 50000], [2, "Phone", 30000], [3, "Tablet", 20000]])
[Link]("off")
[Link]()
df = [Link](data)
print("Original Dataset with Duplicates:\n")
print(df)
Duplicate Records:
ID Name City
2 2 Amit Ahmedabad
5 4 Karan Vadodara
Quiz-4
1. Mention the different types of Data Structures in Pandas
● DataFrame → 2D labeled tabular data (like a table with rows & columns).
● (Panel existed earlier for 3D data but is deprecated** in modern Pandas**).
. Which of the following indexing capabilities is used as a concise means of selecting data
3
from a pandas object?
a. In
b. ix
c. ipy
d. iy
Ans: b. Ix
5. Which of the following function gives information about top level data using Pandas?
a. head
b. tail
c. summary
d. none of the mentioned
Ans: a. head
. What will be output for the following code? import pandas as pd import numpy as np s =
6
[Link]([Link](4)) print([Link])
a. 0
b. 1
c. 2
d. 3
Ans: b. 1
eindexing is the process of changing the row/column labels of a DataFrame or Series to match
R
a new set of labels. If a label is missing in the original data, Pandas will insert NaN for that
position.
[[ 7 8 9]
[10 11 12]]]
. Perform the slicing , dicing, sorting and shuffling operation on NumPy array.
2
Code:
# Create a sample 1D array
arr = [Link]([10, 20, 30, 40, 50, 60])
print("Original Array:", arr)
Slicing
#
print("\nSlicing (arr[1:4]):", arr[1:4]) # elements from index 1 to 3
Sorting
#
unsorted_arr = [Link]([40, 10, 30, 20])
sorted_arr = [Link](unsorted_arr)
print("\nSorted Array:", sorted_arr)
. Perform the task for categorical variable and aggregation of the data.
3
Code:
import pandas as pd
. Demonstrate the usage of datetime and timedelta function in data science project.
4
Code:
import pandas as pd
from datetime import datetime, timedelta
Quiz-5
1. What is Time Series in Pandas?
T ime Series in Pandas is a sequence of data points indexed by timestamps or dates. It allows
easy handling of time-based data, resampling, shifting, and date-range generation.
3. Which are not correct property for Pie Chart plotting in matplotlib?
a. explode
b. autopct
c. align
d. None of the mentioned
Ans: c. align
4. Which are not correct marker for line appreance in matplotlib?
a. s
b. p
c. A
d. None of the mentioned
Ans: c. A
5. The plot method on Series and DataFrame is just a simple wrapper around ____________.
a. [Link]()
b. [Link]()
c. [Link]()
d. none of the mentioned
Ans: b. [Link]()
6. Which of the following graph can be used for simple summarization of data?
a. Scatterplot
b. Overlaying
c. Barplot
d. All of the mentioned
Ans: d. All of the mentioned
7. Which library would you prefer for plotting in Python language: Seaborn or Matplotlib?
● S
eaborn→ Better for statistical visualization, attractivedefault styles, easier for quick
plots.
● M
atplotlib→ More control and customization, supportscomplex visualizations.
For most data science tasks →Seabornis preferredfor quick and beautiful plots.