- Sorting Elements using
arr.sort()
- Checking for Power of 2
- Creating a Dictionary with Default Values
- Applying Functions to Create Dictionary Values
- Return Values of
list.sort()
andsorted()
in Functions - Using
enumerate
to Get Index-Value Pairs - Using
enumerate
with Arrays - Finding the Index of an Element using
arr.index()
- Updating a Global Array Reference
- Perfect Squares
arr.sort(key=function, reverse=True)
- Sorts elements in
arr
usingfunction
and sorts in descending order whenreverse=True
.
Example:
data = [(1, 4), (3, 2), (2, 7)]
data.sort(key=lambda x: x[1], reverse=True)
print(data) # Output: [(2, 7), (1, 4), (3, 2)]
n & (n - 1) == 0
- Checks if
n
is a power of 2. - Ensure
n > 0
.
Example:
def is_power_of_2(n):
return n > 0 and (n & (n - 1)) == 0
print(is_power_of_2(4)) # Output: True
print(is_power_of_2(5)) # Output: False
d = dict.fromkeys(keys, default_value)
- Creates a dictionary using
keys
, all having the samedefault_value
.
Example:
keys = ['a', 'b', 'c']
default_value = 0
result_dict = dict.fromkeys(keys, default_value)
print(result_dict) # Output: {'a': 0, 'b': 0, 'c': 0}
d = {ele: is_even(ele) for ele in a}
- Uses
is_even()
to determine dictionary values. - Uses dictionary comprehension.
Example:
def is_even(n):
return 1 if n % 2 == 0 else 0
a = [1, 2, 3, 4, 5]
d = {ele: is_even(ele) for ele in a}
print(d) # Output: {1: 0, 2: 1, 3: 0, 4: 1, 5: 0}
When using list.sort()
or sorted()
inside a function, remember:
list.sort()
sorts the list in-place and returnsNone
.sorted()
returns a new sorted list.
def sort_list_and_return(l):
l.sort() # Returns None
def sorted_list_and_return(l):
return sorted(l) # Returns a new sorted list
To get index-value pairs from a list, use enumerate
:
dic = {x: index for index, x in enumerate(A2)}
enumerate
returns both the index and value as a tuple for each element in the list.- Useful for creating dictionaries with elements as keys and their respective indices as values.
Example:
A2 = [10, 20, 30, 40, 50]
dic = {x: index for index, x in enumerate(A2)}
print(dic) # Output: {10: 0, 20: 1, 30: 2, 40: 3, 50: 4}
You can use enumerate
with arrays to get both index and value for each element:
for index, value in enumerate(arr):
print(f"Element at index {index}: {value}")
enumerate
returns both the index and value as tuples, allowing you to iterate over arrays with index information.
To find the index of an element in an array, use the arr.index()
method:
index = arr.index(element)
- Returns the index of the first occurrence of
element
in the array. - Raises a
ValueError
ifelement
is not found in the array.
Example:
arr = [10, 20, 30, 40, 20, 50]
index = arr.index(20)
print(index) # Output: 1
When updating a global reference of an array, it's important to note that you need to change the elements of the array one by one.
Example:
Consider the following code snippet:
class Solution:
def rearrange(self, arr, n):
for i in range(n):
arr[i] = array[i] # Update the original array
def is_perfect_square(number):
if number < 0:
return False
i = 1
while number > 0:
number -= i
i += 2
return number == 0
print(is_perfect_square(16)) # Output: True
print(is_perfect_square(25)) # Output: True
print(is_perfect_square(14)) # Output: False
- It works by subtracting consecutive odd numbers from the given number and checking if it reaches zero.
- If it reaches zero, the original number is a perfect square.
- This method is efficient for large numbers as it avoids computing square roots.