• Welcome to the new Internet Infidels Discussion Board, formerly Talk Freethought.

Python

steve_bank

Diabetic retinopathy and poor eyesight. Typos ...
Joined
Nov 9, 2017
Messages
13,775
Location
seattle
Basic Beliefs
secular-skeptic
Ipetrich posted math code in Python so I installed it.

It looks like and old MSDOS program built on C libraries. The language looks fine for math, but a lot of low level system overhead.

I can import a .py file located in the Python install directory and it executes.

I have a directory c:\python with file test.py and I run the code

import sys
sys.path.append("c:/python")
import test

No errors but no execution. c:\python gets an error invalid escape sequence, and c::\\python does not work

Where am I going wrong?
 
Thanks. I can load script files from the Python install directory. I'll wade through the documentation.

The import command apparently does not accept a simple path + file name string.

I'll probably need an IDE.
 
You can also just run test.py in cmd.exe or powershell, with "cd c:\python" and "python test.py".
 
Fr your computing pleasure.

Numpy a math library

Add NumPy and a grphics package and you have a full featured math tool.

The basic distribution is a good programmable calculator.

Math functions
Operators

Operating system module


Python does not have an output window just the command line window, all I need usually is to output numbers to a file.

One problem is Python does not appear to have a formatted file read similar to C fscanf() . So when you read a number array in from a file you have to work out the text string to number conversion, which fsacanf() does automatically.

Python is not typed, it creates a variable when it is used which can make debugging harder on large programs.

Python uses indentation instead of delimiters. If you mix spaces and tabs wnem indenting you will get an error.

After you install to get started with a script file at the command line
line.

import os
import importlib as il - il easier to type than importlib.
os.chdir(('c:\\python')) - the working directory or the directory of your choice
import files - runs files.py from the working directory
os.reload((files) - reruns the file

Notepad works as an editor.
File files,py

Code:
import math
n = 5
x = n*[0]  #create zero arrays
y = n*[0]
for i in range(n):
    x[i] = i #int
    y[i] = i*10.5  #float

for i in range(n):
    print('%d %f' %(x[i],y[i]))

# write() writes string to file,repr() converts  number to string

f = open('c:\python\data.txt','w')
for i in range(n):
    f.write(repr(x[i])+'  '+repr(y[i])+'\n')
f.close()

f = open('c:\python\data.txt','r')
data = f.read()
f.close()
print(data)

Overall a pretty good math tool as long as you don't mid working at a commend line OS level. I downloaded the PYchram IDE but it is not intuitve.
 
List of Python modules



Using the random and statistics modules.

First check the normal random numbers. Then find the distribution of the combination of two rods with normally distributed lengths.

Code:
import math
import random as rn
import statistics as st

n = 1000
x = n*[0]
for i in range(n):x[i] = rn.gauss(100,10)  #mean,stadard deviation
x.sort()
data = open('c:\python\data1.txt','w')
for i in range(n):data.write(repr(i)+'   '+repr(x[i])+'\n')
data.close()
avg = st.mean(x)
med = st.median(x)
std = st.stdev(x)
mi = min(x)
ma = max(x)
print('mean  %f  sigma  %f median  %f' %(avg,std,med))
print('min  %f  max  %f' %(mi,ma))
#----------------------------------------------------------
#two rods normally distributed means and stdrd deviations
r1mean = 100
r1sd = 10
r2mean = 50
r2sd = 5
for i in range(n):x[i] = rn.gauss(r1mean,r1sd)+rn.gauss(r2mean,r2sd)
avg = st.mean(x)
med = st.median(x)
std = st.stdev(x)
mi = min(x)
ma = max(x)
print('mean  %f  sigma  %f median  %f' %(avg,std,med))
print('min  %f  max  %f' %(mi,ma))

rods = open('c:\python\data2.txt','w')
rods.write('mean  '+repr(avg)+'\n')
rods.write('sfandard deviation  '+repr(std)+'\n')
rods.write('median  '+repr(med)+'\n')
rods.write('min  '+repr(mi)+'\n')
rods.write('max  '+repr(ma)+'\n')
rods.close()
 
After some frustration and trial and error I figured out how to read numbers from a text file.




Code:
import math
import os
os.system('cls')  # clear the screen
n = 5
x = n*[0]  # file write data
y = n*[0]
xr = n*[0] # recovered numeric data
yr = n*[0]

for i in range(n):
    x[i] = i
    y[i] = i*10.5

# file of a column of ints and a column of floats
f = open('c:\python\data.txt','w')
for i in range(n):
    f.write(repr(x[i])+'   '+repr(y[i])+'\n')
f.close()

# file read into data as a single string
f = open('c:\python\data.txt','r')
data = f.read()
f.close()

# break single file string into an array of row strings
s = data.splitlines()
print(s)

m = n*[0]
for i in range(n):
    m[i]  = s[i].split() #split each row into two strings
    xr[i] = int(m[i][0])  # convert each row sub strimg to int or float
    yr[i] = float(m[i][1])

print(m)  # array of row strings
print(yr) # floats
print(xr) # ints
p = yr[1] + 1  # verify string conversion to float
print(p)
 
A simpler way to do it is read the line by line. Turned into a function that can be adapted for any number of columns. Reading columns into a multi dimension array is a little more work in the loop.

Code:
import math
import os
os.system('cls')  # clear the screen
n = 5
x = n*[0]  # file write data
y = n*[0]
xr = n*[0] # recoverd numeric data
yr = n*[0]

for i in range(n):
    x[i] = i
    y[i] = i*10.5

# file of a column of ints and a column of floats
f = open('c:\python\data.txt','w')
for i in range(n):
    f.write(repr(x[i])+'   '+repr(y[i])+'\n')
f.close()

def read_numbers(nl,fname,xi,xf):
    f = open(fname,'r')
    for i in range(nl):
        m = f.readline()
        s = m.split()
        xi[i] = int(s[0]) 
        xf[i] = float(s[1])
    f.close()

fn = 'c:\python\data.txt'
read_numbers(n,fn,xr,yr)

print(yr) # floats
print(xr) # ints
p = yr[1] + 1  # verfy string conversion to float
print(p)
 
Havn't gone through the learng curve effort in a long time.

Using variable arguments with functions. Similar to C but easier.

Two functions to read and write single dimension numerical arrays from and to files.

Both take a variable number of arrays. The read function takes a format string and applies it to the string to number conversion.

Character and string arrays can be added.


Code:
import math
import os
os.system('cls')

n = 5
x = n*[0]
y = n*[0]
xr = n*[0]
yr = n*[0]

for i in range(n):
    x[i] = i
    y[i] = i * 2.


def save_nums(fname,*args):
    nrows = len(args[0])
    # check number of rows the same
    for i in range(len(args)):
        if len(args[i]) != nrows : return 'Rows Mismatch'
    f = open(fname,'w')
    for i in range(nrows):
        s = ' ' # row string
        for x in args:s += repr(x[i]) + '  '
        s += '\n'
        f.write(s)
    f.close()
    return 'Save Complete'

fn = 'c:\python\data.text'
s = save_nums(fn,x,y)
print(s)
    
    

def read_nums(nl,fname,format,*args):
    fstr = format.split()
    f = open(fname,'r')
    for i in range(nl):
        m = f.readline()
        s = m.split()
        j = 0
        for x in args:
            
            match (fstr[j]):
                case '%d':x[i] = int(s[j])
                case '%f':x[i] = float(s[j])
                case _:return 'Format Error'
        
            j += 1
    f.close()
    return 'Read Complete'
    
format = '%d  %f'
s = read_nums(n,fn,format,xr,yr)
print(s)

for i in range(n):print('%d   %f' %(xr[i],yr[i]))
 
Not quite related to Python scripting but rather availability.
Can we get "Python on a stick".

At work I have recently been dusting off dormant batch programming skills to do various network information gathering exercises. I can do it except for the formatting of the data.
I thought that Python might be useful but do not want to install Python on all PCs. If i could setup a stick with a Python environment that would enable these scripts to be run on PCs as required.
A quick look does not really show whether it is possible or not. Does anyone here have such experience?
 
Try installing the interpreter on a flash drive, system wise it is just another drive mapped into the system.

Search on python flash drive, beaucoup hits.

Sounds like a good idea for your problem.
 
On ProjectEuler.net, which has a lot of programming problems to solve, I turned to Python in order to have bigger integers....
Screenshot 2023-11-09 at 7.10.50 pm.png
It seems it is theoretically possible to have hundreds of thousands of digits...
If the struct listed in PEP 0237 is accurate, longs' lengths (in digits) are stored as unsigned 32-bit integers, up to 4,294,967,295 digits, meaning they can easily hold φ**(4*10**6), which is "only" 832,951 digits. However, φ is not an integer, so you will need to use a Decimal (Python's floating-point bignum) to calculate the number. You can store the result in a long afterward, however
Though for common use bignum can handle hundreds of digits well.
 
Any reason why after I installed Python on my Windows 10 laptop, I can't run IDLE? The menu item is there, and when I launch it nothing happens. I've re-installed Python from the ground up, the latest version, but no change.
 
The beginnings of a Reverse Polish Notation RPN calculator. On an RPN calculator to find 2.3 ener 2 then 3, then the / key. Then ente next number and operator. No ( ) needed.

Another problem would be to parse the general math functions in a string like

sin(2)
log10(4)

From the net a major application of Python is data science which in part sifts through and parses files looking for text patterns and matches.

Code:
import math
import os
os.system('cls')

def calculate(op,var):
    n = len(op) # number of operations
    acc = var.pop() # first number
    for i in range(n):   
        match(op.pop()):
            case '+': acc = acc + var.pop()
            case '-': acc = acc - var.pop()
            case '*': acc = acc * var.pop()
            case '/': acc = acc / var.pop()           
    return acc

def parse_string(in_string,op,var):
    # splt string and push numbers,operators onto stacks
    sp = in_string.split()
    ns = len(sp)
    for i in range(ns):
        if i%2 == 0: var.append(float(sp[i]))
        else:op.append(sp[i])
    op.reverse()
    var.reverse()

        
ops = []  # operator stack
vars = [] # number stack

s = ' 1 + 2 / 9'
parse_string(s,ops,vars)
print(s)
print(ops)
print(vars)
result = calculate(ops,vars)
print(result)
 
Any reason why after I installed Python on my Windows 10 laptop, I can't run IDLE? The menu item is there, and when I launch it nothing happens. I've re-installed Python from the ground up, the latest version, but no change.
Don't know enough for a direct answer. In order to use a function that is not a built in you have to import the library module that containis the function..
 
I an running W10.

When i run python.exe I do not get a menu just the Python command line shell.

Navigate to Python312\Lib\idlelib and run idle.bat and it comes up and works.
 
Back
Top Bottom