def f(n):
if n == 1:
return 1
else:
return (1 / (n - 1)) * (f(n - 1) + (1 / f(n - 1)))
n = int(input())
print(str(round(f(n),2)))
It's been said that my code is not efficient enough since there are two f(n-1)s in the recursion.
How can I improve it ?
If you use python ≥ 3.8 you could use an assignment expression:
def f(n):
if n == 1:
return 1
else:
return (1/(n-1)) * ((F:=f(n-1)) + (1/F)) # (F:=…) gets evaluated as …
# and instantiates F
n = int(input())
print(str(round(f(n),2)))
def f(n):
if n == 1:
return 1
else:
return (1 / (n - 1)) * (f(n - 1) + (1 / f(n - 1)))
n = int(input())
print(str(round(f(n),2)))
#as long as n gets bigger
the function will turn into infinite loop
You can try this:
else:
def alternative(n):
s= (1 / (n - 1))
def altr(s):
return (n - 1) + (1 / (n - 1))
Related
import sys
t=(int(sys.stdin.readline()))
for i in range(0,t):
n=int(sys.stdin.readline())
c=0
s=n*(n+1)/2
if s%2!=0:
print(0)
else:
c=0
i=-1
a=[i for i in range(1,n+1)]
h=s//2
m=0
s1=0
for i in range(n-1,-1,-1):
s1+=a[i]
c+=1
if s1==h:
m=1
break
if s1>h:
break
if m==1:
s1=((c+1)*(2+((c-1)-1)))//2+((n-c-1)*(2+((n-c-1)-1)))//2
print(s1)
else:
print(c)
I am new to python , How can i write this code with using for loop? i don't want to use for loop because i get TLE error. Thanks in advance
Here is the question :
N. Consider the sequence sequence=(1,2,…,N). You should choose two elements of this sequence and swap them.
A swap is perfect if there is an integer o (1≤o<N) such that the sum of the first M elements of the resulting sequence is equal to the sum of its last N−o elements. Find the number of perfect swaps.
i got interested in the problem and found this so far:
a slow version that creates list and really does swap elements is this:
from itertools import combinations
def slow(N):
found = 0
for i, j in combinations(range(N), 2):
lst = list(range(1, N + 1))
lst[i], lst[j] = lst[j], lst[i]
for m in range(1, N):
a = m * (m + 1) // 2
b = (N - m) * (N + m + 1) // 2
if i < m <= j:
a = a - i + j
b = b - j + i
assert a == sum(lst[:m])
assert b == sum(lst[m:])
if sum(lst[:m]) == sum(lst[m:]):
found += 1
if i < m <= j:
assert 2 * m * (m + 1) + 4 * j == N * (N + 1) + 4 * i
else:
assert 2 * m * (m + 1) == N * (N + 1)
else:
if i < m <= j:
assert 2 * m * (m + 1) + 4 * j != N * (N + 1) + 4 * i
else:
assert 2 * m * (m + 1) != N * (N + 1)
return found
as you see i found criteria the indices have to fulfill in order for the sum to be correct:
if i < m <= j:
assert 2 * m * (m + 1) + 4 * j == N * (N + 1) + 4 * i
else:
assert 2 * m * (m + 1) == N * (N + 1)
i also found the direct formula to calculate the sum up to m and the one starting from m:
a = m * (m + 1) // 2
b = (N - m) * (N + m + 1) // 2
if i < m <= j:
a = a - i + j
b = b - j + i
all of that can can be calculated using some basic mathematics.
starting from that you can do some more maths and see that there are 2 cases to consider:
there is an m such that the sum of the original list [1, 2, 3, ..., m, m+1, ..., N] up to m equals the sum of the rest of the list (e.g. N = 20; m = 14). two cases again:
all the swaps that do not cross the m boundary are valid (there are comb(m, 2) + comb((N - m), 2)) of them.
when you split at m-1 you will find more swaps; this time you have to swap accross the m-1 boundary.
the m in that case is calculated from
m = - 1 + sqrt(1 + 2 * N * (N + 1)) / 2
the calculation for m in the first case is not an integer (i.e. 1 + 2 * N * (N + 1) is not a perfect square). the m to consider is then then the floor of the result of the formula above (i use int instead of math.floor). two cases again for the difference of the sum of the two splits:
the difference is even: there are more swaps that need to go over the m boundary.
the difference is odd: no additional swaps (swapping will always result in an even difference)
this is the code:
from math import sqrt, comb
def fast(N):
found = 0
arg = (1 + 2 * N * (N + 1))
sq = round(sqrt(arg))
if sq ** 2 == arg and sq & 1:
m = (-1 + sq) // 2
found += comb(m, 2) + comb((N - m), 2)
m -= 1
found += N - m - 1
else:
m = int((-1 + sqrt(arg)) // 2)
diff = ((m + 1 + N) * (N - m) - m * (m + 1)) // 2
if diff & 1 == 0:
found += N - m
return found
I am new to python and trying to learn some codes. This is my first programming attempt with python. I have a sequence S and a sequence T(which is also a relation of a couples recurrence relationship equation)where
Sn= 2S(n-1)+S(n-2)+4T(n-1)
and T=S(n-1)+T(n-1).
S0=1, S1=2, T0=0 AND T1=1.
How can i write a function that returns nth value of S and T sequence where the function takes n as a parameter and returns Sn,Tn as a tuple as result of calling the function?
Here are the recursive functions:
def T(n):
if n == 0:
return 0
if n == 1:
return 1
return S(n - 1) + T(n - 1)
def S(n):
if n == 0:
return 1
if n == 1:
return 2
return 2 * S(n - 1) + S(n - 2) + 4 * T(n - 1)
def tuple_func(n):
return(S(n), T(n))
Somewhere between n == 20 and n == 30 this becomes ridiculously slow, depending on your threshold for ridiculousness.
"For fun" I've converted the recursive functions to an iterative version. On my computer it can do up to n == 50,000 in about a second.
def tuple_func(n):
S = [1, 2]
T = [0, 1]
if n < 0:
return(None, None)
if 0 >= n < 2:
return(S[n], T[n])
for n in range(2, n + 1):
S.append(2 * S[n - 1] + S[n - 2] + 4 * T[n - 1])
T.append(S[n - 1] + T[n - 1])
return(S[n], T[n])
I need to find all the combinations flowers. Number of flowers only odd. Purchase amount not greater than the predetermined.
def bouquets(narcissus_price, tulip_price, rose_price, summ):
count_combinations = 0
for n in xrange(int(summ / narcissus_price) + 1):
for t in xrange(int(summ / tulip_price) + 1):
if n * narcissus_price + t * tulip_price > summ:
break
for r in xrange([1,0][(n + t) % 2], int(summ / rose_price) + 1, 2):
if n * narcissus_price + t * tulip_price + r * rose_price > summ:
break
elif (n + t + r) & 1:
count_combinations += 1
return count_combinations
print bouquets(200, 300, 400, 100000) == 3524556 # large run-time
Reduce the iteration range for tulips - rather than iterating to summ // tulip_price you can stop at (summ - n * narcissus_price) // tulip_price
You can count the number of possible values for r without enumerating them
Example:
def bouquets(n_price, t_price, r_price, total_price):
"""
Count how many n, t, r (integers >= 0) exist
such that
n * n_price + t * t_price + r * r_price <= total_price
and
n + t + r is odd
"""
count = 0
max_n = total_price // n_price
for n in xrange(max_n + 1):
rem_n = total_price - n * n_price
max_t = rem_n // t_price
for t in xrange(max_t + 1):
rem_t = rem_n - t * t_price
max_r = rem_t // r_price
min_r = (n + t + 1) % 2
count += (max_r - min_r) // 2 + 1
return count
On the given test input, this reduces the runtime from 2.33s to 67.2ms (about 35 times faster).
def numPotencia(x, n):
if isinstance(x,int) and isinstance(n,int):
return aux_xPower(abs(x), abs(n));
else:
print("\n""Error: The number needs to be a integer");
def aux_xPower(x,n):
if n == 0:
return 1;
elif n == 1:
return x;
else:
return x * aux_xPower(x-1,n)
You're almost there. Right now, your code will evaluate expressions like this:
x * (x - 1) * (x - 2) * (x - 3) * ... (does not terminate)
What you need to do is change this:
return x * aux_xPower(x - 1, n)
To this:
return x * aux_xPower(x, n - 1)
This is necessary because x^n = x * x^(n - 1), x^n = x * (x - 1)^n.
Rewrite this line and try
return x * aux_xPower(x-1,n)
to
return x * aux_xPower(x,n-1)
Your base should be same every time.
What do you think is the best way of writing this method for calculating an ackermann function value? This function incorporates several 'short cuts' to the simplest method of calculating the value that speeds the calculation up considerably by reducing the amount of recursive calls, but you end up with a long expression.
The versions use:
The line continuation character \
Bracketed nested functions
A single outer set of braces
Does any version seem better to you? why? I'm curious.
>>> def ack4(M, N):
return (N + 1) if M == 0 else \
(N + 2) if M == 1 else \
(2*N + 3) if M == 2 else \
(8*(2**N - 1) + 5) if M == 3 else \
ack4(M-1, 1) if N == 0 else \
ack4(M-1, ack4(M, N-1))
>>> def ack2(M, N):
return (N + 1) if M == 0 else (
(N + 2) if M == 1 else (
(2*N + 3) if M == 2 else (
(8*(2**N - 1) + 5) if M == 3 else (
ack2(M-1, 1) if N == 0 else
ack2(M-1, ack2(M, N-1))))))
>>> def ack3(M, N):
return ((N + 1) if M == 0 else
(N + 2) if M == 1 else
(2*N + 3) if M == 2 else
(8*(2**N - 1) + 5) if M == 3 else
ack3(M-1, 1) if N == 0 else
ack3(M-1, ack3(M, N-1)))
>>> ack2(4, 2) == ack3(4, 2) == ack4(4, 2)
True
>>>
What's wrong with just nesting in a simple elif chain?
def ack5(m, n):
if m == 0:
return (n + 1)
elif m == 1:
return (n + 2)
elif m == 2:
return (2 * n + 3)
elif m == 3:
return (8 * ( 2 ** n - 1) + 5)
elif n == 0:
return ack5(m - 1, 1)
else:
return ack5(m - 1, ack5(m, n - 1))
Python code should be readable for the programmer, so it's more of a personal choice question. If I had to pick one of your 3 examples I'd go with ack4 since those backslashes indicate that everything is one big statement without bloating the expression like a bracket does in my opinion.
Don't be afraid of multiple returns. Also, try to avoid capital letters for local variables.
def ack4(m, n):
if m == 0:
return n + 1
if m == 1:
return n + 2
if m == 2:
return 2 * n + 3
if m == 3:
return (8 * ( 2 ** n - 1) + 5)
if n == 0:
return ack5(m - 1, 1)
return ack5(m - 1, ack5(m, n - 1))
def ack5(m, n):
if m == 0: return n + 1
if m == 1: return n + 2
if m == 2: return 2*n + 3
if m == 3: return 8*(2**n - 1) + 5
if n == 0: return ack5(m-1, 1)
return ack5(m-1, ack5(m, n-1))