closed lab solution
play

Closed Lab Solution Review Closed Lab 01 CS 224 Introduction to - PowerPoint PPT Presentation

2/10/20 Closed Lab Solution Review Closed Lab 01 CS 224 Introduction to Python Spring 2020 Class #07: Iteration 1 2/10/20 Preliminaries: Random Preliminaries: Additional List Operations random provides a number of helpful methods


  1. 2/10/20 Closed Lab Solution • Review Closed Lab 01 CS 224 Introduction to Python Spring 2020 Class #07: Iteration 1

  2. 2/10/20 Preliminaries: Random Preliminaries: Additional List Operations • random provides a number of helpful methods • List membership: in • random() returns a float in [0, 1) • returns Boolean • randint(x, y) returns an int in [x, y] • e in L • shuffle(L) permutes L in place • List of consecutive integers: range • Multiple ways to import • returns a list • import random • range(10) [0, 1, …, 9] • random.random, random.randint, random.shuffle • range(100, 200) [100, 101, …, 199] • import random as rd • Assignment: = • rd.random, rd.randint, rd.shuffle • creates an alias • from random import random, randint, shuffle • random, randint, shuffle 2

  3. 2/10/20 Iteration Iteration • while loops • for loops with range and len i = 0 for i in range(len(L)): • range(len(L)) returns list with an • similar to other languages with minor while i < 10: instructions syntactic differences int value, beginning with 0, for each instructions element in a list L i += 1 • iterator • for loops for e in L: for i in range(x): • operate on each element of list • primarily list based instructions instructions • e takes value of each element in list in turn 3

  4. 2/10/20 A big BUT concerning previous note Important note about iterators • Consider code this code fragment • Let L be a list of lists for e in L: • Consider code this code fragment for e in L: e = 2 * e • e is really a reference to each e[0] = 2 * e[0] element in list • e is a reference to each element • e = 2 * e reassigns the in list reference but doesn’t affect the • e[0] = 2 * e[0] does value stored in the list not reassign the reference • Thus L is unchanged • Thus L is updated 4

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend