16/18...What am I doing wrong?


#1

My code :

threes_and_fives =[x for x in range(1,16)]
print filter(lambda x: x % 3==0 or x % 5==0, threes_and_fives)

My Answer:

[3, 5, 6, 9, 10, 12, 15]
None

But it says:

Oops, try again.
threes_and_fives contains 1, but shouldn't.


#2

put it this way

threes_and_fives = filter(lambda x: x % 3==0 or x % 5==0, [x for x in range(1,16)])
print threes_and_fives

they want the variable threes_and_fives to be the modified list because when they test using assert(or which ever way they do) the test what that variable contains


#3

could someone please take me through the syntax here? what is the computer doing with this code?
what does the x: after lambda mean?


#4

when you define function in python you write it as

def function_name(arguments): 
    #some statements with arguments
    #finally return something

the x in lambda analogous to the argument you pass to normal functions. Lambdas are anonymous(function that don't explicitly have names)
when we say

lambda x: x % 3==0 or x % 5==0

think of it as x is our argument in this anonymous function followed by a rule lambda x: x % 3==0 or x % 5==0
and then we apply this rule to a list(i.e. this list [x for x in range(1,16)] )
the filter keyword does as it implies
filter the given list according to the rule(define by the lambda) and put it in the variable threes_and_fives

Read more here

Did this make sense?


#5

You don't need the lambda to do this. You only need:

threes_and_fives = [x for x in range(1,16) if x % 3 == 0 or x % 5 == 0]


#6

Agree with datasurfer75320 you don't need lambda at all. The trick is putting the if statement behind the range part:

threes_and_fives = [x for x in range(1,16) if x % 3 == 0 or x % 5 == 0]

print threes_and_fives

Hope that helps


#7

You can always do it the long way, but I guess that's not the point here.
Anyway, here is how I done it the first time:

threes_and_fives = []
for x in range (1,16):
if x % 3 == 0 or x % 5==0:
threes_and_fives.append(x)
print threes_and_fives


#8

I did it a slightly longer way, I didn't even use range. Here's my code

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
threes_and_fives = []
for number in x:
    if number % 3 == 0 or number % 5 == 0:
        threes_and_fives.append(number)
print threes_and_fives

#9

list = [x for x in range(1, 16)]

three_and_fives = filter(lambda x: x % 3 == 0 or x % 5 ==0, list)

print three_and_fives

is not working. somehow the system only accept certain code


#10

threes_and_fives = [x for x in range(1,16) if (x%3)*(x%5) == 0]