├── README.md ├── disc ├── disc00 │ ├── README.md │ └── disc00.pdf ├── disc01 │ ├── README.md │ └── disc01.pdf ├── disc02 │ ├── README.md │ └── disc02.pdf ├── disc03 │ ├── README.md │ └── disc03.pdf ├── disc04 │ ├── README.md │ └── disc04.pdf ├── disc05 │ ├── README.md │ └── disc05.pdf ├── disc06 │ ├── README.md │ └── disc06.pdf ├── disc07 │ ├── README.md │ └── disc07.pdf ├── disc08 │ ├── README.md │ └── disc08.pdf ├── disc09 │ ├── README.md │ └── disc09.pdf ├── disc10 │ ├── README.md │ └── disc10.pdf ├── disc11 │ ├── README.md │ └── disc11.pdf ├── disc12 │ ├── README.md │ └── disc12.pdf └── 新建文本文档.txt ├── hw ├── hw01 │ ├── README.md │ ├── hw01-sol.zip │ └── hw01.zip ├── hw02 │ ├── README.md │ ├── hw02-sol.zip │ └── hw02.zip ├── hw03 │ ├── README.md │ ├── hw03-sol.zip │ └── hw03.zip ├── hw04 │ ├── README.md │ ├── hw04-sol.zip │ └── hw04.zip ├── hw05 │ ├── README.md │ ├── hw05-sol.zip │ └── hw05.zip ├── hw06 │ ├── README.md │ ├── hw06-sol.zip │ └── hw06.zip ├── hw07 │ ├── README.md │ ├── hw07-sol.zip │ └── hw07.zip ├── hw08 │ ├── README.md │ ├── hw08-sol.zip │ └── hw08.zip ├── hw09 │ ├── README.md │ ├── hw09-sol.zip │ └── hw09.zip ├── hw10 │ ├── README.md │ ├── hw10-sol.zip │ └── hw10.zip └── hw11 │ ├── README.md │ └── hw11.zip ├── lab ├── lab00 │ ├── README.md │ └── lab00.zip ├── lab01 │ ├── README.md │ ├── lab01-sol.zip │ └── lab01.zip ├── lab02 │ ├── README.md │ ├── lab02-sol.zip │ └── lab02.zip ├── lab03 │ ├── README.md │ ├── lab03-sol.zip │ └── lab03.zip ├── lab04 │ ├── README.md │ ├── lab04-sol.zip │ └── lab04.zip ├── lab05 │ ├── README.md │ ├── lab05-sol.zip │ └── lab05.zip ├── lab06 │ ├── README.md │ ├── lab06-sol.zip │ └── lab06.zip ├── lab07 │ ├── README.md │ ├── lab07-sol.zip │ └── lab07.zip ├── lab08 │ ├── README.md │ ├── lab08--sol.zip │ └── lab08.zip ├── lab09 │ ├── README.md │ ├── lab09-sol.zip │ └── lab09.zip ├── lab10 │ ├── README.md │ ├── lab10-sol.zip │ └── lab10.zip ├── lab11 │ ├── README.md │ ├── lab11-sol.zip │ └── lab11.zip └── lab12 │ ├── README.md │ ├── lab12-sol.zip │ └── lab12.zip ├── ppt ├── 01-Computer_Science_1pp.pdf ├── 02-Functions_1pp.pdf ├── 03-Control_1pp.pdf ├── 04-Higher-Order_Functions_1pp.pdf ├── 05-Environments_1pp.pdf ├── 06-Functional_Abstraction_1pp.pdf ├── 07-Function_Examples_1pp.pdf ├── 09-Recursion_1pp.pdf ├── 10-Tree_Recursion_1pp.pdf ├── 11-Sequences_1pp.pdf ├── 12-Containers_1pp.pdf ├── 13-Data_Abstraction_1pp.pdf ├── 14-Trees_1pp.pdf ├── 15-Mutability_1pp.pdf ├── 16-Iterators_1pp.pdf ├── 17-Generators_1pp.pdf ├── 18-Objects_1pp.pdf ├── 19-Attributes_1pp.pdf ├── 20-Inheritance_1pp.pdf ├── 21-Representation_1pp.pdf ├── 22-Composition_1pp.pdf ├── 23-Efficiency_1pp.pdf ├── 24-Decomposition_1pp.pdf ├── 25-Data_Examples_1pp.pdf ├── 27-Scheme_1pp.pdf ├── 28-Scheme_Lists_1pp.pdf ├── 29-Calculator_1pp.pdf ├── 30-Interpreters_1pp.pdf ├── 31-Programs_as_Data_1pp.pdf └── 32-Macros_1pp.pdf ├── projects ├── project01 │ ├── README.md │ ├── hog-sol.zip │ └── hog.zip ├── project02 │ ├── README.md │ ├── cats-sol.zip │ └── cats.zip ├── project03 │ ├── README.md │ ├── ants-sol.zip │ ├── ants.zip │ ├── image-1.png │ └── image.png ├── project04 │ ├── README.md │ └── scheme-sol.zip └── project05 │ ├── README.md │ └── scheme_contest-sol.zip └── schedule.png /README.md: -------------------------------------------------------------------------------- 1 | ## CS 61A - Spring 2024 2 | 3 | Update: 2024--06--20 4 | 5 | 6 | 7 | []() 8 | 9 | This is my repository for lab, homeworks and project when going through the course, CS 61A, Spring 2024, from U.C. Berkeley. 10 | Since the course page change to summar 2024. Some of halfway learners have to stop learning for unable to access to the spring 2024 website. 11 | Hope this repository will help you. 12 | 13 | **We welcome contributions to this repository.** 14 | 15 | > **Warning** 16 | > This repository contains codes for tasks of CS 61A, so please be careful about not viloating the course's policies and not copy-pasting these codes. 17 | 18 | ## Overview 19 | 20 | The CS 61 series is an introduction to computer science, with particular emphasis on software and on machines from a programmer's point of view. 21 | 22 | 1. CS 61A concentrates on the idea of abstraction, allowing the programmer to think in terms appropriate to the problem rather than in low-level operations dictated by the computer hardware. 23 | 2. CS 61B deals with the more advanced engineering aspects of software, such as constructing and analyzing large programs. 24 | 3. CS 61C focuses on machines and how they execute programs. 25 | 26 | In CS 61A, we are interested in teaching you about programming, not about how to use one particular programming language. We consider a series of techniques for controlling program complexity, such as functional programming, data abstraction, and object-oriented programming. 27 | 28 | CS 61A primarily uses the Python 3 programming language. Python is a popular language in both industry and academia. It is also particularly well-suited to the task of exploring the topics taught in this course. It is an open-source language developed by a large volunteer community that prides itself on the diversity of its contributors. We will also dive deeper into interpreters, to which end we'll introduce the Scheme programming language as a way to explore functional programming, and Regular Expressoins and the SQL programming language as a way to explore declarative programming. 29 | 30 | Mastery of a particular programming language is a very useful side effect of CS 61A. However, our goal is not to dictate what language you use in your future endeavors. Instead, our hope is that once you have learned the concepts involved in programming, you will find that picking up a new programming language is but a few days' work. 31 | 32 | ## Contents 33 | 34 | ### Video 35 | - [cs61a videos spring 2024 link](https://www.bilibili.com/video/BV1wSTUeJEwK/?spm_id_from=333.337.search-card.all.click&vd_source=2e51af461f4b6541078245c8e98d9f3a) 36 | 37 | - [23fall lecture 1 ](https://www.youtube.com/watch?v=0P4kOL7pFFo&list=PL6BsET-8jgYXRvFO4WhqFlk3CN5Fy-aM4) 38 | - [23fall lecture 2-4 ](https://www.youtube.com/watch?v=0P4kOL7pFFo&list=PL6BsET-8jgYWZlcJMOuWFSXKc99cSneEN) 39 | - [23fall lecture 5 ](https://www.youtube.com/watch?v=9122neGpcS8&list=PL6BsET-8jgYVc8wS_O6hsmwFiTi7NypvD) 40 | 41 | 42 | 43 | ### Homeworks 44 | 45 | - [Homework 1: Functions, Control](./hw/hw01/) 46 | 47 | - [Homework 2: Higher Order Functions](./hw/hw02/) 48 | 49 | - [Homework 3: Recursion, Tree Recursion](./hw/hw03/) 50 | 51 | - [Homework 4: Sequences, ADT Trees](./hw/hw04/) 52 | 53 | - [Homework 5: Generators](./hw/hw05/) 54 | 55 | - [Homework 6: OOP, Linked Lists](./hw/hw06/) 56 | 57 | - [Homework 7: Scheme](./hw/hw07/) 58 | 59 | - [Homework 8: Scheme Lists](./hw/hw08/) 60 | 61 | - [Homework 9: Programs as Data, Macros](./hw/hw09/) 62 | - [Homework 10: SQL](./hw/hw10/) 63 | - [Homework 11: Finale](./hw/hw11/) 64 | 65 | ### lab 66 | 67 | - [Lab 0: Getting Started](./lab/lab00/) 68 | 69 | - [Lab 1: Functions, Control](./lab/lab01/) 70 | 71 | - [Lab 2: Higher-Order Functions, Lambda Expressions](./lab/lab02/) 72 | 73 | - [Lab 3: Recursion, Python Lists](./lab/lab03/) 74 | 75 | - [Lab 4: Tree Recursion, Data Abstraction](./lab/lab04/) 76 | 77 | - [Lab 5: Mutability, Iterators](./lab/lab05/) 78 | 79 | - [Lab 6: Object-Oriented Programming](./lab/lab06/) 80 | 81 | - [Lab 7: Inheritance, Linked Lists](./lab/lab07/) 82 | 83 | - [Lab 8: Mutable Trees](./lab/lab08/) 84 | 85 | - [Lab 9: Scheme](./lab/lab09/) 86 | 87 | - [Lab 10: Interpreters](./lab/lab10/) 88 | 89 | - [Lab 11: Programs as Data, Macros](./lab/lab11/) 90 | 91 | - [Lab 12: SQL](./lab/lab12/) 92 | 93 | ### discussion 94 | - [disc 0: Getting Started](./disc/disc00/) 95 | 96 | - [disc 1: Control, Environment Diagrams](./disc/disc01/) 97 | 98 | - [disc 2: Environment Diagrams, Higher-Order Functions](./disc/disc02/) 99 | 100 | - [disc 3: Recursion](./disc/disc03/) 101 | 102 | - [disc 4: Tree Recursion](./disc/disc04/) 103 | 104 | - [disc 5: Trees](./disc/disc05/) 105 | 106 | - [disc 6: Iterators, Generators](./disc/disc06/) 107 | 108 | - [disc 7: OOP](./disc/disc07/) 109 | 110 | - [disc 8: Linked Lists, Efficiency](./disc/disc08/) 111 | 112 | - [disc 9: Scheme, Scheme Lists](./disc/disc09/) 113 | 114 | - [disc 10: Interpreters](./disc/disc10/) 115 | 116 | - [disc 11: SQL](./disc/disc11/) 117 | 118 | - [disc 12: Final Review](./disc/disc12/) 119 | 120 | 121 | ### project 122 | 123 | 124 | - [Project 1: The Game of Hog](./projects/project01/) 125 | 126 | - [Project 2: Cats](./projects/project02/) 127 | 128 | - [Project 3: Ants Vs. SomeBees](./projects/project03/) 129 | 130 | - [Project 4: Scheme Interpreter](./projects/project04/) 131 | 132 | - [Project 5: Optional Contest: Scheme Art](./projects/project05/) 133 | 134 | ## Schedule 135 | 136 | ![schedule](schedule.png) 137 | 138 | 139 | ## Links 140 | 141 | - [spring 2022 lab-hw-project](https://github.com/caiscoding/CS61A-Spring2022) 142 | - [Fall 2020 website](https://web.archive.org/web/20210104105406/https://cs61a.org/) 143 | 144 | - [Course Website (2024 Summar)](https://cs61a.org/) 145 | - [Vanshaj's Guide (Summer 2020)](https://cs61a.vanshaj.dev/welcome/) 146 | - [Textbook (SICP for python)](http://composingprograms.com/) 147 | - [Online editor (support scheme, SQL and python)](https://code.cs61a.org/) 148 | 149 | ## Reference 150 | The most of resource of this repository from CS61A Spring 2024 homepage. However, the course page change to 2024 summar on 13 June. So part of materials get from the following Web: 151 | https://www.learncs.site/docs/curriculum-resource/cs61a 152 | -------------------------------------------------------------------------------- /disc/disc00/README.md: -------------------------------------------------------------------------------- 1 | Discussion 0 | CS 61A Spring 2024 2 | ================================= 3 | 4 | Discussion 0: Getting Started[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc00#discussion-0-getting-started "Direct link to Discussion 0: Getting Started") 5 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 6 | 7 | * [disc00.pdf](https://www.learncs.site/assets/files/disc00-fd55edbc1ffb6617f04d8cf499aa0693.pdf) 8 | 9 | Congratulations, you found the Discussion 0 worksheet! 10 | 11 | To find your discussion room, check your email. Unless you opted for the mega section, you should have received an email with your discussion group number, location, and time. All discussion groups meet in person. There are multiple groups at a time in each discussion room, so when you arrive, find your group. 12 | 13 | Please start on Berkeley time, 10 minutes after the scheduled start time (12:40, 2:10, or 3:40). Feel free to introduce yourself to the rest of your group while you wait (and check that they really have the same group number as you do). 14 | 15 | If you need help at any time, [join Discord](https://cs61a.org/articles/discord) and message `@discuss` in the `#help` channel. You can also email our course manager Jenna about any scheduling issues: [jiyeonwoo@berkeley.edu](mailto:jiyeonwoo@berkeley.edu) 16 | 17 | Part 0: Meet your group and learn their names \[5 minutes\][​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc00#part-0-meet-your-group-and-learn-their-names-5-minutes "Direct link to part-0-meet-your-group-and-learn-their-names-5-minutes") 18 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 19 | 20 | Order yourselves by birthday: January 1 at the start and December 31 at the end. Then, on your turn, say your name and where you're from, then say the same information for each person who had a turn already, starting from the most recent turn. For example, the intros might go: 21 | 22 | * **Eva**: I'm Eva from Minneapolis 23 | * **Lem**: I'm Lem from San Diego, and \[turning to Eva\] you're Eva from Minneapolis 24 | * **Alyssa**: I'm Alyssa from Sacramento, \[turning to Lem\] you're Lem from San Diego, and \[turning to Eva\] you're Eva from Minneapolis. 25 | 26 | If you forget someone's name or where they're from, that's fine; everybody is here to learn. When it's someone's turn, give them time to try themselves, but if they need help, offer it. 27 | 28 | _Tip_: Now is a great time to write down the names of the people in your group so that you can look them up later. 29 | 30 | **Find your facilitator:** Now figure out who will be your facilitator for the rest of the discussion. Your facilitator is a group member who gets things started in various ways. 31 | 32 | * If you received an email saying that you're a facilitator, please let everyone know now by saying, "I'm the facilitator." 33 | * If there is no facilitator in your group for some reason, then the person with the latest birthday is the facilitator for today. 34 | * If there is more than one facilitator in your group for some reason, then the one with the latest birthday is the facilitator for today. 35 | 36 | Part 1: Connect to Discord and Pensieve \[5 minutes\][​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc00#part-1-connect-to-discord-and-pensieve-5-minutes "Direct link to part-1-connect-to-discord-and-pensieve-5-minutes") 37 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 38 | 39 | Pick someone in your group to [join Discord](https://cs61a.org/articles/discord), find your group's channel, and post "Hello, Staff!" in your group's Discord [text channel](https://support.discord.com/hc/en-us/articles/4412085582359-Text-Channels-Text-Chat-In-Voice-Channels#h_01FMJT412WBX1MR4HDYNR8E95X). It's fine if multiple people join, but one is enough. 40 | 41 | There's a better version of this worksheet that helps groups collaborate. Join it now: 42 | 43 | * **Everyone**: Go to [discuss.pensieve.co](http://discuss.pensieve.co/) and log in with your @berkeley.edu email. 44 | * **Facilitator**: Click "Create Room" and share the room code (boxed in red in the screenshot below) with your group. 45 | * **Others**: Don't create a room; instead, click "Join Room" after typing in the room code that the facilitator shared with you. 46 | * Post in the `#help` channel on Discord if you have trouble. 47 | 48 | ![Pensieve room](https://www.learncs.site/assets/images/img3-e5592b88a990b145e54642835899ebd3.png) 49 | 50 | Once you're on Pensieve, you don't need to return to this page; Pensieve has all the same content (but more features). If for some reason Penseive doesn't work, return to this page and continue with the discussion. 51 | 52 | Part 2: Learn about each other \[30 minutes\][​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc00#part-2-learn-about-each-other-30-minutes "Direct link to part-2-learn-about-each-other-30-minutes") 53 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 54 | 55 | Here's a game called partitions. Each round, you will split your group into two halves with equal numbers of people (or differing by 1 if there are an odd number of people). The goal is for both groups to find a rare fact that all of their members have in common, that no one in the other group also has in common. For example, Group A may find that they are all left-handed, while Group B may find that they all collect Pokémon cards. For each round follow these steps: 56 | 57 | * Step 1: Split into two equal halves (or differing by 1). 58 | * Step 2: The two groups separate for 10 minutes to talk and find some rare fact about them that they all share. 59 | * Step 3: After 10 minutes, regroup and have each group give their shared fact. If no one in the opposing group has that fact in common as well, then everyone in your group scores a point. (So in the above example, if Group A’s fact is that they’re all left-handed, and no one in Group B is left-handed, everyone in Group A scores a point.) 60 | 61 | Play for 2 rounds using 2 different ways of splitting your group into halves. 62 | 63 | **Important**: The facts you choose _cannot_ be determined by sight (such as height or hair color). They also _cannot_ be based on preferences (such as favorite TV show). Some ideas: 64 | 65 | * Places you've been: Paris, Disneyland, In-N-Out 66 | * Things you've tried: zip-lining, meditation, fishing 67 | * Stuff you can do: ski, crochet, juggle, recite digits of pi 68 | 69 | When you're done, it's time for the final challenge! Find a fact that's true about all of you but you don't think is true of your TA. When you're ready, send a message to @discuss in your group's Discord [text channel](https://support.discord.com/hc/en-us/articles/4412085582359-Text-Channels-Text-Chat-In-Voice-Channels#h_01FMJT412WBX1MR4HDYNR8E95X) that says, "Fact time!" Wait for a TA to join, share your fact, and see if it's true of them too. Any facts related to age or education are off limits for the final challenge. 70 | 71 | Part 3: Solve a problem together \[30 minutes\][​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc00#part-3-solve-a-problem-together-30-minutes "Direct link to part-3-solve-a-problem-together-30-minutes") 72 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 73 | 74 | Imagine you can call only the following three functions: 75 | 76 | * `f(x)`: Subtracts one from an integer `x` 77 | * `g(x)`: Doubles an integer `x` 78 | * `h(x, y)`: Concatenates the digits of two different positive integers `x` and `y`. For example, `h(789, 12)` evaluates to `78912` and `h(12, 789)` evaluates to `12789`. 79 | 80 | **Definition**: A _small expression_ is a call expression that contains only `f`, `g`, `h`, the number 5, and parentheses. All of these can be repeated. For example, `h(g(5), f(f(5)))` is a small expression that evaluates to 103. 81 | 82 | What's the shortest _small expression_ you can find that evaluates to 2024? 83 | 84 | Part 4: Document the occasion \[5 minutes\][​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc00#part-4-document-the-occasion-5-minutes "Direct link to part-4-document-the-occasion-5-minutes") 85 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 86 | 87 | Take a group selfie and add it to the [text chat of your group's Discord channel](https://support.discord.com/hc/en-us/articles/4412085582359-Text-Channels-Text-Chat-In-Voice-Channels#h_01FMJT412WBX1MR4HDYNR8E95X). 88 | 89 | Then, please all fill out the [attendance form](https://forms.gle/yH4KNcMN4VSd6mGG6) (one submission per person per week). 90 | 91 | You're done! It's ok if you finish early. You can leave, or you can hang out and discuss how you might use a computer to find the shortest possible _small expression_ that evaluates to 2024. We'll talk about this in Lecture 2. -------------------------------------------------------------------------------- /disc/disc00/disc00.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/disc/disc00/disc00.pdf -------------------------------------------------------------------------------- /disc/disc01/README.md: -------------------------------------------------------------------------------- 1 | Discussion 1 | CS 61A Spring 2024 2 | ================================= 3 | 4 | Discussion 1: Control, Environment Diagrams[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc01#discussion-1-control-environment-diagrams "Direct link to Discussion 1: Control, Environment Diagrams") 5 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 6 | 7 | * [disc01.pdf](https://www.learncs.site/assets/files/disc01-7ba797eb1a45481ca7996f945c9104e0.pdf) 8 | 9 | What everyone will need: 10 | 11 | * A way to view this worksheet (on your phone is fine) 12 | * A way to take notes (paper or a device) 13 | 14 | Pick someone in your group to [join Discord](https://cs61a.org/articles/discord), find your group's channel, and post "Here we go!" in your group's Discord [text channel](https://support.discord.com/hc/en-us/articles/4412085582359-Text-Channels-Text-Chat-In-Voice-Channels#h_01FMJT412WBX1MR4HDYNR8E95X). It's fine if multiple people join, but one is enough. 15 | 16 | **Find your facilitator:** Now figure out who will be your facilitator for the rest of the discussion. 17 | 18 | * If you know you're the facilitator, let your group know. 19 | * If no one is the facilitator, then whoever has the brightest phone case is the facilitator. 20 | 21 | Now switch to Pensieve: 22 | 23 | * **Everyone**: Go to [discuss.pensieve.co](http://discuss.pensieve.co/) and log in with your @berkeley.edu email. 24 | * **Facilitator**: Click _Create Room_, pick this discussion, and share the room code with your group. 25 | * **Others**: Don't create a room; instead, click "Join Room" after typing in the room code that the facilitator shared with you. 26 | * Post in the `#help` channel on Discord if you have trouble. 27 | 28 | Once you're on Pensieve, you don't need to return to this page; Pensieve has all the same content (but more features). If for some reason Penseive doesn't work, return to this page and continue with the discussion. 29 | 30 | Expressions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc01#expressions "Direct link to Expressions") 31 | --------------------------------------------------------------------------------------------------------------------------- 32 | 33 | Say your name and an expression that people say when they really like something, such as "that's awesome" or "nice one". Each person should try to come up with a different expression. Feel free to ask your group for help if you're stuck. You can even use other languages than English. Now you have things to say later in the discussion when the group solves a problem. 34 | 35 | While and If[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc01#while-and-if "Direct link to While and If") 36 | ------------------------------------------------------------------------------------------------------------------------------ 37 | 38 | Learning to use `if` and `while` is an essential skill. During this discussion, focus on what we've studied in the first three lectures: `if`, `while`, assignment (`=`), comparison (`<`, `>`, `==`, ...), and arithmetic. Please don't use features of Python that we haven't discussed in class yet, such as `for`, `range`, and lists. We'll have plenty of time for those later in the course, but now is the time to practice the use of `if` (textbook section [1.5.4](https://www.composingprograms.com/pages/15-control.html#conditional-statements)) and `while` (textbook section [1.5.5](https://www.composingprograms.com/pages/15-control.html#conditional-statements)). 39 | 40 | ### Q1: Race[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc01#q1-race "Direct link to Q1: Race") 41 | 42 | The `race` function below sometimes returns the wrong value and sometimes runs forever. 43 | 44 | Run in 61A Code 45 | 46 | Find positive integers `x` and `y` (with `y` larger than `x` but not larger than `2 * x`) for which either: 47 | 48 | * `race(x, y)` returns the wrong value or 49 | * `race(x, y)` runs forever 50 | 51 | You just need to find one pair of numbers that satisfies either of these conditions to finish the question, but if you want to think of more you can. 52 | 53 | Notes: 54 | 55 | * `x += 1` is the same as `x = x + 1` when `x` is assigned to a number. 56 | * 0 is a false value and all other numbers are true values. 57 | 58 | The value of `race(x, y)` is incorrect when it is not the **first** time the tortoise passes the hare. Try some small numbers (below 5) to see if you can find a case where `tortoise` has become larger than `hare`, but the expression `tortoise - hare` was not zero when it happened. 59 | 60 | Put your `(x, y)` examples in the [text chat](https://support.discord.com/hc/en-us/articles/4412085582359-Text-Channels-Text-Chat-In-Voice-Channels#h_01FMJT412WBX1MR4HDYNR8E95X) of your group's voice channel. If you get stuck for more than 10 minutes, ask for help! 61 | 62 | ### Q2: Fizzbuzz[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc01#q2-fizzbuzz "Direct link to Q2: Fizzbuzz") 63 | 64 | Implement the classic [_Fizz Buzz_ sequence](https://en.wikipedia.org/wiki/Fizz_buzz). The `fizzbuzz` function takes a positive integer `n` and prints out a _single line_ for each integer from 1 to `n`. For each `i`: 65 | 66 | * If `i` is divisible by both 3 and 5, print `fizzbuzz`. 67 | * If `i` is divisible by 3 (but not 5), print `fizz`. 68 | * If `i` is divisible by 5 (but not 3), print `buzz`. 69 | * Otherwise, print the number `i`. 70 | 71 | Try to make your implementation of `fizzbuzz` concise. 72 | 73 | Run in 61A Code 74 | 75 | Be careful about the order of your `if` and `elif` clauses: try first checking if the current number is divisible by both 3 and 5, then check for just divisibility by 3 and just divisibility by 5. 76 | 77 | Problem Solving[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc01#problem-solving "Direct link to Problem Solving") 78 | --------------------------------------------------------------------------------------------------------------------------------------- 79 | 80 | A useful approach to implementing a function is to: 81 | 82 | 1. Pick an example input and corresponding output. 83 | 2. Describe a process (in English) that computes the output from the input using simple steps. 84 | 3. Figure out what additional names you'll need to carry out this process. 85 | 4. Implement the process in code using those additional names. 86 | 5. Determine whether the implementation really works on your original example. 87 | 6. Determine whether the implementation really works on other examples. (If not, you might need to revise step 2.) 88 | 89 | Importantly, this approach doesn't go straight from reading a question to writing code. 90 | 91 | For example, in the `is_prime` problem below, you could: 92 | 93 | 1. Pick `n` is 9 as the input and `False` as the output. 94 | 2. Here's a process: Check that `9` (`n`) is not a multiple of any integers between 1 and `9` (`n`). 95 | 3. Introduce `i` to represent each number between 1 and 9 (`n`). 96 | 4. Implement `is_prime` (you get to do this part with your group). 97 | 5. Check that `is_prime(9)` will return `False` by thinking through the execution of the code. 98 | 6. Check that `is_prime(3)` will return `True` and `is_prime(1)` will return `False`. 99 | 100 | Try this approach together on the next two problems. 101 | 102 | **Important:** It's highly recommended that you **don't** check your work using a computer right away. Instead, talk to your group and think to try to figure out if an answer is correct. On exams, you won't be able to guess and check because you won't have a Python interpreter. Now is a great time to practice checking your work by thinking through examples. You could even draw an environment diagram! 103 | 104 | If you're not sure about how something works or get stuck, ask for help from the course staff. 105 | 106 | ### Q3: Is Prime?[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc01#q3-is-prime "Direct link to Q3: Is Prime?") 107 | 108 | Write a function that returns `True` if a positive integer `n` is a prime number and `False` otherwise. 109 | 110 | A prime number n is a number that is not divisible by any numbers other than 1 and n itself. For example, 13 is prime, since it is only divisible by 1 and 13, but 14 is not, since it is divisible by 1, 2, 7, and 14. 111 | 112 | Use the `%` operator: `x % y` returns the remainder of `x` when divided by `y`. 113 | 114 | Here's a `while` statement that goes through all numbers above 1 and below `n` : 115 | 116 | i = 2while i < n: ... i = i + 1 117 | 118 | You can use `n % i == 0` to check whether `i` is a factor of `n`. If it is, `return False`. 119 | 120 | Run in 61A Code 121 | 122 | **Presentation Time**: Come up with a **one sentence description** of the process you implemented to solve `is_prime` that you think someone could understand without looking at your code. Pick someone to present, then send a message to the `discuss-queue` channel with the `@discuss` tag, your discussion group number, and the message "Prime Time!" and a member of the course staff will join your voice channel to hear your description and give feedback. 123 | 124 | ### Q4: Unique Digits[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc01#q4-unique-digits "Direct link to Q4: Unique Digits") 125 | 126 | Write a function that returns the number of unique digits in a positive integer. 127 | 128 | > **Hints:** You can use `//` and `%` to separate a positive integer into its one's digit and the rest of its digits. 129 | > 130 | > You may find it helpful to first define a function `has_digit(n, k)`, which determines whether a number `n` has digit `k`. 131 | 132 | Run in 61A Code 133 | 134 | One approach is to loop through every digit from 0 to 9 and check whether `n` has the digit. Count up the ones it has. 135 | 136 | Environment Diagrams[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc01#environment-diagrams "Direct link to Environment Diagrams") 137 | ------------------------------------------------------------------------------------------------------------------------------------------------------ 138 | 139 | An **environment diagram** keeps track of names and their values in frames, which are drawn as boxes. 140 | 141 | ### Q5: Bottles[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc01#q5-bottles "Direct link to Q5: Bottles") 142 | 143 | Answer the following questions with your group. Step through the diagram to check your answers. 144 | 145 | 1) What determines how many different frames appear in an environment diagram? 146 | 147 | * The number of functions defined in the code 148 | * The number of call expressions in the code 149 | * The number of return statements in the code 150 | * The number of times user-defined functions are called when running the code 151 | 152 | 2) What happens to the return value of `pass(bottles)`? 153 | 154 | * It is used as the new value of `remaining` in the global frame 155 | * It is used as the new value of `bottles` in the global frame 156 | * It is used as the new value of `pass` in the global frame 157 | * None of the above 158 | 159 | 3) What effect does the line `bottles = 98` have on the global frame? 160 | 161 | * It temporarily changes the value bound to `bottles` in the global frame. 162 | * It permanently changes the value bound to `bottles` in the global frame. 163 | * It has no effect on the global frame. 164 | 165 | ### Q6: Double Trouble[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc01#q6-double-trouble "Direct link to Q6: Double Trouble") 166 | 167 | Draw the environment diagram on paper or a whiteboard (without having the computer draw it for you)! Then, check your work by stepping through the diagram. 168 | 169 | Document the occasion[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc01#document-the-occasion "Direct link to Document the occasion") 170 | --------------------------------------------------------------------------------------------------------------------------------------------------------- 171 | 172 | If you'd like, take another group selfie and add it to the text chat of your group's Discord channel. Then, please all fill out the [attendance form](https://docs.google.com/forms/d/e/1FAIpQLSeqlK8l6WkScGr-RHR-kM4p5bnR9cllYrG95fDqPJspSlll7A/viewform) (one submission per person per week). 173 | 174 | -------------------------------------------------------------------------------- /disc/disc01/disc01.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/disc/disc01/disc01.pdf -------------------------------------------------------------------------------- /disc/disc02/README.md: -------------------------------------------------------------------------------- 1 | Discussion 2 | CS 61A Spring 2024 2 | ================================= 3 | 4 | Discussion 2: Environment Diagrams, Higher-Order Functions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc02#discussion-2-environment-diagrams-higher-order-functions "Direct link to Discussion 2: Environment Diagrams, Higher-Order Functions") 5 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 6 | 7 | * [disc02.pdf](https://www.learncs.site/assets/files/disc02-43b466125880fe43f9c3b7fcedc64214.pdf) 8 | 9 | Pick someone in your group to [join Discord](https://cs61a.org/articles/discord). It's fine if multiple people join, but one is enough. 10 | 11 | Now switch to Pensieve: 12 | 13 | * **Everyone**: Go to [discuss.pensieve.co](http://discuss.pensieve.co/) and log in with your @berkeley.edu email, then enter your group number. (Your group number is the number of your Discord channel.) 14 | 15 | Once you're on Pensieve, you don't need to return to this page; Pensieve has all the same content (but more features). If for some reason Penseive doesn't work, return to this page and continue with the discussion. 16 | 17 | Post in the `#help` channel on [Discord](https://cs61a.org/articles/discord/) if you have trouble. 18 | 19 | Getting Started \[5 minutes\][​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc02#getting-started-5-minutes "Direct link to getting-started-5-minutes") 20 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 21 | 22 | Say your name and a city (or place) that you like, which is not Berkeley and is not where you have lived. Feel free to share why you like it. 23 | 24 | **VERY IMPORTANT:** In this discussion, don't press _Check Answer_ or run any Python code until your whole group is sure that the answer is right. Your goal should be to have all checks pass the first time! Figure things out and check your work by _thinking_ about what your code will do. Not sure? Talk to your group! (You won't get to run Python during the midterm, so get used to solving problems without it now.) 25 | 26 | ### Q1: Warm Up[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc02#q1-warm-up "Direct link to Q1: Warm Up") 27 | 28 | What is the value of `result` after executing `result = (lambda x: 2 * (lambda x: 3)(4) * x)(5)`? Talk about it with your whole group and make sure you all agree before anybody presses _Check Answer_. 29 | 30 | Call Expressions \[15 minutes\][​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc02#call-expressions-15-minutes "Direct link to call-expressions-15-minutes") 31 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 32 | 33 | Draw an environment diagram for the code below. You can use paper or a tablet or the whiteboard. Talk to your group about how you are going to draw it, then go through each step _together_. Then, step through the diagram to check your work. 34 | 35 | Here's a blank diagram in case you're using a tablet: 36 | 37 | ![template](https://www.learncs.site/assets/images/A9nnHPb-2977a590cb9b8a46c05b4ae094551544.png) 38 | 39 | If you have questions, send a message to the `discuss-queue` channel with the @discuss tag and your discussion group number and talk it through with someone from the course staff. 40 | 41 | Higher-Order Functions \[60 minutes\][​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc02#higher-order-functions-60-minutes "Direct link to higher-order-functions-60-minutes") 42 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 43 | 44 | Remember the problem-solving approach from last discussion; it works just as well for implementing higher-order functions. 45 | 46 | 1. Pick an example input and corresponding output. _(This time it might be a function.)_ 47 | 2. Describe a process (in English) that computes the output from the input using simple steps. 48 | 3. Figure out what additional names you'll need to carry out this process. 49 | 4. Implement the process in code using those additional names. 50 | 5. Determine whether the implementation really works on your original example. 51 | 6. Determine whether the implementation really works on other examples. (If not, you might need to revise step 2.) 52 | 53 | ### Q2: Make Keeper[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc02#q2-make-keeper "Direct link to Q2: Make Keeper") 54 | 55 | Implement `make_keeper`, which takes a positive integer `n` and returns a function `f` that takes as its argument another one-argument function `cond`. When `f` is called on `cond`, it prints out the integers from 1 to `n` (including `n`) for which `cond` returns a true value when called on each of those integers. Each integer is printed on a separate line. 56 | 57 | Run in 61A Code 58 | 59 | No peeking! First try to implement it without the hint. 60 | 61 | To return a function `f`, include `def f(cond):` as the first line of the implementation and `return f` as the last. The `f` function should introduce `i = 1` in order to loop through all integers, calling `cond(i)` to determine whether `cond` returns true for each integer. 62 | 63 | **Don't run Python to check your work. You can check it just by thinking!**. If you get stuck, ask the staff for help. 64 | 65 | Once your group has converged on a solution, now it's time to practice your ability to describe your own code. A good description is like a good program: concise and accurate. Nominate someone to describe how your solution works and have them present to the group for practice. Then, send a message to the `discuss-queue` channel with the @discuss tag, your discussion group number, and the message "Listen up!" and a member of the course staff will join your voice channel to hear your description. If no one comes right away, feel free to work on the next problem until someone from the staff shows up. 66 | 67 | ### Q3: Digit Finder[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc02#q3-digit-finder "Direct link to Q3: Digit Finder") 68 | 69 | Implement `find_digit`, which takes in a positive integer `k` and returns a function that takes in a positive integer `x` and returns the `k`th digit from the right of `x`. If `x` has fewer than `k` digits, it returns 0. 70 | 71 | For example, in the number 4567, 7 is the 1st digit from the right, 6 is the 2nd digit from the right, and the 5th digit from the right is 0 (since there are only 4 digits). 72 | 73 | **Important:** You may not use strings or indexing for this problem. 74 | 75 | Use floor dividing by a power of 10 gets rid of the rightmost digits. 76 | 77 | Run in 61A Code 78 | 79 | First remove all of the digits after digit `k`, at which point digit `k` will be the last digit. 80 | 81 | ### Q4: Match Maker[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc02#q4-match-maker "Direct link to Q4: Match Maker") 82 | 83 | Implement `match_k`, which takes in an integer `k` and returns a function that takes in a variable `x` and returns `True` if all the digits in `x` that are `k` apart are the same. 84 | 85 | For example, `match_k(2)` returns a one argument function that takes in `x` and checks if digits that are 2 away in `x` are the same. 86 | 87 | `match_k(2)(1010)` has the value of `x = 1010` and digits 1, 0, 1, 0 going from left to right. `1 == 1` and `0 == 0`, so the `match_k(2)(1010)` results in `True`. 88 | 89 | `match_k(2)(2010)` has the value of `x = 2010` and digits 2, 0, 1, 0 going from left to right. `2 != 1` and `0 == 0`, so the `match_k(2)(2010)` results in `False`. 90 | 91 | **Important:** You may not use strings or indexing for this problem. 92 | 93 | Floor dividing by powers of 10 gets rid of the rightmost digits. 94 | 95 | Run in 61A Code 96 | 97 | In each iteration, compare the last digit with the one that is `k` positions before it. 98 | 99 | Document the occasion[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc02#document-the-occasion "Direct link to Document the occasion") 100 | --------------------------------------------------------------------------------------------------------------------------------------------------------- 101 | 102 | Please all fill out the [attendance form](https://docs.google.com/forms/d/e/1FAIpQLSeqlK8l6WkScGr-RHR-kM4p5bnR9cllYrG95fDqPJspSlll7A/viewform) (one submission per person per week). -------------------------------------------------------------------------------- /disc/disc02/disc02.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/disc/disc02/disc02.pdf -------------------------------------------------------------------------------- /disc/disc03/README.md: -------------------------------------------------------------------------------- 1 | Discussion 3 | CS 61A Spring 2024 2 | ================================= 3 | 4 | Discussion 3: Recursion[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc03#discussion-3-recursion "Direct link to Discussion 3: Recursion") 5 | -------------------------------------------------------------------------------------------------------------------------------------------------------------- 6 | 7 | * [disc03.pdf](https://www.learncs.site/assets/files/disc03-53861a636dd8c09aa90c785940541179.pdf) 8 | 9 | Pick someone in your group to [join Discord](https://cs61a.org/articles/discord). It's fine if multiple people join, but one is enough. 10 | 11 | Now switch to Pensieve: 12 | 13 | * **Everyone**: Go to [discuss.pensieve.co](http://discuss.pensieve.co/) and log in with your @berkeley.edu email, then enter your group number. (Your group number is the number of your Discord channel.) 14 | 15 | Once you're on Pensieve, you don't need to return to this page; Pensieve has all the same content (but more features). If for some reason Penseive doesn't work, return to this page and continue with the discussion. 16 | 17 | Post in the `#help` channel on [Discord](https://cs61a.org/articles/discord/) if you have trouble. 18 | 19 | Getting Started[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc03#getting-started "Direct link to Getting Started") 20 | --------------------------------------------------------------------------------------------------------------------------------------- 21 | 22 | Say your name and share a food that you really liked as a child. (It's ok if you still like that food now.) 23 | 24 | **Suggestion:** After Midterm 1, some students are looking for more effective ways to study. One great option is to meet up with your discussion group outside of class to review practice problems together. Now is a great time to schedule a time and place for some extra group practice of old Midterm 1 questions. This is optional and not everyone needs to come, but if there are Midterm 1 topics that haven't totally clicked yet, this weekend is a perfect time to review them. 25 | 26 | Everything in this course builds on prior topics, and it's going to be hard to keep up if you don't have a solid understanding of Midterm 1 material. 27 | 28 | Remember, it's ok if someone hasn't learned everything yet and needs more time to master the course material. The whole point of the course is for students to learn things they don't already know. Please support each other in the process. 29 | 30 | Recursion[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc03#recursion "Direct link to Recursion") 31 | --------------------------------------------------------------------------------------------------------------------- 32 | 33 | Ok, time to discuss problems! Remember to work together. Everyone in the group should understand a solution before the group moves on. Many students find this discussion challenging. Everything gets easier with practice. 34 | 35 | **VERY IMPORTANT:** In this discussion, don't check your answers until your whole group is sure that the answer is right. Figure things out and check your work by _thinking_ about what your code will do. Your goal should be to have all checks pass the first time you run them! If you need help, ask. 36 | 37 | ### Q1: Swipe[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc03#q1-swipe "Direct link to Q1: Swipe") 38 | 39 | Implement `swipe`, which prints the digits of argument `n`, one per line, first backward then forward. The left-most digit is printed only once. Do not use `while` or `for` or `str`. (Use recursion, of course!) 40 | 41 | Run in 61A Code 42 | 43 | First `print` the first line of the output, then make a recursive call, then `print` the last line of the output. 44 | 45 | ### Q2: Skip Factorial[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc03#q2-skip-factorial "Direct link to Q2: Skip Factorial") 46 | 47 | Define the base case for the `skip_factorial` function, which returns the product of every other positive integer, starting with `n`. 48 | 49 | Run in 61A Code 50 | 51 | If `n` is even, then the base case will be 2. If `n` is odd, then the base case will be 1. Try to write a condition that handles both possibilities. 52 | 53 | ### Q3: Is Prime[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc03#q3-is-prime "Direct link to Q3: Is Prime") 54 | 55 | Implement `is_prime` that takes an integer `n` greater than 1. It returns `True` if `n` is a prime number and `False` otherwise. Try following the approach below, but implement it recursively without using a `while` (or `for`) statement. 56 | 57 | def is_prime(n): assert n > 1 i = 2 while i < n: if n % i == 0: return False i = i + 1 return True 58 | 59 | You will need to define another "helper" function (a function that exists just to help implement this one). Does it matter whether you define it within `is_prime` or as a separate function in the global frame? Try to define it to take as few arguments as possible. 60 | 61 | Run in 61A Code 62 | 63 | Define an inner function that checks whether some integer between `i` and `n` evenly divides `n`. Then you can call it starting with `i=2`: 64 | 65 | def is_prime(n): def f(i): if n % i == 0: return ____ elif ____: return ____ else: return f(____) return f(2) 66 | 67 | Come up with a one sentence docstring for the helper function that describes what it does. Don't just write, "it helps implement `is_prime`." Instead, describe its behavior. When you're done, paste the text of that docstring in your group's [channel's text chat](https://support.discord.com/hc/en-us/articles/4412085582359-Text-Channels-Text-Chat-In-Voice-Channels#h_01FMJT412WBX1MR4HDYNR8E95X). 68 | 69 | ### Q4: Recursive Hailstone[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc03#q4-recursive-hailstone "Direct link to Q4: Recursive Hailstone") 70 | 71 | Recall the `hailstone` function from [Homework 1](https://cs61a.org/hw/hw01/). First, pick a positive integer `n` as the start. If `n` is even, divide it by 2. If `n` is odd, multiply it by 3 and add 1. Repeat this process until `n` is 1. Complete this recursive version of `hailstone` that prints out the values of the sequence and returns the number of steps. 72 | 73 | Run in 61A Code 74 | 75 | An even number is never a base case, so `even` always makes a recursive call to `hailstone` and returns one more than the length of the rest of the hailstone sequence. 76 | 77 | An odd number might be 1 (the base case) or greater than one (the recursive case). Only the recursive case should call `hailstone`. 78 | 79 | Once your group has converged on a solution, it's time to practice your ability to describe your own code. Pick a presenter, then send a message to the `discuss-queue` channel with the @discuss tag, your discussion group number, and the message "Hailing all course staff!" and a member of the course staff will join your voice channel to hear your description. 80 | 81 | Document the Occasion[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc03#document-the-occasion "Direct link to Document the Occasion") 82 | --------------------------------------------------------------------------------------------------------------------------------------------------------- 83 | 84 | Please all fill out the [attendance form](https://docs.google.com/forms/d/e/1FAIpQLSeqlK8l6WkScGr-RHR-kM4p5bnR9cllYrG95fDqPJspSlll7A/viewform) (one submission per person per week). 85 | 86 | You'll need your whole discussion group for this question. At least try it out. You might have fun. We'll review the question in lecture on Friday. 87 | 88 | ### Q5: Sevens[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc03#q5-sevens "Direct link to Q5: Sevens") 89 | 90 | **The Game of Sevens**: Players in a circle count up from 1 in the clockwise direction. (The starting player says 1, the player to their left says 2, etc.) If a number is divisible by 7 or contains a 7 (or both), switch directions. Numbers must be said on the beat at [60 beats per minute](https://www.youtube.com/watch?v=ymJIXzvDvj4). If someone says a number when it's not their turn or someone misses the beat on their turn, the game ends. 91 | 92 | For example, 5 people would count to 20 like this: 93 | 94 | Player 1 says 1Player 2 says 2Player 3 says 3Player 4 says 4Player 5 says 5Player 1 says 6 # All the way around the circlePlayer 2 says 7 # Switch to counterclockwisePlayer 1 says 8Player 5 says 9 # Back around the circle counterclockwisePlayer 4 says 10Player 3 says 11Player 2 says 12Player 1 says 13Player 5 says 14 # Switch back to clockwisePlayer 1 says 15Player 2 says 16Player 3 says 17 # Switch back to counterclockwisePlayer 2 says 18Player 1 says 19Player 5 says 20 95 | 96 | Play a few games. Post the highest score your group reached on Discord. 97 | 98 | Then, implement `sevens` which takes a positive integer `n` and a number of players `k`. It returns which of the `k` players says `n`. You may call `has_seven`. 99 | 100 | An effective approach to this problem is to simulate the game, stopping on turn `n`. The implementation must keep track of the final number `n`, the current number `i`, the player `who` will say `i`, and the current `direction` that determines the next player (either increasing or decreasing). It works well to use integers to represent all of these, with `direction` switching between `1` (increase) and `-1` (decreasing). 101 | 102 | Run in 61A Code 103 | 104 | First check if `i` is a multiple of 7 or contains a 7, and if so, switch directions. Then, add the direction to `who` and ensure that `who` has not become smaller than 1 or greater than `k`. 105 | 106 | ### Q6: Karel the Robot[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc03#q6-karel-the-robot "Direct link to Q6: Karel the Robot") 107 | 108 | [Karel the robot](https://compedu.stanford.edu/karel-reader/docs/python/en/chapter1.html) starts in the corner of an `n` by `n` square for some unknown number `n`. Karel responds to only four functions: 109 | 110 | * `move()` moves Karel one square forward if there is no wall in front of Karel and errors if there is. 111 | * `turn_left()` turns Karel 90 degrees to the left. 112 | * `front_is_blocked()` returns whether there is a wall in front of Karel. 113 | * `front_is_clear()` returns whether there is no wall in front of Karel. 114 | 115 | Implement a `main()` function that will leave Karel stopped halfway in the middle of the bottom row. For example, if the square is 7 x 7 and Karel starts in position (1, 1), the bottom left, then Karel should end in position (1, 4) (three steps from either side on the bottom row). Karel can be facing in any direction at the end. If the bottom row length is even, Karel can stop in either position (1, `n // 2`) or (1, `n // 2 + 1`). 116 | 117 | **Important** You can only write `if` or `if`/`else` statements and function calls in the body of `main()`. You may not write assignment statements, def statements, lambda expressions, or while/for statements. 118 | 119 | For every two steps forward, take one step back to end up in the middle. -------------------------------------------------------------------------------- /disc/disc03/disc03.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/disc/disc03/disc03.pdf -------------------------------------------------------------------------------- /disc/disc04/README.md: -------------------------------------------------------------------------------- 1 | Discussion 4 | CS 61A Spring 2024 2 | ================================= 3 | 4 | Discussion 4: Tree Recursion[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc04#discussion-4-tree-recursion "Direct link to Discussion 4: Tree Recursion") 5 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 6 | 7 | * [disc04.pdf](https://www.learncs.site/assets/files/disc04-8fcabd16db80d61c0d210604b6028dea.pdf) 8 | 9 | Pick someone in your group to [join Discord](https://cs61a.org/articles/discord). It's fine if multiple people join, but one is enough. 10 | 11 | Now switch to Pensieve: 12 | 13 | * **Everyone**: Go to [discuss.pensieve.co](http://discuss.pensieve.co/) and log in with your @berkeley.edu email, then enter your group number. (Your group number is the number of your Discord channel.) 14 | 15 | Once you're on Pensieve, you don't need to return to this page; Pensieve has all the same content (but more features). If for some reason Penseive doesn't work, return to this page and continue with the discussion. 16 | 17 | Post in the `#help` channel on [Discord](https://cs61a.org/articles/discord/) if you have trouble. 18 | 19 | Getting Started[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc04#getting-started "Direct link to Getting Started") 20 | --------------------------------------------------------------------------------------------------------------------------------------- 21 | 22 | Say your name and your favorite tree (a particular tree or a kind of tree) in honor of today's topic: tree recursion. (Tree recursive functions are functions that call themselves more than once.) 23 | 24 | In this discussion, don't use a Python interpreter to run code until you are confident your solution is correct. Figure things out and check your work by _thinking_ about what your code will do. Not sure? Talk to your group! 25 | 26 | **\[New\]** If you have fewer than 4 people in your group, you can merge with another group in the room with you. 27 | 28 | **\[New\]** Recursion takes practice. Please don't get discouraged if you're struggling to write recursive functions. Instead, every time you do solve one (even with help or in a group), make note of what you had to realize to make progress. Students improve through practice and reflection. 29 | 30 | **\[For Fun\]** This emoticon of a guy in a cowboy hat is valid Python: `o[:-D]` 31 | 32 | >>> o = [2, 0, 2, 4]>>> [ o[:-D] for D in range(1,4) ][[2, 0, 2], [2, 0], [2]] 33 | 34 | 🤠 35 | 36 | Tree Recursion[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc04#tree-recursion "Direct link to Tree Recursion") 37 | ------------------------------------------------------------------------------------------------------------------------------------ 38 | 39 | For the following questions, don't start trying to write code right away. Instead, start by describing the recursive case in words. Some examples: 40 | 41 | * In `fib` from lecture, the recursive case is to add together the previous two Fibonacci numbers. 42 | * In `double_eights` from lab, the recursive case is to check for double eights in the rest of the number. 43 | * In `count_partitions` from lecture, the recursive case is to partition `n-m` using parts up to size `m` **and** to partition `n` using parts up to size `m-1`. 44 | 45 | ### Q1: Insect Combinatorics[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc04#q1-insect-combinatorics "Direct link to Q1: Insect Combinatorics") 46 | 47 | An insect is inside an `m` by `n` grid. The insect starts at the bottom-left corner `(1, 1)` and wants to end up at the top-right corner `(m, n)`. The insect can only move up or to the right. Write a function `paths` that takes the height and width of a grid and returns the number of paths the insect can take from the start to the end. (There is a [closed-form solution](https://en.wikipedia.org/wiki/Closed-form_expression) to this problem, but try to answer it with recursion.) 48 | 49 | ![Insect grids.](https://www.learncs.site/assets/images/grid-b3ad3b8384cd4cef168b8070828e50d3.jpg) 50 | 51 | In the `2` by `2` grid, the insect has two paths from the start to the end. In the `3` by `3` grid, the insect has six paths (only three are shown above). 52 | 53 | > **Hint:** What happens if the insect hits the upper or rightmost edge of the grid? 54 | 55 | Run in 61A Code 56 | 57 | **Presentation Time:** Once your group has converged on a solution, it's time to practice your ability to describe why your recursive case is correct. Pick a presenter, then send a message to the discuss-queue channel with the @discuss tag, your discussion group number, and the message "Here's the path!" and a member of the course staff will join your voice channel to hear your description and give feedback. 58 | 59 | Tree Recursion with Lists[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc04#tree-recursion-with-lists "Direct link to Tree Recursion with Lists") 60 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 61 | 62 | **\[New\]** Some of you already know list operations that we haven't covered yet, such as `append`. Don't use those today. All you need are list literals (e.g., `[1, 2, 3]`), item selection (e.g., `s[0]`), list addition (e.g., `[1] + [2, 3]`), `len` (e.g., `len(s)`), and slicing (e.g., `s[1:]`). Use those! There will be plenty of time for other list operations when we introduce them next week. 63 | 64 | The most important thing to remember about lists is that a non-empty list `s` can be split into its first element `s[0]` and the rest of the list `s[1:]`. 65 | 66 | >>> s = [2, 3, 6, 4]>>> s[0]2>>> s[1:][3, 6, 4] 67 | 68 | ### Q2: Max Product[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc04#q2-max-product "Direct link to Q2: Max Product") 69 | 70 | Implement `max_product`, which takes a list of numbers and returns the maximum product that can be formed by multiplying together non-consecutive elements of the list. Assume that all numbers in the input list are greater than or equal to 1. 71 | 72 | Run in 61A Code 73 | 74 | First try multiplying the first element by the `max_product` of everything after the first two elements (skipping the second element because it is consecutive with the first), then try skipping the first element and finding the `max_product` of the rest. To find which of these options is better, use `max`. 75 | 76 | A great way to get help is to talk to the course staff! 77 | 78 | Complete this sentence together and type your answer into your group's [channel's text chat](https://support.discord.com/hc/en-us/articles/4412085582359-Text-Channels-Text-Chat-In-Voice-Channels#h_01FMJT412WBX1MR4HDYNR8E95X). "The recursive case is to choose the larger of ... and ..." 79 | 80 | ### Q3: Sum Fun[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc04#q3-sum-fun "Direct link to Q3: Sum Fun") 81 | 82 | Implement `sums(n, m)`, which takes a total `n` and maximum `m`. It returns a list of all lists: 83 | 84 | 1. that sum to `n`, 85 | 2. that contain only positive numbers up to `m`, and 86 | 3. in which no two adjacent numbers are the same. 87 | 88 | Two lists with the same numbers in a different order should both be returned. 89 | 90 | Here's a recursive approach that matches the template below: build up the `result` list by building all lists that sum to `n` and start with `k`, for each `k` from 1 to `m`. For example, the result of `sums(5, 3)` is made up of three lists: 91 | 92 | * `[[1, 3, 1]]` starts with 1, 93 | * `[[2, 1, 2], [2, 3]]` start with 2, and 94 | * `[[3, 2]]` starts with 3. 95 | 96 | **Hint:** Use `[k] + s` for a number `k` and list `s` to build a list that starts with `k` and then has all the elements of `s`. 97 | 98 | >>> k = 2>>> s = [4, 3, 1]>>> [k] + s[2, 4, 3, 1] 99 | 100 | Run in 61A Code 101 | 102 | `k` is the first number in a list that sums to `n`, and `rest` is the rest of that list, so build a list that sums to `n`. 103 | 104 | Call `sums` to build all of the lists that sum to `n-k` so that they can be used to construct lists that sum to `n` by putting a `k` on the front. 105 | 106 | Here is where you ensure that "no two adjacent numbers are the same." Since `k` will be the first number in the list you're building, it must not be equal to the first element of `rest` (which will be the second number in the list you're building). 107 | 108 | If you get stuck and want to talk with the staff, post on Discord! 109 | 110 | Document the Occasion[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc04#document-the-occasion "Direct link to Document the Occasion") 111 | --------------------------------------------------------------------------------------------------------------------------------------------------------- 112 | 113 | Please all fill out the [attendance form](https://docs.google.com/forms/d/e/1FAIpQLSeqlK8l6WkScGr-RHR-kM4p5bnR9cllYrG95fDqPJspSlll7A/viewform) (one submission per person per week). -------------------------------------------------------------------------------- /disc/disc04/disc04.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/disc/disc04/disc04.pdf -------------------------------------------------------------------------------- /disc/disc05/README.md: -------------------------------------------------------------------------------- 1 | Discussion 5 | CS 61A Spring 2024 2 | ================================= 3 | 4 | Discussion 5: Trees[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc05#discussion-5-trees "Direct link to Discussion 5: Trees") 5 | -------------------------------------------------------------------------------------------------------------------------------------------------- 6 | 7 | * [disc05.pdf](https://www.learncs.site/assets/files/disc05-2cf1b0e996095933053755a467d5a939.pdf) 8 | 9 | Pick someone in your group to [join Discord](https://cs61a.org/articles/discord). It's fine if multiple people join, but one is enough. 10 | 11 | Now switch to Pensieve: 12 | 13 | * **Everyone**: Go to [discuss.pensieve.co](http://discuss.pensieve.co/) and log in with your @berkeley.edu email, then enter your group number. (Your group number is the number of your Discord channel.) 14 | 15 | Once you're on Pensieve, you don't need to return to this page; Pensieve has all the same content (but more features). If for some reason Penseive doesn't work, return to this page and continue with the discussion. 16 | 17 | Post in the `#help` channel on [Discord](https://cs61a.org/articles/discord/) if you have trouble. 18 | 19 | Getting Started[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc05#getting-started "Direct link to Getting Started") 20 | --------------------------------------------------------------------------------------------------------------------------------------- 21 | 22 | Everyone go around and say your name, just in case someone forgot. 23 | 24 | **For fun:** Think of a big word with at least three syllables, such as "solitary" or "conundrum" or "ominous". Try to use it as many times as you can during today's discussion, but in ways that don't give away that it's your big word. At the end, your group will try to guess each person's big word. Whoever uses their big word the most times (and at least twice) without their group guessing it wins. (You win nothing; it's just a game.) 25 | 26 | **To get help from a TA**, send a message to the `discuss-queue` channel with the @discuss tag and your discussion group number. 27 | 28 | If you have fewer than 4 people in your group, you can merge with another group in the room with you. 29 | 30 | The most common suggestion from last discussion was to add some hints, so we have. The second most common suggestion was to encourage more discussion and collaboration. Discuss and collaborate! 31 | 32 | Trees[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc05#trees "Direct link to Trees") 33 | --------------------------------------------------------------------------------------------------------- 34 | 35 | For a tree `t`: 36 | 37 | * Its root label can be any value, and `label(t)` returns it. 38 | * Its branches are trees, and `branches(t)` returns a list of branches. 39 | * An identical tree can be constructed with `tree(label(t), branches(t))`. 40 | * You can call functions that take trees as arguments, such as `is_leaf(t)`. 41 | * That's how you work with trees. No `t == x` or `t[0]` or `x in t` or `list(t)`, etc. 42 | * There's no way to change a tree (that doesn't violate an abstraction barrier). 43 | 44 | Here's an example tree `t1`, for which its branch `branches(t1)[1]` is `t2`. 45 | 46 | t2 = tree(5, [tree(6), tree(7)])t1 = tree(3, [tree(4), t2]) 47 | 48 | ![Example Tree](https://www.learncs.site/assets/images/example_tree_illustration-f92648cd31ed7e203a304e16bd59c08a.png) 49 | 50 | A path is a sequence of trees in which each is the parent of the next. 51 | 52 | You don't need to know how `tree`, `label`, and `branches` are implemented in order to use them correctly, but here is the implementation from lecture. 53 | 54 | def tree(label, branches=[]): for branch in branches: assert is_tree(branch), 'branches must be trees' return [label] + list(branches)def label(tree): return tree[0]def branches(tree): return tree[1:]def is_leaf(tree): return not branches(tree)def is_tree(tree): if type(tree) != list or len(tree) < 1: return False for branch in branches(tree): if not is_tree(branch): return False return True 55 | 56 | ### Q1: Warm Up[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc05#q1-warm-up "Direct link to Q1: Warm Up") 57 | 58 | What value is bound to `result`? 59 | 60 | result = label(min(branches(max([t1, t2], key=label)), key=label)) 61 | 62 | How convoluted! (That's a big word.) 63 | 64 | Here's a quick refresher on how `key` functions work with `max` and `min`, 65 | 66 | `max(s, key=f)` returns the item `x` in `s` for which `f(x)` is largest. 67 | 68 | >>> s = [-3, -5, -4, -1, -2]>>> max(s)-1>>> max(s, key=abs)-5>>> max([abs(x) for x in s])5 69 | 70 | Therefore, `max([t1, t2], key=label)` returns the tree with the largest label, in this case `t2`. 71 | 72 | In case you're wondering, this expression does not violate an abstraction barrier. `[t1, t2]` and `branches(t)` are both lists (not trees), and so it's fine to call `min` and `max` on them. 73 | 74 | ### Q2: Has Path[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc05#q2-has-path "Direct link to Q2: Has Path") 75 | 76 | Implement `has_path`, which takes a tree `t` and a list `p`. It returns whether there is a path from the root of `t` with labels `p`. For example, `t1` has a path from its root with labels `[3, 5, 6]` but not `[3, 4, 6]` or `[5, 6]`. 77 | 78 | **Important**: Before trying to implement this function, discuss these questions from lecture about the recursive call of a tree processing function: 79 | 80 | * What recursive calls will you make? 81 | * What type of values do they return? 82 | * What do the possible return values mean? 83 | * How can you use those return values to complete your implementation? 84 | 85 | If you get stuck, you can view our answers to these questions by clicking the hint button below, but _please_ don't do that until your whole group agrees. 86 | 87 | **What recursive calls will you make?** 88 | 89 | As you usual, you will call `has_path` on each branch `b`. You'll make this call after comparing `p[0]` to `label(t)`, and so the second argument to `has_path` will be the rest of `p`: `has_path(b, p[1:])`. 90 | 91 | **What type of values do they return?** 92 | 93 | `has_path` always returns a `bool` value: `True` or `False`. 94 | 95 | **What do the possible return values mean?** 96 | 97 | If `has_path(b, p[1:])` returns `True`, then there is a path through branch `b` for which `p[1:]` are the node labels. 98 | 99 | **How can you use those return values to complete your implementation?** 100 | 101 | If you have already checked that `label(t)` is equal to `p[0]`, then a `True` return value means there is a path through `t` with labels `p` using that branch `b`. A `False` value means there is no path through that branch, but there might be path through a different branch. 102 | 103 | Run in 61A Code 104 | 105 | If your group needs some guidance, you can click on the hints below, but please talk with your group first before reading the hints. 106 | 107 | The first base case should check whether `p` is a list of length one with the label of `t` as its only element. The second base case should check if the first element of `p` matches the label of `t`. 108 | 109 | When entering the recursive case, your code should already have checked that `p[0]` is equal to `label(t)`, and so all that's left to check is that `p[1:]` contains the labels in a path through one of the branches. One way is with this template: 110 | 111 | for ____: if ____: return Truereturn False 112 | 113 | **Discussion Time!** Can the `else` case of `has_path` be written in just one line? Why or why not? You can ignore how fast the function will run. When your group has an answer, send a message to the discuss-queue channel with the @discuss tag, your discussion group number, and the message "Maybe?" and a member of the course staff will join your voice channel to hear your answer and give feedback. 114 | 115 | ### Q3: Find Path[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc05#q3-find-path "Direct link to Q3: Find Path") 116 | 117 | Implement `find_path`, which takes a tree `t` with unique labels and a value `x`. It returns a list containing the labels of the nodes along a path from the root of `t` to a node labeled `x`. 118 | 119 | If `x` is not a label in `t`, return `None`. Assume that the labels of `t` are unique. 120 | 121 | First talk through how to make and use the recursive call. (Try it yourselves; don't just click the hint button. That's how you learn.) 122 | 123 | **What recursive calls will you make?** 124 | 125 | `find_path(b, x)` on each branch `b`. 126 | 127 | **What type of values do they return?** 128 | 129 | Each recursive call will either return `None` or a non-empty list of node labels. 130 | 131 | **What do the possible return values mean?** 132 | 133 | If `find_path(b, x)` returns `None`, then `x` does not appear in `b`. If `find_path(b, x)` returns a list, then it contains the node labels for a path through `b` that ends with the node labeled `x`. 134 | 135 | **How can you use those return values to complete your implementation?** 136 | 137 | If a list is returned, then it contains all of the labels in the path except `label(t)`, which must be placed at the front. 138 | 139 | Run in 61A Code 140 | 141 | Please don't view the hints until you've discussed with your group and can't make progress. 142 | 143 | If `x` is the label of `t`, then return a list with one element that contains the label of `t`. 144 | 145 | Assign `path` to the result of a recursive call to `find_path(b, x)` so that you can both check whether it's `None` and extend it if it's a list. 146 | 147 | For a list `path` and a value `v`, the expression `[v] + path` creates a longer list that starts with `v` and then has the elements of `path`. 148 | 149 | **Description Time!** When your group has completed this question, it's time to describe why this function does not have a base case that uses `is_leaf`. Come up with an explanation as a group, pick someone to present your answer, and then send a message to the discuss-queue channel with the @discuss tag, your discussion group number, and the message "Found it!" and a member of the course staff will join your voice channel to hear your description and give feedback. 150 | 151 | Document the Occasion[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc05#document-the-occasion "Direct link to Document the Occasion") 152 | --------------------------------------------------------------------------------------------------------------------------------------------------------- 153 | 154 | For each person, the rest of the group should try to guess their _big word_ (from the Getting Started section). The group only gets one guess. After they guess, reveal your _big word_ and how many times you used it during discussion. 155 | 156 | Please all fill out the [attendance form](https://docs.google.com/forms/d/e/1FAIpQLSeqlK8l6WkScGr-RHR-kM4p5bnR9cllYrG95fDqPJspSlll7A/viewform) (one submission per person per week). -------------------------------------------------------------------------------- /disc/disc05/disc05.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/disc/disc05/disc05.pdf -------------------------------------------------------------------------------- /disc/disc06/README.md: -------------------------------------------------------------------------------- 1 | Discussion 6 | CS 61A Spring 2024 2 | ================================= 3 | 4 | Discussion 6: Iterators, Generators[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc06#discussion-6-iterators-generators "Direct link to Discussion 6: Iterators, Generators") 5 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 6 | 7 | * [disc06.pdf](https://www.learncs.site/assets/files/disc06-8a0e6ecb7c727ac249d70072199729e4.pdf) 8 | 9 | Pick someone in your group to [join Discord](https://cs61a.org/articles/discord). It's fine if multiple people join, but one is enough. 10 | 11 | Now switch to Pensieve: 12 | 13 | * **Everyone**: Go to [discuss.pensieve.co](http://discuss.pensieve.co/) and log in with your @berkeley.edu email, then enter your group number. (Your group number is the number of your Discord channel.) 14 | 15 | Once you're on Pensieve, you don't need to return to this page; Pensieve has all the same content (but more features). If for some reason Penseive doesn't work, return to this page and continue with the discussion. 16 | 17 | Post in the `#help` channel on [Discord](https://cs61a.org/articles/discord/) if you have trouble. 18 | 19 | Getting Started[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc06#getting-started "Direct link to Getting Started") 20 | --------------------------------------------------------------------------------------------------------------------------------------- 21 | 22 | Say your name and share a favorite place on the Berkeley campus or surrounding city that you've discovered. Try to pick a place that others might not have been yet. (But if the room you're in now is your favorite place on campus, that's ok too.) 23 | 24 | [McCone Hall](https://www.campus-maps.com/university-of-california-berkeley/mccone-hall/) has a nice view from the 5th floor balcony. 25 | 26 | Generators[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc06#generators "Direct link to Generators") 27 | ------------------------------------------------------------------------------------------------------------------------ 28 | 29 | A _generator_ is an _iterator_ that is returned by calling a _generator function_, which is a function that contains `yield` statements instead of `return` statements. The ways to use an _iterator_ are to call `next` on it or to use it as an iterable (for example, in a `for` statement). 30 | 31 | ### Q1: Big Fib[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc06#q1-big-fib "Direct link to Q1: Big Fib") 32 | 33 | This generator function yields all of the Fibonacci numbers. 34 | 35 | def gen_fib(): n, add = 0, 1 while True: yield n n, add = n + add, n 36 | 37 | Explain the following expression to each other so that everyone understands how it works. (It creates a list of the first 10 Fibonacci numbers.) 38 | 39 | (lambda t: [next(t) for _ in range(10)])(gen_fib()) 40 | 41 | Then, complete the expression below by writing only names and parentheses in the blanks so that it evaluates to the smallest Fibonacci number that is larger than 2024. 42 | 43 | Talk with each other about what built-in functions might be helpful, such as [`map`](https://docs.python.org/3/library/functions.html#map), [`filter`](https://docs.python.org/3/library/functions.html#filter), [`list`](https://docs.python.org/3/library/functions.html#func-list), [`any`](https://docs.python.org/3/library/functions.html#any), [`all`](https://docs.python.org/3/library/functions.html#all), etc. (Click on these function names to view their documentation.) Try to figure out the answer without using Python. Only run the code when your group agrees that the answer is right. This is not the time for guess-and-check. 44 | 45 | Run in 61A Code 46 | 47 | One solution has the form: `next(____(lambda n: n > 2024, ____))` where the first blank uses a built-in function to create an iterator over just large numbers and the second blank creates an iterator over all Fibonacci numbers. 48 | 49 | Surprise! There's no hint here. If you're still stuck, it's time to get help from the course staff. 50 | 51 | ### Q2: Something Different[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc06#q2-something-different "Direct link to Q2: Something Different") 52 | 53 | Implement `differences`, a generator function that takes `t`, a non-empty iterator over numbers. It yields the differences between each pair of adjacent values from `t`. If `t` iterates over a positive finite number of values `n`, then `differences` should yield `n-1` times. 54 | 55 | Run in 61A Code 56 | 57 | Add to the following implementation by initializing and updating `previous_x` so that it is always bound to the value of `t` that came before `x`. 58 | 59 | for x in t: yield x - previous_x 60 | 61 | **Presentation Time.** Work together to explain why `differences` will always yield `n-1` times for an iterator `t` over `n` values. Pick someone who didn't present to the course staff last week to present your group's answer, and then send a message to the discuss-queue channel with the @discuss tag, your discussion group number, and the message "We beg to differ!" and a member of the course staff will join your voice channel to hear your description and give feedback. 62 | 63 | ### Intermission[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc06#intermission "Direct link to Intermission") 64 | 65 | We're lazy (like an iterator) and used ChatGPT to generate a generator joke... 66 | 67 | Because it was skilled at knowing when to "return" to the recipe and when to "yield" to improvisation! 68 | 69 | ### Q3: Partitions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc06#q3-partitions "Direct link to Q3: Partitions") 70 | 71 | Tree-recursive generator functions have a similar structure to regular tree-recursive functions. They are useful for iterating over all possibilities. Instead of building a list of results and returning it, just `yield` each result. 72 | 73 | You'll need to identify a _recursive decomposition_: how to express the answer in terms of recursive calls that are simpler. Ask yourself what will be yielded by a recursive call, then how to use those results. 74 | 75 | **Definition.** For positive integers `n` and `m`, a _partition_ of `n` using parts up to size `m` is an addition expression of positive integers up to `m` in non-decreasing order that sums to `n`. 76 | 77 | Implement `partition_gen`, a generator functon that takes positive `n` and `m`. It yields the partitions of `n` using parts up to size `m` as strings. 78 | 79 | **Reminder:** For the `partitions` function we studied in lecture ([video](https://youtu.be/DvgT4dnSMVM)), the recursive decomposition was to enumerate all ways of partitioning `n` using at least one `m` and then to enumerate all ways with no `m` (only `m-1` and lower). 80 | 81 | Run in 61A Code 82 | 83 | Yield a partition with just one element, `n`. Make sure you yield a string. 84 | 85 | The first recursive case uses at least one `m`, and so you will need to yield a string that starts with `p` but also includes `m`. The second recursive case only uses parts up to size `m-1`. (You can implement the second case in one line using `yield from`.) 86 | 87 | **Presentation Time.** If you have time, work together to explain why this implementation of `partition_gen` does not include base cases for `n < 0`, `n == 0`, or `m == 0` even though the original implementation of `partitions` from lecture ([video](https://youtu.be/DvgT4dnSMVM?si=MEkqzloqIcbD1-09&t=515)) had all three. Pick someone who didn't present to the course staff this week or last week to present your group's answer, and then send a message to the discuss-queue channel with the @discuss tag, your discussion group number, and the message "We're positive!" and a member of the course staff will join your voice channel to hear your description and give feedback. 88 | 89 | Document the Occasion[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc06#document-the-occasion "Direct link to Document the Occasion") 90 | --------------------------------------------------------------------------------------------------------------------------------------------------------- 91 | 92 | Please all fill out the [attendance form](https://docs.google.com/forms/d/e/1FAIpQLSeqlK8l6WkScGr-RHR-kM4p5bnR9cllYrG95fDqPJspSlll7A/viewform) (one submission per person per week). -------------------------------------------------------------------------------- /disc/disc06/disc06.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/disc/disc06/disc06.pdf -------------------------------------------------------------------------------- /disc/disc07/README.md: -------------------------------------------------------------------------------- 1 | Discussion 7 | CS 61A Spring 2024 2 | Discussion 7: OOP 3 | disc07.pdf 4 | Pick someone in your group to join Discord. It's fine if multiple people join, but one is enough. 5 | 6 | Now switch to Pensieve: 7 | 8 | Everyone: Go to discuss.pensieve.co and log in with your @berkeley.edu email, then enter your group number. (Your group number is the number of your Discord channel.) 9 | Once you're on Pensieve, you don't need to return to this page; Pensieve has all the same content (but more features). If for some reason Penseive doesn't work, return to this page and continue with the discussion. 10 | 11 | Post in the #help channel on Discord if you have trouble. 12 | 13 | Getting Started 14 | Say your name, another class you're taking besides CS 61A, and something you've practiced for a while, such as playing an instrument, juggling, or martial arts. Did you discover any common interests among your group members? 15 | 16 | Q1: Draw 17 | The draw function takes a list hand and a list of unique non-negative integers positions that are all less than the length of hand. It removes hand[p] for each p in positions and returns a list of those elements in the order they appeared in hand (not the order they appeared in positions). 18 | 19 | Fill in each blank with one of these names: list, map, filter, reverse, reversed, sort, sorted, append, insert, index, remove, pop, zip, or sum. See the built-in functions and list methods documentation for descriptions of what these do. 20 | 21 | Discussion Time: Before writing anything, talk as a group about what process you'll implement in order to make sure the right cards are removed and returned. Try not to guess-and-check! The purpose of discussion is for you to try to solve problems without the help of an interpreter checking your work. 22 | 23 | Run in 61A Code 24 | 25 | For a list s and integer i, s.pop(i) returns and removes the ith element, which changes the position (index) of all the later elements but does not affect the position of prior elements. 26 | 27 | Calling reversed(s) on a list s returns an iterator. Calling list(reversed(s)) returns a list of the elements in s in reversed order. 28 | 29 | Aced it? Give yourselves a hand! 30 | 31 | Object-Oriented Programming 32 | A productive approach to defining new classes is to determine what instance attributes each object should have and what class attributes each class should have. First, describe the type of each attribute and how it will be used, then try to implement the class's methods in terms of those attributes. 33 | 34 | Q2: Keyboard 35 | Overview: A keyboard has a button for every letter of the alphabet. When a button is pressed, it outputs its letter by calling an output function (such as print). Whether that letter is uppercase or lowercase depends on how many times the caps lock key has been pressed. 36 | 37 | First, implement the Button class, which takes a lowercase letter (a string) and a one-argument output function, such as Button('c', print). 38 | 39 | The press method of a Button calls its output attribute (a function) on its letter attribute: either uppercase if caps_lock has been pressed an odd number of times or lowercase otherwise. The press method also increments pressed and returns the key that was pressed. Hint: 'hi'.upper() evaluates to 'HI'. 40 | 41 | Second, implement the Keyboard class. A Keyboard has a dictionary called keys containing a Button (with its letter as its key) for each letter in LOWERCASE_LETTERS. It also has a list of the letters typed, which may be a mix of uppercase and lowercase letters. 42 | 43 | The type method takes a string word containing only lowercase letters. It invokes the press method of the Button in keys for each letter in word, which adds a letter (either lowercase or uppercase depending on caps_lock) to the Keyboard's typed list. Important: Do not use upper or letter in your implementation of type; just call press instead. 44 | 45 | Read the doctests and talk about: 46 | 47 | Why it's possible to press a button repeatedly with .press().press().press(). 48 | Why pressing a button repeatedly sometimes prints on only one line and sometimes prints multiple lines. 49 | Why bored.typed has 10 elements at the end. 50 | Discussion Time: Before anyone types anything, have a conversation describing the type of each attribute and how it will be used. Start with Button: how will letter and output be used? Then discuss Keyboard: how will typed and keys be used? How will new letters be added to the list called typed each time a Button in keys is pressed? Call the staff if you're not sure! Once everyone understands the answers to these questions, you can try writing the code together. 51 | 52 | Run in 61A Code 53 | 54 | Please don't look at the hints until you've discussed as a group and agreed that you need a hint. 55 | 56 | Since self.letter is always lowercase, use self.letter.upper() to produce the uppercase version. 57 | 58 | The number of times caps_lock has been pressed is either self.caps_lock.pressed or Button.caps_lock.pressed. 59 | 60 | The output attribute is a function that can be called: self.output(self.letter) or self.output(self.letter.upper()). You do not need to return the result. Instead return self afterward in order to return the button that was pressed. 61 | 62 | The keys can be created using a dictionary comprehension: self.keys = {c: Button(c, ...) for c in LETTERS}. The call to Button should take c and an output function that appends to self.typed, so that every time one of these buttons is pressed, it appends a letter to self.typed. 63 | 64 | Call the press method of self.key[w] for each w in word. It should be the case that when you call press, the Button is already set up (in the Keyboard.__init__ method) to output to the typed list of this Keyboard. 65 | 66 | Presentation Time: Describe how new letters are added to typed each time a Button in keys is pressed. Instead of just reading your code, say what it does (e.g., "When the button of a keyboard is pressed ..."). One short sentence is enough to describe how new letters are added to typed. When you're ready, send a message to the #discuss-queue channel with the @discuss tag, your discussion group number, and the message "Put it on our tab!" and a member of the course staff will join your voice channel to hear your description and give feedback. 67 | 68 | Q3: Bear 69 | Implement the SleepyBear, and WinkingBear classes so that calling their print method matches the doctests. Use as little code as possible and try not to repeat any logic from Eye or Bear. Each blank can be filled with just two short lines. 70 | 71 | Discussion Time: Before writing code, talk about what is different about a SleepyBear and a Bear. When using inheritance, you only need to implement the differences between the base class and subclass. Then, talk about what is different about a WinkingBear and a Bear. Can you think of a way to make the bear wink without a new implementation of print? 72 | 73 | Run in 61A Code 74 | 75 | Implement a next_eye method that returns an Eye instance that is closed. 76 | 77 | One way to make the bear wink is to track how may times the next_eye method is invoked using a new instance attribute and return a closed eye if next_eye has been called an even number of times. 78 | 79 | Document the Occasion 80 | Please all fill out the attendance form (one submission per person per week). -------------------------------------------------------------------------------- /disc/disc07/disc07.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/disc/disc07/disc07.pdf -------------------------------------------------------------------------------- /disc/disc08/disc08.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/disc/disc08/disc08.pdf -------------------------------------------------------------------------------- /disc/disc09/README.md: -------------------------------------------------------------------------------- 1 | Discussion 9 | CS 61A Spring 2024 2 | Discussion 9: Scheme, Scheme Lists 3 | disc09.pdf 4 | Reminder: We'll still use Pensieve, but we've removed the voice/video chat from Pensieve. Use Discord for voice chat with the course staff. It's more reliable and includes screensharing. Write to @discuss in the #discuss-queue channel on Discord at any time, and a member of the course staff will join your group's voice channel. 5 | 6 | Pick someone in your group to join Discord. It's fine if multiple people join, but one is enough. 7 | 8 | Now switch to Pensieve: 9 | 10 | Everyone: Go to discuss.pensieve.co and log in with your @berkeley.edu email, then enter your group number. (Your group number is the number of your Discord channel.) 11 | Once you're on Pensieve, you don't need to return to this page; Pensieve has all the same content (but more features). If for some reason Penseive doesn't work, return to this page and continue with the discussion. 12 | 13 | Post in the #help channel on Discord if you have trouble. 14 | 15 | Pro tip: Any of you can type a question into your group's Discord channel's text chat with the @discuss tag, and a member of the course staff will respond. 16 | 17 | Getting Started 18 | If you have only 1 or 2 people in your group, you can join the other group in the room with you. 19 | 20 | Everybody say your name, and then figure out who most recently pet a dog. (Feel free to share dog photos. Even cat photos are acceptable.) 21 | 22 | Scheme 23 | Q1: Perfect Fit 24 | Definition: A perfect square is k*k for some integer k. 25 | 26 | Implement fit, which takes non-negative integers total and n. It returns whether there are n different positive perfect squares that sum to total. 27 | 28 | Important: Don't use the Scheme interpreter to tell you whether you've implemented it correctly. Discuss! On the final exam, you won't have an interpreter. 29 | 30 | Run in 61A Code 31 | 32 | Use the (or _ _) special form to combine two recursive calls: one that uses k*k in the sum and one that does not. The first should subtract k*k from total and subtract 1 from n; the other should leaves total and n unchanged. In either case, add 1 to k. 33 | 34 | Presentation Time: As a group, come up with one sentence describing how your implementation makes sure that all n positive perfect squares are different (no repeats). Once your group agrees on an answer (or wants help), send a message to the #discuss-queue channel with the @discuss tag, your discussion group number, and the message "It fits!" and a member of the course staff will join your voice channel to hear your explanation and give feedback. 35 | 36 | Scheme Lists & Quotation 37 | Scheme lists are linked lists. Lightning review: 38 | 39 | nil and () are the same thing: the empty list. 40 | (cons first rest) constructs a linked list with first as its first element. and rest as the rest of the list, which should always be a list. 41 | (car s) returns the first element of the list s. 42 | (cdr s) returns the rest of the list s. 43 | (list ...) takes n arguments and returns a list of length n with those arguments as elements. 44 | (append ...) takes n lists as arguments and returns a list of all of the elements of those lists. 45 | (draw s) draws the linked list structure of a list s. It only works on code.cs61a.org/scheme. Try it now with something like (draw (cons 1 nil)). 46 | Quoting an expression leaves it unevaluated. Examples: 47 | 48 | 'four and (quote four) both evaluate to the symbol four. 49 | '(2 3 4) and (quote (2 3 4)) both evaluate to a list containing three elements: 2, 3, and 4. 50 | '(2 3 four) and (quote (2 3 four)) evaluate to a list containing 2, 3, and the symbol four. 51 | Here's an important difference between list and quotation: 52 | 53 | scm> (list 2 (+ 3 4)) 54 | (2 7) 55 | scm> `(2 (+ 3 4)) 56 | (2 (+ 3 4)) 57 | 58 | Q2: Nested Lists 59 | Create the nested list depicted below three different ways: using list, quote, and cons. 60 | 61 | linked list 62 | 63 | First, describe the list together: "It looks like there are four elements, and the first element is ..." If you get stuck, look at the hint below. (But try to describe it yourself first!) 64 | 65 | A four-element list in which the first element is a list containing both a and b, the second element is c, the third element is d, and the fourth element is a list containing just e. 66 | 67 | Next, use calls to list to construct this list. If you run this code and then (draw with-list) in code.cs61a.org, the draw procedure will draw what you've built. 68 | 69 | Run in 61A Code 70 | 71 | Every call to list creates a list, and there are three different lists in this diagram: a list containing a and b: (list 'a 'b), a list containing e: (list 'e), and the whole list of four elements: (list _ 'c 'd _). Try to put these expressions together. 72 | 73 | Now, use quote to construct this list. 74 | 75 | Run in 61A Code 76 | 77 | One quoted expression is enough, but it needs to match the structure of the linked list using Scheme notation. So, your task is to figure out how this list would be displayed in Scheme. 78 | 79 | The nested list drawn above is a four-element list with lists as its first and last elements: ((a b) c d (e)). Quoting that expression will create the list. 80 | 81 | Now, use cons to construct this list. Don't use list. You can use first in your answer. 82 | 83 | Run in 61A Code 84 | 85 | The provided first is the first element of the result, so the answer takes the form: 86 | 87 | first ____ 88 | 89 | You can either fill in the blank with a quoted three-element list: 90 | 91 | '(___ ___ ___) c d (e) 92 | 93 | or with nested calls to cons: 94 | 95 | (cons ___ (cons ___ (cons ___ nil))) c d (e) 96 | 97 | Q3: Pair Up 98 | Implement pair-up, which takes a list s. It returns a list of lists that together contain all of the elements of s in order. Each list in the result should have 2 elements. The last one can have up to 3. 99 | 100 | Look at the examples together to make sure everyone understands what this procedure does. 101 | 102 | Run in 61A Code 103 | 104 | pair-up takes a list (of numbers) and returns a list of lists, so when (length s) is less than or equal to 3, return a list containing the list s. For example, (pair-up (list 2 3 4)) should return ((2 3 4)). 105 | 106 | Use (cons _ (pair-up _)) to create the result, where the first argument to cons is a list with two elements: the (car s) and the (car (cdr s)). The argument to pair-up is everything after the first two elements. 107 | 108 | Discussion: What's the longest list s for which (pair-up (pair-up s)) will return a list with only one element? (Don't just guess and check; discuss!) Post your answer in your group's text chat. 109 | 110 | Document the Occasion 111 | Please all fill out the attendance form (one submission per person per week). 112 | 113 | Important: Please help put the furniture in the room back where you found it before you leave. Thanks! -------------------------------------------------------------------------------- /disc/disc09/disc09.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/disc/disc09/disc09.pdf -------------------------------------------------------------------------------- /disc/disc10/disc10.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/disc/disc10/disc10.pdf -------------------------------------------------------------------------------- /disc/disc11/README.md: -------------------------------------------------------------------------------- 1 | Discussion 11 | CS 61A Spring 2024 2 | ================================== 3 | 4 | Discussion 11: SQL[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc11#discussion-11-sql "Direct link to Discussion 11: SQL") 5 | ----------------------------------------------------------------------------------------------------------------------------------------------- 6 | 7 | * [disc11.pdf](https://www.learncs.site/assets/files/disc11-56a5ca2a4beb2877ab91952fa5ab51a8.pdf) 8 | 9 | **Reminder:** Use Discord for voice chat with the course staff. Write to `@discuss` in the `#discuss-queue` channel on Discord at any time, and a member of the course staff will join your group's voice channel. 10 | 11 | Pick someone in your group to [join Discord](https://cs61a.org/articles/discord). It's fine if multiple people join, but one is enough. 12 | 13 | Now switch to Pensieve: 14 | 15 | * **Everyone**: Go to [discuss.pensieve.co](http://discuss.pensieve.co/) and log in with your @berkeley.edu email, then enter your group number. (Your group number is the number of your Discord channel.) 16 | 17 | Once you're on Pensieve, you don't need to return to this page; Pensieve has all the same content (but more features). If for some reason Penseive doesn't work, return to this page and continue with the discussion. 18 | 19 | Post in the `#help` channel on [Discord](https://cs61a.org/articles/discord/) if you have trouble. 20 | 21 | **Pro tip:** Any of you can type a question into your group's Discord [channel's text chat](https://support.discord.com/hc/en-us/articles/4412085582359-Text-Channels-Text-Chat-In-Voice-Channels#h_01FMJT412WBX1MR4HDYNR8E95X) with the `@discuss` tag, and a member of the course staff will respond. 22 | 23 | Getting Started[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc11#getting-started "Direct link to Getting Started") 24 | --------------------------------------------------------------------------------------------------------------------------------------- 25 | 26 | If you have only 1 or 2 people in your group, you can join the other group in the room with you. 27 | 28 | Everybody say your name, and then share your favorite restaurant, cafe, or boba shop near campus. (Yes, Kingpin Donuts counts as a restaurant.) 29 | 30 | Select Statements[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc11#select-statements "Direct link to Select Statements") 31 | --------------------------------------------------------------------------------------------------------------------------------------------- 32 | 33 | A `SELECT` statement describes an output table based on input rows. To write one: 34 | 35 | 1. Describe the **input rows** using `FROM` and `WHERE` clauses. 36 | 2. Format and order the **output rows** and columns using `SELECT` and `ORDER BY` clauses. 37 | 38 | `SELECT` _(Step 2)_ `FROM` _(Step 1)_ `WHERE` _(Step 1)_ `ORDER BY` _(Step 2)_; 39 | 40 | Step 1 may involve joining tables (using commas) to form input rows that consist of two or more rows from existing tables. 41 | 42 | The `WHERE` and `ORDER BY` clauses are optional. 43 | 44 | Pizza Time[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc11#pizza-time "Direct link to Pizza Time") 45 | ------------------------------------------------------------------------------------------------------------------------ 46 | 47 | The `pizzas` table contains the names, opening, and closing hours of great pizza places in Berkeley. The `meals` table contains typical meal times (for college students). A pizza place is open for a meal if the meal time is at or within the `open` and `close` times. 48 | 49 | CREATE TABLE pizzas AS SELECT "Artichoke" AS name, 12 AS open, 15 AS close UNION SELECT "La Val's" , 11 , 22 UNION SELECT "Sliver" , 11 , 20 UNION SELECT "Cheeseboard" , 16 , 23 UNION SELECT "Emilia's" , 13 , 18;CREATE TABLE meals AS SELECT "breakfast" AS meal, 11 AS time UNION SELECT "lunch" , 13 UNION SELECT "dinner" , 19 UNION SELECT "snack" , 22; 50 | 51 | ### Q1: Open Early[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc11#q1-open-early "Direct link to Q1: Open Early") 52 | 53 | You'd like to have pizza before 13 o'clock (1pm). Create a `opening` table with the names of all pizza places that `open` before 13 o'clock, listed in reverse alphabetical order. 54 | 55 | **`opening`** table: 56 | 57 | name 58 | 59 | Sliver 60 | 61 | La Val's 62 | 63 | Artichoke 64 | 65 | Run in 61A Code 66 | 67 | To order by `name` in reverse alphabitical order, write `ORDER BY name DESC`. 68 | 69 | ### Q2: Study Session[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc11#q2-study-session "Direct link to Q2: Study Session") 70 | 71 | You're planning to study at a pizza place from the moment it opens until 14 o'clock (2pm). Create a table `study` with two columns, the `name` of each pizza place and the `duration` of the study session you would have if you studied there (the difference between when it opens and 14 o'clock). For pizza places that are not open before 2pm, the `duration` should be zero. Order the rows by decreasing duration. 72 | 73 | **Hint:** Use an expression of the form `MAX(_, 0)` to make sure a result is not below 0. 74 | 75 | **`study`** table: 76 | 77 | name 78 | 79 | duration 80 | 81 | La Val's 82 | 83 | 3 84 | 85 | Sliver 86 | 87 | 3 88 | 89 | Artichoke 90 | 91 | 2 92 | 93 | Emilia's 94 | 95 | 1 96 | 97 | Cheeseboard 98 | 99 | 0 100 | 101 | Run in 61A Code 102 | 103 | To order by decreasing duration, first name the column with `SELECT ..., ... AS duration ...`, then `ORDER BY duration DESC`. 104 | 105 | ### Q3: Late Night Snack[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc11#q3-late-night-snack "Direct link to Q3: Late Night Snack") 106 | 107 | What's still open for a late night `snack`? Create a `late` table with one column named `status` that has a sentence describing the closing time of each pizza place that closes at or after `snack` time. **Important:** Don't use any numbers in your SQL query! Instead, use a join to compare each restaurant's closing time to the time of a snack. The rows may appear in any order. 108 | 109 | **`late`** table: 110 | 111 | status 112 | 113 | Cheeseboard closes at 23 114 | 115 | La Val's closes at 22 116 | 117 | Run in 61A Code 118 | 119 | To compare a pizza place's `close` time to the time of a snack: 120 | 121 | * join the `pizzas` and `meals` tables using `FROM pizzas, meals` 122 | * use only rows where the `meal` is a `"snack"` 123 | * compare the `time` of the snack to the `close` of the pizza place. 124 | 125 | Use `name || " closes at " || close` to create the sentences in the resulting table. The `||` operator concatenates values into strings. 126 | 127 | ### Q4: Double Pizza[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc11#q4-double-pizza "Direct link to Q4: Double Pizza") 128 | 129 | If two meals are more than 6 hours apart, then there's nothing wrong with going to the same pizza place for both, right? Create a `double` table with three columns. The `first` column is the earlier meal, the `second` column is the later meal, and the `name` column is the name of a pizza place. Only include rows that describe two meals that are **more than 6 hours apart** and a pizza place that is open for both of the meals. The rows may appear in any order. 130 | 131 | **`double`** table: 132 | 133 | first 134 | 135 | second 136 | 137 | name 138 | 139 | breakfast 140 | 141 | dinner 142 | 143 | La Val's 144 | 145 | breakfast 146 | 147 | dinner 148 | 149 | Sliver 150 | 151 | breakfast 152 | 153 | snack 154 | 155 | La Val's 156 | 157 | lunch 158 | 159 | snack 160 | 161 | La Val's 162 | 163 | Run in 61A Code 164 | 165 | Use `FROM meals AS a, meals AS b, pizzas` so that each row has info about two meals and a pizza place. Then you can write a `WHERE` clause that compares both `a.time` and `b.time` to `open` and `close` and each other to ensure all the relevant conditions are met. 166 | 167 | Document the Occasion[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc11#document-the-occasion "Direct link to Document the Occasion") 168 | --------------------------------------------------------------------------------------------------------------------------------------------------------- 169 | 170 | Please all fill out the [attendance form](https://docs.google.com/forms/d/e/1FAIpQLSeqlK8l6WkScGr-RHR-kM4p5bnR9cllYrG95fDqPJspSlll7A/viewform) (one submission per person per week). 171 | 172 | **Important:** Please help put the furniture in the room back where you found it before you leave. Thanks! 173 | 174 | If you finish early, maybe go get pizza together... -------------------------------------------------------------------------------- /disc/disc11/disc11.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/disc/disc11/disc11.pdf -------------------------------------------------------------------------------- /disc/disc12/README.md: -------------------------------------------------------------------------------- 1 | Discussion 12 | CS 61A Spring 2024 2 | ================================== 3 | 4 | Discussion 12: Final Review[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc12#discussion-12-final-review "Direct link to Discussion 12: Final Review") 5 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 6 | 7 | * [disc12.pdf](https://www.learncs.site/assets/files/disc12-60dd80ec62b0e565d4a3721800d350b8.pdf) 8 | 9 | **Reminder:** Use Discord for voice chat with the course staff. Write to `@discuss` in the `#discuss-queue` channel on Discord at any time, and a member of the course staff will join your group's voice channel. 10 | 11 | Pick someone in your group to [join Discord](https://cs61a.org/articles/discord). It's fine if multiple people join, but one is enough. 12 | 13 | Now switch to Pensieve: 14 | 15 | * **Everyone**: Go to [discuss.pensieve.co](http://discuss.pensieve.co/) and log in with your @berkeley.edu email, then enter your group number. (Your group number is the number of your Discord channel.) 16 | 17 | Once you're on Pensieve, you don't need to return to this page; Pensieve has all the same content (but more features). If for some reason Penseive doesn't work, return to this page and continue with the discussion. 18 | 19 | Post in the `#help` channel on [Discord](https://cs61a.org/articles/discord/) if you have trouble. 20 | 21 | **Pro tip:** Any of you can type a question into your group's Discord [channel's text chat](https://support.discord.com/hc/en-us/articles/4412085582359-Text-Channels-Text-Chat-In-Voice-Channels#h_01FMJT412WBX1MR4HDYNR8E95X) with the `@discuss` tag, and a member of the course staff will respond. 22 | 23 | Getting Started[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc12#getting-started "Direct link to Getting Started") 24 | --------------------------------------------------------------------------------------------------------------------------------------- 25 | 26 | If you have only 1 or 2 people in your group, you can join the other group in the room with you. 27 | 28 | **Ice breaker:** Everybody say your name and the non-CS/EECS course that you're most excited about taking next semester. 29 | 30 | Lists[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc12#lists "Direct link to Lists") 31 | --------------------------------------------------------------------------------------------------------- 32 | 33 | The two most common mutation operations for lists are item assignment and the `append` method. 34 | 35 | >>> s = [1, 3, 4]>>> t = s # A second name for the same list>>> t[0] = 2 # this changes the first element of the list to 2, affecting both s and t>>> s[2, 3, 4]>>> s.append(5) # this adds 5 to the end of the list, affecting both s and t>>> t[2, 3, 4, 5] 36 | 37 | There are many other list mutation methods: 38 | 39 | * `append(elem)`: Add `elem` to the end of the list. Return `None`. 40 | * `extend(s)`: Add all elements of iterable `s` to the end of the list. Return `None`. 41 | * `insert(i, elem)`: Insert `elem` at index `i`. If `i` is greater than or equal to the length of the list, then `elem` is inserted at the end. This does not replace any existing elements, but only adds the new element `elem`. Return `None`. 42 | * `remove(elem)`: Remove the first occurrence of `elem` in list. Return `None`. Errors if `elem` is not in the list. 43 | * `pop(i)`: Remove and return the element at index `i`. 44 | * `pop()`: Remove and return the last element. 45 | 46 | ### Q1: Word Rope[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc12#q1-word-rope "Direct link to Q1: Word Rope") 47 | 48 | **Definition:** A _rope_ in Python is a list containing only one-letter strings except for the last element, which may either be a one-letter string or a rope. 49 | 50 | Implement `word_rope`, a Python function that takes a non-empty string `s` containing only letters and spaces that does not start or end with a space. It returns a _rope_ containing the letters of `s` in which each word is in a separate list. 51 | 52 | **Important:** You may not use slicing or the `split`, `find`, or `index` methods of a string. Solve the problem using list operations. 53 | 54 | **Reminder:** `s[-1]` evaluates to the last element of a sequence `s`. 55 | 56 | Run in 61A Code 57 | 58 | In this implementation, `result` is a rope and `word` is a list within that rope which is still being constructed. When `x` is a space, add an empty list to the end of `word` and assign `word` to this empty list. Otherwise, add `x` to the end of `word`. 59 | 60 | Linked Lists[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc12#linked-lists "Direct link to Linked Lists") 61 | ------------------------------------------------------------------------------------------------------------------------------ 62 | 63 | A linked list is a `Link` object or `Link.empty`. 64 | 65 | You can mutate a `Link` object `s` in two ways: 66 | 67 | * Change the first element with `s.first = ...` 68 | * Change the rest of the elements with `s.rest = ...` 69 | 70 | You can make a new `Link` object by calling `Link`: 71 | 72 | * `Link(4)` makes a linked list of length 1 containing 4. 73 | * `Link(4, s)` makes a linked list that starts with 4 followed by the elements of linked list `s`. 74 | 75 | class Link: """A linked list is either a Link object or Link.empty >>> s = Link(3, Link(4, Link(5))) >>> s.rest Link(4, Link(5)) >>> s.rest.rest.rest is Link.empty True >>> s.rest.first * 2 8 >>> print(s) <3 4 5> """ empty = () def __init__(self, first, rest=empty): assert rest is Link.empty or isinstance(rest, Link) self.first = first self.rest = rest def __repr__(self): if self.rest: rest_repr = ', ' + repr(self.rest) else: rest_repr = '' return 'Link(' + repr(self.first) + rest_repr + ')' def __str__(self): string = '<' while self.rest is not Link.empty: string += str(self.first) + ' ' self = self.rest return string + str(self.first) + '>' 76 | 77 | ### Q2: Linear Sublists[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc12#q2-linear-sublists "Direct link to Q2: Linear Sublists") 78 | 79 | **Definition:** A _sublist_ of linked list `s` is a linked list of some of the elements of `s` in order. For example, `<3 6 2 5 1 7>` has sublists `<3 2 1>` and `<6 2 7>` but not `<5 6 7>`. 80 | 81 | **Definition:** A _linear sublist_ of a linked list of numbers `s` is a sublist in which the difference between adjacent numbers is always the same. For example `<2 4 6 8>` is a linear sublist of `<1 2 3 4 6 9 1 8 5>` because the difference between each pair of adjacent elements is 2. 82 | 83 | Implement `linear` which takes a linked list of numbers `s` (either a `Link` instance or `Link.empty`). It returns the longest linear sublist of `s`. If two linear sublists are tied for the longest, return either one. 84 | 85 | Run in 61A Code 86 | 87 | There are three cases: 88 | 89 | * If `rest` is empty, return a one-element list containing just `first`. 90 | * If `rest.first` is in the linear sublist that starts with `first`, then build a list that contains `first`, and `rest.first`. 91 | * Otherwise, `complete(first, rest.rest)`. 92 | 93 | This while loop is creating a `candidate` linear sublist for every two possible starting values: `s.first` and `t.first`. The rest of the linear sublist must be in `t.rest`. 94 | 95 | Scheme[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc12#scheme "Direct link to Scheme") 96 | ------------------------------------------------------------------------------------------------------------ 97 | 98 | ### Q3: Increasing Rope[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc12#q3-increasing-rope "Direct link to Q3: Increasing Rope") 99 | 100 | **Definition:** A _rope_ in Scheme is a non-empty list containing only numbers except for the last element, which may either be a number or a rope. 101 | 102 | Implement `up`, a Scheme procedure that takes a positive integer `n`. It returns a rope containing the digits of `n` that is the shortest rope in which each pair of adjacent numbers in the same list are in increasing order. 103 | 104 | **Reminder**: the `quotient` procedure performs floor division, like `//` in Python. The `remainder` procedure is like `%` in Python. 105 | 106 | Run in 61A Code 107 | 108 | Compare `first` to `(car result)` to decide whether to `cons` the value `first` onto the `result` or whether to form a new list that contains `first` and `result` as elements. 109 | 110 | To correctly call `helper` from within `up`, build a rope that only contains the last digit of `n`: `(remainder n 10)`. 111 | 112 | SQL[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc12#sql "Direct link to SQL") 113 | --------------------------------------------------------------------------------------------------- 114 | 115 | A `SELECT` statement describes an output table based on input rows. To write one: 116 | 117 | 1. Describe the **input rows** using `FROM` and `WHERE` clauses. 118 | 2. **Group** those rows and determine which groups should appear as output rows using `GROUP BY` and `HAVING` clauses. 119 | 3. Format and order the **output rows** and columns using `SELECT` and `ORDER BY` clauses. 120 | 121 | `SELECT` _(Step 3)_ `FROM` _(Step 1)_ `WHERE` _(Step 1)_ `GROUP BY` _(Step 2)_ `HAVING` _(Step 2)_ `ORDER BY` _(Step 3)_; 122 | 123 | Step 1 may involve joining tables (using commas) to form input rows that consist of two or more rows from existing tables. 124 | 125 | The `WHERE`, `GROUP BY`, `HAVING`, and `ORDER BY` clauses are optional. 126 | 127 | ### Q4: A Secret Message[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc12#q4-a-secret-message "Direct link to Q4: A Secret Message") 128 | 129 | A substitution cipher replaces each word with another word in a table in order to encrypt a message. To decode an encrypted message, replace each word `x` with its corresponding `y` in a code table. 130 | 131 | Write a select statement to decode the `original` message _It's The End_ using the `code` table. 132 | 133 | Run in 61A Code 134 | 135 | Join the `original` and `code` tables and make sure that the joined roles have the same `word` and `x`. 136 | 137 | What happens now? Write another select statement to decode this encrypted message using the same `code` table. 138 | 139 | Run in 61A Code 140 | 141 | Join `original` with `code AS a` and `code AS b` to create six-column rows like: `2|The|The|Happens|Happens|Go`, The _Go_ at the end is part of the decoded message. 142 | 143 | **Scheduling time:** This is the last discussion, but you could schedule a meeting with your group next week to study for the exam. Your regular discussion room and time should be available during RRR week if you want to use it. 144 | 145 | Document the Occasion[​](https://www.learncs.site/docs/curriculum-resource/cs61a/dis/disc12#document-the-occasion "Direct link to Document the Occasion") 146 | --------------------------------------------------------------------------------------------------------------------------------------------------------- 147 | 148 | Please all fill out the [attendance form](https://docs.google.com/forms/d/e/1FAIpQLSeqlK8l6WkScGr-RHR-kM4p5bnR9cllYrG95fDqPJspSlll7A/viewform) (one submission per person per week). 149 | 150 | **Important:** Please help put the furniture in the room back where you found it before you leave. Thanks! -------------------------------------------------------------------------------- /disc/disc12/disc12.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/disc/disc12/disc12.pdf -------------------------------------------------------------------------------- /disc/新建文本文档.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/disc/新建文本文档.txt -------------------------------------------------------------------------------- /hw/hw01/README.md: -------------------------------------------------------------------------------- 1 | Homework 1: Functions, Control[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw01#homework-1-functions-control "Direct link to Homework 1: Functions, Control") 2 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 3 | 4 | * [hw01.zip](https://www.learncs.site/assets/files/hw01-13825eefee70c7f6bd268bdffaf8ba19.zip) 5 | 6 | _Due by 11:59pm on Thursday, January 25_ 7 | 8 | Instructions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw01#instructions "Direct link to Instructions") 9 | --------------------------------------------------------------------------------------------------------------------------------- 10 | 11 | Download [hw01.zip](https://www.learncs.site/assets/files/hw01-13825eefee70c7f6bd268bdffaf8ba19.zip). 12 | 13 | **Submission:** When you are done, submit the assignment by uploading all code files you've edited to Gradescope. You may submit more than once before the deadline; only the final submission will be scored. Check that you have successfully submitted your code on Gradescope. See [Lab 0](https://cs61a.org/lab/lab00#task-c-submitting-the-assignment) for more instructions on submitting assignments. 14 | 15 | **Using Ok:** If you have any questions about using Ok, please refer to [this guide.](https://cs61a.org/articles/using-ok) 16 | 17 | **Readings:** You might find the following references useful: 18 | 19 | * [Section 1.1](https://www.composingprograms.com/pages/11-getting-started.html) 20 | * [Section 1.2](https://www.composingprograms.com/pages/12-elements-of-programming.html) 21 | * [Section 1.3](https://www.composingprograms.com/pages/13-defining-new-functions.html) 22 | * [Section 1.4](https://www.composingprograms.com/pages/14-designing-functions.html) 23 | * [Section 1.5](https://www.composingprograms.com/pages/15-control.html) 24 | 25 | **Grading:** Homework is graded based on correctness. Each incorrect problem will decrease the total score by one point. **This homework is out of 2 points.** 26 | 27 | Getting Started Videos[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw01#getting-started-videos "Direct link to Getting Started Videos") 28 | --------------------------------------------------------------------------------------------------------------------------------------------------------------- 29 | 30 | These videos may provide some helpful direction for tackling the problems on this assignment. 31 | 32 | > To see these videos, you should be logged into your berkeley.edu email. 33 | > 34 | > [YouTube link](https://youtu.be/playlist?list=PLx38hZJ5RLZeW4C9wRpz0ohqMmoctnnra) 35 | 36 | Required Questions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw01#required-questions "Direct link to Required Questions") 37 | --------------------------------------------------------------------------------------------------------------------------------------------------- 38 | 39 | ### Q1: A Plus Abs B[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw01#q1-a-plus-abs-b "Direct link to Q1: A Plus Abs B") 40 | 41 | Python's `operator` module contains two-argument functions such as `add` and `sub` for Python's built-in arithmetic operators. For example, `add(2, 3)` evalutes to 5, just like the expression `2 + 3`. 42 | 43 | Fill in the blanks in the following function for adding `a` to the absolute value of `b`, without calling `abs`. You may **not** modify any of the provided code other than the two blanks. 44 | 45 | def a_plus_abs_b(a, b): """Return a+abs(b), but without calling abs. >>> a_plus_abs_b(2, 3) 5 >>> a_plus_abs_b(2, -3) 5 >>> a_plus_abs_b(-1, 4) 3 >>> a_plus_abs_b(-1, -4) 3 """ if b < 0: f = _____ else: f = _____ return f(a, b) 46 | 47 | Use Ok to test your code: 48 | 49 | python3 ok -q a_plus_abs_b 50 | 51 | Use Ok to run the local syntax checker (which checks that you didn't modify any of the provided code other than the two blanks): 52 | 53 | python3 ok -q a_plus_abs_b_syntax_check 54 | 55 | ### Q2: Two of Three[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw01#q2-two-of-three "Direct link to Q2: Two of Three") 56 | 57 | Write a function that takes three _positive_ numbers as arguments and returns the sum of the squares of the two smallest numbers. **Use only a single line for the body of the function.** 58 | 59 | def two_of_three(i, j, k): """Return m*m + n*n, where m and n are the two smallest members of the positive numbers i, j, and k. >>> two_of_three(1, 2, 3) 5 >>> two_of_three(5, 3, 1) 10 >>> two_of_three(10, 2, 8) 68 >>> two_of_three(5, 5, 5) 50 """ return _____ 60 | 61 | > **Hint:** Consider using the `max` or `min` function: 62 | > 63 | > >>> max(1, 2, 3)3>>> min(-1, -2, -3)-3 64 | 65 | Use Ok to test your code: 66 | 67 | python3 ok -q two_of_three 68 | 69 | Use Ok to run the local syntax checker (which checks that you used only a single line for the body of the function): 70 | 71 | python3 ok -q two_of_three_syntax_check 72 | 73 | ### Q3: Largest Factor[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw01#q3-largest-factor "Direct link to Q3: Largest Factor") 74 | 75 | Write a function that takes an integer `n` that is **greater than 1** and returns the largest integer that is smaller than `n` and evenly divides `n`. 76 | 77 | def largest_factor(n): """Return the largest factor of n that is smaller than n. >>> largest_factor(15) # factors are 1, 3, 5 5 >>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40 40 >>> largest_factor(13) # factor is 1 since 13 is prime 1 """ "*** YOUR CODE HERE ***" 78 | 79 | > **Hint:** To check if `b` evenly divides `a`, use the expression `a % b == 0`, which can be read as, "the remainder when dividing `a` by `b` is 0." 80 | 81 | Use Ok to test your code: 82 | 83 | python3 ok -q largest_factor 84 | 85 | ### Q4: Hailstone[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw01#q4-hailstone "Direct link to Q4: Hailstone") 86 | 87 | Douglas Hofstadter's Pulitzer-prize-winning book, _Gödel, Escher, Bach_, poses the following mathematical puzzle. 88 | 89 | 1. Pick a positive integer `n` as the start. 90 | 2. If `n` is even, divide it by 2. 91 | 3. If `n` is odd, multiply it by 3 and add 1. 92 | 4. Continue this process until `n` is 1. 93 | 94 | The number `n` will travel up and down but eventually end at 1 (at least for all numbers that have ever been tried -- nobody has ever proved that the sequence will terminate). Analogously, a hailstone travels up and down in the atmosphere before eventually landing on earth. 95 | 96 | This sequence of values of `n` is often called a Hailstone sequence. Write a function that takes a single argument with formal parameter name `n`, prints out the hailstone sequence starting at `n`, and returns the number of steps in the sequence: 97 | 98 | def hailstone(n): """Print the hailstone sequence starting at n and return its length. >>> a = hailstone(10) 10 5 16 8 4 2 1 >>> a 7 >>> b = hailstone(1) 1 >>> b 1 """ "*** YOUR CODE HERE ***" 99 | 100 | Hailstone sequences can get quite long! Try 27. What's the longest you can find? 101 | 102 | > Note that if `n == 1` initially, then the sequence is one step long. 103 | > **Hint:** If you see 4.0 but want just 4, try using floor division `//` instead of regular division `/`. 104 | 105 | Use Ok to test your code: 106 | 107 | python3 ok -q hailstone 108 | 109 | **Curious about hailstones or hailstone sequences? Take a look at these articles:** 110 | 111 | * Check out [this article](https://www.nationalgeographic.org/encyclopedia/hail/) to learn more about how hailstones work! 112 | * In 2019, there was a major [development](https://www.quantamagazine.org/mathematician-terence-tao-and-the-collatz-conjecture-20191211/) in understanding how the hailstone conjecture works for most numbers! 113 | 114 | Check Your Score Locally[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw01#check-your-score-locally "Direct link to Check Your Score Locally") 115 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 116 | 117 | You can locally check your score on each question of this assignment by running 118 | 119 | python3 ok --score 120 | 121 | **This does NOT submit the assignment!** When you are satisfied with your score, submit the assignment to Gradescope to receive credit for it. 122 | 123 | Submit[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw01#submit "Direct link to Submit") 124 | --------------------------------------------------------------------------------------------------------------- 125 | 126 | Submit this assignment by uploading any files you've edited **to the appropriate Gradescope assignment.** [Lab 00](https://cs61a.org/lab/lab00/#submit-with-gradescope) has detailed instructions. 127 | 128 | In addition, all students who are **not** in the mega lab must complete this [attendance form](https://go.cs61a.org/lab-att). Submit this form each week, whether you attend lab or missed it for a good reason. The attendance form is not required for mega section students. 129 | 130 | > If you completed all problems correctly, you should see that your score is 6.0 in the autograder output by Gradescope. Each homework assignment counts for 2 points, so in this case you will receive the full 2 points for homework. Remember that every incorrect question costs you 1 point, so a 5.0/6.0 on this assignment will translate to a 1.0/2.0 homework grade for this assignment. -------------------------------------------------------------------------------- /hw/hw01/hw01-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw01/hw01-sol.zip -------------------------------------------------------------------------------- /hw/hw01/hw01.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw01/hw01.zip -------------------------------------------------------------------------------- /hw/hw02/README.md: -------------------------------------------------------------------------------- 1 | Homework 2: Higher-Order Functions 2 | hw02.zip 3 | Due by 11:59pm on Thursday, February 1 4 | 5 | Instructions 6 | Download hw02.zip. Inside the archive, you will find a file called hw02.py, along with a copy of the ok autograder. 7 | 8 | Submission: When you are done, submit the assignment by uploading all code files you've edited to Gradescope. You may submit more than once before the deadline; only the final submission will be scored. Check that you have successfully submitted your code on Gradescope. See Lab 0 for more instructions on submitting assignments. 9 | 10 | Using Ok: If you have any questions about using Ok, please refer to this guide. 11 | 12 | Readings: You might find the following references useful: 13 | 14 | Section 1.6 15 | Grading: Homework is graded based on correctness. Each incorrect problem will decrease the total score by one point. This homework is out of 2 points. 16 | 17 | Required Questions 18 | Getting Started Videos 19 | These videos may provide some helpful direction for tackling the coding problems on this assignment. 20 | 21 | To see these videos, you should be logged into your berkeley.edu email. 22 | 23 | YouTube link 24 | 25 | Several doctests refer to these functions: 26 | 27 | from operator import add, mul 28 | 29 | square = lambda x: x * x 30 | 31 | identity = lambda x: x 32 | 33 | triple = lambda x: 3 * x 34 | 35 | increment = lambda x: x + 1 36 | 37 | Higher-Order Functions 38 | Q1: Product 39 | Write a function called product that returns the product of the first n terms of a sequence. Specifically, product takes in an integer n and term, a single-argument function that determines a sequence. (That is, term(i) gives the ith term of the sequence.) product(n, term) should return term(1) * ... * term(n). 40 | 41 | def product(n, term): 42 | """Return the product of the first n terms in a sequence. 43 | 44 | n: a positive integer 45 | term: a function that takes one argument to produce the term 46 | 47 | >>> product(3, identity) # 1 * 2 * 3 48 | 6 49 | >>> product(5, identity) # 1 * 2 * 3 * 4 * 5 50 | 120 51 | >>> product(3, square) # 1^2 * 2^2 * 3^2 52 | 36 53 | >>> product(5, square) # 1^2 * 2^2 * 3^2 * 4^2 * 5^2 54 | 14400 55 | >>> product(3, increment) # (1+1) * (2+1) * (3+1) 56 | 24 57 | >>> product(3, triple) # 1*3 * 2*3 * 3*3 58 | 162 59 | """ 60 | "*** YOUR CODE HERE ***" 61 | 62 | 63 | Use Ok to test your code: 64 | 65 | python3 ok -q product 66 | 67 | Q2: Accumulate 68 | Let's take a look at how product is an instance of a more general function called accumulate, which we would like to implement: 69 | 70 | def accumulate(fuse, start, n, term): 71 | """Return the result of fusing together the first n terms in a sequence 72 | and start. The terms to be fused are term(1), term(2), ..., term(n). 73 | The function fuse is a two-argument commutative & associative function. 74 | 75 | >>> accumulate(add, 0, 5, identity) # 0 + 1 + 2 + 3 + 4 + 5 76 | 15 77 | >>> accumulate(add, 11, 5, identity) # 11 + 1 + 2 + 3 + 4 + 5 78 | 26 79 | >>> accumulate(add, 11, 0, identity) # 11 (fuse is never used) 80 | 11 81 | >>> accumulate(add, 11, 3, square) # 11 + 1^2 + 2^2 + 3^2 82 | 25 83 | >>> accumulate(mul, 2, 3, square) # 2 * 1^2 * 2^2 * 3^2 84 | 72 85 | >>> # 2 + (1^2 + 1) + (2^2 + 1) + (3^2 + 1) 86 | >>> accumulate(lambda x, y: x + y + 1, 2, 3, square) 87 | 19 88 | """ 89 | "*** YOUR CODE HERE ***" 90 | 91 | 92 | accumulate has the following parameters: 93 | 94 | fuse: a two-argument function that specifies how the current term is fused with the previously accumulated terms 95 | start: value at which to start the accumulation 96 | n: a non-negative integer indicating the number of terms to fuse 97 | term: a single-argument function; term(i) is the ith term of the sequence 98 | Implement accumulate, which fuses the first n terms of the sequence defined by term with the start value using the fuse function. 99 | 100 | For example, the result of accumulate(add, 11, 3, square) is 101 | 102 | add(11, add(square(1), add(square(2), square(3)))) = 103 | 11 + square(1) + square(2) + square(3) = 104 | 11 + 1 + 4 + 9 = 25 105 | 106 | Assume that fuse is commutative, fuse(a, b) == fuse(b, a), and associative, fuse(fuse(a, b), c) == fuse(a, fuse(b, c)). 107 | 108 | Then, implement summation (from lecture) and product as one-line calls to accumulate. 109 | 110 | Important: Both summation_using_accumulate and product_using_accumulate should be implemented with a single line of code starting with return. 111 | 112 | def summation_using_accumulate(n, term): 113 | """Returns the sum: term(1) + ... + term(n), using accumulate. 114 | 115 | >>> summation_using_accumulate(5, square) 116 | 55 117 | >>> summation_using_accumulate(5, triple) 118 | 45 119 | >>> # This test checks that the body of the function is just a return statement. 120 | >>> import inspect, ast 121 | >>> [type(x).__name__ for x in ast.parse(inspect.getsource(summation_using_accumulate)).body[0].body] 122 | ['Expr', 'Return'] 123 | """ 124 | return ____ 125 | 126 | def product_using_accumulate(n, term): 127 | """Returns the product: term(1) * ... * term(n), using accumulate. 128 | 129 | >>> product_using_accumulate(4, square) 130 | 576 131 | >>> product_using_accumulate(6, triple) 132 | 524880 133 | >>> # This test checks that the body of the function is just a return statement. 134 | >>> import inspect, ast 135 | >>> [type(x).__name__ for x in ast.parse(inspect.getsource(product_using_accumulate)).body[0].body] 136 | ['Expr', 'Return'] 137 | """ 138 | return ____ 139 | 140 | 141 | Use Ok to test your code: 142 | 143 | python3 ok -q accumulate 144 | python3 ok -q summation_using_accumulate 145 | python3 ok -q product_using_accumulate 146 | 147 | Q3: Make Repeater 148 | Implement the function make_repeater that takes a one-argument function f and a positive integer n. It returns a one-argument function, where make_repeater(f, n)(x) returns the value of f(f(...f(x)...)) in which f is applied n times to x. For example, make_repeater(square, 3)(5) squares 5 three times and returns 390625, just like square(square(square(5))). 149 | 150 | def make_repeater(f, n): 151 | """Returns the function that computes the nth application of f. 152 | 153 | >>> add_three = make_repeater(increment, 3) 154 | >>> add_three(5) 155 | 8 156 | >>> make_repeater(triple, 5)(1) # 3 * 3 * 3 * 3 * 3 * 1 157 | 243 158 | >>> make_repeater(square, 2)(5) # square(square(5)) 159 | 625 160 | >>> make_repeater(square, 3)(5) # square(square(square(5))) 161 | 390625 162 | """ 163 | "*** YOUR CODE HERE ***" 164 | 165 | 166 | Use Ok to test your code: 167 | 168 | python3 ok -q make_repeater 169 | 170 | Check Your Score Locally 171 | You can locally check your score on each question of this assignment by running 172 | 173 | python3 ok --score 174 | 175 | This does NOT submit the assignment! When you are satisfied with your score, submit the assignment to Gradescope to receive credit for it. 176 | 177 | Submit 178 | Submit this assignment by uploading any files you've edited to the appropriate Gradescope assignment. Lab 00 has detailed instructions. 179 | 180 | In addition, all students who are not in the mega lab must complete this attendance form. Submit this form each week, whether you attend lab or missed it for a good reason. The attendance form is not required for mega section students. 181 | 182 | Exam Practice 183 | Here are some related questions from past exams for you to try. These are optional. There is no way to submit them. 184 | 185 | Note that exams from Spring 2020, Fall 2020, and Spring 2021 gave students access to an interpreter, so the question format may be different than other years. Regardless, the questions below are good problems to try without access to an interpreter. 186 | 187 | Fall 2019 MT1 Q3: You Again [Higher-Order Functions] 188 | Spring 2021 MT1 Q4: Domain on the Range [Higher-Order Functions] 189 | Fall 2021 MT1 Q1b: tik [Functions and Expressions] -------------------------------------------------------------------------------- /hw/hw02/hw02-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw02/hw02-sol.zip -------------------------------------------------------------------------------- /hw/hw02/hw02.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw02/hw02.zip -------------------------------------------------------------------------------- /hw/hw03/hw03-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw03/hw03-sol.zip -------------------------------------------------------------------------------- /hw/hw03/hw03.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw03/hw03.zip -------------------------------------------------------------------------------- /hw/hw04/hw04-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw04/hw04-sol.zip -------------------------------------------------------------------------------- /hw/hw04/hw04.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw04/hw04.zip -------------------------------------------------------------------------------- /hw/hw05/README.md: -------------------------------------------------------------------------------- 1 | Homework 5 | CS 61A Spring 2024 2 | =============================== 3 | 4 | Homework 5: Generators[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw05#homework-5-generators "Direct link to Homework 5: Generators") 5 | -------------------------------------------------------------------------------------------------------------------------------------------------------------- 6 | 7 | * [hw05.zip](https://www.learncs.site/assets/files/hw05-ff324bf956b7998a49297cff704df2e3.zip) 8 | 9 | _Due by 11:59pm on Thursday, March 7_ 10 | 11 | Instructions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw05#instructions "Direct link to Instructions") 12 | --------------------------------------------------------------------------------------------------------------------------------- 13 | 14 | Download [hw05.zip](https://www.learncs.site/assets/files/hw05-ff324bf956b7998a49297cff704df2e3.zip). Inside the archive, you will find a file called [hw05.py](https://cs61a.org//hw/hw05/hw05.py), along with a copy of the `ok` autograder. 15 | 16 | **Submission:** When you are done, submit the assignment by uploading all code files you've edited to Gradescope. You may submit more than once before the deadline; only the final submission will be scored. Check that you have successfully submitted your code on Gradescope. See [Lab 0](https://cs61a.org/lab/lab00#task-c-submitting-the-assignment) for more instructions on submitting assignments. 17 | 18 | **Using Ok:** If you have any questions about using Ok, please refer to [this guide.](https://cs61a.org/articles/using-ok) 19 | 20 | **Readings:** You might find the following references useful: 21 | 22 | * [Section 4.2](https://www.composingprograms.com/pages/42-implicit-sequences.html) 23 | 24 | **Grading:** Homework is graded based on correctness. Each incorrect problem will decrease the total score by one point. **This homework is out of 2 points.** 25 | 26 | Required Questions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw05#required-questions "Direct link to Required Questions") 27 | --------------------------------------------------------------------------------------------------------------------------------------------------- 28 | 29 | Getting Started Videos[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw05#getting-started-videos "Direct link to Getting Started Videos") 30 | --------------------------------------------------------------------------------------------------------------------------------------------------------------- 31 | 32 | These videos may provide some helpful direction for tackling the coding problems on this assignment. 33 | 34 | > To see these videos, you should be logged into your berkeley.edu email. 35 | 36 | [YouTube link](https://youtu.be/playlist?list=PLx38hZJ5RLZcg5Zd4EMdx9fctIYVfJvnd) 37 | 38 | ### Q1: Infinite Hailstone[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw05#q1-infinite-hailstone "Direct link to Q1: Infinite Hailstone") 39 | 40 | Write a generator function that yiels the elements of the hailstone sequence starting at number `n`. After reaching the end of the hailstone sequence, the generator should yield the value 1 indefinitely. 41 | 42 | Here's a quick reminder of how the hailstone sequence is defined: 43 | 44 | 1. Pick a positive integer `n` as the start. 45 | 2. If `n` is even, divide it by 2. 46 | 3. If `n` is odd, multiply it by 3 and add 1. 47 | 4. Continue this process until `n` is 1. 48 | 49 | Try to write this generator function recursively. If you're stuck, you can first try writing it iteratively and then seeing how you can turn that implementation into a recursive one. 50 | 51 | > **Hint:** Since `hailstone` returns a generator, you can `yield from` a call to `hailstone`! 52 | 53 | def hailstone(n): """Q1: Yields the elements of the hailstone sequence starting at n. At the end of the sequence, yield 1 infinitely. >>> hail_gen = hailstone(10) >>> [next(hail_gen) for _ in range(10)] [10, 5, 16, 8, 4, 2, 1, 1, 1, 1] >>> next(hail_gen) 1 """ "*** YOUR CODE HERE ***" 54 | 55 | Use Ok to test your code: 56 | 57 | python3 ok -q hailstone 58 | 59 | ### Q2: Merge[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw05#q2-merge "Direct link to Q2: Merge") 60 | 61 | Write a generator function `merge` that takes in two infinite generators `a` and `b` that are in increasing order without duplicates and returns a generator that has all the elements of both generators, in increasing order, without duplicates. 62 | 63 | def merge(a, b): """Q2: >>> def sequence(start, step): ... while True: ... yield start ... start += step >>> a = sequence(2, 3) # 2, 5, 8, 11, 14, ... >>> b = sequence(3, 2) # 3, 5, 7, 9, 11, 13, 15, ... >>> result = merge(a, b) # 2, 3, 5, 7, 8, 9, 11, 13, 14, 15 >>> [next(result) for _ in range(10)] [2, 3, 5, 7, 8, 9, 11, 13, 14, 15] """ "*** YOUR CODE HERE ***" 64 | 65 | Use Ok to test your code: 66 | 67 | python3 ok -q merge 68 | 69 | ### Q3: Yield Paths[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw05#q3-yield-paths "Direct link to Q3: Yield Paths") 70 | 71 | Define a generator function `yield_paths` which takes in a tree `t`, a value `value`, and returns a generator object which yields each path from the root of `t` to a node that has label `value`. 72 | 73 | Each path should be represented as a list of the labels along that path in the tree. You may yield the paths in any order. 74 | 75 | def yield_paths(t, value): """Q4: Yields all possible paths from the root of t to a node with the label value as a list. >>> t1 = tree(1, [tree(2, [tree(3), tree(4, [tree(6)]), tree(5)]), tree(5)]) >>> print_tree(t1) 1 2 3 4 6 5 5 >>> next(yield_paths(t1, 6)) [1, 2, 4, 6] >>> path_to_5 = yield_paths(t1, 5) >>> sorted(list(path_to_5)) [[1, 2, 5], [1, 5]] >>> t2 = tree(0, [tree(2, [t1])]) >>> print_tree(t2) 0 2 1 2 3 4 6 5 5 >>> path_to_2 = yield_paths(t2, 2) >>> sorted(list(path_to_2)) [[0, 2], [0, 2, 1, 2]] """ if label(t) == value: yield ____ for b in branches(t): for ____ in ____: yield ____ 76 | 77 | > _Hint:_ If you're having trouble getting started, think about how you'd approach this problem if it wasn't a generator function. What would your recursive calls be? With a generator function, what happens if you make a "recursive call" within its body? 78 | 79 | > _Hint:_ Try coming up with a few simple cases of your own! How should this function work when `t` is a leaf node? 80 | 81 | > _Hint:_ Remember, it's possible to loop over generator objects because generators are iterators! 82 | 83 | > Note: Remember that this problem should **yield paths** \-- do not return a list of paths! 84 | 85 | Use Ok to test your code: 86 | 87 | python3 ok -q yield_paths 88 | 89 | Check Your Score Locally[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw05#check-your-score-locally "Direct link to Check Your Score Locally") 90 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 91 | 92 | You can locally check your score on each question of this assignment by running 93 | 94 | python3 ok --score 95 | 96 | **This does NOT submit the assignment!** When you are satisfied with your score, submit the assignment to Gradescope to receive credit for it. 97 | 98 | Submit[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw05#submit "Direct link to Submit") 99 | --------------------------------------------------------------------------------------------------------------- 100 | 101 | Submit this assignment by uploading any files you've edited **to the appropriate Gradescope assignment.** [Lab 00](https://cs61a.org/lab/lab00/#submit-with-gradescope) has detailed instructions. 102 | 103 | Exam Practice[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw05#exam-practice "Direct link to Exam Practice") 104 | ------------------------------------------------------------------------------------------------------------------------------------ 105 | 106 | Homework assignments will also contain prior exam questions for you to try. These questions have no submission component; feel free to attempt them if you'd like some practice! 107 | 108 | 1. Summer 2018 Final Q7a,b: [Streams and Jennyrators](https://inst.eecs.berkeley.edu/~cs61a/su18/assets/pdfs/61a-su18-final.pdf#page=9) 109 | 2. Spring 2019 Final Q1: [Iterators are inevitable](https://cs61a.org/exam/sp19/final/61a-sp19-final.pdf#page=2) 110 | 3. Spring 2021 MT2 Q8: [The Tree of L-I-F-E](https://cs61a.org/exam/sp21/mt2/61a-sp21-mt2.pdf#page=18) 111 | 4. Summer 2016 Final Q8: [Zhen-erators Produce Power](https://inst.eecs.berkeley.edu//~cs61a/su16/assets/pdfs/61a-su16-final.pdf#page=13) 112 | 5. Spring 2018 Final Q4a: [Apply Yourself](https://inst.eecs.berkeley.edu/~cs61a/sp18/assets/pdfs/61a-sp18-final.pdf#page=5) -------------------------------------------------------------------------------- /hw/hw05/hw05-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw05/hw05-sol.zip -------------------------------------------------------------------------------- /hw/hw05/hw05.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw05/hw05.zip -------------------------------------------------------------------------------- /hw/hw06/hw06-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw06/hw06-sol.zip -------------------------------------------------------------------------------- /hw/hw06/hw06.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw06/hw06.zip -------------------------------------------------------------------------------- /hw/hw07/README.md: -------------------------------------------------------------------------------- 1 | Homework 7 | CS 61A Spring 2024 2 | =============================== 3 | 4 | Homework 7: Scheme[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw07#homework-7-scheme "Direct link to Homework 7: Scheme") 5 | -------------------------------------------------------------------------------------------------------------------------------------------------- 6 | 7 | * [hw07.zip](https://www.learncs.site/assets/files/hw07-af8715b3051f03242ee48aa812dba214.zip) 8 | 9 | _Due by 11:59pm on Thursday, April 4_ 10 | 11 | Instructions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw07#instructions "Direct link to Instructions") 12 | --------------------------------------------------------------------------------------------------------------------------------- 13 | 14 | Download [hw07.zip](https://www.learncs.site/assets/files/hw07-af8715b3051f03242ee48aa812dba214.zip). Inside the archive, you will find a file called [hw07.scm](https://cs61a.org//hw/hw07/hw07.scm), along with a copy of the `ok` autograder. 15 | 16 | **Submission:** When you are done, submit the assignment by uploading all code files you've edited to Gradescope. You may submit more than once before the deadline; only the final submission will be scored. Check that you have successfully submitted your code on Gradescope. See [Lab 0](https://cs61a.org/lab/lab00#task-c-submitting-the-assignment) for more instructions on submitting assignments. 17 | 18 | **Using Ok:** If you have any questions about using Ok, please refer to [this guide.](https://cs61a.org/articles/using-ok) 19 | 20 | **Readings:** You might find the following references useful: 21 | 22 | * [Scheme Specification](https://cs61a.org/articles/scheme-spec/) 23 | * [Scheme Built-in Procedure Reference](https://cs61a.org/articles/scheme-builtins/) 24 | 25 | **Grading:** Homework is graded based on correctness. Each incorrect problem will decrease the total score by one point. **This homework is out of 2 points.** 26 | 27 | The 61A Scheme interpreter is included in each Scheme assignment. To start it, type `python3 scheme` in a terminal. To load a Scheme file called `f.scm`, type `python3 scheme -i f.scm`. To exit the Scheme interpreter, type `(exit)`. 28 | 29 | ### Scheme Editor[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw07#scheme-editor "Direct link to Scheme Editor") 30 | 31 | All Scheme assignments include a web-based editor that makes it easy to run ok tests and visualize environments. Type `python3 editor` in a terminal, and the editor will open in a browser window (at `http://127.0.0.1:31415/`). To stop running the editor and return to the command line, type `Ctrl-C` in the terminal where you started the editor. 32 | 33 | The `Run` button loads the current assignment's `.scm` file and opens a Scheme interpreter, allowing you to try evaluating different Scheme expressions. 34 | 35 | The `Test` button runs all ok tests for the assignment. Click `View Case` for a failed test, then click `Debug` to step through its evaluation. 36 | 37 | ### Recommended VS Code Extensions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw07#recommended-vs-code-extensions "Direct link to Recommended VS Code Extensions") 38 | 39 | If you choose to use VS Code as your text editor (instead of the web-based editor), install the [vscode-scheme](https://marketplace.visualstudio.com/items?itemName=sjhuangx.vscode-scheme) extension so that parentheses are highlighted. 40 | 41 | Before: 42 | 43 | ![](https://www.learncs.site/assets/images/before-1fb62971706b817f8b61c7a23705e08a.png) 44 | 45 | After: 46 | 47 | ![](https://www.learncs.site/assets/images/after-49c28554ee03a6642fe04e111fd59fd5.png) 48 | 49 | In addition, the 61a-bot ([installation instructions](https://cs61a.org/articles/61a-bot)) VS Code extension is available for Scheme homeworks. The bot is also integrated into `ok`. 50 | 51 | Required Questions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw07#required-questions "Direct link to Required Questions") 52 | --------------------------------------------------------------------------------------------------------------------------------------------------- 53 | 54 | Getting Started Videos[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw07#getting-started-videos "Direct link to Getting Started Videos") 55 | --------------------------------------------------------------------------------------------------------------------------------------------------------------- 56 | 57 | These videos may provide some helpful direction for tackling the coding problems on this assignment. 58 | 59 | > To see these videos, you should be logged into your berkeley.edu email. 60 | 61 | [YouTube link](https://youtu.be/playlist?list=PLx38hZJ5RLZcQgwUYw_yvAcp0-vz6L0Zh) 62 | 63 | ### Q1: Pow[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw07#q1-pow "Direct link to Q1: Pow") 64 | 65 | Implement a procedure `pow` that raises a `base` to the power of a nonnegative integer `exp`. The number of recursive `pow` calls should grow logarithmically with respect to `exp`, rather than linearly. For example, `(pow 2 32)` should result in 5 recursive `pow` calls rather than 32 recursive `pow` calls. 66 | 67 | > _Hint:_ 68 | > 69 | > 1. x2y = (xy)2 70 | > 2. x2y+1 = x(xy)2 71 | > 72 | > For example, 216 = (28)2 and 217 = 2 \* (28)2. 73 | > 74 | > You may use the built-in predicates `even?` and `odd?`. Also, the `square` procedure is defined for you. 75 | > 76 | > Scheme doesn't have `while` or `for` statements, so use recursion to solve this problem. 77 | 78 | (define (square n) (* n n))(define (pow base exp) 'YOUR-CODE-HERE) 79 | 80 | Use Ok to test your code: 81 | 82 | python3 ok -q pow 83 | 84 | ### Q2: Repeatedly Cube[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw07#q2-repeatedly-cube "Direct link to Q2: Repeatedly Cube") 85 | 86 | Implement `repeatedly-cube`, which receives a number `x` and cubes it `n` times. 87 | 88 | Here are some examples of how `repeatedly-cube` should behave: 89 | 90 | scm> (repeatedly-cube 100 1) ; 1 cubed 100 times is still 11scm> (repeatedly-cube 2 2) ; (2^3)^3512scm> (repeatedly-cube 3 2) ; ((2^3)^3)^3134217728 91 | 92 | > For information on `let`, see [the Scheme spec](https://cs61a.org/articles/scheme-spec/#let). 93 | 94 | (define (repeatedly-cube n x) (if (zero? n) x (let (_________________) (* y y y)))) 95 | 96 | Use Ok to test your code: 97 | 98 | python3 ok -q repeatedly-cube 99 | 100 | ### Q3: Cadr[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw07#q3-cadr "Direct link to Q3: Cadr") 101 | 102 | **Note:** _Scheme lists are covered in the lecture videos for Wednesday, April 3._ 103 | 104 | Define the procedure `cadr`, which returns the second element of a list. Also define `caddr`, which returns the third element of a list. 105 | 106 | (define (cddr s) (cdr (cdr s)))(define (cadr s) 'YOUR-CODE-HERE)(define (caddr s) 'YOUR-CODE-HERE) 107 | 108 | Use Ok to test your code: 109 | 110 | python3 ok -q cadr-caddr -------------------------------------------------------------------------------- /hw/hw07/hw07-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw07/hw07-sol.zip -------------------------------------------------------------------------------- /hw/hw07/hw07.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw07/hw07.zip -------------------------------------------------------------------------------- /hw/hw08/README.md: -------------------------------------------------------------------------------- 1 | Homework 8: Scheme Lists[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw08#homework-8-scheme-lists "Direct link to Homework 8: Scheme Lists") 2 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- 3 | 4 | * [hw08.zip](https://www.learncs.site/assets/files/hw08-912d428eb7876001702e96d040d986ca.zip) 5 | 6 | _Due by 11:59pm on Thursday, April 11_ 7 | 8 | Instructions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw08#instructions "Direct link to Instructions") 9 | --------------------------------------------------------------------------------------------------------------------------------- 10 | 11 | Download [hw08.zip](https://www.learncs.site/assets/files/hw08-912d428eb7876001702e96d040d986ca.zip). Inside the archive, you will find a file called [hw08.scm](https://cs61a.org//hw/hw08/hw08.scm), along with a copy of the `ok` autograder. 12 | 13 | **Submission:** When you are done, submit the assignment by uploading all code files you've edited to Gradescope. You may submit more than once before the deadline; only the final submission will be scored. Check that you have successfully submitted your code on Gradescope. See [Lab 0](https://cs61a.org/lab/lab00#task-c-submitting-the-assignment) for more instructions on submitting assignments. 14 | 15 | **Using Ok:** If you have any questions about using Ok, please refer to [this guide.](https://cs61a.org/articles/using-ok) 16 | 17 | **Readings:** You might find the following references useful: 18 | 19 | * [Scheme Specification](https://cs61a.org/articles/scheme-spec/) 20 | * [Scheme Built-in Procedure Reference](https://cs61a.org/articles/scheme-builtins/) 21 | 22 | **Grading:** Homework is graded based on correctness. Each incorrect problem will decrease the total score by one point. **This homework is out of 2 points.** 23 | 24 | The 61A Scheme interpreter is included in each Scheme assignment. To start it, type `python3 scheme` in a terminal. To load a Scheme file called `f.scm`, type `python3 scheme -i f.scm`. To exit the Scheme interpreter, type `(exit)`. 25 | 26 | ### Scheme Editor[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw08#scheme-editor "Direct link to Scheme Editor") 27 | 28 | All Scheme assignments include a web-based editor that makes it easy to run ok tests and visualize environments. Type `python3 editor` in a terminal, and the editor will open in a browser window (at `http://127.0.0.1:31415/`). To stop running the editor and return to the command line, type `Ctrl-C` in the terminal where you started the editor. 29 | 30 | The `Run` button loads the current assignment's `.scm` file and opens a Scheme interpreter, allowing you to try evaluating different Scheme expressions. 31 | 32 | The `Test` button runs all ok tests for the assignment. Click `View Case` for a failed test, then click `Debug` to step through its evaluation. 33 | 34 | ### Recommended VS Code Extensions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw08#recommended-vs-code-extensions "Direct link to Recommended VS Code Extensions") 35 | 36 | If you choose to use VS Code as your text editor (instead of the web-based editor), install the [vscode-scheme](https://marketplace.visualstudio.com/items?itemName=sjhuangx.vscode-scheme) extension so that parentheses are highlighted. 37 | 38 | Before: 39 | 40 | ![](https://www.learncs.site/assets/images/before-1fb62971706b817f8b61c7a23705e08a.png) 41 | 42 | After: 43 | 44 | ![](https://www.learncs.site/assets/images/after-49c28554ee03a6642fe04e111fd59fd5.png) 45 | 46 | In addition, the 61a-bot ([installation instructions](https://cs61a.org/articles/61a-bot)) VS Code extension is available for Scheme homeworks. The bot is also integrated into `ok`. 47 | 48 | Required Questions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw08#required-questions "Direct link to Required Questions") 49 | --------------------------------------------------------------------------------------------------------------------------------------------------- 50 | 51 | Required Questions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw08#required-questions-1 "Direct link to Required Questions") 52 | ----------------------------------------------------------------------------------------------------------------------------------------------------- 53 | 54 | Getting Started Videos[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw08#getting-started-videos "Direct link to Getting Started Videos") 55 | --------------------------------------------------------------------------------------------------------------------------------------------------------------- 56 | 57 | These videos may provide some helpful direction for tackling the coding problems on this assignment. 58 | 59 | > To see these videos, you should be logged into your berkeley.edu email. 60 | 61 | [YouTube link](https://youtu.be/playlist?list=PLx38hZJ5RLZeOPmZFG6vuUl71MdfpmBLe) 62 | 63 | ### Q1: Ascending[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw08#q1-ascending "Direct link to Q1: Ascending") 64 | 65 | Implement a procedure called `ascending?`, which takes a list of numbers `s` and returns `True` if the numbers are in non-descending order, and `False` otherwise. 66 | 67 | A list of numbers is non-descending if each element after the first is greater than or equal to the previous element. For example... 68 | 69 | * `(1 2 3 3 4)` is non-descending. 70 | * `(1 2 3 3 2)` is not. 71 | 72 | > **Hint**: The built-in `null?` procedure returns whether its argument is `nil`. 73 | 74 | > **Note**: The question mark in `ascending?` is just part of the procedure name and has no special meaning in terms of Scheme syntax. It is a common practice in Scheme to name procedures with a question mark at the end if it returns a boolean value. 75 | 76 | (define (ascending? s) 'YOUR-CODE-HERE) 77 | 78 | Use Ok to unlock and test your code: 79 | 80 | python3 ok -q ascending -upython3 ok -q ascending 81 | 82 | ### Q2: My Filter[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw08#q2-my-filter "Direct link to Q2: My Filter") 83 | 84 | Write a procedure `my-filter`, which takes a predicate `pred` and a list `s`, and returns a new list containing only elements of the list that satisfy the predicate. The output should contain the elements in the same order that they appeared in the original list. 85 | 86 | **Note:** Make sure that you are not just calling the built-in `filter` function in Scheme - we are asking you to re-implement this! 87 | 88 | (define (my-filter pred s) 'YOUR-CODE-HERE) 89 | 90 | Use Ok to unlock and test your code: 91 | 92 | python3 ok -q filter -upython3 ok -q filter 93 | 94 | ### Q3: Interleave[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw08#q3-interleave "Direct link to Q3: Interleave") 95 | 96 | Implement the function `interleave`, which takes two lists `lst1` and `lst2` as arguments. `interleave` should return a new list that interleaves the elements of the two lists. (In other words, the resulting list should contain elements alternating between `lst1` and `lst2`, starting at `lst1`). 97 | 98 | If one of the input lists to `interleave` is shorter than the other, then `interleave` should alternate elements from both lists until one list has no more elements, and then the remaining elements from the longer list should be added to the end of the new list. 99 | 100 | (define (interleave lst1 lst2) 'YOUR-CODE-HERE) 101 | 102 | Use Ok to unlock and test your code: 103 | 104 | python3 ok -q interleave -upython3 ok -q interleave 105 | 106 | ### Q4: No Repeats[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw08#q4-no-repeats "Direct link to Q4: No Repeats") 107 | 108 | Implement `no-repeats`, which takes a list of numbers `s`. It returns a list that has all of the unique elements of `s` in the order that they first appear, but no repeats. 109 | 110 | For example, `(no-repeats (list 5 4 5 4 2 2))` evaluates to `(5 4 2)`. 111 | 112 | > **Hint:** You may find it helpful to use `filter` with a `lambda` procedure to filter out repeats. To test if two numbers `a` and `b` are not equal, use `(not (= a b))`. 113 | 114 | (define (no-repeats s) 'YOUR-CODE-HERE) 115 | 116 | Use Ok to test your code: 117 | 118 | python3 ok -q no_repeats 119 | 120 | Submit[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw08#submit "Direct link to Submit") 121 | --------------------------------------------------------------------------------------------------------------- 122 | 123 | Submit this assignment by uploading any files you've edited **to the appropriate Gradescope assignment.** [Lab 00](https://cs61a.org/lab/lab00/#submit-with-gradescope) has detailed instructions. 124 | 125 | In addition, all students who are **not** in the mega lab must complete this [attendance form](https://go.cs61a.org/lab-att). Submit this form each week, whether you attend lab or missed it for a good reason. The attendance form is not required for mega section students. 126 | 127 | Exam Practice[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw08#exam-practice "Direct link to Exam Practice") 128 | ------------------------------------------------------------------------------------------------------------------------------------ 129 | 130 | The following are some Scheme List exam problems from previous semesters that you may find useful as additional exam practice. 131 | 132 | 1. [Fall 2022 Final, Question 8: A Parentheses Scheme](https://cs61a.org/exam/fa22/final/61a-fa22-final.pdf#page=20) 133 | 2. [Spring 2022 Final, Question 11: Beadazzled, The Scheme-quel](https://cs61a.org/exam/sp22/final/61a-sp22-final.pdf#page=23) 134 | 3. [Fall 2021 Final, Question 4: Spice](https://cs61a.org/exam/fa21/final/61a-fa21-final.pdf#page=18) -------------------------------------------------------------------------------- /hw/hw08/hw08-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw08/hw08-sol.zip -------------------------------------------------------------------------------- /hw/hw08/hw08.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw08/hw08.zip -------------------------------------------------------------------------------- /hw/hw09/README.md: -------------------------------------------------------------------------------- 1 | Homework 9: Programs as Data, Macros[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw09#homework-9-programs-as-data-macros "Direct link to Homework 9: Programs as Data, Macros") 2 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 3 | 4 | * [hw09.zip](https://www.learncs.site/assets/files/hw09-79d4a7fb62d63538c4cff2da66480a98.zip) 5 | 6 | _Due by 11:59pm on Thursday, April 25_ 7 | 8 | Instructions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw09#instructions "Direct link to Instructions") 9 | --------------------------------------------------------------------------------------------------------------------------------- 10 | 11 | Download [hw09.zip](https://www.learncs.site/assets/files/hw09-79d4a7fb62d63538c4cff2da66480a98.zip). Inside the archive, you will find a file called [hw09.scm](https://cs61a.org//hw/hw09/hw09.scm), along with a copy of the `ok` autograder. 12 | 13 | **Submission:** When you are done, submit the assignment by uploading all code files you've edited to Gradescope. You may submit more than once before the deadline; only the final submission will be scored. Check that you have successfully submitted your code on Gradescope. See [Lab 0](https://cs61a.org/lab/lab00#task-c-submitting-the-assignment) for more instructions on submitting assignments. 14 | 15 | **Using Ok:** If you have any questions about using Ok, please refer to [this guide.](https://cs61a.org/articles/using-ok) 16 | 17 | **Readings:** You might find the following references useful: 18 | 19 | * [Scheme Specification](https://cs61a.org/articles/scheme-spec/) 20 | * [Scheme Built-in Procedure Reference](https://cs61a.org/articles/scheme-builtins/) 21 | 22 | **Grading:** Homework is graded based on correctness. Each incorrect problem will decrease the total score by one point. **This homework is out of 2 points.** 23 | 24 | The 61A Scheme interpreter is included in each Scheme assignment. To start it, type `python3 scheme` in a terminal. To load a Scheme file called `f.scm`, type `python3 scheme -i f.scm`. To exit the Scheme interpreter, type `(exit)`. 25 | 26 | ### Scheme Editor[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw09#scheme-editor "Direct link to Scheme Editor") 27 | 28 | All Scheme assignments include a web-based editor that makes it easy to run ok tests and visualize environments. Type `python3 editor` in a terminal, and the editor will open in a browser window (at `http://127.0.0.1:31415/`). To stop running the editor and return to the command line, type `Ctrl-C` in the terminal where you started the editor. 29 | 30 | The `Run` button loads the current assignment's `.scm` file and opens a Scheme interpreter, allowing you to try evaluating different Scheme expressions. 31 | 32 | The `Test` button runs all ok tests for the assignment. Click `View Case` for a failed test, then click `Debug` to step through its evaluation. 33 | 34 | ### Recommended VS Code Extensions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw09#recommended-vs-code-extensions "Direct link to Recommended VS Code Extensions") 35 | 36 | If you choose to use VS Code as your text editor (instead of the web-based editor), install the [vscode-scheme](https://marketplace.visualstudio.com/items?itemName=sjhuangx.vscode-scheme) extension so that parentheses are highlighted. 37 | 38 | Before: 39 | 40 | ![](https://www.learncs.site/assets/images/before-1fb62971706b817f8b61c7a23705e08a.png) 41 | 42 | After: 43 | 44 | ![](https://www.learncs.site/assets/images/after-49c28554ee03a6642fe04e111fd59fd5.png) 45 | 46 | In addition, the 61a-bot ([installation instructions](https://cs61a.org/articles/61a-bot)) VS Code extension is available for Scheme homeworks. The bot is also integrated into `ok`. 47 | 48 | Required Questions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw09#required-questions "Direct link to Required Questions") 49 | --------------------------------------------------------------------------------------------------------------------------------------------------- 50 | 51 | Getting Started Videos[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw09#getting-started-videos "Direct link to Getting Started Videos") 52 | --------------------------------------------------------------------------------------------------------------------------------------------------------------- 53 | 54 | These videos may provide some helpful direction for tackling the coding problems on this assignment. 55 | 56 | > To see these videos, you should be logged into your berkeley.edu email. 57 | 58 | [YouTube link](https://youtu.be/playlist?list=PLx38hZJ5RLZcRCa7WhQVKh5s5ZLfGV9hc) 59 | 60 | Programs as Data: Chef Curry[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw09#programs-as-data-chef-curry "Direct link to Programs as Data: Chef Curry") 61 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 62 | 63 | Recall that currying transforms a multiple argument function into a series of higher-order, one argument functions. In the next set of questions, you will be creating functions that can automatically curry a function of any length using the notion that programs are data! 64 | 65 | ### Q1: Cooking Curry[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw09#q1-cooking-curry "Direct link to Q1: Cooking Curry") 66 | 67 | Implement the function `curry-cook`, which takes in a Scheme list `formals` and a quoted expression `body`. `curry-cook` should generate a program as a list which is a curried version of a lambda function. The outputted program should be a curried version of a lambda function with formal arguments equal to `formals`, and a function body equal to `body`. You may assume that all functions passed in will have more than 0 `formals`; otherwise, it would not be curry-able! 68 | 69 | For example, if you wanted to curry the function `(lambda (x y) (+ x y))`, you would set `formals` equal to `'(x y)`, the `body` equal to `'(+ x y)`, and make a call to `curry-cook`: `(curry-cook '(x y) '(+ x y))`. 70 | 71 | scm> (curry-cook '(a) 'a)(lambda (a) a)scm> (curry-cook '(x y) '(+ x y))(lambda (x) (lambda (y) (+ x y))) 72 | 73 | (define (curry-cook formals body) 'YOUR-CODE-HERE) 74 | 75 | Use Ok to test your code: 76 | 77 | python3 ok -q curry-cook 78 | 79 | ### Q2: Consuming Curry[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw09#q2-consuming-curry "Direct link to Q2: Consuming Curry") 80 | 81 | Implement the function `curry-consume`, which takes in a curried lambda function `curry` and applies the function to a list of arguments `args`. You may make the following assumptions: 82 | 83 | 1. If `curry` is an `n`\-curried function, then there will be at most `n` arguments in `args`. 84 | 2. **If there are 0 arguments** (`args` is an empty list), then you may assume that `curry` has been fully applied with relevant arguments; in this case, `curry` now contains a value representing the output of the lambda function. Return it. 85 | 86 | Note that there can be fewer `args` than `formals` for the corresponding lambda function `curry`! In the case that there are fewer arguments, `curry-consume` should return a curried lambda function, which is the result of partially applying `curry` up to the number of `args` provdied. See the doctests below for a few examples. 87 | 88 | scm> (define three-curry (lambda (x) (lambda (y) (lambda (z) (+ x (* y z)))) ))three-curryscm> (define eat-two (curry-consume three-curry '(1 2))) ; pass in only two arguments, return should be a one-arg lambda function!eat-twoscm> eat-two(lambda (z) (+ x (* y z)))scm> (eat-two 3) ; pass in the last argument; 1 + (2 * 3)7scm> (curry-consume three-curry '(1 2 3)) ; all three arguments at once7 89 | 90 | (define (curry-consume curry args) 'YOUR-CODE-HERE) 91 | 92 | Use Ok to test your code: 93 | 94 | python3 ok -q curry-consume 95 | 96 | Macros[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw09#macros "Direct link to Macros") 97 | --------------------------------------------------------------------------------------------------------------- 98 | 99 | ### Q3: Switch to Cond[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw09#q3-switch-to-cond "Direct link to Q3: Switch to Cond") 100 | 101 | `switch` is a macro that takes in an expression `expr` and a list of pairs, `options`, where the first element of each pair is some value and the second element is a single expression. `switch` evaluates the expression contained in the list of `options` that corresponds to the value that `expr` evaluates to. 102 | 103 | scm> (switch (+ 1 1) ((1 (print 'a)) (2 (print 'b)) ; (print 'b) is evaluated because (+ 1 1) evaluates to 2 (3 (print 'c))))b 104 | 105 | `switch` uses another procedure called `switch-to-cond` in its implementation: 106 | 107 | scm> (define-macro (switch expr options) (switch-to-cond (list 'switch expr options)) ) 108 | 109 | Your task is to define `switch-to-cond`, which is a procedure (not a macro) that takes a quoted `switch` expression and converts it into a `cond` expression with the same behavior. An example is shown below. 110 | 111 | scm> (switch-to-cond `(switch (+ 1 1) ((1 2) (2 4) (3 6))))(cond ((equal? (+ 1 1) 1) 2) ((equal? (+ 1 1) 2) 4) ((equal? (+ 1 1) 3) 6)) 112 | 113 | (define-macro (switch expr options) (switch-to-cond (list 'switch expr options)))(define (switch-to-cond switch-expr) (cons _________ (map (lambda (option) (cons _______________ (cdr option))) (car (cdr (cdr switch-expr)))))) 114 | 115 | Use Ok to test your code: 116 | 117 | python3 ok -q switch-to-cond 118 | 119 | Check Your Score Locally[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw09#check-your-score-locally "Direct link to Check Your Score Locally") 120 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 121 | 122 | You can locally check your score on each question of this assignment by running 123 | 124 | python3 ok --score 125 | 126 | **This does NOT submit the assignment!** When you are satisfied with your score, submit the assignment to Gradescope to receive credit for it. 127 | 128 | Submit[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw09#submit "Direct link to Submit") 129 | --------------------------------------------------------------------------------------------------------------- 130 | 131 | Submit this assignment by uploading any files you've edited **to the appropriate Gradescope assignment.** [Lab 00](https://cs61a.org/lab/lab00/#submit-with-gradescope) has detailed instructions. 132 | 133 | In addition, all students who are **not** in the mega lab must complete this [attendance form](https://go.cs61a.org/lab-att). Submit this form each week, whether you attend lab or missed it for a good reason. The attendance form is not required for mega section students. 134 | 135 | Exam Practice[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw09#exam-practice "Direct link to Exam Practice") 136 | ------------------------------------------------------------------------------------------------------------------------------------ 137 | 138 | Homework assignments will also contain prior exam questions for you to try. These questions have no submission component; feel free to attempt them if you'd like some practice! 139 | 140 | Macros 141 | 142 | 1. Fall 2019 Final Q9: [Macro Lens](https://cs61a.org/exam/fa19/final/61a-fa19-final.pdf#page=10) 143 | 2. Summer 2019 Final Q10c: [Slice](https://cs61a.org/exam/su19/final/61a-su19-final.pdf#page=10) 144 | 3. Spring 2019 Final Q8: [Macros](https://cs61a.org/exam/sp19/final/61a-sp19-final.pdf#page=8) -------------------------------------------------------------------------------- /hw/hw09/hw09-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw09/hw09-sol.zip -------------------------------------------------------------------------------- /hw/hw09/hw09.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw09/hw09.zip -------------------------------------------------------------------------------- /hw/hw10/README.md: -------------------------------------------------------------------------------- 1 | Homework 10: SQL[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw10#homework-10-sql "Direct link to Homework 10: SQL") 2 | -------------------------------------------------------------------------------------------------------------------------------------------- 3 | 4 | * [hw10.zip](https://www.learncs.site/assets/files/hw10-6a0d60620839e6fcb4e64351bc47b624.zip) 5 | 6 | _Due by 11:59pm on Thursday, April 25_ 7 | 8 | Instructions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw10#instructions "Direct link to Instructions") 9 | --------------------------------------------------------------------------------------------------------------------------------- 10 | 11 | Download [hw10.zip](https://www.learncs.site/assets/files/hw10-6a0d60620839e6fcb4e64351bc47b624.zip). 12 | 13 | **Submission:** When you are done, submit the assignment by uploading all code files you've edited to Gradescope. You may submit more than once before the deadline; only the final submission will be scored. Check that you have successfully submitted your code on Gradescope. See [Lab 0](https://cs61a.org/lab/lab00#task-c-submitting-the-assignment) for more instructions on submitting assignments. 14 | 15 | **Using Ok:** If you have any questions about using Ok, please refer to [this guide.](https://cs61a.org/articles/using-ok) 16 | 17 | **Grading:** Homework is graded based on correctness. Each incorrect problem will decrease the total score by one point. **This homework is out of 2 points.** 18 | 19 | To check your progress, you can run `sqlite3` directly by running: 20 | 21 | python3 sqlite_shell.py --init hw10.sql 22 | 23 | You should also check your work using `ok`: 24 | 25 | python3 ok 26 | 27 | Required Questions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw10#required-questions "Direct link to Required Questions") 28 | --------------------------------------------------------------------------------------------------------------------------------------------------- 29 | 30 | Getting Started Videos[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw10#getting-started-videos "Direct link to Getting Started Videos") 31 | --------------------------------------------------------------------------------------------------------------------------------------------------------------- 32 | 33 | These videos may provide some helpful direction for tackling the coding problems on this assignment. 34 | 35 | > To see these videos, you should be logged into your berkeley.edu email. 36 | 37 | [YouTube link](https://youtu.be/playlist?list=PLx38hZJ5RLZdu9gX9JS-nvtf4ELt9Vtnm) 38 | 39 | SQL[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw10#sql "Direct link to SQL") 40 | ------------------------------------------------------------------------------------------------------ 41 | 42 | ### Dog Data[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw10#dog-data "Direct link to Dog Data") 43 | 44 | In each question below, you will define a new table based on the following tables. 45 | 46 | CREATE TABLE parents AS SELECT "abraham" AS parent, "barack" AS child UNION SELECT "abraham" , "clinton" UNION SELECT "delano" , "herbert" UNION SELECT "fillmore" , "abraham" UNION SELECT "fillmore" , "delano" UNION SELECT "fillmore" , "grover" UNION SELECT "eisenhower" , "fillmore";CREATE TABLE dogs AS SELECT "abraham" AS name, "long" AS fur, 26 AS height UNION SELECT "barack" , "short" , 52 UNION SELECT "clinton" , "long" , 47 UNION SELECT "delano" , "long" , 46 UNION SELECT "eisenhower" , "short" , 35 UNION SELECT "fillmore" , "curly" , 32 UNION SELECT "grover" , "short" , 28 UNION SELECT "herbert" , "curly" , 31;CREATE TABLE sizes AS SELECT "toy" AS size, 24 AS min, 28 AS max UNION SELECT "mini" , 28 , 35 UNION SELECT "medium" , 35 , 45 UNION SELECT "standard" , 45 , 60; 47 | 48 | Your tables should still perform correctly even if the values in these tables change. For example, if you are asked to list all dogs with a name that starts with h, you should write: 49 | 50 | SELECT name FROM dogs WHERE "h" <= name AND name < "i"; 51 | 52 | Instead of assuming that the `dogs` table has only the data above and writing 53 | 54 | SELECT "herbert"; 55 | 56 | The former query would still be correct if the name `grover` were changed to `hoover` or a row was added with the name `harry`. 57 | 58 | ### Q1: By Parent Height[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw10#q1-by-parent-height "Direct link to Q1: By Parent Height") 59 | 60 | Create a table `by_parent_height` that has a column of the names of all dogs that have a `parent`, ordered by the height of the parent dog from tallest parent to shortest parent. 61 | 62 | -- All dogs with parents ordered by decreasing height of their parentCREATE TABLE by_parent_height AS SELECT "REPLACE THIS LINE WITH YOUR SOLUTION"; 63 | 64 | For example, `fillmore` has a parent `eisenhower` with height 35, and so should appear before `grover` who has a parent `fillmore` with height 32. The names of dogs with parents of the same height should appear together in any order. For example, `barack` and `clinton` should both appear at the end, but either one can come before the other. 65 | 66 | sqlite> select * from by_parent_height;herbertfillmoreabrahamdelanogroverbarackclinton 67 | 68 | Use Ok to test your code: 69 | 70 | python3 ok -q by_parent_height 71 | 72 | ### Q2: Size of Dogs[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw10#q2-size-of-dogs "Direct link to Q2: Size of Dogs") 73 | 74 | The Fédération Cynologique Internationale classifies a standard poodle as over 45 cm and up to 60 cm. The `sizes` table describes this and other such classifications, where a dog must be over the `min` and less than or equal to the `max` in `height` to qualify as `size`. 75 | 76 | Create a `size_of_dogs` table with two columns, one for each dog's `name` and another for its `size`. 77 | 78 | -- The size of each dogCREATE TABLE size_of_dogs AS SELECT "REPLACE THIS LINE WITH YOUR SOLUTION"; 79 | 80 | The output should look like the following: 81 | 82 | sqlite> select * from size_of_dogs;abraham|toybarack|standardclinton|standarddelano|standardeisenhower|minifillmore|minigrover|toyherbert|mini 83 | 84 | Use Ok to test your code: 85 | 86 | python3 ok -q size_of_dogs 87 | 88 | ### Q3: Sentences[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw10#q3-sentences "Direct link to Q3: Sentences") 89 | 90 | There are two pairs of siblings that have the same size. Create a table that contains a row with a string for each of these pairs. Each string should be a sentence describing the siblings by their size. 91 | 92 | -- Filling out this helper table is optionalCREATE TABLE siblings AS SELECT "REPLACE THIS LINE WITH YOUR SOLUTION";-- Sentences about siblings that are the same sizeCREATE TABLE sentences AS SELECT "REPLACE THIS LINE WITH YOUR SOLUTION"; 93 | 94 | Each sibling pair should appear only once in the output, and siblings should be listed in alphabetical order (e.g. `"barack and clinton..."` instead of `"clinton and barack..."`), as follows: 95 | 96 | sqlite> select * from sentences;The two siblings, barack and clinton, have the same size: standardThe two siblings, abraham and grover, have the same size: toy 97 | 98 | > **Hint**: First, create a helper table containing each pair of siblings. This will make comparing the sizes of siblings when constructing the main table easier. 99 | > 100 | > **Hint**: If you join a table with itself, use `AS` within the `FROM` clause to give each table an alias. 101 | > 102 | > **Hint**: In order to concatenate two strings into one, use the `||` operator. 103 | 104 | Use Ok to test your code: 105 | 106 | python3 ok -q sentences 107 | 108 | ### Q4: Low Variance[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw10#q4-low-variance "Direct link to Q4: Low Variance") 109 | 110 | We want to create a table that contains the height range (difference between maximum and minimum height) of all dogs that share a fur type. However, we'll only consider fur types where each dog with that fur type is within 30% of the average height of all dogs with that fur type. 111 | 112 | For example, if the average height for short-haired dogs is 10, then in order to be included in our output, all dogs with short hair must have a height of at most 13 and at least 7. 113 | 114 | To achieve this, we can use `MIN`, `MAX`, and `AVG`. For this problem, we'll want to find the average height and make sure that: 115 | 116 | * There are no heights smaller than 0.7 of the average. 117 | * There are no heights greater than 1.3 of the average. 118 | 119 | Your output should first include the fur type and then the height range for the fur types that meet this criteria. 120 | 121 | -- Height range for each fur type where all of the heights differ by no more than 30% from the average heightCREATE TABLE low_variance AS SELECT "REPLACE THIS LINE WITH YOUR SOLUTION";-- Example:SELECT * FROM low_variance;-- Expected output:-- curly|1 122 | 123 | _Explanation_: The average height of long-haired dogs is 39.7, so the low variance criterion requires the height of each long-haired dog to be between 27.8 and 51.6. However, `abraham` is a long-haired dog with height 26, which is outside this range. For short-haired dogs, `barack` falls outside the valid range (check!). Thus, neither short nor long haired dogs are included in the output. There are two curly haired dogs: `fillmore` with height 32 and `herbert` with height 31. This gives a height range of 1. 124 | 125 | Use Ok to test your code: 126 | 127 | python3 ok -q low_variance 128 | 129 | Submit[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw10#submit "Direct link to Submit") 130 | --------------------------------------------------------------------------------------------------------------- 131 | 132 | Submit this assignment by uploading any files you've edited **to the appropriate Gradescope assignment.** [Lab 00](https://cs61a.org/lab/lab00/#submit-with-gradescope) has detailed instructions. 133 | 134 | Make sure to submit `hw10.sql` to the autograder! 135 | 136 | Exam Practice[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw10#exam-practice "Direct link to Exam Practice") 137 | ------------------------------------------------------------------------------------------------------------------------------------ 138 | 139 | The following are some SQL exam problems from previous semesters that you may find useful as additional exam practice. 140 | 141 | 1. [Fall 2019 Final, Question 10: Big Game](https://cs61a.org/exam/fa19/final/61a-fa19-final.pdf#page=11) 142 | 2. [Summer 2019 Final, Question 8: The Big SQL](https://cs61a.org/exam/su19/final/61a-su19-final.pdf#page=11) 143 | 3. [Fall 2018 Final, Question 7: SQL of Course](https://inst.eecs.berkeley.edu/~cs61a/fa18/assets/pdfs/61a-fa18-final.pdf#page=9) -------------------------------------------------------------------------------- /hw/hw10/hw10-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw10/hw10-sol.zip -------------------------------------------------------------------------------- /hw/hw10/hw10.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw10/hw10.zip -------------------------------------------------------------------------------- /hw/hw11/README.md: -------------------------------------------------------------------------------- 1 | Homework 11 | CS 61A Spring 2024 2 | ================================ 3 | 4 | Homework 11: Finale[​](https://www.learncs.site/docs/curriculum-resource/cs61a/homework/hw11#homework-11-finale "Direct link to Homework 11: Finale") 5 | ----------------------------------------------------------------------------------------------------------------------------------------------------- 6 | 7 | _Due by 11:59pm on Sunday, May 5_ 8 | 9 | This homework has nothing you need to submit to Gradescope. Rather, there are 3 surveys you need to fill out. 10 | 11 | * Complete the [61A end-of-semester survey](https://forms.gle/vY3xWvk71tpF8x8K9), 12 | * Fill out the [UC Berkeley course evaluations](https://course-evaluations.berkeley.edu/), and 13 | * [Vote](https://forms.gle/dTzYHR23ZMDQ8URp6) on your favorite [Scheme art](https://cs61a.org/proj/scheme_gallery). 14 | 15 | If 80% or more students (computed as the fraction of the number of students who took Midterm 2) complete all three, then all students who complete this homework get an extra credit point! -------------------------------------------------------------------------------- /hw/hw11/hw11.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/hw/hw11/hw11.zip -------------------------------------------------------------------------------- /lab/lab00/lab00.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab00/lab00.zip -------------------------------------------------------------------------------- /lab/lab01/lab01-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab01/lab01-sol.zip -------------------------------------------------------------------------------- /lab/lab01/lab01.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab01/lab01.zip -------------------------------------------------------------------------------- /lab/lab02/lab02-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab02/lab02-sol.zip -------------------------------------------------------------------------------- /lab/lab02/lab02.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab02/lab02.zip -------------------------------------------------------------------------------- /lab/lab03/lab03-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab03/lab03-sol.zip -------------------------------------------------------------------------------- /lab/lab03/lab03.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab03/lab03.zip -------------------------------------------------------------------------------- /lab/lab04/lab04-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab04/lab04-sol.zip -------------------------------------------------------------------------------- /lab/lab04/lab04.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab04/lab04.zip -------------------------------------------------------------------------------- /lab/lab05/lab05-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab05/lab05-sol.zip -------------------------------------------------------------------------------- /lab/lab05/lab05.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab05/lab05.zip -------------------------------------------------------------------------------- /lab/lab06/lab06-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab06/lab06-sol.zip -------------------------------------------------------------------------------- /lab/lab06/lab06.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab06/lab06.zip -------------------------------------------------------------------------------- /lab/lab07/lab07-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab07/lab07-sol.zip -------------------------------------------------------------------------------- /lab/lab07/lab07.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab07/lab07.zip -------------------------------------------------------------------------------- /lab/lab08/lab08--sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab08/lab08--sol.zip -------------------------------------------------------------------------------- /lab/lab08/lab08.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab08/lab08.zip -------------------------------------------------------------------------------- /lab/lab09/lab09-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab09/lab09-sol.zip -------------------------------------------------------------------------------- /lab/lab09/lab09.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab09/lab09.zip -------------------------------------------------------------------------------- /lab/lab10/lab10-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab10/lab10-sol.zip -------------------------------------------------------------------------------- /lab/lab10/lab10.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab10/lab10.zip -------------------------------------------------------------------------------- /lab/lab11/README.md: -------------------------------------------------------------------------------- 1 | Lab 11: Programs as Data, Macros 2 | Due by 11:59pm on Wednesday, April 17. 3 | 4 | Starter Files 5 | Download lab11.zip. Inside the archive, you will find starter files for the questions in this lab, along with a copy of the Ok autograder. 6 | 7 | Required Questions 8 | Getting Started Videos 9 | These videos may provide some helpful direction for tackling the coding problems on this assignment. 10 | 11 | To see these videos, you should be logged into your berkeley.edu email. 12 | 13 | YouTube link 14 | 15 | Quasiquotation 16 | Consult the drop-down if you need a refresher on quasiquotation. It's okay to skip directly to the questions and refer back here should you get stuck. 17 | 18 | The normal quote ' and the quasiquote ` are both valid ways to quote an expression. However, the quasiquoted expression can be unquoted with the "unquote" , (represented by a comma). When a term in a quasiquoted expression is unquoted, the unquoted term is evaluated, instead of being taken as literal text. This mechanism is somewhat akin to using f-strings in Python, where expressions inside {} are evaluated and inserted into the string. 19 | 20 | scm> (define a 5) 21 | a 22 | scm> (define b 3) 23 | b 24 | scm> `(* a b) ; Quasiquoted expression 25 | (* a b) 26 | scm> `(* a ,b) ; Unquoted b, which evaluates to 3 27 | (* a 3) 28 | scm> `(* ,(+ a b) b) ; Unquoted (+ a b), which evaluates to 8 29 | (* 8 b) 30 | 31 | Q1: WWSD: Quasiquote 32 | Use Ok to test your knowledge with the following "What Would Scheme Display?" questions: 33 | 34 | python3 ok -q wwsd-quasiquote -u 35 | 36 | scm> '(1 x 3) 37 | 38 | scm> (define x 2) 39 | 40 | scm> `(1 x 3) 41 | 42 | scm> `(1 ,x 3) 43 | 44 | scm> `(1 x ,3) 45 | 46 | scm> `(1 (,x) 3) 47 | 48 | scm> `(1 ,(+ x 2) 3) 49 | 50 | scm> (define y 3) 51 | 52 | scm> `(x ,(* y x) y) 53 | 54 | scm> `(1 ,(cons x (list y 4)) 5) 55 | 56 | Programs as Data 57 | Consult the drop-down if you need a refresher on Programs as Data. It's okay to skip directly to the questions and refer back here should you get stuck. 58 | 59 | All Scheme programs are made up of expressions. There are two types of expressions: primitive (a.k.a atomic) expressions and combinations. Here are some examples of each: 60 | 61 | Primitive/atomic expression: #f, 1.7, + 62 | Combinations: (factorial 10), (/ 8 3), (not #f) 63 | Scheme represents combinations as a Scheme list. Therefore, a combination can be constructed through list manipulation. 64 | 65 | For example, the expression (list '+ 2 2) evaluates to the list (+ 2 2), which is also an expression. If we then call eval on this list, it will evaluate to 4. The eval procedure takes in one argument expr and evaluates expr in the current environment. 66 | 67 | scm> (define expr (list '+ 2 2)) 68 | expr 69 | scm> expr 70 | (+ 2 2) 71 | scm> (eval expr) 72 | 4 73 | 74 | Additionally, quasiquotation is very helpful for building procedures that create expressions. Take a look at the following add-program: 75 | 76 | scm> (define (add-program x y) 77 | ...> `(+ ,x ,y)) 78 | add-program 79 | scm> (add-program 3 6) 80 | (+ 3 6) 81 | 82 | add-program takes in two inputs x and y and returns an expression that, if evaluated, evaluates to the result of adding x and y together. Within add-program, we use a quasiquote to build the addition expression (+ ...), and we unquote x and y to get their evaluated values in the addition expression. 83 | 84 | Q2: If Program 85 | In Scheme, the if special form allows us to evaluate one of two expressions based on a predicate. Write a program if-program that takes in the following parameters: 86 | 87 | predicate : a quoted expression which will evaluate to the condition in our if-expression 88 | if-true : a quoted expression which will evaluate to the value we want to return if predicate evaluates to true (#t) 89 | if-false : a quoted expression which will evaluate to the value we want to return if predicate evaluates to false (#f) 90 | The program returns a Scheme list that represents an if expression in the form: (if ). Evaluating this expression returns the result of evaluating this if expression. 91 | 92 | Here are some doctests to show this: 93 | 94 | scm> (define x 1) 95 | scm> (if-program '(= 0 0) '(+ x 1) 'x) 96 | (if (= 0 0) (+ x 1) x) 97 | scm> (eval (if-program '(= 0 0) '(+ x 1) 'x)) 98 | 2 99 | scm> (if-program '(= 1 0) '(print 3) '(print 5)) 100 | (if (= 1 0) (print 3) (print 5)) 101 | scm> (eval (if-program '(= 1 0) '(print 3) '(print 5))) 102 | 5 103 | 104 | (define (if-program condition if-true if-false) 105 | 'YOUR-CODE-HERE 106 | ) 107 | 108 | Use Ok to test your code: 109 | 110 | python3 ok -q if-program 111 | 112 | Q3: Exponential Powers 113 | Implement a procedure (pow-expr base exp) that returns an expression that, when evaluated, raises the number base to the power of the nonnegative integer exp. The body of pow-expr should not perform any multiplication (or exponentiation). Instead, it should just construct an expression containing only the symbols square and * as well as the number base and parentheses. The length of this expression should grow logarithmically with respect to exp, rather than linearly. 114 | 115 | Examples: 116 | 117 | scm> (pow-expr 2 0) 118 | 1 119 | scm> (pow-expr 2 1) 120 | (* 2 1) 121 | scm> (pow-expr 2 5) 122 | (* 2 (square (square (* 2 1)))) 123 | scm> (pow-expr 2 15) 124 | (* 2 (square (* 2 (square (* 2 (square (* 2 1))))))) 125 | scm> (pow-expr 2 16) 126 | (square (square (square (square (* 2 1))))) 127 | scm> (eval (pow-expr 2 16)) 128 | 65536 129 | 130 | Hint: 131 | 132 | x2y = (xy)2 133 | x2y+1 = x(xy)2 134 | For example, 216 = (28)2 and 217 = 2 * (28)2. 135 | 136 | You may use the built-in predicates even? and odd?. Also, the square procedure is defined for you. 137 | 138 | Here's the solution to a similar homework problem. 139 | 140 | (define (square n) (* n n)) 141 | 142 | (define (pow-expr base exp) 143 | 'YOUR-CODE-HERE 144 | ) 145 | 146 | Use Ok to test your code: 147 | 148 | python3 ok -q pow 149 | 150 | Macros 151 | A macro is a code transformation that is created using define-macro and applied using a call expression. A macro call is evaluated by: 152 | 153 | Binding the formal paramters of the macro to the unevaluated operand expressions of the macro call. 154 | Evaluating the body of the macro, which returns an expression. 155 | Evaluating the expression returned by the macro in the frame of the original macro call. 156 | scm> (define-macro (twice expr) (list 'begin expr expr)) 157 | twice 158 | scm> (twice (+ 2 2)) ; evaluates (begin (+ 2 2) (+ 2 2)) 159 | 4 160 | scm> (twice (print (+ 2 2))) ; evaluates (begin (print (+ 2 2)) (print (+ 2 2))) 161 | 4 162 | 4 163 | 164 | Q4: Repeat 165 | Define repeat, a macro that is called on a number n and an expression expr. Calling it evaluates expr in a local frame n times, and its value is the final result. You will find the helper function repeated-call useful, which takes a number n and a zero-argument procedure f and calls f n times. 166 | 167 | For example, (repeat (+ 2 3) (print 1)) is equivalent to: 168 | 169 | (repeated-call (+ 2 3) (lambda () (print 1))) 170 | 171 | and should evaluate (print 1) repeatedly 5 times. 172 | 173 | The following expression should print four four times: 174 | 175 | (repeat 2 (repeat 2 (print 'four))) 176 | 177 | (define-macro (repeat n expr) 178 | `(repeated-call ,n ___)) 179 | 180 | ; Call zero-argument procedure f n times and return the final result. 181 | (define (repeated-call n f) 182 | (if (= n 1) ___ (begin ___ ___))) 183 | 184 | 185 | Use Ok to test your code: 186 | 187 | python3 ok -q repeat-lambda 188 | 189 | The repeated-call procedure takes a zero-argument procedure, so (lambda () ___) must appear in the blank. The body of the lambda is expr, which must be unquoted. 190 | 191 | Call f on no arguments with (f). If n is 1, just call f. If n is greater than 1, first call f and then call (repeated-call (- n 1) f). -------------------------------------------------------------------------------- /lab/lab11/lab11-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab11/lab11-sol.zip -------------------------------------------------------------------------------- /lab/lab11/lab11.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab11/lab11.zip -------------------------------------------------------------------------------- /lab/lab12/lab12-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab12/lab12-sol.zip -------------------------------------------------------------------------------- /lab/lab12/lab12.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/lab/lab12/lab12.zip -------------------------------------------------------------------------------- /ppt/01-Computer_Science_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/01-Computer_Science_1pp.pdf -------------------------------------------------------------------------------- /ppt/02-Functions_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/02-Functions_1pp.pdf -------------------------------------------------------------------------------- /ppt/03-Control_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/03-Control_1pp.pdf -------------------------------------------------------------------------------- /ppt/04-Higher-Order_Functions_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/04-Higher-Order_Functions_1pp.pdf -------------------------------------------------------------------------------- /ppt/05-Environments_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/05-Environments_1pp.pdf -------------------------------------------------------------------------------- /ppt/06-Functional_Abstraction_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/06-Functional_Abstraction_1pp.pdf -------------------------------------------------------------------------------- /ppt/07-Function_Examples_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/07-Function_Examples_1pp.pdf -------------------------------------------------------------------------------- /ppt/09-Recursion_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/09-Recursion_1pp.pdf -------------------------------------------------------------------------------- /ppt/10-Tree_Recursion_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/10-Tree_Recursion_1pp.pdf -------------------------------------------------------------------------------- /ppt/11-Sequences_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/11-Sequences_1pp.pdf -------------------------------------------------------------------------------- /ppt/12-Containers_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/12-Containers_1pp.pdf -------------------------------------------------------------------------------- /ppt/13-Data_Abstraction_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/13-Data_Abstraction_1pp.pdf -------------------------------------------------------------------------------- /ppt/14-Trees_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/14-Trees_1pp.pdf -------------------------------------------------------------------------------- /ppt/15-Mutability_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/15-Mutability_1pp.pdf -------------------------------------------------------------------------------- /ppt/16-Iterators_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/16-Iterators_1pp.pdf -------------------------------------------------------------------------------- /ppt/17-Generators_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/17-Generators_1pp.pdf -------------------------------------------------------------------------------- /ppt/18-Objects_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/18-Objects_1pp.pdf -------------------------------------------------------------------------------- /ppt/19-Attributes_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/19-Attributes_1pp.pdf -------------------------------------------------------------------------------- /ppt/20-Inheritance_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/20-Inheritance_1pp.pdf -------------------------------------------------------------------------------- /ppt/21-Representation_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/21-Representation_1pp.pdf -------------------------------------------------------------------------------- /ppt/22-Composition_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/22-Composition_1pp.pdf -------------------------------------------------------------------------------- /ppt/23-Efficiency_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/23-Efficiency_1pp.pdf -------------------------------------------------------------------------------- /ppt/24-Decomposition_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/24-Decomposition_1pp.pdf -------------------------------------------------------------------------------- /ppt/25-Data_Examples_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/25-Data_Examples_1pp.pdf -------------------------------------------------------------------------------- /ppt/27-Scheme_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/27-Scheme_1pp.pdf -------------------------------------------------------------------------------- /ppt/28-Scheme_Lists_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/28-Scheme_Lists_1pp.pdf -------------------------------------------------------------------------------- /ppt/29-Calculator_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/29-Calculator_1pp.pdf -------------------------------------------------------------------------------- /ppt/30-Interpreters_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/30-Interpreters_1pp.pdf -------------------------------------------------------------------------------- /ppt/31-Programs_as_Data_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/31-Programs_as_Data_1pp.pdf -------------------------------------------------------------------------------- /ppt/32-Macros_1pp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/ppt/32-Macros_1pp.pdf -------------------------------------------------------------------------------- /projects/project01/hog-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/projects/project01/hog-sol.zip -------------------------------------------------------------------------------- /projects/project01/hog.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/projects/project01/hog.zip -------------------------------------------------------------------------------- /projects/project02/cats-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/projects/project02/cats-sol.zip -------------------------------------------------------------------------------- /projects/project02/cats.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/projects/project02/cats.zip -------------------------------------------------------------------------------- /projects/project03/ants-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/projects/project03/ants-sol.zip -------------------------------------------------------------------------------- /projects/project03/ants.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/projects/project03/ants.zip -------------------------------------------------------------------------------- /projects/project03/image-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/projects/project03/image-1.png -------------------------------------------------------------------------------- /projects/project03/image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/projects/project03/image.png -------------------------------------------------------------------------------- /projects/project04/scheme-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/projects/project04/scheme-sol.zip -------------------------------------------------------------------------------- /projects/project05/README.md: -------------------------------------------------------------------------------- 1 | Optional Contest: Scheme Art | CS 61A Spring 2024 2 | ================================================= 3 | 4 | Optional Contest: Scheme Art[​](https://www.learncs.site/docs/curriculum-resource/cs61a/project/scheme_contest#optional-contest-scheme-art "Direct link to Optional Contest: Scheme Art") 5 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 6 | 7 | * [scheme\_contest.zip](https://www.learncs.site/assets/files/scheme_contest-9cd30ff71e159090e06d9952e990e0cb.zip) 8 | 9 | > The output is art, 10 | > But what about its source code? 11 | > It's just as abstract. 12 | 13 | Instructions[​](https://www.learncs.site/docs/curriculum-resource/cs61a/project/scheme_contest#instructions "Direct link to Instructions") 14 | ------------------------------------------------------------------------------------------------------------------------------------------ 15 | 16 | > This contest is completely optional! 17 | 18 | Entries are due at **11:59pm on Wednesday, April 24th.** 19 | 20 | Here are the steps to enter the contest: 21 | 22 | 1. Download [scheme\_contest.zip](https://www.learncs.site/assets/files/scheme_contest-9cd30ff71e159090e06d9952e990e0cb.zip). 23 | 24 | 2. Download the file `abstract_turtle.zip` from [this link](https://www.learncs.site/assets/files/abstract_turtle-0b04ea2c0963973049d299d600173c80.zip). Then, unzip the file into your `scheme_contest` directory. The unzipped folder should contain files including `canvas.py` and `color_names.py`. Alternatively, if you'd prefer to install using the `pip` command, you can run `pip3 install abstract-turtle` instead of downloading this zip file. 25 | 26 | 3. Complete the `contest.scm` file (you can render your drawing with `python3 scheme contest.scm --pillow-turtle --turtle-save-path output`). See the [Scheme Built-in Reference on graphics](https://cs61a.org/articles/scheme-builtins/#turtle-graphics) for a description of drawing procedures. 27 | 28 | * If this command doesn't work, try running `python3 scheme contest.scm --turtle-save-path output` instead. The main difference is that this command uses the `tkinter` library, while the former command uses the `pillow` library. Both should generate the same output. 29 | 4. Upload `output.png` which was created by the previous command. 30 | 31 | 32 | In `contest.scm`, the `draw` procedure should draw your entry and then exit on click. 33 | 34 | All entries, including their source code, will be distributed to your fellow students for voting. Please **do not include personal info in your submission.** 35 | 36 | > **Important:** when you are ready to submit, follow **both** these steps: 37 | > 38 | > * Submit your `contest.scm` file to the **Scheme Contest** assignment on Gradescope. 39 | > * Fill out the [contest form](https://forms.gle/FtHnvNcx1jRvZLDS7). Make sure the information here is correct, since we'll be using it to generate your entry in the Scheme art gallery. 40 | > 41 | > **Troubleshooting:** Are you experiencing the error `name 'builtins' is not defined` when trying to render your artwork? If so, add the following line to the top of `scheme_builtins.py`: `import builtins`. You might also be asked to install some dependencies when you try to render your image, and if you do so, it should properly create your visualization. If you don't see this error (it has usually been popping up for select Windows users), you do not need to add the additional import. 42 | 43 | Contest Description[​](https://www.learncs.site/docs/curriculum-resource/cs61a/project/scheme_contest#contest-description "Direct link to Contest Description") 44 | --------------------------------------------------------------------------------------------------------------------------------------------------------------- 45 | 46 | Create a visualization of an iterative or recursive process of your choosing, using turtle graphics. Your implementation must be written entirely in Scheme using the interpreter you have built. All computation must be done in Scheme. 47 | 48 | We will have two categories of submissions: 49 | 50 | * _Featherweight_: Fewer than 512 Scheme tokens (including parentheses) 51 | * _Heavyweight_: Fewer than 4096 Scheme tokens (including parentheses) 52 | 53 | **No single token may contain more than 50 characters.** If your entry requires more tokens than are allowed in the heavyweight category, please contact the course staff for special permission to submit an even longer entry. 54 | 55 | You can check the number of tokens in a Scheme file called `contest.scm` by running the following command: 56 | 57 | python3 scheme_tokens.py contest.scm 58 | 59 | Entries (code and images) will be posted online, and winners will be selected by popular vote. The top three entries in each category will be announced on Ed after voting is closed. 60 | 61 | To improve your chance of success, you are welcome to include a title and descriptive [haiku](http://en.wikipedia.org/wiki/Haiku) in the comments of your entry, which will be included in the voting. 62 | 63 | Contest Rules[​](https://www.learncs.site/docs/curriculum-resource/cs61a/project/scheme_contest#contest-rules "Direct link to Contest Rules") 64 | --------------------------------------------------------------------------------------------------------------------------------------------- 65 | 66 | Before submission, please ensure that your entry abides by these guidelines: 67 | 68 | * Entries must not contain tokens that contain more than 50 characters and must be submitted under the correct category (featherweight/heavyweight). 69 | * Entries must not contain any political content. 70 | * Entries must not contain any offensive, sexually explicit, or ethically objectionable content. 71 | * Entries must not contain any personal information. 72 | * Entries must match your code. That is, the Scheme code you submit must be able to exactly generate the output graphic file you submit. 73 | * Entries must be static images (no animations). We encourage you to experiment with animations on your own, but you may not submit animated artwork for this contest. 74 | 75 | We reserve the right to disqualify any entries that do not follow these guidelines. 76 | 77 | Past Entries[​](https://www.learncs.site/docs/curriculum-resource/cs61a/project/scheme_contest#past-entries "Direct link to Past Entries") 78 | ------------------------------------------------------------------------------------------------------------------------------------------ 79 | 80 | For inspiration, you can peruse these galleries of past entries. Please note that certain submissions may not follow the current guidelines. 81 | 82 | * [Fall 2023] 83 | * [Summer 2023] 84 | * [Spring 2023] 85 | * [Fall 2022] 86 | * [Summer 2022] 87 | * [Spring 2022](https://github.com/caiscoding/CS61A-Spring2022/tree/main) 88 | * [Fall 2021] 89 | * [Summer 2021] 90 | * [Spring 2021] 91 | * [Fall 2020] 92 | * [Summer 2020] 93 | * [Spring 2020] 94 | * [Fall 2019] 95 | * [Summer 2019] 96 | * [Spring 2019] 97 | * [Fall 2018] 98 | * [Summer 2018] 99 | * [Spring 2018] 100 | * [Fall 2017] 101 | * [Summer 2017] 102 | * [Spring 2017] 103 | * [Fall 2016] 104 | * [Summer 2016] 105 | * [Spring 2016] 106 | * [Fall 2015] 107 | * [Spring 2015] 108 | * [Fall 2014] 109 | * [Spring 2014] 110 | * [Fall 2013] 111 | * [Spring 2013] 112 | * [Fall 2012] -------------------------------------------------------------------------------- /projects/project05/scheme_contest-sol.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/projects/project05/scheme_contest-sol.zip -------------------------------------------------------------------------------- /schedule.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leejianping/cs61A-Spring2024/595ac217fe01538edd68ec53bc5304918783b567/schedule.png --------------------------------------------------------------------------------