Am I able to identify sequence, but not formula
I have the whole code
def analyse_sequence_type(y:list[int]):
if len(y) >= 5:
res = {"linear":[],"quadratic":[],"exponential":[],"cubic":[]}
for i in reversed(range(len(y))):
if i-2>=0 and (y[i] + y[i-2] == 2*y[i-1]): res["linear"].append(True)
elif i-3>=0 and (y[i] - 2*y[i-1] + y[i-2] == y[i-1] - 2*y[i-2] + y[i-3]): res["quadratic"].append(True)
for k, v in res.items():
if v:
if k == "linear" and len(v)+2 == len(y): return k
elif k == "quadratic" and len(v)+3 == len(y): return k
return
print(f"A relation cannot be made with just {len(y)} values.\nPlease enter a minimum of 5 values!")
return
I can identify linear and quadratic but how do I make a function
So, firstly we will need to create two functions for linear and quadratic (formulae attached below).
def linear(y):
"""
Returns equation in format (str)
y = mx + c
"""
d = y[1]-y[0] # get difference
c = f"{y[0]-d:+}" # get slope
if d == 0: c = y[0] - d # if no difference then intercept is 0
return f"f(x) = {d}x {c} ; f(1) = {y[0]}".replace("0x ","").replace("1x","x").replace(" + 0","");
We apply a similar logic for quadratic:
def quadratic(y):
"""
Returns equation in format (str)
y = ax² + bx + c
"""
a = logic_round((y[2] - 2*y[1] + y[0])/2) # get a
b = logic_round(y[1] - y[0] - 3*a) # get b
c = logic_round(y[0]-a-b) # get c
return f"f(x) = {a}x² {b:+}x {c:+} ; f(1) = {y[0]}".replace('1x²','x²').replace('1x','x').replace(' +0x','').replace(' +0','')
If you try the code with multiple inputs such as 5.0 you will get 5.0x + 4 (example). To omit that try:
def logic_round(num):
splitted = str(num).split('.') # split decimal
if len(splitted)>1 and len(set(splitted[-1])) == 1 and splitted[-1].startswith('0'): return int(splitted[0]) # check if it is int.0 or similar
elif len(splitted)>1: return float(num) # else returns float
return int(num)
The above functions will work in any way provided that the y is a list where the domain is [1, ∞).
Hope this helps :) Also give cubic a try.
I have implemented Karatsuba multiplication in Python.
The code and pseudocode are as follow:
def karatsuba(x, y):
"""
Input: two n-digit positive integers x and y.
Output: the product x·y.
Assumption: n is a power of 2. (NOT assuming this)
if n =1 then // base case
compute x·y in one step and return the result
else
a,b := first and second halves of x
c,d := first and second halves of y
compute p := a + b and q := c + d using grade-school addition
recursively compute ac := a·c, bd := b·d, and pq := p·q
compute adbc := pqacbd using grade-school addition
compute 10n ·ac + 10n/2 ·adbc + bd using grade-school addition and return the result
"""
str_x = str(x)
str_y = str(y)
if len(str_x) == 1 or len(str_y) == 1:
return x*y
else:
n = max(len(str_x), len(str_y))
n_half = int(n / 2)
a, b = x // 10**n_half, x % 10**n_half
c, d = y // 10**n_half, y % 10**n_half
p = a + b
q = c + d
ac = karatsuba(a, c)
bd = karatsuba(b, c)
pq = karatsuba(p, q)
adbc = pq - ac - bd
return 10**(2*n_half) * ac + 10**n_half * adbc + bd
When I do the multiplication of very large numbers, my code is failing.
Here is an example:
>>> a = 3141592653589793238462643383279502884197169399375105820974944592
>>> b = 2718281828459045235360287471352662497757247093699959574966967627
>>> mul_karatsuba = karatsuba(a, b)
>>> mul_builtin = a * b
>>> mul_karatsuba == mul_builtin
False
>>> mul_karatsuba
8945653667798941823160787739573304887842903322205621858854691873536479127635014727457078833467629169552143732979528067839403974
>>> mul_builtin
8539734222673567065463550869546574495034888535765114961879601127067743044893204848617875072216249073013374895871952806582723184
I am not able to find what exactly is wrong with my code. I have coded everything according to mentioned pseudocode.
Can you please help me?
This script has a formula where at the beginning the numbers x1 and x2 in the code are set, and
I need to change the code so that the value x1 is taken from the list
pre-prepared text document
For example, from a document: 'List.txt'
That is, it turns out I need to enter:
with open ("List.txt '", "r") as f:
into place the value x1 = 6 in the code. But how to systematize it? Just not very rich in knowledge of Python.
List of numbers:
1
4
2
15
6
8
13
3
12
5
10
7
14
9
11
Code: (Powered by Python 2.7)
import sys
a=0
b=7
p=37
x1=6
x2=8
if (len(sys.argv)>1):
x1=int(sys.argv[1])
if (len(sys.argv)>2):
x2=int(sys.argv[2])
if (len(sys.argv)>3):
p=int(sys.argv[3])
if (len(sys.argv)>4):
a=int(sys.argv[4])
if (len(sys.argv)>5):
b=int(sys.argv[5])
def modular_sqrt(a, p):
""" Find a quadratic residue (mod p) of 'a'. p
must be an odd prime.
Solve the congruence of the form:
x^2 = a (mod p)
And returns x. Note that p - x is also a root.
0 is returned is no square root exists for
these a and p.
The Tonelli-Shanks algorithm is used (except
for some simple cases in which the solution
is known from an identity). This algorithm
runs in polynomial time (unless the
generalized Riemann hypothesis is false).
"""
# Simple cases
#
if legendre_symbol(a, p) != 1:
return 0
elif a == 0:
return 0
elif p == 2:
return p
elif p % 4 == 3:
return pow(a, (p + 1) / 4, p)
# Partition p-1 to s * 2^e for an odd s (i.e.
# reduce all the powers of 2 from p-1)
#
s = p - 1
e = 0
while s % 2 == 0:
s /= 2
e += 1
# Find some 'n' with a legendre symbol n|p = -1.
# Shouldn't take long.
#
n = 2
while legendre_symbol(n, p) != -1:
n += 1
x = pow(a, (s + 1) / 2, p)
b = pow(a, s, p)
g = pow(n, s, p)
r = e
while True:
t = b
m = 0
for m in xrange(r):
if t == 1:
break
t = pow(t, 2, p)
if m == 0:
return x
gs = pow(g, 2 ** (r - m - 1), p)
g = (gs * gs) % p
x = (x * gs) % p
b = (b * g) % p
r = m
def legendre_symbol(a, p):
""" Compute the Legendre symbol a|p using
Euler's criterion. p is a prime, a is
relatively prime to p (if p divides
a, then a|p = 0)
Returns 1 if a has a square root modulo
p, -1 otherwise.
"""
ls = pow(a, (p - 1) / 2, p)
return -1 if ls == p - 1 else ls
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
print ("x")
else:
return x % m
print "a=",a
print "b=",b
print "p=",p
print "x-point=",x1
print "x-point=",x2
z=(x1**3 + a*x1 +b) % p
y1=modular_sqrt(z, p)
z=(x2**3 + a*x2 +b) % p
y2=modular_sqrt(z, p)
print "\nP1\t(%d,%d)" % (x1,y1)
print "P2\t(%d,%d)" % (x2,y2)
s=((-y2)-y1)* modinv(x2-x1,p)
x3=(s**2-x2-x1) % p
y3=((s*(x2-x3)+y2)) % p
result = "Q\t(%d,%d)" % (x3,y3)
f = open('Result01.txt', 'w')
f.write(result)
f.close()
Earlier, I saw scripts where numbers are taken from one text document, perform a function, and the result is saved in another text document.
Try using the pandas library to read, process and write your numbers.
import pandas as pd # import pandas module and call it pd for short
x2 = 6
df = pd.read_csv('input_file.txt') # read the data from a text file into a dataframe
df['x1 times x2'] = df['x1'] * x2 # create new column in your dataframe with result of your function
df.to_csv('output_file.txt', index=False) # output result of your calculations (dropping the dataframe index column)
Although you're hard coding the values of x1, x2, in your code, they can be redefined, as you're doing here:
if (len(sys.argv)>1):
x1=int(sys.argv[1])
if (len(sys.argv)>2):
x2=int(sys.argv[2])
So if you call your script from command line, like C:\Users\test.py x1value x2value you can redefine x1 and x2. If you really want a text file to contain your x1 and x2, just use the following snippet somewhere at the top
import json
with open("input.json","r",encoding="utf-8") as stream:
parsed = json.load(stream)
x1,x2 = parsed["x1"],parsed["x2"]
Contents of "input.json":
{"x1":1,"x2"=2}
With only python without extra dependencies, your can read List.txt as follow
with open("List.txt","r") as f:
arrX1 = list(map(int,f.readlines()))
print (arrX1)
The above reads all the lines in f and converts/maps them to integers. The list function then gives you an array you can loop through to generate x2 and write to the Result.txt file.
The above prints
[1, 4, 2, 15, 6, 8, 13, 5, 3, 10, 7, 14, 9, 11]
So for your code replace all lines from 125 downward with
# Read numbers from file and put them in an array
with open("List.txt","r") as f:
arrX1 = list(map(int,f.readlines()))
f.close()
# Open the result file to write to
f = open('Result01.txt', 'w')
# Now get x1 for each item in the list of numbers from the file
# then do the calculations
# and write the result
for x1 in arrX1:
z=(x1**3 + a*x1 +b) % p
y1=modular_sqrt(z, p)
z=(x2**3 + a*x2 +b) % p
y2=modular_sqrt(z, p)
print "\nP1\t(%d,%d)" % (x1,y1)
print "P2\t(%d,%d)" % (x2,y2)
s=((-y2)-y1)* modinv(x2-x1,p)
x3=(s**2-x2-x1) % p
y3=((s*(x2-x3)+y2)) % p
result = "Q\t(%d,%d)" % (x3,y3)
f.write(result)
f.close()
I'm fairly new to this but will try and be as clear as possible.
Essentially I have 5 different lists of lists. 4 are imported from txt files and the 5th is a merger of the 4. Each inner list contains a value at index position 3. My objective is to maximize the sum by picking appropriately.
I also have a couple constraints:
The sum of the values at index 6 position can't exceed 50000
I pick 2 items from set C, 3 from set W, 2 from set D, 1 from set G, and 1 from set U (the combined) and I can't pick the same item for each set. Ie. each pick in W has to be different.
My code is below. I'm having trouble in that the optimizer just spits out my initial list of picks. Looking at the data though, I know for sure there are better solutions. I read that the issue may be related to late binding but I'm not sure if that's right and if it is, not sure how to update to fix error either. Appreciate any help. Thanks!
Read: Scipy.optimize.minimize SLSQP with linear constraints fails
import numpy as np
from scipy.optimize import minimize
C = open('C.txt','r').read().splitlines()
W = open('W.txt','r').read().splitlines()
D = open('D.txt','r').read().splitlines()
G = open('G.txt','r').read().splitlines()
def splitdata(file):
for index,line in enumerate(file):
file[index] = line.split('\t')
return(file)
def objective(x, sign=-1.0):
x = list(map(int, x))
pos = 3
Cvalue = float(C[x[0]][pos]) + float(C[x[1]][pos])
Wvalue = float(W[x[2]][pos]) + float(W[x[3]][pos]) + float(W[x[4]][pos])
Dvalue = float(D[x[5]][pos]) + float(D[x[6]][pos])
Gvalue = float(G[x[7]][pos])
Uvalue = float(U[x[8]][pos])
grand_value = sign*(Cvalue + Wvalue + Dvalue + Gvalue + Uvalue)
#print(grand_value)
return grand_value
def constraint_cost(x):
x = list(map(int, x))
pos = 6
Ccost = int(C[x[0]][pos]) + int(C[x[1]][pos])
Wcost = int(W[x[2]][pos]) + int(W[x[3]][pos]) + int(W[x[4]][pos])
Dcost = int(D[x[5]][pos]) + int(D[x[6]][pos])
Gcost = int(G[x[7]][pos])
Ucost = int(U[x[8]][pos])
grand_cost = 50000 - (Ccost + Wcost + Dcost + Gcost + Ucost)
#print(grand_cost)
return grand_cost
def constraint_C(x):
if x[0] == x[1]:
return 0
else:
return 1
def constraint_W(x):
if x[2] == x[3] or x[2] == x[4] or x[3] == x[4]:
return 0
else:
return 1
def constraint_D(x):
if x[5] == init[6]:
return 0
else:
return 1
con1 = {'type':'ineq','fun':constraint_cost}
con2 = {'type':'ineq','fun':constraint_C}
con3 = {'type':'ineq','fun':constraint_W}
con4 = {'type':'ineq','fun':constraint_D}
con = [con1, con2, con3, con4]
c0 = [0,1]
w0 = [0,1,2]
d0 = [0,1]
g0 = [0]
u0 = [0]
init = c0+w0+d0+g0+u0
C = splitdata(C)
W = splitdata(W)
D = splitdata(D)
G = splitdata(G)
U = C + W + D + G
sol = minimize(objective, init, method='SLSQP',constraints=con)
print(sol)
I have been thinking about this issue and I can't figure it out. Perhaps you can assist me. The problem is my code isn't working to output 1000 digits of pi in the Python coding language.
Here's my code:
def make_pi():
q, r, t, k, m, x = 1, 0, 1, 1, 3, 3
while True:
if 4 * q + r - t < m * t:
yield m
q, r, t, k, m, x = (10*q, 10*(r-m*t), t, k, (10*(3*q+r))//t - 10*m, x)
else:
q, r, t, k, m, x = (q*k, (2*q+r)*x, t*x, k+1, (q*(7*k+2)+r*x)//(t*x), x+2)
digits = make_pi()
pi_list = []
my_array = []
for i in range(1000):
my_array.append(str("hello, I'm an element in an array \n" ))
big_string = "".join(my_array)
print "here is a big string:\n %s" % big_string
I know this code can be fixed to work, but I'm not sure what to fix... The print statement saying here is a big string and the my_array.append(str("hello, im an element in an array \n)) is just a filler for now. I know how all the code is used to work, but like I said before, I can't get it to shoot out that code.
If you don't want to implement your own algorithm, you can use mpmath.
try:
# import version included with old SymPy
from sympy.mpmath import mp
except ImportError:
# import newer version
from mpmath import mp
mp.dps = 1000 # set number of digits
print(mp.pi) # print pi to a thousand places
Reference
Update: Code supports older and newer installations of SymPy (see comment).*
Run this
def make_pi():
q, r, t, k, m, x = 1, 0, 1, 1, 3, 3
for j in range(1000):
if 4 * q + r - t < m * t:
yield m
q, r, t, k, m, x = 10*q, 10*(r-m*t), t, k, (10*(3*q+r))//t - 10*m, x
else:
q, r, t, k, m, x = q*k, (2*q+r)*x, t*x, k+1, (q*(7*k+2)+r*x)//(t*x), x+2
my_array = []
for i in make_pi():
my_array.append(str(i))
my_array = my_array[:1] + ['.'] + my_array[1:]
big_string = "".join(my_array)
print "here is a big string:\n %s" % big_string
And read about yield operator from here:
What does the "yield" keyword do?
Here is the answer:
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337
The accepted answer is incorrect, as noted in comments.
The OP's code appears to be based on an implementation of Spigot's algorithm copied from here.
To fix the code per the OP's question (although I renamed the variables and functions to match what they were in the original source), one solution might be:
#!/usr/bin/env python
DIGITS = 1000
def pi_digits(x):
"""Generate x digits of Pi."""
q,r,t,k,n,l = 1,0,1,1,3,3
while x >= 0:
if 4*q+r-t < x*t:
yield n
x -= 1
q,r,t,k,n,l = 10*q, 10*(r-n*t), t, k, (10*(3*q + r))/t-10*n, l
else:
q,r,t,k,n,l = q*k, (2*q+r)*l, t*l, k+1, (q*(7*k+2)+r*l)/(t*l), l+2
digits = [str(n) for n in list(pi_digits(DIGITS))]
print("%s.%s\n" % (digits.pop(0), "".join(digits)))
Also, here is a much faster* implementation, also apparently based on Spigot's algorithm:
#!/usr/bin/env python
DIGITS = 1000
def pi_digits(x):
"""Generate x digits of Pi."""
k,a,b,a1,b1 = 2,4,1,12,4
while x > 0:
p,q,k = k * k, 2 * k + 1, k + 1
a,b,a1,b1 = a1, b1, p*a + q*a1, p*b + q*b1
d,d1 = a/b, a1/b1
while d == d1 and x > 0:
yield int(d)
x -= 1
a,a1 = 10*(a % b), 10*(a1 % b1)
d,d1 = a/b, a1/b1
digits = [str(n) for n in list(pi_digits(DIGITS))]
print("%s.%s\n" % (digits.pop(0), "".join(digits)))
I tested both a few times against this online Pi digit generator.
All credit to this Gist by deeplook.
* Based on testing 10,000 digits, where I got about 7 seconds compared to about 1 second.
For up to 1 million digits of pi use math_pi (note: I am the author of the module)
Install with pip:
pip install math-pi
In Python:
>>> import math_pi
>>> print(math_pi.pi(b=1000))
3.1415926535...
From Fabrice Bellard site: Pi Computation algorithm. Sorry for such a straightforward implementation. 1000 is fast enough (0.1s for me), but 10000 isn't such fast - 71s :-(
import time
from decimal import Decimal, getcontext
def compute(n):
getcontext().prec = n
res = Decimal(0)
for i in range(n):
a = Decimal(1)/(16**i)
b = Decimal(4)/(8*i+1)
c = Decimal(2)/(8*i+4)
d = Decimal(1)/(8*i+5)
e = Decimal(1)/(8*i+6)
r = a*(b-c-d-e)
res += r
return res
if __name__ == "__main__":
t1 = time.time()
res = compute(1000)
dt = time.time()-t1
print(res)
print(dt)
I was solved with bellow formula 5-6 years ago.
Machin-like formula
Wikipedia: https://en.wikipedia.org/wiki/Machin-like_formula
Sorry for the code quality. Variable names can be meaningless.
#-*- coding: utf-8 -*-
# Author: Fatih Mert Doğancan
# Date: 02.12.2014
def arccot(x, u):
sum = ussu = u // x
n = 3
sign = -1
while 1:
ussu = ussu // (x*x)
term = ussu // n
if not term:
break
sum += sign * term
sign = -sign
n += 2
return sum
def pi(basamak):
u = 10**(basamak+10)
pi = 4 * (4*arccot(5,u) - arccot(239,u))
return pi // 10**10
if __name__ == "__main__":
print pi(1000) # 1000
I'm not familiar with your algorithm. Is it an implementation of BBP?
In any case, your make_pi is a generator. Try using it in a for loop:
for digit in make_pi():
print digit
Note that this loop is infinite: make_pi() never throws StopIteration
Here you can check whether your program outputs correct 1000 digits:
http://spoj.com/CONSTANT
Of course you can use diff or tc as well but you'd have to copy these 1000 digits from somewhere and there you just submit your program and check whether the score is bigger than 999.
You can try to print even more digits there and thus get more points. Perhaps you'd enjoy it.
Does this do what you want?
i = 0;
pi_str = ""
for x in make_pi():
pi_str += str(x)
i += 1
if i == 1001:
break
print "pi= %s.%s" % (pi_str[0],pi_str[1:])
Here is a different way I found here --> Python pi calculation? to approximate python based on the Chudnovsky brothers formula for generating Pi which I have sightly modified for my program.
def pifunction():
numberofdigits = int(input("please enter the number of digits of pi that you want to generate"))
getcontext().prec = numberofdigits
def calc(n):
t = Decimal(0)
pi = Decimal(0)
deno = Decimal(0)
k = 0
for k in range(n):
t = (Decimal(-1)**k)*(math.factorial(Decimal(6)*k))*(13591409+545140134*k)
deno = math.factorial(3*k)*(math.factorial(k)**Decimal(3))*(640320**(3*k))
pi += Decimal(t)/Decimal(deno)
pi = pi * Decimal(12)/Decimal(640320**Decimal(1.5))
pi = 1/pi
return str(pi)
print(calc(1))
I hope this helps as you can generate any number of digits of pi that you wish to generate.
wallis formula can get to 3.141592661439964 but a more efficient way is needed to solve this problem.
https://www.youtube.com/watch?v=EZSiQv_G9HM
and now my code
x, y, summing = 2, 3, 4
for count in range (0,100000000):
summing *= (x/y)
x += 2
summing *= (x/y)
y += 2
print (summing)