Skip to content

Instantly share code, notes, and snippets.

@CharudattaManwatkar
CharudattaManwatkar / for_else_alt.py
Last active April 8, 2021 18:17
Alternative to for-else
my_list = ['some', 'list', 'containing', 'five', 'elements']
min_len = 3
no_break = True
for element in my_list:
if len(element) < min_len:
print(f'Caught an element shorter than {min_len} letters')
no_break = False
break
@CharudattaManwatkar
CharudattaManwatkar / ellipsis_3.py
Created April 4, 2021 10:28
Ellipsis for slicing in Numpy
import numpy as np
a = np.arange(16).reshape(2,2,2,2)
print(a[..., 0].flatten())
print(a[:, :, :, 0].flatten())
@CharudattaManwatkar
CharudattaManwatkar / ellipsis_2.py
Last active April 4, 2021 10:39
Ellipsis as an alternative to None
# calculate nth odd number
def nth_odd(n):
if isinstance(n, int):
return 2 * n - 1
else:
return None
# calculate the original n of nth odd number
def original_num(m=...):
@CharudattaManwatkar
CharudattaManwatkar / ellipsis_1.py
Created April 4, 2021 09:29
Ellipsis as a placeholder for unwritten code in python
def some_function():
...
def another_function():
pass
@CharudattaManwatkar
CharudattaManwatkar / eval_exec.py
Created April 4, 2021 08:22
eval and exec functions can
a = 3
b = eval('a + 2')
print('b =', b)
exec('c = a ** 2')
print('c is', c)
@CharudattaManwatkar
CharudattaManwatkar / int_separators.py
Created April 4, 2021 07:37
Integers can be written with the separator '_' to improve readability.
a = 3250
b = 67_543_423_778
print(type(a))
print(type(b))
print(type(a)==type(b))
@CharudattaManwatkar
CharudattaManwatkar / function_attribute.py
Last active April 30, 2021 20:15
Function attributes in python
def func(x):
intermediate_var = x**2 + x + 1
if intermediate_var % 2:
y = intermediate_var ** 3
else:
y = intermediate_var **3 + 1
# setting attributes here
func.optional_return = intermediate_var
@CharudattaManwatkar
CharudattaManwatkar / for_else_demo.py
Last active April 4, 2021 06:52
An example of else clause with for loop in python
my_list = ['some', 'list', 'containing', 'five', 'elements']
min_len = 3
for element in my_list:
if len(element) < min_len:
print(f'Caught an element shorter than {min_len} letters')
break
else:
print(f'All elements at least {min_len} letters long')