[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

Postby eef » Wed Jul 09, 2014 8:18 pm

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):
        answer=1
        for i in range(1,n):
                answer = lcm(i, answer)
                return answer

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

Postby Yoriz » Wed Jul 09, 2014 8:24 pm

Welcome to the forum, please read the new users read this link in my signature.

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):
    answer = 1
    for i in range(1, n):
        answer = lcm(i, answer)
        print 'value of i inside loop:', i
        return answer

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.
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Image
User avatar
Yoriz
 
Posts: 1029
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

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

Postby eef » Wed Jul 09, 2014 9:22 pm

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

Postby Yoriz » Wed Jul 09, 2014 9:44 pm

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.
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Image
User avatar
Yoriz
 
Posts: 1029
Joined: Fri Feb 08, 2013 1:35 am
Location: UK


Return to Project Euler

Who is online

Users browsing this forum: No registered users and 0 guests