0

I want to program this function from C to Python but the condition on the return is hard to convert:

In C:

int pos(int b) {
    char *r = strchr(a, b);
    return r?(r - a):-1;
}

Here what I tried:

def pos(b) :
    r = alphabet[a.rfind(b):]
    return r if (r - len(a)) else -1

The r variable is the same but the problem is the ternary operator. So of course, it doesn't do the same work :/ Can you help me?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Alpacah
  • 39
  • 8

2 Answers2

7

The Python ternary operator goes in a different order than the C ternary operator. The C ternary operator is in the form:

condition ? expr_if_true : expr_if_false

Whereas the Python version of this is in the form:

expr_if_true if condition else expr_if_false
0
return r?(r - a):-1;

Is the same as

if (r != NULL) return r - a;
else           return -1;
pmg
  • 106,608
  • 13
  • 126
  • 198