Python Assignment-2
Python Assignment-2
2. Write a Python code to delete all odd numbers and negative numbers from a given numeric list.
list=[]
n=int(input("Enter the number of elements you want to add "))
for i in range(0,n):
ele=int(input())
list.append(ele)
print("The entered list is: "+str(list))
list1=[]
for i in list:
if i >0:
if i%2==0:
list1.append(i)
print("Modified list is "+str(list1))
6. Write a program to determine whether a given string has balanced parenthesis or not.
def bp(st):
s1=[]
for s in st:
if s in ('(', '{', '['):
s1.append(s)
else:
if s1 and ((s1[-1] == '(' and s == ')') or(s1[-1] == '{' and s == '}') or
(s1[-1] == '[' and s == ']')):
s1.pop()
else:
return False
return not s1
st=input("Enter the expression ")
if bp(st):
print("Balanced parenthesis")
else:
print("Not balanced parenthesis")
7. Display Letters which are in the First String but not in the Second
s1= input("Enter string 1")
s2 = input("Enter string 2")
result=set(s1)-set(s2)
print(result)
dict={}
for i in range(len(list)):
dict[list[i]]=list1[i]
print("The dictionary formed is "+str(dict))
11. WAP to store students information like admission number, roll number, name and marks in a
dictionary and display information on the basis of admission number.
dict={}
for i in range(num_st):
print(f"\nEnter information for student {i+1} ")
adm_no=input("Admission number ")
roll_num=input("Roll number ")
name=input("Name ")
marks=input("Marks ")
12. Python Program to Find the Total Sum of a Nested List Using Recursion
def total_sum(nested_list):
total = 0
for item in nested_list:
if isinstance(item, list):
total += total_sum(item)
else:
total += item
13. Python Program to Read a String from the User and Append it into a File
with open("file.txt","a") as f1:
string = input("Enter a string to append to this file: ")
f1.write(string)
f1.write("\n")
print("String Appended to the file successfully")
16. Accept list and key as input and find the index of the key in the list using linear search
def ls(lst,key):
for i in range(len(lst)):
if lst[i]==key:
return i
return -1
if index != -1:
print(f"The key {key} is found at index {index}")
else:
print(f"The key {key} is not found")
def bs(lst):
n=len(lst)
for i in range(n):
for j in range(0,n-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
return lst