Return to Video

Generators 2 Solution - Design of Computer Programs

  • 0:00 - 0:05
    And for me the problem is that this solution uses too much memory, uses it unnecessarily.
  • 0:05 - 0:12
    We quit this gigantic list with a million elements and actually a million and one elements
  • 0:12 - 0:14
    and we don't ever use it again.
  • 0:14 - 0:18
    We just use it once to calculate the sum. That seems like sort of waste to me.
  • 0:18 - 0:22
    And this is exactly the motivation for generator expression.
  • 0:22 - 0:24
    We don't want to create list that we're never going to use.
  • 0:24 - 0:28
    So if we want to solve this exact same problem with the generator expression,
  • 0:28 - 0:32
    it's a simple as converting brackets to parenthesis.
  • 0:32 - 0:37
    Actually, we could do away with one set of parenthesis here but I'm going to leave them in
  • 0:37 - 0:39
    and running gives the exact same result.
  • 0:39 - 0:45
    Interesting aside here since range is actually creating a gigantic list as well,
  • 0:45 - 0:48
    we can use Python's built-in xrange function--
  • 0:48 - 0:51
    basically, this prevents us from generating this entire list.
  • 0:51 - 0:55
    Okay. So now we know how to use generator expressions.
  • 0:55 - 1:00
    Let's poke around a bit and figure out exactly what's going on inside of them.
タイトル:
Generators 2 Solution - Design of Computer Programs
概説:

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

English subtitles

改訂 Compare revisions