[Problem 5] For Loop does not seem to work

For questions about problems on the Project Euler web site. No spoilers. Please include the question number in the subject line of your post.

[Problem 5] For Loop does not seem to work

hi,

i was trying to solve problem 5 using a gcd and lcm function and a for loop to iterate the lcm (yes, i'm a beginner). However, the loop does not seem to work and the output is always equal to 1. What do I do wrong? I'm using the python 3.4.1 shell
Code: Select all
from fractions import gcd

def lcm(a,b):
return int((a*b)/gcd(a,b))

def problem(n):
for i in range(1,n):

print(problem(10))
Last edited by Yoriz on Wed Jul 09, 2014 8:24 pm, edited 1 time in total.
Reason: First post lock, Added code tags.
eef

Posts: 2
Joined: Wed Jul 09, 2014 8:12 pm

Re: [Problem 5] For Loop does not seem to work

If you put a print inside your loop before the return
Code: Select all
from fractions import gcd

def lcm(a, b):
return int((a * b) / gcd(a, b))

def problem(n):
for i in range(1, n):
print 'value of i inside loop:', i

print(problem(10))

Youll see that the resulting output is
Code: Select all
value of i inside loop: 1
1

your loop is only managing to loop once before it returns, can you see why it returns without carrying on the rest of the loop before it returns the result.
Due to the reasons discussed here we will be moving to python-forum.io/ on October 1 2016
This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.

Yoriz

Posts: 1672
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: [Problem 5] For Loop does not seem to work

I understood that, however, I could not see from your comment how to fix it.

However, removing four spaces before "return answer" did the job, and the code is now working fine.
eef

Posts: 2
Joined: Wed Jul 09, 2014 8:12 pm

Re: [Problem 5] For Loop does not seem to work

Yoriz wrote:your loop is only managing to loop once before it returns, can you see why it returns without carrying on the rest of the loop before it returns the result.

The hints where there as the indentaion of your return was incorrect making it return on the first iteration of the loop.
Its better that you worked out how to solve it on your own though, well done.
Due to the reasons discussed here we will be moving to python-forum.io/ on October 1 2016
This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.

Yoriz

Posts: 1672
Joined: Fri Feb 08, 2013 1:35 am
Location: UK