Última atividade 1763751204

creating a data structure to "bin" items

binning.md Bruto

Binning of frequencies

Examples of python and java of using dict/hashmap for binning of 1) dice rolls, 2) letter frequency and 3) checking for existing keys.

Key patterns:

  • Python: dict.get(key, default) and defaultdict(int) are idiomatic
  • Java: map.getOrDefault(key, default) and map.merge() are modern approaches
  • Both languages support checking key existence before accessing

in Python

# 1) Dice rolls - counting occurrences
from collections import defaultdict
import random

# Using defaultdict (cleaner)
dice_counts = defaultdict(int)
for _ in range(100):
    roll = random.randint(1, 6)
    dice_counts[roll] += 1
# Result: {1: 15, 2: 18, 3: 17, 4: 16, 5: 19, 6: 15}

# Using regular dict
dice_counts = {}
for _ in range(100):
    roll = random.randint(1, 6)
    dice_counts[roll] = dice_counts.get(roll, 0) + 1

# 2) Letter frequency
text = "hello world"
letter_freq = {}
for char in text.lower():
    if char.isalpha():
        letter_freq[char] = letter_freq.get(char, 0) + 1
# Result: {'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1}

# 3) Checking for existing keys
inventory = {'apples': 5, 'bananas': 3}

# Method 1: using 'in'
if 'apples' in inventory:
    print(f"Have {inventory['apples']} apples")

# Method 2: using get() with default
oranges = inventory.get('oranges', 0)  # Returns 0 if not found

# Method 3: try/except
try:
    count = inventory['oranges']
except KeyError:
    count = 0

in Java

import java.util.*;

// 1) Dice rolls - counting occurrences
Map<Integer, Integer> diceCount = new HashMap<>();
Random rand = new Random();

for (int i = 0; i < 100; i++) {
    int roll = rand.nextInt(6) + 1;
    diceCount.put(roll, diceCount.getOrDefault(roll, 0) + 1);
}
// Result: {1=15, 2=18, 3=17, 4=16, 5=19, 6=15}

// Alternative using merge()
for (int i = 0; i < 100; i++) {
    int roll = rand.nextInt(6) + 1;
    diceCount.merge(roll, 1, Integer::sum);
}

// 2) Letter frequency
String text = "hello world";
Map<Character, Integer> letterFreq = new HashMap<>();

for (char c : text.toLowerCase().toCharArray()) {
    if (Character.isLetter(c)) {
        letterFreq.put(c, letterFreq.getOrDefault(c, 0) + 1);
    }
}
// Result: {h=1, e=1, l=3, o=2, w=1, r=1, d=1}

// 3) Checking for existing keys
Map<String, Integer> inventory = new HashMap<>();
inventory.put("apples", 5);
inventory.put("bananas", 3);

// Method 1: using containsKey()
if (inventory.containsKey("apples")) {
    System.out.println("Have " + inventory.get("apples") + " apples");
}

// Method 2: using getOrDefault()
int oranges = inventory.getOrDefault("oranges", 0);  // Returns 0 if not found

// Method 3: checking null
Integer count = inventory.get("oranges");
if (count == null) {
    count = 0;
}