merge
Python, List
.👉🏻 Use range() in combination with the max_length variable to loop as many times as there are elements in the longest list.
.👉🏻If a list is shorter than max_length, use fill_value for the remaining items (defaults to None).
.👉🏻zip() and itertools.zip_longest() provide similar functionality to this snippet.
Code:
merge(['a', 'b'], [1, 2], [True, False])
Output: [['a', 1, True], ['b', 2, False]]
Share and Support
@Python_Codes
Python, List
Merges two or more lists into a list of lists, combining elements from each of the input lists based on their positions..👉🏻 Use max() combined with a list comprehension to get the length of the longest list in the arguments.
.👉🏻 Use range() in combination with the max_length variable to loop as many times as there are elements in the longest list.
.👉🏻If a list is shorter than max_length, use fill_value for the remaining items (defaults to None).
.👉🏻zip() and itertools.zip_longest() provide similar functionality to this snippet.
Code:
def merge(*args, fill_value = None):Example:
max_length = max([len(lst) for lst in args])
result = []
for i in range(max_length):
result.append([
args[k][i] if i < len(args[k]) else fill_value for k in range(len(args))
])
return result
merge(['a', 'b'], [1, 2], [True, False])
Output: [['a', 1, True], ['b', 2, False]]
Share and Support
@Python_Codes
What are named tuples in Python?
These are part of the collections module and act very similar to regular tuples
The main difference being that values stored in a named tuple can be accessed using field names instead of indexes.
For example, a point in the two-dimensional plane can be represented using two coordinates. In a regular tuple, these values would be accessed by index ([0] and [1]), but if we define a named tuple, Point, we can access them using x and y instead (although we can still use indexes, too, if we want):
Example:
@Python_Codes
These are part of the collections module and act very similar to regular tuples
The main difference being that values stored in a named tuple can be accessed using field names instead of indexes.
For example, a point in the two-dimensional plane can be represented using two coordinates. In a regular tuple, these values would be accessed by index ([0] and [1]), but if we define a named tuple, Point, we can access them using x and y instead (although we can still use indexes, too, if we want):
Example:
from collections import namedtuple
# Regular tuple
p = (2, 4) # p[0] = 2, p[1] = 4
# Named tuple
Point = namedtuple('Point', 'x y')
q = Point(3, 5) # q.x = 3, q.y = 5
Example 2:from collections import namedtuple
Point = namedtuple('Point', ['x', 'y', 'z'], defaults = [1]);
a = Point(1, 1, 0); # a.x = 1, a.y = 1, a.z = 0
# Default value used for `z`
b = Point(2, 2); # b.x = 2, b.y = 2, b.z = 1 (default)
Share and Support@Python_Codes
bifurcate_by
Splits values into two groups, based on the result of the given filtering function.
👉Use a list comprehension to add elements to groups, based on the value returned by fn for each element.
👉If fn returns a truthy value for any element, add it to the first group, otherwise add it to the second group.
CODE:
def bifurcate_by(lst, fn):
return [
[x for x in lst if fn(x)],
[x for x in lst if not fn(x)]
]
Examples
Input:
bifurcate_by(['beep', 'boop', 'foo', 'bar'], lambda x: x[0] == 'b')
Output:
[ ['beep', 'boop', 'bar'], ['foo'] ]
Share and Support
@Python_Codes
Splits values into two groups, based on the result of the given filtering function.
👉Use a list comprehension to add elements to groups, based on the value returned by fn for each element.
👉If fn returns a truthy value for any element, add it to the first group, otherwise add it to the second group.
CODE:
def bifurcate_by(lst, fn):
return [
[x for x in lst if fn(x)],
[x for x in lst if not fn(x)]
]
Examples
Input:
bifurcate_by(['beep', 'boop', 'foo', 'bar'], lambda x: x[0] == 'b')
Output:
[ ['beep', 'boop', 'bar'], ['foo'] ]
Share and Support
@Python_Codes
Converts a string to kebab case.
👉Use re.sub() to replace any - or _ with a space, using the regexp r"(_|-)+".
👉Use re.sub() to match all words in the string, str.lower() to lowercase them.
👉Finally, use str.join() to combine all word using - as the separator.
CODE:
from re import sub
kebab('camelCase') # 'camel-case'
kebab('some text') # 'some-text'
kebab('some-mixed_string With spaces_underscores-and-hyphens')
# 'some-mixed-string-with-spaces-underscores-and-hyphens'
kebab('AllThe-small Things') # 'all-the-small-things'
Share and Support
@Python_Codes
👉Use re.sub() to replace any - or _ with a space, using the regexp r"(_|-)+".
👉Use re.sub() to match all words in the string, str.lower() to lowercase them.
👉Finally, use str.join() to combine all word using - as the separator.
CODE:
from re import sub
def kebab(s):
return '-'.join(
sub(r"(\s|_|-)+"," ",
sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+",
lambda mo: ' ' + mo.group(0).lower(), s)).split())
Exampleskebab('camelCase') # 'camel-case'
kebab('some text') # 'some-text'
kebab('some-mixed_string With spaces_underscores-and-hyphens')
# 'some-mixed-string-with-spaces-underscores-and-hyphens'
kebab('AllThe-small Things') # 'all-the-small-things'
Share and Support
@Python_Codes
Sorts one list based on another list containing the desired indexes.
Use zip() and sorted() to combine and sort the two lists, based on the values of indexes.
Use a list comprehension to get the first element of each pair from the result.
Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the third argument.
CODE:
a = ['eggs', 'bread', 'oranges', 'jam', 'apples', 'milk']
b = [3, 2, 6, 4, 1, 5]
sort_by_indexes(a, b)
Output: ['apples', 'bread', 'eggs', 'jam', 'milk', 'oranges']
sort_by_indexes(a, b, True)
Output: ['oranges', 'milk', 'jam', 'eggs', 'bread', 'apples']
Share and Support
@Python_Codes
Use zip() and sorted() to combine and sort the two lists, based on the values of indexes.
Use a list comprehension to get the first element of each pair from the result.
Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the third argument.
CODE:
def sort_by_indexes(lst, indexes, reverse=False):
return [val for (_, val) in sorted(zip(indexes, lst), key=lambda x: \
x[0], reverse=reverse)]
Example:a = ['eggs', 'bread', 'oranges', 'jam', 'apples', 'milk']
b = [3, 2, 6, 4, 1, 5]
sort_by_indexes(a, b)
Output: ['apples', 'bread', 'eggs', 'jam', 'milk', 'oranges']
sort_by_indexes(a, b, True)
Output: ['oranges', 'milk', 'jam', 'eggs', 'bread', 'apples']
Share and Support
@Python_Codes
unfold
Builds a list, using an iterator function and an initial seed value.
The iterator function accepts one argument (seed) and must always return a list with two elements ([value, nextSeed]) or False to terminate.
Use a generator function, fn_generator, that uses a while loop to call the iterator function and yield the value until it returns False.
Use a list comprehension to return the list that is produced by the generator, using the iterator function.
CODE:
INPUT:
unfold(f, 10)
OUTPUT:
[-10, -20, -30, -40, -50]
Share and Support
@Python_Codes
Builds a list, using an iterator function and an initial seed value.
Use a generator function, fn_generator, that uses a while loop to call the iterator function and yield the value until it returns False.
Use a list comprehension to return the list that is produced by the generator, using the iterator function.
def unfold(fn, seed):f = lambda n: False if n > 50 else [-n, n + 10]
def fn_generator(val):
while True:
val = fn(val[1])
if val == False: break
yield val[0]
return [i for i in fn_generator([None, seed])]
INPUT:
unfold(f, 10)
OUTPUT:
[-10, -20, -30, -40, -50]
Share and Support
@Python_Codes
curry
Curries a function.
Use functools.partial() to return a new partial object which behaves like fn with the given arguments, args, partially applied.
CODE:
@Python_Codes
Curries a function.
from functools import partial
def curry(fn, *args):
return partial(fn, *args)
Examples:add = lambda x, y: x + y
add10 = curry(add, 10)
add10(20) # 30
Share and Support@Python_Codes
From Today we start from basic useful Python codes which are useful to everyone while coding in python
#Basics
Return Multiple Values From Functions.
Code:
print(a, b, c, d)
Output:
1 2 3 4
Share and Support
@Python_Codes
Return Multiple Values From Functions.
Code:
def x():Input:
return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
Output:
1 2 3 4
Share and Support
@Python_Codes
#Basics
Find The Most Frequent Value In A List
Code:
4
Share and Support
@Python_Codes
Find The Most Frequent Value In A List
Code:
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]Output:
print(max(set(test), key = test.count))
4
Share and Support
@Python_Codes
#Basics
Check The Memory Usage Of An Object.
Code:
28
Share and Support
@Python_Codes
Check The Memory Usage Of An Object.
Code:
import sysOutput:
x = 1
print(sys.getsizeof(x))
28
Share and Support
@Python_Codes
#Basics
Checking if two words are anagrams
Code:
print(is_anagram('code', 'doce'))
print(is_anagram('python', 'yton'))
Output:
True
False
Share and Support
@Python_Codes
Checking if two words are anagrams
Code:
from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)
# or without having to import anything
def is_anagram(str1, str2):
return sorted(str1) == sorted(str2)
print(is_anagram('code', 'doce'))
print(is_anagram('python', 'yton'))
Output:
True
False
Share and Support
@Python_Codes