diff --git a/thinkcspy/Chapter-10-Exercises/Exercises.md b/thinkcspy/Chapter-10-Exercises/Exercises.md deleted file mode 100644 index 5d03d88..0000000 --- a/thinkcspy/Chapter-10-Exercises/Exercises.md +++ /dev/null @@ -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) \ No newline at end of file diff --git a/thinkcspy/Chapter-10-Exercises/Exercises/1_image.png b/thinkcspy/Chapter-10-Exercises/Exercises/1_image.png deleted file mode 100644 index b8e4a24..0000000 Binary files a/thinkcspy/Chapter-10-Exercises/Exercises/1_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-10-Exercises/Exercises/2_image.png b/thinkcspy/Chapter-10-Exercises/Exercises/2_image.png deleted file mode 100644 index 307dc07..0000000 Binary files a/thinkcspy/Chapter-10-Exercises/Exercises/2_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-10-Exercises/Exercises/3_image.png b/thinkcspy/Chapter-10-Exercises/Exercises/3_image.png deleted file mode 100644 index 151a9a8..0000000 Binary files a/thinkcspy/Chapter-10-Exercises/Exercises/3_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-10-Exercises/Exercises/4_image.png b/thinkcspy/Chapter-10-Exercises/Exercises/4_image.png deleted file mode 100644 index c7f0d79..0000000 Binary files a/thinkcspy/Chapter-10-Exercises/Exercises/4_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-10-Exercises/Exercises/5_image.png b/thinkcspy/Chapter-10-Exercises/Exercises/5_image.png deleted file mode 100644 index 68eaf93..0000000 Binary files a/thinkcspy/Chapter-10-Exercises/Exercises/5_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-10-Exercises/Exercises/6_image.png b/thinkcspy/Chapter-10-Exercises/Exercises/6_image.png deleted file mode 100644 index f474612..0000000 Binary files a/thinkcspy/Chapter-10-Exercises/Exercises/6_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-10-Exercises/Exercises/7_image.png b/thinkcspy/Chapter-10-Exercises/Exercises/7_image.png deleted file mode 100644 index 5ab7522..0000000 Binary files a/thinkcspy/Chapter-10-Exercises/Exercises/7_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-10-Exercises/Exercises/8_image.png b/thinkcspy/Chapter-10-Exercises/Exercises/8_image.png deleted file mode 100644 index aa34ad7..0000000 Binary files a/thinkcspy/Chapter-10-Exercises/Exercises/8_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-10-Exercises/Exercises/image.png b/thinkcspy/Chapter-10-Exercises/Exercises/image.png deleted file mode 100644 index c1caf83..0000000 Binary files a/thinkcspy/Chapter-10-Exercises/Exercises/image.png and /dev/null differ diff --git a/thinkcspy/Chapter-10-Exercises/Python-files/Problem11.py b/thinkcspy/Chapter-10-Exercises/Problem11.py similarity index 100% rename from thinkcspy/Chapter-10-Exercises/Python-files/Problem11.py rename to thinkcspy/Chapter-10-Exercises/Problem11.py diff --git a/thinkcspy/Chapter-10-Exercises/Python-files/Problem12.py b/thinkcspy/Chapter-10-Exercises/Problem12.py similarity index 100% rename from thinkcspy/Chapter-10-Exercises/Python-files/Problem12.py rename to thinkcspy/Chapter-10-Exercises/Problem12.py diff --git a/thinkcspy/Chapter-10-Exercises/Python-files/Problem13.py b/thinkcspy/Chapter-10-Exercises/Problem13.py similarity index 100% rename from thinkcspy/Chapter-10-Exercises/Python-files/Problem13.py rename to thinkcspy/Chapter-10-Exercises/Problem13.py diff --git a/thinkcspy/Chapter-10-Exercises/Python-files/Problem14.py b/thinkcspy/Chapter-10-Exercises/Problem14.py similarity index 100% rename from thinkcspy/Chapter-10-Exercises/Python-files/Problem14.py rename to thinkcspy/Chapter-10-Exercises/Problem14.py diff --git a/thinkcspy/Chapter-10-Exercises/Python-files/Problem15.py b/thinkcspy/Chapter-10-Exercises/Problem15.py similarity index 100% rename from thinkcspy/Chapter-10-Exercises/Python-files/Problem15.py rename to thinkcspy/Chapter-10-Exercises/Problem15.py diff --git a/thinkcspy/Chapter-10-Exercises/Python-files/Problem16.py b/thinkcspy/Chapter-10-Exercises/Problem16.py similarity index 100% rename from thinkcspy/Chapter-10-Exercises/Python-files/Problem16.py rename to thinkcspy/Chapter-10-Exercises/Problem16.py diff --git a/thinkcspy/Chapter-10-Exercises/Python-files/Problem3.py b/thinkcspy/Chapter-10-Exercises/Problem3.py similarity index 100% rename from thinkcspy/Chapter-10-Exercises/Python-files/Problem3.py rename to thinkcspy/Chapter-10-Exercises/Problem3.py diff --git a/thinkcspy/Chapter-11-Exercises/Exercises.md b/thinkcspy/Chapter-11-Exercises/Exercises.md deleted file mode 100644 index 17a4199..0000000 --- a/thinkcspy/Chapter-11-Exercises/Exercises.md +++ /dev/null @@ -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) \ No newline at end of file diff --git a/thinkcspy/Chapter-11-Exercises/Exercises/1_image.png b/thinkcspy/Chapter-11-Exercises/Exercises/1_image.png deleted file mode 100644 index 7e17c06..0000000 Binary files a/thinkcspy/Chapter-11-Exercises/Exercises/1_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-11-Exercises/Exercises/2_image.png b/thinkcspy/Chapter-11-Exercises/Exercises/2_image.png deleted file mode 100644 index b809cad..0000000 Binary files a/thinkcspy/Chapter-11-Exercises/Exercises/2_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-11-Exercises/Exercises/3_image.png b/thinkcspy/Chapter-11-Exercises/Exercises/3_image.png deleted file mode 100644 index f0b2c0f..0000000 Binary files a/thinkcspy/Chapter-11-Exercises/Exercises/3_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-11-Exercises/Exercises/4_image.png b/thinkcspy/Chapter-11-Exercises/Exercises/4_image.png deleted file mode 100644 index f4053a4..0000000 Binary files a/thinkcspy/Chapter-11-Exercises/Exercises/4_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-11-Exercises/Exercises/5_image.png b/thinkcspy/Chapter-11-Exercises/Exercises/5_image.png deleted file mode 100644 index 5394457..0000000 Binary files a/thinkcspy/Chapter-11-Exercises/Exercises/5_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-11-Exercises/Exercises/6_image.png b/thinkcspy/Chapter-11-Exercises/Exercises/6_image.png deleted file mode 100644 index 9378d69..0000000 Binary files a/thinkcspy/Chapter-11-Exercises/Exercises/6_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-11-Exercises/Exercises/image.png b/thinkcspy/Chapter-11-Exercises/Exercises/image.png deleted file mode 100644 index 8d58fa3..0000000 Binary files a/thinkcspy/Chapter-11-Exercises/Exercises/image.png and /dev/null differ diff --git a/thinkcspy/Chapter-11-Exercises/Exercises/mystery-2023-10-27_15.00.35.gif b/thinkcspy/Chapter-11-Exercises/Exercises/mystery-2023-10-27_15.00.35.gif deleted file mode 100644 index c9bfddf..0000000 Binary files a/thinkcspy/Chapter-11-Exercises/Exercises/mystery-2023-10-27_15.00.35.gif and /dev/null differ diff --git a/thinkcspy/Chapter-11-Exercises/Exercises/mystery.txt.md b/thinkcspy/Chapter-11-Exercises/Exercises/mystery.txt.md deleted file mode 100644 index aca8b16..0000000 --- a/thinkcspy/Chapter-11-Exercises/Exercises/mystery.txt.md +++ /dev/null @@ -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 -``` \ No newline at end of file diff --git a/thinkcspy/Chapter-11-Exercises/Python-files/Problem1.py b/thinkcspy/Chapter-11-Exercises/Problem1.py similarity index 100% rename from thinkcspy/Chapter-11-Exercises/Python-files/Problem1.py rename to thinkcspy/Chapter-11-Exercises/Problem1.py diff --git a/thinkcspy/Chapter-11-Exercises/Python-files/Problem2.py b/thinkcspy/Chapter-11-Exercises/Problem2.py similarity index 100% rename from thinkcspy/Chapter-11-Exercises/Python-files/Problem2.py rename to thinkcspy/Chapter-11-Exercises/Problem2.py diff --git a/thinkcspy/Chapter-11-Exercises/Python-files/Problem3.py b/thinkcspy/Chapter-11-Exercises/Problem3.py similarity index 100% rename from thinkcspy/Chapter-11-Exercises/Python-files/Problem3.py rename to thinkcspy/Chapter-11-Exercises/Problem3.py diff --git a/thinkcspy/Chapter-11-Exercises/Python-files/Problem4.py b/thinkcspy/Chapter-11-Exercises/Problem4.py similarity index 100% rename from thinkcspy/Chapter-11-Exercises/Python-files/Problem4.py rename to thinkcspy/Chapter-11-Exercises/Problem4.py diff --git a/thinkcspy/Chapter-11-Exercises/Python-files/Problem5.py b/thinkcspy/Chapter-11-Exercises/Problem5.py similarity index 100% rename from thinkcspy/Chapter-11-Exercises/Python-files/Problem5.py rename to thinkcspy/Chapter-11-Exercises/Problem5.py diff --git a/thinkcspy/Chapter-2-Exercises/Chapter-2-Exercises.md b/thinkcspy/Chapter-2-Exercises/Chapter-2-Exercises.md deleted file mode 100644 index 5eb983a..0000000 --- a/thinkcspy/Chapter-2-Exercises/Chapter-2-Exercises.md +++ /dev/null @@ -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.') -``` \ No newline at end of file diff --git a/thinkcspy/Chapter-2-Exercises/Python-Files/problem10.py b/thinkcspy/Chapter-2-Exercises/problem10.py similarity index 100% rename from thinkcspy/Chapter-2-Exercises/Python-Files/problem10.py rename to thinkcspy/Chapter-2-Exercises/problem10.py diff --git a/thinkcspy/Chapter-2-Exercises/Python-Files/problem11.py b/thinkcspy/Chapter-2-Exercises/problem11.py similarity index 100% rename from thinkcspy/Chapter-2-Exercises/Python-Files/problem11.py rename to thinkcspy/Chapter-2-Exercises/problem11.py diff --git a/thinkcspy/Chapter-2-Exercises/Python-Files/problem12.py b/thinkcspy/Chapter-2-Exercises/problem12.py similarity index 100% rename from thinkcspy/Chapter-2-Exercises/Python-Files/problem12.py rename to thinkcspy/Chapter-2-Exercises/problem12.py diff --git a/thinkcspy/Chapter-2-Exercises/Python-Files/problem3.py b/thinkcspy/Chapter-2-Exercises/problem3.py similarity index 100% rename from thinkcspy/Chapter-2-Exercises/Python-Files/problem3.py rename to thinkcspy/Chapter-2-Exercises/problem3.py diff --git a/thinkcspy/Chapter-2-Exercises/Python-Files/problem4.py b/thinkcspy/Chapter-2-Exercises/problem4.py similarity index 100% rename from thinkcspy/Chapter-2-Exercises/Python-Files/problem4.py rename to thinkcspy/Chapter-2-Exercises/problem4.py diff --git a/thinkcspy/Chapter-2-Exercises/Python-Files/problem7.py b/thinkcspy/Chapter-2-Exercises/problem7.py similarity index 100% rename from thinkcspy/Chapter-2-Exercises/Python-Files/problem7.py rename to thinkcspy/Chapter-2-Exercises/problem7.py diff --git a/thinkcspy/Chapter-2-Exercises/Python-Files/problem8.py b/thinkcspy/Chapter-2-Exercises/problem8.py similarity index 100% rename from thinkcspy/Chapter-2-Exercises/Python-Files/problem8.py rename to thinkcspy/Chapter-2-Exercises/problem8.py diff --git a/thinkcspy/Chapter-2-Exercises/Python-Files/problem9.py b/thinkcspy/Chapter-2-Exercises/problem9.py similarity index 100% rename from thinkcspy/Chapter-2-Exercises/Python-Files/problem9.py rename to thinkcspy/Chapter-2-Exercises/problem9.py diff --git a/thinkcspy/Chapter-4-Exercises/Chapter-4-Exercises.md b/thinkcspy/Chapter-4-Exercises/Chapter-4-Exercises.md deleted file mode 100644 index 278eaf2..0000000 --- a/thinkcspy/Chapter-4-Exercises/Chapter-4-Exercises.md +++ /dev/null @@ -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) \ No newline at end of file diff --git a/thinkcspy/Chapter-4-Exercises/Exercises/1_image.png b/thinkcspy/Chapter-4-Exercises/Exercises/1_image.png deleted file mode 100644 index 9a8aab2..0000000 Binary files a/thinkcspy/Chapter-4-Exercises/Exercises/1_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-4-Exercises/Exercises/2_image.png b/thinkcspy/Chapter-4-Exercises/Exercises/2_image.png deleted file mode 100644 index 3411763..0000000 Binary files a/thinkcspy/Chapter-4-Exercises/Exercises/2_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-4-Exercises/Exercises/3_image.png b/thinkcspy/Chapter-4-Exercises/Exercises/3_image.png deleted file mode 100644 index c257715..0000000 Binary files a/thinkcspy/Chapter-4-Exercises/Exercises/3_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-4-Exercises/Exercises/4_image.png b/thinkcspy/Chapter-4-Exercises/Exercises/4_image.png deleted file mode 100644 index 2fe5eb2..0000000 Binary files a/thinkcspy/Chapter-4-Exercises/Exercises/4_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-4-Exercises/Exercises/image.png b/thinkcspy/Chapter-4-Exercises/Exercises/image.png deleted file mode 100644 index 86962e1..0000000 Binary files a/thinkcspy/Chapter-4-Exercises/Exercises/image.png and /dev/null differ diff --git a/thinkcspy/Chapter-4-Exercises/Exercises/star1.png b/thinkcspy/Chapter-4-Exercises/Exercises/star1.png deleted file mode 100644 index c3257be..0000000 Binary files a/thinkcspy/Chapter-4-Exercises/Exercises/star1.png and /dev/null differ diff --git a/thinkcspy/Chapter-4-Exercises/Exercises/tess_clock1.png b/thinkcspy/Chapter-4-Exercises/Exercises/tess_clock1.png deleted file mode 100644 index ad61838..0000000 Binary files a/thinkcspy/Chapter-4-Exercises/Exercises/tess_clock1.png and /dev/null differ diff --git a/thinkcspy/Chapter-4-Exercises/Python-Files/problem10.py b/thinkcspy/Chapter-4-Exercises/problem10.py similarity index 100% rename from thinkcspy/Chapter-4-Exercises/Python-Files/problem10.py rename to thinkcspy/Chapter-4-Exercises/problem10.py diff --git a/thinkcspy/Chapter-4-Exercises/Python-Files/problem11.py b/thinkcspy/Chapter-4-Exercises/problem11.py similarity index 100% rename from thinkcspy/Chapter-4-Exercises/Python-Files/problem11.py rename to thinkcspy/Chapter-4-Exercises/problem11.py diff --git a/thinkcspy/Chapter-4-Exercises/Python-Files/problem4.py b/thinkcspy/Chapter-4-Exercises/problem4.py similarity index 100% rename from thinkcspy/Chapter-4-Exercises/Python-Files/problem4.py rename to thinkcspy/Chapter-4-Exercises/problem4.py diff --git a/thinkcspy/Chapter-4-Exercises/Python-Files/problem5.py b/thinkcspy/Chapter-4-Exercises/problem5.py similarity index 100% rename from thinkcspy/Chapter-4-Exercises/Python-Files/problem5.py rename to thinkcspy/Chapter-4-Exercises/problem5.py diff --git a/thinkcspy/Chapter-4-Exercises/Python-Files/problem9.py b/thinkcspy/Chapter-4-Exercises/problem9.py similarity index 100% rename from thinkcspy/Chapter-4-Exercises/Python-Files/problem9.py rename to thinkcspy/Chapter-4-Exercises/problem9.py diff --git a/thinkcspy/Chapter-5-Exercises/Exercises.md b/thinkcspy/Chapter-5-Exercises/Exercises.md deleted file mode 100644 index 319be17..0000000 --- a/thinkcspy/Chapter-5-Exercises/Exercises.md +++ /dev/null @@ -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). \ No newline at end of file diff --git a/thinkcspy/Chapter-5-Exercises/Exercises/1_image.png b/thinkcspy/Chapter-5-Exercises/Exercises/1_image.png deleted file mode 100644 index 041be83..0000000 Binary files a/thinkcspy/Chapter-5-Exercises/Exercises/1_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-5-Exercises/Exercises/2_image.png b/thinkcspy/Chapter-5-Exercises/Exercises/2_image.png deleted file mode 100644 index dcf80ee..0000000 Binary files a/thinkcspy/Chapter-5-Exercises/Exercises/2_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-5-Exercises/Exercises/3_image.png b/thinkcspy/Chapter-5-Exercises/Exercises/3_image.png deleted file mode 100644 index 22cda79..0000000 Binary files a/thinkcspy/Chapter-5-Exercises/Exercises/3_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-5-Exercises/Exercises/image.png b/thinkcspy/Chapter-5-Exercises/Exercises/image.png deleted file mode 100644 index 65c212e..0000000 Binary files a/thinkcspy/Chapter-5-Exercises/Exercises/image.png and /dev/null differ diff --git a/thinkcspy/Chapter-5-Exercises/Python-files/Lab.py b/thinkcspy/Chapter-5-Exercises/Lab.py similarity index 100% rename from thinkcspy/Chapter-5-Exercises/Python-files/Lab.py rename to thinkcspy/Chapter-5-Exercises/Lab.py diff --git a/thinkcspy/Chapter-5-Exercises/Lab/image.png b/thinkcspy/Chapter-5-Exercises/Lab/image.png deleted file mode 100644 index ac9bd5f..0000000 Binary files a/thinkcspy/Chapter-5-Exercises/Lab/image.png and /dev/null differ diff --git a/thinkcspy/Chapter-5-Exercises/Lab_Plotting_a_Sine_Wave.md b/thinkcspy/Chapter-5-Exercises/Lab_Plotting_a_Sine_Wave.md deleted file mode 100644 index 293b331..0000000 --- a/thinkcspy/Chapter-5-Exercises/Lab_Plotting_a_Sine_Wave.md +++ /dev/null @@ -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) \ No newline at end of file diff --git a/thinkcspy/Chapter-5-Exercises/Python-files/problem16.py b/thinkcspy/Chapter-5-Exercises/problem16.py similarity index 100% rename from thinkcspy/Chapter-5-Exercises/Python-files/problem16.py rename to thinkcspy/Chapter-5-Exercises/problem16.py diff --git a/thinkcspy/Chapter-5-Exercises/Python-files/problem17.py b/thinkcspy/Chapter-5-Exercises/problem17.py similarity index 100% rename from thinkcspy/Chapter-5-Exercises/Python-files/problem17.py rename to thinkcspy/Chapter-5-Exercises/problem17.py diff --git a/thinkcspy/Chapter-5-Exercises/Python-files/problem18.py b/thinkcspy/Chapter-5-Exercises/problem18.py similarity index 100% rename from thinkcspy/Chapter-5-Exercises/Python-files/problem18.py rename to thinkcspy/Chapter-5-Exercises/problem18.py diff --git a/thinkcspy/Chapter-5-Exercises/Python-files/problem19.py b/thinkcspy/Chapter-5-Exercises/problem19.py similarity index 100% rename from thinkcspy/Chapter-5-Exercises/Python-files/problem19.py rename to thinkcspy/Chapter-5-Exercises/problem19.py diff --git a/thinkcspy/Chapter-6-Exercises/Exercises.md b/thinkcspy/Chapter-6-Exercises/Exercises.md deleted file mode 100644 index bd18261..0000000 --- a/thinkcspy/Chapter-6-Exercises/Exercises.md +++ /dev/null @@ -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) \ No newline at end of file diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/10_image.png b/thinkcspy/Chapter-6-Exercises/Exercises/10_image.png deleted file mode 100644 index 7e9bb08..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/10_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/11_image.png b/thinkcspy/Chapter-6-Exercises/Exercises/11_image.png deleted file mode 100644 index 34b702b..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/11_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/12_image.png b/thinkcspy/Chapter-6-Exercises/Exercises/12_image.png deleted file mode 100644 index 985d642..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/12_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/13_image.png b/thinkcspy/Chapter-6-Exercises/Exercises/13_image.png deleted file mode 100644 index 0efed20..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/13_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/14_image.png b/thinkcspy/Chapter-6-Exercises/Exercises/14_image.png deleted file mode 100644 index cb90b50..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/14_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/15_image.png b/thinkcspy/Chapter-6-Exercises/Exercises/15_image.png deleted file mode 100644 index 5db23c2..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/15_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/1_image.png b/thinkcspy/Chapter-6-Exercises/Exercises/1_image.png deleted file mode 100644 index 2bc0d57..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/1_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/2_image.png b/thinkcspy/Chapter-6-Exercises/Exercises/2_image.png deleted file mode 100644 index 9b6c7d8..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/2_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/3_image.png b/thinkcspy/Chapter-6-Exercises/Exercises/3_image.png deleted file mode 100644 index 867b9a0..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/3_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/4_image.png b/thinkcspy/Chapter-6-Exercises/Exercises/4_image.png deleted file mode 100644 index bc8eb6d..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/4_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/5_image.png b/thinkcspy/Chapter-6-Exercises/Exercises/5_image.png deleted file mode 100644 index 3f5dde4..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/5_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/6_image.png b/thinkcspy/Chapter-6-Exercises/Exercises/6_image.png deleted file mode 100644 index 3f5af54..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/6_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/7_image.png b/thinkcspy/Chapter-6-Exercises/Exercises/7_image.png deleted file mode 100644 index 2d6d0f2..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/7_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/8_image.png b/thinkcspy/Chapter-6-Exercises/Exercises/8_image.png deleted file mode 100644 index 1c26c3d..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/8_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/9_image.png b/thinkcspy/Chapter-6-Exercises/Exercises/9_image.png deleted file mode 100644 index 44014a3..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/9_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/five_squares.png b/thinkcspy/Chapter-6-Exercises/Exercises/five_squares.png deleted file mode 100644 index 02584c7..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/five_squares.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/five_stars.png b/thinkcspy/Chapter-6-Exercises/Exercises/five_stars.png deleted file mode 100644 index 1f680ab..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/five_stars.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/image.png b/thinkcspy/Chapter-6-Exercises/Exercises/image.png deleted file mode 100644 index a3ee998..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/image.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/nested_squares.png b/thinkcspy/Chapter-6-Exercises/Exercises/nested_squares.png deleted file mode 100644 index 2e7596c..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/nested_squares.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/regularpolygon.png b/thinkcspy/Chapter-6-Exercises/Exercises/regularpolygon.png deleted file mode 100644 index 08fa110..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/regularpolygon.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/tess08.png b/thinkcspy/Chapter-6-Exercises/Exercises/tess08.png deleted file mode 100644 index 0cf6eb5..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/tess08.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Exercises/tess_spirals.png b/thinkcspy/Chapter-6-Exercises/Exercises/tess_spirals.png deleted file mode 100644 index 50bc7c8..0000000 Binary files a/thinkcspy/Chapter-6-Exercises/Exercises/tess_spirals.png and /dev/null differ diff --git a/thinkcspy/Chapter-6-Exercises/Python-files/problem1.py b/thinkcspy/Chapter-6-Exercises/problem1.py similarity index 100% rename from thinkcspy/Chapter-6-Exercises/Python-files/problem1.py rename to thinkcspy/Chapter-6-Exercises/problem1.py diff --git a/thinkcspy/Chapter-6-Exercises/Python-files/problem10.py b/thinkcspy/Chapter-6-Exercises/problem10.py similarity index 100% rename from thinkcspy/Chapter-6-Exercises/Python-files/problem10.py rename to thinkcspy/Chapter-6-Exercises/problem10.py diff --git a/thinkcspy/Chapter-6-Exercises/Python-files/problem11.py b/thinkcspy/Chapter-6-Exercises/problem11.py similarity index 100% rename from thinkcspy/Chapter-6-Exercises/Python-files/problem11.py rename to thinkcspy/Chapter-6-Exercises/problem11.py diff --git a/thinkcspy/Chapter-6-Exercises/Python-files/problem12.py b/thinkcspy/Chapter-6-Exercises/problem12.py similarity index 100% rename from thinkcspy/Chapter-6-Exercises/Python-files/problem12.py rename to thinkcspy/Chapter-6-Exercises/problem12.py diff --git a/thinkcspy/Chapter-6-Exercises/Python-files/problem13.py b/thinkcspy/Chapter-6-Exercises/problem13.py similarity index 100% rename from thinkcspy/Chapter-6-Exercises/Python-files/problem13.py rename to thinkcspy/Chapter-6-Exercises/problem13.py diff --git a/thinkcspy/Chapter-6-Exercises/Python-files/problem14.py b/thinkcspy/Chapter-6-Exercises/problem14.py similarity index 100% rename from thinkcspy/Chapter-6-Exercises/Python-files/problem14.py rename to thinkcspy/Chapter-6-Exercises/problem14.py diff --git a/thinkcspy/Chapter-6-Exercises/Python-files/problem15.py b/thinkcspy/Chapter-6-Exercises/problem15.py similarity index 100% rename from thinkcspy/Chapter-6-Exercises/Python-files/problem15.py rename to thinkcspy/Chapter-6-Exercises/problem15.py diff --git a/thinkcspy/Chapter-6-Exercises/Python-files/problem16.py b/thinkcspy/Chapter-6-Exercises/problem16.py similarity index 100% rename from thinkcspy/Chapter-6-Exercises/Python-files/problem16.py rename to thinkcspy/Chapter-6-Exercises/problem16.py diff --git a/thinkcspy/Chapter-6-Exercises/Python-files/problem17.py b/thinkcspy/Chapter-6-Exercises/problem17.py similarity index 100% rename from thinkcspy/Chapter-6-Exercises/Python-files/problem17.py rename to thinkcspy/Chapter-6-Exercises/problem17.py diff --git a/thinkcspy/Chapter-6-Exercises/Python-files/problem18.py b/thinkcspy/Chapter-6-Exercises/problem18.py similarity index 100% rename from thinkcspy/Chapter-6-Exercises/Python-files/problem18.py rename to thinkcspy/Chapter-6-Exercises/problem18.py diff --git a/thinkcspy/Chapter-6-Exercises/Python-files/problem2.py b/thinkcspy/Chapter-6-Exercises/problem2.py similarity index 100% rename from thinkcspy/Chapter-6-Exercises/Python-files/problem2.py rename to thinkcspy/Chapter-6-Exercises/problem2.py diff --git a/thinkcspy/Chapter-6-Exercises/Python-files/problem3.py b/thinkcspy/Chapter-6-Exercises/problem3.py similarity index 100% rename from thinkcspy/Chapter-6-Exercises/Python-files/problem3.py rename to thinkcspy/Chapter-6-Exercises/problem3.py diff --git a/thinkcspy/Chapter-6-Exercises/Python-files/problem4.py b/thinkcspy/Chapter-6-Exercises/problem4.py similarity index 100% rename from thinkcspy/Chapter-6-Exercises/Python-files/problem4.py rename to thinkcspy/Chapter-6-Exercises/problem4.py diff --git a/thinkcspy/Chapter-6-Exercises/Python-files/problem5.py b/thinkcspy/Chapter-6-Exercises/problem5.py similarity index 100% rename from thinkcspy/Chapter-6-Exercises/Python-files/problem5.py rename to thinkcspy/Chapter-6-Exercises/problem5.py diff --git a/thinkcspy/Chapter-7-Exercises/Exercises.md b/thinkcspy/Chapter-7-Exercises/Exercises.md deleted file mode 100644 index f63727b..0000000 --- a/thinkcspy/Chapter-7-Exercises/Exercises.md +++ /dev/null @@ -1,248 +0,0 @@ -# Exercises -Problem 4 ---------- - -> Modify the turtle bar chart program from the previous chapter so that the bar for any value of 200 or more is filled with red, values between \[100 and 200) are filled yellow, and bars representing values less than 100 are filled green. - -Back at it with the turtle bar! See the last problem in chapter 6 for context.  - -This one was more involved than I expected. Plus there is some unexpected behavior that I haven't quite figured out. When I tried to assign color to `alex`, it would write every number except the one to the furthest right. I have no idea why, at least not yet. My Solution was just to not include `alex` in the `getColor` function. To be honest, it looks better that why, but it's still bothering me that the last number gets left out like that. - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 7 -# Problem 4 - -import turtle - -def getColor(tf, tw, height): - if height >= 200: - tf.fillcolor("red") - elif height >= 100: - tf.fillcolor("yellow") - else: - tf.fillcolor("green") - -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") -wn.tracer(100) - -tess = turtle.Turtle() # create tess and set some attributes -tess.color("black") -tess.pensize(3) - -alex = turtle.Turtle() - -for a in xs: - getColor(tess, alex, a) - drawBar(tess, a) - writeData(alex, a) - - -wn.exitonclick() -``` - -Result: - -![](Exercises/image.png) - -Problem 5 ---------- - -> In the turtle bar chart program, what do you expect to happen if one or more of the data values in the list is negative? Go back and try it out. Change the program so that when it prints the text value for the negative bars, it puts the text above the base of the bar (on the 0 axis) - -No new functions this time, but I did have to adjust the `writeData` function, the world coordinates and the data, itself, of course.  - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 7 -# Problem 5 - -import turtle - -def getColor(tf, tw, height): - if height >= 200: - tf.fillcolor("red") - elif height >= 100: - tf.fillcolor("yellow") - else: - tf.fillcolor("green") - -def writeData(tt, height): - if height < 0: - writeHeight = 0 - else: - writeHeight = height - - tt.up() - tt.left(90) - tt.forward(writeHeight+10) - tt.right(90) - tt.forward(10) - tt.write(str(height)) - tt.forward(30) - tt.right(90) - tt.forward(writeHeight+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 -minheight = min(xs)-10 -numbars = len(xs) -border = 10 - -wn = turtle.Screen() # Set up the window and its attributes -wn.setworldcoordinates(0-border, 0+minheight, 40*numbars+border, maxheight+border) -wn.bgcolor("lightblue") -wn.tracer(100) - -tess = turtle.Turtle() # create tess and set some attributes -tess.color("black") -tess.pensize(3) - -alex = turtle.Turtle() - -for a in xs: - getColor(tess, alex, a) - drawBar(tess, a) - writeData(alex, a) - - -wn.exitonclick() -``` - -Result: - -![](Exercises/1_image.png) - -Problem 13 ----------- - -> Implement the calculator for the date of Easter. -> -> The following algorithm computes the date for Easter Sunday for any year between 1900 to 2099. -> -> Ask the user to enter a year. Compute the following: -> -> 1. a = year % 19 -> 2. b = year % 4 -> 3. c = year % 7 -> 4. d = (19 \* a + 24) % 30 -> 5. e = (2 \* b + 4 \* c + 6 \* d + 5) % 7 -> 6. dateofeaster = 22 + d + e -> -> Special note: The algorithm can give a date in April. Also, if the year is one of four special years (1954, 1981, 2049, or 2076) then subtract 7 from the date. -> -> Your program should print an error message if the user provides a date that is out of range. - -We had to figure out the leap year in problem 12: - -> 3 criteria must be taken into account to identify leap years: -> -> The year is evenly divisible by 4; -> -> If the year can be evenly divided by 100, it is NOT a leap year, unless; -> -> The year is also evenly divisible by 400. Then it is a leap year. -> -> Write a function that takes a year as a parameter and returns `True` if the year is a leap year, `False` otherwise. - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 7 -# Problem 13 - -def isLeap(year): - # your code here - if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: - return True - else: - return False - -def easter(year): - a = year % 19 - b = year % 4 - c = year % 7 - d = (19 * a + 24) % 30 - e = (2 * b + 4 * c + 6 * d + 5) % 7 - - if year >= 1900 and year <= 2099: - if isLeap(year): - dateofeaster = 22 + d + e - 7 - else: - dateofeaster = 22 + d + e - else: - dateofeaster = 0 - - return dateofeaster - -def convertDate(year): - date = easter(year) - - if date == 0: - print("Error: Date is out of range.") - elif date <= 30: - print("In", year, "Easter falls on March", date - 1, ".") - else: - print("In", year, "Easter falls on April", date - 31, ".") - -userYear = int(input("Enter a year between 1900 and 2099.")) - -convertDate(userYear) -``` - -Result in range: - -![](Exercises/2_image.png) - -Result out of range: - -![](Exercises/3_image.png) \ No newline at end of file diff --git a/thinkcspy/Chapter-7-Exercises/Exercises/1_image.png b/thinkcspy/Chapter-7-Exercises/Exercises/1_image.png deleted file mode 100644 index 5033c63..0000000 Binary files a/thinkcspy/Chapter-7-Exercises/Exercises/1_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-7-Exercises/Exercises/2_image.png b/thinkcspy/Chapter-7-Exercises/Exercises/2_image.png deleted file mode 100644 index 49d922e..0000000 Binary files a/thinkcspy/Chapter-7-Exercises/Exercises/2_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-7-Exercises/Exercises/3_image.png b/thinkcspy/Chapter-7-Exercises/Exercises/3_image.png deleted file mode 100644 index 6e14817..0000000 Binary files a/thinkcspy/Chapter-7-Exercises/Exercises/3_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-7-Exercises/Exercises/image.png b/thinkcspy/Chapter-7-Exercises/Exercises/image.png deleted file mode 100644 index 98e5a7b..0000000 Binary files a/thinkcspy/Chapter-7-Exercises/Exercises/image.png and /dev/null differ diff --git a/thinkcspy/Chapter-7-Exercises/Python-files/Lab.py b/thinkcspy/Chapter-7-Exercises/Lab.py similarity index 100% rename from thinkcspy/Chapter-7-Exercises/Python-files/Lab.py rename to thinkcspy/Chapter-7-Exercises/Lab.py diff --git a/thinkcspy/Chapter-7-Exercises/Lab_Approximating_the_Value_of_Pi/Lab Approximating the Value of Pi/image.png b/thinkcspy/Chapter-7-Exercises/Lab_Approximating_the_Value_of_Pi/Lab Approximating the Value of Pi/image.png deleted file mode 100644 index e150809..0000000 Binary files a/thinkcspy/Chapter-7-Exercises/Lab_Approximating_the_Value_of_Pi/Lab Approximating the Value of Pi/image.png and /dev/null differ diff --git a/thinkcspy/Chapter-7-Exercises/Lab_Approximating_the_Value_of_Pi/Lab Approximating the Value of.md b/thinkcspy/Chapter-7-Exercises/Lab_Approximating_the_Value_of_Pi/Lab Approximating the Value of.md deleted file mode 100644 index 4dd777a..0000000 --- a/thinkcspy/Chapter-7-Exercises/Lab_Approximating_the_Value_of_Pi/Lab Approximating the Value of.md +++ /dev/null @@ -1,100 +0,0 @@ -# Lab: Approximating the Value of Pi -In this lab, our task was to simulate throwing darts at a 2x2 board, count how many landed in the circle out of the total amount and then approximate pi based on that.  - -This is the code they started me off with: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 7 -# Lab - -import turtle -import math -import random - -fred = turtle.Turtle() - -wn = turtle.Screen() -wn.setworldcoordinates(-1,-1,1,1) - -fred.up() - -numdarts = 10 -for i in range(numdarts): - randx = random.random() - randy = random.random() - - x = - y = - -wn.exitonclick() -``` - -My additions and changes to the above code: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 7 -# Lab - -import turtle -#import math -import random - - -fred = turtle.Turtle() -clara = turtle.Turtle() - -wn = turtle.Screen() -wn.setworldcoordinates(-1,-1,1,1) -wn.bgcolor("tan") -wn.tracer(100) - -clara.dot() -print(clara.pos()) -clara.up() -clara.goto(0,1) -clara.down() -clara.circle(-1) -print(clara.pos()) -print(clara.distance(0.0,0.0)) - -fred.up() - -numdarts = 100000 -insideCount = 0 - -for i in range(numdarts): - randx = random.random()*2-1 - randy = random.random()*2-1 - - fred.goto(randx,randy) - dist = fred.distance(0.0, 0.0) - - if dist < 1: - color = "red" - insideCount += 1 - place = "in" - else: - color = "blue" - place = "out" - - fred.down() - fred.dot(10,color) - fred.up() - - -mypi = 4 * (insideCount / numdarts) -print(insideCount,"out of", numdarts, "darts made it into the circle.") -print("The value of Pi based on the numbers number of darts that made it into the circle is", mypi, ".") - -wn.exitonclick() -``` - -Result: - -![](Lab%20Approximating%20the%20Value%20of%20Pi/image.png) - -Order really does matter.. My first solution to this lab was mostly fine, except that the dots were being colored wrong. Some dots inside the circle were blue and some outside the circle were red. It was supposed to be the other way around.  - -Initially I had fred go to his position after the if else block, but the problem was, the distance was being measured _before_ he moved. So distance was based on the previous loop's coordinates and coloring the darts based on those rather than the current loop's points. It took me a minute but I finally figured out that I needed to position fred _before_ measuring the distance between fred's current position and the center. \ No newline at end of file diff --git a/thinkcspy/Chapter-7-Exercises/Python-files/Problem13.py b/thinkcspy/Chapter-7-Exercises/Problem13.py similarity index 100% rename from thinkcspy/Chapter-7-Exercises/Python-files/Problem13.py rename to thinkcspy/Chapter-7-Exercises/Problem13.py diff --git a/thinkcspy/Chapter-7-Exercises/Python-files/Problem4.py b/thinkcspy/Chapter-7-Exercises/Problem4.py similarity index 100% rename from thinkcspy/Chapter-7-Exercises/Python-files/Problem4.py rename to thinkcspy/Chapter-7-Exercises/Problem4.py diff --git a/thinkcspy/Chapter-7-Exercises/Python-files/Problem5.py b/thinkcspy/Chapter-7-Exercises/Problem5.py similarity index 100% rename from thinkcspy/Chapter-7-Exercises/Python-files/Problem5.py rename to thinkcspy/Chapter-7-Exercises/Problem5.py diff --git a/thinkcspy/Chapter-8-Exercises/Exercises.md b/thinkcspy/Chapter-8-Exercises/Exercises.md deleted file mode 100644 index 32438d2..0000000 --- a/thinkcspy/Chapter-8-Exercises/Exercises.md +++ /dev/null @@ -1,641 +0,0 @@ -# Exercises -I won't lie, this lesson's exercises were challenging. Some of them I actually needed to look at the answers for help. Nearly all of them required some extra research. The interesting ones I was able to research and figure out on my own are included here.  - -Problem 2 ---------- - -> Write a function `print_triangular_numbers(n)` that prints out the first n triangular numbers. A call to `print_triangular_numbers(5)` would produce the following output: -> -> ```text-plain -> 1 1 -> 2 3 -> 3 6 -> 4 10 -> 5 15 -> ``` -> -> (_hint: use a web search to find out what a triangular number is._) - -This one was more of a challenge than I expected. I started the problem off with just getting one triangular sum, which amounts to \\(trisum = n + (n - 1) + (n-2) + ... + (n-n)\\). Then I had to figure out how to print that sum from 1 to n. Finding the triangular sum was surprisingly easy. What wasn't easy was doing that recursively from 1 to n.  - -My initial attempt was to decrement `n` the way `bound` is decremented in the final code below. The problem is, once I did that, I couldn't recover `n` for the next 4 rounds. I thought about using `i` for that purpose but remembered there was a reason I tried to use `n` first — I needed two variables: one to increment and another to decrement.  - -So that's when `bound` was created. Problem was, I initialized it to the value of `n` _outside of both loops_ but then ran into the same problem I'd had with using `n` in the first place. _Finally_, I realized that I needed to recursively initialize `bound` to the value of `i` _in the first loop_ and _then_ decrement it within the second loop.  - -That was a pretty fun problem! Alright, now to the solution: - -```text-x-python -def print_triangular_numbers(n): - # your code here - i = 1 - - while i <= n: - trinum = 0 - bound = i - - while bound > 0: - trinum += bound - bound -= 1 - - print(i, "\t", trinum) - i += 1 - -print_triangular_numbers(5) -``` - -Result: - -![](Exercises/image.png) - -Problem 3 ---------- - -> Write a function, `is_prime`, that takes a single integer argument and returns `True` when the argument is a _prime number_ and `False` otherwise. - -Something good about this book I'm working in is that it shows me how many steps the code is going through to get to final outcome. In my initial working of this problem, I had `x` initialized to the absolute value of `n` - 1. And then I looked at the steps, the code was going through, figured that was too many and the remembered that after the halfway point, numbers will no longer be evenly divisible (e.g. after 10, 20 divided by any number, will produce a remainder or a fraction, depending on what you're doing with the numbers).  - -With that in mind, I changed that value from `x = abs(n) - 1` to `x = abs(n) / 2`. That drastically cut down on the number of steps the program was expected to perform. I also realized that this was not necessarily a great way to test odd numbers, so initialized x to that value minus 1 and proceeded from there.  - -Now the real struggle was working with primes larger than 2. Turns out that solution was simple. Return `True` if the function didn't exit during the `while` loop.  - -But then we get back to the whole “taking too many steps thing”. I did more research and learned that taking the square root of `n` and making that the limit for the while loop would help the program execute a lot faster than testing if x was greater than. Then I reinitialized x to 3, incremented it by 2 instead of decrementing it by 2 and wallah! I had a program that was decently efficient and effective and it passed all the built in tests! - -```text-x-python -import math - -def is_prime(n): - # your code here - - x = 3 - - if abs(n) > 2: - while x < math.sqrt(n): - if n % 2 == 0: - return False - elif n % x == 0: - return False - else: - x += 2 - return True - else: - return True - -print(is_prime(4813)) -``` - -![](Exercises/1_image.png) - -### Correction (Oct 15, 2023): - -While learning about loops and arrays in JavaScript, I had a similar problem where I had to print all the prime numbers for a given number. I came back to this one as a reference and realized that there was actually an issue with the way I looked for prime numbers. For some reason, the number 25 returned `True`, when it should have returned `False`. - - This is how I solved the problem in JavaScript: - -```application-javascript-env-frontend -let n = prompt("Enter a positive integer."); - -outer: -for (let i = 2; i <= n; i++){ - - for (let j = 2; j < i; j++){ - if (i % j == 0) continue outer; - } - - console.log(i); -} -``` - -Result with an input of 25: - -![](Exercises/8_image.png) - -With the above script as a reference, this is how I revised my solution for problem 3: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 8 -# Problem 3 - -def is_prime(n): - # your code - - for i in range (2, n): - if n % i == 0: - return False - return True - -print(is_prime(25)) -``` - -Result: - -![](Exercises/7_image.png) - -Once again, the built in tests are not the end all be all for these problems (see chapter 9's exercises for more context). I passed the tests with the last iteration of my problem, but there was still that _one_ number (25 and maybe more), that got missed by the tests.  - -Turtle Problems ---------------- - -I'm combining problems 4 through 6 because they build on each other. - -> **Problem 4:** -> -> Modify the walking turtle program so that rather than a 90 degree left or right turn the angle of the turn is determined randomly at each step. -> -> **Problem 5:** -> -> Modify the turtle walk program so that you have two turtles each with a random starting location. Keep the turtles moving until one of them leaves the screen. -> -> **Problem 6:**  -> -> Modify the previous turtle walk program so that the turtle turns around when it hits the wall or when one turtle collides with another turtle (when the positions of the two turtles are closer than some small number). - -### Initial code from an earlier lesson section: - -```text-x-python -import random -import turtle - -def isInScreen(w,t): - leftBound = - w.window_width() / 2 - rightBound = w.window_width() / 2 - topBound = w.window_height() / 2 - bottomBound = -w.window_height() / 2 - - turtleX = t.xcor() - turtleY = t.ycor() - - stillIn = True - if turtleX > rightBound or turtleX < leftBound: - stillIn = False - if turtleY > topBound or turtleY < bottomBound: - stillIn = False - - return stillIn - -t = turtle.Turtle() -wn = turtle.Screen() - -t.shape('turtle') -while isInScreen(wn,t): - coin = random.randrange(0, 2) - if coin == 0: - t.left(90) - else: - t.right(90) - - t.forward(50) - -wn.exitonclick() -``` - -### My Code - -Oh boy.. this one was a lot. Problem 4 was pretty easy. All I had to do was have them go at a random angle. That initial code looked like this: - -```text-x-python -import random -import turtle - -def isInScreen(w,t): - leftBound = - w.window_width() / 2 - rightBound = w.window_width() / 2 - topBound = w.window_height() / 2 - bottomBound = -w.window_height() / 2 - - turtleX = t.xcor() - turtleY = t.ycor() - - stillIn = True - if turtleX > rightBound or turtleX < leftBound: - stillIn = False - if turtleY > topBound or turtleY < bottomBound: - stillIn = False - - return stillIn - -t = turtle.Turtle() -wn = turtle.Screen() - -t.shape('turtle') -while isInScreen(wn,t): - coin = random.randrange(0, 2) - if coin == 0: - t.left(random.randrange(1,180)) - else: - t.right(random.randrange(1,180)) - - t.forward(50) - -wn.exitonclick() -``` - -The random starting position proved to be more challenging. The calculations were all fine from the getgo. The issue was I forgot bring the pen up before I moved the turtles to a random location. I ended up moving on to the image problems before coming back to this and realizing that lol. Here's the code for that: - -```text-x-python -import random -import turtle - -def isInScreen(w, t, lBound, rBound, bBound, tBound): - turtleX = t.xcor() - turtleY = t.ycor() - - stillIn = True - if turtleX > rBound or turtleX < lBound: - stillIn = False - if turtleY > tBound or turtleY < bBound: - stillIn = False - - return stillIn - - -def randGoto(t, num1, num2): - return random.randrange(num1, num2) - - -def randPos(t, lBound, rBound, bBound, tBound): - xpos = randGoto(t, lBound, rBound) - ypos = randGoto(t, bBound, tBound) - t.up() - t.goto(xpos, ypos) - t.down() - - -def randMove(wn, t1, t2, lBound, rBound, bBound, tBound): - randPos(t1, lBound, rBound, bBound, tBound) - randPos(t2, lBound, rBound, bBound, tBound) - - while isInScreen(wn, t1, lBound, rBound, bBound, tBound) and isInScreen(wn, t2, lBound, rBound, bBound, tBound): - coin = random.randrange(0, 2) - if coin == 0: - t1.left(random.randrange(1,180)) - t2.left(random.randrange(1,180)) - else: - t1.right(random.randrange(1,180)) - t2.right(random.randrange(1,180)) - - t1.forward(50) - t2.forward(50) - - -wn = turtle.Screen() -wn.bgcolor("lightblue") - -x1 = -wn.window_width() / 2 -x2 = wn.window_width() / 2 -y1 = -wn.window_height() / 2 -y2 = wn.window_height() / 2 - -ella = turtle.Turtle() -ella.color("pink") -ella.shape('turtle') - -micah = turtle.Turtle() -micah.color("green") -micah.shape('turtle') - -randMove(wn, ella, micah, x1, x2, y1, y2) - - -wn.exitonclick() -``` - -Finally, here's the code where the turtles turn around if they run into each other or into a boundary. The instructions for this one was a little vague, but I knew that if I didn't ever let the turtles escape the boundaries, I might have an infinite loop on my hands. So, the turtles, will turn around if they get close to the boundaries, but they can still pass through if they are headed in that direction between 5 and 50 points. - -I also initially had the conditions for the boundaries look like this: - -```text-x-python -if spaceBetween(t1x, lBound) or spaceBetween(t1x, rBound) or spaceBetween(t1y, bBound) or spaceBetween(t1y, tBound): - t1.right(180) -elif spaceBetween(t2x, lBound) or spaceBetween(t2x, rBound) or spaceBetween(t2y, bBound) or spaceBetween(t2y, tBound): - t2.right(180) -elif spaceBetween(t1x, t2x) or spaceBetween(t1y, t2y): - t1.left(180) - t2.right(180) -``` - -The problem with this is that only one of these will execute at a time, when really all of these conditions need to be tested “simultaneously”. So I changed all the `elif` statements to `if` statements.  - -I also changed the angle from `180` to `170` and that seemed to keep the turtles from going straight through the wall when they made another turn at the coin flip part.  - -Here's the final code: - -```text-x-python -import random -import turtle -import math - -def isInScreen(w, t, lBound, rBound, bBound, tBound): - turtleX = t.xcor() - turtleY = t.ycor() - - stillIn = True - if turtleX > rBound or turtleX < lBound: - stillIn = False - if turtleY > tBound or turtleY < bBound: - stillIn = False - - return stillIn - - -def randGoto(t, num1, num2): - return random.randrange(num1, num2) - - -def randPos(t, lBound, rBound, bBound, tBound): - xpos = randGoto(t, lBound, rBound) - ypos = randGoto(t, bBound, tBound) - t.up() - t.goto(xpos, ypos) - t.down() - - -def spaceBetween(num1, num2): - if math.sqrt(num1**2 + num2**2) < 5: - return True - else: - return False - - -def randMove(wn, t1, t2, lBound, rBound, bBound, tBound): - randPos(t1, lBound, rBound, bBound, tBound) - randPos(t2, lBound, rBound, bBound, tBound) - - while isInScreen(wn, t1, lBound, rBound, bBound, tBound) and isInScreen(wn, t2, lBound, rBound, bBound, tBound): - t1x = t1.xcor() - t1y = t1.ycor() - t2x = t2.xcor() - t2y = t2.ycor() - coin = random.randrange(0, 2) - - if spaceBetween(t1x, lBound) or spaceBetween(t1x, rBound) or spaceBetween(t1y, bBound) or spaceBetween(t1y, tBound): - t1.right(170) - if spaceBetween(t2x, lBound) or spaceBetween(t2x, rBound) or spaceBetween(t2y, bBound) or spaceBetween(t2y, tBound): - t2.right(170) - if spaceBetween(t1x, t2x) or spaceBetween(t1y, t2y): - t1.left(170) - t2.right(170) - - if coin == 0: - t1.left(random.randrange(1,180)) - t2.left(random.randrange(1,180)) - else: - t1.right(random.randrange(1,180)) - t2.right(random.randrange(1,180)) - - t1.forward(50) - t2.forward(50) - - - -wn = turtle.Screen() -wn.bgcolor("lightblue") - -x1 = -wn.window_width() / 2 -x2 = wn.window_width() / 2 -y1 = -wn.window_height() / 2 -y2 = wn.window_height() / 2 - -ella = turtle.Turtle() -ella.color("pink") -ella.shape('turtle') - -micah = turtle.Turtle() -micah.color("green") -micah.shape('turtle') - -randMove(wn, ella, micah, x1, x2, y1, y2) - - -wn.exitonclick() -``` - -Result: - -I started after the turtles already got moving, but you get the idea.  -![](Exercises/turtlemoves-2023-09-29_11.47.3.gif) - -Image problems --------------- - -The following problems used the following image and code (from an earlier lesson section) as a starting point: - -![](Exercises/LutherBellPic.jpg) - -```text-x-python -import image - -img = image.Image("luther.jpg") -win = image.ImageWin(img.getWidth(), img.getHeight()) -img.draw(win) -img.setDelay(0) # setDelay(0) turns off animation - -for row in range(img.getHeight()): - for col in range(img.getWidth()): - p = img.getPixel(col, row) - - newred = p.getRed() - newgreen = p.getGreen() - newblue = p.getBlue() - - newpixel = image.Pixel(newred, newgreen, newblue) - - img.setPixel(col, row, newpixel) - -img.draw(win) -win.exitonclick() -``` - -### Problem 8 - -> Write a function to convert the image to grayscale. - -This was my initial solution.  - -```text-x-python -import image - -img = image.Image("luther.jpg") -win = image.ImageWin(img.getWidth(), img.getHeight()) -img.draw(win) -img.setDelay(0) # setDelay(0) turns off animation - -for row in range(img.getHeight()): - for col in range(img.getWidth()): - p = img.getPixel(col, row) - - newred = (p.getRed()+p.getGreen()+p.getBlue())/3 - newgreen = (p.getRed()+p.getGreen()+p.getBlue())/3 - newblue = (p.getRed()+p.getGreen()+p.getBlue())/3 - - newpixel = image.Pixel(newred, newgreen, newblue) - - img.setPixel(col, row, newpixel) - -img.draw(win) -win.exitonclick() -``` - -And the result: - -![](Exercises/3_image.png) - -But then I had to figure out turning That into a function. I was going to go the lazy route and leave it as it was since it gave me the solution I was looking for, but then I figured actually turning this into a function would help me with the next problem.  - -Here was my final solution with the function: - -```text-x-python -import image - -def greyScale (red, blue, green): - return (red + blue + green)/3 - -img = image.Image("luther.jpg") -win = image.ImageWin(img.getWidth(), img.getHeight()) -img.draw(win) -img.setDelay(0) # setDelay(0) turns off animation - -for row in range(img.getHeight()): - for col in range(img.getWidth()): - p = img.getPixel(col, row) - - pixelColor = greyScale(p.getRed(), p.getGreen(), p.getBlue()) - - newblue = newgreen = newred = pixelColor - - newpixel = image.Pixel(newred, newgreen, newblue) - - img.setPixel(col, row, newpixel) - -img.draw(win) -win.exitonclick() -``` - -And the result, of course, is the same: - -![](Exercises/4_image.png) - -### Problem 9 - -> Write a function to convert an image to black and white. - -This was my initial solution: - -```text-x-python -import image - -img = image.Image("luther.jpg") -win = image.ImageWin(img.getWidth(), img.getHeight()) -img.draw(win) -img.setDelay(0) # setDelay(0) turns off animation - -def blackWhite (color): - if color >= 255 / 2: - return 255 - else: - return 0 - -for row in range(img.getHeight()): - for col in range(img.getWidth()): - p = img.getPixel(col, row) - - newred = blackWhite(p.getRed()) - newgreen = blackWhite(p.getGreen()) - newblue = blackWhite(p.getBlue()) - - newpixel = image.Pixel(newred, newgreen, newblue) - - img.setPixel(col, row, newpixel) - -img.draw(win) -win.exitonclick() -``` - -The result was: - -![](Exercises/2_image.png) - -Close, but not quite. I needed black and white, not high contrast. But my intuition was in the ballpark. I figured that this would work better if I actually took the solution I got from the grey scale problem and then turned _that_ black and white. So, I went back to Problem 8, turned my solution into a function and then fixed up the code for this problem like this: - -```text-x-python -import image - -def greyScale (red, blue, green): - return (red + blue + green)/3 - -def blackWhite (color): - if color >= 255 / 2: - return 255 - else: - return 0 - -img = image.Image("luther.jpg") -win = image.ImageWin(img.getWidth(), img.getHeight()) -img.draw(win) -img.setDelay(0) # setDelay(0) turns off animation - -for row in range(img.getHeight()): - for col in range(img.getWidth()): - p = img.getPixel(col, row) - - pixelColor = greyScale(p.getRed(), p.getGreen(), p.getBlue()) - - newblue = newgreen = newred = blackWhite(pixelColor) - - newpixel = image.Pixel(newred, newgreen, newblue) - - img.setPixel(col, row, newpixel) - -img.draw(win) -win.exitonclick() -``` - -![](Exercises/5_image.png) - -### Problem 10 - -> Sepia Tone images are those brownish colored images that may remind you of times past. The formula for creating a sepia tone is as follows: -> -> ```text-plain -> newR = (R × 0.393 + G × 0.769 + B × 0.189) -> newG = (R × 0.349 + G × 0.686 + B × 0.168) -> newB = (R × 0.272 + G × 0.534 + B × 0.131) -> ``` -> -> Write a function to convert an image to sepia tone. _Hint:_ Remember that rgb values must be integers between 0 and 255. - -This didn't take too much effort since they gave me the formula. Just sharing, because I think it's cool. - -```text-x-python -import image - - -img = image.Image("luther.jpg") -win = image.ImageWin(img.getWidth(), img.getHeight()) -img.draw(win) -img.setDelay(0) # setDelay(0) turns off animation - - -for row in range(img.getHeight()): - for col in range(img.getWidth()): - p = img.getPixel(col, row) - - R = p.getRed() - G = p.getGreen() - B = p.getBlue() - - newred = (R * 0.393 + G * 0.769 + B * 0.189) - newgreen = (R * 0.349 + G * 0.686 + B * 0.168) - newblue = (R * 0.272 + G * 0.534 + B * 0.131) - - newpixel = image.Pixel(newred, newgreen, newblue) - - img.setPixel(col, row, newpixel) - -img.draw(win) -win.exitonclick() -``` - -Result: - -![](Exercises/6_image.png) \ No newline at end of file diff --git a/thinkcspy/Chapter-8-Exercises/Exercises/1_image.png b/thinkcspy/Chapter-8-Exercises/Exercises/1_image.png deleted file mode 100644 index e2ef8b1..0000000 Binary files a/thinkcspy/Chapter-8-Exercises/Exercises/1_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-8-Exercises/Exercises/2_image.png b/thinkcspy/Chapter-8-Exercises/Exercises/2_image.png deleted file mode 100644 index be8e001..0000000 Binary files a/thinkcspy/Chapter-8-Exercises/Exercises/2_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-8-Exercises/Exercises/3_image.png b/thinkcspy/Chapter-8-Exercises/Exercises/3_image.png deleted file mode 100644 index b6fdd2f..0000000 Binary files a/thinkcspy/Chapter-8-Exercises/Exercises/3_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-8-Exercises/Exercises/4_image.png b/thinkcspy/Chapter-8-Exercises/Exercises/4_image.png deleted file mode 100644 index 3d0a99e..0000000 Binary files a/thinkcspy/Chapter-8-Exercises/Exercises/4_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-8-Exercises/Exercises/5_image.png b/thinkcspy/Chapter-8-Exercises/Exercises/5_image.png deleted file mode 100644 index 64d239b..0000000 Binary files a/thinkcspy/Chapter-8-Exercises/Exercises/5_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-8-Exercises/Exercises/6_image.png b/thinkcspy/Chapter-8-Exercises/Exercises/6_image.png deleted file mode 100644 index 35eef0d..0000000 Binary files a/thinkcspy/Chapter-8-Exercises/Exercises/6_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-8-Exercises/Exercises/7_image.png b/thinkcspy/Chapter-8-Exercises/Exercises/7_image.png deleted file mode 100644 index 1b28a35..0000000 Binary files a/thinkcspy/Chapter-8-Exercises/Exercises/7_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-8-Exercises/Exercises/8_image.png b/thinkcspy/Chapter-8-Exercises/Exercises/8_image.png deleted file mode 100644 index 2563f35..0000000 Binary files a/thinkcspy/Chapter-8-Exercises/Exercises/8_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-8-Exercises/Exercises/LutherBellPic.jpg b/thinkcspy/Chapter-8-Exercises/Exercises/LutherBellPic.jpg deleted file mode 100644 index c5c64bd..0000000 Binary files a/thinkcspy/Chapter-8-Exercises/Exercises/LutherBellPic.jpg and /dev/null differ diff --git a/thinkcspy/Chapter-8-Exercises/Exercises/image.png b/thinkcspy/Chapter-8-Exercises/Exercises/image.png deleted file mode 100644 index 69c2f49..0000000 Binary files a/thinkcspy/Chapter-8-Exercises/Exercises/image.png and /dev/null differ diff --git a/thinkcspy/Chapter-8-Exercises/Exercises/turtlemoves-2023-09-29_11.47.3.gif b/thinkcspy/Chapter-8-Exercises/Exercises/turtlemoves-2023-09-29_11.47.3.gif deleted file mode 100644 index 0037dce..0000000 Binary files a/thinkcspy/Chapter-8-Exercises/Exercises/turtlemoves-2023-09-29_11.47.3.gif and /dev/null differ diff --git a/thinkcspy/Chapter-8-Exercises/Python-files/Lab.py b/thinkcspy/Chapter-8-Exercises/Lab.py similarity index 100% rename from thinkcspy/Chapter-8-Exercises/Python-files/Lab.py rename to thinkcspy/Chapter-8-Exercises/Lab.py diff --git a/thinkcspy/Chapter-8-Exercises/Lab_Experimenting_with_the_3n+1_Sequence/Lab Experimenting With the 3n+.md b/thinkcspy/Chapter-8-Exercises/Lab_Experimenting_with_the_3n+1_Sequence/Lab Experimenting With the 3n+.md deleted file mode 100644 index 913bba1..0000000 --- a/thinkcspy/Chapter-8-Exercises/Lab_Experimenting_with_the_3n+1_Sequence/Lab Experimenting With the 3n+.md +++ /dev/null @@ -1,125 +0,0 @@ -# Lab: Experimenting With the 3n+1 Sequence -Instructions ------------- - -In this lab my job was to take the initial code, graph the iterations and find the max number of iterations from one of the 50 sequence starts.  - -Initial Code ------------- - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 8 -# Lab - -def seq3np1(n): - """ Print the 3n+1 sequence from n, terminating when it reaches 1.""" - - while n != 1: - print(n) - if n % 2 == 0: # n is even - n = n // 2 - else: # n is odd - n = n * 3 + 1 - print(n) # the last print is 1 -``` - -My Code -------- - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 8 -# Lab - -import turtle - -border = 10 - -def writeData(tt, itr, height): - tt.goto(0-border, 0-border) - tt.up() - - if height >= 100: - tt.left(90) - tt.forward(height+20) - tt.right(90) - tt.forward(itr*39) - tt.write(str(height), move=False, align='center', font=('Times New Roman', 30, 'normal')) - tt.forward(70) - tt.write(str(itr), move=False, align='center', font=('Times New Roman', 30, 'normal')) - else: # this is here so the last bar actually fills - tt.left(90) - tt.forward(height) - tt.right(90) - tt.forward(itr*40) - tt.right(90) - tt.forward(height) - 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 - - -def seq3np1(n): - """ Print the 3n+1 sequence from n, terminating when it reaches 1.""" - count = 1 - - while n != 1: - count += 1 - - #print(n) - if n % 2 == 0: # n is even - n = n // 2 - else: # n is odd - n = n * 3 + 1 - #print(n) # the last print is 1 - #print(count) - return count - - -wn = turtle.Screen() # Set up the window and its attributes -wn.setworldcoordinates(0-border, 0-border, 40*50+border, 150) -wn.bgcolor("lightblue") -wn.tracer(100) - -tess = turtle.Turtle() # create tess and set some attributes -tess.color("purple") -tess.fillcolor("magenta") -tess.pensize(3) - -alex = turtle.Turtle() -alex.color("purple") - -maxSoFar = 0 - -for i in range(50): - start = i + 1 - result = seq3np1(start) - - #print("Number of iterations to get to '1' from", start, ":", result) - - drawBar(tess, result) - writeData(alex, start, result) - - if result > maxSoFar: - maxSoFar = result - -print("The max number of iterations was", maxSoFar, "from sequence start", start) -``` - -Result ------- - -![](Lab%20Experimenting%20With%20the%203n%2B1%20Sequence/image.png) - -The numbers are not very readable, but it gets the job done. \ No newline at end of file diff --git a/thinkcspy/Chapter-8-Exercises/Lab_Experimenting_with_the_3n+1_Sequence/Lab Experimenting With the 3n+1 Sequence/image.png b/thinkcspy/Chapter-8-Exercises/Lab_Experimenting_with_the_3n+1_Sequence/Lab Experimenting With the 3n+1 Sequence/image.png deleted file mode 100644 index 6e7252d..0000000 Binary files a/thinkcspy/Chapter-8-Exercises/Lab_Experimenting_with_the_3n+1_Sequence/Lab Experimenting With the 3n+1 Sequence/image.png and /dev/null differ diff --git a/thinkcspy/Chapter-8-Exercises/Python-files/Problem10.py b/thinkcspy/Chapter-8-Exercises/Problem10.py similarity index 100% rename from thinkcspy/Chapter-8-Exercises/Python-files/Problem10.py rename to thinkcspy/Chapter-8-Exercises/Problem10.py diff --git a/thinkcspy/Chapter-8-Exercises/Python-files/Problem2.py b/thinkcspy/Chapter-8-Exercises/Problem2.py similarity index 100% rename from thinkcspy/Chapter-8-Exercises/Python-files/Problem2.py rename to thinkcspy/Chapter-8-Exercises/Problem2.py diff --git a/thinkcspy/Chapter-8-Exercises/Python-files/Problem3.py b/thinkcspy/Chapter-8-Exercises/Problem3.py similarity index 100% rename from thinkcspy/Chapter-8-Exercises/Python-files/Problem3.py rename to thinkcspy/Chapter-8-Exercises/Problem3.py diff --git a/thinkcspy/Chapter-8-Exercises/Python-files/Problem6.py b/thinkcspy/Chapter-8-Exercises/Problem6.py similarity index 100% rename from thinkcspy/Chapter-8-Exercises/Python-files/Problem6.py rename to thinkcspy/Chapter-8-Exercises/Problem6.py diff --git a/thinkcspy/Chapter-8-Exercises/Python-files/Problem8.py b/thinkcspy/Chapter-8-Exercises/Problem8.py similarity index 100% rename from thinkcspy/Chapter-8-Exercises/Python-files/Problem8.py rename to thinkcspy/Chapter-8-Exercises/Problem8.py diff --git a/thinkcspy/Chapter-8-Exercises/Python-files/Problem9.py b/thinkcspy/Chapter-8-Exercises/Problem9.py similarity index 100% rename from thinkcspy/Chapter-8-Exercises/Python-files/Problem9.py rename to thinkcspy/Chapter-8-Exercises/Problem9.py diff --git a/thinkcspy/Chapter-9-Exercises/Exercises.md b/thinkcspy/Chapter-9-Exercises/Exercises.md deleted file mode 100644 index fa7da3c..0000000 --- a/thinkcspy/Chapter-9-Exercises/Exercises.md +++ /dev/null @@ -1,769 +0,0 @@ -# Exercises -This one was fun! I had no idea that manipulating strings could be as interesting as manipulating numbers or pixels. These exercises were certainly some of the more challenging ones thus far, but I got through them all! - -Problem 3 ---------- - -> Assign to a variable in your program a triple-quoted string that contains your favorite paragraph of text - perhaps a poem, a speech, instructions to bake a cake, some inspirational verses, etc. -> -> Write a function that counts the number of alphabetic characters (a through z, or A through Z) in your text and then keeps track of how many are the letter ‘e’. Your function should print an analysis of the text like this: -> -> ```text-plain -> Your text contains 243 alphabetic characters, of which 109 (44.8%) are 'e'. -> ``` - -My Solution: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem 3 - -import string - -def count(p): - # your code here - abc = 0 - e = 0 - alphabet = string.ascii_lowercase + string.ascii_uppercase - - for achar in p: - for alphaChar in alphabet: - if achar == alphaChar: - abc += 1 - if achar == "e" or achar == "E": - e += 1 - - if abc != 0: - ePerAbc = e / abc * 100 - else: - ePerAbc = 0 - - finalMsg = "Your text contains {} alphabetic characters, of which {} ({:.1f}%) are 'e'.".format(abc, e, ePerAbc) - - return finalMsg - -text = "Bell of the ball" -print(count(text)) -``` - -Result: - -![](Exercises/3_image.png) - -I failed a lot of the built in tests for this one, but the output is is fine. I think they were looking for individual variables to be returned somewhere, maybe in separate functions.  - -I looked at the answer for this one to see if I was missing anything, and the answer provided also failed the built in tests due to a division be zero error so uh… I'm going to table this one and call it a win.  - -Here is their code and the results: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Answer 3 - -def count(p): - lows = "abcdefghijklmnopqrstuvwxyz" - ups = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - - numberOfe = 0 - totalChars = 0 - for achar in p: - if achar in lows or achar in ups: - totalChars = totalChars + 1 - if achar == 'e': - numberOfe = numberOfe + 1 - - percent_with_e = (numberOfe / totalChars) * 100 - print("Your text contains", totalChars, "alphabetic characters of which", numberOfe, "(", percent_with_e, "%)", "are 'e'.") - - -p = ''' -"If the automobile had followed the same development cycle as the computer, a -Rolls-Royce would today cost $100, get a million miles per gallon, and explode -once a year, killing everyone inside." --Robert Cringely -''' - -count(p) -``` - -![](Exercises/4_image.png) - -Problem 4 ---------- - -> Print out a neatly formatted multiplication table, up to 12 x 12. - -My code: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem 4 - -# your code here - -num1 = 1 -product = 0 - -for n in range(12): - num2 = 1 - row = "" - - for x in range(12): - product = num1 * num2 - row += "{} \t".format(product) - num2 += 1 - - print(row) - num1 += 1 -``` - -![](Exercises/image.png) - -Problem 5 ---------- - -> Write a function that will return the number of digits in an integer. - -My code: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem - -def numDigits(n): - # your code here - toText = str(n) - count = 0 - - for i in range (len(toText)): - count += 1 - - return count - -print(numDigits(13)) -``` - -Result: - -![](Exercises/1_image.png) - -The Letter Problems -------------------- - -The following three problems are very interrelated. I would work on one and realize the previous one needed to be changed too. Strap in, because this next section is hella long.  - -### Problem 10 - -> Write a function that counts how many non-overlapping occurences of a substring appear in a string. - -For such a short piece of code, this one really threw me for a loop. First, I had to get help figuring out exactly what “non-overlapping occurrences” meant in the context of a string, lol (_"anan"_ has overlapping occurrences of _“an”_, _“panpan”_ does not). Then, I had to figure out moving through the text by substring while also comparing more than just the first occurrence of that substring. Finally, I had to make sure the program understood _when to count_, which was tightly connected with how the program moved through the string.  - -Hopefully my code can explain this better than I can in English: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem 10 - -def count(substr,theStr): - # your code here - count = 0 - char = 0 - pos1 = 0 - pos2 = len(substr) - charPos = len(substr) + 1 - - while char < len(theStr): - if substr == theStr[pos1:pos2]: - count += 1 - char += charPos - else: - char += 1 - - pos1 += 1 - pos2 += 1 - - return count - -print(count("e", "tree")) -``` - -Result: - -![](Exercises/2_image.png) - -~I'm really glad this one had unit tests on it, because it helped me validate if I understood the instructions and if I gave the program the right instructions. This problem alone is a great practice for “thinking like a computer scientist” as it were.~  - -That test didn't mean shit. When I went to the next problem, I realized there was a problem with the program, even though my initial tests and the built in checks checked out.  - -The problem was that my solution broke down when the program looked for only 1 character. When I put a non repeating character in between repeating characters like in _"banana"_, and looked for _"a"_, the program only counted _two “a's” instead of three, even though the “a's” were not “overlapping occurrences”._  - -I eventually realized that I needed to move through the string differently for single characters in a non-overlapping context, so I added this conditional block to the existing one (I changed `char` to `charCount` because the latter makes more sense for the use of the variable): - -```text-x-python -elif len(substr) == 1 and substr == theStr[pos1:pos2]: - count += 1 - charCount += 1 -``` - -But now I had a different problem. The original version of the code was working perfectly fine for words like “tree”. This additional code, now meant that overlapping characters in these types of words, were being counted. That meant that I either needed to modify an existing condition or add another conditional block.  - -I opted to modify an existing condition, the original `if` block, and test if the next letter was the same as the current. Great test, but by this point I began playing a game of whack-a-mole. The thing that fixed tests for words like “tree” broke tests words like “banana”, especially when the last letter of the word just so happened to be the letter the program was looking for.  - -Eventually I switched the order of the if and elif blocks, because that simplified the program and kept the conditions from becoming monstrously long and difficult to understand. Then, I finally had the good sense to check if `pos2` was numerically equivalent to the length of the string. This way the program wouldn't keep looking for an index position that was out of range (because computers count from 0… not 1). - -And with that, I finally found something that, to the best of my current knowledge, could handle any length of strings and substrings given to it. Here's the final code: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem 10 - -def count(substr,theStr): - # your code here - count = 0 - charCount = 0 - pos1 = 0 - pos2 = len(substr) - charPos = len(substr) - - while charCount < len(theStr): - if charPos == 1 and substr == theStr[pos1] and (pos2 == len(theStr) or substr != theStr[pos2]): - count += 1 - charCount += 1 - elif substr == theStr[pos1:pos2]: - count += 1 - charCount += charPos + 1 - else: - charCount += 1 - - - pos1 += 1 - pos2 += 1 - - return count - -print(count("e", "treeleee")) -``` - -I used `treeleee` as a test, because it allowed me to test for all the conditions that I had failed before finding this solution. By those metrics, this bit of code took me to the finish line. Below are the results: - -![](Exercises/5_image.png) - -Also, this is the 2nd built in test to fall short in these exercises. I'll probably be a little less excited when I pass them and less concerned when I don't. - -### Problem 11 - -> Write a function that removes the first occurrence of a string from another string. - -So I started with this and then realized there was an issue with the program and went back to problem 10 to fix it.  - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem 11 - -def remove(substr,theStr): - # your code here - char = 0 - pos1 = 0 - pos2 = len(substr) - found = False - newStr = "" - - while char < len(theStr) and not found: - currentPos = theStr[pos1:pos2] - if substr == currentPos: - found = True - else: - char += 1 - newStr = theStr[:pos2] - - pos1 += 1 - pos2 += 1 - - newStr += theStr[pos2:] - - return newStr - -print(remove("e", "tree")) -``` - -Then I came back with this: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem 11 - -def remove(substr,theStr): - # your code here - count = 0 - charCount = 0 - pos1 = 0 - pos2 = len(substr) - charPos = len(substr) - found = False - newStr = "" - - while charCount < len(theStr) and not found: - if charPos == 1 and substr == theStr[pos1] and (pos2 == len(theStr) or substr != theStr[pos2]): - count += 1 - charCount += 1 - found = True - elif substr == theStr[pos1:pos2]: - count += 1 - charCount += charPos + 1 - found = True - else: - charCount += 1 - newStr = theStr[:pos2] - - pos1 += 1 - pos2 += 1 - - newStr += theStr[pos2:] - - return newStr - -print(remove("e", "tree")) -``` - -Well… this code basically does the same thing as the previous bit of code, so I went back to the previous one, because why have more complicated code to do essentially the same thing? - -The problem (or at least one of the problems) in my code was here: - -```text-x-python -else: - char += 1 - newStr = theStr[:pos2] -``` - -Specifically, the way I coded `newStr`. If there is no match. it takes everything up to `pos2` which, by nature of how I wrote the code, includes code that I actually wanted to take out! - -I realized that I didn't actually need to change `newStr` in the `else` block. I actually needed to change it in the `if` block, and I needed to create another conditional block to finish constructing the word based on whether or not the substring was found: - -```text-x-python -if found: - newStr += theStr[pos2-1:] -else: - newStr = theStr -``` - -And wallah, it worked! Here is the ~final~ code (I changed a variable name for the same reason I changed it in the previous problem): - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem 11 - -def remove(substr,theStr): - # your code here - charCount = 0 - pos1 = 0 - pos2 = len(substr) - found = False - newStr = "" - - while charCount < len(theStr) and not found: - currentPos = theStr[pos1:pos2] - if substr == currentPos: - newStr = theStr[:pos1] - found = True - else: - charCount += 1 - - pos1 += 1 - pos2 += 1 - - if found: - newStr += theStr[pos2-1:] - else: - newStr = theStr - - return newStr - -print(remove("e", "tree")) -print(remove("iss", "Mississippi")) -print(remove("an", "banana")) -print(remove("e", "treeeleee")) -``` - -Results: - -![](Exercises/6_image.png) - -But now… I had a new challenge…  - -### Problem 12 - -> Write a function that removes all occurrences of a string from another string. - -My initial logic was to break the initial `while` statement of the previous solution into nesting `while` statements and initialize in the variables in the first one: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem 12 - -def remove_all(substr,theStr): - # your code here - charCount = 0 - - while charCount < len(theStr): - pos1 = 0 - pos2 = len(substr) - found = False - newStr = "" - - while not found: - currentPos = theStr[pos1:pos2] - if substr == currentPos: - newStr = theStr[:pos1] - found = True - else: - charCount += 1 - - pos1 += 1 - pos2 += 1 - - if found: - newStr += theStr[pos2-1:] - else: - newStr = theStr - - return newStr - -print(remove_all("e", "tree")) -print(remove_all("iss", "Mississippi")) -print(remove_all("an", "banana")) -print(remove_all("e", "treeeleee")) -``` - -I may as well had not made any changes at all, because it just gave the same results as if the code were the exact same.  - -Then, I realized that, unlike in the first problem, I actually needed to adjust `newStr` in an `else` statement, or more specifically in an `elif` statement to test if the condition had been found: - -```text-x-python -elif not found: - charCount += 1 - newStr = theStr[:pos1+1] -``` - -This block ensured that I still had any characters that existed before any matches were found. But I still had the issue of adding characters after any matches were found. I had bunch of failed ideas, but finally I came up with one that produced better results: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem 12 - -def remove_all(substr,theStr): - # your code here - charCount = 0 - pos1 = 0 - pos2 = len(substr) - newStr = theStr - - while charCount < len(newStr): - currentPos = newStr[pos1:pos2] - - if substr == currentPos: - newStr = newStr[:pos1+1] + newStr[pos2+1:] - charCount += 1 - else: - pos1 += 1 - pos2 += 1 - charCount += 1 - - return newStr - -print(remove_all("e", "tree")) -print(remove_all("iss", "Mississippi")) -print(remove_all("an", "banana")) -print(remove_all("e", "treeeleee")) -``` - -I took out everything related to the `found` variable, because I no longer needed to stop the program once the first instance of `substr` was found. I then moved the iteration of `pos1` and `pos2` to the `else` block, because if nothing was found, then we needed to move on to the next set of characters, but _only if nothing was found._  - -~T~his allowed me to pass most of the built in checks and half my own~, but there was still a piece missing~. Actually, there were too many pieces.  - -It turns out that I didn't need to add to `pos1` and `pos2` when recreating `newStr`, because the end of an index is excluded and the beginning is excluded. Additionally, the variable I needed to test for in the while loop was actually `pos1`. `charCount` was redundant. Turns out, it was redundant in the previous problem's code too.  - -Here's the final code: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem 12 - -def remove_all(substr,theStr): - # your code here - pos1 = 0 - pos2 = len(substr) - newStr = theStr - - while pos1 < len(newStr): - currentPos = newStr[pos1:pos2] - - if substr == currentPos: - newStr = newStr[:pos1] + newStr[pos2:] - else: - pos1 += 1 - pos2 += 1 - - return newStr - - -print(remove_all("e", "treeeleee")) -``` - -Results: - -![](Exercises/7_image.png) - -And the _actual_ final code for problem 11: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem 11 - -def remove(substr,theStr): - # your code here - pos1 = 0 - pos2 = len(substr) - found = False - newStr = theStr - - while pos1 < len(newStr) and not found: - currentPos = newStr[pos1:pos2] - - if substr == currentPos: - newStr = newStr[:pos1] + newStr[pos2:] - found = True - else: - pos1 += 1 - pos2 += 1 - - return newStr - -print(remove("e", "tree")) -print(remove("iss", "Mississippi")) -print(remove("an", "banana")) -print(remove("e", "treeeleee")) -``` - -Results: - -![](Exercises/8_image.png) - -Problem 14 ----------- - -> Here is a dragon curve. Use 90 degrees.: -> -> ```text-plain -> FX -> X -> X+YF+ -> Y -> -FX-Y -> ``` - -Most of this code came from the lesson on L-Systems in this chapter. I'm just including it here, because I think it's cool and wanted to show at least one of these types of problems in this set of exercises.  - -The code: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem 14 - -# Your code here -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 == 'X': - newstr = 'X+YF+' # Rule 1 - elif ch == 'Y': - newstr = '-FX-Y' # Rule 2 - else: - newstr = ch # no rules apply so keep the character - - return newstr - -def drawLsystem(aTurtle, instructions, angle, distance): - 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) - -def main(): - inst = createLSystem(10, "FX") # create the string - print(inst) - t = turtle.Turtle() # create the turtle - wn = turtle.Screen() - wn.tracer(10) - - t.up() - t.back(100) - t.down() - t.speed(0) - drawLsystem(t, inst, 90, 5) # draw the picture - # angle 90, segment length 5 - wn.exitonclick() - -main() -``` - -Results: - -I'm just including the visual result, because the text is just a _very loooonng_ string of repeating `FX+YF++-FX-YF++-FX+YF+--`. - -![](Exercises/12_image.png) - -Encrypt, Decrypt ----------------- - -I needed a little help figuring out transferring one index to the other, but once I got that, it was smooth sailing from there.  - -### Problem 18 - -> Write a function that implements a substitution cipher. In a substitution cipher one letter is substituted for another to garble the message. For example A -> Q, B -> T, C -> G etc. your function should take two parameters, the message you want to encrypt, and a string that represents the mapping of the 26 letters in the alphabet. Your function should return a string that is the encrypted version of the message. - -My code: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem 18 - -import string - -def encrypt(msg, code): - alpha = string.ascii_lowercase - newStr = "" - pos = 0 - msg = msg.lower() - - for char in msg: - if char in alpha: - pos = alpha.index(char) - newStr += newAlpha[pos] - else: - newStr += char # no rules apply so keep the character - - return newStr - -newAlpha = "qwertyuiopasdfghjklzxcvbnm" - -print(encrypt("Hello World!", newAlpha)) -``` - -Result: - -![](Exercises/9_image.png) - -### Problem 19 - -> Write a function that decrypts the message from the previous exercise. It should also take two parameters. The encrypted message, and the mixed up alphabet. The function should return a string that is the same as the original unencrypted message. - -I literally just had to switch the role of the two indexes: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem 19 - -import string - -def decrypt(msg, code): - alpha = string.ascii_lowercase - newStr = "" - pos = 0 - msg = msg.lower() - - for char in msg: - if char in alpha: - pos = newAlpha.index(char) - newStr += alpha[pos] - else: - newStr += char # no rules apply so keep the character - - return newStr - -newAlpha = "qwertyuiopasdfghjklzxcvbnm" - -print(decrypt("itssg vgksr!", newAlpha)) -``` - -![](Exercises/10_image.png) - -### Problem 21 - -> Write a function called `rot13` that uses the Caesar cipher to encrypt a message. The Caesar cipher works like a substitution cipher but each character is replaced by the character 13 characters to ‘its right’ in the alphabet. So for example the letter a becomes the letter n. If a letter is past the middle of the alphabet then the counting wraps around to the letter a again, so n becomes a, o becomes b and so on. _Hint:_ Whenever you talk about things wrapping around its a good idea to think of modulo arithmetic. - -That hint at the end was really helpful. The one thing I messed up on was forgetting that lists in programming languages tend to start at 0 instead of 1. I had to print `pos` before I figured out what the issue was, but once I did, it was an easy fix. Here's the final code: - -```text-x-python -# Runestone.Academy thinkcspy course -# Chapter 9 -# Problem 21 - -import string - -def rot13(mess): - # Your code here - alpha = string.ascii_lowercase - newStr = "" - pos = 0 - mess = mess.lower() - - for char in mess: - if char in alpha: - pos = alpha.index(char) - - if pos <= 12: - pos += 13 - else: - pos = pos % 13 - - newStr += alpha[pos] - - else: - newStr += char # no rules apply so keep the character - - return newStr - -print(rot13('abcde')) -print(rot13('nopqr')) -print(rot13(rot13('Since rot13 is symmetric you should see this message'))) -``` - -Results: - -![](Exercises/11_image.png) \ No newline at end of file diff --git a/thinkcspy/Chapter-9-Exercises/Exercises/10_image.png b/thinkcspy/Chapter-9-Exercises/Exercises/10_image.png deleted file mode 100644 index 3ca7731..0000000 Binary files a/thinkcspy/Chapter-9-Exercises/Exercises/10_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-9-Exercises/Exercises/11_image.png b/thinkcspy/Chapter-9-Exercises/Exercises/11_image.png deleted file mode 100644 index 20c5fcb..0000000 Binary files a/thinkcspy/Chapter-9-Exercises/Exercises/11_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-9-Exercises/Exercises/12_image.png b/thinkcspy/Chapter-9-Exercises/Exercises/12_image.png deleted file mode 100644 index 07bf4c9..0000000 Binary files a/thinkcspy/Chapter-9-Exercises/Exercises/12_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-9-Exercises/Exercises/1_image.png b/thinkcspy/Chapter-9-Exercises/Exercises/1_image.png deleted file mode 100644 index 17a56d3..0000000 Binary files a/thinkcspy/Chapter-9-Exercises/Exercises/1_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-9-Exercises/Exercises/2_image.png b/thinkcspy/Chapter-9-Exercises/Exercises/2_image.png deleted file mode 100644 index a49e5a7..0000000 Binary files a/thinkcspy/Chapter-9-Exercises/Exercises/2_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-9-Exercises/Exercises/3_image.png b/thinkcspy/Chapter-9-Exercises/Exercises/3_image.png deleted file mode 100644 index d0e1ae1..0000000 Binary files a/thinkcspy/Chapter-9-Exercises/Exercises/3_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-9-Exercises/Exercises/4_image.png b/thinkcspy/Chapter-9-Exercises/Exercises/4_image.png deleted file mode 100644 index ac3750c..0000000 Binary files a/thinkcspy/Chapter-9-Exercises/Exercises/4_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-9-Exercises/Exercises/5_image.png b/thinkcspy/Chapter-9-Exercises/Exercises/5_image.png deleted file mode 100644 index 632c8ad..0000000 Binary files a/thinkcspy/Chapter-9-Exercises/Exercises/5_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-9-Exercises/Exercises/6_image.png b/thinkcspy/Chapter-9-Exercises/Exercises/6_image.png deleted file mode 100644 index e0ecf0f..0000000 Binary files a/thinkcspy/Chapter-9-Exercises/Exercises/6_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-9-Exercises/Exercises/7_image.png b/thinkcspy/Chapter-9-Exercises/Exercises/7_image.png deleted file mode 100644 index 242d40d..0000000 Binary files a/thinkcspy/Chapter-9-Exercises/Exercises/7_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-9-Exercises/Exercises/8_image.png b/thinkcspy/Chapter-9-Exercises/Exercises/8_image.png deleted file mode 100644 index 8ead9db..0000000 Binary files a/thinkcspy/Chapter-9-Exercises/Exercises/8_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-9-Exercises/Exercises/9_image.png b/thinkcspy/Chapter-9-Exercises/Exercises/9_image.png deleted file mode 100644 index 32306b4..0000000 Binary files a/thinkcspy/Chapter-9-Exercises/Exercises/9_image.png and /dev/null differ diff --git a/thinkcspy/Chapter-9-Exercises/Exercises/image.png b/thinkcspy/Chapter-9-Exercises/Exercises/image.png deleted file mode 100644 index c68cc26..0000000 Binary files a/thinkcspy/Chapter-9-Exercises/Exercises/image.png and /dev/null differ diff --git a/thinkcspy/Chapter-9-Exercises/Python-files/Problem10.py b/thinkcspy/Chapter-9-Exercises/Problem10.py similarity index 100% rename from thinkcspy/Chapter-9-Exercises/Python-files/Problem10.py rename to thinkcspy/Chapter-9-Exercises/Problem10.py diff --git a/thinkcspy/Chapter-9-Exercises/Python-files/Problem11.py b/thinkcspy/Chapter-9-Exercises/Problem11.py similarity index 100% rename from thinkcspy/Chapter-9-Exercises/Python-files/Problem11.py rename to thinkcspy/Chapter-9-Exercises/Problem11.py diff --git a/thinkcspy/Chapter-9-Exercises/Python-files/Problem12.py b/thinkcspy/Chapter-9-Exercises/Problem12.py similarity index 100% rename from thinkcspy/Chapter-9-Exercises/Python-files/Problem12.py rename to thinkcspy/Chapter-9-Exercises/Problem12.py diff --git a/thinkcspy/Chapter-9-Exercises/Python-files/Problem14.py b/thinkcspy/Chapter-9-Exercises/Problem14.py similarity index 100% rename from thinkcspy/Chapter-9-Exercises/Python-files/Problem14.py rename to thinkcspy/Chapter-9-Exercises/Problem14.py diff --git a/thinkcspy/Chapter-9-Exercises/Python-files/Problem18.py b/thinkcspy/Chapter-9-Exercises/Problem18.py similarity index 100% rename from thinkcspy/Chapter-9-Exercises/Python-files/Problem18.py rename to thinkcspy/Chapter-9-Exercises/Problem18.py diff --git a/thinkcspy/Chapter-9-Exercises/Python-files/Problem19.py b/thinkcspy/Chapter-9-Exercises/Problem19.py similarity index 100% rename from thinkcspy/Chapter-9-Exercises/Python-files/Problem19.py rename to thinkcspy/Chapter-9-Exercises/Problem19.py diff --git a/thinkcspy/Chapter-9-Exercises/Python-files/Problem21.py b/thinkcspy/Chapter-9-Exercises/Problem21.py similarity index 100% rename from thinkcspy/Chapter-9-Exercises/Python-files/Problem21.py rename to thinkcspy/Chapter-9-Exercises/Problem21.py diff --git a/thinkcspy/Chapter-9-Exercises/Python-files/Problem3.py b/thinkcspy/Chapter-9-Exercises/Problem3.py similarity index 100% rename from thinkcspy/Chapter-9-Exercises/Python-files/Problem3.py rename to thinkcspy/Chapter-9-Exercises/Problem3.py diff --git a/thinkcspy/Chapter-9-Exercises/Python-files/Problem4.py b/thinkcspy/Chapter-9-Exercises/Problem4.py similarity index 100% rename from thinkcspy/Chapter-9-Exercises/Python-files/Problem4.py rename to thinkcspy/Chapter-9-Exercises/Problem4.py diff --git a/thinkcspy/Chapter-9-Exercises/Python-files/Problem5.py b/thinkcspy/Chapter-9-Exercises/Problem5.py similarity index 100% rename from thinkcspy/Chapter-9-Exercises/Python-files/Problem5.py rename to thinkcspy/Chapter-9-Exercises/Problem5.py