New course! Every coder should learn Generative AI!
Try a free lesson+ 5
Can you please explain the output of this code?
def chek(x): if x%3==0: return False; return True; a = sum([i for in range(6) if chek(i)]); print(a)
7 Answers
+ 5
The chek() function checks if the given number is not divisible by 3 (returns False if x is divisible by 3 and True otherwise).
[i for i in range(6) if chek(i)] creates list from numbers 0, 1, 2, 3, 4, 5 (range(6)) filtering them through function chek() (numbers that are not divisible by 3).
The list will be [1, 2, 4, 5]
sum returns the sum of that numbers 1+2+4+5 = 12
print outputs the result.
Bur your code will not compile because you forgot to put i between "for" and "in"
line
a = sum([i for in range(6) if chek(i)]);
should be:
a = sum([i for i in range(6) if chek(i)]);
+ 5
The explanation is in the code
https://code.sololearn.com/cRr8WXlW2C5G/?ref=app
+ 4
WhyFry Yes but can you explain?
+ 4
The Sylar yes but what that return True and False doing there with different indentation?
+ 3
def chek(x):
if x%3==0:
return False;
return True;
b = sum([i for i in range(6) if chek(i)])
print(b)
About the above code in short
if the number in the range(6) have a zero remainder on dividing with 3 (Basically a multiple of 3) then it is not added in the list because the function chek(i) will return False for that.
So the list will be
b = [1, 2, 4, 5]
b = sum([1, 2, 4, 5]) gives 12
Basic maths... Just add all elements
+ 2
Search 'list comprehension'.
Basically, from range 0 to 5, it check which number is not divisible by 3.
So they will be 1,2,4,5.
And sum of them is 12.
That is ! :)
+ 2
chek(0) will get false, right?
So a will become:
a = [i for i in range(6) if false]
So, 0 will not be inserted because 'if' statement is false.
So do the 3.
But 1,2,4,5 will be included in the list because 'if' statement become true from chek(1 or 2 or 4 or 5).
Hope it's clear now.