norvig / pytudes Goto Github PK
View Code? Open in Web Editor NEWPython programs, usually short, of considerable difficulty, to perfect particular skills.
License: MIT License
Python programs, usually short, of considerable difficulty, to perfect particular skills.
License: MIT License
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()
Running the notebook ipynb/Economics.ipynb
raises an AttributeError
exception with matplotlib-3.1.3
installed.
hold
An AttributeError
exception is raised.
A sweet notebook running.
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'
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.
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.
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).
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'
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:
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).
Accessing python .py files from Index of Python Files leads to 404 page
There is a typo:
There are nine blanks, each of which can be filled by one of four operators, so there are 9^4 = 262,144 possibilities
in the notebook: ipynb/Countdown.ipynb
It should be 4^9 = 262144
https://atlasml.io/ does not respond
In the first bullet in the "how not to win a million bux" section of beal.html (Beal's Conjecture discussion). Or else, if I've misread it, perhaps some other rewording that might make it clearer?
Perhaps, there's a typo in the number of possibilities here:
https://github.com/norvig/pytudes/blame/master/ipynb/Countdown.ipynb#L58
It might be meant to be the other way around 4^9 = 262,144
instead of 9^4
.
"Can you get your hand of cards into a nice order with just one move?" is used both for "Properly Ordered Card Hands" and "Tracking Trump: Electoral Votes" what seems to be a mistake
REAMDE at https://github.com/norvig/pytudes is affected
Perhaps, adding open in Emacs would be good?
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.
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
pytudes/ipynb/Advent-2020.ipynb
Line 104 in 994d790
pytudes/ipynb/Advent-2020.ipynb
Line 110 in 994d790
pytudes/ipynb/Advent-2020.ipynb
Line 123 in 994d790
x < y < z
?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)
when i type console.log in visual studios in doesn't translate the code onto the website console.
Came across http://norvig.com/sudopy.shtml which doesn't work.
I guess since the py
subdirectory was added.
Using map in Python 3 gives you <map object at 0x123466632abcd>
map needs changing from
'map': map
to
'map': lambda f,i: list(map(f, i))
for it to work as expected
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
I noticed that the Democrat shame factor slanted the polls, still do. Folks who answer the pollsters often will not cop to being Trump supporters because of the rabid blow back from friends, relatives, and neighbors. By the look of it excellent work, far above my pay grade.
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?
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.
.
Hi,
I have extended your & John Cook's work on this topic using fractional steps and wanted to share that. There is a 'chaotic' puzzle to this when the fractional step is -1 and could be an interesting topic in itself:
https://github.com/cdragun/python-progs/blob/master/Sierpinski.ipynb
Regards,
Chandra
Hi,
missing input folder data/advent2018 in repository
Alessio
input1 = Input(1, int)
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'
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.
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.
Below the section Faster Arithmetic (mod p), module must be modulo
Weighing Twelve Balls on a Scale: https://github.com/norvig/pytudes/blob/main/ipynb/TwelveBalls.ipynb
Might be worth linking this fantastic genius solution for readers' interest as well: https://puzzling.stackexchange.com/a/48892
Explanation: https://www.cut-the-knot.org/blue/12CoinsInVerse.shtml#solution
@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?
The link of "notebook to solve Jotto" in Wordle.ipynb seems to be broken.
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'
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.
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.