LeetCode: Add Two Numbers Python 3 iterative solution

[Problem Link]

Hello,

Here’s my solution for the add two numbers problem on LeetCode.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

When doing problems on websites such as LeetCode, I like to code in my own IDE, that’s why you’ll see some additional helper functions besides the solution code.

class Solution(object):
    def _get_append_func(self, root):
        _root = root
        def __add_to_list(value):
            nonlocal _root
            _root.next = ListNode(value)
            _root = _root.next
        return __add_to_list

    def _compute(self, result, base=10):
        carry = result // base
        rest = result % base
        return carry, rest

    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        root_node = None
        root_append_func = None

        term_1 = l1
        term_2 = l2
        saved_carry = 0
        while True:
            # end of expression ; add cary if any
            if term_1 is None and term_2 is None:
                if saved_carry > 0:
                    root_append_func(saved_carry)
                break

            # We haven't reached the end, we assume that whatever term is left is 0
            if term_1 is None:
                term_1 = ListNode(0)
            if term_2 is None:
                term_2 = ListNode(0)

            # add the two terms
            term_sum_carry, term_sum_no_carry = self._compute(term_1.val + term_2.val)

            # add sum to current carry
            next_carry, total_with_carry = self._compute(term_sum_no_carry + saved_carry)

            # save carry
            saved_carry = term_sum_carry + next_carry

            # save total
            if not root_node:
                root_node = ListNode(total_with_carry)
                root_append_func = self._get_append_func(root_node)
            else:
                root_append_func(total_with_carry)

            # move on
            term_1 = term_1.next
            term_2 = term_2.next

        return root_node

My solution isn’t that great because of the _add_to_list function which iterates the root_node to append the next value. I have no idea how to optimize that right now.

UPDATE:

I’ve learnt about nonlocal and found a way to slightly optimize my code:

    def _get_append_func(self, root):
        _root = root
        def __add_to_list(value):
            nonlocal _root
            _root.next = ListNode(value)
            _root = _root.next
        return __add_to_list

Thanks for reading!

Firebase REST Authentication

Hello,

In this article I will show you how to authenticate to Firebase and secure the databases with some simple security rules. I’m using this setup for my NucuCar project.

Authentication

The first step is to enable the Email/Password sign in method, by going to the Authentication and clicking the Sign-In Method tab:

Next, we can add a manual user by clicking Users tab and Add user.

Now, to login with our newly created user, we make a POST request with a json body to the following endpoint:

// POST https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=WEB_API_KEY 
{
     "email": "your_user@email.com",
     "password": "your_password",
     "returnSecureToken": true
 }

Note that you need to fill in the WEB_API_KEY parameter as well! You can obtain it by clicking the settings gear next to Project Overview. The General tab should open and it should list the Web API Key.

If the login is successful you will get a response similar to the following:

{
  "kind": "identitytoolkit#VerifyPasswordResponse",
  "localId": "drH5pThXcuY1V2w2FSVwlaRZXEN2",
  "email": "xx.xx@xx.xx",
  "displayName": "",
  "idToken": "xx.xx.xx-xx-xx-xx",
  "registered": true,
  "refreshToken": "xx-xx-xx",
  "expiresIn": "3600"
}

In order to make authenticated requests you’ll have to provide the following header to all requests:

Authentication: Bearer ${idToken}

Keep in mind that the idToken expires in 3600 seconds and you’ll need to exchange the refresh token for a new idToken before or after it expires:

// https://securetoken.googleapis.com/v1/token?key=WEB_API_KEY
{
  "grant_type": "refresh_token",
  "refresh_token": your_refresh_token
}

Security Rules

To secure my database I’ve used the following security rules. The don’t allow deletion and only allow creating, updating and reading documents. Deleting them is forbidden.

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow delete: if false;
      allow create, update, read: if (request.auth != null && request.auth.uid != null);
    }
  }
}

Thanks for reading!