GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Home
  • About
  • Learn Python
  • Archives
  • Contact
  • here
  • Playing and Recording Sound in Python
  • https://github.com/jabbalaci/keysound
  • https://help.dropbox.com/sync/ignored-files
  • https://github.com/iustin/pyxattr
  • https://github.com/xattr/xattr
  • https://www.geeksforgeeks.org/merging-intervals/
  • example
  • You Should Compile Your Python And Here’s Why

This view

  • Original page
  • New address

GeezerVison is showing pythonadventures.wordpress.com — python – Python Adventures

Python Adventures

Welcome to the Jungle!
  • Home
  • About
  • Learn Python
  • Archives
  • Contact

Archive

Archive for the ‘python’ Category

Get the value of PI without a constant

December 24, 2025 Jabba Laci Leave a comment

Problem

You are using a new programming language and you need the value of PI. However, there’s no such constant in the language. What do you do?

Solution

You can copy the value of PI from somewhere and create your own constant. Or, you can use a math function for that.

>>> import math
>>> from math import *
>>> 
>>> cos(math.pi)
-1.0
>>> acos(-1)
3.141592653589793
>>> acos(-1) == math.pi
True

I must have learnt it in high school, but it was long forgotten. It was nice to re-discover it :)

Fortran

At the end of December 2025, I started to learn Fortran (just for fun). Actually, Modern Fortran is pretty good! I like it. However, the constant PI is missing. So I came up with this:

use iso_fortran_env, only: real64
real(real64), parameter :: PI = acos(-1.0_real64)

Categories: fortran, python Tags: acos, cos, pi

How to solve a two-variable equation with Sympy

December 13, 2024 Jabba Laci Leave a comment

Problem

You have a two-variable equation and you want to solve it with Python / Sympy.

Solution

Let’s see this example:

7x + 9y = 8
9x - 8y = 69

What is the value of ‘x’ and ‘y’?

We could solve it manually too, of course, but let’s say we have hundreds of these. So let’s solve it with Python using the Sympy library.

>>> import sympy as sp
>>>
>>> x = sp.symbols('x')
>>> y = sp.symbols('y')
>>>
>>> eq1 = sp.Eq(7 * x + 9 * y, 8)
>>> eq2 = sp.Eq(9 * x - 8 * y, 69)
>>>
>>> system = [eq1, eq2]
>>>
>>> sol_set = sp.linsolve(system, x, y)
>>> sol_set
{(5, -3)}
>>>
>>> 7 * 5 + 9 * (-3)
8
>>> 9 * 5 - 8 * (-3)
69
Categories: python Tags: advent of code, aoc, equation, math, sympy

Autoformat your Python code with Ruff

March 11, 2024 Jabba Laci Leave a comment

Problem

You use VS Code. When you save a Python file, you want the source code to be autoformatted.

Solution

Use Ruff for that. Follow these steps:

  1. Install the Ruff VS Code extension from Astral Software (extension ID: charliermarsh.ruff).
  2. Add the following lines to your settings.json :
"[python]": {
    "editor.tabSize": 4,
    "editor.insertSpaces": true,
    "editor.defaultFormatter": "charliermarsh.ruff",
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
      "source.organizeImports": "explicit"
    },
    "editor.formatOnType": true
  },

3. Optionally, you can create a config file for Ruff. Under Linux, its location is ~/.config/ruff/ruff.toml . Here is a basic config file:

# on Linux:     ~/.config/ruff/ruff.toml
# on Windows:   C:\Users\Alice\AppData\Roaming\ruff\ruff.toml

line-length = 100

[lint]
# rule IDs: https://docs.astral.sh/ruff/rules/

# ignore = ["E203","F401","F841","E712","E722"]
ignore = ["E722"]

Now, if you save a Python file in VS Code, you’ll get the following goodies:

  1. The code will be formatted automatically.
  2. The import lines will be sorted.
  3. A linter will analyze your code and indicate problems.

Links

  • My complete config files are here
Categories: python Tags: autoformat, black, format, isort, linter, ruff

Play a sound file from memory

February 6, 2024 Jabba Laci Leave a comment

Problem

I wanted to play short sound files a lot of times. Calling an external program each time to play a file would have been too slow. How to read sound files in the memory and play them from there?

Solution

First I tried the package simpleaudio. It worked well but it turned out that it couldn’t play every .wav file. VLC could play my file correctly, but simpleaudio just produced some noise. So I needed another solution.

And that’s how I found soundfile and sounddevice. Their usage is very simple:

import soundfile as sf
import sounddevice as sd

samples, samplerate = sf.read('file.wav')
sd.play(samples, samplerate)
sd.wait()

To use them, you also need to install numpy.

More info here: https://stackoverflow.com/a/42387773/232485

Update:

I had some .wav files that were not played correctly with soundfile+sounddevice. So I ended by using soundfile+sounddevice for certain files and by using simpleaudio for some other files.

Links

  • Playing and Recording Sound in Python (this is where I read about simpleaudio)
  • https://github.com/jabbalaci/keysound (my project, in which I needed to play sound files)
Categories: python Tags: in memory, play, sound, wav

Handle extended file attributes

February 6, 2024 Jabba Laci Leave a comment

Problem

You want to handle extended file attributes from Python.

Solution

If you are not familiar with extended file attributes, you can read more about it here. I also have a blog post (see here), in which I show how to set/remove extended file attributes using the attr Linux command.

To handle the extended file attributes from Python, you can use the pyxattr package: https://github.com/iustin/pyxattr

Its usage is very simple:

>>> import xattr
>>> xattr.listxattr("main.py")
[b'user.com.dropbox.attrs']
>>> xattr.getxattr("main.py", "user.com.dropbox.attrs")
b'\n\x12...'
>>> xattr.setxattr("main.py", "user.com.dropbox.ignored", "1")
>>> xattr.listxattr("main.py")
[b'user.com.dropbox.attrs', b'user.com.dropbox.ignored']
>>> xattr.getxattr("main.py", "user.com.dropbox.ignored")
b'1'
>>> xattr.removexattr("main.py", "user.com.dropbox.ignored")
>>> xattr.listxattr("main.py")
[b'user.com.dropbox.attrs']

A typical use case: you want Dropbox to ignore your venv/ folder inside your project.

Links

  • https://en.wikipedia.org/wiki/Extended_file_attributes
  • https://help.dropbox.com/sync/ignored-files
  • https://github.com/iustin/pyxattr (I used this in this post)
  • https://github.com/xattr/xattr (an alternative)
Categories: python Tags: attr, dropbox, extended, file attributes, pyxattr, xattr

keysound

February 5, 2024 Jabba Laci Leave a comment

Problem

I have a non-mechanical keyboard. However, when I press keys, I also want to hear some insane clickytty clicks. What to do?

Solution

If you don’t want to buy a new keyboard, you can try my keysound project. When you press a key, a short sound file is played.

At the bottom of the README of this project’s GitHub page, I also collected some related work, thus there are several alternatives available.

Categories: python Tags: click, keyboard, mechanical, sound

Sum the digits of a number until you get just one digit

June 7, 2023 Jabba Laci Leave a comment

Problem

Take a positive integer and sum its digits. Repeat this process until you get just one digit.

Example: 1472 🠖 1+4+7+2 = 14 🠖 1+4 = 5. The answer is 5.

Solution

# Python code
n = 1472
result = ((n-1) % 9) + 1

Credits

Thanks to my friend Mocsa who told me this math trick.

Categories: python Tags: math, sum, trick

Merge Overlapping Intervals

December 17, 2022 Jabba Laci Leave a comment

Problem

You have some overlapping closed intervals and you want to merge them. What is the algorithm for this?

Solution

Here are some examples with input and output:

Input1: Intervals = [[1, 3], [2, 4], [6, 8], [9, 10]]

Output1: [[1, 4], [6, 8], [9, 10]]


Input2: Intervals = [[6, 8], [1, 9], [2, 4], [4, 7]]

Output2: [[1, 9]]

And the algorithm:

def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
    # Sort the array on the basis of start values of intervals.
    intervals.sort()
    stack = []
    # insert first interval into stack
    stack.append(intervals[0])
    for curr in intervals[1:]:
        # Check for overlapping interval,
        # if interval overlap
        if stack[-1][0] <= curr[0] <= stack[-1][-1]:
            stack[-1][-1] = max(stack[-1][-1], curr[-1])
        else:
            stack.append(curr)
        #
    #
    return stack

Links

  • https://www.geeksforgeeks.org/merging-intervals/ (found here)

Categories: python Tags: algorithms, intervals, merge

Compile Python module to C extension

May 1, 2022 Jabba Laci Leave a comment

I found an interesting blog post: You Should Compile Your Python And Here’s Why. In short: if you have a type-annotated Python code (mypy), then with the command mypyc you can compile it to a C extension. Under Linux, the result will be an .so file, which is a binary format.

Here you can find a concrete example: https://github.com/jabbalaci/SpeedTests/tree/master/python3

Steps:

  • We need a type-annotated source code (example). It’s enough to add type hints to functions. It’s not necessary to annotate every single variable.
  • Compile it (mypyc main.py). The result is an .so file.
  • You can import the .so file as if it were a normal Python module.
  • If your project consists of just one file (main.py) that you compiled, here is a simple launcher for it:
#!/usr/bin/env bash

python3 -c "import main; main.main()"

If you do a lot of computation in a function, then with this trick you can make it 4-5 times faster.

I don’t think I would use it very often, but it’s good to know that this thing exists. And all you have to do is to add type hints to your code.

Links

  • You Should Compile Your Python And Here’s Why
  • mypyc documentation

Categories: python Tags: .so, compile, mypy, mypyc

Simulate keypresses

March 3, 2022 Jabba Laci Leave a comment

Problem

You want to simulate keypresses from a Python program.

Solution

Use PyAutoGUI. Easy to install, easy to use. The keyboard control functions are here.

Categories: python Tags: keypress, pyautogui, simulate
Older Entries
RSS feed
  • Google
  • Youdao
  • Xian Guo
  • Zhua Xia
  • My Yahoo!
  • newsgator
  • Bloglines
  • iNezha

Blog Stats

  • 1,659,935 hits

Random Post

Click here for a random post

Recent Posts

  • Get the value of PI without a constant
  • In a graph, find the largest complete subgraph
  • How to solve a two-variable equation with Sympy
  • Autoformat your Python code with Ruff
  • Play a sound file from memory

ascii bash beautifulsoup book bpython challenge command-line convert cron crontab date datetime distance dropbox email eric exercise extract file firefox github google hacking heroku html ide imdb imgur install ipython java jinja2 json linux module modules MongoDB movies news pdf perl pi pip print pylint pypi python3 python shell quote readline reddit redirect refactoring regexp requests reverse review shell sound stdout string tab text threads time tip tutorial unicode url video virtualenv virtual environment virtualenvwrapper xml zip

Archives

  • December 2025 (1)
  • December 2024 (2)
  • March 2024 (1)
  • February 2024 (3)
  • June 2023 (1)
  • December 2022 (1)
  • May 2022 (1)
  • March 2022 (1)
  • February 2022 (2)
  • October 2020 (3)
  • September 2020 (2)
  • July 2020 (1)
  • December 2019 (1)
  • November 2019 (7)
  • June 2019 (2)
  • May 2019 (1)
  • February 2019 (1)
  • January 2019 (1)
  • August 2018 (1)
  • July 2018 (4)
  • June 2018 (5)
  • May 2018 (1)
  • March 2018 (2)
  • February 2018 (1)
  • January 2018 (2)
  • December 2017 (2)
  • October 2017 (1)
  • August 2017 (1)
  • May 2017 (2)
  • April 2017 (1)
  • March 2017 (1)
  • February 2017 (3)
  • January 2017 (5)
  • December 2016 (3)
  • October 2016 (2)
  • September 2016 (1)
  • August 2016 (4)
  • July 2016 (3)
  • June 2016 (2)
  • May 2016 (2)
  • April 2016 (1)
  • March 2016 (4)
  • February 2016 (1)
  • January 2016 (4)
  • December 2015 (5)
  • November 2015 (8)
  • October 2015 (2)
  • September 2015 (3)
  • August 2015 (6)
  • July 2015 (4)
  • June 2015 (1)
  • May 2015 (3)
  • April 2015 (2)
  • February 2015 (1)
  • January 2015 (6)
  • December 2014 (5)
  • November 2014 (2)
  • October 2014 (1)
  • September 2014 (1)
  • August 2014 (14)
  • July 2014 (3)
  • June 2014 (6)
  • May 2014 (3)
  • April 2014 (2)
  • March 2014 (4)
  • February 2014 (3)
  • January 2014 (19)
  • December 2013 (8)
  • November 2013 (9)
  • October 2013 (4)
  • September 2013 (10)
  • August 2013 (16)
  • July 2013 (4)
  • June 2013 (7)
  • May 2013 (7)
  • April 2013 (3)
  • March 2013 (12)
  • February 2013 (2)
  • January 2013 (10)
  • December 2012 (18)
  • November 2012 (3)
  • October 2012 (4)
  • September 2012 (5)
  • August 2012 (1)
  • July 2012 (1)
  • May 2012 (8)
  • April 2012 (9)
  • March 2012 (17)
  • February 2012 (3)
  • January 2012 (8)
  • November 2011 (11)
  • October 2011 (7)
  • September 2011 (17)
  • August 2011 (5)
  • June 2011 (1)
  • May 2011 (7)
  • April 2011 (21)
  • March 2011 (21)
  • February 2011 (7)
  • December 2010 (4)
  • November 2010 (1)
  • October 2010 (16)
  • September 2010 (15)

Meta

  • Create account
  • Log in
  • Entries feed
  • Comments feed
  • WordPress.com
Python Adventures
Blog at WordPress.com.
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy
  • Subscribe Subscribed
  • Python Adventures
    View site in Reader
    Manage subscriptionsSign upLog in
    Report this content
    Collapse this bar
Loading Comments...

You must be logged in to post a comment.

Create your own website, free on WordPress.com.Create your own website.
Start free
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.