Sunday, 29 March 2026

How to calculate number of zeros of analytic function and their values via Python

cat  pythonComplex01.py
import numpy as np
from cxroots import Circle

def count_zeros(f, df, contour_points):
   """
   Counts zeros of f(z) within the region enclosed by contour_points.
   f: The analytic function
   df: The derivative of the function
   contour_points: Array of complex numbers forming a closed loop
   """
   # Evaluate f and f' at each point on the contour
   fz = f(contour_points)
   dfz = df(contour_points)
   # Calculate the integrand: f'(z) / f(z)
   integrand = dfz / fz
   # Calculate dz (the difference between consecutive points)
   dz = np.diff(contour_points, append=contour_points[0])
   # Compute the contour integral using the trapezoidal rule
   integral = np.sum(integrand * dz)
   # The result should be an integer
   return int(np.round((integral / (2j * np.pi)).real))

t = np.linspace(0, 2 * np.pi, 1000)
circle = 3 * np.exp(1j * t)

f = lambda z: z**4 + 4*z**3 - 8*z - 2
df = lambda z: 4*z**3 + 12*z**2 -8   
print("The Argument Principle and the Logarithmic Derivative in Complex Analysis\n")
print("f(z) = z**4 + 4*z**3 - 8*z - 2 ; df/dz(z) = 4*z**3 + 12*z**2 -8\n")
print(f"Number of zeros in circle of radius 3: {count_zeros(f, df, circle)}")
# Define a circle of radius 3 centered at the origin
C = Circle(0, 3)
# Find all roots within the circle
roots = C.roots(f, df)
print(roots,"\n")

circle = 1 * np.exp(1j * t)
print(f"Number of zeros in circle of radius 1: {count_zeros(f, df, circle)}")
# Define a circle of radius 3 centered at the origin
C = Circle(0, 1)
# Find all roots within the circle
roots = C.roots(f, df)
print(roots)

$ python  pythonComplex01.py
The Argument Principle and the Logarithmic Derivative in Complex Analysis

f(z) = z**4 + 4*z**3 - 8*z - 2 ; df/dz(z) = 4*z**3 + 12*z**2 -8

Number of zeros in circle of radius 3: 3
Multiplicity |               Root               
------------------------------------------------
     1       | -1.741963784303 +0.000000000000i
     1       | -0.258036215697 +0.000000000000i
     1       |  1.334414218339 +0.000000000000i  

Number of zeros in circle of radius 1: 1
Multiplicity |               Root               
------------------------------------------------
     1       | -0.258036215697 +0.000000000000i


















$ cat  pythonComplex02.py
import numpy as np
from cxroots import Circle

def count_zeros(f, df, contour_points):
   """
   Counts zeros of f(z) within the region enclosed by contour_points.
   f: The analytic function
   df: The derivative of the function
   contour_points: Array of complex numbers forming a closed loop
   """
   # Evaluate f and f' at each point on the contour
   fz = f(contour_points)
   dfz = df(contour_points)
   # Calculate the integrand: f'(z) / f(z)
   integrand = dfz / fz
   # Calculate dz (the difference between consecutive points)
   dz = np.diff(contour_points, append=contour_points[0])
   # Compute the contour integral using the trapezoidal rule
   integral = np.sum(integrand * dz)
   # The result should be an integer
   return int(np.round((integral / (2j * np.pi)).real))

t = np.linspace(0, 2 * np.pi, 1000)
circle = 3 * np.exp(1j * t)

f = lambda z: z**13 + 5*z + 2  
df = lambda z: 13*z**12 + 5   

print("The Argument Principle and the Logarithmic Derivative in Complex Analysis\n")
print("f(z) = z**13 +5*z +2  ; df/dz(z) = 13*z**12 + 5\n")
print(f"Number of zeros in circle of radius 3: {count_zeros(f, df, circle)}")
# Define a circle of radius 3 centered at the origin
C = Circle(0, 3)
# Find all roots within the circle
roots = C.roots(f, df)
print(roots)

circle = 1 * np.exp(1j * t)
print(f"Number of zeros in circle of radius 1: {count_zeros(f, df, circle)}")
# Define a circle of radius 3 centered at the origin
C = Circle(0, 1)
# Find all roots within the circle
roots = C.roots(f, df)
print(roots)

~/ComplexAnalysis
python  pythonComplex02.py
The Argument Principle and the Logarithmic Derivative in Complex Analysis

f(z) = z**13 +5*z +2  ; df/dz(z) = 13*z**12 + 5

Number of zeros in circle of radius 3: 13
RootError encountered when subdivding Annulus sector: center=0.000+0.000i, r0=1.129, r1=1.221, phi0=7.414, phi1=8.168 into:
Annulus sector: center=0.000+0.000i, r0=1.129, r1=1.156, phi0=7.414, phi1=8.168
Annulus sector: center=0.000+0.000i, r0=1.156, r1=1.221, phi0=7.414, phi1=8.168
Multiplicity |               Root               
------------------------------------------------
     1       | -1.063154526530 -0.299112694677i
     1       | -1.063154526530 +0.299112694677i
     1       | -0.771405797002 -0.815087403529i
     1       | -0.771405797002 +0.815087403529i
     1       | -0.399998657881 +0.000000000000i
     1       | -0.262722673288 -1.111020328751i
     1       | -0.262722673288 +1.111020328751i
     1       |  0.326597088580 -1.109580758477i
     1       |  0.326597088580 +1.109580758477i
     1       |  0.837706346436 -0.811700768559i
     1       |  0.837706346436 +0.811700768559i
     1       |  1.132978890745 +0.297012150385i
     1       |  1.132978890745 -0.297012150385i
Number of zeros in circle of radius 1: 1
Multiplicity |               Root               
------------------------------------------------
     1       | -0.399998657881 +0.000000000000i











Saturday, 12 April 2025

Решение задач №9 КЕГЭ Информатика в пакетном режиме ( Python 3.13.2)

 Рассмотрены примеры

https://inf-ege.sdamgia.ru/problem?id=76677

https://inf-ege.sdamgia.ru/problem?id=55596












(.env) boris@fedora41KDE:~/KEGE2025/KRASN/EXCEL09$ cat djs76677VR-09.py

import openpyxl
import csv
# input excel file path
inputExcel = '/home/boris/Downloads/0976677.xlsx'
newWorkbook = openpyxl.load_workbook(inputExcel)
# getting the active workbook sheet(Bydefault-->Sheet1)
worksheet = newWorkbook.active
# Opening a output csv file in write mode
F = open("result0976677.csv", 'w')
OutCsv = csv.writer(F,delimiter=";")
for eachrow in worksheet.rows:
      OutCsv.writerow([cell.value for cell in eachrow])
F.close()

f = list(map(lambda x: list(map(int, x.split(';'))), \
         open('./result0976677.csv').readlines()))
count = 0
for a in f:
 averg = sum(a)/len(a)
 zeven = [ x for x in a if x%2 == 0 and x > averg ]
 zodd = [ x for x in a if x%2 == 1 and x > averg]
 if len(zodd) < len(zeven):
    if sum(x for x in a if x%2==0) < sum(x for x in a if x%2==1):
                    count += 1
print(count)

(.env) boris@fedora41KDE:~/KEGE2025/KRASN/EXCEL09$ python djs76677VR-09.py

232

(.env) boris@fedora41KDE:~/KEGE2025/KRASN/EXCEL09$ cat djs55596V-09.py

import openpyxl
import csv
# input excel file path
inputExcel = '/home/boris/Downloads/0955596.xlsx'
newWorkbook = openpyxl.load_workbook(inputExcel)
# getting the active workbook sheet(Bydefault-->Sheet1)
worksheet = newWorkbook.active
# Opening a output csv file in write mode
F = open("result0955596.csv", 'w')
OutCsv = csv.writer(F,delimiter=";")
for eachrow in worksheet.rows:
      OutCsv.writerow([cell.value for cell in eachrow])
F.close()
#############################################################
# Solve problem via exporting xlsx file to csv in batch mode
#############################################################
matrix = list(map(lambda x: list(map(int, x.split(';'))), \
         open('./result0955596.csv').readlines()))

allString = []
for string in matrix:

         for z in string:
            allString.append(z)  
okstr = [string for string in matrix \
              if any([string.count(x)==1 and allString.count(x)==46 for x in string])]
print(len(okstr))

(.env) boris@fedora41KDE:~/KEGE2025/KRASN/EXCEL09$ python djs55596V-09.py

445

References

https://statusneo.com/excel-automation-with-pythons-openpyxl-a-comprehensive-guide/


Saturday, 20 April 2024

Convertion Excel SpreadSheets into SQLITE3 Database via python on Fedora 40 WKS

 Original task proposed here  https://inf-ege.sdamgia.ru/problem?id=47000 

Python script code

(.env) boris@fedora40RCKDE:~/EXCEL$ cat excelSqlite.py
import sqlite3
import pandas as pd
 
con = sqlite3.connect('cps.db')
wb = pd.read_excel('031.xlsx',sheet_name = None)
for sheet in wb:
   wb[sheet].to_sql(sheet,con,index=False)
con.commit()
con.close()

$  rm -f cps.db
$  touch -f cps.db
$  python excelSqlite.py

Database tables structure

















SQL QUERY OUTPUT
















SOLVE USE SAMPLE OUTPUT obtained via excel filtering

















Sunday, 10 October 2021

Python C++ Wrapper для решения одной задачи YandexQ используя решето Эратосфена как процедуру C++

Этот пост является непосредственным продолжением http://lxer.com/module/newswire/view/306255/index.html , что приведет к значительному увеличению производительности по сравнению с версией Python для процедуры решета Эратосфена.

Мы намерены использовать для решения https://github.com/mathbunnyru/python-cpp-extension

Загрузите и распакуйте tarball в Fedora 34 с установленными «инструментами разработки C» и python-devel. Настройте python venv в вашем рабочем каталоге

$ python3 -m venv .env

$ source .env/bin/activate

  and run straight away:-

$ python setup.py install

(.env) [boris@fedora34server python-cpp-extension-delta]$ ll

total 36

drwxrwxr-x. 5 boris boris   89 Oct 10 09:37 build

drwxrwxr-x. 2 boris boris   90 Oct 10 09:37 cpp_python_extension.egg-info

-rw-rw-r--. 1 boris boris  751 Oct 10 11:57 delta16.py

drwxrwxr-x. 2 boris boris   61 Oct 10 09:37 dist

-rw-rw-r--. 1 boris boris   85 Oct 10 09:18 MyProg.py

-rw-rw-r--. 1 boris boris 1192 Oct 10 09:18 README.md

-rw-rw-r--. 1 boris boris  682 Oct 10 09:18 setup.py

-rw-rw-r--. 1 boris boris  450 Oct 10 09:18 sieve.cpp

-rw-rw-r--. 1 boris boris  140 Oct 10 09:18 sieve.h

-rw-rw-r--. 1 boris boris 1542 Oct 10 09:18 sieve_python_wrapper.cpp

-rw-rw-r--. 1 boris boris  200 Oct 10 09:18 test_benchmark.py

(.env) [boris@fedora34server python-cpp-extension-delta]$ cat delta16.py

import cpp_python_extension

def sumDigits(N,k):

    sum = 0

    while (N != 0):

        sum = sum + N % k

        N = N // k

    return sum

def SearchNumber(uplimit,sdg):

   imax = 0

   zn = []

   # Here we invoke cpp_python_extension.sieve_of_eratosthenes 

   # been written in C++ via Python C API which returns 

   # python's object list containing all prime numbers <= uplimit

   zn = cpp_python_extension.sieve_of_eratosthenes(uplimit) 

   spisok = set(zn)

   for i in range(2,uplimit):

        # Look for highest prime number <= uplimit 

        # and summa of digits <= sdg

        if (i in spisok)  and sumDigits(i,10) <= sdg:

            if i > imax:

                 imax = i

   print("Maximum = ",imax)

def main():

   uplimit,sdg = 0,0

   uplimit = int(input("Input range of scan :"))

   sdg = int(input("Input sum of digits :"))

   SearchNumber(uplimit,sdg) 

if __name__ == "__main__":

       main()

Friday, 24 September 2021

 The executor has three commands, which are assigned numbers:

1) Add 2  2) Add previous 3) Add the following

The first command increases the number by 2, the second - by the previous one (for example,the number 5 will be converted according to the rule 5 + 4), the third - to the next (similarly, 5 according to the rule 5 + 6 = 11).How many programs are there that the original number is 7 is converted to the number 63, while the computation path does not contain the number 43?


$ cat task23.py

a =[0]*130
a[7] =1

for i in range(7,43):
    a[i+2] += a[i]
    a[i + (i - 1)] += a[i]
    a[i + (i + 1)] += a[i]

for i in range(44,63):
    a[i+2] += a[i]
    a[i + (i - 1)] += a[i]
    a[i + (i + 1)] += a[i]

print(a[63])

$ python  task23.py
116
















How to calculate number of zeros of analytic function and their values via Python

$  cat  pythonComplex01.py import numpy as np from cxroots import Circle def count_zeros(f, df, contour_points):    ""...