Coder Social home page Coder Social logo

norvig / pytudes Goto Github PK

View Code? Open in Web Editor NEW
22.5K 771.0 2.4K 91.03 MB

Python programs, usually short, of considerable difficulty, to perfect particular skills.

License: MIT License

Python 0.63% Jupyter Notebook 98.47% HTML 0.74% Java 0.17%
python python-3 programming practice demonstrate-skills

pytudes's People

Contributors

alexrkopp avatar carreau avatar ghurley avatar grodrigues3 avatar kasimte avatar kpathakota avatar mco-gh avatar mcsalgado avatar milmazz avatar naereen avatar necmttn avatar nicholascc avatar nischalshrestha avatar norvig avatar ocyj avatar pathcl avatar polonez avatar rahimnathwani avatar ramalho avatar raphaelwimmer avatar rmeertens avatar sandeep-ghimire avatar sbiddand avatar stephenleeustc avatar tbroadley avatar treszkai avatar vladimirlojanica avatar windlessstorm avatar ybashir avatar yu-mc 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

pytudes's Issues

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

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.

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.

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

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'

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.

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

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 ?

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)

console problems

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

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

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?

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.

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'

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.

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.

Typo

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

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

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'

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.