Git Product home page Git Product logo

pytudes's Introduction

Peter Norvig
MIT License
2015-2022

pytudes

"An étude (a French word meaning study) is an instrumental musical composition, usually short, of considerable difficulty, and designed to provide practice material for perfecting a particular musical skill." — Wikipedia

This project contains pytudes—Python programs, usually short, for perfecting particular programming skills.

Who is this for?

To continue the musical analogy, some people think of programming like Spotify: they want to know how to install the app, find a good playlist, and hit the "play" button; after that they don't want to think about it. There are plenty of other tutorials that will tell you how to do the equivalent of that for various programming tasks—this one won't help. But if you think of programming like playing the piano—a craft that can take years to perfect—then I hope this collection can help.

Index of Jupyter (IPython) Notebooks

For each notebook you can hover on the title to see a description, or click the title to view on github, or click one of the letters in the left column to launch the notebook on Colab, Deepnote, Mybinder, Sagemaker, or NBViewer.

Run Year Newest
C D M N S 2024 Counting Cluster Sizes in Paint by Numbers
C D M N S 2024 Overtime in American Football
C D M N S 2024 Stubborn number endings
C D M N S 2023 Advent of Code 2023
C D M N S 2023 Docstring Fixpoint Theory
C D M N S 2023 One Letter Off
C D M N S 2023 The Diamond Game: A Probability Puzzle
C D M N S 2022 Advent of Code 2022
C D M N S 2022 Advent of Code Utilities
C D M N S 2022 AlphaCode Automated Programming
C D M N S 2022 Anigrams: Word Chains
C D M N S 2022 Selecting Names from a Menu
C D M N S 2022 Winning Wordle
Run Year Programming Examples
C D M N S 2022 AlphaCode Automated Programming
C D M N S 2018 Beal's Conjecture Revisited
C D M N S 2020 Bicycling Statistics
C D M N S 2018 Can't Stop
C D M N S 2019 Chaos with Triangles
C D M N S 2017 Conway's Game of Life
C D M N S 2020 Generating and Solving Mazes
C D M N S 2021 Mel's Konane Board
C D M N S 2020 Photo Focal Lengths
C D M N S 2018 Pickleball Tournament
C D M N S 2017 Project Euler Utilities
C D M N S 2022 Selecting Names from a Menu
C D M N S 2020 Tracking Polls: Electoral Votes
Run Year Advent of Code
C D M N S 2023 Advent of Code 2023
C D M N S 2022 Advent of Code 2022
C D M N S 2021 Advent of Code 2021
C D M N S 2020 Advent of Code 2020
C D M N S 2018 Advent of Code 2018
C D M N S 2017 Advent of Code 2017
C D M N S 2016 Advent of Code 2016
C D M N S 2022 Advent of Code Utilities
Run Year Probability and Uncertainty
C D M N S 2019 Effectiveness of Language Models
C D M N S 2018 A Concrete Introduction to Probability
C D M N S 2016 Probability, Paradox, and the Reasonable Person Principle
C D M N S 2020 Estimating Probabilities with Simulations
C D M N S 2023 The Diamond Game: A Probability Puzzle
C D M N S 2019 The Devil and the Coin Flip Game
C D M N S 2020 Dice Baseball
C D M N S 2018 Economics Simulation
C D M N S 2024 Overtime in American Football
C D M N S 2012 Poker Hand Ranking
C D M N S 2020 The Unfinished Game .... of Risk
C D M N S 2019 WWW: Who Will Win (NBA Title)?
Run Year Logic and Number/Counting Puzzles
C D M N S 2024 Counting Cluster Sizes in Paint by Numbers
C D M N S 2014 Cryptarithmetic
C D M N S 2018 Euler's Sum of Powers Conjecture
C D M N S 2020 Four 4s, Five 5s, and Countdowns
C D M N S 2021 KenKen (Sudoku-like Puzzle)
C D M N S 2019 Pairing Socks
C D M N S 2018 Sicherman Dice
C D M N S 2014 Sol Golomb's Rectangle Puzzle
C D M N S 2024 Stubborn number endings
C D M N S 2021 Star Battle (Sudoku-like Puzzle)
C D M N S 2006 Sudoku
C D M N S 2021 Sudoku: 100,000 puzzles/second in Java
C D M N S 2020 Square Sum Puzzle
C D M N S 2020 When is Cheryl's Birthday?
C D M N S 2015 When Cheryl Met Eve: A Birthday Story
C D M N S 2015 xkcd 1313: Regex Golf
C D M N S 2015 xkcd 1313: Regex Golf (Part 2: Infinite Problems)
Run Year Word Puzzles
C D M N S 2020 Boggle / Inverse Boggle
C D M N S 2020 Chemical Element Spelling
C D M N S 2020 Equilength Numbers: FOUR = 4
C D M N S 2017 Gesture Typing
C D M N S 2017 Ghost: A Word game
C D M N S 2018 How to Do Things with Words: NLP in Python
C D M N S 2015 Let's Code About Bike Locks
C D M N S 2023 One Letter Off
C D M N S 2017 Scrabble: Refactoring a Crossword Game Program
C D M N S 2020 Spelling Bee
C D M N S 2017 Translating English into Propositional Logic
C D M N S 2020 Wordle, Evil Wordle, Antiwordle, and Jotto
C D M N S 2022 Winning Wordle
C D M N S 2017 World's Longest Palindrome
C D M N S 2020 World's Shortest Portmantout Word
C D M N S 2018 xkcd 1970: Name Dominoes
Run Year The Riddler (from 538)
C D M N S 2022 Anigrams: Word Chains
C D M N S 2017 Battle Royale
C D M N S 2021 Climbing Wall
C D M N S 2021 CrossProduct
C D M N S 2020 Flipping Cards; A Guessing Game
C D M N S 2019 Lottery
C D M N S 2019 How Many Soldiers to Beat the Night King?
C D M N S 2017 Misanthropic Neighbors
C D M N S 2018 Properly Ordered Card Hands
C D M N S 2021 Race Track
C D M N S 2021 Split the States
C D M N S 2020 Tour de 538
C D M N S 2020 Weighing Twelve Balls
C D M N S 2020 War. What is it Good For?
Run Year Computer Science Algorithms and Concepts
C D M N S 2017 BASIC Interpreter
C D M N S 2017 Convex Hull Problem
C D M N S 2023 Docstring Fixpoint Theory
C D M N S 2020 How to Count Things
C D M N S 2020 Stable Matching Problem
C D M N S 2017 Symbolic Algebra, Simplification, and Differentiation
C D M N S 2017 Snobol: Bad Grade, Good Experience
C D M N S 2018 Traveling Salesperson Problem

Index of Python Files

File Description Documentation
beal.py Search for counterexamples to Beal's Conjecture documentation
docex.py An obsolete framework for running unit tests, similar to doctest
ibol.py An Exercise in Species Barcoding documentation
lettercount.py Convert Google Ngram Counts to Letter Counts documentation
lis.py Lisp Interpreter written in Python documentation
lispy.py Even Better Lisp Interpreter written in Python documentation
lispytest.py Tests for Lisp Interpreters
pal.py Find long palindromes documentation
pal2.py Find longer palindromes documentation
pal3.py Find even longer palindromes documentation
pytudes.py Pre-process text to generate this README.md file.
py2html.py Pretty-printer to format Python files as html
SET.py Analyze the card game SET documentation
spell.py Spelling corrector documentation
sudoku.py Program to solve sudoku puzzles documentation
testaccum.py Tests for my failed Python accumulation display proposal documentation
yaptu.py Yet Another Python Templating Utility

Etudes for Programmers

I got the idea for the "etudes" part of the name from this 1978 book by Charles Wetherell that was very influential to me when I was first learning to program. I still have my copy.

pytudes's People

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

pytudes's Issues

AssertionError and KeyError

There is an error in line 61 inside grid_values def, because chars will always be 1
assert len(chars) == 81

Next in the line 103 there is a KeyError when hitting the "A2"
width = 1+max(len(values[s]) for s in squares)

I've tried it with python3 and python2 and both has the same problem

Is this intentional?

Chaining comparisons and assumed uniqueness

"in1: Set[int] = set(data(1, int))\n",

" if x != y)"

The puzzle description doesn't guarantee that each entry is unique; it's possible that a report contains the entry 1010 twice.

" if x != z != y)"

If we want to find unique entries anyway, this comparison chain does not preclude x == y. Perhaps use x < y < z ?

Cannot see big.txt

Hi,
I'm trying to start my first project using Python and I'm studying all somewhat related projects I can find.
That's how I came to your Spell code. As I could not get the file big.txt I replaced it by a list of 117,969 words - the sum of 2 .txt files from Moby Project.
Nevertheless, I would like to test the script with big.txt to compare the results.
Thank you.

Update: Got it. I suppose I tried to get the file while not signed in. I'll close this. Sorry to bother you.

console problems

when i type console.log in visual studios in doesn't translate the code onto the website console.

Wordle based on your Sudoku solver

Saw that you recently added an implementation for solving Wordle (referencing commit 7a746ae) . Your Sudoku solver was my starting point when I implemented a different Wordle solution based on treating the use of nouns and consonants as a form of constraint propagation. Mostly just wanted to say thanks for helping me think about strategies to solve puzzles.

https://github.com/tbonza/puzzles/blob/main/wordle/Solving%20Wordle.ipynb

Including my most recent commit for reference (tbonza/puzzles@b81a476)

Pin matplotlib version in requirements.txt or drop usage of hold to avoid AttributeError

Summary:


Running the notebook ipynb/Economics.ipynb raises an AttributeError exception with matplotlib-3.1.3 installed.

Reproduce:


  • Run the notebook with a matplotlib version that deprecated hold

Actual outcome:


An AttributeError exception is raised.

Expected outcome:


A sweet notebook running.

Logs &/or traceback:


Traceback

AttributeError Traceback (most recent call last)
in
----> 1 show(population)

in show(population, k, percentiles, **kwargs)
19 plt.title('/'.join(map(str, percentiles)) + ' Percentile Plots')
20 times = [t for (t, pop) in results]
-->21 plt.hold(True); plt.xlabel('wealth'); plt.ylabel('time'); plt.grid(True)
22 for pct in percentiles:
23 line = [percent(pct, pop) for (t, pop) in results]

AttributeError: module 'matplotlib.pyplot' has no attribute 'hold'

Likely parts and draft fix:


Change requirements.txt to pin the matplotlib version to something like 2.1.0:

numpy
matplotlib==2.1.0

Another option is to update the code in ipynb/Economics.ipynb to use the updated API.

Python 3 issues

flake8 testing of https://github.com/norvig/pytudes on Python 3.7.0

$ flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics

./py/testaccum.py:21:21: E999 SyntaxError: invalid syntax
    print acc_display
                    ^
./py/py2html.py:79:12: F821 undefined name 'cmp'
    return cmp(num(x[0]), num(y[0]))
           ^
./py/lispy.py:119:26: E999 SyntaxError: invalid syntax
            print '%s: %s' % (type(e).__name__, e)
                         ^
./py/pal.py:130:22: E999 SyntaxError: invalid syntax
            print self.best
                     ^
./py/lispytest.py:106:19: E999 SyntaxError: invalid syntax
            print x, '=>', to_string(result)
                  ^
./py/ibol.py:78:47: E999 SyntaxError: invalid syntax
    print "Number of genomes: %d (%d distinct)" % (len(genomes), len(set(genomes)))
                                              ^
./py/docex.py:101:16: E999 TabError: inconsistent use of tabs and spaces in indentation
	if self.failed:
               ^
./py/lettercount.py:64:49: E999 SyntaxError: invalid syntax
        print '%s: %s %s words (%s tokens) at %s' % (
                                                ^
./py/parse.py:29:19: E999 TabError: inconsistent use of tabs and spaces in indentation
		rhs = mklist(rhs)
                  ^
./py/ngrams.py:30:28: E999 SyntaxError: invalid syntax
    print 'Running tests...'
                           ^
./py/pal2.py:188:37: E999 SyntaxError: invalid syntax
        print 'using reversibles ...'
                                    ^
./py/lis.py:98:26: F821 undefined name 'raw_input'
        val = eval(parse(raw_input(prompt)))
                         ^
./py/yaptu.py:76:49: E999 SyntaxError: invalid syntax
            if self.verbose: print '=== eval{%s}' % expr,
                                                ^
11    E999 TabError: inconsistent use of tabs and spaces in indentation
2     F821 undefined name 'raw_input'
13

advent 2017 day 5 functions mutate the list

I think it would be good to create a copy of M within the run and run2 functions to avoid mutating the list that is passed in - it worked out fine since you created the input each time, but it would have gone wrong if you had only created it once.

missing '/data/advent2020/' folder

FileNotFoundError Traceback (most recent call last)
in
----> 1 in1: Set[int] = set(data(1, int))

in data(day, parser, sep)
1 def data(day: int, parser=str, sep='\n') -> list:
2 "Split the day's input file into sections separated by sep, and apply parser to each."
----> 3 sections = open(f'data/advent2020/input{day}.txt').read().rstrip().split(sep)
4 return [parser(section) for section in sections]
5

FileNotFoundError: [Errno 2] No such file or directory: 'data/advent2020/input1.txt'

A Chaos Game with Triangles - Improvements with Transparency and Oversampling

Hello,

It is possible to significantly and cheaply improve the rendering of the figures of the A Chaos Game with Triangles notebook by using transparency, smaller marker size and a some oversampling:

def show_walk(vertexes, N=5000):
    "Walk halfway towards a random vertex for N points; show reults."
    Xs, Ys = transpose(random_walk(vertexes, N))
    Xv, Yv = transpose(vertexes)
    plt.plot(Xs, Ys, 'r.', alpha=0.5, markersize=1)
    plt.plot(Xv, Yv, 'bs', clip_on=False)
    plt.gca().set_aspect('equal')
    plt.gcf().set_size_inches(9, 9)
    plt.axis('off')
    plt.show()

image
image

image
image

Split error while input string contained whitespace in tokenize function under lis.py

for example , just input "hello wolrd" after call repl()

"hello world" will be splitted to two tokens like ("hello) and (world"). it should be treated as one single string expression, not two tokens, otherwise "hello will be thought as an operator, but it can not be found from environment.

Below is my test log:

lis.py> "hello world"
Traceback (most recent call last):
File "", line 1, in
File "/home/klose/Documents/programming/python/intepreter/lis.py", line 98, in repl
val = eval(parse(raw_input(prompt)))
File "/home/klose/Documents/programming/python/intepreter/lis.py", line 123, in eval
return env.find(x)[x]
File "/home/klose/Documents/programming/python/intepreter/lis.py", line 89, in find
return self if (var in self) else self.outer.find(var)
AttributeError: 'NoneType' object has no attribute 'find'

missing data/advent2018 input folder

Hi,
missing input folder data/advent2018 in repository
Alessio

input1 = Input(1, int)

sum(input1)

FileNotFoundError Traceback (most recent call last)
in
----> 1 input1 = Input(1, int)
2
3 sum(input1)

in Input(day, line_parser, file_template)
18 def Input(day, line_parser=str.strip, file_template='data/advent2018/input{}.txt'):
19 "For this day's input file, return a tuple of each line parsed by line_parser."
---> 20 return mapt(line_parser, open(file_template.format(day)))
21
22 def integers(text):

FileNotFoundError: [Errno 2] No such file or directory: 'data/advent2018/input1.txt'

Loading function for loading files "count_1w.txt" is not working

Hi,

This function is always throwing an error.

def load_counts(filename, sep='\t'):
"""Return a Counter initialized from key-value pairs,
one on each line of filename."""
C = Counter()
for line in open(filename):
key, count = line.split(sep)
C[key] = int(count)
return C

Sometimes it is throwing an error of this type:-
Error is in line --> 168 C[key].append(int(count))

and error is--> TypeError: unhashable type: 'list'

And sometimes:-
--> 167 key, count = line.split(sep)

ValueError: not enough values to unpack (expected 2, got 1)

I can't find the reason.Please help.I am using Python3 and have edited everything related to Python3 in this program.Please let me know the reason of above errors.

"Advent of Code 2021" is actually "Advent of Code 2020"

@norvig, you have Advent of Code 2020 notebooks and you have Advent of Code 2021 notebooks (if you believe the hyperlink text, anyway), but following the links to the mentioned notebooks reveals that everything leads to the one and only Advent of Code 2020.

There aren't any real Advent of Code 2021 notebooks, are there, Peter? Is this an early April Fools' Day prank maybe?

time_solve() nested in sudoku.html

The function time_solve() is nested within solve_all() on sudoku.html, but is a global function in sudoku.py. Was wondering if I may be missing something, but I'm happy to do the quick fix if it's an issue.

Bug in Day 1 function

The code for day 1 that finds entries that sum to 2020 assumes that every entry is unique. However, this assumtion is not supported by the assignment, so it doesn't find the answer in the case that the expense report contains the number 1010 twice (which isn't even that unlikely for an expenses report).

Typo

Below the section Faster Arithmetic (mod p), module must be modulo

incorrect comment on Advent of Code 2018 Day 6 Part 1

The notebook states:

Originally, I thought that if a point on the perimeter of the [bounding] box was closest to point p, then p has an infinite area. That's true for p that are in the corners, but need not be true for all p (consider a set of 5 points, 4 in the corners of a box, and one near the center; the center point will have a diamond-shaped area, and unless it is at the exact center, it will "leak" outside one of the edges). So I expand the bounding box by a margin.

I tried to replicate this with a drawing of the described situation, but found that the area of the point near the center was still infinite:

2019-06-03

I believe that you don't need a buffer on the perimeter. In the Manhatten distance metric, traveling "across then up" is the equal-best way to get between two points. Thus if the closest point to A on the perimeter is B, and B is itself closest to (e), then A is closest to (e).

This fails in the normal Euclidean plane because if you move far enough to the right you will eventually be closer to (b) then to (e) (imagine a circle through (e) with center very far to the right - the circumference through (e) locally appears to be a straight vertical line).

Python3 compatibility How to Do Things with Words.ipynb

Hello,

I'm trying to use 'How to Do Things with Words' notebook but...


NameError Traceback (most recent call last)
in ()
----> 1 TEXT = file('big.txt').read()
2 len(TEXT)

NameError: name 'file' is not defined

  • I think this should be replaced to use open() instead of file().

  • I was able to use 'big.txt' downloading from https://norvig.com/big.txt .Not sure if its the same.

I'll upload a PR to make it py3 compatible.

AoC 2016 day 11

Hi Mr Norvig,

In recent months I've been doing a lot of AoC puzzles in Python.
Today I solved 2016 day 11 then noticed you said in your dedicated notebook at the time that your own solution ran in about 14 min for part 2. I checked the Reddit thread for that day and many if not all Python solutions also took several minutes to complete for part 2.
I've been impressed by your concise and clear, functional style and overall efficiency across all your AoC solutions, therefore I'm surprised my own Python solution takes only about 2 seconds to run for part 2.

I guess there must be other explaining factors than the difference in hardware between then and now, or the fact that background processes may have slowed down your run at the time.
I hardly believe my solution is that much optimized (especially since I did not consider the symmetry trick you mention in the notebook) so I'm guessing it must contain some flaw somewhere.

If you'd like to have a look at my implementation, I'd be more than happy to be proven wrong and learn in the process.

Kind regards,

Clement

Write Moby Dick approximately

Can you tackle this one ?
Short description:

Here is a 1.2Mb ASCII text file containing the text of Herman Melville's Moby-Dick; or, The Whale. Your task is to write a program or function (or class, etc. -- see below) which will be given this file one character at a time, and at each step must guess the next character.

If it tickles your fancy. Thanks.

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.