Python Tutorial: List Related Program

Friday, 31 July 2020

List Related Program


List Program

Q1. Write a program to create a listA a containg positive and negative from the console. Also create two separate list called PosNum and NegNum to store positive and negative numbers respectively. Also, Calculate and print the total of all positive and negative numbers.
Source Code:
ListA=[]
n=int(input("How many number do you want :"))
i=0
if(n>0):
    print("Enter positve and negative numbers ")
    for i in range(n):
        print("Enter number %d:"%(i+1), end="")
        Num=int(input())
        ListA.append(Num)
    PosNum=[]
    NegNum=[]
    print("ListA", ListA)
    for i in range(len(ListA)):
        if(ListA[i]>0):
            PosNum.append(ListA[i])
        else:
            NegNum.append(ListA[i])
    print("The +ve number list is :", PosNum)
    print("The -ve number list is :", NegNum)
    SPos=SNeg=0
    for i in range(0,len(PosNum)):
        SPos=SPos+PosNum[i]
    for i in range(0,len(NegNum)):
        SNeg=SNeg+NegNum[i]
    print("Sum of +ve number :",SPos)
    print("Sum of -ve number: ",SNeg)

Q2. How many times repeat search value is a list.
Source Code
aList=eval(input("Enter the value of list :"))
Search=int(input("Enter the value to be search :"))
length=len(aList)
pos=0
for i in range(length):
    if(Search==aList[i]):
        pos=pos+1
print(Search,' repeates ',pos,' times.'  )
     
       
Q3.  Write a program to shift the first element to the last position.
Answer:
aList=eval(input("Enter the value of list :"))
print("Original List ->",aList)
length=len(aList)
N=1
if(length>0):
    P=aList[0]
    for i in range(0,N):
        aList[i]=aList[i+1]
    aList[length-1]=P
for i in range(length):
        print(aList[i],end="\t")

Q4. Write a program to delete all duplicate elements in a list.

For example : [54,32,65,-54,76,43,54,32]

Then after deleting the duplicate elements, the new list will be :

[-54,32,43,54,65,76]

Answer :

aList=eval(input("Enter a list in [] :"))

if (aList):

    print("Original List :",aList)

    aList.sort() # use sort function for reording

    last=aList[-1]

    for i in range(len(aList)-2,-1,-1):

        if (last==aList[i]):

            del aList[i]

        else:

            last=aList[i]

    print("Now after deleting duplicates list :", aList)

       

    

Q5. Write a program to find all duplicate elements in a list. For example, if the elements of a list aList is : [54, 32, 65, -54, 76, 43, 54, 32, -54, 32, 54]

Then it will print as :

The duplicate elements are [-54, 32, 32, 54, 54]

Answer :

aList=eval(input("Enter a list in [] :"))

aDlist=[]# store duplicate value

print("Original List :",aList)

aList.sort() # use sort function

last=aList[-1]

for i in range(len(aList)-2,-1,-1):

    if (last==aList[i]):

        aDlist.append(aList[i])#store duplicate value

        aDlist.sort()

        del aList[i]

    else:

        last=aList[i]

print("Duplicate value in a list ",aDlist)

print("Now after deleting duplicates list :", aList)

Q6. Write a program which accepts an integer list and exchanges the values of first half side elements with the second half side elements of the list :

Example : if a list of eight elements has initial content as

                [21,32,34,98,7,54,23,25]

                The program should rearrange the array as

                [7,54,23,25,21,32,34,98]

 Answer :

aList=eval(input("Enter a list in [] :"))

print("Original List :",aList)

length=len(aList)

hLen=length//2 # calculate half length

for i in range(hLen):

    temp=aList[i]

    aList[i]=aList[hLen+i]

    aList[hLen+i]=temp

print("The exchange elements are ",aList)

Q7. Given an array named AList with the following elements

[2, 3, 4, -5, 6, -8, 11, -9]

Write a python program to shift the negative to left and the positive numbers to right so that the resultant list will look like :

[-5, -8, -9, 2, 3, 4, 6, 11]

Answer :

aList=eval(input("Enter a list in [] :"))

print("Original List :",aList)

i=j=0

ln=len(aList)

for i in range(ln):

    j=i

    if(aList[i]<0):

        temp=aList[i] #store list element in temp variable

        for j in range(i,-1,-1):

            aList[j]=aList[j-1]

            if(aList[j]<0):

                break

        aList[j]=temp

print("After shifting ",aList)


Q8. Write a python program to find frequencies of all elements of a list. Also, print the list of unique elements in the list and duplicate elements in the given list.

Answer :

aList=eval(input("Enter a list in [] :"))

print("Original List ->", aList)

ln=len(aList)

uniq=[]

dupl=[]

count=i=0

for i in range(ln):

    value=aList[i]

    count=1

    if value not in uniq and value not in dupl:

        i=i+1

        for j in range(i,ln):

            if (value==aList[j]):

                count+=1

        else:

            print("Element ", value,"frequency", count)

            if(count==1):

                uniq.append(value)

            else:

                dupl.append(value)

else:

        i=i+1

print("Unique elements list-> ",uniq)

print("Duplicates elements-> ",dupl)

Q9. Write python program to find minimum element from a list of element along with its index in the list.

Answer :

aList=eval(input("Enter a list in [] :"))

print("Original List ->", aList)

ln=len(aList)

min_value=aList[0]

min_index=0

for i in range(0,ln-1,1):

    if (aList[i]<min_value):

        min_value=aList[i]

        min_index=i

print("Minimum value is ->",min_value," at index ",min_index)

    Q10. Write a Python program to count frequency of a given element in a list of numbers.

Answer:

aList=eval(input("Enter a list in [] :"))

print("Original List ->", aList)

ln=len(aList)

find=int(input("Enter element ->"))

count=0

for i in range(0,ln-1):

    if (find==aList[i]):

        count+=1

if (count==0):

    print(find, " not found in given list")

else:

    print(find ," has frequency as" ,count,", in given list")    

Q11. Write a python program to calculate average/mean of given list.

Answer:

aList=eval(input("Enter a list in [] :"))

print("Original List ->", aList)

ln=len(aList)

sum1=ag=0

for i in range(ln):

    sum1=sum1+aList[i]

avg=sum1/ln

print("The average/mean of the given list -> ",avg)     


Q4. Write a menu driven program to perform the following operations on a list/array.
1.   Add/append element into list
2.   Delete element from list
A.   Delete at beginning
B.   Delete at end
C.   Delete at position
D.  Delete by value
E.   Exit
3.   Show the elements
4.   Quit

Source Code :
Num=[] #empty list/array
opt=0
while(True):
    print()
    print('MAIN MENU')
    print('------------')
    print("1. Add/Append element into list")
    print("2. Delete elements from list")
    print("3. Show list element")
    print("4. Quit")
    print("-----------")
    opt=int(input("Enter your option "))
    print()
    if(opt==1):
        ctr=1
        ch='Y'
        while(ch=='Y' or ch=='y'):
            print("Enter number  ", ctr,": ", end='')
            val=int(input())
            Num.append(val) #adding list
            ch=input("Do you want to add more record (Y/N)...").upper()
            ctr+=1
            if(ch=='N' or ch=='n'):
                break
    elif(opt==2):
        ch=''
        print("A. Delete at beginning")
        print("B. Delete at end")
        print("C. Delete at position")
        print("D. Delete by value")
        print("E. Exit")
        print("-----------")
        ch=input("Enter your choice :").upper()
        if(ch=='A'):
            if(len(Num)>=1):
                val=Num.pop(0) # delete first element
                print(val, "deleted element from the list")
            else:
                print('List is empty')
        elif(ch=='B'):
             if(len(Num)>=1):
                 length=len(Num)
                 val=Num.pop() # delete last element
                 print(val, "deleted element from the list")
             else:
                print('List is empty')
        elif(ch=='C'):
             length=len(Num)
             if(len(Num)>=1):
                 pos=int(input("Enter the index postion to delete"))
                 if(pos>=0 and pos<length):
                      val=Num.pop(pos) 
                      print(val, "deleted element from the list")
                 else:
                    print("Postion out of range")
             else:
                  print('List is empty')
        elif(ch=='D'):
            if(len(Num)>=1):
                val=int(input("enter the number which will be delete :"))
                flag=0
                for i in range(len(Num)):
                    if(Num[i]==val):
                        del(Num[i])
                        flag=1
                        break
                if(flag==0):
                    print("element does not found in list")
                else:
                    print('Sucessfully delete')
            else:
                print("Empty list")
        else:
            print("Wrong option, try again")
    elif(opt==3):
        print("Show list")
        for i in range(0,len(Num)):
            print(Num[i],end=" ")
    elif(opt==4):
        break
    else:
        print('Wrong option, try again')
        




  
  

1 comment: