allendowney / thinkpython2 Goto Github PK
View Code? Open in Web Editor NEWLaTeX source and supporting code for Think Python, 2nd edition, by Allen Downey.
License: Other
LaTeX source and supporting code for Think Python, 2nd edition, by Allen Downey.
License: Other
It appears that the function rotate_pairs (solution for Exercise 11.5) does not check for all rotated words, due to the stop argument of the range being 14 instead of 26. For example, passing the word "act" as argument should print out "act 24 yar", but currently does not print out anything. It's also possible to avoid iterating through all possible rotated words for each word in the list of words.
In section 16.2, the function add_time
has sum
as local variable. But sum
is a built-in function.
This may work but it might be considered as a bad habit to use built-in function names as variable names.
I guess that sum
can be replaced, in this particular context, by totaltime
(or simply total
).
In exercise 8.3, we read
A step size of 2 means every other character;(...).
As non native English reader, I get confuse: is every other
an idiom that means every two
?
I would favour plain English.
Hi, I'm having an hard time generating an epub version of the book on windows.
Sadly I haven't found any version of hevea for windows, and I would need to install Ubuntu or another linux distro just to compile the book to epub (and it will not be sure that I will be able to compile it, since from what I've understand the process is very difficult)
Could you please provide an updated epub version of the latest version of the book? (Which I think it is 2.4.0)
Thanks
In order to build the book on Ubuntu 16.04 with make all
I had to install the following packages:
The first one is pretty obvious, but the other two I only discovered I had to install after doing research to decode some incomprehensible error messages.
The glossary for chapter 1 contains the following glossary terms that are not covered in the body text of the chapter:
I think I remember that in an earlier version of Think Python, there was additional text that explained these concepts to some depth. But that text is not there any more…
rengaraj@toad:~/ThinkPython2/book$ make
makeindex book.idx
Input index file book.idx not found.
Usage: makeindex [-ilqrcgLT] [-s sty] [-o ind] [-t log] [-p num] [idx0 idx1 ...]
Makefile:20: recipe for target 'all' failed
make: *** [all] Error 1
for i in range(4):
bob.fd(100)
bob.lt(90)
from random import randint
print('Ghost Game')
feeling_brave = True
score = 0
while feeling_brave:
ghost_door = randint (1, 3)
print ('Three doors ahead...')
print ('A ghost behind one.')
print ('Which door do you open?')
door = input('1, 2, or 3?')
door_num = int(door)
if door_num == ghost_door:
print ('Ghost!')
feeling_brave = False
else:
print('No ghost!')
print ('You enter the next room.')
score = score + 1
print ('Run away!')
print ('Game over! You scored', score)
hi,
Thank you for your excellent book. A sharp-eyed student in my class raised a question with the circle function:
def circle(t, r):
circumference = 2 * math.pi * r
n = int(circumference / 3) + 1
length = circumference / n
polygon(t, n, length)
We are wondering if n should always be larger than 3, otherwise the polygon function wouldn't work.
So we should have this line instead:
n = int(circumference / 3) + 3
The relevant line in the tex source is here:
Line 3210 in 9b78593
The polygon function draws a regular n-sided polygon, defined this way:
def polygon(t, n, length):
angle = 360 / n
for i in range(n):
t.fd(length)
t.lt(angle)
Chapter 14.8 Pipes:
For example, most Unix systems provide a command called md5sum that reads the contents of a file and computes a “checksum”. You can read about MD5 at http://en.wikipedia.org/wiki/Md5. This command provides an efficient way to check whether two files have the same contents. The probability that different contents yield the same checksum is very small (that is, unlikely to happen before the universe collapses).
md5 hash collisions are easily generated now. Maybe a footnote is warranted?
Page 103
I love the book. It has really been amazing. Especially the example questions.
There was just one that was very unclear to me.
"Exercise 17.1. Download the code from this chapter from http: // thinkpython2. com/ code/
Time2. py . Change the attributes of Time to be a single integer representing seconds since midnight.
Then modify the methods (and the function int_to_time) to work with the new implementation.
You should not have to modify the test code in main. When you are done, the output should
be the same as before. Solution: http: // thinkpython2. com/ code/ Time2_ soln. py ."
If I can't modify the code in main() then how am I supposed to change the attributes of the Time class?
In main() it declares Time objects like "start = Time(9, 45, 00)"
If I change the attributes of time, then doesn't that mean that object class declaration will only include one number?
I would really love to read it in my e-reader :)
In chapter 15, it says the corner
attribute of the Rectangle
class "specifies the lower-left corner". However, it seems to me that function rect_in_circle
treats it as the upper-left corner. Shouldn't line 54 in Circle.py
be: p.y += rect.height
instead?
Exercise 1
The time module provides a function, also named time, that returns the current Greenwich Mean Time in “the epoch”, which is an arbitrary time used as a reference point. On UNIX systems, the epoch is 1 January 1970.>> import time >> time.time() 1437746094.5735958
Write a script that reads the current time and converts it to a time of day in hours, minutes, and seconds, plus the number of days since the epoch.
I think asking a student to convert the epoch into time of day might be a little too complicated for Exercise 1 of the chapter. Dates aren't the easiest subject to deal with this early into python. I was trying to use ThinkPython 2 to tutor a student today and found it to be far too advanced having just learned conditionals and floor division in the same chapter.
>>> # Part 1
>>> mydate = int(1437746094.5735958)
>>> num_days = mydate // 3600 // 24
>>> print(num_days, "days since epoch")
16640 days since epoch
>>> # Part 2
>>> midnight_on_mydate = num_days * 24 * 3600
>>>
>>> seconds_since_midnight = mydate - midnight_on_mydate
>>>
>>> hours = seconds_since_midnight // 3600
>>> minutes = (seconds_since_midnight - (hours * 3600)) // 60
>>> seconds = seconds_since_midnight - (hours * 3600 + minutes * 60)
>>>
>>> time_of_day = "%s:%s:%s" % (hours, minutes, seconds)
>>>
>>> print(time_of_day, "on", num_days, "days since epoch")
13:54:54 on 16640 days since epoch
Page 86
Page 89
Hi Allen
I've not found a better way to ask you this question than doing it here (since this is the source of the original English version, I think doing it here is not so bad).
Is there an up-to-date translation of ThinkPython2 to Spanish?
The only thing I've found is a translation made by Miguel Ángel Vilella, Ángel Arnal (among others), but it is dated back into 2002.
This semester, I'm using your book as a complement to my lectures at my University, but since I'm from Chile, not all the people are comfortable enough reading in English.
If there's anything I could do to help in this issue, just tell me.
Congratulations for your huge work in this book. This is something that has done an enormous impact, due to both its contents and its license.
It'd be nice to have the url text the same font throughout the book.
Hello Sir
Could you provide steps and requirements to compile the book in epub format?
Edit:
I came up after tinkering with the makefile and found out there are some commands issued in the makefile that were absent in my installation.
Finally was able to compile it in epub by installing these (additional to the tex packages mentioned in the readme):
sudo apt install hevea hoz calibre
Then i could finally issue
make epub
If i'm not mistaken, hevea brings the hevea and the imagen commands. Calibre is needed for the ebook-convert command, and hoz brings hacha
Fig 5-1 the letters get cut off on the left
The table on page 264 needs help (and we should check other tables)"
What bother me a bit is into classes and methods
: I find this restrictive. In language C
we can program in an oriented manner without involving classes and methods
. (Note that I have a good practice of C
but without a theoretical background in programming.)
In section 17.2, a double zero (00
) is used instead of a single zero (0
) to initiate start.second
to zero.
I think the boxes around the figures are unnecessary.
At present, grid.py has two iterations via the "exploratory process".
I wonder if another iteration would help future readers continue discerning the patterns.
Recognizing the grid as rows of repeated patterns, one may be able to restructure the code using a generalized 'row'.
By 'generalized row', I meant each row differs from each other, only by marker ('+' or '|') and filler('-' or ' '), hence its drawing can be encapsulated into one function with marker and filler as parameters.
This is the best book I have found for an introduction to Python. I have to ask if there is a book that is recommended after this one?
This book doesn't use any of the icons on page xiii -- can we drop them?
Can we get a Python 2 icon to mark the places where I discuss Python 2? (There are only 4-5 of them)
Inexpressively written:
Page 4, title no. 1.5, 2nd paragraph from the end.
Thanks
My code finds 46 words in words.txt but your code finds 4 words. Why is it like that?
Here's my code:
def is_three_consecutive_double(word):
"""Tests if a word contains three consecutive double letters
Args:
word (str): ASCII letters
Returns:
bool: True or False
"""
c = 0
while len(word) > 1:
if word[0] == word[1]:
c += 1
word = word[1:]
return True if c == 3 else False
def main():
"""Reads words.txt with English words
Prints a word list and count
"""
f = open('words.txt')
words_list = f.read().split('\n')
words_list.remove('')
f.close()
consecutive_double = []
count = 0
for word in words_list:
if is_three_consecutive_double(word):
consecutive_double.append(word)
count += 1
print(consecutive_double, count)
if __name__ == '__main__':
main()
I use VS code 1.55.0 on Windows 10. Thanks
I'm getting the following error in Markov.py:
File "C:\Users\tyson\AppData\Local\Programs\Python\Python310\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 7158: character maps to
I fixed it (or broke it more?) by using a context manager and encoding as utf8.
This is now the output:
t h a d b e l i n g s o . W o o d y c o m u s t o t s u r c e . H e c a n c e a n t h a r r y w i t g i p p e n i t y . ” B u t f i r f r o o b e i g e n t e t h a t s t o c o u t - - e n j u d d a r
I just don't understand why we use "i = i + 1 - 2*count" to reset the pointer in line 31 if two nearby characters doesn't match. I replaced the line with "i = i + 1" and got the same result.
Steps:
Cause:
It is not obvious when looking at the files in GitHub or Windows explorer, but there are two Markov.py files in the code folder (one starting with an uppercase M and the other with a lower m). The contents of the two files are different. You can see it when you download and open the .zip from GitHub (for some reason windows has no problem listing both files when viewing the contents of the .zip, but when you extract them one will get overwritten).
One gets overwritten, the other stays. Git sees it is different than the last commit and marks it as modified.
Hello Sir,
As per https://github.com/AllenDowney/ThinkPython2/blob/master/LICENSE , it is MIT
As per http://greenteapress.com/wp/think-python-2e/ :
Think Python 2e is a Free Book. It is available under the Creative Commons Attribution-NonCommercial 3.0 Unported License, which means that you are free to copy, distribute, and modify it, as long as you attribute the work and don’t use it for commercial purposes.
Could you please clarify the purpose of each license? If I fork this repo, should I mention both licenses?
Also, if I am interested in porting the book to Ruby, is it okay?
Thanks,
Sundeep
"A design principle that helps achieve that goal is to keep interfaces separate from implementations. For objects, that means that the methods a class provides should not depend on how the attributes are represented."
Your earlier definitions:
Chapter 4
"interface: A description of how to use a function, including the name and descriptions of the arguments and return value."
Chapter 11
"implementation: A way of performing a computation."
So rewritten with your definitions:
A design principle that helps achieve that goal is to keep descriptions of how to use functions, (including the names and descriptions of the arguments and return values) separate from ways of preforming a computation.
So... I should keep my descriptions of how a function works (like comments?) separate from the ways I preform a computation... (like the actual code...)??
Again, maybe it's just me being too dumb, but it sounds more like: you want to use a cutesy phrase that has some meaning in computer science circles- in an introductory computer science textbook.
I'm fine with introducing jargon (like you have done excellently throughout the rest of the book) but I don't like it when you introduce it without an explanation.
Here's my own cute phrase for what I mean: "Jargon without explanation is frustration."
should add syntax coloring to code block
Is it possible to grab the codes from http://www.cauldron.sakura.ne.jp/thinkpython/thinkpython/ThinkPython2.pdf and develop a Japanese-English bilingual version of the book? This might be good for learning both programming and Japanese.
p 226 the line spacing is too wide
""The exercises should be labelled "Exercise" rather than "Example"
import time
epoch = time.time()
seconds_in_a_day = 24 * 60 * 60
seconds_in_an_hour = 60 * 60
seconds_in_a_minute = 60
days = epoch // seconds_in_a_day
hours = (epoch % seconds_in_a_day) // seconds_in_an_hour + 8
minutes = (epoch % seconds_in_a_day) % seconds_in_an_hour // seconds_in_a_minute
seconds = (epoch % seconds_in_a_day) % seconds_in_an_hour % seconds_in_a_minute
print("%s: %s: %s: %s" %(days, hours, minutes, seconds))
print("Beijing Current time is %d: %d: %d: %d" %(days, hours, minutes, seconds))
_Originally posted by @JCWDFCS in https://github.com/AllenDowney/ThinkPython2/issues/18#issuecomment-292769002_
Since the contributor list is quite long, should we consider using a smaller font?
Page 7, Title 1.9 Exercises:
Exercise1.1.
Are exercises 1 & 2 the same, or did I miss something?
Thanks
Hi,
the book has an entire chapter about Inheritance, but I noticed it lacks a mention of super()
. Being able to use code of the parent function is, in my opinion, a pretty useful thing to do. Could you consider adding that?
the sentence: I don't work very hard to remember the precedence of operators.
I do not know if I understood the real meaning or what u want to say.
I guess what u want to say is: I know it's very hard to ....
As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python.
As of Python 3.7, this is a guaranteed language feature, not merely an implementation detail.
ThinkPython2/code/cartalk1.py
The sample solution skips forward after a match but if later matches fail, it never rewinds.
This would reject words like:
aaabbcc
aaaaabb
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.