![]() |
Home | Accounts | Setup | Verify | Play | Hacks |
3.2 Data Abstraction all Hacks
All Hacks for Data Abstraction
Popcorn Hack #2
Create a simple calculator in javascript and python
%%js
const prompt = require("prompt-sync")();
const firstNumber = parseFloat(prompt("Enter the first number: "));
const secondNumber = parseFloat(prompt("Enter the second number: "));
const operation = prompt("Enter the operation (+, -, *, /): ");
let result;
switch (operation) {
case "+":
result = firstNumber + secondNumber;
break;
case "-":
result = firstNumber - secondNumber;
break;
case "*":
result = firstNumber * secondNumber;
break;
case "/":
if (secondNumber !== 0) {
result = firstNumber / secondNumber;
} else {
result = "Error: Division by zero is not allowed.";
}
break;
default:
result = "Invalid operation!";
}
console.log("The result is:", result);
<IPython.core.display.Javascript object>
# Simple calculator in Python
first_number = float(input("Enter the first number: "))
second_number = float(input("Enter the second number: "))
operation = input("Enter the operation (+, -, *, /): ")
if operation == "+":
result = first_number + second_number
elif operation == "-":
result = first_number - second_number
elif operation == "*":
result = first_number * second_number
elif operation == "/":
if second_number != 0:
result = first_number / second_number
else:
result = "Error: Division by zero is not allowed."
else:
result = "Invalid operation!"
print("The result is:", result)
The result is: 4.0
Popcorn Hack 3
Write a function that takes a list of strings and an integer
%%js
function repeatStrings(strings, n) {
return strings.map(str => str.repeat(n));
}
// Example usage:
const strings = ["apple", "banana", "cherry"];
const n = 3;
console.log(repeatStrings(strings, n));
// Output: ["appleappleapple", "bananabananabanana", "cherrycherrycherry"]
<IPython.core.display.Javascript object>
##Python
def repeat_strings(strings, n):
return [s * n for s in strings]
# Example usage:
strings = ["apple", "banana", "cherry"]
n = 3
print(repeat_strings(strings, n))
# Output: ['appleappleapple', 'bananabananabanana', 'cherrycherrycherry']
['appleappleapple', 'bananabananabanana', 'cherrycherrycherry']
Popcorn Hack 4
a function that compares two sets, and checks if there is an value within set 2 that is within set 1. If a value from set 2 is in set 1, then return the boolean output ‘True’ . If not, then return the boolean value ‘False’.
%%js
function hasCommonValue(set1, set2) {
return set2.some(value => set1.includes(value));
}
// Example usage:
const set1 = [1, 2, 3, 4, 5];
const set2 = [5, 6, 7];
console.log(hasCommonValue(set1, set2)); // Output: true
const set3 = [8, 9, 10];
console.log(hasCommonValue(set1, set3)); // Output: false
<IPython.core.display.Javascript object>
#Python
def has_common_value(set1, set2):
return any(value in set1 for value in set2)
# Example usage:
set1 = {1, 2, 3, 4, 5}
set2 = {5, 6, 7}
print(has_common_value(set1, set2)) # Output: True
set3 = {8, 9, 10}
print(has_common_value(set1, set3)) # Output: False
True
False
Popcorn Hack 1
Abstract keys of bananas, apples, and pears, and assign them to numbers 1, 2 and 3 in the most effective way
%%js
// Creating an object to map fruits to numbers
const fruitMap = {
bananas: 1,
apples: 2,
pears: 3
};
// Accessing values through keys
console.log("Bananas:", fruitMap.bananas); // Output: Bananas: 1
console.log("Apples:", fruitMap.apples); // Output: Apples: 2
console.log("Pears:", fruitMap.pears); // Output: Pears: 3
<IPython.core.display.Javascript object>
#Python
# Creating a dictionary to map fruits to numbers
fruit_map = {
"bananas": 1,
"apples": 2,
"pears": 3
}
# Accessing values through keys
print("Bananas:", fruit_map["bananas"]) # Output: Bananas: 1
print("Apples:", fruit_map["apples"]) # Output: Apples: 2
print("Pears:", fruit_map["pears"]) # Output: Pears: 3
Bananas: 1
Apples: 2
Pears: 3
Homework Hack #1
# Part 1: Create a Profile Information (dict)
profile = {
"name": "Arhaan",
"age": 15,
"city": "New York",
"favorite_color": "Blue"
}
print("Profile Information:", profile)
# Part 2: Create a List of Hobbies (list)
hobbies = ["reading", "cycling", "coding"]
print("Hobbies:", hobbies)
# Part 3: Add Hobbies to Profile (dict and list)
profile["hobbies"] = hobbies
print("Updated Profile with Hobbies:", profile)
# Part 4: Check Availability of a Hobby (bool)
chosen_hobby = "cycling"
has_hobby = True # Set to True if "cycling" is available today
print(f"Is '{chosen_hobby}' available today? {has_hobby}")
# Part 5: Total Number of Hobbies (int)
total_hobbies = len(hobbies)
print(f"I have {total_hobbies} hobbies.")
# Part 6: Favorite Hobbies (tuple)
favorite_hobbies = ("reading", "coding")
print("Favorite Hobbies:", favorite_hobbies)
# Part 7: Add a New Item to Your Profile (set)
skills = {"problem-solving", "programming", "public speaking"}
print("Skills:", skills)
# Part 8: Decide to Add a New Skill (NoneType)
new_skill = None # Undecided new skill
print("New Skill:", new_skill)
# Part 9: Calculate Total Profile Cost (float)
hobby_cost = 5
skill_cost = 10
total_cost = (total_hobbies * hobby_cost) + (len(skills) * skill_cost)
print(f"Total Profile Cost: ${total_cost:.2f}")
%%js
// Part 1: Create a Profile Information (object)
let profile = {
name: "Arhaan",
age: 15,
city: "New York",
favorite_color: "Blue"
};
console.log("Profile Information:", profile);
// Part 2: Create a List of Hobbies (array)
let hobbies = ["reading", "cycling", "coding"];
console.log("Hobbies:", hobbies);
// Part 3: Add Hobbies to Profile (object and array)
profile.hobbies = hobbies;
console.log("Updated Profile with Hobbies:", profile);
// Part 4: Check Availability of a Hobby (boolean)
let chosenHobby = "cycling";
let hasHobby = true; // Set to true if "cycling" is available today
console.log(`Is '${chosenHobby}' available today? ${hasHobby}`);
// Part 5: Total Number of Hobbies (integer)
let totalHobbies = hobbies.length;
console.log(`I have ${totalHobbies} hobbies.`);
// Part 6: Favorite Hobbies (array as tuple equivalent in JavaScript)
let favoriteHobbies = ["reading", "coding"];
console.log("Favorite Hobbies:", favoriteHobbies);
// Part 7: Add a New Item to Your Profile (set)
let skills = new Set(["problem-solving", "programming", "public speaking"]);
console.log("Skills:", Array.from(skills));
// Part 8: Decide to Add a New Skill (null)
let newSkill = null; // Undecided new skill
console.log("New Skill:", newSkill);
// Part 9: Calculate Total Profile Cost (float)
let hobbyCost = 5;
let skillCost = 10;
let totalCost = (totalHobbies * hobbyCost) + (skills.size * skillCost);
console.log(`Total Profile Cost: $${totalCost.toFixed(2)}`);