34.Example programs using Lists

Program to read list of names and sort the list in alphabetical order.( university question)
n=int(input("Enter the number of names...."))
names=[]
print("Enter {} names".format(n))
for i in range(n):
    nam=input()
    names.append(nam)
names.sort()
print("names in alphabetical order")
for nam in names:
    print(nam)

Program to find the sum of all even numbers in a group of n numbers entered by the user. (university question)
n=int(input("Enter the number of elements..."))
print("Enter the {} elements".format(n))
l=[] # creating an empty list
for i in range(n):
    x=int(input())
    l.append(x)
sum=0
for i in range(n):
    if l[i]%2==0:
        sum=sum+l[i]
print("Sum of all even numbers",sum)

Program to read a string and remove the given words from the string.
s=input("Enter the string....")
wr=input("Enter the word to remove....")
wrds=s.split(" ")
ns=""
for w in wrds:
    if w!=wr:
        ns=ns+" "+w
print("new string...",ns)
 
Find the average word length of a sentence ( university question)
sentence=input("Enter a sentence: ")
listOfWords=sentence.split()
print("There are", len(listOfWords), "words.")
sum=0
for word in listOfWords:
    sum += len(word)
print("The average word length is",sum/len(listOfWords))
 

Program to read list of numbers and find the median
#We can find median by sorting the list and then take the middle element. If the list contains even number of elements take the average of the two middle elements.
n=int(input("Enter how many numbers...."))
print("Enter {} numbers....".format(n))
lst=[]
for i in range(n):
   x=int(input())
   lst.append(x)
lst.sort()
print(lst)
mid=n//2
if n%2==1:
   print("Median",lst[mid])
else:
   print("Median",(lst[mid]+lst[mid-1])/2)

Finding the mode of list of numbers(A number that appears most often is the mode.)
l=[]
n=int(input("Enter n.."))
print("Enter the numbers..")
for i in range(n):
    x=int(input())
    l.append(x)
c=[]
e=[]
for x in l:
    if x not in e:
        c.append(l.count(x))
        e.append(x)
mc=max(c)
ne=len(c)
i=0
print("mode..")
while i<ne:
    if c[i]==mc:
        print(e[i])
    i+=1

Program to remove all duplicate elements from a list
lst=[]
n=int(input("enter how many numbers.."))
print("Enter elements...")
for i in range(n):
    x=int(input())
    lst.append(x)

nlst=[]
for x in lst:
    if x not in nlst:
        nlst.append(x)
print("new list after removing duplicates")
print(nlst)

Consider a list consisting of integers, floating point numbers and strings. Separate them into different lists depending on the data(university question)
il=[]
fl=[]
sl=[]
l=[12,23.5,'klf',34,4343,34.566,3+3j,'ddldl',35]
for i in l:
  if type(i)==int:
    il.append(i)
  if type(i)==str:
    sl.append(i)
  if type(i)==float:
    fl.append(i)
print("Integer list")
print(il)
print("Float list")
print(fl)
print("String List")
print(sl)

Write a Python program to read list of positive integers and separate the prime and composite numbers (university question)
def prime(n):
        flag=1
        for i in range(2,n//2+1):
                if n%i==0:
                        flag=0
                        break
        return flag    
pl=[]
cl=[]
l=[]
n=int(input("Enter n.."))
print("Enter the numbers..")
for i in range(n):
    x=int(input())
    l.append(x)
for i in l:
  if prime(i):
          pl.append(i)
  else:
          cl.append(i)
print("prime list")
print(pl)
print("composite list")
print(cl)  
Write a Python program to read a list of numbers and sort the list in a nondecreasing order without using any built in functions. Separate function should be written to sort the list wherein the name of the list is passed as the parameter
def sortlist(lst,n):
    for i in range(n-1):
        for j in range(i+1,n):
            if lst[i]>lst[j]:
                lst[i],lst[j]=lst[j],lst[i]
n=int(input("Enter how many numbers...."))
print("Enter {} numbers....".format(n))
lst=[]
for i in range(n):
    x=int(input())
    lst.append(x)
sortlist(lst,n)
print("sorted List is")
print(lst)

Check if the items in the list are sorted in ascending or descending order and print suitable messages accordingly. Otherwise, print “Items in list are not sorted” ( university question)

# initializing list
list = [ 5, 14, 11, 10]

# printing original list
print ("Original list : " + str(list))

# using sort() to
# check sorted list
flag1 = 0
flag2 = 0
list1 = list[:]
list2=list[:]
list1.sort()
list2.sort(reverse=True)
print(list1)
print(list2)
if (list1 == list):
flag1 = 1
if(list2 == list):
   flag2=1 
# printing result
if (flag1) :
print ("Yes, List is sorted in Asceding order.")
elif(flag2) :
    print ("Yes, List is sorted in Desceding order.")
else:
print ("No, List is not sorted.")
 
Write a python code to input n numbers and calculate sum of cubes of each number and store it in a list.( university question)

n=int(input("Enter the number of elements..."))
print("Enter the {} elements".format(n))
l=[] # creating an empty list
for i in range(n):
    x=int(input())
    l.append(x)
sum=0
for i in range(n):
    sum=sum+l[i]**3
print("Sum of cubes of  numbers",sum)

Write a Python program to check whether a list contains a sublist.(University Question)
Eg. Input 1: my_list = [3,4,5,2,7,8] , sub_list = [2,7]
output 1: True
input 2: my_list = [3,4,5,2,7,8] , sub_list = [5,7]
output 2: False

print('enter size of my_list')
n1=int(input())
print('Enter my_list')
my_list=[int(input()) for i in range(n1) ]

print('enter size of sub_list')
n2=int(input())
print('Enter sublist_list')
sub_list=[int(input()) for i in range(n2) ]

flag=0
for i in range(n1+1):
    if my_list[i:i+n2]==sub_list:
        flag=1
        break
if flag:
    print("Sublist TRUE")
else:
    print("Sublist FALSE")

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020

46.Classes and Objects in Python- Accessors and mutators