Channel: Python Codes
Examples :
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
#gives_count_of_apples
fruits.count('apple')
2
fruits.count('tangerine')
0
#to_get_index_of_banana
fruits.index('banana')
3
#Find_next_banana_starting_a_position_4
fruits.index('banana', 4)
6
#to_reverse_fruits_list
fruits.reverse()
fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
#to_add_item_at_the_end_of_the_list
fruits.append('grape')
fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
#sort_the_fruits_list
fruits.sort()
fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
#to_delete_the_last_item_in_the_list
fruits.pop()
'pear'
Share and Support @python_codes
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
#gives_count_of_apples
fruits.count('apple')
2
fruits.count('tangerine')
0
#to_get_index_of_banana
fruits.index('banana')
3
#Find_next_banana_starting_a_position_4
fruits.index('banana', 4)
6
#to_reverse_fruits_list
fruits.reverse()
fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
#to_add_item_at_the_end_of_the_list
fruits.append('grape')
fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
#sort_the_fruits_list
fruits.sort()
fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
#to_delete_the_last_item_in_the_list
fruits.pop()
'pear'
Share and Support @python_codes
Lambda functions in Python:
In Python, an anonymous function is a function that is defined without a name.
While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword.
Hence, anonymous functions are also called lambda functions.
Syntax of Lambda Function in python:
EX:
double = lambda x: x * 2
double(4) output: —> 8
Share and Support @python_codes
In Python, an anonymous function is a function that is defined without a name.
While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword.
Hence, anonymous functions are also called lambda functions.
Syntax of Lambda Function in python:
lambda arguments: expression
Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.EX:
double = lambda x: x * 2
double(4) output: —> 8
Share and Support @python_codes
Best Examples of Lambda Functions:
Factorial of a Number:
Factorial of a Number:
fact=lambda n:1 if n<=1 else n*fact(n-1)
fact(5)
n th fibonacci Number:fib=lambda n:n if n<=1 else fib(n-1)+fib(n-2)
fib(8)
Share and Support @python_codes"""
The following code adds two positive integers without using the '+' operator.
The code uses bitwise operations to add two numbers.
Input: 2 3
Output: 5
"""
The following code adds two positive integers without using the '+' operator.
The code uses bitwise operations to add two numbers.
Input: 2 3
Output: 5
"""
def add_bitwise_operator(x, y):
while y:
carry = x & y
x = x ^ y
y = carry << 1
return x
Share and Support @python_codesProblem:
Given a String contains Opening and Closing Brackets return True or False based on the given Brackets are Balanced or Not
INPUT: OUTPUT:
{[()]} —-> True
{{){}} —-> False
Given a String contains Opening and Closing Brackets return True or False based on the given Brackets are Balanced or Not
INPUT: OUTPUT:
{[()]} —-> True
{{){}} —-> False
Solution:
def BalancedBrackets(st):
openingBrackets="([{"
closingBrackets=")]}"
matchingBrackets={ ')':'(',
'}':'{',
']':'[' }
stack=[]
for char in st:
if char in openingBrackets:
stack.append(char)
elif char in closingBrackets:
if len(stack)==0:
return False
if stack[-1]==matchingBrackets[char]:
stack.pop()
else:
return False
return len(stack)==0
print(BalancedBrackets(input()))
Share and Support @python_codesSorts 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.
Code:
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.
Code:
def sort_by_indexes(lst, indexes):
return [val for _, val in sorted(zip(indexes, lst), key = lambda x: x[0])]
EXAMPLESa = ['eggs', 'bread', 'oranges', 'jam', 'apples', 'milk']
b = [3, 2, 6, 4, 1, 5]
sort_by_indexes(a, b) # ['apples', 'bread', 'eggs', 'jam', 'milk', 'oranges']
Share and Support @python_codesSlugify :
Converts a string to a URL-friendly slug.
Use str.lower() and str.strip() to normalize the input string.
Use re.sub() to to replace spaces, dashes and underscores with - and remove special characters.
Code:
import re
def slugify(s):
s = s.lower().strip()
s = re.sub(r'[^\w\s-]', '', s)
s = re.sub(r'[\s_-]+', '-', s)
s = re.sub(r'^-+|-+$', '', s)
return s
EXAMPLE
slugify('Hello World!')
Output:
'hello-world'
Share and Support
@Python_Codes
Converts a string to a URL-friendly slug.
Use str.lower() and str.strip() to normalize the input string.
Use re.sub() to to replace spaces, dashes and underscores with - and remove special characters.
Code:
import re
def slugify(s):
s = s.lower().strip()
s = re.sub(r'[^\w\s-]', '', s)
s = re.sub(r'[\s_-]+', '-', s)
s = re.sub(r'^-+|-+$', '', s)
return s
EXAMPLE
slugify('Hello World!')
Output:
'hello-world'
Share and Support
@Python_Codes
Calculates the date of n days ago from today.
Use datetime.date.today() to get the current day.
Use datetime.timedelta to subtract n days from today's date.
Code:
from datetime import timedelta, date
def days_ago(n):
return date.today() - timedelta(n)
EXAMPLE
days_ago(5)
Output:
date(2020, 10, 23)
Share and Support
@Python_Codes
Use datetime.date.today() to get the current day.
Use datetime.timedelta to subtract n days from today's date.
Code:
from datetime import timedelta, date
def days_ago(n):
return date.today() - timedelta(n)
EXAMPLE
days_ago(5)
Output:
date(2020, 10, 23)
Share and Support
@Python_Codes
Converts a date to its ISO-8601 represenation.
Use datetime.datetime.isoformat() to convert the given datetime object to an ISO-8601 date.
Code:
from datetime import datetime
def to_iso_date(d):
return d.isoformat()
EXAMPLE
from datetime import datetime
to_iso_date(datetime(2020,10,25))
Output:
2020-10-25T00:00:00
Share and Support
@Python_Codes
Use datetime.datetime.isoformat() to convert the given datetime object to an ISO-8601 date.
Code:
from datetime import datetime
def to_iso_date(d):
return d.isoformat()
EXAMPLE
from datetime import datetime
to_iso_date(datetime(2020,10,25))
Output:
2020-10-25T00:00:00
Share and Support
@Python_Codes
Converts a hexadecimal color code to a tuple of integers corresponding to its RGB components.
Use a list comprehension in combination with int() and list slice notation to get the RGB components from the hexadecimal string.
Use tuple() to convert the resulting list to a tuple.
Code:
def hex_to_rgb(hex):
return tuple(int(hex[i:i+2], 16) for i in (0, 2, 4))
EXAMPLE
hex_to_rgb('FFA501')
Output:
(255, 165, 1)
Share and Support
@Python_Codes
Use a list comprehension in combination with int() and list slice notation to get the RGB components from the hexadecimal string.
Use tuple() to convert the resulting list to a tuple.
Code:
def hex_to_rgb(hex):
return tuple(int(hex[i:i+2], 16) for i in (0, 2, 4))
EXAMPLE
hex_to_rgb('FFA501')
Output:
(255, 165, 1)
Share and Support
@Python_Codes
Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).
Use isalnum() to filter out non-alphanumeric characters, lower() to transform each character to lowercase.
Use collections.Counter to count the resulting characters for each string and compare the results.
Code:
from collections import Counter
def is_anagram(s1, s2):
return Counter(
c.lower() for c in s1 if c.isalnum()
) == Counter(
c.lower() for c in s2 if c.isalnum()
)
EXAMPLE
is_anagram("#anagram", "Nag a ram!")
Output:
True
Share and Support
@Python_Codes
Use isalnum() to filter out non-alphanumeric characters, lower() to transform each character to lowercase.
Use collections.Counter to count the resulting characters for each string and compare the results.
Code:
from collections import Counter
def is_anagram(s1, s2):
return Counter(
c.lower() for c in s1 if c.isalnum()
) == Counter(
c.lower() for c in s2 if c.isalnum()
)
EXAMPLE
is_anagram("#anagram", "Nag a ram!")
Output:
True
Share and Support
@Python_Codes
What is the difference between list.sort() and sorted() in Python?
Python provides two ways to sort a list, the built-in list method list.sort() and the built-in function sorted(). Although both will sort the elements of a list, if used incorrectly they can produce unexpected or undesired results.
Differences and similarities
The primary difference between the two is that list.sort() will sort the list in-place, mutating its indexes and returning None, whereas sorted() will return a new sorted list leaving the original list unchanged. Another difference is that sorted() accepts any iterable while list.sort() is a method of the list class and can only be used with lists.
Example:
nums = [2, 3, 1, 5, 6, 4, 0]
print(sorted(nums)) # [0, 1, 2, 3, 4, 5, 6]
print(nums) # [2, 3, 1, 5, 6, 4, 0]
print(nums.sort()) # None
print(nums) # [0, 1, 2, 3, 4, 5, 6]
Both list.sort() and sorted() have the same key and reverse optional arguments and can be called on each list element prior to making comparisons.
When to use each one:
list.sort() should be used whenever mutating the list is intended and retrieving the original order of the elements is not desired. On the other hand, sorted() should be used when the object to be sorted is an iterable (e.g. list, tuple, dictionary, string) and the desired outcome is a sorted list containing all elements.
Share and Support
@Python_Codes
Python provides two ways to sort a list, the built-in list method list.sort() and the built-in function sorted(). Although both will sort the elements of a list, if used incorrectly they can produce unexpected or undesired results.
Differences and similarities
The primary difference between the two is that list.sort() will sort the list in-place, mutating its indexes and returning None, whereas sorted() will return a new sorted list leaving the original list unchanged. Another difference is that sorted() accepts any iterable while list.sort() is a method of the list class and can only be used with lists.
Example:
nums = [2, 3, 1, 5, 6, 4, 0]
print(sorted(nums)) # [0, 1, 2, 3, 4, 5, 6]
print(nums) # [2, 3, 1, 5, 6, 4, 0]
print(nums.sort()) # None
print(nums) # [0, 1, 2, 3, 4, 5, 6]
Both list.sort() and sorted() have the same key and reverse optional arguments and can be called on each list element prior to making comparisons.
When to use each one:
list.sort() should be used whenever mutating the list is intended and retrieving the original order of the elements is not desired. On the other hand, sorted() should be used when the object to be sorted is an iterable (e.g. list, tuple, dictionary, string) and the desired outcome is a sorted list containing all elements.
Share and Support
@Python_Codes
What are named tuples in Python?
Python's named tuples are a very simple yet interesting feature that can make a developer's life easier. They 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
Apart from the increased readability of your code, named tuples provide a few other quality of life improvements. First and foremost, they allow for default values to be specified via the defaults iterable argument. Secondly, they have the ability to automatically rename duplicate or invalid fields via the rename boolean argument. And, finally, they even provide a convenient option to specify field names as a list or comma/space-separated string.
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
b = Point(2, 2); # b.x = 2, b.y = 2, b.z = 1 (default)
Where's the catch? you might ask. Well, it seems like there's none! The obvious parallel to dictionaries in terms of syntax doesn't seem to go any further, as named tuple instances do not have per-instance dictionaries, meaning they require as much memory as regular tuples.
Share and Support
@Python_Codes
Python's named tuples are a very simple yet interesting feature that can make a developer's life easier. They 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
Apart from the increased readability of your code, named tuples provide a few other quality of life improvements. First and foremost, they allow for default values to be specified via the defaults iterable argument. Secondly, they have the ability to automatically rename duplicate or invalid fields via the rename boolean argument. And, finally, they even provide a convenient option to specify field names as a list or comma/space-separated string.
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)
Where's the catch? you might ask. Well, it seems like there's none! The obvious parallel to dictionaries in terms of syntax doesn't seem to go any further, as named tuple instances do not have per-instance dictionaries, meaning they require as much memory as regular tuples.
Share and Support
@Python_Codes
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
HTML Embed Code: