133k views
3 votes
PythonFunction Name: doublesParameters: list of int Returns: list of intDescription: Write a function, doubles, that takes a list of integers and finds values in the list that are exactly twice the previous integer in the list. Return a list of integers from the parameter that meet the criteria specified.Sample Inputs/Outputs:Example Call: doubles([1, 2, 4, 3, 6])Expected Return: [2, 4, 6]Example Call: doubles([3, 0, 1, 2, 3, 6, 2, 4, 5, 6, 5])Expected Return: [2, 6, 4]

User Vodet
by
8.1k points

1 Answer

7 votes

Answer:

def doubles(ls):

new = []

for i in ls:

for a in ls:

if (i == a*2) and (i not in new) and i != 0:

new.append(i)

break

return new

ls = [3, 0, 1, 2, 3, 6, 2, 4, 5, 6, 5]

print(doubles(ls))

Step-by-step explanation:

The code is written in python.

The function doubles is created and it has one parameter.

In the function, a new list is created to hold the values that are exactly twice the previous integer in the list.

Two nested for loops are used with an if statement to achieve the desired result. The first FOR loop gets a number from the list entered by the user and holds that number while it waits for the second for loop and the if statement. The second FOR loop, iterates through all the elements in the list and compares them with the number being held by the first for loop through the IF statement.

The IF statement checks 3 things:

  • if the first number is x2 the second
  • if it is not already contained in the list
  • if the number is not zero

All these conditions must pass as True before the number is appended to the new list.

The break statement is there to ensure that the loop does not start evaluating unnecessary conditions, so when a match is found for one element the second loop breaks thereby allowing the first FOR loop to move to the next number.

Finally, the new list is returned and the function is called.

I have attached a picture of the result.

PythonFunction Name: doublesParameters: list of int Returns: list of intDescription-example-1
User Jlengrand
by
9.2k points