Day 10 of 10: IngressiveForGood Data Structures and Algorithm

Day 10 of 10: IngressiveForGood Data Structures and Algorithm

Woohoo!!!

I made it to the final day. Phew, it took a lot of consistent consistency and belief in myself to get this far. At a point, I felt I was wayyyyy over my head but I didn't give up and I sure am glad.

To wrap it up, we were given a task to validate a number.

A valid number can be split up into these components (in order):

  1. A decimal number or an integer.
  2. (Optional) An 'e' or 'E', followed by an integer.

A decimal number can be split up into these components (in order):

  1. (Optional) A sign character (either '+' or '-').
  2. One of the following formats:
  3. One or more digits, followed by a dot '.'.
  4. One or more digits, followed by a dot '.', followed by one or more digits.
  5. A dot '.', followed by one or more digits.

An integer can be split up into these components (in order):

  1. (Optional) A sign character (either '+' or '-').
  2. One or more digits.

For example, all the following are valid numbers:

["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"].

Instructions

Given a string s, return true if s is a valid number.

TestCase

Input: s = "0"
Output: true

My Solution

At first, I thought of using multiple nested if-elif statements but the conditions were just too many. Thinking of how to combine some patterns into nested conditions reminded me of how I could achieve the same result with regex.

I had to go back to the site where I first learned regex to refresh and carefully came up with a regex expression to handle all the conditions. It was very tricky and took quite a while. But when I finally got the right expression, I wrote one if statement which returned true if there was a match.

This used up 13.9Mb and seeing that there were submissions that used up less, I tried to modify the code to use up less space. I removed the if statement and used a re.match(instead of re.search) which returns True if there is a match and False otherwise. Then, I removed the pattern variable I had created and passed the whole regex pattern directly in the return statement.

However, this didn't take up any less space than the previous code, it only made it faster and more compact and I couldn't think of another way to modify the code. If you do know a way, I wouldn't mind learning from you! Just drop a comment...

day 10 submission.PNG

And that's all for I4G 10DaysofCodeChallenge.

It's been a fun and educative ten days. I hope to engage in more challenges in the future.

Thank you IngressiveForGood(I4G) for a good time coding and learning.

If you would love to be a member of I4G, I'd love to show you how! Hit me up.