0% found this document useful (0 votes)
107 views5 pages

Python Programming Practical Exercises

The document provides a practical list for a BSc IIIrd Year Computer Science course focused on Python programming. It includes ten exercises that cover various programming concepts such as finding multiples, string manipulation, removing duplicates, copying lists, and generating dictionaries. Each exercise is accompanied by sample code demonstrating the required functionality.
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)
107 views5 pages

Python Programming Practical Exercises

The document provides a practical list for a BSc IIIrd Year Computer Science course focused on Python programming. It includes ten exercises that cover various programming concepts such as finding multiples, string manipulation, removing duplicates, copying lists, and generating dictionaries. Each exercise is accompanied by sample code demonstrating the required functionality.
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

BSc IIIrd Year CS Practical List ( Python Programming )

1. Find all numbers which are multiple of 17, but not the multiple of
5, between 2000 and 2500.

for i in range (2000,2500):


if(i%17==0) and (i%5!=0):
print("",i)

2. Print the first 2 and last 3 characters in a given string. Use the
string slicing.

def string_both_ends(str):
if len(str) < 2:
return ''
return str[0:2] + str[-2:]
string = input('Enter string \n')
print(string)
print(string_both_ends(string))

3. Write a program that eliminates duplicates in a list.

def Remove(duplicate):
final_list=[]
for num in duplicate:
if num not in final_list:
final_list.append(num)
return final_list
duplicate = [2,4,10,20,5,2,20,4]
print(Remove(duplicate))
4. Implement shallow copy and deep copy of a list.
import copy
# initializing list 1
list1 = [1, 7, [3,5], 8]
# using copy to shallow copy
list2 = [Link](list1)
# original elements of list
print ("The original elements before shallow copying")
for i in range(0,len(list1)):
print (list1[i],end=" ")
print("\r")
# adding and element to new list
list2[2][0] = 10
# checking if change is reflected
print ("The original elements after shallow copying")
for i in range(0,len( list1)):
print (list1[i],end=" ")

5. Find the largest of a n number, usinga user defined function


(largest).

# Take input from user


n = int(input("Enter the number of elements: "))
elements = []
for i in range(n):
element = int(input(f"Enter element {i + 1}: "))
[Link](element)
largest = elements[0]
for num in elements:
if num > largest:
largest = num
print("The largest number is:", largest)
6. Write a function that capitalizes all vowels in a string.

name = input('Enter string?\n')


def conVowUpp(str):
N = len(name)
str1 =""
for i in range(N):
if (str[i] == 'a' or str[i] == 'e' or
str[i] == 'i' or str[i] == 'o' or
str[i] == 'u'):
c = (str[i]).upper()
str1 += c
else:
str1 += str[i]
print("Printing vowels of string in capital letters")
print(str1)
# Driver Code
if __name__ == '__main__':
conVowUpp(name)

7. Read a line containing digits and letters. Write a program to give


the count of digit and letters.

str1 = input('Enter string?\n')


print("Calculating number of digits and letters in entered string")
alpha,string=0,str1
for i in string:
if ([Link]()):
alpha+=1
print("Number of Digit is", len(string)-alpha)
print("Number of Alphabets is", alpha)
8. Write a function myReverse() which receives a string as an input
and returns the reverse of the string.

string = input('Enter a string \n')


print("You entered : ",string)
def myReverse(x):
return x[::-1]
mytxt = myReverse(string)
print("Its reverse is : ", mytxt)

9. Use the list comprehension methodology in python , to generate the


square of all odd numbers in a given list.

data=[1,2,3,4,5,6,7]
# use list comprehension to get square of odd numbers
result = [i*i for i in data if i%2!=0]
print(result)

10. Generate a dictionary which contains cubes of key of integers


between 1 and 10.

A
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
cubes = {x: x * x * x for x in numbers}
print(numbers)
print(cubes)
B
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
d=dict()
cubes = {d := x * x * x for x in numbers}
print(numbers)
print(cubes)

C
d = dict()
# Iterate through numbers from 1 to 'n' (inclusive).
for x in range(1, 11):
# Calculate the square of each number and store it in the dictionary
'd' with the number as the key.
d[x] = x * x * x
# Print the dictionary 'd' containing the squares of numbers from 1 to
'n'.
print("dictionary to store the cube of numbers (1-10).")
print(d)

Common questions

Powered by AI

Writing programs to perform shallow and deep copies involves understanding memory allocation and object referencing in Python. For shallow copies, using `copy()` replicates the top-level structure, whereas `deepcopy()` duplicates the whole object graph. Considerations include knowing when changes to nested objects should or shouldn't affect the original object. Pitfalls include inadvertently modifying shared resources in shallow copies, leading to debugging challenges, and potential performance drawbacks of deep copies due to increased memory and process time .

A Python program counts the number of alphabets and digits in a string by iterating over each character and testing if it is an alphabet or digit using built-in methods like `isalpha()` and `isdigit()`. The challenges involve correctly identifying and segregating these characters in diverse input forms and ensuring efficiency in processing large strings. It requires understanding of Python’s string-handling capabilities and logical structuring to maintain accuracy in various scenarios .

List comprehension is a concise way to create lists in Python. It allows the generation of a list by iterating over an iterable and applying an expression on each element. In generating squares of odd numbers, list comprehension saves time and reduces code complexity by encapsulating loops and conditional logic into a single line. This enhances code efficiency as it minimizes the need for multiple lines of loop structures to filter and process each element individually .

Capitalizing vowels in a string can be significant for enhancing textual data readability or creating stylistic text variations. This can be applied in contexts like formatting user input for consistent data entry in applications, improving readability in environments where case distinction enhances understanding, or generating visually distinct text for artistic or design purposes. It is a basic string manipulation task that showcases understanding of character iteration and conditional transformations in Python .

Reversing a string with a custom function allows for tailored control of the reversal process and offers educational insight into string manipulation logic. Unlike Python’s built-in functions that achieve this directly, a custom function can include additional operations or conditions during reversal. It might be used in pedagogical settings to understand underlying operations or when additional functionality (such as reversing selective segments) is needed within the same operation .

Using list comprehension for generating dictionaries of cubes provides a clearer, more concise syntax compared to traditional iterative loops. List comprehension encapsulates the logic of iteration and expression in a single, readable line of code, reducing the potential for errors and enhancing readability. Conversely, traditional loops require separate structures for iteration and logic application, which can lead to verbose and error-prone code. This is beneficial for experienced programmers who seek efficiency and clarity in their scripts .

In Python, a shallow copy of a list replicates the list structure but not the nested objects. Changes to nested mutable objects in the shallow copy affect the original list. Conversely, a deep copy creates a new list and recursively copies every object found in the original list, ensuring independence from the original. The implication of using a shallow copy is that modifications to nested objects reflect in both lists, which may lead to unintended side-effects. A deep copy, however, is safer for complex, nested lists because it prevents these side-effects, although it demands more memory and processing time .

Implementing a function to eliminate duplicates in a list is crucial for data integrity and reducing data redundancy. By ensuring each element is unique, it optimizes data processing tasks, such as searching or aggregating data. This is particularly important in data analysis and database management, where duplicate entries can skew results and analyses. It enhances the accuracy and efficiency of operations on datasets by maintaining a consistent and concise list .

String slicing in Python allows for efficient retrieval of substrings by specifying a start and end index. This provides a simple way to extract parts of the string. Slicing is useful in scenarios where specific parts of a string format need extraction, such as accessing the first and last few characters of a string for data processing tasks or formatting strings by combining beginning and ending segments to create new strings .

Using a user-defined function to find the largest number in a collection involves creating a procedure that iterates through the elements, compares each with the current largest, and updates accordingly. This approach is beneficial because it encapsulates the logic for reuse and makes the code modular and maintainable. It is particularly useful in data analysis as it streamlines processing large datasets by automating common analytical tasks, reducing potential for error and improving code readability and maintainability .

You might also like