Python Tutorial: CS-Python Functions Exercises2

Sunday, 28 April 2024

CS-Python Functions Exercises2

Q1. Vivek has written a code to input a number and check whether it is even or odd number. His code is having errors. Rewrite the correct code and underline the corrections made.

Def checkNumber(N):

status = N%2

return

#main-code

num=int( input(“ Enter a number to check :))

k=checkNumber(num)

if k = 0:

print(“This is EVEN number”)

else:

print(“This is ODD number”)

Ans:

Incorrect Code

Incorrect Code

Def checkNumber(N):

status = N%2

return

#main-code

num=int( input(“ Enter a number to check :))

k=checkNumber(num)

if k = 0:

print(“This is EVEN number”)

else:

print(“This is ODD number”)

def checkNumber(N):

status = N%2

return

#main-code

num=int( input(“ Enter a number to check :”))

k=checkNumber(num)

if k = = 0:

print(“This is EVEN number”)

else:

print(“This is ODD number”)

 

 

Q2. Sameer has written a python function to compute the reverse of a number. He has however committed a few errors in his code. Rewrite the code after removing errors also underline the corrections made.

define reverse(num):

    REV=0

While num > 0:

rem == num %10

rev = rev*10 + rem

        Num=NUM//10         

return rev

 

print(reverse(1234))

Ans:

Incorrect Code

Correct Code

define reverse(num):

    REV=0

While num > 0:

rem == num %10

rev = rev*10 + rem

        Num=NUM//10         

return rev

 

print(reverse(1234))

 

def reverse(num):

    rev=rem=0

    while num > 0:

          rem = num%10

          rev = rev*10 + rem

          num=num//10

    return rev

 

print(reverse(1234))

 

Q3. Rewrite the following code in python after removing all syntax error(s). Underline each correction done in the code.

Num=int(rawinput("Number:"))

sum=0

for i in range(10,Num,3)

sum+=1

if i%2=0:

                        print(i*2)

            else:    

                        print(i*3)

 print (Sum)

Ans:

Incorrect Code

Correct Code

Num=int(rawinput("Number:"))

sum=0

for i in range(10,Num,3)

sum+=1

if i%2=0:

                 print(i*2)

     else:

                 print(i*3)

 print (Sum)

 

Num=int(input("Number:"))

sum=0

for i in range(10,Num,3) :

      sum+=1

      if i%2==0:

            print(i*2)

      else:

            print(i*3)

print(sum)

 

Q4. Observe the following Python code very carefully and rewrite it after removing all syntactical errors with each correction underlined.

DEF execmain():

x = input("Enter a number:")

if (abs(x)== x)

print("You entered a positive number")

 else:

            print("Number made positive:" x )

Ans:

Incorrect Code

Correct Code

DEF execmain():

x = input("Enter a number:")

if (abs(x)== x)

print("You entered a positive number")

 else:

    print("Number made positive:" x )

 

def execmain():

      x = int(input("Enter a number:"))

      if (abs(x)== x):

            print("You entered a positive number")

      else:

            print("Number made positive:" ,x )

execmain()

 

Q5. Rewrite the following code in python after removing all syntax error(s). Underline each correction done in the code.

30=Value

for VAL in range(0,Value)

If val%4==0:

print (VAL*4)

Elseif val%5==0:

print (VAL+3)

else

print(VAL+10)

Ans:

Incorrect Code

Correct Code

30=Value

for VAL in range(0,Value)

If val%4==0:

print (VAL*4)

Elseif val%5==0:

print (VAL+3)

else

print(VAL+10)

Value=30

for val in range(0,Value):

      if val%4==0:

            print (val*4)

      elif val%5==0:

            print (val+3)

      else:

            print(val+10)

Q6. Ravi has written a function to print Fibonacci series for first 10 elements. His code is having errors. Rewrite the correct code and underline the corrections made. some initial elements of Fibonacci series are:

def fibonacci()

    first=0,second=1

    print(("first no. is ", first)

    print("second no. is , second)

    for a in range (1,9):

          third=first+second

          print(third)

          first,second=second,third

fibonacci()

Incorrect Code

Correct Code

def fibonacci()

    first=0,second=1

    print(("first no. is ", first)

    print("second no. is , second)

    for a in range (1,9):

          third=first+second

          print(third)

          first,second=second,third

fibonacci()

 

def fibonacci():

    first=0;second=1

    print("first no. is ", first)

    print("second no. is ", second)

    for a in range (1,9):

          third=first+second

          print(third)

          first,second=second,third

fibonacci()

 

Q7. Aarti has written a code to input an integer and check whether it is even or odd. The code has errors. Rewrite the code after removing all the syntactical errors, underlining each correction:

checkval def():

    x = input("Enter a number")

    if x % 2 == 0

        print (x, "is even")

    else;

        print (x, "is odd")

Ans:

Incorrect Code

Correct Code

checkval def():

    x = input("Enter a number")

    if x % 2 == 0

        print (x, "is even")

    else;

        print (x, "is odd")

 

def checkval():

    x = int(input("Enter a number"))

    if x % 2 == 0:

        print (x, "is even")

    else:

        print (x, "is odd")

checkval()

 

Q8. Mithilesh has written a code to input a number and evaluate its factorial and then finally print the result in the format : “The factorial of the <number> is <factorial value>” His code is having errors. Rewrite the correct code and underline the corrections made.

f = 0

num = input("Enter a number whose factorial you want to evaluate :")

n = num

while num > 1:

f = f * num

num -= 1

else:

print("The factorial of : ", n , "is" , f)

Incorrect Code

Correct Code

f = 0

num = input("Enter a number whose factorial you want to evaluate :")

n = num

while num > 1:

f = f * num

num -= 1

else:

print("The factorial of : ", n , "is" , f)

 

f = 1

num = int(input("Enter a number whose factorial you want to evaluate :"))

n = num

while num > 1:

      f = f * num

      num -= 1

else:

      print("The factorial of : ", n , "is" , f)

 

Q9. Find error in the following code(if any) and correct code by rewriting code and  underline the

correction;

Def Errors()

x= int(“Enter value of x:”)

for in range [0,10]:

if x=y              

print( x + y)

else:

print( xy)

Incorrect Code

Correct Code

Def Errors()

x= int(“Enter value of x:”)

for in range [0,10]:

if x=y

print( x + y)

else:

print( xy)

 

def Errors():

      x= int(input("Enter value of x:"))

      for y in range (0,10):

            if x==y:

                  print( x + y)

            else:

                  print(x-y)

 

Q10. Mohini has written a code to input a positive integer and display all its even factors in descending order. Her code is having errors. Rewrite the correct code and underline the corrections made.

n=input("Enter a positive integer: ")

for i in range(n):

if i%2:

if n%i==0:

print(i,end=' ')

Incorrect Code

Correct Code

Def code()

n=input("Enter a positive integer: ")

for i in range(n):

if i%2:

if n%i==0:

print(i,end=' ')

define code()

def code():

      n=int(input("Enter a positive integer: ") )

      for i in range(n):

            if i%2:

                  if n%i==0:

                        print(i,end=' ')

code()

 

Q11.  Write the output of the following code:

def printMe(q,r=2):

    p=r+q**3

    print(p)

#main-code

a=10

b=5

printMe(a,b)

printMe(r=4,q=2)

Output: 1005

              12

def show():

data = [1,2,4,5]

for x in data:

x = x + 10

print(data)

show()

Output: [1, 2, 4, 5]

 

def foo(s1,s2):

l1=[]

l2=[]

for x in s1:

l1.append(x)

for x in s2:

l2.append(x)

return l1,l2

a,b=foo("FUN",'DAY')

print(a,b)

Output: ['F', 'U', 'N'] ['D', 'A', 'Y']

def sumList():

    data = [2,4,2,1,2,1,3,3,4,4]

    d = {}

    for x in data:

        if x in d:

            d[x]=d[x]+1

        else:

            d[x]=1

    print(d)

sumList()

Output: {2: 3, 4: 3, 1: 2, 3: 2}

def convert(s):

    n = len(s)

    m=""

    for i in range(0, n):

        if (s[i] >= 'a' and s[i] <= 'm'):

            m = m +s[i].upper()

        elif (s[i] >= 'n' and s[i] <= 'z'):

            m = m +s[i-1]

        elif (s[i].isupper()):

            m = m +s[i-1]

        elif (s[i].isupper()):

            m=m+s[i].lower()

        else:

            m=m+'#'

    print(m)

s="welcome2dis"

convert(s)

Output: sELCcME#DIi

st = "python programming"

def countShow(st):   

    count = 4

    while True:

        if st[0]== "p":

            st = st[2:]

        elif st[-2]=="n":

            st = st[:4]

        else:

            count+=1

            break

    print(st)

    print(count)

 

countShow(st)

Output: thon

              5

def output(myvalue):

    alpha = 0

    beta = ""

    gama = 0

    for i in range(1,6,2):

        alpha += i

        beta += myvalue[i-1]+ "#"

        gama += myvalue[i]

    print(alpha, beta, gama)

 

myvalue = ["A", 40, "B", 60, "C", 20]

output(myvalue)

 

 

Output: 9 A#B#C# 120

def convert(line):

    n = len(line)

    new_line = ''

    for i in range(0,n):

        if not line[i].isalpha():

            new_line = new_line + '@'

        else:

            if line[i].isupper():

                new_line = new_line + line[i]*2

            else:

                new_line = new_line + line[i]

    return new_line

 

new_line = convert("Be 180 HuMan")

print(new_line)

Output : BBe@@@@@HHuMMan

def Change(P ,Q=30):

    P=P+Q

    Q=P-Q

    print(P,"#",Q)

    return(P)

R=150

S=100

R=Change(R,S)

print(R,"#",S)

S=Change(S)

Output: 250 # 150

             250 # 100

             130 # 100

def newTuple(tuple1):

    list1 =list(tuple1)

    new_list = []

    for i in list1:

        if i%2==0:

            new_list.append(i)

    new_tuple = tuple(new_list)

    print(new_tuple)

 

tuple1 = (11, 22, 33, 44, 55 ,66)

newTuple(tuple1)

 

Output: (22, 44, 66)

def ChangeVal(M,N):

      for i in range(N):

            if M[i]%5 == 0:

                M[i]//=5

            if M[i]%3 == 0:

                M[i]//=3

L= [25,8,75,12]

ChangeVal(L,4)

for i in L:

    print(i,end="#")

 

Output: 5#8#5#4#

def Call(P=40,Q=20):

    P=P+Q

    Q=P-Q

    print(P,'@',Q)

    return P

R=200

S=100

R=Call(R,S)

print(R,'@',S)

S=Call(S)

print(R,'@',S)

Output: 300 @ 200

             300 @ 100

             120 @ 100

             300 @ 120

def Alpha(N1):

    while N1:

        a=N1.pop()

        if a%5>2:

            print(a,end='@')

        else:

            break

NUM=[13,24,12,53,34]

Alpha(NUM);print(NUM)

 

 

Output : 34@53@[13, 24]

T1 = tuple("Amsterdam")

 

def vowel(T1):   

    T2, new_list = T1[1:-1], []

    for i in T2:

        if i in 'aeiou':

            j=T1.index(i)

            new_list+=[j]

    print(new_list)

 

vowel(T1)

Output : [4, 7]

T = (9,18,27,36,45,54)

def User_func(T):

    L=list(T)

    L1 = []

    for i in L:

        if i%6==0:

            L1.append(i)

    T1 = tuple(L1)

    print(T1)

 

User_func(T)

Output: (18, 36, 54)

L=[4,6,7,1,6,9,4]

def fun(L):

    for i in range(len(L)):

        if(L[i]%3==0 and L[i]%2==0):

            L[i]=L[i]+1

   

    return(L)

print("Original List : ", L)

k=fun(L)

print("Now New List : ",k)

 

Output: Original List :  [4, 6, 7, 1, 6, 9, 4]

                 Now New List :  [4, 7, 7, 1, 7, 9, 4]

def Convert(s):   

    n = len(s)

    m=""

    for i in range(0, n):

        if (s[i] >= 'a' and s[i] <= 'm'):

            m = m +s[i].upper()

        elif (s[i] >= 'n' and s[i] <= 'z'):

            m = m +s[i-1]

        elif (s[i].isupper()):

            m=m+s[i].lower()

        else:

            m=m+'&'

    print(m)

 

s="Hello2everyone"

Convert(s)

Output: hELLl&EeEeryoE

def Display(str):

    m=""

    for i in range(0,len(str)):

        if(str[i].isupper()):

            m=m+str[i].lower()

        elif str[i].islower():

            m=m+str[i].upper()

        else:

            if i%2==0:

                m=m+str[i-1]

            else:

                m=m+"#"

    print(m)

Display('Fun@World2.0')

 

 

Output : fUN#wORLD#2#

x="hello world"

def Testy(x):

    print(x[:2],x[:-2],x[-2:])

    print(x[6],x[2:4])

    print(x[2:-3],x[-4:-2])

Testy(x)

 

 

 

 

 

Output: he hello wor ld

             w ll

             llo wo or

def encrypt(s):

    k=len(s)

    m=""

    for i in range(0,k):

        if(s[i].isupper( )):

            m=m+str(i)

        elif s[i].islower( ):

            m=m+s[i].upper()

        else:

            m=m+'*'

        print(m)

encrypt('DooN@Kanpur')

Output:

0

0O

0OO

0OO3

0OO3*

0OO3*5

0OO3*5A

0OO3*5AN

0OO3*5ANP

0OO3*5ANPU

0OO3*5ANPUR

def Change(P ,Q=10):

    P=P*Q

    Q=Q+P

    print( P,"#",Q)

    return (Q)

A=5

B=10

A=Change(A)

B=Change(A,B)

print(A,"#",B)

 

Output: 50 # 60

             600 # 610

             60 # 610

value = 50

def display(N):

    global value

    value = 25

    if N%7==0:

        value = value + N

    else:

        value = value - N

 

print(value, end="#")

display(20)

print(value)

 

Output: 50#5

a=20

def call():

    global a

    b=20

    a=a+b

    return a

print(a)

call()

print(a)

Output: 20

             40

x = 50

def func():

    global x

    print('x is', x)

    x = 20

    print('Changed global+local x to', x)

func()

 

 

Output: x is 50

             Changed global+local x to 20

def convert(Old):

    l=len(Old)

    New=""

    for i in range(0,l):

        if Old[i].isupper():

            New=New+Old[i].lower()

        elif Old[i].islower():

            New=New+Old[i].upper()

        elif Old[i].isdigit():

            New=New+"*"

        else:

            New=New+"%"

    return New

Older="InDIa@2022"

Newer=convert(Older)

print("New String is: ", Newer)

Output: New String is:  iNdiA%****

def Compy(N1,N2=10):

    return N1 > N2

NUM= [10,23,14,54,32]

for VAR in range (4,0,-1):

    A=NUM[VAR]

    B=NUM[VAR-1]

    if VAR > len(NUM)//2:

        print(Compy(A,B),'#', end=' ')

    else:

        print(Compy(B),'%',end=' ')

 

 

 

 

 

 

Output: False # True # True % False %

tuple1 = ( [7,6],[4,4],[5,9],[3,4],[5,5], [6,2] , [8,4])

 

def newValue(tuple1):

    listy = list( tuple1)

    new_list = list()

    for elem in listy :

        tot = 0

        for value in elem:

            tot += value

            if elem.count(value) == 2:

                new_list.append(value)

                tot = 0

    else:

        print( tuple(new_list) )

newValue(tuple1)

Output: (4, 4, 5, 5)

string="aabbcc"

count=3

def fun(string):

    count=3

    while True:

        if string[0]=='a':

            string=string[2:]

        elif string[-1]=='b':

            string=string[:2]

        else:

            count+=1

            break

    print(string)

    print(count)

fun(string)

Output: bbcc

             4

def Fruit(fruit_list1):

    fruit_list2 = fruit_list1

    fruit_list3 = fruit_list1[:]

    fruit_list2[0] = 'Guava'

    fruit_list3[1] = 'Kiwi'

    sum = 0

    for ls in (fruit_list1, fruit_list2, fruit_list3):

        if ls[0] == 'Guava':

            sum += 1

        if ls[1] == 'Kiwi':

            sum += 20

    print (sum)

   

fruit_list1 = ['Apple', 'Berry', 'Cherry', 'Papaya']

Fruit(fruit_list1)

Output: 22

my_dict = {}

my_dict[(1,2,4)] = 8

my_dict[(4,2,1)] = 10

my_dict[(1,2)] = 12

 

def Value(my_dict):

    sum = 0

    for k in my_dict:

        sum += my_dict[k]

    print (sum)

Value(my_dict)

print(my_dict)

 

 

Output: 30

             {(1, 2, 4): 8, (4, 2, 1): 10, (1, 2): 12}

def Alpha(N1,N2):

    if N1>N2:

        print(N1%N2)

    else:

          print(N2//N1,'#',end=' ')

NUM=[10,23,14,54,32]

for C in range (4,0,-1):

    A=NUM[C]

    B=NUM[C-1]

    Alpha(A,B)

 

Output: 1 # 12

             1 # 3

List1 = list("Examination")

List2 =List1[1:-1]

def newList(List2):

    new_list = []

    for i in List2:

        j=List2.index(i)

        if j%2==0:

            List1.remove(i)

    return(List1)

print(newList(List2))

 

 

Output: ['E', 'a', 'i', 'a', 'i', 'n']

p=8

def sum(q,r=5):

    global p

    p=(r+q)**2

    print(p, end= '#')

a=2; b=5; sum(b,a)

sum(r=3,q=2)

Output : 49#25#

s="3 & Four"

n = len(s)

def Convert(s,n):

    m=""

    for i in range(0, n):

        if (s[i] >= 'A' and s[i] <= 'Z'):

            m = m +s[i].upper()

        elif (s[i] >= 'a' and s[i] <= 'z'):

            m = m +s[i-1]

        if (s[i].isdigit()):

                m = m + s[i].lower()

        else:   m = m +'-'

    return m

s=Convert(s,n)

print(s)

Output: 3---F-F-o-u-

def multiply(number1, number2) :

    answer = number1 * number2

    return(answer)

    print(number1, 'times', number2, '=', answer)

output = multiply(5, 5)

print(output)

 

Output : 25

def addEm(x,y,z):

      return(x+y+2)

def prod(x,y,z):

      return x*y*z

a= addEm(6,16,26)

b= prod(2,3,6)

print(a,b)

Output :24 36

 

Q12. Write a function modilst(L) that accepts a list of numbers as argument and increases the value of the elements by 10 if the elements are divisible by 5. Also write a proper call statement for the function.

For example:

If list L contains [3,5,10,12,15]

Then the modilist() should make the list L as [3,15,20,12,25]

Ans:

def modilst(L):

      for i in range(len(L)):

            if L[i] % 5 == 0:

                  L[i]+=10

L = [12,10,15,20,25]

modilst(L)

print(L)

 

Q13. Write a function lenFOURword(L), where L is the list of elements (list of words) passed as argument to the function. The function returns another list named ‘indexList’ that stores the indices of all four lettered word

of L.

For example:

If L contains [“DINESH”, “RAMESH”, “AMAN”, “SURESH”, “KARN”]

The indexList will have [2, 4]

Ans:

def lenFOURword(L):

      indexList=[]

      for i in range(len(L)):

            if len(L[i])==4:

                  indexList.append(i)

      return indexList

L=["DINESH", "RAMESH", "AMAN", "SURESH", "KARN"]

print(lenFOURword(L))

 

Q14. Write a python function displaywords() that will print all the words that are having length greater than 3.

Example:

For the fie content:

A man always wants to strive higher in his life. He wants to be perfect.

The output after executing displayword() will be:

Always wants strive higher life wants perfect

Ans:

strings='A man always wants to strive higher in his life. He wants to be perfect.'

def displayword(strings):     

      words=strings.split()

      for i in words:

            if len(i)>3:

                  print(i,end=' ')

displayword(strings)

Q15. Write a python function countvowel() that reads the contents of the string and counts the occurrence of vowels(A,E,I,O,U) in the file.

Ans:

def countvowels(st):

      c=0

      for i in st:

            if i in 'aeiouAEIOU':

                  c+=1

      return c

           

st="The quick brown fox jumps over the lazy dog"

count=countvowels(st)

print("Count no. of vowels :", count)

 

Q16. Ravi a python programmer is working on a project, for some requirement, he has to define a function with

name CalculateInterest(), he defined it as:

def CalculateInterest (Principal, Rate=.06,Time): # code

But this code is not working, Can you help Ravi to identify the error in the above function and what is the solution.

Ans:

In the function CalculateInterest (Principal, Rate=.06,Time) parameters should be default parameters from right to left hence either Time should be provided with some default value or default value of rate should removed.

Q17. What do you understand the default argument in function? Which function parameter must be given default argument if it is used? Give example of function header to illustrate default argument.

Ans:

Default argument in function- value provided in the formal arguments in the definition header of a function is called as default argument in function. They should always be from right side argument to the left in sequence. For example:

def func( a, b=2, c=5): # definition of function func( )

Q18. Write a function INDEX_LIST(L), where L is the list of elements passed as argument to the function. The function returns another list named ‘indexList’ that stores the indices of all Non-Zero Elements of L.

For example:

If L contains [12,4,0,11,0,56]

The indexList will have - [0,1,3,5]

Ans:

def INDEX_LIST(L):

      indexList = [ ]

      for i in range(0,len(L)):

            if (L[i]%2 == 0):

                  indexList.append(i)

      return indexList

 

L =[12,4,15,11,9,56]

print(INDEX_LIST(L))

Q19. Write a function LeftShift(Numlist, n) in Python, which accepts a list Numlist of numbers and n is a numeric value by which all elements of the list are shifted to left.

Sample input data of the list

Numlist = [10, 20, 30, 40, 50, 60, 70], n=2

Output

Numlist = [30, 40, 50, 60, 70, 10, 20]

Ans:

def LeftShift(Numlist,n):

      NumList=Numlist[n:]+Numlist[:n]

      return NumList

 

Numlist = [10, 20, 30, 40, 50, 60, 70]

n=2

print("Original List",Numlist)

print("After Shift List :",LeftShift(Numlist,n))

Q20. Write a function SQUARE_LIST(L), where L is the list of elements passed as argument to the function. The function returns another list named ‘SList’ that stores the Squares of all Non-Zero Elements of L.

For example:

If L contains [9,4,0,11,0,6,0]

The SList will have-[81,14,121,36]

Ans:

def SQUARE_LIST(L):

      SList=[]

      for i in L:

            if i!= 0:

                  SList.append(i*i)

      return SList

L=[9,4,0,11,0,6,0]

print(SQUARE_LIST(L))

 

Q21. Write a function in Python Convert() to replaces elements having even values with its half and elements having odd values with twice its value in a list.

eg: if the list contains 3,4,5,16,9 then  rearranged list as 6,2,10,8, 18

Ans:

def Convert(L):

      SList=[]

      for i in L:

            if i%2== 0:

                  SList.append(i//2)

            else:

                  SList.append(i*2)

                 

      return SList

L=[3,4,5,16,9]

print(Convert(L))

Q22. Write a function AdjustList(L), where L is a list of integers. The function should reverse the contents of the list without slicing the list and without using any second list.

Example: If the list initially contains 2, 15, 3, 14, 7, 9, 19, 6, 1, 10,

then after reversal the list should contain 10, 1, 6, 19, 9, 7, 14, 3, 15, 2

Ans:

def AdjustList(lst):

      print("Reversed List : ",end="")

      print(list(reversed(lst)))

lst=[2, 15, 3, 14, 7, 9, 19, 6, 1, 10]

print("Original list : ",lst)

AdjustList(lst)

Q23. Write a function EVEN_LIST(L), where L is the list of elements passed as argument to the function.

The function returns another list named ‘evenList’ that stores the indices of all even numbers of L.

For example:

If L contains [12,4,3,11,13,56]

The evenList will have - [12,4,5]

Ans:

def EVEN_LIST(L):

      evenList=[]

      for i in L:

            if i%2==0:

                  evenList.append(i)

      return(evenList)

L=[12,4,3,11,13,56]

print("Original List : ", L)

L2=EVEN_LIST(L)

print("Even List : ",L2)

Q24. Write definition of a method/function DoubletheOdd( ) to add and display twice of odd values from the list of Nums.

For example :

If the Nums contains [25,24,35,20,32,41]

The function should display

Twice of Odd Sum: 202

Ans:

def DoubletheOdd(Nums):

      s=0

      for i in Nums :

            if i%2!=0:

                  s+=i*2

      print("Twice of Odd Sum : ",s)

Nums=[25,24,35,20,32,41]

print("Original List ", Nums)

DoubletheOdd(Nums)

Q25. Write a function in python named SwapHalfList(Array), which accepts a list Array of numbers and swaps the elements of 1st Half of the list with the 2nd Half of the list, ONLY if the sum of 1st Half is greater than 2nd Half of the list.

Sample Input Data of the list

Array= [ 100, 200, 300, 40, 50, 60],

Output Array = [40, 50, 60, 100, 200, 300]

def SwapHalfList(Array):

      s1=s2=0

      L=len(Array)

      for i in range(0,L//2):

            s1+=Array[i]

      for i in range(L//2, L):

            s2+=Array[i]

      if s1>s2:

            for i in range(0,L//2):

                  Array[i],Array[i+L//2]=Array[i+L//2],Array[i]

L=[ 100, 200, 300, 40, 50, 60]

SwapHalfList(L)

print(L)

Q26. Write a function INDEX_LIST(L), where L is the list of elements passed as argument to the function. The function returns another list named ‘indexList’ that stores the indices of all Elements of L which has a even unit place digit.

For example:

If L contains [12,4,15,11,9,56]

The indexList will have - [0,1,5]

Ans:

def Index_List(L):

      index_List=[]

      for i in range(len(L)):

            if L[i]%2==0:

                  index_List.append(i)

      return index_List

L=[12,4,15,11,9,56]

print(L)

idx=Index_List(L)

print(idx)

Q27. Write definition of a method/function AddOdd(VALUES) to display sum of odd values from the

list of VALUES.

Ans:

def AddOdd(Values):

      n=len(Values)

      s=0

      for i in Values:

            if (i%2!=0):

                  s=s+i

      print(s)

Values=[10,3,24,5,7,9,40]

AddOdd(Values)

Q28. Write the definition of a function Sum3(L) in Python, which accepts a list L of integers and displays the sum of all such integers from the list L which end with the digit 3.

For example, if the list L is passed

[ 123, 10, 13, 15, 23]

then the function should display the sum of 123, 13, 23, i.e. 159 as follows :

Sum of integers ending with digit 3 = 159

Ans:

def sum3(L):

      s=0

      for i in L:

            if i%10==3:

                  s=s+i

      return s

L=[123, 10, 13, 15, 23]

print(sum3(L))

Q29. Write a function Accept()  which is accept the employee id from the user and display its detail from the dictionary. Data is stored in the dictionary in the following format

{Empid1 : (Empname1, EmpSalary), Empid1 : (Empname1, EmpSalary),…..}

Ans:

def accept(pid):

    l=[ ]

    if pid in emp:

      l=emp[pid]

      print("Employee id, Employee Name", "\t""Salary")

      print(pid,"\t\t",l[0],"\t\t",l[1])

    else:

      print("Record not found")

 

emp={1:("Jyoti",25000),2:("Anshu",30000),3:("Dhairy",36000)}

print(emp)

pid=int(input("Enter the product id : "))

accept(pid)

Q30. Write a program to accept the employee id from the user and check Salary. If salary is less than 25000 then increase the salary by Rs1000. Data is stored in the dictionary in the following format.
{Empid : (Empname, EmpSalary}
Q31. Write a program to count the frequency of each character in a given string accepted from the user using dictionary.(Store the character as key and it’s frequency as value)

Ans

def accept(pid):

    l=[ ]

    if pid in emp:

      l=emp[pid]

      if l[1]>25000:

        emp[pid]=(l[0],l[1]+1000)

    print(emp)

 

emp={1:("Amit",25000),2:("Vanshi",30000),3:("Ravi",36000)}

print(emp)

pid=int(input("Enter the product id : "))

accept(pid)

Ans:

def freqDict(str1):

    d={ }

    for i in str1:

        if i not in d:

            d[i]=str1.count(i)

    return d

 

str1=input("Enter any String")

dic=freqDict(str1)

print(dic)

No comments:

Post a Comment