Module 3 · Data, Variables, Samples, and Measurement Lesson 21 of 120
Observations, Entities, Variables, and Datasets
Three payment rows are not three customers.
Transcript
24 sentences · select one to jump thereCheck your understanding
Should the second C1 row be removed as a duplicate?
Code lab
Run it yourself
The lesson source in 7 languages. Edit it, run TypeScript and Python right here, and compare with the expected output.
/**
* Fintech Math Bootcamp · Lesson 021 of 120
* Observations, Entities, Variables, and Datasets
* Module 03: Data, Variables, Samples, and Measurement
*
* Scenario: Three payment rows are not three customers
* Rule: observation ≠ entity ≠ variable
*
* Try it: Should the second C1 row be removed as a duplicate?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/data-variables-samples-and-measurement/observations-entities-variables-and-datasets/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*/
export function lesson021() {
const rows = [
{payment: "P1", customer: "C1", amount: 20},
{payment: "P2", customer: "C1", amount: 30},
{payment: "P3", customer: "C2", amount: 50}
];
const result = {rows: rows.length,
customers: new Set(rows.map(r => r.customer)).size};
return result;
}
export const checkedResult = {"rows":3,"customers":2};
// Run this file directly: npx tsx lessons/03-data-variables-samples-and-measurement/021-observations-entities-variables-and-datasets.ts
if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop()!)) {
console.log(JSON.stringify(lesson021(), null, 2));
}
Your output
Press Run to execute the code in your browser.
Expected output
{
"rows": 3,
"customers": 2
}"""
Fintech Math Bootcamp · Lesson 021 of 120
Observations, Entities, Variables, and Datasets
Module 03: Data, Variables, Samples, and Measurement
Scenario: Three payment rows are not three customers
Rule: observation ≠ entity ≠ variable
Try it: Should the second C1 row be removed as a duplicate?
Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/data-variables-samples-and-measurement/observations-entities-variables-and-datasets/
Free course: https://courses.thefintechbuilder.com
Synthetic teaching example, not financial advice or a production library.
Run it: python main.py
"""
import json
def lesson021() -> dict:
rows = [
{"payment": "P1", "customer": "C1", "amount": 20},
{"payment": "P2", "customer": "C1", "amount": 30},
{"payment": "P3", "customer": "C2", "amount": 50},
]
result = {"rows": len(rows), "customers": len({r["customer"] for r in rows})}
return result
if __name__ == "__main__":
print(json.dumps(lesson021(), indent=2))
Your output
Press Run to execute the code in your browser.
Expected output
{
"rows": 3,
"customers": 2
}/**
* Fintech Math Bootcamp · Lesson 021 of 120
* Observations, Entities, Variables, and Datasets
* Module 03: Data, Variables, Samples, and Measurement
*
* Scenario: Three payment rows are not three customers
* Rule: observation ≠ entity ≠ variable
*
* Try it: Should the second C1 row be removed as a duplicate?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/data-variables-samples-and-measurement/observations-entities-variables-and-datasets/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*
* Run it: javac Main.java && java Main
*/
import java.util.HashSet;
import java.util.Set;
public class Main {
static final class PaymentRow {
final String payment;
final String customer;
final double amount;
PaymentRow(String payment, String customer, double amount) {
this.payment = payment;
this.customer = customer;
this.amount = amount;
}
}
static final class RowCounts {
final int rows;
final int customers;
RowCounts(int rows, int customers) {
this.rows = rows;
this.customers = customers;
}
}
static RowCounts lesson021() {
PaymentRow[] rows = {
new PaymentRow("P1", "C1", 20),
new PaymentRow("P2", "C1", 30),
new PaymentRow("P3", "C2", 50)
};
Set<String> customers = new HashSet<String>();
for (PaymentRow r : rows) customers.add(r.customer);
RowCounts result = new RowCounts(rows.length, customers.size());
return result;
}
public static void main(String[] args) {
RowCounts result = lesson021();
System.out.println(object("rows", num(result.rows), "customers", num(result.customers)));
}
// Formats a double the way JSON.stringify does: whole numbers without ".0", null for NaN or infinity.
static String num(double x) {
if (Double.isNaN(x) || Double.isInfinite(x)) return "null";
if (x == Math.rint(x) && Math.abs(x) < 1e15) return String.valueOf((long) x);
return String.valueOf(x);
}
static String quote(String text) {
return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
}
// Indents an already formatted JSON value by one level.
static String nested(String json) {
return json.replace("\n", "\n ");
}
static String object(String... keysAndValues) {
if (keysAndValues.length == 0) return "{}";
StringBuilder out = new StringBuilder("{");
for (int i = 0; i < keysAndValues.length; i += 2) {
out.append(i == 0 ? "\n " : ",\n ")
.append(quote(keysAndValues[i])).append(": ").append(nested(keysAndValues[i + 1]));
}
return out.append("\n}").toString();
}
}
No browser runner for Java yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"rows": 3,
"customers": 2
}// Fintech Math Bootcamp · Lesson 021 of 120
// Observations, Entities, Variables, and Datasets
// Module 03: Data, Variables, Samples, and Measurement
//
// Scenario: Three payment rows are not three customers
// Rule: observation ≠ entity ≠ variable
//
// Try it: Should the second C1 row be removed as a duplicate?
//
// Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/data-variables-samples-and-measurement/observations-entities-variables-and-datasets/
// Free course: https://courses.thefintechbuilder.com
// Synthetic teaching example, not financial advice or a production library.
//
// Run it: go run main.go
package main
import (
"encoding/json"
"fmt"
)
type PaymentRow struct {
Payment string
Customer string
Amount float64
}
type RowCounts struct {
Rows int `json:"rows"`
Customers int `json:"customers"`
}
func lesson021() RowCounts {
rows := []PaymentRow{
{Payment: "P1", Customer: "C1", Amount: 20},
{Payment: "P2", Customer: "C1", Amount: 30},
{Payment: "P3", Customer: "C2", Amount: 50},
}
customers := map[string]bool{}
for _, r := range rows {
customers[r.Customer] = true
}
result := RowCounts{Rows: len(rows), Customers: len(customers)}
return result
}
func main() {
printJSON(lesson021())
}
// printJSON prints a value as JSON indented with two spaces, like JSON.stringify(value, null, 2).
func printJSON(value any) {
out, err := json.MarshalIndent(value, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(out))
}
No browser runner for Go yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"rows": 3,
"customers": 2
}/**
* Fintech Math Bootcamp · Lesson 021 of 120
* Observations, Entities, Variables, and Datasets
* Module 03: Data, Variables, Samples, and Measurement
*
* Scenario: Three payment rows are not three customers
* Rule: observation ≠ entity ≠ variable
*
* Try it: Should the second C1 row be removed as a duplicate?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/data-variables-samples-and-measurement/observations-entities-variables-and-datasets/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*
* Run it: g++ -std=c++17 -o main main.cpp && ./main
*/
#include <iostream>
#include <set>
#include <string>
#include <utility>
#include <vector>
std::string quote(const std::string& text) {
std::string out = "\"";
for (char c : text) {
if (c == '"' || c == '\\') out += '\\';
out += c;
}
return out + "\"";
}
// Indents an already formatted JSON value by one level.
std::string nested(const std::string& json) {
std::string out;
for (char c : json) {
out += c;
if (c == '\n') out += " ";
}
return out;
}
std::string object(const std::vector<std::pair<std::string, std::string>>& fields) {
if (fields.empty()) return "{}";
std::string out = "{";
for (std::size_t i = 0; i < fields.size(); ++i) {
out += i == 0 ? "\n " : ",\n ";
out += quote(fields[i].first) + ": " + nested(fields[i].second);
}
return out + "\n}";
}
struct PaymentRow {
std::string payment;
std::string customer;
double amount;
};
struct RowCounts {
std::size_t rows;
std::size_t customers;
};
RowCounts lesson021() {
const std::vector<PaymentRow> rows{
{"P1", "C1", 20},
{"P2", "C1", 30},
{"P3", "C2", 50}
};
std::set<std::string> customers;
for (const PaymentRow& r : rows) customers.insert(r.customer);
const RowCounts result{rows.size(), customers.size()};
return result;
}
int main() {
const RowCounts result = lesson021();
std::cout << object({
{"rows", std::to_string(result.rows)},
{"customers", std::to_string(result.customers)}
}) << "\n";
}
No browser runner for C++ yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"rows": 3,
"customers": 2
}//! Fintech Math Bootcamp · Lesson 021 of 120
//! Observations, Entities, Variables, and Datasets
//! Module 03: Data, Variables, Samples, and Measurement
//!
//! Scenario: Three payment rows are not three customers
//! Rule: observation ≠ entity ≠ variable
//!
//! Try it: Should the second C1 row be removed as a duplicate?
//!
//! Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/data-variables-samples-and-measurement/observations-entities-variables-and-datasets/
//! Free course: https://courses.thefintechbuilder.com
//! Synthetic teaching example, not financial advice or a production library.
//!
//! Run it: rustc main.rs && ./main
use std::collections::HashSet;
#[allow(dead_code)] // payment and amount describe the row but are not needed for the counts
struct PaymentRow {
payment: &'static str,
customer: &'static str,
amount: f64,
}
struct RowCounts {
rows: usize,
customers: usize,
}
fn lesson021() -> RowCounts {
let rows = [
PaymentRow { payment: "P1", customer: "C1", amount: 20.0 },
PaymentRow { payment: "P2", customer: "C1", amount: 30.0 },
PaymentRow { payment: "P3", customer: "C2", amount: 50.0 },
];
let customers: HashSet<&str> = rows.iter().map(|r| r.customer).collect();
let result = RowCounts { rows: rows.len(), customers: customers.len() };
result
}
fn main() {
let result = lesson021();
println!(
"{}",
object(&[
("rows", result.rows.to_string()),
("customers", result.customers.to_string()),
])
);
}
fn quote(text: &str) -> String {
format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
}
/// Indents an already formatted JSON value by one level.
fn nested(json: &str) -> String {
json.replace('\n', "\n ")
}
fn object(fields: &[(&str, String)]) -> String {
if fields.is_empty() {
return "{}".to_string();
}
let lines: Vec<String> = fields
.iter()
.map(|(key, value)| format!(" {}: {}", quote(key), nested(value)))
.collect();
format!("{{\n{}\n}}", lines.join(",\n"))
}
No browser runner for Rust yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"rows": 3,
"customers": 2
}/**
* Fintech Math Bootcamp · Lesson 021 of 120
* Observations, Entities, Variables, and Datasets
* Module 03: Data, Variables, Samples, and Measurement
*
* Scenario: Three payment rows are not three customers
* Rule: observation ≠ entity ≠ variable
*
* Try it: Should the second C1 row be removed as a duplicate?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/data-variables-samples-and-measurement/observations-entities-variables-and-datasets/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*
* Run it: dotnet run (inside a console project that holds this Program.cs)
*/
using System.Text.Json;
var jsonOptions = new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
Console.WriteLine(JsonSerializer.Serialize(Lesson021(), jsonOptions));
static RowCounts Lesson021()
{
var rows = new[]
{
new PaymentRow("P1", "C1", 20),
new PaymentRow("P2", "C1", 30),
new PaymentRow("P3", "C2", 50),
};
var result = new RowCounts(rows.Length, rows.Select(r => r.Customer).ToHashSet().Count);
return result;
}
record PaymentRow(string Payment, string Customer, double Amount);
record RowCounts(int Rows, int Customers);
No browser runner for C# yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"rows": 3,
"customers": 2
}Prefer your own machine? Every file is in the course repository · open it in Codespaces.
Lesson notes
The rule
observation ≠ entity ≠ variable