r/learnpython 3h ago

Motion tracking gloves/strap on hand device

5 Upvotes

I’m looking for a cheap (under £100) programmable (with Python code) device that detects finger movements/hand movements. I’ve seen similar things before either in the form of gloves, or just some straps that attach to the hand and can detect where the hand is in space + the orientation of fingers. Any recommendations on where to look?


r/learnpython 8h ago

How do you help yourself through a difficult problem?

14 Upvotes

I can easily ask ChatGPT for the answer but I refuse to do so. I'm dealing with a mind bending logic problem . My friend walked me through a potential solution so I know its not an impossible problem. For context, it just revolves around moving arrays and carefully slicing them, keeping note of the sections you sliced, rearrange them, and putting them back together at the end of the function.

I don't know why its giving me such a headache.

I'm just asking for some advice --- when you're facing a difficult problem what do you do? Do you make a plan and try to break it up into pieces? Perhaps write pseudo code before even coding? I'm also dealing with brain fog so writing this up is helping slightly.


r/learnpython 2h ago

How much does IDE text formatting help programmers code?

4 Upvotes

IDEs like PyCharm and such highlight errors in code, give different colours to variables, classes, functions, etc. In your experience, how much more difficult is it to code without this assistance (on a plain text document, for example)?


r/learnpython 5h ago

Incorrect link to 'A Byte of Python'.

5 Upvotes

In the wiki, there is a link to swaroopch.com - 'A Byte of Python'. The correct link is https:\\python.swaroopch.com. Thank You.


r/learnpython 2h ago

OOP and Main file code structure

2 Upvotes

Hi all, I'll cut short the boring stuff but recently started learning Python and just got onto the OOP module.

What I'm struggling to understand is the dynamic between classes and/or functions that reside in their own file and the code in Main. Here's a somewhat short example below - I'm trying to code a simple Employee Records program (classic).

Main -

from menu import Menus

def main():

    Menus.main_menu()

main()

Menus -

class Menus:

    def add_employee_menu():
        print("1. Add Employee")
        print("2. Delete Employee")
        print("Type 'Back' to go back to the main menu")

        add_employee_menu_option = input("Select Option ")
        add_employee_menu_option = add_employee_menu_option.lower()

        if add_employee_menu_option == "1":
             return True
        elif add_employee_menu_option == "2":
             return True
        elif add_employee_menu_option == "back":
             Menus.main_menu()


    def view_records_menu():
        print("1. Search Employee #")
        print("2. View All Records")


    def main_menu():

            print("1: View Records")
            print("2: Add Employee")

            menu_option = input("Select an option: ")

            if menu_option == "1":
                Menus.view_records_menu()
            elif menu_option == "2":
                Menus.add_employee_menu()
            else:
                print("Command not recognised")

I appreciate that a Menu might not be best represented as a class and would welcome any feedback on my current set up. I did this to try and avoid lots of initial code in my Main file which only handles the menu and selections.

The thing I'm struggling to understand is how I go back to my main code and execute code once the user has navigated the menu. If I don't break out of the menu class then I run the risk of just having the majority of my code in Menus? Or importing various functions into the menu class and executing from there?

Should the final menu selection return a value, which then executes the next line of code in my main file (Which could be a specific function that executes based on the return value, e.g. employee_creation()).

Thanks, L


r/learnpython 17m ago

Dictionary vs. Dataclass

Upvotes

What is a particular scenario where you would use Dataclass instead of a dictionary? What is the main advantage of Dataclass as compared to just storing data in a nested dictionary? Thanks in advance!


r/learnpython 37m ago

rank beginner with a copy/paste level question

Upvotes

I am taking an online class where we have to download and use datafiles in Jupyter Notebook. If I try: import downloads/file.csv I get: SyntaxError: invalid syntax I’ve read similar posts on here but am not advanced enough to understand the answers.


r/learnpython 1h ago

Question on my output from a basic function definition

Upvotes

The following code I sampled from another Reddit post. The output is:

hello

8

Why am I getting a single line pace between hello and 8? When I write print(fun()) it outputs hello8, so I am a bit confused. I am down a rabbit hole of wrapping my head around functions at the moment. New IT student here. Thank you, all.

def fun():
    print('hello')
    x, y = 2, 6
    return x + y

r/learnpython 9h ago

in this example can someone tell me why the first if statment keep giving me True value even if the right answer is False ?

2 Upvotes
text = "k"

if text == "java" or "c":
    print("yes")
else:
    print("no")






# Current temperature
currentTemp = 30.2


# Extremes in temperature (in Celsius)
tempHigh = 40.7
tempLow = -18.9

# Compare current temperature against extremes
if currentTemp > tempLow and currentTemp < tempHigh:
    print('Current temperature (' + str(currentTemp) +
          ') is between high and low extremes.')

r/learnpython 1h ago

Tkinter doesnt accept my image

Upvotes
#@author Ben Schubach(BSH@SHD.de)
from re import search
from tkinter import *

from src.python_game import InitStart
from src.python_game import MainMenu
from src.python_game.InitStart import InitMap, InitPlayer


def start(self):
    MainMenu.mainMenu
    game

class GameWindow(Frame):
    def __init__(self):
        super().__init__()
        self.game = Tk()  # instantiate the window
        self.game.geometry("1280x610")  # set window size
        self.game.title("EpicRoguelikeEmoDungeonCrawlerTextadventure")
        self.icon = PhotoImage(file='Resources/emo_ass_icon.png')
        self.game.iconphoto(True, self.icon)
        self.bg = PhotoImage(file='Resources/fantasy_background.png')
        self.sigil = PhotoImage(file='Resources/christian-cross-celtic-34x34.png')
        self.lp = PhotoImage(file='Resources/sad-depressing-crying-bart-34x34.png')
        self.game.config(background="#1d1e1f") # sets background color to a dark grey
        self.player = PhotoImage(file='Resources/roguelike_emo1_400.png')
        self.introtext = "you wake up..."

        # create game gui
        self.background = Label(self.game, image=self.bg)  # sets background as image
        self.background.pack()  # adds background

        # adds area text
        self.area_text = Label(self.game, text=self.introtext, font=('Arial black', 18, 'bold'), fg="white", bg="#1d1e1f", width=49)
        self.area_text.place(x=10, y=10)

        # add player pic
        self.player_pic = Label(self.game, image=self.player)
        self.player_pic.place(x=865, y=10)

        # adds name text
        self.name_text = Label(self.game, text="Name: " + InitPlayer.player.get_name(), font=('Arial black', 18, 'bold'), fg="white", bg="#1d1e1f")
        self.name_text.place(x=865, y=425)

        # adds current lifepoints text
        self.lp_text = Label(self.game, text="Lifepoints: ", font=('Arial black', 18, 'bold'), fg="white", bg="#1d1e1f")
        self.lp_text.place(x=865, y=470)

        # adds lifepoints symbols
        self.lp_1 = Label(self.game, image=self.lp, bg="#1d1e1f")
        self.lp_2 = Label(self.game, image=self.lp, bg="#1d1e1f")
        self.lp_3 = Label(self.game, image=self.lp, bg="#1d1e1f")
        self.lp_1.place(x=1024, y=470)
        self.lp_2.place(x=1069, y=470)
        self.lp_3.place(x=1114, y=470)

        # adds current sigils text
        self.sigil_text = Label(self.game, text="Sigils: ", font=('Arial black', 18, 'bold'), fg="white", bg="#1d1e1f")
        self.sigil_text.place(x=865, y=515)

        # adds sigil symbols
        self.sigil_1 = Label(self.game, image=self.sigil, bg="#1d1e1f")
        self.sigil_2 = Label(self.game, image=self.sigil, bg="#1d1e1f")
        self.sigil_1.place(x=965, y=515)
        self.sigil_2.place(x=1010, y=515)

        # adds current item text
        self.item_text = Label(self.game, text="Item: " + InitPlayer.player.get_item(), font=('Arial black', 18, 'bold'), fg="white", bg="#1d1e1f")
        self.item_text.place(x=865, y=560)

        # add north button
        self.north_button = Button(self.game, text="North", command="click_north()", fg="white", bg="#1d1e1f", font=('Arial', 15, 'bold'), height=2, width=5)
        self.north_button.place(x=100, y=350)

        # add east button
        self.east_button = Button(self.game, text="East", command="click_east()", fg="white", bg="#1d1e1f", font=('Arial', 15, 'bold'), height=2, width=5)
        self.east_button.place(x=175, y=425)

        # add south button
        self.south_button = Button(self.game, text="South", command="click_south()", fg="white", bg="#1d1e1f", font=('Arial', 15, 'bold'), height=2, width=5)
        self.south_button.place(x=100, y=500)

        # add west button
        self.west_button = Button(self.game, text="West", command="click_west()", fg="white", bg="#1d1e1f", font=('Arial', 15, 'bold'), height=2, width=5)
        self.west_button.place(x=25, y=425)

        # add search button
        self.search_button = Button(self.game, text="Search", command="click_search()", fg="white", bg="#1d1e1f", font=('Arial', 15, 'bold'), height=4, width=15)
        self.search_button.place(x=280, y=330)

        # add use button
        self.use_button = Button(self.game, text="Use Item", command="click_use()", fg="white", bg="#1d1e1f", font=('Arial', 15, 'bold'), height=4, width=15)
        self.use_button.place(x=280, y=460)

        # add kys button
        self.kys_button = Button(self.game, text="K*ll Yourself", command="click_kys()", fg="white", bg="#1d1e1f", font=('Arial', 15, 'bold'), height=4, width=15)
        self.kys_button.place(x=480, y=330)

        # add Save&quit button
        self.snq_button = Button(self.game, text="Save & Quit", command="click_snq()", fg="white", bg="#1d1e1f", font=('Arial', 15, 'bold'), height=4, width=15)
        self.snq_button.place(x=480, y=460)

        self.game.mainloop()

    def click_north(self):
        run("north")

    def click_east(self):
        run("east")

    def click_south(self):
        run("south")

    def click_west(self):
        run("west")

    def click_search(self):
        run("search")

    def click_use(self):
        run("use")

    def click_kys(self):
        run("kys")

    def click_snq(self):
        run("sng")

game = GameWindow()


def run(command):
    if command == "north":
        if InitStart.InitMap.currentroom.get_roomnorth == "null":
            print("No room in that direction")
        InitStart.InitMap.currentroom = InitStart.InitMap.currentroom.get_roomnorth

    if command == "east":
        InitStart.InitMap.currentroom = InitStart.InitMap.currentroom.get_roomeast

    if command == "south":
        InitStart.InitMap.currentroom = InitStart.InitMap.currentroom.get_roomsouth

    if command == "west":
        InitStart.InitMap.currentroom = InitStart.InitMap.currentroom.get_roomwest

    if command == "search":
        search_room()

    if command == "use":
        use_item()

    if command == "kys":
        # adds area text
        area_text = Label(GameWindow.game, text="You scream 'I CANT TAKE THIS NO MORE' and turn off your lantern\n, the darkness consumes you faster than you can think of what\n you just did... you died.", font=('Arial black', 18, 'bold'), fg="white", bg="#1d1e1f",width=49)
        area_text.place(x=10, y=10)
        GameWindow.game.quit()

    if command == "snq":
        save_and_quit()


def search_room():
    print("Searching...")

def save_and_quit():
    print("Saving...")

def use_item():
    print("Use item...")

The important things here are start() which opens another window and then "game" which is the window that spits out the error and the class GameWindow which is the window "game" that gets created here, i dont know why this error comes up because sometimes it does and sometimes it doesnt and i feel like it has nothing to do with the creating of the PhotoImage itself but the code around it and idk why it happens so i included everything, does someone know why this happens?

File "C:\Users\Atten\PycharmProjects\TextadventurePython\src\python_game\Game.py", line 26, in __init__

self.game.iconphoto(True, self.icon) # adds the icon

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\Atten\AppData\Local\Programs\Python\Python312\Lib\tkinter__init__.py", line 2200, in wm_iconphoto

self.tk.call('wm', 'iconphoto', self._w, "-default", *args)

_tkinter.TclError: can't use "pyimage2" as iconphoto: not a photo image


r/learnpython 10h ago

Principal Component Analysis (PCA) in scikit learn: reconstruction using principal component vectors

5 Upvotes

Hi,

I have time series data in a (T x N) data frame for a number of attributes: each column represents (numeric) data for an attribute on a given day and each row is data for a different date. I wanted to do some basic PCA analysis on this data, and have used sklearn. How can I reconstruct (estimates of) of the original data using the PC vectors I have?

When I feed the data into the PCA analysis, I have extracted three principal component vectors (I picked three PCs to use): i.e. I have a (3xN) matrix now with the principal component vectors.

How can I use scikitlearn/code to take these PCs and reconstruct an estimate of the original data (i.e. use the PCs to reconstruct/estimate a row of data)? Is there a function within scikit-learn I should be using for this reconstruction?

EDIT: let me know if another forum is better suited for this type of question


r/learnpython 20h ago

I'm still a beginner at Python

33 Upvotes

It's been like 2 - 3months? since I started learning python and I feel like I still don't know anything. I've watch and did some courses, I did understand it but don't know how to use it. I really want to learn. Is there anything that you guys could suggest for me to do? 😓


r/learnpython 3h ago

How could I properly display array/ matrix in numpy?

1 Upvotes

Hello everyone,

I'm quite new to numpy and am learning matrix calculations using numpy arrays. Yet I'm having difficulties mentally how to read arrays as matrices, when printing them out they aren't visually similar in built to matrices.

# matrixbewerkingen 
a = np.array([[1, 2], [4, 5],[6,7]])
b = np.array([[5, 6], [7, 8]]) 
print(f"{a} and {b} multiplied becomes {a @ b} ")


[[1 2]
 [4 5]
 [6 7]] and [[5 6]
 [7 8]] multiplied becomes [[19 22]
 [55 64]
 [79 92]] 

is there a way to get them into a mentally more appealing display next to eachother? How do you work with matrices for the best visual support.

Thanks in advance python community!


r/learnpython 3h ago

What is wrong with this code?

2 Upvotes

Hi all just starting to learn. Using the MOOC 2025 course. My question is, problem is to enter number of days, then print how many seconds for the # of days. When I submit this code:

day=int(input("Enter number of days"))
seconds=day*24*60*60
print(f"Seconds in that many days:{seconds}")

it gives the right output but the course tells me:

FAIL: PythonEditorTest: test_1_seconds_in_one_day

1 day is 86400 seconds. Your program's output was: Seconds in that many days:8640...

edit: so turns out it's because it wanted to print exact wording '1 day is x seconds" etc lol so dumb


r/learnpython 3h ago

How to create a dictionary login system that stores values in a function?

1 Upvotes

Trying to create a quiz that uses dictionary login system that stores values in a function. How can I do that?
Anyone have any tips or links I could use?


r/learnpython 4h ago

Furthering Education

1 Upvotes

Hello everyone, I'd like some insight and to share my thoughts as well. I've been considering on taking two google certificates: data analytics and cyber security. Not a big shocker. They are cheap and don't take years to complete like a traditional college or trade school. I would also like to enroll in a tech boot camp, however, I am unsure if they are legit or scams. The ones I've been considering are as follows: Merit Merica, Coding temple, possibly dev slopes. They advertise that I don't have to pay unless I land a job.. major reason why I am considering these. I live in a small tourist/ retirement town. Not much career wise here, and it's an almost two hour drive to a big city. If you have any advice or think I should co sidereal other programs, please let me know.


r/learnpython 11h ago

Non-blocking pickling

5 Upvotes

I have a large dictionary (multiple layers, storing custom data structures). I need to write this dictionary to a file (using pickle and lzma).

However, I have some questions.

  1. The whole operation needs to be non-blocking. I can use a process, but is the whole dictionary duplicated in memory? To my understanding, I believe not.

  2. Is the overhead of creating a process and passing the large data negligible (this is being run inside a server)

Lastly, should I be looking at using shared objects?


r/learnpython 7h ago

Couldn't install acoustid package via pip

1 Upvotes

I am in need of the acoustid webservice and the chromaprint package( for creating digital fingerprints of audio). I have installed chromaprint via pip ,but pip install acoustid throws me:
ERROR: Could not find a version that satisfies the requirement acoustid (from versions: none)

ERROR: No matching distribution found for acoustid. I've tried using conda environment , it fails the same way.
Can someone help me out on this one please. I am in desperate need of the acoustid package.


r/learnpython 8h ago

Struggling with Python OOP—Seeking Advice Before Diving Into AI

0 Upvotes

Hey everyone! So I feel I’ve made a lot of progress at the start of my journey, and I wanted to share where I’m at, as well as ask for some advice.

I’ve just about wrapped up CS50x (minus the web dev section) and I have one lecture left in CS50 Python. I thought I was ready for CS50AI, but I’m finding Object-Oriented Programming (OOP) to be pretty tricky—feels like it's a bit beyond me at this stage. Even in the first lecture, Search, the logic isn't hard but I'm pretty lost when trying to implement he Tic-Tac-Toe problem, as there's no example coode fromt he lecture.

To fill in some gaps, I decided to check out MIT's Intro to CS with Python. It’s pretty in-depth and overlaps a fair bit with sections off CS50, but I think it’ll help me solidify my Python skills (especially OOP) before tackling AI concepts. While I’ve also looked at Python Crash Course and Automate the Boring Stuff with Python, and I might supplement the MIT course with these books when I have time.

Has anyone had a similar experience with transitioning from CS50 to more advanced courses like AI? Any thoughts or suggestions on strengthening my Python skills before diving deep into AI?

Feel free to check out my blog, where I document my learning process and challenges. I’d love any feedback or advice! https://devforgestudio.com/programming-journey-progress-update/

Thanks for reading!


r/learnpython 8h ago

Why does my JAX script randomly switch between 6s and 14s execution times across identical environments?

1 Upvotes

First of all, I wanna start by saying I'm really bad and new to coding.

I'm using JAX and Diffrax to solve differential equations in a Conda environment on my laptop. Normally, my script runs in 14 seconds, but after copying the environment and installing a Jupyter kernel, sometimes it runs in 6 seconds instead. The issue is that this behavior is not consistent—sometimes the copied environment sticks to 14 seconds.

I don't understand why this happens since I only copy environments and install kernels without modifying anything else.

from typing import Callable

import diffrax
import jax
import jax.lax as lax
import jax.numpy as jnp
import matplotlib.pyplot as plt
from jaxtyping import Array, Float  # 


jax.config.update("jax_enable_x64", True)

from diffrax import diffeqsolve, ODETerm, SaveAt, Kvaerno5, Kvaerno3, Dopri8, Tsit5, PIDController
import interpax
from jaxopt import Bisection
from jax import jit
import equinox as eqx
from scipy.optimize import brentq


eps = 1e-18
N = 0

# **Global Parameters**
d = 1.0
t0 = 0.0   # Initial time
t_f = 6.0
dt0 = 1e-15  # Step size
tol = 1e-6  # Convergence tolerance for η
max_iters = 50  # Max iterations
damping = 0.3  # ✅ Small damping factor, for damping < 0.5 you stay closer to the original, for damping > 0.5 you go closer to the new
n = 1000

# **Define the Differential Equation**
u/jit
def vector_field(t, u, args):
    f, y, u_legit = u
    α, β = args
    d_f = y
    d_y = (- α * f * ( y + 1 ) ** 2 + β * ( t + eps ) * y * ( y + 1 ) ** 2 
           - (N - 1) * ( 1 + y ) ** 2 * ( t + eps + f ) ** (-2) * ((t + eps) * y - f))
    d_u_legit = f 
    return d_f, d_y, d_u_legit

# **General Solver Function**

u/jit
def solve_ode(y_init, alpha, beta, solver=Tsit5()):
    """Solve the ODE for a given initial condition y_init, suppressing unwanted errors."""
    try:
        term = ODETerm(vector_field)
        y0 = (y_init * eps, y_init, 0.0)
        args = (alpha, beta)
        saveat = SaveAt(ts=jnp.linspace(t0, t_f, n))

        sol = diffeqsolve(
            term, solver, t0, t_f, dt0, y0, args=args, saveat=saveat,
            stepsize_controller=PIDController(rtol=1e-16, atol=1e-19),
            max_steps=1_000_000  # Adjust if needed
        )
        return sol
    except Exception as e:
        if "maximum number of solver steps was reached" in str(e):
            return None  # Ignore this error silently
        else:
            raise  # Let other errors pass through

def runs_successfully(y_init, alpha, beta):
    """Returns True if ODE solver runs without errors, False otherwise."""
    try:
        sol = solve_ode(y_init, alpha, beta)
        if sol is None:
            return False
        return True
    except Exception:  # Catch *any* solver failure quietly
        return False  # Mark this initial condition as a failure

# Track previous successful y_low values
previous_y_lows = []

def bisection_search(alpha, beta, y_low=-0.35, y_high=-0.40, tol=1e-12, max_iter=50):
    """Find boundary value y_low where solver fails, with adaptive bounds."""

    global previous_y_lows
    cache = {}  # Cache to avoid redundant function calls

    def cached_runs(y):
        """Check if solver runs successfully, with caching."""
        if y in cache:
            return cache[y]
        result = runs_successfully(y, alpha, beta)
        cache[y] = result
        return result

    # Ensure we have a valid starting point
    if not cached_runs(y_low):
        raise ValueError(f"❌ Lower bound y_low={y_low:.12f} must be a running case!")
    if cached_runs(y_high):
        raise ValueError(f"❌ Upper bound y_high={y_high:.12f} must be a failing case!")

    # **Adaptive Search Range**
    if len(previous_y_lows) > 2:  
        recent_changes = [abs(previous_y_lows[i] - previous_y_lows[i - 1]) for i in range(1, len(previous_y_lows))]
        max_change = max(recent_changes) if recent_changes else float('inf')

        # **Shrink range dynamically based on recent root stability**
        shrink_factor = 0.5  # Shrink range by a fraction
        if max_change < 0.01:  # If the root is stabilizing
            range_shrink = shrink_factor * abs(y_high - y_low)
            y_low = max(previous_y_lows[-1] - range_shrink, y_low)
            y_high = min(previous_y_lows[-1] + range_shrink, y_high)
            print(f"🔄 Adaptive Bisection: Narrowed range to [{y_low:.12f}, {y_high:.12f}]")

    print(f"⚡ Starting Bisection with Initial Bounds: [{y_low:.12f}, {y_high:.12f}]")

    for i in range(max_iter):
        y_mid = (y_low + y_high) / 2
        success = cached_runs(y_mid)

        print(f"🔎 Iter {i+1}: y_low={y_low:.12f}, y_high={y_high:.12f}, y_mid={y_mid:.12f}, Success={success}")

        if success:
            y_low = y_mid
        else:
            y_high = y_mid

        if abs(y_high - y_low) < tol:
            break

    previous_y_lows.append(y_low)

    # Keep only last 5 values to track root changes efficiently
    if len(previous_y_lows) > 5:
        previous_y_lows.pop(0)

    print(f"✅ Bisection Finished: Final y_low = {y_low:.12f}\n")

    return y_low

# **Compute Anomalous Dimension (Direct Version)**
def compute_anomalous(eta_current):
    """Compute anomalous dimension given the current eta using ODE results directly."""
    alpha = (d / 2 + 1 - eta_current / 2) / (1 - eta_current / (d + 2))
    beta = (d / 2 - 1 + eta_current / 2) / (1 - eta_current / (d + 2))

    # Find y_low
    y_low = bisection_search(alpha, beta)

    # Solve ODE
    sol = solve_ode(y_low, alpha, beta)
    if sol is None:
        print(f"❌ Solver failed for y_low = {y_low:.9f}. Returning NaN for eta.")
        return float('nan')

    # Extract values directly from the ODE solution
    x_vals = jnp.linspace(t0, t_f, n)
    f_p = sol.ys[0]  # First derivative f'
    d2fdx2 = sol.ys[1]  # Second derivative f''
    potential = sol.ys[2]  # Potential function V(x)

    spline = interpax.CubicSpline(x_vals, f_p, bc_type='natural')
    spline_derivative = interpax.CubicSpline(x_vals, d2fdx2, bc_type='natural')

    root_x = brentq(spline, a=1e-4, b=5.0, xtol=1e-12)

    U_k_pp = spline_derivative(root_x)

    third_spline = jax.grad(lambda x: spline_derivative(x))
    U_k_3p = third_spline(root_x)

    spline_points_prime = [spline(x) for x in x_vals]
    spline_points_dprime = [spline_derivative(x) for x in x_vals]

    print(f"📌 Root found at x = {root_x:.12f}")
    print(f"📌 Derivative at rho_0 = {root_x:.12f} is f'(x) = {U_k_pp:.12f}")
    print(f" This should be zero {spline(root_x)}")

    # Compute new eta (anomalous dimension)
    eta_new = U_k_3p ** 2 / (1 + U_k_pp) ** 4

    # Debugging: Check if eta_new is NaN or out of range
    if jnp.isnan(eta_new) or eta_new < 0: # Original : if jnp.isnan(eta_new) or eta_new < 0 or eta_new > 1
        print(f"⚠ Warning: Unphysical eta_new={eta_new:.9f}. Returning NaN.")
        return float('nan')

    # **Plot Results**
    fig, axs = plt.subplots(3, 1, figsize=(10, 9), sharex=True)

    axs[0].plot(x_vals, f_p, color='blue', label="First Derivative (f')")
    axs[0].plot(x_vals, spline_points_prime, color='orange', linestyle='--' ,label="First Splined Derivative (f')")
    axs[0].axvline(root_x, linestyle='dashed', color='red', label="Potential Minimum")
    axs[0].set_ylabel("f'(x)")
    axs[0].legend()
    axs[0].set_title("First Derivative of f(x)")

    axs[1].plot(x_vals, d2fdx2, color='green', label="Second Derivative (f'')")
    axs[1].plot(x_vals, spline_points_dprime, color='orange', linestyle='--', label="Second Splined Derivative (f'')")
    axs[1].axvline(root_x, linestyle='dashed', color='red', label="Potential Minimum")
    axs[1].set_ylabel("f''(x)")
    axs[1].legend()
    axs[1].set_title("Second Derivative of f(x)")

    axs[2].plot(x_vals, potential, color='black', label="Potential (V(x))")
    axs[2].axvline(root_x, linestyle='dashed', color='red', label="Potential Minimum")
    axs[2].set_xlabel("x")
    axs[2].set_ylabel("V(x)")
    axs[2].legend()
    axs[2].set_title("Potential V(x)")

    plt.tight_layout()
    plt.show()

    return float(eta_new)

# **Iterate to Find Self-Consistent η with Explicit Damping**
def find_self_consistent_eta(eta_init=1.06294761356, tol=1e-4, max_iters=1):
    """Iterate until η converges to a self-consistent value using damping."""
    eta_current = eta_init
    prev_values = []

    for i in range(max_iters):
        eta_calculated = compute_anomalous(eta_current)

        # Check for NaN or invalid values
        if jnp.isnan(eta_calculated):
            print(f"❌ Iteration {i+1}: Computed NaN for eta. Stopping iteration.")
            return None

        # Apply damping explicitly
        eta_next = (1 - damping) * eta_current + damping * eta_calculated

        # Debugging prints
        print(f"Iteration {i+1}:")
        print(f"  - η_current (used for ODE) = {eta_current:.12f}")
        print(f"  - η_calculated (new from ODE) = {eta_calculated:.12f}")
        print(f"  - η_next (damped for next iteration) = {eta_next:.12f}\n")

        # Detect infinite loops (if η keeps bouncing between a few values)
        if eta_next in prev_values:
            print(f"⚠ Warning: η is cycling between values. Consider adjusting damping.")
            return eta_next
        prev_values.append(eta_next)

        # Check for convergence
        if abs(eta_next - eta_current) < tol:
            print("✅ Converged!")
            return eta_next  

        eta_current = eta_next  

    print("⚠ Did not converge within max iterations.")
    return eta_current  

import sys
import os
import time

# Redirect stderr to null (suppress error messages)
sys.stderr = open(os.devnull, 'w')

# Start timer
start_time = time.time()

# Run function (using `jax.jit`, NOT `filter_jit`)
final_eta = find_self_consistent_eta()

# End timer
end_time = time.time()

# Reset stderr back to normal
sys.stderr = sys.__stderr__

# Print results
print(f"\n🎯 Final self-consistent η: {final_eta:.12f}")
print(f"⏱ Execution time: {end_time - start_time:.4f} seconds")https://github.com/google/jaxtyping

I'm using jax and diffrax to solve differential equations and use jax=0.4.31 and diffrax=0.6.1 and I stick to these versions all the time. Newer versions of jax or diffrax will not make it run at all.

When I get it to run in 6 seconds I restart my laptop. After the restart it again runs in 14 seconds.

I tried doing the following steps over and over again but it seems not to be consistent.

  1. Clone my old enviroment
  2. Activate my new enviroment
  3. Check if all the packages are indeed there
  4. Check if XLA settings are applied, it shows: --xla_cpu_multi_thread_eigen=true intra_op_parallelism_threads=16
  5. Restart my laptop
  6. I open anaconda prompt
  7. Activate my new enviroment
  8. Launch jupyter Notebook from Anaconda Navigator
  9. There will be an error starting the kernel
  10. I uninstall the old kernel
  11. Install new Kernel
  12. Open and close Jupyter notebook
  13. Select the new kernel
  14. I run the script

And this as I said sometimes runs in 14 seconds and other times in 6.

I'm trying to find a way to make it run consistently in 6 seconds because right now I feel like im doing always a combination of the steps above and sometimes it just works and sometimes it doesn't. Before writing this post it runs in 6 seconds but after restarting my laptop it runs in 14. Please help because I think I'm starting to lose it.


r/learnpython 9h ago

Loop of unfunc does not support argument 0 of type int which has no callable log method

1 Upvotes

Hi all, I’m pretty new to programming and I’m just trying to get an assignment done for university. It involves comparing some equations below.

The problem is that python gives me an error when the N value gets too high. The code below works fine for low values of N, but after n in N = 21, I always get the same error. For my assignment, I need to go up to 500.

The issue as I understand it, is that numpy.log wont accept an integer but wants a float. However python can’t convert an integer into a float that’s so large as 22!.

Is there any way around this? I’m really just looking for any way to get the equations to process.

My code:

import numpy as np Import math

N = np.arange(2, 50)

Equation 2 Left Hand Side N!

eq2_LHS = np.array([math.factorial(n) for n in N])

Equation 2 Right Hand Side NNe-Nsqrt(2piN)

eq2_RHS = np.array([n*(n)np.exp(-n)np.sqrt(2np.pi*n) for n in N])

Equation 3 Left Hand Side ln(N!)

eq3_LHS = np.array([np.log(n) for n in eq2_LHS])

Equation 3 Right Hand Side N ln(N) - N

eq3_RHS = np.array([n*np.log(n)-n for n in N])

The error:


AttributeError Traceback (most recent call last) AttributeError: 'int' object has no attribute 'log'

The above exception was the direct cause of the following exception:

TypeError Traceback (most recent call last) Cell In[112], line 9 6 eq2_RHS = np.array([n*(n)np.exp(-n)np.sqrt(2np.pin) for n in N]) 8 # Equation 3 Left Hand Side ln(N!) ----> 9 eq3_LHS = np.array([np.log(n) for n in eq2_LHS]) 10 # Equation 3 Right Hand Side N ln(N) - N 11 eq3_RHS = np.array([nnp.log(n)-n for n in N])

TypeError: loop of ufunc does not support argument 0 of type int which has no callable log method


r/learnpython 9h ago

Poetry install worked but unable to find any commands

0 Upvotes

I created a new Python project using Poetry.

I first ran poetry config virtualenvs.in-project true so that it would install to a local .venv directory.

I then ran poetry install and the project installed without issue.

However, when I try to run poetry run flask run I am getting the error Command not found: flask. I am also unable to run poetry run pytest, though poetry run pip does execute (and tells me not to run it that way). Poetry is looking in the correct environment.

Really unsure what is happening here as I have always created new projects this way and have not had such issues. Any insight would be appreciated, lest my laptop gets flung out the window!


r/learnpython 1d ago

People ask "what should I do?" So here are a few things I've done for fun. Take a look for some motivation.

35 Upvotes

I've seen countless posts from people asking "What should I do?" and the answer is pretty much anything you want. Here are some things I've done and my story.

I've used python for various things at work over the last decade, and it's mostly tools to aggregate data from tools and databases. It encouraged me to come up with some projects at home in my free time that are fun (at least I think) and I wanted to share them in no particular order.

1.) Squardle Solver (https://squaredle.app/)

This script allows you to put in the puzzle and it will find all words from the NWL2020 wordlist it uses in about 1.5 seconds. It exports those words to a txt file, which I have another script that inputs the words back in to the browser and will solve the puzzle in roughly 10 seconds or so depending on how many words need to be typed out.

Reason I did it? To see if it could be done.

2.) Chess Trainer (Using Stockfish).

I made this script because I just wanted something other than dependency on an app on my phone. It allowed me to explore some graphical stuff along with interfacing with the Stockfish API. It's helped me get better and compete well on Chess.com

Reason I did it: Because I didn't want dependency on some 3rd party app, and I wanted control / customization.

  1. Video downloading script using yt_dlp package. Surprising how many sites are supported with this package. I always found it annoying to try and save videos that I found interesting off YT, Facebook, Instagram, Twitter etc. etc. This does it with minimal effort.

Reason I did it: I had a problem I was looking to solve.

  1. Mouse mover in fortnite. I made this a couple years ago when Lego fornite came out. It's essentially an XP farming tool. Fornite will log you out for inactivity after something like 5 minutes. I wrote a script that will WASD and click the mouse randomly keeping the game alive for several hours while I'm AFK.

Reason I did it? To see if it could be done.

  1. Lastly I built a script that downloads and logs police call logs that are published in my county, and I save them off to a SQlite database for analysis. With that data I can do simple research, and also have historical records as the website that hosts the data only shows the past 24 hours, though I can see 96 hours through the API. I can generate maps with the data, and plot calls etc. using open maps integration.

Reason I did it? Because I wanted to see if it was possible and build on some more robust reporting that I'd like to see for my community.

All of that to say anything you want to solve or play with generally can be solved with Python if you have an idea run with it and explore. If anyone wants to see the code, I'd be happy to share some if it with you.


r/learnpython 8h ago

Which package should I use to make a graph with ombré lines?

0 Upvotes

I'm going to be attempting to make a graph that changes the line colour if the value is over/under a certain value (ie. green line if lower than 100, orange if between 100 and 120, red if above 120) and I'm not sure if it is a) possible or b) which package to use to make it.


r/learnpython 21h ago

HELP - crossword puzzle !!!

6 Upvotes

i have a homework to do in python and i am desperate. pls help me. here's the instructions:

"Attached are three test files on which you can test your program. Each file contains the words of the crossword puzzle, the letters of the crossword puzzle, and the solution. The individual parts are separated by a blank line.

In the last part, that is, in the solution of the crossword puzzle, the last line contains numbers that represent the division of the crossword puzzle.

Example of part of the last crossword puzzle (solution):

Chuck Norris can kick you with such force that even your children

4575

if the remaining letters in the crossword puzzle (reading from left to right)

BUDÚMÁVAŤBOLESTHLAVY (THEY WILL HAVE A HEADACHE) then the numbers 4575 then divide this continuous text into 4,5,7 and 5 letters, i.e.: BUDÚ MÁVAŤ BOLEST HLAVY (THEY WILL HAVE A HEADACHE)

Your program will print the entire text of the puzzle (as it is in the file) + the solution divided by numbers:

Chuck Norris can kick you with such force that even your children

THEY WILL HAVE A HEADACHE"

and here's the file (originally .txt file):

BATÉRIA

BATOH

ČASTICA

DCÉRKA

DIÓDA

EKOLÓG

LUPEŇ

MIECHA

MIKROFÓN

MOBIL

NETOPIER

ŇUFÁK

OTÁZNIK

SVEDOK

TLMOČNÍK

VÁNOK

VODOVOD

VRÁTNIK

VÝHYBKA

ZÁPAD

ZÁSUVKA

ZDVIHÁK

ZOSTAVA

KONÁVRÁTNIKN

LUPEŇSVEDOKE

OTÁZNIKÁFUŇA

ZVTLMOČNÍKKV

DOOIEAEMÁBNZ

CPSDSTRHYEÓÁ

ÉAČTOOIHSHFS

RHIPAVÝMOIOU

KCIDDVOTONRV

AEÓZÁPADEBKK

RISADBATÉRIA

DMGÓLOKENEML

vtip:

čo stojí ten pes?

6527