ECS10 Counting heads Functions that return values List with length

Counting heads
What does exact distribution of number of flips
look like?
  Let’s make a graph, like we will do with
temperature.
  Run experiment 10K (10,000) times, make a
histogram of number of flips required.
 
ECS10
10/21
Functions that return values
List with length > r
def giveNum():
x=2
return x+2
>>> freq = [1]
>>> r = 3
>>> while len(freq) < r+1:
freq.append(0)
>>> freq
[1, 0, 0, 0]
y = giveNum()
Value of expression after return is stored into
variable y by assignment statement.
 Lots of functions return values – int(), input(),
randrange()….
 
Changing a list element
>>> L = [0,0,0]
>>> L[1] = 5
>>> L
[0,5,0]
Each list element is itself an individual variable
Can change contents of one without taking the others
out of the box
What if we start with freq = [3,4]?
What about freq = [5,2,3,6,8]?
Variable
 
Metaphor:
x = None
 
 
 
Reality: there is a space in computer memory that
program calls x.
1
Variable
 
Storing a lot of stuff
Metaphor:
 
Lots of boxes is messy.
x=2
2
 
Reality: the integer 2 is saved in memory, in the
location program calls x.
Organized memory
List organizes memory.
One name for whole filing
cabinet.
  Each drawer has a
number in the filing
cabinet.
  Modifying a list element
= opening one drawer,
replacing contents with
something else.
Jan = 31
Feb = 28
Mar = 31
Apr = 30
…
 
So are lots of variables.
Changing list element
freq[result] = freq[result]+1
 
 
Writing an output file
Need to open file
outFile = open(“histo.csv”,”w”)
  “w” means write
  write() method takes a SINGLE STRING as input
  To get lots of stuff into single string, concatenate
outFile.write(str(i)+”,”+str(freq[i])+”\n”)
  End text file lines with newline
 
Just like:
 
x = x+1
Take value out of drawer, do computation, put result
into drawer.
 
.csv file
Text file
Each line ends with newline character, “\n”
  Data items on line separated by commas
 
 
1888, -0.566
1889,-0.698
2
Visualize in Google Docs
3