Menu
Coddy logo textTech

Recap - Product List

Part of the Fundamentals section of Coddy's R journey — lesson 75 of 78.

challenge icon

Challenge

Easy

You will receive four lines of input:

  1. A product name (e.g., Wireless Headphones)
  2. A price (e.g., 79.99)
  3. A stock quantity (e.g., 25)
  4. A discount percentage to apply (e.g., 20)

Perform the following operations:

  1. Create a named list called product with elements: name (character), price (numeric), stock (numeric), and available (set to TRUE if stock is greater than 0, otherwise FALSE)
  2. Print the product name using the $ operator
  3. Calculate the discounted price (original price minus the discount percentage) and update the price element
  4. Add a new element called discounted with the value TRUE
  5. Reduce the stock by 1 (simulating a purchase)
  6. Remove the available element from the list
  7. Print the final list

For example, if the inputs are:

Smart Watch
150
10
25

The output should be:

[1] "Smart Watch"
$name
[1] "Smart Watch"

$price
[1] 112.5

$stock
[1] 9

$discounted
[1] TRUE

Explanation:

  • Original price 150 with 25% discount: 150 - (150 * 25/100) = 112.5
  • Stock reduced from 10 to 9
  • The available element was removed from the final list

Try it yourself

# Read input
con <- file("stdin", "r")
product_name <- suppressWarnings(readLines(con, n = 1))
price <- as.numeric(suppressWarnings(readLines(con, n = 1)))
stock <- as.numeric(suppressWarnings(readLines(con, n = 1)))
discount_percentage <- as.numeric(suppressWarnings(readLines(con, n = 1)))
close(con)

# TODO: Write your code below
# 1. Create a named list called 'product' with elements: name, price, stock, and available
# 2. Print the product name using the $ operator
# 3. Calculate the discounted price and update the price element
# 4. Add a new element called 'discounted' with value TRUE
# 5. Reduce the stock by 1
# 6. Remove the 'available' element from the list
# 7. Print the final list

All lessons in Fundamentals