Coder Social home page Coder Social logo

thinkpython2's Introduction

ThinkPython

LaTeX source, code examples, and exercise solutions for Think Python, 2nd edition, by Allen Downey.

You can download this book in PDF from Green Tea Press or buy it in paper and other formats from O'Reilly Media.

To build the book from source you will need a LaTeX installion. I recommend the TeX Live distribution with the following packages:

  • texlive-latex-base
  • texlive-latex-extra
  • texlive-fonts-recommended

thinkpython2's People

Contributors

abhitrueprogrammer avatar allendowney avatar calcisme avatar egcircle avatar espinoza avatar lbordoni avatar lbt avatar marked avatar nouraellm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

thinkpython2's Issues

cartalk1, why using i=i+1-2*count?

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.

Compile to epub

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

Spanish translation of ThinkPython2

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.

next iteration of grid.py

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.

Suddenly confusing passage on page 169, 17.11

"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."

removed extra quote on last print statement

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_

Clarification on book license

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

MD5 commentary is out of date

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?

color

should add syntax coloring to code block

Unclear Question

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?

Two markov.py files w/different filename casing cause git for Windows confusion: Markov.py and markov.py

Steps:

  1. User forks AllenDowney/ThinkPython2 to their GitHub
  2. User clones their new ThinkPython2 fork from their GitHub to their local Windows PC.
  3. Local git clients (git-gui, git-bash, GitHub Desktop) all say there are un-staged edits to code/Markov.py even though the user has made no changes (or even opened one of the files):
    image
    gitstatus

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).
image
One gets overwritten, the other stays. Git sees it is different than the last commit and marks it as modified.

Ghost 👻👻👻👻 Game

39123332-beyder-d-chistyy-python-tonkosti-programmirovaniya-dlya-profi-39123332-300x424~2

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)

rotate_pairs does not find all possible rotate pairs

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.

Exercise 9.7 cartalk1.py

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

Section 5.14 - Exercise 1

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

super() missing?

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?

section 16.2: built-in function name used as local variable name

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).

Production: boxes around figures

I think the boxes around the figures are unnecessary.

  • We can remove them, but boxes are our style, and I see them in the other "Think" books. I'd vote for leaving them be.

Section 4.6 circle function should ensure n >= 3

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:

n = int(circumference / 3) + 1

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 2 and section 2.5

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 ....

Next steps after Think Python

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?

Epub version of 2.4.0

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

Dict is now ordered. Maybe the book should be updated?

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.

Production: icon to identify Python 2

Can we get a Python 2 icon to mark the places where I discuss Python 2? (There are only 4-5 of them)

  • What should the icon look like? Doable, but we need more guidance on what he's thinking. Maybe a mockup or pointing us to something similar in another title? Sounds doable though.

Describe dependencies in README

In order to build the book on Ubuntu 16.04 with make all I had to install the following packages:

  • texlive-latex-base
  • texlive-latex-extra
  • texlive-fonts-recommended

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.

exercise 8.3: every other

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.

Markov.py need to change file read encoding to utf8 - among other issues

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

Extraneous glossary terms in chapter 1

The glossary for chapter 1 contains the following glossary terms that are not covered in the body text of the chapter:

  • high-level language
  • low-level language
  • portability

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…

Production: figure 5-1 cut off

Fig 5-1 the letters get cut off on the left

  • From what I can tell, that's a problem in the source image file. We'd need to redraw it, unless he has a good copy.

Rectangle corner in rect_in_circle function

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?

cartalk1 has an edge case

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

Build failure

  • I cloned the latest master branch a2b4cb7
  • I was trying to build book but i got following error
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

  • There is no book.idx file found inside the book directory.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.