Ky1p
Ky1p

Reputation: 9

Can someone explain to me how this function using sum works?

def no_six_in_range(start, end):
    print(sum('6' not in str(i) for i in range(start, end + 1)))

no_six_in_range(6, 12)

"The sum() function returns a number, the sum of all items in an iterable."

So my question is, how would the sum work in this equation as sum adds the iterables together. But when you run the code it gives a lower number than the numbers given. If someone could explain this to me, it would be much appreciated.

Upvotes: 0

Views: 162

Answers (3)

Arjun Ghosh
Arjun Ghosh

Reputation: 161

According to the python documentation,

5.1.3. List Comprehensions List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

The list comprehension evaluvates to a list, which like the sum funtion states, is an iterable.

The syntax is generally:

l = [ iterator for iterator in iterable ]

eg:

my_list_comprehension = [ i for i in range(10) ]

Note that the first iterable and the second iterable can be different, so [ a for a in ARRAY ] and [ b for a in ARRAY ] both work as long as b is defined

In this case, the code actually uses a Generator comprehension, which generates a generator instead of a list. A generator can also be iterated. The syntax for the generator comprehension is the same as that of a list, except that the [] is substituted for ().

So the

'6' not in str(i) for i in range(start, end + 1)

appends ( '6' not in str(i) ) to the generator as i goes through range(start, end + 1)

As the other answers explain, You can print out the arguments to figure out whats going on, like so: Testing the values with the interpreter

And finally an array of booleans is converted by sum into integers and then added.

More info about generators in python.

Upvotes: 0

Talha Tayyab
Talha Tayyab

Reputation: 27665

if you run this code:

def no_six_in_range(start, end):
    print(list('6' not in str(i) for i in range(start, end + 1)))

no_six_in_range(6, 12)

you get:

[False, True, True, True, True, True, True]

so, if you sum them you will get 6 as each True is 1 and False is 0

Upvotes: 2

user2390182
user2390182

Reputation: 73470

This just counts numbers without any digit "6". Note that the iterable here is the entire generator expression expr_a for expr_b in expr_c. The values that are being summed here (expr_a)

'6' not in str(i) 

are bool values (True or False). bool is a subclass of int, so summing over them is summing over a bunch of 1s and 0s.

Compare e.g.:

>>> True + True
2

Upvotes: 5

Related Questions