Appearance
question:determine if two strings are anagrams or not. string1 = 'listen' string2 = 'silent'
answer:""" Determine if two strings are anagrams or not """ def is_anagram(string1, string2): # get lists of characters list1 = list(string1.lower()) list2 = list(string2.lower()) # sort both lists list1.sort() list2.sort() if list1 == list2: return True else: return False if __name__ == '__main__': string1 = 'listen' string2 = 'silent' print("Result: " + str(is_anagram(string1, string2)))
question:Given a binary tree, write a program to calculate the sum of all its nodes.
answer:def calculateSumOfBinaryTree(root): if root == None: return 0 else: return root.data + calculateSumOfBinaryTree(root.left) + calculateSumOfBinaryTree(root.right)
question:Write a function to calculate the number of letter and non-letter characters in a string. Input: 'If These Hills'
answer:def numberOfLettersAndNonLetterCharacters(string): count_characters = 0 count_non_characters = 0 for char in string: if char.isalpha(): count_characters += 1 else: count_non_characters += 1 return (count_characters, count_non_characters) print(numberOfLettersAndNonLetterCharacters('If These Hills'))
question:Write a correct implementation of the following algorithm Binary search for an element x in a sorted array
answer:def binary_search(arr, x): low = 0 high = len(arr) - 1 while low <= high: mid = (high+low)//2 if arr[mid] < x: low = mid + 1 elif arr[mid] > x: high = mid - 1 else: return mid return -1