Wednesday, 4 April 2018

Python:Assertion


Assertions in Python:
================
What Are Assertions & What Are They Good For?

Python’s assert statement is a debugging aid that tests a condition. If the condition is true, it does nothing and your program just continues to execute. But if the assert condition evaluates to false, it raises an AssertionError exception with an optional error message.

The proper use of assertions is to inform developers about unrecoverable errors in a program. They’re not intended to signal expected error conditions, like “file not found”, where a user can take corrective action or just try again.
Another way to look at it is to say that assertions are internal self-checks for your program. They work by declaring some conditions as impossible in your code. If one of these conditions doesn’t hold that means there’s a bug in the program.
If your program is bug-free, these conditions will never occur. But if they do occur the program will crash with an assertion error telling you exactly which “impossible” condition was triggered. This makes it much easier to track down and fix bugs in your programs.
To summarize: Python’s assert statement is a debugging aid, not a mechanism for handling run-time errors. The goal of using assertions is to let developers find the likely root cause of a bug more quickly. An assertion error should never be raised unless there’s a bug in your program.

The assert Statement
When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception.
The syntax for assert is –
assert Expression[, Arguments]
If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback.

Example1:
def get_age(age):
    print ("Your age is:" ,age)

get_age(20)
get_age(-1)

Output:
Your age is: 20
Your age is: -1


#After Adding Assert Staement
def get_age(age):
    assert age > 0, "Age cannot be Negative!"
    print ("Your age is:" ,age)
get_age(-1)

Output:
======
Traceback (most recent call last):
File "<ipython-input-27-6628f64fef17>", line 5, in <module>
get_age(-1)
File "<ipython-input-27-6628f64fef17>", line 2, in get_age
assert age > 0, "Age cannot be Negative!"
AssertionError: Age cannot be Negative!

Example2:
Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative temperature.
#!/usr/bin/python
def KelvinToFahrenheit(Temperature):
   assert (Temperature >= 0),"Colder than absolute zero!"
   return ((Temperature-273)*1.8)+32

print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)

When the above code is executed, it produces the following result −
32.0
451
Traceback (most recent call last):
   File "test.py", line 9, in <module>
      print KelvinToFahrenheit(-5)
   File "test.py", line 4, in KelvinToFahrenheit
      assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!

Go Through the Below Videos for a Quick Overview:
==========================================











Python: Interview Questions:MCQ's


Python: Interview Questions MCQ
===============================
 Given the following Python statements
>>> a = 'nicola tesla'
>>> b = 'nicola tesla'
What will be the output of following statements?
1.     a is b

2.     a == b

3. What is the output of the following program snippet?
   a = [1, 3, 5, 7, 9]
   b = a
   a.remove(3)
   print(b)

4.     The value of the expression:
4 + 3 % 5
a) 4
b) 7
c) 2
d) 0
5.     What is the output of the code shown below?
def mk(x):
    def mk1():
        print("Decorated")
        x()
    return mk1
def mk2():
    print("Ordinary")
p = mk(mk2)
p()

a) Decorated
Decorated
b) Ordinary
Ordinary
c) Ordinary
Decorated
d) Decorated
Ordinary
6.  What is the output of the code shown below?

def f(x):
    def f1(a, b):
        print("hello")
        if b==0:
            print("NO")
            return
        return f(a, b)
    return f1
@f
def f(a, b):
    return a%b
f(4,0)

a) hello
NO
b) hello
Zero Division Error
c) NO
d) hello

7.  What is the output of the code shown below?
def d(f):
    def n(*args):
        return '$' + str(f(*args))
    return n
@d
def p(a, t):
    return a + a*t
print(p(100,0))

a) 100
b) $100
c) $0
d) 0
8.  What is the output of print(k) in the following?
k = [print(i) for i in my_string if i not in "aeiou"]
print(k)

a) all characters of my_string that aren’t vowels
b) a list of Nones
c) list of Trues
d) list of Falses




9.  What is the output of the code shown below?
l1=[2,4,6]
l2=[-2,-4,-6]
for i in zip(l1, l2):
    print(i)
a) 2, -2
4, -4
6, -6
b) [(2, -2), (4, -4), (6, -6)]
c) (2, -2)
(4, -4)
(6, -6)
d) [-4, -16, -36]

10.          Which of these about a dictionary is false?
a)    The values of a dictionary can be accessed using keys
b)    The keys of a dictionary can be accessed using values
c)    Dictionaries aren’t ordered
d)    Dictionaries are mutable

11.          What is the output of the code shown below?
w = {"house":"Haus","cat":"Katze","red":"rot"}
w1 = {"red":"rouge","blau":"bleu"}
w.update(w1)
print w


12.          What is the output of the following code?
count={}
count[(1,2,4)] = 5
count[(4,2,1)] = 7
count[(1,2)] = 6
count[(4,2,1)] = 2
tot = 0
for i in count:
    tot=tot+count[i]
print(len(count)+tot)

a)    25
b)    17
c)    16
d)    Tuples can’t be made keys of a dictionary


13.          Write a one-line python statement that swaps the key-value pairs of a dictionary?
Example: if a dictionary is x = { ‘a’:1, ‘b’:2 } the output should be { 1:’a’, 2:’b’ }


14.          Write a one-line python statement that dynamically generates a list of all even numbers between 0 to 100 without using mod operator?

     15. What is the output of the line of code shown below?
   re.split('\W+', 'Hello, hello, hello.')

a) [‘Hello’, ‘hello’, ‘hello.’]
b) [‘Hello, ‘hello’, ‘hello’]
c) [‘Hello’, ‘hello’, ‘hello’, ‘.’]
d) [‘Hello’, ‘hello’, ‘hello’, ‘’]

16.          Write a python function that will take hex values
(Eg: “00:2B:2C:5A:5B:23:25”) as a string and
a.  Extract 2nd and 3rd bytes of the string and print them in reversed order. Eg: “2B:2C” will be printed as “2C:2B”
b.  Check is if the 6th byte is zero, if so return True, else return False



17.          What is the output of the following code?
>>> class demo():
      def __repr__(self):
            return '__repr__ built-in function called'
      def __str__(self):
            return '__str__ built-in function called'
>>> s=demo()
>>> s


a) Error
b) Nothing is printed
c) __str__ called
d) __repr__ called

18.          What is the output of the following piece of code?
class A:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __str__(self):
        return 1
    def __eq__(self, other):
        return self.x * self.y == other.x * other.y
obj1 = A(5, 2)
obj2 = A(2, 5)
print(obj1 == obj2)


a) False
b) 1
c) True
d) An exception is thrown



19.          Write a python function that removes all spaces in a string and returns the resultant string?



20.          You will be given an array of numbers in which some numbers occur once and the rest occur more than once. Your task will be to write a python function to return the sum of the numbers that occur only once.
For example, repeats([4,5,7,5,4,8]) = 15 because only the numbers 7 and 8 occur once, and their sum is 15.



Solutions:

1.  False à [1]
2.  True  à [1]
3.  [1, 5, 7, 9] à [2] 
4.  b à [1]
5.  d à [3]
6.  a à [5]
7.  b à [3]
8.  b à [2]
9.  c à [2]
10.          b à [1]
11.   {'house': 'Haus', 'blau': 'bleu', 'red': 'rouge', 'cat': 'Katze'} à [2]
12.          c à [3]
13.          { v:k for k,v in x.items() }  OR { v:k for k,v in x.iteritems() } OR dict(zip(x.values(), x.keys())) à [5]
14.          x = [ n for n in range(0, 101, 2) ] à [2]
15.          d à [3]
16.          One possible solution à [5]
def func(mac):
    s = mac.split(“:”)
    print(“:”.join(s[2],s[1]))
    return hex(s[5]) == 0
17.          d à [2]
18.          c à [3]
19.          One possible solution: à [3]
def remove_spaces(string):
    return “”.join(string.split(“ “))

20.          One possible solution: à [5]
from collections import Counter
from functools import reduce

def repeats(number_list):
    x = Counter(number_list)
    return reduce(sum, [ k for k,v in x.items() if v == 1 ])