Posts

Showing posts from February, 2017

Each element in its input list is at most as big as the one before it

Question:- Define a Python function "descending(l)" that returns True if each element in its input list is at most as big as the one before it For instance: >>> descending([]) True >>> descending([4,4,3]) True >>> descending([19,17,18,7]) False Answer:- def descending(l):   a=True   if l==[]:     return True   for x in range(0,len(l)-1):     if l[x]<l[x+1]:         a=False         break         return a

Sum of prime numbers in list

Question:-  Write a function sumprimes(l) that takes as input a list of integers and returns the sum of all the prime numbers in l. Here are some examples to show how your function should work. >>> sumprimes([3,3,1,13]) 19 >>> sumprimes([2,4,6,9,11]) 13 >>> sumprimes([-3,1,6]) 0 Solution:- def prime (a): for j in range ( 2 ,a): if a % j == 0 : return False if a == 1 : return False if a <= 0 : return False return True def sumprimes (l): sum = 0 for i in range ( 0 , len (l)): if prime(l[i]): sum = sum + l[i] return sum

Bracket Checking

Question:- Write a function matched(s) that takes as input a   string s and checks if the brackets "(" and ")" in s are   matched: that is, every "(" has a matching ")" after it and   every ")" has a matching "(" before it.    Your function should   ignore all other symbols that appear in s.    Your function   should return True if s has matched brackets and False if it   does not. Here are some examples to show how your function should work. >>> matched("zb%78") True >>> matched("(7)(a") False >>> matched("a)*(?") False >>> matched("((jkl)78(A)&l(8(dd(FJI:),):)?)") True Solution:- def matched (s): a = 0 for i in range ( 0 , len (s)): if s[i] == '(' : if a >= 0 : a = a + 1 elif s[i] == ')' : a = a - 1 if a == 0 : return True else : return False

Reversing a number

Question:- Write a function intreverse(n) that takes as input a positive integer n and returns the integer obtained by reversing the digits in n. Here are some examples of how your function should work. >>> intreverse(783) 387 >>> intreverse(242789) 987242 >>> intreverse(3) 3 Solution:- def intreverse (n): a = "" while n > 0 : b = str (n % 10 ) a = a + b n = n // 10 return int (a)