Search code examples
pythonlistfunctiontuplespseudocode

Python pass tuple in function argument


I'm trying to convert this code to python

function foo(int[] x, int a, int b, int i, int j) returns int
    int k = j
    int ct = 0
    while k > i-1
        if x[k] <= b and not (x[k] <= a)
            ct = ct + 1
        end
        k = k - 1
    end
    return ct
end

int[] x = [11,10,10,5,10,15,20,10,7,11]
print(foo(x,8,18,3,6))
print(foo(x,10,20,0,9))
print(foo(x,8,18,6,3))
print(foo(x,20,10,0,9))
print(foo(x,6,7,8,8))

Convert to python:

import pandas as pd

def foo(*x,a,b,i,j):
    ct = 0
    for k in x:
        k = j,
        ct = 0,
        while k > (i-1):
            if x[k] <b and ~(x[k]<=a):
                ct = ct+1
            else:
                k = k-1
    return ct

x = (11,10,10,5,10,15,20,10,7,11)

I see that int[] x in the first code converted to tuple in python. however I'm stuck with code conversion when passing tuple as argument in the function foo.


Solution

  • end of line k=j, you use ',' this code convert k to tuple and you get error in while k > (i-1) because you check tuple with int.

    I convert to python like below:

    def foo(x, a, b, i, j):
        k = j
        ct = 0
        while k > i-1:
            if x[k] <= b and not (x[k] <= a):
                ct = ct + 1
            k = k - 1
        return ct
    
    x = (11,10,10,5,10,15,20,10,7,11)
    
    print(foo(x,8,18,3,6))
    print(foo(x,10,20,0,9))
    print(foo(x,8,18,6,3))
    print(foo(x,20,10,0,9))
    print(foo(x,6,7,8,8))
    

    output:

    2
    4
    0
    0
    1