Efficiency Flashcards

1
Q
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
A
def isPalindrome(self, x: int) -> bool:
        return str(x) == str(x)[::-1]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the most efficient way to convert a list of multiple integers into a single integer?

A
# 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is most efficient way to convert an integer into a list of ints?

A
# 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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are two ways to optimize a for loop?

A

All acceptable answers:

  1. if using a “.” operator, make sure to assign to a variable, should help with the search process
  2. use local variables instead of global variables
  3. using map() if possible
  4. list comprehension
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Why is list comprehension faster than a for loop?

A

List comprehension is faster because it is optimized for the Python interpreter to spot a predictable pattern during looping

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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()

A
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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly