First, we ask, do the two routines produce the same output? Yes.

Second, is the output correct? No.

Here's the code I used to test sameness. It produces files nf1 and nf2 which I compared with unix cmp command. You can see that I merely changed the input to pass in as an argument. And I used the dirty trick to reassign sys.stdout. See code. And I spot checked values "num" in range(1000,1100).
Code:

def num_facs1(num):
factors = 1
numbers = []
for every in range(1, num + 1):
if num % every == 0:
factors += 1
numbers.append(every)
if factors == 1:
print('{0} is a prime number and it has {1} factor:'.format(num, factors))
elif factors > 2:
print('{0} is a composite number and it has {1} factors:'.format(num, factors))
else:
print('{0} is a prime number and it has {1} factors:'.format(num, factors))
for each in numbers:
print(each)
# Code #2
def num_facs2(num):
factors = 1
for every in range(1, num + 1):
if num % every == 0:
factors += 1
if factors == 1:
print('{0} is a prime number and it has {1} factor:'.format(num, factors))
elif factors > 2:
print('{0} is a composite number and it has {1} factors:'.format(num, factors))
else:
print('{0} is a prime number and it has {1} factors:'.format(num, factors))
factors = 1
for every in range(1, num + 1):
if num % every == 0:
factors += 1
print(every)
import sys
with open('nf1','w') as nf1:
with open('nf2','w') as nf2:
for i in range(1000,1100):
sys.stdout = nf1
num_facs1(i)
sys.stdout = nf2
num_facs2(i)

Using j, from www.jsoftware.com executable Iverson notation I found the factors of 1000, the tally of these factors, and the next prime number exceeding 1050.
Code:

factors NB. definition of j factors verb
[: ([: /:~ [: */"1 ([: x: [) ^"1 [: > [: , [: { [: <@:i.@>: ])/ __ q: ]
factors 1000 NB. get the factors of 1000
1 2 4 5 8 10 20 25 40 50 100 125 200 250 500 1000
#factors 1000 NB. tally of the factors of 1000
16
[&.(p:^:_1)1050 NB. next prime number greater than 1050
1051

Now, what are the results from num_facs ? I see an "off by 1" error. Reporting 1051 as composite is a blunder.
Code:

1000 is a composite number and it has 17 factors:
1
2
4
5
8
10
20
25
40
50
100
125
200
250
500
1000
1001 is a composite number and it has 9 factors:
1
7
11
13
77
91
143
1001
1002 is a composite number and it has 9 factors:
...
1050 is a composite number and it has 25 factors:
1
2
3
5
6
7
10
14
15
21
25
30
35
42
50
70
75
105
150
175
210
350
525
1050
1051 is a composite number and it has 3 factors:
1
1051
1052 is a composite number and it has 7 factors:
...

Even for trivial problems, the policy is "don't bother timing incorrect programs". I suggest using the timeit module if you want to compare run time.

Tweet This+ 1 thisPost To Linkedin