Deepanshu Sagar - 1 year ago 90

Python Question

please help me with this:

Is Fraction

Create a function is_fraction that accepts a string and returns True

if the string represents a fraction.

By our definition a fraction consists of:

An optional - character

Followed by 1 or more digits

Followed by a /

Followed by 1 or more digits, at least one of which is non-zero (the

denominator cannot be the number 0).

Tip

Modify the is_fraction function in the validation module.

Your function should work like this:

`>>> is_fraction("")`

False

>>> is_fraction("5000")

False

>>> is_fraction("-999/1")

True

>>> is_fraction("+999/1")

False

>>> is_fraction("00/1")

True

>>> is_fraction("/5")

False

>>> is_fraction("5/0")

False

>>> is_fraction("5/010")

True

>>> is_fraction("5/105")

True

>>> is_fraction("5 / 1")

False

This is what I've got so far:

`def is_fraction(string):`

"""Return True iff the string represents a valid fraction."""

return bool(re.search(r'^-?[0-9]+\/[0-9]+$', string))

Answer Source

Right, you need your denominator to be a sequence of digits, at least one of which is not `0`

. This can be modeled using the regex `0*[1-9][0-9]*`

So your validation method now becomes:

```
def is_fraction(string):
"""Return True iff the string represents a valid fraction."""
return bool(re.search(r'^-?[0-9]+/0*[1-9][0-9]*$', string))
```