Python Interviews
- Check whether a number is divisible by another number using the modulus operator, %
n % k == 0
- Open a file:
f=open('text.txt','r') l=f.readlines() for i in l: print(i.strip('\n'))
- List Comprehension
[x**2 for x in range(1,11) if x % 2 == 1] [x for x in range(1,11) if x % 2 == 0]
- Slicing Operator:
[start : stop : steps]
- Floor Division operator used for dividing two operands with the result as quotient showing only digits before the decimal point:
10//5 = 2 10.0//5.0 = 2.0 10.0//4 = 2.0 10.0//7 = 1.0
- List vs. Tuple.
List is mutable while the Tuple is not. A tuple is allowed to be hashed. E.g: using it as a key for dictionaries.
List: a = [1,3,6] Tuple: b = (1,4,8)
- Lambda vs. def.
Def can hold multiple expressions while lambda is a uni-expression function. Def generates a function and designates a name to call it later. Lambda forms a function object and returns it. Def can have a return statement. Lambda can’t have return statements. Lambda supports to get used inside a list and dictionary.
- Optional statements possible inside a try-except block:
“else” clause: It is useful if you want to run a piece of code when the try block doesn’t create an exception. “finally” clause: It is useful when you want to execute some steps which run, irrespective of whether there occurs an exception or not.
- List Operations:
Insert integer at position 5 at position 0:
a.insert(0,5)
Delete the first occurrence of integer:
a.remove(6)
Insert integer at the end of the list:
a.append(9)
Sort the list:
a.sort()
Pop the last element from the list:
a.pop()
Pop 3rd element:
list1.pop(2)
Reverse the list:
a.reverse()
Max of List(print runner-ups score):
arr = [1,4,2,6,7,6] mx = max(arr) b = [j for j in arr if j != mx] print(max(b))
- List to Tuple Conv & Hashing:
>>> a = [1,2,3,45,6,7] >>> a [1, 2, 3, 45, 6, 7]
>>> tuple(a) (1, 2, 3, 45, 6, 7)
>>> hash(tuple(a)) 1409902629973635913
- Eval Function:
You are given a polynomial of a single indeterminate (or variable), . You are also given the values of and . Your task is to verify if .
Input:
1 4 x**3 + x**2 + x + 1
a = (input()).split() x = int(a[0]) k = int(a[1]) # Sol 1: print (eval(input()) == k) # Python 2: print eval(raw_input()) == k # Sol 2: f = lambda x:eval(input()) print (f(x) == k)
- Swap Case
def swap_case(s): a = "" for i in s: if i.isupper(): a += i.lower() elif i.islower: a += i.upper() else: a += i return a if __name__ == '__main__': s = input() result = swap_case(s) print(result)
print .join([i.lower() if i.isupper() else i.upper() for i in raw_input()])
def swap_case(s): a = "" for let in s: if let.isupper() == True: a+=(let.lower()) else: a+=(let.upper()) return a print raw_input().swapcase() print(input().swapcase())