I have not been able to solve this exercise, I would like to know the answer.
Write function doubles() that takes as input a list of integers and outputs the integers in the list that are exactly twice the previous integer in the list, one per line.
>>> doubles([3, 0, 1, 2, 3, 6, 2, 4, 5, 6, 5])
2
6
4
I am a beginner, try to solve the exercise as follows:
def doubles(lst):
for i in range(len(lst)):
if lst[i]%2 == 0:
print(lst[i])
doubles([3, 0, 1, 2, 3, 6, 2, 4, 5, 6, 5])
CodePudding user response:
The problem you're having is that you're missing the bit about doubling the previous entry in the list. So, we can make a couple modifications to your code to do this:
def doubles(lst):
for i in range(1, len(lst)):
if lst[i] == list[i - 1] * 2:
print(lst[i])
This works by comparing the current entry to the double the previous entry. Note, I've modified the range to start at one because you there's entry before the 0th one. If you're looking for a performance boost, you can replace the multiplication with a bit-shift:
def doubles(lst):
for i in range(1, len(lst)):
if lst[i] == list[i - 1] << 1:
print(lst[i])
Because integers are in binary, doing a bitshift (shifting each bit to the right by one) is the same as multiplying the value by two. This is much cheaper than multiplication at the processor level.
CodePudding user response:
def doubles(lst):
for i in range(len(lst)-1):
if lst[i 1] == 2*lst[i]:
print(lst[i 1])
doubles([3, 0, 1, 2, 3, 6, 2, 4, 5, 6, 5])
or this may also give a same style
CodePudding user response:
You need to keep track of 2 elements: the previous element and the current element. The previous element is represented by lst[i-1]
and the current element is represented by lst[i]
.
The range needs to start at 1 so you can retrieve the 0th element with lst[i-1], where i = 1, so lst[1-1] = lst[0] = 3. That is the previous element's value.
Then, check to see if the previous element * 2 is equal to the current element.
def doubles(lst):
for i in range(1, len(lst)):
if lst[i-1]*2 == lst[i]:
print(lst[i])
doubles([3, 0, 1, 2, 3, 6, 2, 4, 5, 6, 5])