Daily Coding Problem – cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair.

Daily Coding Problem sends daily coding problem sample when you subscribe to their service. This service is very useful to practice your coding ability and think through the logic you will be using to solve the problem.

Problem

This problem was asked by Jane Street.

cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair.
For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.

Given this implementation of cons:

def cons(a, b):
    def pair(f):
        return f(a, b)
    return pair


Implement car and cdr.

Context

So what is car and cdr anyway? You can check out some more details about car and cdr in Wikipedia.

A cons cell is composed of two pointers; the car operation extracts the first pointer, and the cdr operation extracts the second.

Solution

For the solution for this problem, I reference the code from this github.

Code Example

def cons(a, b):
    def pair(f):
        return f(a, b)
    return pair

def car(cons):
    return cons(lambda a, b: a)

def cdr(cons):
    return cons(lambda a, b: b)

print(car(cons(3, 4)))
print(cdr(cons(3, 4)))

Sample Code Download

Download from here

Daily Coding Problem – Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

Daily Coding Problem sends daily coding problem sample when you subscribe to their service. This service is very useful to practice your coding ability and think through the logic you will be using to solve the problem.

Problem

This problem was asked by Uber.

Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].

Follow-up: what if you can’t use division?

Context

The key to above problem is to multiply all the numbers in the list except the one at index “i”. Index “i” in this case is the value where that index was pointed during the iteration.

If the given list is [1, 2, 3, 4, 5], the calculation will be:

[2*3*4*5] where the output should be 120

then the next will be

[1*3*4*5] and the output will be 60

and so on…

On each computation, you need to add them in to new list and eventually, you need do complete a list looks like [120, 60, 40, 30, 24].

Solution

We know that to get the product, you just need to multiply all the numbers in the list except the index at i. We also know that anything you multiply by 1 has pretty much no effect. So What I did is, for the value we need to skip, replace with value of 1. once the multiplication is done in the list, put back the original value and move on to next computation. Below is the sample code.

Code Example

given_list = [1, 2, 3, 4, 5]

def compute(a_list):
    new_list = []

    for index, value in enumerate(a_list):
        original_list = a_list
        original_int = original_list[index]
        original_list[index] = 1

        result = 1
        for x in original_list:
            result = result * x

        new_list.append(result)

        original_list[index] = original_int

    return new_list

r = compute(given_list)
print(r)

Sample Code Download

Download from here

Daily Coding Problem – Given a list of numbers and a number k, return whether any two numbers from the list add up to k.

Problem

Daily Coding Problem sends daily coding problem sample when you subscribe to their service. This service is very useful to practice your coding ability and think through the logic you will be using to solve the problem.

I received the following problem for the 11/03/2018 coding problem.

This problem was asked by Google.

Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.

Bonus: Can you do this in one pass?

Context

Based on the above given problem, basically, you need to find out if there are two values can sum to ‘k’ (which in this case “17”).

Solution

Below how I approached the problem.

Let me show the illustration how I thought of solving this problem.

There are items in the list. Iterate from first item then add the next item and check if there is a match to ‘k’. If there is no match, keep going. once it went through the first iteration, pop() the first item and refresh the list. Then, repeat the same step until you exhaust all the items in the list.

So you can see from above illustration, if I have [10, 15, 3, 7], I will try to add 10 + 15 first, and the sum is 25, which is not equal to 17, so move on to next one which is 10 + 3 and the sum is 13 which is not equal to 17. And so on…

If at some point, it matches the sum to 17, it will exist the recursion. If no match, remove (pop) the fist item in the list and try it again until it may or may not match the sum to 17.

Code Example

So below is the code I came up with:

# given values
l = [10, 15, 3, 7]
k = 17

# will be used for recursion
l_len = len(l)

# do the work
def compute(a_list, k):
    
    # loop through the list
    for i in range(l_len):

        a_list_len = len(a_list)
        base_num = a_list[0]
        sum_num = 0

        # pop the first item in the list
        a_list.pop(0)

        # refresh the list without the first one
        a_list_len = len(a_list)

        for j in range(a_list_len):
            sum_num = base_num + a_list[j]
            # print(base_num, a_list, a_list_len, sum_num)

            if sum_num == k:
                # return the values used to match the k value
                return base_num, a_list[j]
    
    # return False if nothing matches.
    return False

r = compute(l, k)

if not r:
    print("there was no match!")
else:
    print(f'there was a match with k({k}), {r[0]} + {r[1]}')

Step 1

you need to figure out how many items in the list. In the given example, it has 4 items (but you should consider number of items can be more or less). So using Python built-in function len(), you can find out the number of items in the list. We will use this value to iterate inside the list.

Step 2

Next, keep the first item in the variable (base_num) then pop the first item in the list. Now refresh the set of items.

Step 3

Use the refreshed list and iterate within. While iterating, check if the sum of base_num and a_list[j] match the k value.  If yes, return True (in the code above, returning the used values)

Step 4

If there is no match, keep iterating until it hits the condition or not.

Step 5

Output either there was a match or not.

Code Download

You may download the sample code here if you wan to try it out by yourself. Let me know how you approach this problem.

Python Tutorial – How to make a JSON REST API Call

Intro

In this article, we will make a REST API call to OpenWeatheMap service and get the weather information in JSON data format using Python script.

Setup OpenWeatherMap Account

Before we jump into Python scripting, you need to have an account with OpenWeatherMap service. Creating an account with OpenWeatherMap service is free. Go to OpenWeatherMap website and sign up.

Get you API Key

Once you have an account with OpenWeatherMap. Go to your API Key page and grab the API Key displayed on that page.

You should also read How to use APPID so you have an idea how to make a service call to OpenWeatherMap service.

Making a REST API call using Python

Once you have the OpenWeatherMap account and have your API Key with their service, now let’s move to Python side and start scripting in Python.

Python Module

You will need the following Python module in your system. In order to make a REST API call to the OpenWeatherMap service.

requests

If you do not have requests module in your system, run a pip3 install to install it. You can check first using pip3 list to find out if you have the module installed already.

Check what Python packages you have in your system

pip3 list

Use the pip3 install <package name> to install the Python package you need for your project. In this exercise, you will need the requests Python package

pip3 install requests

or

sudo pip3 install requests

Script

Below is the complete Python script to connect to the OpenWeatherMap service, getting the weather info and just grab the temperature data.

import requests

OWM_API = "https://api.openweathermap.org/data/2.5/weather"
city_name = "london"
APPID = "<USE YOUR API KEY>"

# parameters to send along with REST API Endpoint
payload = {'q': city_name, 'APPID': APPID}

# make a requests call using GET (including parameters)
r = requests.get(OWM_API, params=payload)

# get the returns json data
json_data = r.json()

# temperature is stored in main > temp (in the form of Kelvin)
temp_in_kelvin = json_data['main']['temp']
temp_in_celcius = temp_in_kelvin - 273.15

print(f'Temp in K: {temp_in_kelvin}')
print(f'Temp in C: {temp_in_celcius}')

Notes

If you made a call to OpenWeatherMap (in this case using City Name as your passing parameter.) it will return a weather info in JSON format. The JSON data will include the details such as shown in below. You can use an online JSON viewer to view the JSON data in more friendlier way if you are not use to how to consume JSON data.  

Sample JSON data returning from OpenWeatherMap Service:

{
  "coord": {
    "lon": -122.09,
    "lat": 37.39
  },
  "weather": [
    {
      "id": 500,
      "main": "Rain",
      "description": "light rain",
      "icon": "10d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 280.44,
    "pressure": 1017,
    "humidity": 61,
    "temp_min": 279.15,
    "temp_max": 281.15
  },
  "visibility": 12874,
  "wind": {
    "speed": 8.2,
    "deg": 340,
    "gust": 11.3
  },
  "clouds": {
    "all": 1
  },
  "dt": 1519061700,
  "sys": {
    "type": 1,
    "id": 392,
    "message": 0.0027,
    "country": "US",
    "sunrise": 1519051894,
    "sunset": 1519091585
  },
  "id": 0,
  "name": "Mountain View",
  "cod": 200
}

GitHub

If you want to download the .py file, you can grab it from GitHub link below.

Sample Code

Python 2.7 retire countdown

Python 2.7 will retire soon

If you are using Python 2.7, you should be start thinking of migrating your script to Python 3.x. As you can see from this website, Python 2.7 will retire in about a year (as of the time this was posted).

Below is the except from the website:

What's all this, then?
Python 2.7 will not be maintained past 2020. Originally, there was no official date. Recently, that date has been updated to January 1, 2020. This clock has been updated accordingly. My original idea was to throw a Python 2 Celebration of Life party at PyCon 2020, to celebrate everything Python 2 did for us. That idea still stands. (If this sounds interesting to you, email pythonclockorg@gmail.com).
Python 2, thank you for your years of faithful service.
Python 3, your time is now.
How do I get started?
If the code you care about is still on Python 2, that's totally understandable. Most of PyPI's popular packages now work on Python 2 and 3, and more are being added every day. Additionally, a number of critical Python projects have pledged to stop supporting Python 2 soon. To ease the transition, the official porting guide has advice for running Python 2 code in Python 3.

How to migrate your Python 2 code to Python 3

If you have Python installed on your system, you should have a tool called “2to3”. To Check your Python 2 code compatibility with Python 3, run the “2to3”.

Let’s say you have a Python file called “hello_world_py2.py“. And let’s say it has the following code:

print "hello world - Python 2.7"

Next, run the “2to3” tool from the command line like below:

2to3 helloworld_py2.py

And then, you will get an output something like below:

RefactoringTool: Skipping optional fixer: buffer
RefactoringTool: Skipping optional fixer: idioms
RefactoringTool: Skipping optional fixer: set_literal
RefactoringTool: Skipping optional fixer: ws_comma
RefactoringTool: Refactored hello_world_py2.py
--- hello_world_py2.py	(original)
+++ hello_world_py2.py	(refactored)
@@ -1,2 +1,2 @@
-print "hello world - Python 2.7"
+print("hello world - Python 2.7")
 
RefactoringTool: Files that need to be modified:
RefactoringTool: hello_world_py2.py

For more details about “2to3” tool, please check out this page.

If you are thinking of starting to learn Python, I would encourage you to use Python 3.x. already.