Return to Video

Generators - Design of Computer Programs

  • 0:00 - 0:04
    We saw generator expressions and functions in Unit 2,
  • 0:04 - 0:07
    but some people in the forums still seemed a bit confused.
  • 0:07 - 0:09
    Don't worry. This is understandable.
  • 0:09 - 0:12
    The generator is an entirely new object, and it can be confusing.
  • 0:12 - 0:14
    In the next few videos, we're going to answer three questions.
  • 0:14 - 0:20
    How do we use generators? I think this is actually an easier question to answer than the second.
  • 0:20 - 0:25
    What is a generator expression/function/object?
  • 0:25 - 0:29
    We'll also talk about when and why do we use generators?
  • 0:29 - 0:32
    Let's start with a problem.
  • 0:32 - 0:37
    We want to compute the sum of the squares of the integers from 1 to 1 million.
  • 0:37 - 0:44
    That would be 1 + 4 + 9--and I probably shouldn't write all of these out.
  • 0:44 - 0:47
    The question is how would you do this?
  • 0:47 - 0:53
    If you came from CS101, your answer is probably to start with a function.
  • 0:53 - 0:56
    Maybe your function would have looked something like this
  • 0:56 - 1:00
    where we make an empty list, append all of the squares to that list,
  • 1:00 - 1:02
    and then return the sum of that list.
  • 1:02 - 1:06
    Then you would have called your function with an argument of 1 million,
  • 1:06 - 1:09
    and you would've gotten your answer.
  • 1:09 - 1:15
    First let me say this is a find solution. It gets the job done, but it has some problems.
  • 1:15 - 1:20
    Keeping in mind that we just want to make this calculation once,
  • 1:20 - 1:23
    what do you think is the biggest problem with this solution.
  • 1:23 - 1:26
    Do you think it's messy, and it unnecessary clutters up the program?
  • 1:26 - 1:29
    Do you think it uses memory when it doesn't really have to?
  • 1:29 - 1:33
    Do you think it runs to slowly? Or do you think the code doesn't work?
  • 1:33 - 1:36
    You may have several problems with this, so it's somewhat subjective.
  • 1:36 - 1:39
    Just choose whatever you think is the biggest problem.
タイトル:
Generators - Design of Computer Programs
概説:

more » « less
Video Language:
English
Team:
Udacity
プロジェクト:
CS212 - Design of Computer Programs
Duration:
01:40

English subtitles

改訂 Compare revisions