Night 19: The pet shop
Bạn đã hoàn thành đêm này bằng Python hoặc mã giả. Kết quả được tính cho cả hai. Bạn có thể luyện tập lại nếu muốn.
Tonight: the pet shop
- Your pet goes shopping! The shop keeps each item as a record: a name and a price.
- You will learn one thing: an array of records.
Words for tonight
| Word | Meaning |
|---|---|
| price | how much something costs |
| search | look for something, one by one |
| total | all the numbers added together |
An array of records
- Last night you made one card. A shop needs many cards: an array of them.
TYPE ItemRecord
DECLARE Name : STRING
DECLARE Price : INTEGER
ENDTYPE
DECLARE Shop : ARRAY[1:2] OF ItemRecord
Shop[1].Name ← "apple"
Shop[1].Price ← 2
Shop[2].Name ← "fish"
Shop[2].Price ← 5
OUTPUT Shop[2].Name, " costs ", Shop[2].Price
| Index | .Name |
.Price |
|---|---|---|
| 1 | apple | 2 |
| 2 | fish | 5 |
Loop through the shop
Shop[Index]is one record.Shop[Index].Priceis one field of it.
TYPE ItemRecord
DECLARE Name : STRING
DECLARE Price : INTEGER
ENDTYPE
DECLARE Shop : ARRAY[1:2] OF ItemRecord
DECLARE Index : INTEGER
Shop[1].Name ← "apple"
Shop[1].Price ← 2
Shop[2].Name ← "fish"
Shop[2].Price ← 5
FOR Index ← 1 TO 2
OUTPUT Shop[Index].Name, " costs ", Shop[Index].Price
NEXT Index
Search for one item
- Look at each record in turn. A BOOLEAN remembers if you found it.
| Step | What to write |
|---|---|
| before the loop | Found ← FALSE |
| in the loop | IF Shop[Index].Name = Wanted THEN … Found ← TRUE |
| after the loop | IF NOT Found THEN OUTPUT "Sold out" |
- Now go shopping with your pet!
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
The shop is an array of records. Use a FOR loop to output each item's name and price. The first line is apple 2.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Read an item name with INPUT. Search the shop. If you find it, output its price. If not, output Sold out.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Your pet buys 3 items. Read 3 item names, one at a time. Find each price in the shop and add it to Total. Output Total. Every item is in the shop.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 4/5 · 280 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Find the cheapest item with a loop. Keep its index in Best. Output its name. The answer is rice.
Nhấn Chạy để xem kết quả ở đây.