Remove .md and image files and move python files into main chapter folders

This commit is contained in:
lolabird 2023-11-19 20:53:50 -07:00
commit 67806dab6a
159 changed files with 0 additions and 4562 deletions

View file

@ -1,534 +0,0 @@
# Exercises
I'm not sure I'm starting to get a better handle on this stuff or if they were giving me a break this chapter, but this chapter was not as challenging as the previous two, but it was just as fun! There were a couple of exercises that did throw me for a loop, but it was mostly smooth sailing!
Problem 3
---------
> Starting with the list of the previous exercise, write Python statements to do the following:
>
> 1. Append “apple” and 76 to the list.
> 2. Insert the value “cat” at position 3.
> 3. Insert the value 99 at the start of the list.
> 4. Find the index of “hello”.
> 5. Count the number of 76s in the list.
> 6. Remove the first occurrence of 76 from the list.
> 7. Remove True from the list using `pop` and `index`.
I'm including this one because I think the command chaining necessary for part g is cool.
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 10
# Problem 3
myList = [76, 92.3, 'hello', True, 4, 76]
# Your code here
myList += ["apple"]
myList.insert(3, "cat")
myList.insert(0, 99)
print(myList)
print(myList.index("hello"))
print(myList.count(76))
myList.remove(76)
myList.pop(myList.index(True))
print(myList)
```
Result:
![](Exercises/image.png)
Problem 11
----------
> Sum all the elements in a list up to but not including the first even number.
Up until now, the problems had been rather straightforward, but this one presented an interesting challenge. My first attempt included a while loop:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 10
# Problem 11
def sumUntilEven(lst):
# your code here
sumlist = 0
for num in lst:
while num % 2 != 0:
sumlist += num
return sumlist
mylist = [15, 85, 11, 20, 27, 38, 13]
print(sumUntilEven(mylist))
```
But then I realized that this created an infinite loop because I provided no way to exit  `while` loop. Then I tried this:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 10
# Problem 11
def sumUntilEven(lst):
# your code here
sumlist = 0
for num in lst:
if num % 2 != 0:
sumlist += num
else:
return sumlist
mylist = [15, 85, 11, 20, 27, 38, 13]
print(sumUntilEven(mylist))
```
My test worked, but I failed one of the built in tests, which was a list of _only_ odd numbers. And this was because I provided no return value for cases where the list contained only odd numbers. Once I added another return value, it was smooth sailing from there. Here's the final code and its results:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 10
# Problem 11
def sumUntilEven(lst):
# your code here
sumlist = 0
for num in lst:
if num % 2 != 0:
sumlist += num
else:
return sumlist
return sumlist
mylist = [15, 85, 11, 20, 27, 38, 13]
oddlist = [13, 11, 29, 37]
print(sumUntilEven(mylist))
print(sumUntilEven(oddlist))
```
Results:
![](Exercises/1_image.png)
Problem 12
----------
> Count how many words occur in a list up to and including the first occurrence of the word “sam”.
I'm including this simply because I thought it was an interesting problem.
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 10
# Problem 12
def count(lst):
# your code here
wordCount = 0
for item in lst:
if type(item) is str:
if item != "sam":
wordCount += 1
else:
wordCount += 1
return wordCount
return wordCount
myList = ["apple", 5, 6, True, "purple", False, "mushroom", 11, "gen-x", "sam", 7, 10, "cause", "interim"]
print(count(myList))
```
Result:
![](Exercises/2_image.png)
Problem 13
----------
> Although Python provides us with many list methods, it is good practice and very instructive to think about how they are implemented. Implement a Python function that works like the following:
>
> 1. count
> 2. in
> 3. reverse
> 4. index
> 5. insert
This one was fun. The more challenging ones to think about were `index` and `in`. I take those for granted when I'm coding and as you can probably tell, I use `in` _a lot_ when I'm doing something that requires traversing through a list of items. 
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 10
# Problem 13
def count(lst):
count = 0
for num in lst:
count += 1
return count
def findIn(item, lst):
pos = 0
inLst = False
while pos < len(lst) and not inLst:
if lst[pos] == item:
inLst = True
else:
pos += 1
return inLst
def reverse(lst):
newlist = []
for num in lst:
newlist = [num] + newlist
return newlist
def index(item, lst):
pos = 0
for num in lst:
if num == item:
return pos
else:
pos += 1
return "Item not found."
def insert(pos, item, lst):
newlst = lst[:pos] + [item] + lst[pos:]
return newlst
myList = ["apple", 5, 6, True, "purple", False, "mushroom", 11, "gen-x", "sam", 7, 10, "cause", "interim"]
print(count(myList))
print(findIn("purple", myList))
print(findIn(99, myList))
print(reverse(myList))
print(index(False, myList))
print(index("jello", myList))
print(insert(5, 7.89, myList))
```
Results:
![](Exercises/3_image.png)
Problem 14
----------
> Write a function `replace(s, old, new)` that replaces all occurences of `old` with `new` in a string `s`:
>
> ```text-plain
> test(replace('Mississippi', 'i', 'I'), 'MIssIssIppI')
>
> s = 'I love spom! Spom is my favorite food. Spom, spom, spom, yum!'
> test(replace(s, 'om', 'am'),
> 'I love spam! Spam is my favorite food. Spam, spam, spam, yum!')
>
> test(replace(s, 'o', 'a'),
> 'I lave spam! Spam is my favarite faad. Spam, spam, spam, yum!')
> ```
>
> _Hint_: use the `split` and `join` methods.
Okay… this one was a challenge. Here was the first iteration of my code:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 10
# Problem 14
def replace(s, old, new):
# your code here
for item in s:
if item == old:
newStr = s.split(old)
newStr = new.join(newStr)
return newStr
s = 'I love spom! Spom is my favorite food. Spom, spom, spom, yum!'
print(replace('Mississippi', 'i', 'I'))
print(replace(s, 'om', 'am'))
print(replace(s, 'o', 'a'))
```
I got an error because I didn't initialize the variable, `newStr`. So I added `newStr = ‘’` before the `for` loop. Here was the result:
![](Exercises/4_image.png)
My first solution worked better than I expected, but as you can see, there was a problem with the second test, and of course, this was missed by the built in checks. 
The error that was produced as a result of not initializing `newStr` wasn't actually about `newStr`. The real problem was that my loop was only looking for one character at a time and the second test gave me _two_ characters to search and replace. So of course the program would give me an initialization error. In that instance, I was asking it to return something that could not be created given the instructions I provided. 
This reminded me of the letter problems from the previous chapter, so I referenced those to figure out how I could replace any number of characters. This is what I came up with:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 10
# Problem 14
def replace(s, old, new):
# your code here
newStr = s
pos1 = 0
pos2 = len(old)
while pos1 < len(s):
item = newStr[pos1:pos2]
if item == old:
newStr = s.split(old)
newStr = new.join(newStr)
pos1 += 1
pos2 += 2
return newStr
s = 'I love spom! Spom is my favorite food. Spom, spom, spom, yum!'
print(replace('Mississippi', 'i', 'I'))
print(replace(s, 'om', 'am'))
print(replace(s, 'o', 'a'))
```
Results:
![](Exercises/5_image.png)
One step forward, two steps backward. The first test still worked, and the second one at least printed this time, but neither the second nor third test printed the expected results. 
Lawl… I really overcomplicated this. 🤦🏿‍♀️ Here is the final code:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 10
# Problem 14
def replace(s, old, new):
# your code here
newStr = s.split(old)
newStr = new.join(newStr)
return newStr
s = 'I love spom! Spom is my favorite food. Spom, spom, spom, yum!'
print(replace('Mississippi', 'i', 'I'))
print(replace(s, 'om', 'am'))
print(replace(s, 'o', 'a'))
```
Results:
![](Exercises/6_image.png)
Iteration is already built into `split` and `join`, so all that extra looping I did in the previous two solutions were unnecessary. Lesson learned… hopefully.
My problem is that I hadn't fully grasp how `split` and `join` were actually working. In my head, all the words were a different item in an array, when in reality, they were a part of a single string that was then split into different array items where any occurrence of `old` was found. Then those splits were “healed” with `new`. I was thinking like a human familiar with words and sentences rather than like a computer that would see the entire string provided as a single item until told otherwise. 
More L-Systems
--------------
### Problem 15
> Here are the rules for an L-system that creates something that resembles a common garden herb. Implement the following rules and try it. Use an angle of 25.7 degrees.
>
> ```text-plain
> H
> H --> HFX[+H][-H]
> X --> X[-FFF][+FFF]FX
> ```
Like last chapter, I really didn't have to change much. I just took existing code from the last chapter, changed the instructions in `applyRules`, changed `drawLsystem` to reflect what I learned in this chapter adjusted the angle and iterations and wallah, cool freaky pattern!
I did this one in my terminal though, because the book I'm using can only run so much. Anyway, here's the code and the result. And again, I'm leaving out the stuff that got pritned to the terminal, because it's just a long list of repeating numbers and letters. The image is more interesting. 
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 10
# Problem 15
import turtle
def createLSystem(numIters,axiom):
startString = axiom
endString = ""
for i in range(numIters):
endString = processString(startString)
startString = endString
return endString
def processString(oldStr):
newstr = ""
for ch in oldStr:
newstr = newstr + applyRules(ch)
return newstr
def applyRules(ch):
newstr = ""
if ch == 'H':
newstr = 'HFX[+H][-H]' # Rule 1
elif ch == 'X':
newstr = 'X[-FFF][+FFF]FX' # Rule 2
else:
newstr = ch # no rules apply so keep the character
return newstr
def drawLsystem(aTurtle, instructions, angle, distance):
savedInfoList = []
for cmd in instructions:
if cmd == 'F':
aTurtle.forward(distance)
elif cmd == 'B':
aTurtle.backward(distance)
elif cmd == '+':
aTurtle.right(angle)
elif cmd == '-':
aTurtle.left(angle)
elif cmd == '[':
savedInfoList.append([aTurtle.heading(), aTurtle.xcor(), aTurtle.ycor()])
print(savedInfoList)
elif cmd == ']':
newInfo = savedInfoList.pop()
aTurtle.setheading(newInfo[0])
aTurtle.setposition(newInfo[1], newInfo[2])
def main():
inst = createLSystem(6, "H") # create the string
print(inst)
t = turtle.Turtle() # create the turtle
wn = turtle.Screen()
wn.tracer(10)
t.up()
t.back(200)
t.down()
t.speed(0)
drawLsystem(t, inst, 25.7, 5) # draw the picture
# angle 2, segment length 5
wn.exitonclick()
main()
```
![](Exercises/7_image.png)
### Problem 16
> Here is another L-System. Use an Angle of 25.
>
> ```text-plain
> F
> F --> F[-F]F[+F]F
> ```
Same deal as problem 15 but prettier.
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 10
# Problem 16
import turtle
def createLSystem(numIters,axiom):
startString = axiom
endString = ""
for i in range(numIters):
endString = processString(startString)
startString = endString
return endString
def processString(oldStr):
newstr = ""
for ch in oldStr:
newstr = newstr + applyRules(ch)
return newstr
def applyRules(ch):
newstr = ""
if ch == 'F':
newstr = 'F[-F]F[+F]F' # Rule 1
else:
newstr = ch # no rules apply so keep the character
return newstr
def drawLsystem(aTurtle, instructions, angle, distance):
savedInfoList = []
for cmd in instructions:
if cmd == 'F':
aTurtle.forward(distance)
elif cmd == 'B':
aTurtle.backward(distance)
elif cmd == '+':
aTurtle.right(angle)
elif cmd == '-':
aTurtle.left(angle)
elif cmd == '[':
savedInfoList.append([aTurtle.heading(), aTurtle.xcor(), aTurtle.ycor()])
print(savedInfoList)
elif cmd == ']':
newInfo = savedInfoList.pop()
aTurtle.setheading(newInfo[0])
aTurtle.setposition(newInfo[1], newInfo[2])
def main():
inst = createLSystem(5, "F") # create the string
print(inst)
t = turtle.Turtle() # create the turtle
wn = turtle.Screen()
wn.tracer(10)
t.up()
t.back(600)
t.down()
t.speed(0)
drawLsystem(t, inst, 25, 5) # draw the picture
# angle 25, segment length 5
wn.exitonclick()
main()
```
Result:
![](Exercises/8_image.png)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

View file

@ -1,481 +0,0 @@
# Exercises
This lesson only had five problems, and thank goodness for that, because problem 4 really threw me for a loop. I've included all 5 here, because there are so few problems and because I genuinely found them all to be interesting problems. 
Also, I kept getting tripped up with how I interpreted the numbers from the files vs how Python interpreted them. Because they were coming from a file, those numbers were interpreted as strings, not numbers. You'd think that after my first encounter with this, I'd understand that, but I was literally still struggling with that on problem 5 lol. 
Anyway, enough talk. Let's go through the exercises. 
Student Data
------------
The following three questions uses the following file as a reference:
![](Exercises/image.png)
### Problem 1
> The following sample file called `studentdata.txt` contains one line for each student in an imaginary class. The student’s name is the first thing on each line, followed by some exam scores. The number of scores might be different for each student.
>
> \[studentdata.txt\]
>
> Using the text file `studentdata.txt` write a program that prints out the names of students that have more than six quiz scores.
My solution:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 11
# Problem 1
sdfile = open("studentdata.txt", "r")
for line in sdfile:
student = line.split()
if len(student[1:]) > 6:
print(student[0])
sdfile.close()
```
Result:
![](Exercises/1_image.png)
### Problem 2
> Using the text file `studentdata.txt` (shown in exercise 1) write a program that calculates the average grade for each student, and print out the student’s name along with their average grade.
My solution:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 11
# Problem 2
sdfile = open("studentdata.txt", "r")
for line in sdfile:
student = line.split()
sum = 0
avg = 0
count = len(student[1:])
for grade in student:
if grade != student[0]:
sum += int(grade)
avg = sum/count
print(student[0], "-", avg)
sdfile.close()
```
Result:
![](Exercises/2_image.png)
### Problem 3
> Using the text file `studentdata.txt` (shown in exercise 1) write a program that calculates the minimum and maximum score for each student. Print out their name as well.
My first attempt at this problem, did not get the right results, even though my logic was right. The issue was that I needed to convert the grades from strings to numbers before comparing them. Once I figured that out, everything was gucci. Here's the final code:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 11
# Problem 3
sdfile = open("studentdata.txt", "r")
for line in sdfile:
student = line.split()
mingrade = student[1]
maxgrade = student[1]
for grade in student:
if grade != student[0]:
if int(grade) < int(mingrade):
mingrade = grade
if int(grade) > int(maxgrade):
maxgrade = grade
outputText = "{} - minimum score:{}; maximum score:{}".format(student[0], mingrade, maxgrade)
print(outputText)
sdfile.close()
```
Result:
![](Exercises/3_image.png)
Problem 4
---------
> Here is a file called `labdata.txt` that contains some sample data from a lab experiment.
>
> ![](Exercises/5_image.png)
>
> Interpret the data file `labdata.txt` such that each line contains a an x,y coordinate pair. Write a function called `plotRegression` that reads the data from this file and uses a turtle to plot those points and a best fit line according to the following formulas:
>
> \\(y = \\bar{y} + m(x - \\bar{x})\\)
>
> \\(m = \\frac{\\sum{x\_iy\_i - n\\bar{x}\\bar{y}}}{\\sum{x\_i^2}-n\\bar{x}^2}\\)
>
> where \\(\\bar{x}\\) is the mean of the x-values, \\(\\bar{y}\\) is the mean of the y- values and is the number of points. If you are not familiar with the mathematical \\(\\sum\\) it is the sum operation. For example \\(\\sum{x\_i}\\) means to add up all the x values.
>
> Your program should analyze the points and correctly scale the window using `setworldcoordinates` so that that each point can be plotted. Then you should draw the best fit line, in a different color, through the points.
Mkay… this one was kind of a pain in the ass, from formatting the instructions above, to refreshing myself on how sums worked, to actually structuring the solution. But I got through it. 
First attempt:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 11
# Problem 4
import turtle
with open('labdata.txt') as lab:
def plotRegression():
sumx = 0
sumy = 0
sumxy = 0
sumxsq = 0
count = 0
meanx = 0
meany = 0
'''this is basically a normal linear line except with average values'''
for line in lab:
x = int(line[0])
y = int(line[1])
sumx += x
sumy += y
sumxy += x*y
sumxsq += x**2
count += 1
meanx = sumx/count
meany = sumy/count
#meanxsq = meanx**2
slope = (sumxy - (count*meanx*meany))/(sumxsq - (count*meanx**2)) #m
for line in lab:
plot = meany + slope(line[0] - meanx) #y
plotTurtle(line[0], line[1], plot)
def plotTurtle(x, y, plot):
wn = turtle.Screen()
ella = turtle.Turtle() #points from the labdata.txt
#maya = turtle.Turtle() #line of best fit (y)
ella.up()
ella.goto(x,y)
ella.down()
ella.stamp()
ella.up()
wn.exitonclick()
plotRegression()
```
I forgot to split each line, so of course I was getting an error. 
Next, needed to figure out accurately getting the values needed for the equations.
I ended up separating the calculation of slope from the calculation of the regression line into two separate functions decided to send the list of x and y values, the mean x and y, and the slope through as parameters to the `plotRegression` function. 
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 11
# Problem 4
import turtle
def slope():
xlist = []
ylist = []
sumx = 0
sumy = 0
sumxy = 0
sumxsq = 0
count = 0 #n
meanx = 0
meany = 0
slope = 0 #m
with open('labdata.txt') as lab:
for line in lab:
values = line.split()
xlist += [int(values[0])]
ylist += [int(values[1])]
x = int(values[0])
y = int(values[1])
sumx += x
sumy += y
sumxy += x*y
sumxsq += x**2
count += 1
meanx = sumx / count
meany = sumy / count
slope = (sumxy - count*meanx*meany) / (sumxsq - count*meanx**2)
plotRegression(xlist, ylist, meanx, meany, slope)
def plotRegression(xlist, ylist, meanx, meany, slope):
for x in xlist:
yplot = meany + slope*(x - meanx)
plotTurtle(x, yplot)
def plotTurtle(x, y):
wn = turtle.Screen()
ella = turtle.Turtle() #points from the labdata.txt
#maya = turtle.Turtle() #line of best fit (y)
ella.up()
ella.goto(x,y)
ella.down()
ella.stamp()
ella.up()
wn.exitonclick()
slope()
```
This helped clean up the code a bit, but I still had the issue of exactly how I was going to plot the line and the x and y value pairs at the same time. I knew that I couldn't just do a simple nested loop. That would result in one of those values being referenced too many times. I needed to find a way to go through both `xlist` and `ylist` at the same time.
So I didn't need a _simple_ nested loop, but I _did_ need a nested loop. What I figured out was that I needed two new variables: one to use as a binary and another to use an index for one of the lists. 
The binary variable was there to keep the value from the first list from being repeated and the index was there to make sure the right value from the second list was being sent to `plotTurtle`. This is what `plotRegression` ended up looking like once I figured that out:
```text-x-python
def plotRegression(xlist, ylist, meanx, meany, slope):
i = 0
for x in xlist:
j = 0
yplot = meany + slope*(x - meanx)
while not j:
plotTurtle(x, ylist[i], yplot)
j += 1
i += 1
```
Now I needed to figure out getting my turtles to draw a line from `yplot` rather than just a series of points. 
Because of the way I was feeding points to `plotTurtle`, the turtles would go back to their starting point, before going back to their respective, (x,y) positions. This is fine for the turtle plotting the original x and y value pairs, but not fine for the turtle plotting the line of best fit. I needed to make sure that the second turtle stayed where it was when it got fed the next plot point.
Turns out the solution to making it stay where it was, was just to have the turtles in the the same function where `yplot` was being calculated. Now all that was left was to get the world coordinates to scale (and change up the colors, just because).
Here's te final code:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 11
# Problem 4
import turtle
def slope():
xlist = []
ylist = []
sumx = 0
sumy = 0
sumxy = 0
sumxsq = 0
count = 0 #n
meanx = 0
meany = 0
slope = 0 #m
with open('labdata.txt') as lab:
for line in lab:
values = line.split()
xlist += [int(values[0])]
ylist += [int(values[1])]
x = int(values[0])
y = int(values[1])
sumx += x
sumy += y
sumxy += x*y
sumxsq += x**2
count += 1
meanx = sumx / count
meany = sumy / count
slope = (sumxy - count*meanx*meany) / (sumxsq - count*meanx**2)
plotRegression(xlist, ylist, meanx, meany, slope)
def plotRegression(xlist, ylist, meanx, meany, slope):
#set world coordinates
minx = xlist[0]
miny = ylist[0]
maxx = xlist[0]
maxy = ylist[0]
count = len(xlist)
num = 0
while num < count:
if xlist[num] < minx:
minx = xlist[num]
if xlist[num] > maxx:
maxx = xlist[num]
if ylist[num] < miny:
miny = ylist[num]
if ylist[num] > maxy:
maxy = ylist[num]
num += 1
turtle.setworldcoordinates(minx-10, miny-10, maxx+10, maxy+10)
#plot points
i = 0
wn = turtle.Screen()
wn.bgcolor("#222")
ella = turtle.Turtle() #points from the labdata.txt
ella.color("pink")
maya = turtle.Turtle() #line of best fit (yplot)
maya.color("lightblue")
for x in xlist:
j = 0
yplot = meany + slope*(x - meanx)
while not j:
ella.up()
ella.goto(x, ylist[i])
ella.dot()
if i != 0:
maya.goto(x, yplot)
else:
maya.up()
maya.goto(x, yplot)
maya.down()
j += 1
i += 1
wn.exitonclick()
slope()
```
Result:
![](Exercises/4_image.png)
Problem 5
---------
> At the bottom of this page is a very long file called `mystery.txt` The lines of this file contain either the word UP or DOWN or a pair of numbers. UP and DOWN are instructions for a turtle to lift up or put down its tail. The pairs of numbers are some x,y coordinates. Write a program that reads the file `mystery.txt` and uses the turtle to draw the picture described by the commands and the set of points.
It's long, so I'll just link to the data in `mystery.txt` [here](Exercises/mystery.txt.md). 
Drawing the image was relatively straightforward. It was getting the world coordinates that was challenging, even though I literally just did the same thing in the previous problem. 
The challenge was that this time, just splitting the data into x and y coordinates was not that simple. I now had to contend with strings `“UP”` and `“DOWN”`, as well. 
What also threw me for a loop was that the program was expecting me to initialize the min/max variables before what I thought of as the actual initialization (assigning the variables to the first numbers in the file). My guess is that I had to go through this extra step, because unlike in the previous problem, I was pulling the numbers directly from the file instead of an array. 
Anywho, here's my solution:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 11
# Problem 5
import turtle
def getMinMax():
#get world coordinates
minx = 0
miny = 0
maxx = 0
maxy = 0
with open('mystery.txt') as data:
for line in data:
values = line.split()
if values[0] != "UP" and values[0] != "DOWN":
minx = int(values[0])
miny = int(values[1])
maxx = int(values[0])
maxy = int(values[1])
break
for line in data:
values = line.split()
if values[0] != "UP" and values[0] != "DOWN":
if int(values[0]) < minx:
minx = int(values[0])
if int(values[0]) > maxx:
maxx = int(values[0])
if int(values[1]) < miny:
miny = int(values[1])
if int(values[1]) > maxy:
maxy = int(values[1])
draw(minx, miny, maxx, maxy)
def draw(minx, miny, maxx, maxy):
turtle.setworldcoordinates(minx-10, miny-10, maxx+10, maxy+10)
wn = turtle.Screen()
wn.bgcolor("#e0e0e0")
ella = turtle.Turtle()
ella.color("brown")
with open('mystery.txt') as data:
for line in data:
values = line.split()
if values[0] == "UP":
ella.up()
elif values[0] == "DOWN":
ella.down()
else:
x = int(values[0])
y = int(values[1])
ella.goto(x,y)
getMinMax()
```
Result:
![](Exercises/6_image.png)
It's a dinosaur!
And here's a gif of Python actually generating the image from the instructions. Figured that'd be more interesting than a static image:
![](Exercises/mystery-2023-10-27_15.00.35.gif)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 238 KiB

View file

@ -1,409 +0,0 @@
# mystery.txt
```text-plain
UP
-218 185
DOWN
-240 189
-246 188
-248 183
-246 178
-244 175
-240 170
-235 166
-229 163
-220 158
-208 156
-203 153
-194 148
-187 141
-179 133
-171 119
-166 106
-163 87
-161 66
-162 52
-164 44
-167 28
-171 6
-172 -15
-171 -30
-165 -46
-156 -60
-152 -67
-152 -68
UP
-134 -61
DOWN
-145 -66
-152 -78
-152 -94
-157 -109
-157 -118
-151 -128
-146 -135
-146 -136
UP
-97 -134
DOWN
-98 -138
-97 -143
-96 -157
-96 -169
-98 -183
-104 -194
-110 -203
-114 -211
-117 -220
-120 -233
-122 -243
-123 -247
-157 -248
-157 -240
-154 -234
-154 -230
-153 -229
-149 -226
-146 -223
-145 -219
-143 -214
-142 -210
-141 -203
-139 -199
-136 -192
-132 -184
-130 -179
-132 -171
-133 -162
-134 -153
-138 -145
-143 -137
-143 -132
-142 -124
-138 -112
-134 -104
-132 -102
UP
-97 -155
DOWN
-92 -151
-91 -147
-89 -142
-89 -135
-90 -129
-90 -128
UP
-94 -170
DOWN
-83 -171
-68 -174
-47 -177
-30 -172
-15 -171
-11 -170
UP
12 -96
DOWN
9 -109
9 -127
7 -140
5 -157
9 -164
22 -176
37 -204
40 -209
49 -220
55 -229
57 -235
57 -238
50 -239
49 -241
51 -248
53 -249
63 -245
70 -243
57 -249
62 -250
71 -250
75 -250
81 -250
86 -248
86 -242
84 -232
85 -226
81 -221
77 -211
73 -205
67 -196
62 -187
58 -180
51 -171
47 -164
46 -153
50 -141
53 -130
54 -124
57 -112
56 -102
55 -98
UP
48 -164
DOWN
54 -158
60 -146
64 -136
64 -131
UP
5 -152
DOWN
1 -150
-4 -145
-8 -138
-14 -128
-19 -119
-17 -124
UP
21 -177
DOWN
14 -176
7 -174
-6 -174
-14 -170
-19 -166
-20 -164
UP
-8 -173
DOWN
-8 -180
-5 -189
-4 -201
-2 -211
-1 -220
-2 -231
-5 -238
-8 -241
-9 -244
-7 -249
6 -247
9 -248
16 -247
21 -246
24 -241
27 -234
27 -226
27 -219
27 -209
27 -202
28 -193
28 -188
28 -184
UP
-60 -177
DOWN
-59 -186
-57 -199
-56 -211
-59 -225
-61 -233
-65 -243
-66 -245
-73 -246
-81 -246
-84 -246
-91 -245
-91 -244
-88 -231
-87 -225
-85 -218
-85 -211
-85 -203
-85 -193
-88 -185
-89 -180
-91 -175
-92 -172
-93 -170
UP
-154 -93
DOWN
-157 -87
-162 -74
-168 -66
-172 -57
-175 -49
-178 -38
-178 -26
-178 -12
-177 4
-175 17
-172 27
-168 36
-161 48
-161 50
UP
-217 178
DOWN
-217 178
-217 177
-215 176
-214 175
-220 177
-223 178
-223 178
-222 178
UP
-248 185
DOWN
-245 184
-240 182
-237 181
-234 179
-231 177
-229 176
-228 175
-226 174
-224 173
-223 173
-220 172
-217 172
-216 171
-214 170
-214 169
UP
-218 186
DOWN
-195 173
-183 165
-175 159
-164 151
-158 145
-152 139
-145 128
-143 122
-139 112
-138 105
-134 95
-131 88
-129 78
-126 67
-125 62
-125 54
-124 44
-125 38
-126 30
-125 27
-125 8
-126 5
-125 -9
-122 -15
-115 -25
-109 -32
-103 -39
-95 -42
-84 -45
-72 -47
-56 -48
-41 -47
-31 -46
-18 -45
-1 -44
9 -43
34 -45
50 -52
67 -61
83 -68
95 -80
112 -97
142 -115
180 -132
200 -146
227 -159
259 -175
289 -185
317 -189
349 -190
375 -191
385 -192
382 -196
366 -199
352 -204
343 -204
330 -205
315 -209
296 -212
276 -214
252 -208
237 -202
218 -197
202 -193
184 -187
164 -179
147 -173
128 -168
116 -164
102 -160
88 -158
78 -159
69 -162
57 -164
56 -165
51 -165
UP
68 -144
DOWN
83 -143
96 -141
109 -139
119 -146
141 -150
161 -155
181 -163
195 -169
208 -179
223 -187
241 -191
247 -193
249 -194
UP
-6 -141
DOWN
-15 -146
-29 -150
-42 -154
-51 -153
-60 -152
-60 -152
UP
-90 -134
DOWN
-85 -131
-79 -128
-78 -123
-80 -115
-82 -106
-80 -101
-76 -101
UP
-81 -132
DOWN
-76 -130
-71 -126
-72 -124
UP
43 -118
DOWN
44 -125
47 -135
41 -156
37 -160
40 -166
47 -171
47 -171
UP
-106 -153
DOWN
-107 -167
-106 -178
-109 -192
-114 -198
-116 -201
```

View file

@ -1,193 +0,0 @@
Problem 3
---------
_Many people keep time using a 24 hour clock (11 is 11am and 23 is 11pm, 0 is midnight). If it is currently 13 and you set your alarm to go off in 50 hours, it will be 15 (3pm). Write a Python program to solve the general version of the above problem. Ask the user for the time now (in hours), and then ask for the number of hours to wait for the alarm. Your program should output what the time will be on the clock when the alarm goes off._
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 2
# Problem 3
currentTime = input('What time is it?')
currentTime = int(currentTime)
waitTime = input('In how many hours do you need to wake up?')
waitTime = int(waitTime)
print('It is currently', currentTime,'.')
print('You need to wake up in', waitTime, 'hours.')
# My solution was more long winded than the actual answer, but it still works!
totalTime = currentTime + waitTime
time24hr = totalTime // 24
alarmTime = totalTime - 24 * time24hr
print('The alarm has been set for', alarmTime, '.')
```
Problem 4
---------
_It is possible to name the days 0 through 6 where day 0 is Sunday and day 6 is Saturday. If you go on a wonderful holiday leaving on day number 3 (a Wednesday) and you return home after 10 nights you would return home on a Saturday (day 6) Write a general version of the program which asks for the starting day number, and the length of your stay, and it will tell you the number of day of the week you will return on._
```text-x-python
#Runestone.Academy thinkcspy course
# Chapter 2
# Problem 4
currentDay = input('''Enter the current day using one of the following numbers:
Sunday = 0
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6''')
currentDay = int(currentDay)
stayLength = input('How long is your stay?')
stayLength = int(stayLength)
# Improved upon the long windedness of my answer this time by following the example of the solution
# in the previous problem
stay = currentDay + stayLength
returnDay = stay % 7
print('It is currently Day', currentDay,'.')
print('Your stay is ', stayLength, 'days long.')
print('You will return on Day', returnDay, '.')
print('''Sunday = 0
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6''')
```
Problem 7
---------
_The formula for computing the final amount if one is earning compound interest is given on Wikipedia as_
_![formula for compound interest](api/images/9sYRfd0tfbOC/compoundInterest.png)_
_Write a Python program that assigns the principal amount of 10000 to variable P, assign to n the value 12, and assign to r the interest rate of 8% (0.08). Then have the program prompt the user for the number of years, t, that the money will be compounded for. Calculate and print the final amount after t years._
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 2
# Problem 7
P = 10000
n = 12
r = 0.08
n = 12
# Noticed that they gave separate variables to the inputs problem 3 and
# the converted ints so decided to do the same here.
t_string = input('For how many years will your principal be earning interest?')
t = int(t_string)
A = P*(1+r/n)**(n*t)
print('The final amount after you will earn after', t, 'years is', A)
```
Problem 8
---------
_Write a program that will compute the area of a circle. Prompt the user to enter the radius and print a nice message back to the user with the answer._
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 2
# Problem 8
r_string = input('Enter the radius of the circle')
r = int(r_string)
pi = 3.14
area = pi * r**2
print('The approximate area of the circle with', r, 'radius is', area, '.')
```
Problem 9
---------
_Write a program that will compute the area of a rectangle. Prompt the user to enter the width and height of the rectangle. Print a nice message with the answer._
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 2
# Problem 9
width = input('What is the width of the rectangle?')
w = int(width)
height = input('What is the height of the rectangle?')
h = int(height)
area = w*h
print('The area of the rectangle with a width of', w, 'and a height of', h, 'is', area, '.')
```
Problem 10
----------
_Write a program that will compute MPG for a car. Prompt the user to enter the number of miles driven and the number of gallons used. Print a nice message with the answer._
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 2
# Problem 10
miles = input('How many miles did you drive before refueling?')
mi = int(miles)
gallons = input('How many gallons did you use to refuel your vehicle?')
gal = int(gallons)
mpg = mi / gal
print('Your fuel efficiency is', mpg, 'MPG.')
```
Problem 11
----------
_Write a program that will convert degrees celsius to degrees fahrenheit._
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 2
# Problem 11
celcius = input('What is the temperature in degrees celsius?')
C = int(celcius)
F = (C * 9/5) + 32
print(C, 'degrees celcius is equivalent to', F, 'degrees fahrenheit.')
```
Problem 12
----------
_Write a program that will convert degrees fahrenheit to degrees celsius._
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 2
# Problem 12
fahrenheit = input('What is the temperature in degrees fahrenheit?')
F = int(fahrenheit)
C = (F - 32) * 5/9
print(F, 'degrees fahrenheit is equivalent to', C, 'degrees celcius.')
```

View file

@ -1,256 +0,0 @@
# Exercises
This lesson had a bunch of exercises in it, but I just picked a few that best showcased what I learned which was mostly about using `for` loops and the `Turtle()` object. 
Problem 4
---------
_Assume you have a list of numbers_ `12, 10, 32, 3, 66, 17, 42, 99, 20`
1. _Write a loop that prints each of the numbers on a new line._
2. _Write a loop that prints each number and its square on a new line._
### My code
This one had a visual counterpart, but that would require me including a video which is something I'm simply not keen on doing, right now. So here are some text and numbers instead.
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 4
# Problem 4
for i in [12, 10, 32, 3, 66, 17, 42, 99, 20]:
print(i)
for i in [12, 10, 32, 3, 66, 17, 42, 99, 20]:
print("The square of", i,"is", i**2)
```
### Result
![](Exercises/4_image.png)
Problem 5
---------
_Use_ `for` _loops to make a turtle draw these regular polygons (regular means all sides the same lengths, all angles the same):_
* _An equilateral triangle_
* _A square_
* _A hexagon (six sides)_
* _An octagon (eight sides)_
### My code:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 4
# Problem 5
import turtle
wn = turtle.Screen()
avery = turtle.Turtle()
avery.color("blue")
dun = turtle.Turtle()
dun.color("pink")
elliot = turtle.Turtle()
elliot.color("lime")
missy = turtle.Turtle()
missy.color("yellow")
for i in range(3):
avery.forward(50)
avery.left(120)
for i in range(4):
dun.backward(70)
dun.left(90)
for i in range(6):
elliot.left(60)
elliot.forward(40)
for i in range(8):
missy.right(45)
missy.backward(80)
wn.exitonclick()
```
### Result:
![](Exercises/image.png)
Problem 9
---------
_Write a program to draw a shape like this:_
_![../_images/star1.png](Exercises/star1.png)_
### My Code:
I probably need to go back to and relearn geometry lol. Took me forever to figure out the right angle. 
In case you're curious (and not a geometry wiz), to draw any type of star you need the formula \\(a = 180 - 360/(n/2)\\) or more simply \\(a=180-180/n\\), where \\(a\\) is the angle and \\(n\\) is the number of sides. Now, I'll do my best to explain why this works.
To find the angle of a normal polygon, you need to divide 360 by the number of sides, which would be expressed as \\(a=360/n\\). But a star is like an inverted form of a polygon that has bunch of unfinished interconnecting triangles. Unlike polygons with 4+ sides, all the angles of a triangle must equal 180 — and coincidentally, that happens to be the case with stars as well. Don't ask me why, I don't know. It's been well over a decade since I've had to touch do any geometry like this lol. 
If you look closely at the center of the star presented above, you'll notice a pentagon in the center. Extending from every angle of that pentagon are triangles. Again, we know that the angles of triangles must total of 180 and we also know that each angle in the star is the same, so we can treat these triangles as equilateral triangles. This means that each angle of the arms will be half the angle its polygon counterpart, hence the \\(360/(n/2)\\), where the \\(2\\) is simply halving each angle of the original polygon.
Now, if we were just trying to find the acute angle present in the star, we could stop here, but at least for the way I drew my star, I actually need an obtuse angle, because the program is tracing around and through the star. This is where the \\(180\\) comes in. I need to subtract the acute angle from \\(180\\) to get to the angle I need to create the star. You can actually see this angle in the concave portions of the star. 
So all that is how I got to \\(a = 180 - 360/(n/2)\\). I probably could have looked this up — and I did partially, which is how I understood to treat the star like a triangle — but otherwise I just played around with it until I figured it out. 
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 4
# Problem 9
import turtle
wn = turtle.Screen()
stella = turtle.Turtle()
stella.color("yellow")
stella.up()
stella.forward(-50)
stella.down()
for i in range(5):
stella.left(144)
stella.forward(-100)
wn.exitonclick()
```
### Result
![](Exercises/1_image.png)
Problem 10
----------
_Write a program to draw a face of a clock that looks something like this:_
_![../_images/tess_clock1.png](Exercises/tess_clock1.png)_
### My Code:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 4
# Problem 10
import turtle
wn = turtle.Screen()
wn.bgcolor("lightgreen")
stella = turtle.Turtle()
stella.color("blue")
stella.shape("turtle")
avery = turtle.Turtle()
avery.color("blue")
stella.up()
avery.up()
stella.stamp()
for i in range(12):
stella.forward(100)
stella.stamp()
avery.forward(70)
avery.down()
avery.forward(10)
avery.up()
stella.forward(-100)
avery.forward(-80)
stella.right(30)
avery.right(30)
wn.exitonclick()
```
### Result
![](Exercises/2_image.png)
Problem 11
----------
_Write a program to draw some kind of picture. Be creative and experiment with the turtle methods provided in Summary of Turtle Methods._
### My Code
Used what I learned from problem 9 on this one. Even took the time to figure out getting the star to fit inside its corresponding polygon. Then I made a weird spiral thingy and was like “ooh that looks like a huge ponytail!”and then I made a crown. That one took me forever to figure out too, but I don't really have a rationale for you for this one. 
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 4
# Problem 11
import turtle
wn = turtle.Screen()
wn.bgcolor("black")
stella = turtle.Turtle()
stella.color("lightblue")
stella.speed(10)
avery = turtle.Turtle()
avery.color("purple")
avery.speed(10)
avery.up()
avery.right(90)
avery.down()
missy = turtle.Turtle()
missy.color("purple")
missy.speed(10)
missy.up()
missy.left(90)
missy.down()
dun = turtle.Turtle()
dun.color("gold")
dun.speed(10)
dun.up()
dun.left(90)
dun.forward(30)
dun.right(90)
dun.down()
for i in range(8):
stella.left(135)
stella.forward(-120)
avery.right(45)
avery.forward(-50)
for i in range(30, -32, -1):
missy.forward(i)
missy.left(20)
dun.forward(120)
dun.left(120)
dun.forward(70)
for i in range(2):
dun.left(120)
dun.forward(30)
dun.right(120)
dun.forward(30)
dun.left(120)
dun.forward(70)
wn.exitonclick()
```
### Result
![](Exercises/3_image.png)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7 KiB

View file

@ -1,111 +0,0 @@
# Exercises
So this lesson only had 4 exercises (from what I could see, anyway), but for some reason they start at 16. 
At any rate, this lesson was about modules. `math` and `random` were at the focus of the lesson and its exercises. 
Problem 16
----------
_Use a_ `for` _statement to print 10 random numbers._
### My Code
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 5
# Problem 16
import random
for i in range(10):
prob = random.random()
print(i+1, '-', prob)
```
### Result
![](Exercises/image.png)
Result from the first run of this script
Problem 17
----------
_Repeat the above exercise but this time print 10 random numbers between 25 and 35, inclusive._
### My Code
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 5
# Problem 17
import random
for i in range(10):
prob = random.randrange(25, 36)
print(i+1, '-', prob)
```
### Result
![](Exercises/1_image.png)
Result from the first run of this script
Problem 18
----------
_The **Pythagorean Theorem** tells us that the length of the hypotenuse of a right triangle is related to the lengths of the other two sides. Look through the_ `math` _module and see if you can find a function that will compute this relationship for you. Once you find it, write a short program to try it out._
### My Code
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 5
# Problem 18
import math
a = float(input('What is the length of the first side of the triangle?'))
b = float(input('What is the length of the second side of the triangle?'))
c = math.sqrt(a*a + b*b)
print('The hypotenuse of this triangle with is', c, '.')
```
### Result
![](Exercises/2_image.png)
The numbers used to get this result were 12 and 12.
Problem 19
----------
_Search on the internet for a way to calculate an approximation for **pi**. There are many that use simple arithmetic. Write a program to compute the approximation and then print that value as well as the value of_ `math.pi` _from the math module._
### My Code
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 5
# Problem 19
import math
c = float(input("Today we are going to calculate pi from the dimensions of a circle. What is the circumference of your circle?"))
d = float(input("And what is the diameter of your circle?"))
zpi = c/d
print("The approximate value of pi from the dimensions provided is", zpi)
print("The actual (also technically approximate) value of pi is", math.pi)
```
### Result
![](Exercises/3_image.png)
The numbers were 22.2817 for the diameter and 70 for the circumference. The numbers were generated on [this site](https://www.omnicalculator.com/math/circle-measurements).

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

View file

@ -1,43 +0,0 @@
# Lab: Plotting a Sine Wave
Create and set up the turtle and the screen.
Iterate the angle from 0 to 360.
> Generate the sine value for each angle.
>
> Move the turtle to that position (leave a line behind).
_My note: the lab encouraged us to try other functions out, so I included a turtle drawing cosign._
```text-x-python
import math
import turtle
wn = turtle.Screen()
wn.bgcolor('lightblue')
turtle.setworldcoordinates(0, -1.25, 360, 1.25)
fred = turtle.Turtle()
fred.speed(10)
fred.color('red')
george = turtle.Turtle()
george.speed(10)
george.color('blue')
for angle in range(361):
x = angle
y = math.sin(math.radians(angle))
fred.goto(x,y)
for angle in range(361):
x = angle
y = math.cos(math.radians(angle))
george.goto(x,y)
wn.exitonclick()
```
![](Lab/image.png)

View file

@ -1,652 +0,0 @@
# Exercises
Problem 1
---------
> Use the drawsquare function we wrote in this chapter in a program to draw the image shown below. Assume each side is 20 units. (Hint: notice that the turtle has already moved away from the ending point of the last square when the program ends.)
>
> ![../_images/five_squares.png](Exercises/five_squares.png)
Most of this code was already added. The only things I added were the pensize and the `drawManySquares` function and call.
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 6
# Problem 1
import turtle
def drawSquare(t, sz):
"""Get turtle t to draw a square of sz side"""
for i in range(4):
t.forward(sz)
t.left(90)
wn = turtle.Screen()
wn.bgcolor("lightgreen")
alex = turtle.Turtle()
alex.color("pink")
alex.pensize(2)
def drawManySquares(tt, num):
for i in range(num):
drawSquare(tt, 20)
tt.up()
tt.forward(30)
tt.down()
drawManySquares(alex, 5)
wn.exitonclick()
```
Result
![](Exercises/image.png)
Problem 2
---------
> Write a program to draw this. Assume the innermost square is 20 units per side, and each successive square is 20 units bigger, per side, than the one inside it.
>
> ![../_images/nested_squares.png](Exercises/nested_squares.png)
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 6
# Problem 2
import turtle
def drawSquare(t, sz):
"""Get turtle t to draw a square of sz side"""
for i in range(4):
t.forward(sz)
t.left(90)
wn = turtle.Screen()
wn.bgcolor("lightgreen")
alex = turtle.Turtle()
alex.color("pink")
alex.pensize(2)
def drawStackedSquares(tt, num):
for i in range(num):
drawSquare(tt, 20*(i+1))
tt.up()
tt.backward(10)
tt.left(90)
tt.backward(10)
tt.right(90)
tt.down()
drawStackedSquares(alex, 5)
wn.exitonclick()
```
Result:
![](Exercises/1_image.png)
Problem 3
---------
> Write a non-fruitful function `drawPoly(someturtle, somesides, somesize)` which makes a turtle draw a regular polygon. When called with `drawPoly(tess, 8, 50)`, it will draw a shape like this:
>
> ![../_images/regularpolygon.png](Exercises/regularpolygon.png)
Lol… I realized I didn't fully read the instructions and didn't name the parameters or the function the way they wanted me to, but… the result is the same so, I think I did my job. 
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 6
# Problem 3
import turtle
def drawPolygon(t, sideLength, numSides):
"""Make turtle t draw a polygon."""
angle = 360/numSides
for i in range(numSides):
t.forward(sideLength)
t.left(angle)
wn = turtle.Screen()
wn.bgcolor("lightgreen")
tess = turtle.Turtle()
tess.color("pink")
tess.pensize(2)
drawPolygon(tess,50,8)
wn.exitonclick()
```
Result:
![](Exercises/2_image.png)
Problem 4
---------
> Draw this pretty pattern.
>
> ![../_images/tess08.png](Exercises/tess08.png)
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 6
# Problem 4
import turtle
def drawSquare(t, sz):
"""Get turtle t to draw a square of sz side"""
for i in range(4):
t.forward(sz)
t.left(90)
wn = turtle.Screen()
wn.bgcolor("lightgreen")
alex = turtle.Turtle()
alex.color("blue")
alex.pensize(2)
alex.speed(10)
def drawCircleSquares(tt, num):
for i in range(num):
drawSquare(tt, 80)
tt.right(15)
drawCircleSquares(alex, 25)
wn.exitonclick()
```
Result:
![](Exercises/3_image.png)
Problem 5
---------
> The two spirals in this picture differ only by the turn angle. Draw both.
>
> ![../_images/tess_spirals.png](Exercises/tess_spirals.png)
It took me a minute to realize that was the angle for the spiral on the right was literally just 1° different. Also.. I made Tess purple. Gotta have some variety. 
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 6
# Problem 5
import turtle
def drawSquareSpiral(t, sz, num, angle):
"""Get turtle t to draw a square of sz side"""
for i in range(num):
t.forward(sz*i)
t.left(angle)
wn = turtle.Screen()
wn.setworldcoordinates(-300,-300,300,300)
wn.bgcolor("lightgreen")
alex = turtle.Turtle()
alex.color("blue")
alex.speed(0)
alex.up()
alex.goto(-150,0)
alex.down()
tess = turtle.Turtle()
tess.color("purple")
tess.speed(0)
tess.up()
tess.goto(150,0)
tess.down()
drawSquareSpiral(alex,2,100,90)
drawSquareSpiral(tess,2,100,91)
wn.exitonclick()
```
Result:
![](Exercises/4_image.png)
Problem 10
----------
> Extend your program above. Draw five stars, but between each, pick up the pen, move forward by 350 units, turn right by 144, put the pen down, and draw the next star. You’ll get something like this (note that you will need to move to the left before drawing your first star in order to fit everything in the window):
>
> ![../_images/five_stars.png](Exercises/five_stars.png)
I really don't like the pink and green, so I went with purple and tan instead. The program to be extended was the `drawStar` function. 
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 6
# Problem 10
import turtle
def drawStar(t):
for i in range(5):
t.left(144)
t.forward(-100)
def drawFiveStars(tt):
tt.up()
tt.goto(-180,50)
tt.down()
for i in range(5):
drawStar(tt)
tt.up()
tt.forward(350)
tt.right(144)
tt.down()
wn = turtle.Screen()
wn.bgcolor("tan")
stella = turtle.Turtle()
stella.color("purple")
stella.pensize(2)
stella.speed(10)
drawFiveStars(stella)
wn.exitonclick()
```
Result:
![](Exercises/5_image.png)
Problem 11
----------
> Extend the star function to draw an n pointed star. (Hint: n must be an odd number greater or equal to 3).
This one was a lot of fun! I decided to do the most and get some user input and give feedback. 
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 6
# Problem 11
import turtle
def drawStar(t, numSides, sideLength):
angle = 180 - 180/numSides
t.up()
t.goto(sideLength/2,0)
t.down()
for i in range(numSides):
t.left(angle)
t.forward(sideLength)
def checkSides(tt, sides, length):
if sides >= 3 and sides % 2 != 0:
print("What a beautiful star!")
drawStar(tt, sides, length)
else:
print("Oops! Your star must have an ODD number of at least 3 sides. Let's try that again!")
wn = turtle.Screen()
wn.bgcolor("tan")
stella = turtle.Turtle()
stella.color("purple")
stella.pensize(2)
stella.speed(0)
a = int(input("Help Stella draw a star! How many points does the star have?"))
b = int(input("How long is each side?"))
checkSides(stella, a, b)
wn.exitonclick()
```
Results:
![](Exercises/6_image.png)
Input for `a`: `15`. Input for `b`: `100`
![](Exercises/7_image.png)
Input for `a`: `30`, input for `b`: `100`
Problem 12
----------
> Write a function called drawSprite that will draw a sprite. The function will need parameters for the turtle, the number of legs, and the length of the legs. Invoke the function to create a sprite with 15 legs of length 120.
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 6
# Problem 12
import turtle
def drawSprite(t, numSides, legLength):
angle = 360/numSides
for i in range(numSides):
t.forward(legLength)
t.up()
t.forward(-legLength)
t.right(angle)
t.down()
wn = turtle.Screen()
wn.bgcolor("tan")
avery = turtle.Turtle()
avery.color("brown")
drawSprite(avery, 15, 120)
wn.exitonclick()
```
Result:
![](Exercises/8_image.png)
Problem 13
----------
> Rewrite the function `sumTo(n)` that returns the sum of all integer numbers up to and including n. This time use the accumulator pattern.
The original solution from problem 7 (the equation was given in the instructions: adding numbers 1-10):
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 6
# Problem 7
def sumTo(n):
# your code here
y = (n*(n+1))/2
return y
print(sumTo(10))
```
The modified code for this problem:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 6
# Problem 13
def sumTo(n):
# your code here
runningTotal = 0
for counter in range(n):
runningTotal = runningTotal + (n+1)/2
return runningTotal
print(sumTo(10))
```
I've got to be honest, both solutions seem more complicated than they should be. I'll have to take a closer look to see why the solutions are what they are. 
Problem 14
----------
> Write a function called `mySqrt` that will approximate the square root of a number, call it n, by using Newton’s algorithm. Newton’s approach is an iterative guessing algorithm where the initial guess is n/2 and each subsequent guess is computed using the formula: newguess = (1/2) \* (oldguess + (n/oldguess)).
I'm adding this one here, because it took me a minute to figure out the most efficient way to compute. this. At first I had a for loop, but that was taking way too many steps for the program to get to the right answer. Then I did a for loop with a break and that was better, but that was still taking the program too many steps. 
Finally, I realized that I could just create this program with a while loop and that drastically reduced the amount of steps the program had to go through. It still seems to be going through a few too any checks, but I think it's okay for my current skill level. Plus, it passed all the built in checks!
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 6
# Problem 14
def mySqrt(n):
# your code here
oldGuess = n/2
while oldGuess**2 != n:
oldGuess = (1/2)*(oldGuess+(n/oldGuess))
return oldGuess
print(mySqrt(10000))
```
Result:
![](Exercises/9_image.png)
Problem 15
----------
> Write a function called `myPi` that will return an approximation of PI (3.14159…). Use the [Leibniz](http://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80) approximation.
This is here because, what the hell? They got me approximating pi now?? _cries in calc 1_
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 6
# Problem 15
def myPi(iters):
# Calculate an approximation of PI using the Leibniz
# approximation with iters number of iterations
# your code here
apprPi = 0
for i in range(iters):
term = (-1)**i/(2*i+1)
apprPi += term
return apprPi * 4
print(myPi(1000000))
```
Result:
![](Exercises/10_image.png)
Problem 16
----------
> Write a function called myPi that will return an approximation of PI (3.14159…). Use the [Madhava](http://en.wikipedia.org/wiki/Madhava_of_Sangamagrama) approximation.
Lol this is the above problem but the calculations to get there are on steroids. They weren't kidding when they said this equation converges to real value of pi faster. The last one took 1000000 iterations to get to 3.14519. This one only took 9... (10 if you want to round it). That's insane.
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 6
# Problem 16
import math
def myPi(iters):
# Calculate an approximation of PI using the Madhava
# approximation with iters number of iterations
#your code here
apprPi = 0
for i in range(iters):
term = (-1)**i/((2*i+1)*3**i)
apprPi += term
return apprPi * math.sqrt(12)
print(myPi(10))
```
![](Exercises/11_image.png)
Problem 17
----------
> Write a function called fancySquare that will draw a square with fancy corners (sprites on the corners). You should implement and use the drawSprite function from above. For an even more interesting look, how about adding small triangles to the ends of the sprite legs.
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 6
# Problem 17
import turtle
def drawSprite(t, numSides, legLength):
angle = 360/numSides
for i in range(numSides):
t.forward(legLength)
t.up()
t.forward(-legLength)
t.right(angle)
t.down()
def fancySquare(tt, sz):
"""Get turtle t to draw a square of sz side"""
for i in range(4):
drawSprite(tt, int(sz/10), int(sz/20))
tt.forward(sz)
tt.left(90)
wn = turtle.Screen()
wn.bgcolor("lightblue")
alex = turtle.Turtle()
alex.color("maroon")
alex.pensize(2)
fancySquare(alex, 100)
```
Result:
![](Exercises/12_image.png)
Problem 18
----------
> There was a whole program in A Turtle Bar Chart to create a bar chart with specific data. Creating a bar chart is a useful idea in general. Write a non-fruitful function called barChart, that takes the numeric list of data as a parameter, and draws the bar chart. Write a full program calling this function. The current version of the `drawBar` function unfortuately draws the top of the bar through the bottom of the label. A nice elaboration is to make the label appear completely above the top line. To keep the spacing consistent you might pass an extra parameter to `drawBar` for the distance to move up. For the `barChart` function make that parameter be some small fraction of `maxheight+border`. The fill action makes this modification particularly tricky: You will want to move past the top of the bar and write before or after drawing and filling the bar.
Phew we made it to the last problem! 
Lol they must have known we wouldn't do right in the lesson. We had to work on this exact code and bring the numbers further above the bars. They gave us this (with the code of course):
![](Exercises/14_image.png)
And I did this:
![](Exercises/13_image.png)
Technically, I did _solve_ the problem but was tired and didn't feel like dealing with the little line that appeared as a result of combing `write` and `fill` within the same function. But then we got this problem in the exercises lol and they specifically mentioned the “trickiness” of being able to write the data and fill the bars at the same time. Presumably because of that little extra line. 
So this time I actually did deal with the little line. Created a second turtle, `alex`, and a separate function `writeData`, for `alex` to write with. Also changed the colors, because what even is that red blue green color combo? 
Anyway, here is the code:
```text-x-python
# Runestone.Academy thinkcspy course
# Chapter 6
# Problem 18
import turtle
def writeData(tt, height):
tt.up()
tt.left(90)
tt.forward(height+10)
tt.right(90)
tt.forward(10)
tt.write(str(height))
tt.forward(30)
tt.right(90)
tt.forward(height+10)
tt.left(90)
def drawBar(t, height):
""" Get turtle t to draw one bar, of height. """
t.begin_fill() # start filling this shape
t.left(90)
t.forward(height)
t.right(90)
t.forward(40)
t.right(90)
t.forward(height)
t.left(90)
t.end_fill() # stop filling this shape
xs = [48, 117, 200, 240, 160, 260, 220] # here is the data
maxheight = max(xs)+10
numbars = len(xs)
border = 10
wn = turtle.Screen() # Set up the window and its attributes
wn.setworldcoordinates(0-border, 0-border, 40*numbars+border, maxheight+border)
wn.bgcolor("lightblue")
tess = turtle.Turtle() # create tess and set some attributes
tess.color("purple")
tess.fillcolor("magenta")
tess.pensize(3)
alex = turtle.Turtle()
alex.color("magenta")
for a in xs:
drawBar(tess, a)
writeData(alex, a)
wn.exitonclick()
```
Result:
![](Exercises/15_image.png)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Some files were not shown because too many files have changed in this diff Show more