Python Interviews: Difference between revisions

No edit summary
 
(18 intermediate revisions by the same user not shown)
Line 1:
 
= Modulus Operator =
 
* 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()
f.close()
for i in l:
print(i.strip('\n'))
 
 
* List Comprehension
= Read Log File =
 
* Better way to open a file as it auto closed file, even on crash
<pre>
with open('/var/log/apache2/access.log','r') as file:
for line in file:
print(line.split()[3], line.split()[6], line.split()[8], line.split()[9])
try:
b = b +int(line.split()[9])
except:
pass
 
print(b)
</pre>
 
= 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 =
* Floor Division operator used for dividing two operands with the result as quotient showing only digits before the decimal point:
10//5 = 2
Line 23 ⟶ 43:
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.
Line 30 ⟶ 50:
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.
Line 36 ⟶ 56:
Lambda supports to get used inside a list and dictionary.
 
= Optional statements in try-except block =
* 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:
Line 69 ⟶ 90:
print(max(b))
 
*= List to Tuple Conv & Hashing: =
>>> a = [1,2,3,45,6,7]
>>> a
Line 80 ⟶ 101:
1409902629973635913
 
*= Eval Function: =
 
You are given a polynomial of a single indeterminate (or variable), .
Line 106 ⟶ 127:
</pre>
 
*= Swap Case =
 
Python has built-in string validation methods for basic data. It can check if a string is composed of alphabetical characters, alphanumeric characters, digits, etc.
 
str.isalnum() checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9).
 
>>> print 'ab123'.isalnum()
True
 
str.isalpha() checks if all the characters of a string are alphabetical (a-z and A-Z).
 
>>> print 'abcD'.isalpha()
True
 
str.isdigit() checks if all the characters of a string are digits (0-9).
 
>>> print '1234'.isdigit()
True
 
str.islower() checks if all the characters of a string are lowercase characters (a-z).
 
>>> print 'abcd123#'.islower()
True
 
str.isupper() checks if all the characters of a string are uppercase characters (A-Z).
 
>>> print 'ABCD123#'.isupper()
True
 
 
<pre>
def swap_case(s):
Line 143 ⟶ 193:
print(input().swapcase())
</pre>
 
= Arrays & Reverse it =
<pre>
>>> input ="1 2 3 4 -8 -10"
 
>>> arr = input.split(' ')
>>> arr
['1', '2', '3', '4', '-8', '-10']
 
>>> arr[::-1]
['-10', '-8', '4', '3', '2', '1']
</pre>
 
= Regex =
 
Positive lookahead (?=REGEX_1)REGEX_2 (?=regex) t(?=s) matches the second t in streets.
Negative lookahead (?!REGEX_1)REGEX_2 (?!regex) t(?!s) matches the first t in streets.
Positive lookbehind (?<=regex) (?<=s)t matches the first t in streets.
Negative lookbehind (?<!regex) (?<!s)t matches the second t in streets.
 
= Sum Function =
 
lst = []
num = int(input('How many numbers: '))
for n in range(num):
numbers = int(input('Enter number '))
lst.append(numbers)
print("Sum of elements in given list is :", sum(lst))
 
= Convert Numeral System =
 
for i in range(0,10):
print(i, oct(i), hex(i), bin(i))
 
for i in range(0,10):
print(i, oct(i)[2:], hex(i)[2:].upper(), bin(i)[2:])
 
= Justify Text =
 
text.rjust(3,' ')
text.ljust(3,' ')
text.center(3,' ')
 
= Formatting =
[https://pyformat.info/ pyformat.info]
 
Old Method:
print('%s %s' % ('one','two'))
 
New Method:
print('{} {}'.format('one','two'))
 
Positional Index:
print('{1} {0}'.format(56,'ld'))
 
= Sorting =
 
listed ={}
 
plist = set(port_list)
listed.update({v:sorted(plist)})
 
for k,v in listed.items():
print("Tenant: ", k, "\nNo of Ports: ", len(v), '\n', [i for i in v if len(v) >0], '\n')
 
c = [1,5,2,3,9,6,2,0]
c.sort()
 
= Reverse a String =
'hello world'[::-1]
'dlrow olleh'
 
= Convert to Positive Number =
 
>>> a = -30
>>> abs(a)
30
 
* Interger can be positive or Negative:
>>> int(a)
-30
>>> -a
30
 
>>> c = 30.9
>>> int(c)
30
 
= "is" vs "==" =
 
a = [1,2,3]
b = a
 
c = [1,2,3]
 
print(a==c)
print(a is c)
 
Output:
True
False
 
 
= Dictionary =
 
a = {}