Thread: Python to C++ ?

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

    Join Date
    May 2013
    Posts
    1
    Rep Power
    0

    Python to C++ ?


    Hello guys !

    Is there any guru out there that could help me translating this piece of python code to C++ ?

    def ruleAsc(n):
    a = [0 for i in range(n + 1)]
    k = 1
    a[0] = 0
    a[1] = n
    while k != 0:
    x = a[k - 1] + 1
    y = a[k] - 1
    k -= 1
    while x <= y:
    a[k] = x
    y -= x
    k += 1
    a[k] = x + y
    yield a[:k + 1]

    Thank you very much !!
  2. #2
  3. Contributing User

    Join Date
    Aug 2011
    Posts
    5,305
    Rep Power
    505
    First of all, the source indentation is part of python syntax; it delimits the blocks. Please follow the instructions at my signature for your future python posts.

    Next, the piece of code is a generator, meaning it needs to preserve state. We can do this with static variables. It will also need set up and clean up calls. You'll to also change the way the code is used. Thus, I'll translate more python than you requested. The code might be made more efficient if you also showed how it's used.

    I'm not going to finish. Enough of your homework.
    Code:
    /*
    #$ python3 p.py
    #[1, 1, 1]
    #[1, 2]
    #[3]
    
    def ruleAsc(n):
        a = [0 for i in range(n + 1)]
        k = 1
        a[0] = 0
        a[1] = n
        while k != 0:
            x = a[k - 1] + 1
            y = a[k] - 1
            k -= 1
            while x <= y:
                a[k] = x
                y -= x
                k += 1
            a[k] = x + y
            yield a[:k + 1]
    
    for i in ruleAsc(3):
        print(i)
    */
    {{
        a = calloc(n+1, sizeof(int));
        if (NULL == a)		// memory fault
          exit(1);
        N = n, k = 1, a[1] = n;
        return NULL;
    
    #include<stdio.h>
    #include<stdlib.h>
    
    int*ruleAsc(int n) {
      // setup: call with positive n
      // clean up: call with negative n
      // get next value: call with n == 0
      // returns NULL when done or invalid use
      static int
        *a = NULL,
        *result = NULL,
        k, N, x, y;
      if (NULL != result) // differs from python behavior.  python uses reference counted garbage collection.
        free(result);
      if (0 < n)
        if (NULL != a) {
          free(a);
          return NULL;
        }
      if (0 == n) {
    
    }
    
    int main() {
    }
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo