patternpythonCritical
Using separate functions for Project Euler 1
Viewed 0 times
separateprojectforusingeulerfunctions
Problem
I started programming with Java and C++, so I'm used to having a 'main' function that calls other functions that do the actual work. At university I was always told that doing actual computation in the main function is bad practice. I'm currently playing around with Python, and I have trouble figuring out how to write a nice 'main' function, especially since I'm doing small stuff that doesn't need separate classes.
What do you think about the following code? Is the main function necessary, or would you just write everything without functions? Is there a general consent on this in the Python world?
What do you think about the following code? Is the main function necessary, or would you just write everything without functions? Is there a general consent on this in the Python world?
# Finds sum of all multiples of 3 and 5 from 0 to 999
def find_multiples():
global numbers
for i in range(0,1000):
if i%3==0 or i%5==0:
numbers.append(i);
numbers = []
if __name__ == '__main__':
find_multiples()
print sum(numbers)Solution
Here's some superficial review. More for testing the site and some comment formatting than anything, but: do create main functions (helps us benchmarkers a lot) and do think that your module can be imported, so docstrings and local variables help.
# Finds...
###-^ Put this in a docstring
def find_multiples():
"""Finds sum of all multiples of 3 and 5 from 0 to 999 """
###-^ This allows you to "from x import find_multiples, help(find_multiples)"
numbers = []
###-^ Avoid globals
for i in xrange(1000):
###-^ Use xrange if Python 2.x, no need to start at 0 (it's the default)
if not (i % 3) or not (i % 5):
###-^ Add spaces around operators, simplify
###-^ the boolean/numeric checks
numbers.append(i)
###-^ Remove trailing ;
return numbers
###-^ Removed global
def main():
###-^ Allows calling main many times, e.g. for benchmarking
numbers = find_multiples()
print sum(numbers)
if __name__ == '__main__':
main()Code Snippets
# Finds...
###-^ Put this in a docstring
def find_multiples():
"""Finds sum of all multiples of 3 and 5 from 0 to 999 """
###-^ This allows you to "from x import find_multiples, help(find_multiples)"
numbers = []
###-^ Avoid globals
for i in xrange(1000):
###-^ Use xrange if Python 2.x, no need to start at 0 (it's the default)
if not (i % 3) or not (i % 5):
###-^ Add spaces around operators, simplify
###-^ the boolean/numeric checks
numbers.append(i)
###-^ Remove trailing ;
return numbers
###-^ Removed global
def main():
###-^ Allows calling main many times, e.g. for benchmarking
numbers = find_multiples()
print sum(numbers)
if __name__ == '__main__':
main()Context
StackExchange Code Review Q#7, answer score: 55
Revisions (0)
No revisions yet.