Efficiency Flashcards
what is a more efficient way to write this function: def isPalindrome(self, x: int) -> bool: if str(x) == str(x)[::-1]: return True return False
def isPalindrome(self, x: int) -> bool: return str(x) == str(x)[::-1]
What is the most efficient way to convert a list of multiple integers into a single integer?
# Python3 program to convert a list # of integers into a single integer def convert(list):
# multiply each integer element with its # corresponding power and perform summation
res = sum(d * 10**i for i, d in enumerate(list[::-1])) return(res)
# Driver code list = [1, 2, 3] print(convert(list))
output: 123
What is most efficient way to convert an integer into a list of ints?
# Python3 code to demonstrate # conversion of number to list of integers # using map()
# initializing number num = 2019
# printing number print ("The original number is " + str(num))
# using map() # to convert number to list of integers res = list(map(int, str(num)))
# printing result print ("The list from number is " + str(res))
output:
The original number is 2019
The list from number is [2, 0, 1, 9]
What are two ways to optimize a for loop?
All acceptable answers:
- if using a “.” operator, make sure to assign to a variable, should help with the search process
- use local variables instead of global variables
- using map() if possible
- list comprehension
Why is list comprehension faster than a for loop?
List comprehension is faster because it is optimized for the Python interpreter to spot a predictable pattern during looping
How can this code be optimized? Why are the changes you’ve made helping?
upper = str.upper
append = upperlist.append
def to_upper_2():
for word in lowerlist:
append(upper(word))
to_upper_2()
def to_upper_3(): upperlist = [] upper = str.upper append = upperlist.append for word in lowerlist: append(upper(word)) return upperlist
upperlist = to_upper_3()
reason: using local variables as opposed to global variables is a way to increase efficiency. Local variables are accessed more efficiently in Python.