Loading...
More Python Posts
# Python binary search functiondef binary_search(arr, target):left = 0right = len(arr) - 1while left <= right:mid = (left + right) // 2if arr[mid] == target:return midelif arr[mid] < target:left = mid + 1else:right = mid - 1return -1# Usagearr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]target = 7result = binary_search(arr, target)if result != -1:print(f"Element is present at index {result}")else:print("Element is not present in array")
# @return a list of strings, [s1, s2]def letterCombinations(self, digits):if '' == digits: return []kvmaps = {'2': 'abc','3': 'def','4': 'ghi','5': 'jkl','6': 'mno','7': 'pqrs','8': 'tuv','9': 'wxyz'}return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])
filename = "data.txt"data = "Hello, World!"with open(filename, "a") as file:file.write(data)
# function which return reverse of a stringdef isPalindrome(s):return s == s[::-1]# Driver codes = "malayalam"ans = isPalindrome(s)if ans:print("Yes")else:print("No")
# Function to multiply two matricesdef multiply_matrices(matrix1, matrix2):# Check if the matrices can be multipliedif len(matrix1[0]) != len(matrix2):print("Error: The number of columns in the first matrix must be equal to the number of rows in the second matrix.")return None# Create the result matrix filled with zerosresult = [[0 for _ in range(len(matrix2[0]))] for _ in range(len(matrix1))]# Perform matrix multiplicationfor i in range(len(matrix1)):for j in range(len(matrix2[0])):for k in range(len(matrix2)):result[i][j] += matrix1[i][k] * matrix2[k][j]return result# Example matricesmatrix1 = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]matrix2 = [[10, 11],[12, 13],[14, 15]]# Multiply the matricesresult_matrix = multiply_matrices(matrix1, matrix2)# Display the resultif result_matrix is not None:print("Result:")for row in result_matrix:print(row)
my_list = ["blue", "red", "green"]#1- Using sort or srted directly or with specifc keysmy_list.sort() #sorts alphabetically or in an ascending order for numeric datamy_list = sorted(my_list, key=len) #sorts the list based on the length of the strings from shortest to longest.# You can use reverse=True to flip the order#2- Using locale and functoolsimport localefrom functools import cmp_to_keymy_list = sorted(my_list, key=cmp_to_key(locale.strcoll))