Create a random number between 10 and 30 in Python
import random num = random.randint(10, 30)
alternate way: from random import randint
Python function used to prompt the user to enter text?
input()
input() returns string
Validate that string name contains only digits.
name.isdigit()
What will happen with below code:
int('34e5')ValueError will be thrown.
Print a list of first 5 even numbers without using for loop.
print(list(range(2,11,2)))
_ operator allows a function to receive an unknown (0 or more) num
ber of arguments.
splat
mysum(*[1,2,3]) = mysum(1,2,3)
argument becomes a tuple
condition for empty string str in Python
if not str
same expression for non-zeroness
Round up mins (float) to two decimal places.
round(mins, 2)
In f-string: f”{mins: .2f}”
Convert one_run into float and throw error if it is non-numeric.
try:
mins = float(one_run)
except ValueError as e:
print(f"{one_run} is not a valid number. Digits expected!")Traverse through each digit of a decimal number num
Print index (position) and digit in reverse order (right to left).
for i, d in enumerate(reversed(str(num))):
print(f'position: {i}, digit: {d}')hnum (string) to its decimal equivalent.ord()ord(hnum) - ord('a') + 10Alternatively, int(hnum, 16)
Check if ‘a’ is present in ‘abcd’
if 'a' in 'abcd'
same for any sequence: list or tuple
numbers = [5, 2, 9, 1, 5, 6, 9, 7]
Find unique numbers from the numbers list.
set(numbers)
a,b,c = 3,4,8
Swap the three variables, such that after swapping:a=4, b=8, c=3.
Hint: In-place replacement in Python
a,b,c = b, c, a
Use Python to create a safe “lowest possible” numeric value.
Hint: float
neg_inf = float('-inf')
print(neg_inf < -10**9) # TrueWrite function third_max to find the third maximum number in a numeric list.
numbers = [5, 2, 9, 1, 5, 6, 9, 7]
from typing import List, Optional
def third_max(numbers: List[int]) -> Optional[int]:
'''
Write function `third_max` to find the third maximum number in a numeric list.
'''
unique_nums = set(numbers)
if len(unique_nums) < 3:
print('Not sufficient numbers')
return None
firstM = secondM = thirdM = float('-inf') # firstM >= secondM >= thirdM
for num in unique_nums:
if num > firstM:
firstM, secondM, thirdM = num, firstM, secondM
elif num > secondM:
secondM, thirdM = num, secondM
elif num > thirdM:
thirdM = num
return int(thirdM)
print(third_max([5, 2, 9, 1, 5, 6, 9, 7])) # should return 6Return ‘bdf’ from ‘abcdef’ using slicing in Python
'abcdef'[1::2]
type of the sliced output is same as input’s type
Break string ‘abc def ghi’ apart based on spaces.
'abc def ghi'.split()
output of split() is list
join a list of strings ['abc', 'def',
'ghi'] by spaces.
' '.join(['abc', 'def', 'ghi'])
output of join depends on type of items in list
defining a function name a second time will overwrite the first definition.
(T/F)
True
Which of the following will throw error?
1. print('data engineer'.split(None))
2. print('data engineer'.split(''))
3. print('data engineer'.split())
4. print('data engineer'.split(' '))
['data', 'engineer']['data', 'engineer']['data', 'engineer']default value of sep is None
generic way to create empty list/tuple/str from given argument?
def first_last(seq):
if not seq:
return seq
output = type(seq[0])()seq[:1]seq[-1:]