Python iterators question

https://www.codecademy.com/courses/learn-intermediate-python-3/lessons/iterables-and-iterators/exercises/iterables-and-iterators-review

error in recommended answer - Python 3 intermediate - ITERABLES & ITERATORS
Review - checkpoint 6

Codecademy answer: 'tuple for laser and scratcher toys"

correct answer: [(‘laser’, 1.99, ‘fountain’, 5.99), (‘laser’, 1.99, ‘scratcher’, 10.99)]
(i.e. tuple for laser and fountain toys as well)

reason: cost of laser + fountain also less than 15 (maxmoney)

my code:
# Write your code below:
import itertools

cat_toys = [
(“laser”, 1.99),
(“fountain”, 5.99),
(“scratcher”,10.99),
(“catnip”, 15.99)
]

cat_toy_iterator = iter(cat_toys)

print (next(cat_toy_iterator))
print (next(cat_toy_iterator))
print (next(cat_toy_iterator))
print (next(cat_toy_iterator))

max_money = 15
options = []

toy_combos = itertools.combinations(cat_toys, 2)

for combo in toy_combos:

  • toy1 = combo[0]*
  • cost_of_toy1 = toy1[1]*
  • toy2 = combo[1]*
  • cost_of_toy2 = toy2[1]*
  • if cost_of_toy1 + cost_of_toy2 <= max_money:*
  •    options.append((toy1) + (toy2))*
    

print(options)

I think the problem is on the next-to-last line

You should be appending a tuple to the list.
The tuple should be (toy1, toy2)
(toy1) + (toy2) would not be a tuple

options.append((toy1, toy2))

Many thanks for your helpful and speedy reply – much appreciated – I understand my error now.

Model answer:

options.append(combo)

returns:

[((‘laser’, 1.99**), (‘fountain’, 5.99)), ((‘laser’, 1.99), (‘scratcher’, 10.99)**)]

My answer:

options.append((toy1) + (toy2))

returns:

[(‘laser’, 1.99, ‘fountain’, 5.99), (‘laser’, 1.99, ‘scratcher’, 10.99)]

~WRD000.jpg

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.