0
def pyg(n):
    n=int(n)
    for i in range(1,n):
        a=(2*i)+1
        b=(2*i)*(i+1)
        c=(2*i)*(i+1)+1
        return(a,b,c)

When i try to run this on Shell using pyg(100) I only get output (3, 4, 5). What might be the problem all the triplets are not generating.

awesoon
  • 32,469
  • 11
  • 74
  • 99

3 Answers3

0

The return sentence. Change it for a yield. If you want to test it, you could:

>>> pygs = pyg(100)
>>> next(pygs)
(3, 4, 5)
>>> next(pygs)
.
.
.
jgomo3
  • 1,153
  • 1
  • 13
  • 26
0

Your function produces only one pair, because return interrupts function execution. You could use yield keyword, as suggested by @jgomo3, or map function:

def generate_triplet(n):
    a=(2*n)+1
    b=(2*n)*(n+1)
    c=(2*n)*(n+1)+1
    return(a,b,c)

def pyg(n):
    return map(generate_triplet, range(1, int(n))
Community
  • 1
  • 1
awesoon
  • 32,469
  • 11
  • 74
  • 99
0

As many others pointed out, when the return statement executes, your function will finish, and will not continue looping. However, you have options for returning multiple values from a single function. For example aggregating your values in a list and return that, or to use the yield keyword instead of return. The yield keyword will make your function a generator function, which returns an iterable generator object with all your expected elements.

I advise you to split your code into separate functions, so you have the original formula as a function of i, and a generator function which will return the elements for 1 <= i < n. Note that you can collect the elements of a generator to a list by supplying it to the list constructor.

def pyg(i):
  a = (2*i) + 1
  b = (2*i) * (i+1)
  c = (2*i) * (i+1) + 1
  return (a,b,c)

def pygs(n):
  for i in range(1, n):
    yield pyg(i)

print(list(pygs(10))) # prints the first 9 Pythagorean triplet as a list of tuples
Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97