Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

iHerzeleid

macrumors 6502a
Original poster
May 5, 2007
555
0
how can i get the list to print out like this (to a output file)

ex input: 10

2
5


def get_factor(x):
l = []
for i in range(1,((x + 2)/2)):
if (x%i == 0 and i!=1 and i!=x):
l = l +
return l

m = input ("Please enter a number greater than 2: ")
outfile = 'primes-'+str(m)+'.txt'
output = open (outfile, "w")



nn = get_factor(m)
nnn = (str(nn[1:]))

#for i in range(len(nnn)):
print "Found", len(get_factor(m)), "Numbers; please check the file primes-",m,".txt"
print nn
output.write (nnn)

output.close()

 

HiRez

macrumors 603
Jan 6, 2004
6,250
2,576
Western US
Code: PIMPED!

Code:
def get_factors(x):
	l = []
	for i in range(1, (x + 2) / 2):
		if (x % i == 0 and i != 1 and i != x):
			l = l + [i]
	return l
	
max_num = input("Please enter a number greater than 2: ")
out_file_name = "factors-" + str(max_num) + ".txt"
out_file = open(out_file_name, "w")

factors = get_factors(max_num)

print "Found " + str(len(factors)) + " numbers; please check the file " + out_file_name + "."
print factors
out_file.write("\n".join(map(str, factors)))
out_file.close()
Basically I'm using the string.join operator to join the list, but since join doesn't work with integers, I use the map function to turn each element of the list into a string first. Not sure if this is the most efficient method of going about it, but it works. Also notice I cleaned a few things up. In particular, you should really avoid calculating values and running functions more than once, as you were doing building the file name and then with the get_factors function, which could potentially be expensive.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.