Python Forum
LCM with recursion ( least common multiple)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
LCM with recursion ( least common multiple)
#1
When i run this code python shell shows nothing

in '2.txt' 2 numbers " 21,53"
# least common multiple
def lcm(a,b):
 with open('2.txt') as f:
    a, b = [int(x) for x in next(f).split(',')]
    array = [[int(x) for x in line.split(',')] for line in f]
    m = a*b
    while a != 0 and b != 0:
        if a > b:
            a %= b
        else:
            b %= a
    return m // (a+b)

 print("a=%d ; b=%d ; LCM=%d"%(a,b,lcm(a, b)))
Reply
#2
With 1 change your code runs well:

#!/usr/bin/python3
def lcm(a,b):
    m = a*b
    while a != 0 and b != 0:
        if a > b:
            a %= b
        else:
            b %= a
    return m // (a+b)

with open('2.txt') as f:
    a, b = [int(x) for x in next(f).split(',')]

print("a=%d ; b=%d ; LCM=%d"%(a,b,lcm(a, b)))
Reply
#3
That's because you never call your function. Your print statement is indented under the function. That may be because you are using only a one space indent for the first indent, which makes it hard to see the indent. However, if you unindent that, you'll get an error, because a and b are not defined in the global namespace. It's not clear why you have parameters, if you are going to read them from a file, and thus discard whatever was passed to the function. You also would want to read from a file for recursion, because you would be realoading the values every time you recursed, leading to an infinite recursion. Although, despite the title you are not actually recursing here, so I'm not sure what is up with that.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
thanks, but our teacher said that reading from file must be in function before return
Reply
#5
Ok, then reorder the code yourself.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  GCF function w recursion and helper function(how do i fix this Recursion Error) hhydration 3 2,521 Oct-05-2020, 07:47 PM
Last Post: deanhystad
  Least Common multiple python minko 5 2,622 Aug-18-2020, 02:54 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020