Tuesday, November 25, 2025

Python library for all standard data structures.

 pygorithm-module-in-python/


# Help on package pygorithm.data_structures
help(data_structures)
Output:
NAME
    pygorithm.data_structures - Collection of data structure examples

PACKAGE CONTENTS
    graph
    heap
    linked_list
    quadtree
    queue
    stack
    tree
    trie
#Example 1:
# import the required data structure
from pygorithm.data_structures import stack


# create a stack with default stack size 10
myStack = stack.Stack()

# push elements into the stack
myStack.push(2)
myStack.push(5)
myStack.push(9)
myStack.push(10)

# print the contents of stack
print(myStack)

# pop elements from stack
myStack.pop()
print(myStack)

# peek element in stack
print(myStack.peek())

# size of stack
print(myStack.size())
Output:
2 5 9 10
2 5 9
9
3
#Example 2:
# to get code for BinarySearchTree
BStree = tree.BinarySearchTree.get_code()
print(BStree)
Output:
class BinarySearchTree(object):
   
    def __init__(self):
        self.root = None

    def insert(self, data):
        """
        inserts a node in the tree
        """
        if self.root:
            return self.root.insert(data)
        else:
            self.root = BSTNode(data)
            return True

    def delete(self, data):
        """
        deletes the node with the specified data from the tree
        """
        if self.root is not None:
            return self.root.delete(data)

    def find(self, data):
        if self.root:
            return self.root.find(data)
        else:
            return False

    def preorder(self):
        """
        finding the preorder of the tree
        """
        if self.root is not None:
            return self.root.preorder(self.root)

    def inorder(self):
        """
        finding the inorder of the tree
        """
        if self.root is not None:
            return self.root.inorder(self.root)

    def postorder(self):
        """
        finding the postorder of the tree
        """
        if self.root is not None:
            return self.root.postorder(self.root)
    
    @staticmethod
    def get_code():
        """
        returns the code of the current class
        """
        return inspect.getsource(BinarySearchTree)
Example 3:
To get complexities for the following scripts:
# create a stack with default stack size 10
Bsort = sorting.bubble_sort.time_complexities()
Output:
Best Case: O(n), Average Case: O(n ^ 2), Worst Case: O(n ^ 2).

For Improved Bubble Sort:
Best Case: O(n); Average Case: O(n * (n - 1) / 4); Worst Case: O(n ^ 2)
Source code of this package: https://github.com/OmkarPathak/pygorithm

Wednesday, November 19, 2025

Integer caching in python

 Python (specifically the default CPython implementation) uses integer caching to optimize performance and memory usage by pre-allocating a range of commonly used small integer objects. 


How Integer Caching Works
  • Cached Range: CPython pre-loads all integer objects in the range of -5 to 256 during interpreter startup.
  • Singleton Instances: When you assign a variable an integer value within this range, Python simply returns a reference to the existing, pre-allocated object rather than creating a new one. This makes each integer in this range a singleton.
  • Memory and Performance: This optimization saves significant memory and computation time because small integers are used very frequently (e.g., as loop counters or list indices).
  • Immutability: Integer caching is safe because integers are immutable data types. Sharing the same object across multiple variables does not cause issues, as any operation that appears to modify an integer actually creates a new integer object. 
Key Behaviors and Examples
The effect of integer caching is most apparent when using the operator, which checks for object identity (same memory location) rather than value equality ( operator).
  • Within the Cached Range:
  • >>> a = 100
  • >>> b = 100
  • >>> a is b
  • True
  • >>> id(a) == id(b)
  • True
  • and point to the same memory location because 100 is within the range.
  • Outside the Cached Range (in the Python REPL):
  • >>> x = 257
  • >>> y = 257
  • >>> x is y
  • False
  • >>> id(x) == id(y)
  • False
  • and are different objects with different memory locations because 257 is outside the cached range. 
Compiler Optimization (Scripts vs. REPL)
Interestingly, the behavior for integers outside the range can differ between a Python interactive shell (REPL) and running code from a Python file (script).
  • When running a whole script, the Python compiler can optimize and reuse identical integer literals even outside the standard range, making return for .
  • In the REPL, code is compiled line-by-line, limiting this optimization and making the distinct object creation more apparent. 
Best Practices
Do not rely on the operator for integer value comparison, except when checking for (which is always a singleton). The behavior of for integers can vary across different Python implementations (e.g., CPython, PyPy) and even different versions of the same implementation. 

Always use the operator to check if two variables have the same value. 



Tuesday, November 18, 2025

What apparatus is used to measure the electrostatic force between two objects

 A torsion balance is the apparatus used to measure the electrostatic force between two objects. This device, famously used by Charles-Augustin de Coulomb, uses a suspended rod with a charged ball and measures the force by the twist of a fiber, which is proportional to the torque created by the electrostatic repulsion or attraction.

  • Torsion Balance: This is a sensitive instrument consisting of a rod suspended from its center by a thin fiber.
  • How it works: A charged object is placed near a second charged ball on the rod. The resulting electrostatic force causes the rod to twist the fiber through a specific angle. By measuring this angle and knowing the properties of the fiber, the force can be calculated. [1, 4, 5]

AI responses may include mistakes.

What apparatus is used to measure the gravitational force between two objects?

 The primary apparatus for measuring the gravitational force between two objects is a torsion balance, famously used in the Cavendish experiment. For measuring the gravitational force of a planet, a gravimeter is used, which can be based on a spring or a free-fall method. [1, 2, 3, 4, 5]


Torsion Balance
  • Principle: This device measures the extremely small twist in a wire caused by the gravitational pull between two large, known masses and two smaller masses suspended at the ends of a rod.
  • Function: By measuring the angle of the twist (often using a mirror and laser pointer), the force can be calculated. This was the first method to accurately measure the gravitational constant, . [4, 5, 6, 7, 8]
Gravimeter
  • Principle: A gravimeter is used to measure the Earth's gravitational field, which is a measure of gravitational acceleration (). It works on the principle that gravitational force is a type of acceleration.
  • Function: It measures the gravitational force exerted by the Earth on an object.
    • Spring-based gravimeters: Use a spring to counteract the force of gravity. The change in the spring's length is calibrated to the force required to balance the pull.
    • Absolute gravimeters: Directly measure the acceleration of a free-falling mass in a vacuum. [1, 2, 3, 9, 10]

AI responses may include mistakes.

Saturday, June 21, 2025

Basic Flask web app

 from flask import Flask

app = Flask(__name__)


#In Flask, URL rules can be added using either the @app.route() decorator or the app.add_url_rule() method.


@app.route('/')

def hello_world():

   return '<center><h1><I>Hello World</I></h1></center>'


def bye_world():

   return '<center><h1><I>Bye World</I></h1></center>'


app.add_url_rule('/bye', 'bye', bye_world)


if __name__ == "__main__":

   app.run(debug = True)

Thursday, May 1, 2025

Query for finding high dividend paying stocks

 Post the following query in Screen.in, to get list of high dividend yield stocks:


Dividend yield > 6


AND


Dividend last year > 1000


AND


Dividend preceding year > 1000


AND


Profit after tax > 0 

_________________________________________________________________________

you can further add few more filters to know which ones are low priced now

AND

Price to Earning < Industry PE 

AND

%Down from 52w high > 20



Resources for preparing for SDE2/SDE3 roles

Software Design principals and patterns. (Design Patterns)  1.  https://bytebytego.com/ 2.  https://refactoring.guru/