Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Tuples & Functions
#8
This is generator function i.e it emits values. In this case it yields digits in num from end:

 def digits(num): 
        while num:                        # while num value is truthy i.e. not 0*
            num, digit = divmod(num, 10)  # num is quotient, digit is reminder
            yield digit                   # yield digit

# list(digits(427)) -> [7, 2, 4]
This generator function (digits) is enclosed in function count_divisible_digits. Enclosing function does something before and after digits function. Before divisor is checked and num is assigned absolute value; then generator function for emitting digits is defined and after that enclosing function calls digits from generator and calculates sum of divisible digits.

Re 'mixed up': code in spoken language: 'give me boolean value of divisibility for every digit in num' (sum(digit % divisor == 0 for digit in digits(num))). This is generator expression inside sum which is often referred as 'generator comprehension' due to similarity to list comprehension.

Boolean values are subclass of int and can be used for calculations.

>>> type(True)
<class 'bool'>
>>> type(True).mro()        # method resolution order
[<class 'bool'>, <class 'int'>, <class 'object'>]
>>> True == 1
True
>>> False == 0
True
>>> True + True
2
* Documentation > The Python Standard Library > Built-in Types > Truth Value Testing
nman52 likes this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
Tuples & Functions - by nman52 - Nov-09-2020, 12:27 AM
RE: Tuples & Functions - by nman52 - Nov-09-2020, 01:16 AM
RE: Tuples & Functions - by nman52 - Nov-09-2020, 03:00 AM
RE: Tuples & Functions - by deanhystad - Nov-09-2020, 04:00 AM
RE: Tuples & Functions - by buran - Nov-09-2020, 05:03 AM
RE: Tuples & Functions - by perfringo - Nov-09-2020, 09:35 AM
RE: Tuples & Functions - by nman52 - Nov-14-2020, 10:50 AM
RE: Tuples & Functions - by perfringo - Nov-14-2020, 07:36 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020