how to write a algorithm given the condition using python - python

Approximate the value of n for the formula (1-1/n)**n for which the difference between the value of n in the formula and 1/e is less than 0.0001.
How can we do using while and for loop in python .
I tried using while with the following code
from math import exp
value = 1/exp(1) # e being the exponential
n = 1;
while check < 0.0001:
n=n+1
formula = (1-1/n)^n
check = value - formula
if check <0.0001:
print(n)
but since check is not defined before while the program doesn't run.
Is there any better solution?

Define check at the beginning, and replace ^ with **, as the latter one is the correct way to write power in python
import math
value = 1/math.exp(1) # e being the exponential
n = 1
check=1
while check > 0.0001:
n=n+1
formula = (1-1/n)**n
check = value - formula
print(n)
By the way, ^ is the bitwise xor operator in python. You can look here for further description:
http://python-reference.readthedocs.io/en/latest/docs/operators/bitwise_XOR.html

Related

Derivative function python

I need to write code for the derivation of the function without using NumPy or SymPy. Users should input function as polynomes (example: 2*x^3+5) and a number. The code should write n-th derivation of function (function 3*x^3 and number 2 (second derivation): 18*x^1). I have some of the code but I have problems with it: if a function is entered as 2*x^3+5*x it prints derivation only of 2*x^3 (or derives but in next line -like two separate functions) and it doesn't show the n-th derivation (but some number close to n). Some ideas for improving? 1
Code:
a=input("Polinom:")
b=int(input("Number:"))
z=a.split("+")
i,j=0
while i<b:
for j in range(len(z)):
coeff=int(z[j][0])
exp=int(z[j][-1])
e=("{}x^{}".format(coeff*exp,exp-1))
print(e)
z.append(e)
coeff=coeff*exp
exp=exp-1
i+=1
Note that this answer is based on your existing code, and simply shows how you could expand on that to improve what you have so far.
It is not how I would usually go about differentation in python.
I'll provide some explanations as comments in the code.
A few assumptions: only polynomials are allowed. Scientific notation is not allowed. Your variable is denoted by x and the multiplication symbol is ommited.
import re
p = '2x^6-4x^5+3x^3' #example of polynomial
b = 3 #no of derivations
i=0
while i<=b:
z = re.split('(\+|-)',p) #in your code you only check for +. - can also be present
z = list(filter(None, z)) #output of the last couple lines of code: ['2x^6', '-', '4x^5', '+', '3x^3']
deriv = '' #this is where we save the derivative expression
for j in range(len(z)):
if 'x' in z[j]: #only do something when we encounter a monome
sign = ''
if j!=len(z) - 1 and 'x' in z[j+2]: #we add the sign only if we are not at the end of the list and if the next monome will not vanish during differentiation
sign = z[j+1]
coeff=int(z[j].split('x')[0]) #get coefficient
exp = z[j].split('^') #split monome to get exponent
if len(exp)>1:
e = int(exp[1])
if e - 1 > 1:
deriv+=("{}x^{}{}".format(coeff*e,e-1,sign)) if sign != '' else ("{}x^{}".format(coeff*e,e-1))
else: #if x is of power 2, it will be shown as x and x^1
deriv+=("{}x{}".format(coeff*e, sign)) if sign != '' else ("{}x".format(coeff*e))
else: #if x is of the power of 1, x will not be shown in the expression
deriv+=("{}{}".format(coeff,sign)) if sign != '' else ("{}".format(coeff))
print(deriv) #print the current derivative
p = deriv #current derivative becomes the next polynomial to differentiate
i+=1
Hope this helps.

Split up a number as the sum of two powers

x is my input.
I need to find i,j>=0 and n,m>1 such as x = i**m+j**n
For now I have been doing this , but it is way to slow !! How can I improve it ?
from math import sqrt
import numpy as np
def check(x):
for i in range(1,int(np.ceil(sqrt(x)))):
for j in range(1,int(np.ceil(sqrt(x)))):
for m in range(2,x/2+1):
for n in range(2,x/2+1):
if((pow(i,m) +pow(j,n))==x):
print 'Yes';
return ;
print 'No';
thank you !
You could reverse the process, by finding all powers (i**m) smaller than x. Then you just check if any pair of these powers adds up to x.
def check(x):
all_powers = set([1]) #add 1 as a special case
#find all powers smaller than x
for base in range(2,int(math.ceil(sqrt(x)))):
exponent = 2;
while pow(base, exponent) < x:
all_powers.add(pow(base, exponent))
exponent+=1
#check if a pair of elements in all_powers adds up to x
for power in all_powers:
if (x - power) in all_powers:
print 'Yes'
return
print 'No'
The code above is simple but can be optimized, e.g., by integrating the check if a pair adds up to x in the while loop you can stop early in most cases.
From time to time a question pops up here about determining if a positive integer is the integral power of another positive integer. I.e. given positive integer z find positive integers j and n such that z == j**n. This can be done in time complexity O(log(z)) so it is fairly fast.
So find or develop such a routine: call it is_a_power(z) which returns a tuple (j, n) if z is such a power of (0, 0) if it is not. Then loop over i and m, then check if x - i**m is a power. When it becomes one, you are done.
I'll let you finish the code from here, except for one more pointer. Given x and i where i > 1, you can find the upper limit on m such that i**m <= x with
m <= log(x) / log(i)
Note that i == 1 is a special case, since i**m does not actually depend on m in that case.
from math import sqrt
import numpy as np
def build(x):
# this function creates number that are in form of
# a^b such that a^b <= x and b>1
sq=sqrt(x);
dict[1]:1; # 1 is always obtainable
dict[0]:1; # also 0 is always obtainable
for i in range(1,sq): # try the base
number=i*i; # firstly our number is i^2
while number<=x:
dict[number]:1; # this number is in form of a^b
number*=i; # increase power of the number
def check(x):
sq=sqrt(x);
for i in range(1,sq): # we will try base of the first number
firstnumber=1;
while firstnumber<=x: # we are trying powers of i
remaining=x-firstnumber; # this number is remaining number when we substract firstnumber from x
if dict[remaining]==1: # if remaining number is in dictionary which means it is representable as a^b
print("YES"); # then print YES
return ;
firstnumber*=i; # increase the power of the base
print("NO");
return ;
Above code works in O( sqrt(x) * log(x) * log(x) ) which is faster.
You can read comments in code to understand it.

HackerRank "AND product"

When I submit the below code for testcases in HackerRank challenge "AND product"...
You will be given two integers A and B. You are required to compute the bitwise AND amongst all natural numbers lying between A and B, both inclusive.
Input Format:
First line of the input contains T, the number of testcases to follow.
Each testcase in a newline contains A and B separated by a single space.
from math import log
for case in range(int(raw_input())):
l, u = map(int, (raw_input()).split())
if log(l, 2) == log(u, 2) or int(log(l,2))!=int(log(l,2)):
print 0
else:
s = ""
l, u = [x for x in str(bin(l))[2:]], [x for x in str(bin(u))[2:]]
while len(u)!=len(l):
u.pop(0)
Ll = len(l)
for n in range(0, len(l)):
if u[n]==l[n]:
s+=u[n]
while len(s)!=len(l):
s+="0"
print int(s, 2)
...it passes 9 of the test cases, Shows "Runtime error" in 1 test case and shows "Wrong Answer" in the rest 10 of them.
What's wrong in this?
It would be better for you to use the Bitwise operator in Python for AND. The operator is: '&'
Try this code:
def andProduct(a, b):
j=a+1
x=a
while(j<=b):
x = x&j
j+=1
return x
For more information on Bitwise operator you can see: https://wiki.python.org/moin/BitwiseOperators
Yeah you can do this much faster.
You are doing this very straightforward, calculating all ands in a for loop.
It should actually be possible to calculate this in O(1) (I think)
But here are some optimisations:
1) abort the for loop if you get the value 0, because it will stay 0 no matter what
2)If there is a power of 2 between l and u return 0 (you don't need a loop in that case)
My Idea for O(1) would be to think about which bits change between u and l.
Because every bit that changes somewhere between u and l becomes 0 in the answer.
EDIT 1: Here is an answer in O(same leading digits) time.
https://math.stackexchange.com/questions/1073532/how-to-find-bitwise-and-of-all-numbers-for-a-given-range
EDIT 2: Here is my code, I have not tested it extensively but it seems to work. (O(log(n))
from math import log
for case in [[i+1,j+i+1] for i in range(30) for j in range(30)]:
#Get input
l, u = case
invL=2**int(log(l,2)+1)-l
invU=2**int(log(u,2)+1)-u
#Calculate pseudo bitwise xnor of input and format to binary rep
e=format((u&l | invL & invU),'010b')
lBin=format(l,'010b')
#output to zero
res=0
#boolean to check if we have found any zero
anyZero=False
#boolean to check the first one because we have leading zeros
firstOne=False
for ind,i in enumerate(e):
#for every digit
#if it is a leading one
if i=='1' and (not anyZero):
firstOne=True
#leftshift result (multiply by 2)
res=res<<1
#and add 1
res=res+int(lBin[ind])
#else if we already had a one and find a zero this happens every time
elif(firstOne):
anyZero=True
#leftshift
res=res<<1
#test if we are in the same power, if not there was a power between
if(res!=0):
#print "test",(int(log(res,2))!=int(log(l,2))) | ((log(res,2))!=int(log(u,2)))
if((int(log(res,2))!=int(log(l,2))) or (int(log(res,2))!=int(log(u,2)))):
res=0
print res
Worked for every but a single testcase. Small change needed to get the last one. You'll have to find out what that small change is yourself. Seriously

What is the fastest way to find the exact value of the factorial of a large number in python?

I'm aiming at particularly large values of the number whose factorial is to be found for example- 12345678!. Even math.factorial(12345678) in python takes a lot of time to compute the factorial of such a number.
I tried Stirling's Appoximation to compute the same but it does not give the exact value. Is there any other method to compute the same?
EDIT 1: This is the preview of the code I tried to compute the trailing zeros in factorial of the number
import math
def main():
total_cases = int(eval(raw_input()))
for case in xrange(total_cases):
number = int(eval(raw_input()))
if number >= 1e9:
break
factorial_n = math.factorial(number)
count = 0
for i in xrange(1, number):
temp = 10**i
if factorial_n % temp == 0 :
count += 1
else:
print count
break
main()
EDIT 2: I just found that the bottleneck is the dividing step.
scipy has a fast C implementation for both an approximation and exact values.
scipy.misc.factorial(12345, exact=True)
Tried this myself, takes under a second.
But upon trying math.factorial(12345) it also takes under a second. Have you tried this yourself?
def factorial(n):
result = 1
for i in range (1, (n +1)):
result = i * result
return result
print (factorial (100))
This code computes the factorial of a number by using range function and for loop.

Generate and Enter Value for OEIS Sequence in Python?

This is a rather difficult challenge for me as I am new to Python. How would I write a program in python based off this sequence function:
http://oeis.org/A063655
and does the following:
It asks for the value of the sequence and returns the corresponding number. For example, the number corresponding to the 10th value of the sequence is 7. I'd like to be able to do this for values over 300,000,000.
So, the final product would look like this:
Enter a value: 4
[7]
Any ideas where to start? I have a framework to generate sequences where (x) would be to put a mathematical equation or numbers, but I'm not exactly sure how to go from here or how to implement the "Enter a value" portion:
import math
def my_deltas():
while True:
yield (x)
yield (x)
def numbers(start, deltas, max):
i=start
while i<=max:
yield i
i+=next(deltas)
print(','.join(str(i) for i in numbers((x), my_deltas(),(x))))
If you're looking to have your computer keep track of over 300,000,000 elements of a sequence, if each is a 4 byte integer, you'll need at least 300,000,000 * 4bytes, or over 1.1GB of space to store all the values. I assume generating the sequence would also take a really long time, so generating the whole sequence again each time the user wants a value is not quite optimal either. I am a little confused about how you are trying to approach this exactly.
To get a value from the user is simple: you can use val = input("What is your value? ") where val is the variable you store it in.
EDIT:
It seems like a quick and simple approach would be this way, with a reasonable number of steps for each value (unless the value is prime...but lets keep the concept simple for now): You'd need the integer less than or equal to the square root of n (start_int = n ** .5), and from there you test each integer below to see if it divides n, first converting start_int to an integer with start_int = int(start_int) (which gives you the floor of start_int), like so: while (n % start_int) != 0: start_int = start_int - 1, decrement by one, and then set b = start_int. Something similar to find d, but you'll have to figure that part out. Note that % is the modulus operator (if you don't know what that is, you can read up on it, google: 'modulus python'), and ** is exponentiation. You can then return a value with the return statement. Your function would look something like this (lines starting with # are comments and python skips over them):
def find_number(value):
#using value instead of n
start_int = value ** .5
start_int = int(start_int)
while (n % start_int) != 0:
#same thing as start_int = start_int - 1
start_int -= 1
b = start_int
#...more code here
semiperimeter = b + d
return semiperimeter
#Let's use this function now!
#store
my_val = input("Enter a value: ")
my_number = find_number(my_val)
print my_number
There are many introductory guides to Python, and I would suggest you go through one first before tackling implementing a problem like this. If you already know how to program in another language you can just skim a guide to Python's syntax.
Don't forget to choose this answer if it helped!
from math import sqrt, floor
def A063655(n):
for i in range(floor(sqrt(n)), 0, -1):
j = floor(n / i)
if i * j == n:
return i + j
if __name__ == '__main__':
my_value = int(input("Enter a value: "))
my_number = A063655(my_value)
print(my_number)
USAGE
> python3 test.py
Enter a value: 10
7
> python3 test.py
Enter a value: 350000
1185
>

Categories