Reputation: 41
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
.
Upvotes: 1
Views: 2423
Reputation: 5935
You already have an accepted answer, but sometimes it is useful to make everything a bit simpler to understand by using a pythonic way to write the function.
"We want to count (sum up) the number of elements of x
between indices i
and j
which are greater than a
and less than or equal to b
", thus becomes:
from typing import Sequence
def foo(x: Sequence[int], a: int, b: int, i: int, j: int) -> int:
return sum(a < v <= b for v in x[i:j])
Upvotes: 1
Reputation: 12159
If possible, don't use positional arguments with larger amount of args, instead use kwargs e.g. foo(x=(1,2,3), a=4, b=5, i=6, j=7)
if you intend to mix them or split it into positionals that are obvious and keyword-based which are not or do not follow the same types (tuple for you) otherwise it's just a matter of time until you swap the args or cause a different type of mess by unpacking the values incorrectly.
For example:
def foo(a: int, b: int, /, values: tuple, length: int = 1, start: int = 0) -> int:
k = start
ct = 0
while k > length - 1:
if x[k] <= b and not (x[k] <= a):
ct = ct + 1
k = k - 1
return ct
/
splits the positional-only (a
, b
because I couldn't really figure out what do they mean in that func) and optionally-keyword arguments which can be passed as positionals as well:
foo(100, 200, values=(9, 8, 7), length=1, start=0)
# 0
foo(100, 200, (9, 8, 7), 1, 0)
# 0
Also, Python doesn't enforce the types, so in case your code relies on that, use MyPy
for static analysis and ensure.ensure_annotations
decorator for dynamic one (e.g. in tests or in the app).
Upvotes: 2
Reputation: 24049
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
Upvotes: 2