Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Tuples & Functions
#1
Hello, I'm on Problem 1 from this website: https://courses.cs.washington.edu/course...part1.html



The premise is simple, but I'm having difficulties with the syntax.

The objective is to build a function with two inputs, n & m, and returns the digits within n that are divisible by m.

For example, if n = 1234567 & m = 2, then the output would be 2, 4 & 6.

And for any 0's in n, it is always divisible and shown in the output.

For example, if n = 1500000 & m = 5, then the output would be 0 & 5.

Lastly, if m = 0, then the output will always be 0.

E.g., n = 22 & m = 0, output = 0.



My strategy is to allow n to be a tuple, and create a for loop that goes over each digit of n.
For each digit, it will be divided by m to see if it's divisible, but it'll first check to see if that digit is 0.
I haven't included what happens when m = 0, but what I have so far gives me a TypeError that 'int' object is not iterable.

   def count_divisible_digit(tuple(n), m):
        
        for i in n[i]:
            if value = 0:
                result.append(value)
            elif (value/m = int) and (value % m = 0):
                result.append(value)
            else:
                return null
        Print(result)
    def count_divisible_number(n, m):
        
        x=tuple(n)
        for i in len(x):
            if x[i] == 0:
                result.append(value)
            elif x[i] % m == 0 & x[i] != 0:
                result.append(value)
        return result
Reply
#2
I think I've found something online: Will keep you guys updated.

https://www.kite.com/python/answers/how-...0iteration.
Reply
#3
My solution. Open to recommendations.


    def count_divisible_number(n,m):
        
        x_list = []
        divisible = []
        returnable = []
       
        for digit in str(abs(n)):
            x_list.append(int(digit))
        
        print (x_list)
        
        #Converted the digits into a tuple :-) 
        
        #for each element of x_list, divide (%) it by m. If there are no remainders, then add element to divisible.  
        
        for value in x_list:
            if m == 0:
                return 0
            elif value % m == 0:
                divisible.append(value)
        
        print(divisible)
        
        print(len(divisible))
        
Reply
#4
Why do you separate getting the digits and processing the digits? Is there any reason you nead "x_list"?

Why are you converting the number to a string? Is there another way you can get the digits?
Reply
#5
I would suggest to check if m == 0 (and possibly return) at the top of the function, before doing anything else.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
One should always look for hints in assignment text. In this one there is prominently displayed hint:

Quote:There is a app function for that!

And also important information:

Quote:To receive full credit on this problem, you should avoid building up a string containing the digits of the number. Intead, you should solve this problem by manipulating the nunmber itself.

So if converting to string out of the question what should be 'function for that'? How can we get digits out of number? There are //, % operators and there is built-in function divmod() which combines them both.

One can loop with divmod() and get the digits.

Just for fun ('return 0 if divisor is 0 otherwise return sum of boolean values for digit in number divisible by divisor'):

def count_divisible_digits(num, divisor):
    if divisor == 0:
        return 0
    num = abs(num)
    def digits(num): 
        while num:
            num, digit = divmod(num, 10)
            yield digit
    return sum(digit % divisor == 0 for digit in digits(num))


assert (count_divisible_digits(650899, 3)) == 4
assert (count_divisible_digits(-204, 5)) == 1
assert (count_divisible_digits(24, 5)) == 0
assert (count_divisible_digits(1, 0)) == 0
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
#7
Thank you for post. I was aware of the "hints" though they weren't very helpful to say the least.

In regards to your code, I'm having difficulty understanding the def digits(num) function.

def digits(num): 
        while num:
#while num is true?
            num, digit = divmod(num, 10)
#From what I understand, this assigns the object num, digit as the quotient and remainder of num/10
            yield digit
#Gives out remainder for each iteration?

    return sum(digit % divisor == 0 for digit in digits(num))
#I'm mixed up between which digit is which -_-. 
Reply
#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


Forum Jump:

User Panel Messages

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