#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    2
    Rep Power
    0

    Printing Triangular Numbers


    Hi, i have a wrote a program with the code:

    def triangle(n):
    if n<=0:
    return 0
    else:
    return n+triangle(n-1)

    To print triangular numbers such as 1,3,6,10..etc.
    But im not too sure how im meant to print the actual numbers? Could anybody give me a hand? Thank you
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,837
    Rep Power
    480
    Code:
    def triangle(n):
        return n*(1+n)//2
    
    for n in range(10):
       print('{} {}'.format(n,triangle(n)))
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    606
    Rep Power
    65
    You could do it this way ...
    Code:
    def triangle(n):
        if n <= 0:
            return 0
        else:
            return n + triangle(n-1)
    
    for n in range(1, 16):
        print("%2d --> %d" % (n, triangle(n)))
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Posts
    475
    Rep Power
    33
    IMHO a for() loop is easier.
    Code:
    num=0
    
    for x in range(1, 5):
       num += x
       print num
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    114
    Rep Power
    3
    Code:
    from itertools import accumulate
    print(*accumulate(range(1, 10)), sep=", ")
    Last edited by Nyktos; February 22nd, 2013 at 12:47 PM.

IMN logo majestic logo threadwatch logo seochat tools logo