Loading [MathJax]/jax/output/HTML-CSS/jax.js
Ask Your Question
0

Boolean conditional function

asked 4 years ago

Cyrille gravatar image

I would like to construct a function with return the string "Vrai" or the string 'Faux' selon qu x>y ou x<=y. I have tried

cond(x, y)= if bool(x<y)='True' then Print("Accepté") else Print("Rejeté")

but it leads to an error

Preview: (hide)

Comments

Could you please edit the question to make it more consistent:

  • decide between Vrai/Faux vs Accepté/Rejeté
  • "a function with" -> "a function which"
  • selon que ... ou ... -> according to whether ... or ...
  • decide whether it's "x > y" or "x < y" that should be "accepted"
slelievre gravatar imageslelievre ( 4 years ago )

I am confused to be able to write such inconsistent english

Cyrille gravatar imageCyrille ( 4 years ago )

2 Answers

Sort by » oldest newest most voted
0

answered 4 years ago

tmonteil gravatar image

updated 4 years ago

To construct a function, you have to use def Python statement.

def cond(x, y):
    if x<y:
        print("Accepté")
    else:
        print("Rejeté")

EDIT given the comment, it seems that you do not want to only print the result, but you want the function to return the string. So, here it is:

def cond(x, y):
    if x<y:
        return "Accepté"
    else:
        return "Rejeté"

All this is pure Python. Let me suggest to read some introductions about this generic language, since Sage is based on it, and you will benefit a lot to make clever constructions out of Sage mathematical bricks.

Preview: (hide)
link

Comments

tmonteil thanks for your reactivity

Cyrille gravatar imageCyrille ( 4 years ago )

A subsequent consequence of your formula. I have an error with the following code

a=1
b=2 
c=3 
d=4
e=5
f=6
essay = [[cond(a,b)],[cond(c,d)],[cond(e,f)]]
table(essay,header_row=[r'A',r'B',r'C')

and when it works results are not displayed in the table

Cyrille gravatar imageCyrille ( 4 years ago )
0

answered 4 years ago

slelievre gravatar image

To complement @tmonteil's answer.

In some cases a lambda function is also okay.

It takes up less lines than a def function.

sage: cond = lambda x, y: "Accepté" if bool(x<y) else "Rejeté"

Then:

sage: a, b, c, d, e, f = [1 .. 6]
sage: essay = [[cond(a, b)], [cond(c, d)], [cond(e, f)]]
sage: hc = ['test', r'A', r'B', r'C']
sage: table(essay, header_row=['résultat'], header_column=hc)
  test | résultat
+------+----------+
  A    | Accepté
  B    | Accepté
  C    | Accepté
Preview: (hide)
link

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 4 years ago

Seen: 503 times

Last updated: May 06 '20