# Extending piecwise to 2 variables (or a variable and a parameter)

This piecewise function work correctly

score =  piecewise([([i,i], ncand - i) for i in range(ncand)])


because ncand is defined earlier in my notebook. when I typeset say score(1) It returns what I expect. But I would like that ncand be a variable.

edit retag close merge delete

score can only be evaluated in the integers $0, 1, 2,...,\mathtt{ncand}-1$ and, in fact, $\mathtt{score}(i)=\mathtt{ncand}-i$. Is it intended? Anyway, if you have something like

ncand = some value
score = piecewise(list of cases depending on ncand)


you can redefine score to depend on ncand as follows:

def score(x,ncand):
s = piecewise(list of cases depending on ncand)
return s(x)


But you answer is not self evident. Even short it ananswer not a comment.

Sort by » oldest newest most voted Define score as follows:

def score(x, ncand=10):
s = piecewise([([i,i], ncand - i) for i in range(ncand)])
return s(x)


Then you can use score as in the following examples:

sage: score(7)
3
sage: score(3, ncand=7)
4
sage: score(3,7)
4


Observe that, if omitted, the value of ncand is 10.

more

I was aware of the default mechanism. But in all cases thanks for uour answer.