• Click below to download Unit 2 programs in pdf file: -



Unit 2


# 1. Write a program to create one array from another array.


from array import *

array1 = array('d',[1,2,3,4,5,6,7,8,9,0])

print("Elements are")

print(array1)

print("Length of array")

print(len(array1))

array2 = array(array1.typecode,(a for a in array1))

print("array2")

for i in array2:

    print(i)

#2nd Method

"""for i in array1:

    array2.append(i)

    print(i)"""



""" 2. Create a program to retrieve, display and update only a

range of elements from an array using indexing and

slicing in arrays. """


from array import *

arr1=array('b',[10,20,30,40,50,60,70,80,90,100,110])

print("MENU")

print("1:Slice 3rd element of the array")

print("2:Slice  element 3,4,5 of the array")

print("3:Slice element from the middle of the array to the last element")

print("4:Slice print elements even position")

print("5:Slice print elements even array")


ch=int(input("Enter your choice :"))

print(arr1)

if ch==1:

    print(arr1[2:3])

elif ch==2:

    print(arr1[2:5])

elif ch==3:

    print(int(len(arr1)/2))

    print(arr1[int(len(arr1)/2):])

elif ch==4:

    for i in range(len (arr1)):

        if((i+1)%2==0):

            print(arr1[i])

elif ch==5:

    for i in range(len(arr1[i])):

        if((i+1)%2==0):

            print(arr1[i])

    

else:

    print("Invalid choice")



""" 3. Write a program to understand various methods of array

class mentioned: append, insert, remove, pop, index,

to list and count. """

from array import*

ar1=array('d',[10,20,30,40,50,60])

print("original arrayis:",ar1)


ar1.append(-2100)

print("after append")

print(ar1)


ar1.insert(1,199)

print("after insert",ar1)


ar1.remove(-2100)

print("after removing",ar1)


ar1.pop()

print("after pop function",ar1)


n=ar1.index(30)

print("first occurrence of element 30 at:",n)


n=ar1.tolist()

print("list:",n)

print("Array:",ar1)



# 4. Write a program to sort the array elements using bubble sort technique.


from array import*

array1=array('i',[])

n=int(input("how many elements ?"))

for i in range(n):

    a=int(input("enter element"))

    array1.append(a)


for i in range(n):

          print(array1[i])

for i in range(n):

    for j in range(i+1):

        if array1[i]<array[j]:

            Temp=array1[j]

            array1[j]=array1[i]

            array1[i]=temp


print("after sorting the array")

for i in range(n):

          print(array1[i])



""" 5. Create a program to search the position of an element in

an array using index() method of array class. """


from array import*

x=array('i',[])

print("how many value in array")

n=(int(input()))

for i in range(n):

    x.append(int(input("enter element")))


print("array entered")

print(x)


print("enter value to search")

s=int(input())


try:

    pos=x.index(s)

    print("found at position:",pos+1)

except ValueError:

    print("search element ",s,"not found")



""" 6. Write a program to generate prime numbers with the

help of a function to test prime or not. """


def prime(n):

    flag=0

    for i in range(2,n):

        if(n%i ==0):

            flag=1

            break

        return flag

n=int(input("enter number"))

ans=prime(n)

if(ans==1):

    print("number",n,"is not prime")

else:

    print("number",n,"is prime")



""" 7. Write a python program that removes any repeated items

from a list so that each item appears at most once. For

instance, the list [1,1,2,3,4,3,0,0] would become

[1,2,3,4,0]. """


#this removes repeated element in the list

list=[10,1,2,3,4,5,1,2,20,10,100]

new=[]

for i in list:

    if i not in new:

        new.append(i)


print("Original list",list)

print("the list after removing duplicate element",new)



""" 8. Write a program to pass a list to a function and display

it. """


def fun (list1):

    for i in list1:

        print(i)


list=[1,2,3,4,5]

fun(list)



""" 9. Write a program to demonstrate the use of Positional

argument, keyword argument and default arguments. """


print("Example of positional argument")

def com(s1,s2):

    s3=s1+s2

    print("total string=",s3)

com("Michigan","University")


print("example of keyword argument")

def grocery(item,price,location):

    print("Item:",item)

    print("Price:",price)

    print("Location:",location)


grocery(item="Amul butter",price="50",location="refrigerator")

grocery(item="Baadshah Masala",price="150",location="2nd shelf")



print("Example of default argument")

def grocery(item,price=99.99):

    print("item:",item)

    print("price:",price)


grocery(item="sugar")

grocery(item="butter",price=50)



""" 10. Write a program to show variable length argument and

its use. """


def add(farg,*args):

    print("Formal argument",farg)

    sum=0

    for i in args:

        print(i)

        sum+=i

        print("sum of all numbers is",(farg+sum))


add(5,10)

add(5,10,15)

add(10,5,15,100)



"""11. Write a lambda/Anonymous function to find bigger

number in two given numbers. """


f=lambda x,y:x if x>y else y

x,y=[int(n)for n in input ("Enter two number:").split(',')]

print("larger number is ",f(x,y))

value=f(5,19)

print("max value is=",value)



""" 12. Create a decorator function to increase the value of a

function by 3."""


def decor(fun):

    def inner():

        value=fun()

        return value +10

    return inner

def num():

    return 100

result_fun=decor(num)

print("Increase the value by using decor function",result_fun())



""" 13. Create a program name “employee.py” and implement

the functions DA, HRA, PF, and ITAX. Create another

program that uses the function of employee module and

calculates gross and net salaries of an employee."""


from calc import*

basic=float(input("entr basic salary of employee:"))

gross=basic+da(basic)+hra(basic)

print("gross salary is{:10.2f}".format(gross))

net=gross-pf(basic)-it(gross)

print("net salary is{10.2f}",net)



#Save below code with 'calc' file name in same folder


def da(basic):

    da=1.2*basic

    print("DA is ...",da)

    return da

def hra(basic):

    hra=0.2*basic

    print("HRA is ...",hra)

    return hra

def pf(basic):

    pf=0.8*basic

    print("PF is ...",pf)

    return pf

def it(gross):

    it=gross*0.1

    print("IT is ...",it)

    return it



""" 14. Write a program to create a list using range functions

and perform append, update and delete elements

operations in it."""


lst=list(range(5,10))

print(lst)

lst.append(10)

print("after update at index position 2:",lst)



""" 15. Write a program to combine two List, perform repetition

of lists and create cloning of lists."""


x=[10,20,30,40,50]

y=[100,200,300,400,500]

x1=x[:]

print("x1:",x1)

y1=y[:]

y1[0]=0

print("y1:",y1)

z=x+y

print("Combined list z is x+y:",z)

z1=x1+y1

print("Combined list z1 is x1+y1:",z1)


""" 16. Create a sample list of 7 elements and implement the

List methods mentioned: append, insert, copy, extend,

count, remove, pop, sort, reverse and clear. """


list=[10,20,30,40,50,60,70,80]

print("original list:LIST",list)

list1=[]

list.append(70)

print("After appending",list)

list.insert(0,0)

print("insert number value at 0 position",list)

list1=list.copy()

print("After copy list to list 1:",list1)

list.extend(list1)

print("After extending list1 to list",list)

n=list.count(50)

list.remove(80)

print("list after removing 80",list1)

list1.pop()

print("After removing last element",list1)

list.sort()

print("list after sorting...",list)

list1.clear()

print("list 1 after clear:list2",list1)




""" 17. Write a program to create nested list and display its

elements."""


list1=[10,20,30,40,50,60,[70,80,90,100]]

print("list is",list1)

print("first element is ",list1[0])

print("last element is",list1[6])


for i in list1[6]:

    print(i)



""" 18. Write a program to accept elements in the form of a tuple

and display its minimum, maximum, sum and average """


num=eval(input("enter element  in():"))

sum=0

n=len(num)

for i in range(n):

    sum=sum+num[i]

print("sum of number is:",sum)

print("average of number :",sum/n)

print("maximum of number :",max(num))

print("minimum  nu ber is ",min(num))



# 19. Create a program to sort tuple with nested tuples.


tuple=((10,"A",20000),(20,"c",100000),(-30,"B",40000),(40,"D",30000))

print(sorted(tuple))

print("Reverse  the tuple")

print(sorted(tuple,reverse=True))

print()

print("sorted by index 1: name display")

print(sorted(tuple,key=lambda x:x[1]))

print()

print("soretd by index 2:salary display")

print(sorted(tuple,key=lambda x:x[2]))

print()



""" 20. Write a program to create a dictionary from the user and

display the elements. """


dict={}

n=int(input("How many element in dictionary:"))

for i in range(n):

    print("enter the name:",end="")

    k=input()

    print("enter value:",end="")

    v=int(input())

    dict.update({k:v})

print("the dictionary is",dict)



""" 21. Create a dictionary that will accept cricket players name

and scores in a match. Also we are retrieving runs by

entering the player’s name. """


dict={}

n=int(input("how many player in dictionary:"))

for i in range(n):

    print("enter player name:",end='')

    k=input()

    print("enter score value:",end='')

    v=int(input())

    dict.update({k:v})

print("player in this match are:")

for pname in dict.keys():

    print(pname)

print("enter a player name to search ",end='')

name=input()

runs=dict.get(name,-1)

if(runs==-1):

    print("player not found")

else:

    print("{}made {} runs".format(name,runs))



""" 22. Write a program to convert the elements of two lists into

key-value pairs of a dictionary """


con=["Gujarat","Mumbai","Delhi"]

cap=["Gandhinagar","Pune","Guwahati"]

z=zip(con,cap)

d=dict(z)

print('{:15s}--{:15s}'.format('country','capital'))

for k in d:

    print('{:15s}--{:15s}'.format(k,d[k]))



""" 23. Create a python function to accept python function as a

dictionary and display its elements. """


def fun(dictionary):

    for i,j in dictionary.items():

        print(i,'--',j)

d={'A':'Apple','B':'Book','c':'cat'}

fun(d)