Python Forum
coding help lists, loops, and if statement
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
coding help lists, loops, and if statement
#1
My problem asks me to write a program to find all the divisors of a number. What I have done so far I realize is of target from that goal however there is part of this code that does not act as I want.

Inline 18 I have an if statement that is supposed to put x into a list if the check inline 17 is equal to 0. However, it only does that only 1 time after which the if statement lets through any number into the list decreasing by 1.

number = int(input("Enter a number for which you want to know all the divisors  "))
divisors = []
i = number
list = range(0, (number + 1))
check = list[number] % 2
if check != 0:
    print(str(number) + " does not have any divisors")
else:
    while i > 0:
        print("The list char")
        print(list[i])
        print("The i char")
        print(i)
        x = list[i] / 2
        print("The x value")
        print(x)
        check = list[i] % 2
        if check == 0:
            divisors.append(x)
        i -= 1
    print("The divisors of " + str(number) + " are: " + str(divisors))
Reply
#2
Some observations:

Never use 'list' as name. This will happen:

>>> list('abc')
['a', 'b', 'c']
>>> list = [1, 2, 3]
>>> list('abc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
When defining range no need define zero, it's default:

>>> help(range)
Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |  
 |  Return an object that produces a sequence of integers from start (inclusive)
 |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
 |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
 |  These are exactly the valid indices for a list of 4 elements.
 |  When step is given, it specifies the increment (or decrement).
/.../
What is your idea how to find divisors? You testing if number is even and if it's not then you print out 'does not have any divisors'. Is it really so? 9 % 2 --> 1 but clearly there is divisor 3. You should define your idea in spoken language and then implement it in Python.
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
#3
When I was writing that code I thought that divisors were whole numbers that resulted from continues dividing a number by 2. For instance 8. Under my logic, it would have divisors of 4, 2, and 1. Or if I have 18 it would have the divisors of 9. I realize now that is incorrect, however, the issue of my code remains. Under the above logic if I put in 8 into my code I should be getting back [4, 2, 1], however, I am getting back [4, 3, 2, 1].
Reply
#4
Just to take ambiguity out of terminology: divisor.

To work out solution there are some hints:

- every number divides with 1 and itself --> no need to check those
- there can't be bigger divisor than half of number --> look for divisors in range up to num / 2
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
#5
My new code:
number = int(input("Enter a number for which you want to know all the divisors  "))
divisors = []
pdiv = range(1, number + 1)
i = number
while i >= 1:
    check = number % i
    if check == 0:
        divisors.append(i)
    i -= 1
print(str(divisors) + " are the divisors of " + str(number))
Reply
#6
Observations:
  • This code is brute-force as it looks for divisors in range (larger than half on number) where there can't be divisors.
  • There is no need for row pdiv = range(1, number + 1) as it's never used
  • There is no need for renaming 'number' --> 'i'. One can use 'number' directly
  • Use for-loop instead on while-loop (let Python keep count)

One can make code more effective and concise:

number = int(input('Enter a number for which you want to know all divisors: '))
divisors = [1]                             # 1 is divisor of all natural numbers
for divisor in range(2, number // 2 + 1):  # we look for divisors only up to half of entered number  
    if number % divisor == 0:              # or 'if not number % divisor:'
        divisors.append(divisor)
else:                                      # no-break
    divisors.append(number)                # natural number is always divisor of itself
For life-like scenarios one can add handling situations when user enters 0 or negative number (in mathematics negatives considered numbers) and input validation (accept only integers and not characters etc).

There are further ways to make this more efficient. For example - there is no point of checking of even divisors if number is odd (one can reduce checks by half in case of odd numbers)

EDIT: regarding printing out

>>> print(str(divisors) + " are the divisors of " + str(number))           
[1, 2, 5, 10] are the divisors of 10
This is not very 'pretty' for human eyes. If using 3.6 <= Python then one can take advantage of f-string:

print(f'The divisors of {number} are {", ".join(str(num) for num in divisors)}')                                                              
The divisors of 10 are 1, 2, 5, 10
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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,360 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,252 Mar-20-2019, 08:01 PM
Last Post: stillsen
  Problems with For Loops and Lists Sagramor72 2 2,175 Mar-04-2019, 01:26 PM
Last Post: Sagramor72

Forum Jump:

User Panel Messages

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