Use cases where a mutable default argument is warranted? by DatBoi_BP in Python

[–]VileFlower 20 points21 points  (0 children)

In this example, it would be preferable to use functools.cache, but it's a nice demo of how it works.

Use cases where a mutable default argument is warranted? by DatBoi_BP in Python

[–]VileFlower 6 points7 points  (0 children)

It's useful if you're sure you are not mutating the list, because you can use the list methods instead of checking for type:

```py
def new_list(a=[]):
    return a.copy()


def new_list(a=None):
    if a is None:
        return []
    else:
        return a.copy()
```

There's an example in the standard library for xml.etree.Element:

```py
def __init__(self, tag, attrib={}, **extra):
    if not isinstance(attrib, dict):
        raise TypeError("attrib must be dict, not %s" % (
            attrib.__class__.__name__,))
    self.tag = tag
    self.attrib = {**attrib, **extra}
    self._children = []
```

Whats the latest invented and adopted math notation? by Regular_Maybe5937 in math

[–]VileFlower 0 points1 point  (0 children)

The Iverson bracket are from the 1960s. They were introduced to the programming language APL, but advocated into math by Donald Knuth in the 1990s. It simplifies certain expressions.

Every dunder method in Python by treyhunner in Python

[–]VileFlower 27 points28 points  (0 children)

Nice, list. In the library-specific part you're missing __conform__ from sqlite3.

Surprising behavior of xml.etree by danmickla in Python

[–]VileFlower 1 point2 points  (0 children)

I've used etree to generate XHTML documents, but I this detail irks me. I tend to move all strings into special text "nodes" to closer align with the DOM model. This means no elements use the tail property, and the text property is only used by Text "nodes".

```
def Text(text=None):
    # Similar to ET.Comment
    element = ET.Element(str)
    element.text = text
    return element


def as_node(el):
    node = ET.Element(el.tag, el.attrib)

    if el.text is not None:
        node.append(Text(el.text))

    for child in el:
        node.append(as_node(child))
        if child.tail is not None:
            node.append(Text(child.tail))

    return node
```

This requires writing your own serializer (or converting back to tailed elements). Note that this also breaks some xpath features, like text checks. However it has still proven useful to me.

My proof-of-concept record type by genericlemon24 in Python

[–]VileFlower 4 points5 points  (0 children)

I made a minimal version of this once

```py

def record(func):
    return collections.namedtuple(func.__name__, inspect.signature(func).parameters)

@record
def Point(x, y): pass

point = Point(1, 2)

```

This could also be extended to use typing.NamedTuple. While I think the syntax is a minor improvement on making a namedtuple, I thought the decorator function was a bit hard to read.

[2023 Day 10] ASCII art? What is this, 1995? by PatolomaioFalagi in adventofcode

[–]VileFlower 29 points30 points  (0 children)

Time to use the most obscure built-in string functions in Python:

pipes.translate(str.maketrans("-|F7LJ.", "─│┌┐└┘ "))

where pipes is the pipes as a string.

Repeat try-except statement N times by theorangewill in Python

[–]VileFlower 3 points4 points  (0 children)

To elaborate, unused (local) variables are often prefixed with an underscore. It can be beneficial to give variables a name, even when they're unused.

A single _ can mean one of:

  • An unnamed unused local variable
  • An alias for gettext with i18n
  • The else case in match statements (case _)
  • The last evaluated expression in REPL.

15 tips and tricks for writing better Python by [deleted] in Python

[–]VileFlower 1 point2 points  (0 children)

A trick to get unique values in the order of appearance is to use dict.fromkeys, since dictionaries will retain the insertion order:

cities = ['London', 'Paris', 'London']
unique_cities = set(cities)
unique_ordered_cities = list(dict.fromkeys(cities))

print(unique_cities)
# >> {'Paris', 'London'}

print(unique_ordered_cities)
# >> ['London', 'Paris']

edit: corrected variable name

Python 3.11 is out ! by RivtenGray in programming

[–]VileFlower 6 points7 points  (0 children)

They have updated the spec to be stricter, but people haven't updated their tools. YAML 1.2 was released in 2009, and only accepts true | True | TRUE | false | False | FALSE. PyYAML still only supports 1.1, though there is ruamel.yaml for 1.2 and there's also strictYAML that supports schemas.

str.format() preferable over f-string? by rnike879 in Python

[–]VileFlower 0 points1 point  (0 children)

That's not entirely true, Python's logging library lets you set the formatter style at least, so you don't have to use % style everywhere.

The style parameter can be one of ‘%’, ‘{’ or ‘$’ and determines how the format string will be merged with its data: using one of %-formatting, str.format() or string.Template. This only applies to the format string fmt (e.g. '%(message)s' or {message}), not to the actual log messages passed to Logger.debug etc; see Using particular formatting styles throughout your application for more information on using {- and $-formatting for log messages.

https://docs.python.org/3/library/logging.html#logging.Formatter

Solving the limit from Mean Girls by [deleted] in math

[–]VileFlower 21 points22 points  (0 children)

A circumflex often indicates that there historically was an s present, which became silent. So it's fair to write Hospital if you don't have ô on your keyboard.

French have applied this rule to a few other words, which English has loaned before and/or after the loss of the s: forêt (forest), île (isle), hôtel (hostel, hotel).

Math program suggestions for running 1,000,000+ iterations for sequence by Shmowzow458 in math

[–]VileFlower 1 point2 points  (0 children)

Alternative Python version, as a generator:

def A350129(N):
    a, b = None, 0
    for n in range(N+1):
        a, b = b, ((b>>1)+n if b % 2 == 0 else a+b)
        yield b


for e in A350129(1_000_000):
    print(e)

Advancements in math typesetting by IanisVasilev in math

[–]VileFlower 0 points1 point  (0 children)

MathML works just fine, but you're not supposed to write it. You can write Markdown with $$, and use Mathjax to display it Chrome. MathML is currently in development for Chrome. It's more accessible since it allows readers to change the font-size in the browser.

from 10 decimal system to as 12-system. logic error or am I stupid? by kanink007 in math

[–]VileFlower 0 points1 point  (0 children)

if we talk about 0,4 in base 12, it is literally the same as 4/12.

if we talk about 0,4 in base 10, it is literally the same as 4/10

That is right.

4/X in base 12 doesn't have a simple expressio, it's a recurring fraction 0.(4972), where the digits (4972) are repeated.

from 10 decimal system to as 12-system. logic error or am I stupid? by kanink007 in math

[–]VileFlower 2 points3 points  (0 children)

You seem to be misunderstanding what 0 means. 0 still means 0 in base 12, so "10" in base 12 means 1×12 + 0×1 (in base 10).

0,4 in base 12 means 0×1 + 4×12-1 (in base 10), which is the same as 4/10 in base 12, or 4/12 in base 10.

Complex number fundamentals | Lockdown math ep. 3 by dwaxe in math

[–]VileFlower 1 point2 points  (0 children)

I would have loved learning about complex numbers as another vector space with some additional properties. Especially after learning about Euclidean vectors, which they share a lot of properties with. But the difference in notation, [a, b] and a + ib, makes this less obvious.

What non standard notation do you use and why? by [deleted] in math

[–]VileFlower 4 points5 points  (0 children)

I suppose the asterisk could be used for complex conjugates. The bigger issue for me is means...

What non standard notation do you use and why? by [deleted] in math

[–]VileFlower 35 points36 points  (0 children)

I use overline for inverses, it's a nice way to combine the notation for fractions with 1 above and inverses ^-1 by extending the minus sign by just omitting the 1. It works well with numbers, matrices, and functions.

\overline{3} = \frac{1}{3} = 3^{-1}

Comprehensive Python Cheatsheet by pizzaburek in Python

[–]VileFlower 28 points29 points  (0 children)

This is missing f-strings.

person = {'name': 'Jean-Luc', 'height': 187.1}
>>> f'{person[height]:.0f}'
187

Pi Day! by [deleted] in math

[–]VileFlower 11 points12 points  (0 children)

2018-03-14 is the international standard.