Recursion function inn python - python-3.x

I am trying to understand the recursion function. I would like to know how that answer is coming with steps
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
results are this just want to know how its coming
1
3
6
10
15
21

The function computes the sum of all numbers between 0 and n, and prints intermediate results. The first 1 is 0+1, the 3 = 0+1+2, 6 = 0+1+2+3, 10 = 0+1+2+3+4, ...
To understand a recursive function, you need 2 points : how is the recursive call done, and when does the recursion stop.
The recursive call is given by result = k+tri_recursion(k-1)and the recursion stops when k <= 0and returns 0. So if we assume only positive numbers, we could describe tri_recursion so:
tri_recursion(k) = k + tri_recursion(k-1) if k > 0
tri_recursion(0) = 0
So tri_recursion(k) = k + tri_recursion(k-1) = k + (k-1) + tri_recursion(k-2) = k + (k-1) + (k-2) + tri_recursion(k-3) ... = k + (k-1) + (k-2) + ... + 0
So tri_recursion(k) is the sum of all numbers between 0 and k.
Note that the sum on all numbers between 0 and k equals k*(k+1) / 2 so tri_recursion(6) = 6 * 7 / 2 = 21

Related

EXCEL / VBA - function #VALUE error in spreadsheet

(I want to calculate the number of possible ways of getting 'sum' out of 'n' dice throws (dices have 'k' faces from 1..k).)
When i want to use this function in an excel spreadsheet, I get a #VALUE error no matter what inputs i try.
I have other functions in the same module, used in the same sheet that work fine\
Function how_many_ways(n, k, sum)
If n = 0 Then
If sum = 0 Then
how_many_ways = 1
Else
how_many_ways = 0
End If
End If
If sum < 0 Or k * n < sum Or n > sum Then
how_many_ways = 0
End If
res = 0
For i = 1 To k
res = res + how_many_ways(n - 1, k, sum - i)
Next i
how_many_ways = res
End Function
It always runs the for loop so it recurs infinitely. Try this.
Function how_many_ways(n, k, sum)
If n = 0 Then
If sum = 0 Then
how_many_ways = 1
Else
how_many_ways = 0
End If
ElseIf sum < 0 Or k * n < sum Or n > sum Then
how_many_ways = 0
Else
res = 0
For i = 1 To k
res = res + how_many_ways(n - 1, k, sum - i)
Next i
how_many_ways = res
End If
End Function

Python(AI Constraint satisfaction problem) Fitting square and/or rectangular (2d) tiles onto a rectangular ground

I have to arrange and/or fit 2d tiles into a 2d square or rectangular plane with AI algorithm using python program. Each tile has a length and width. For example if a plane is 4x3 and set of tiles is
S={(2,3),(1,2),(2,2)}
these tiles can be rotated 90 degrees in order to fit the matrix.
input
first line contains length and width of the plane
second line number of tiles
and then the length,width of the subsequent tiles
but the inputs should be tab seperated
for eg
4 3
3
2 3
1 2
2 2
output
for eg
1 1 2 2
1 1 3 3
1 1 3 3
I have trouble solving this as i have to use only standard libraries in python no NumPy and no CSP library
~Edit 2`
my code so far I cant figure out how to add algorithm without csp library or to generate grid
from sys import stdin
a = stdin.readline()
x = a.split()
rectangular_plane = [[0] * int(x[0]) for i in range(int(x[1]))]
num_of_rectangles = stdin.readline()
r_widths = []
r_lengths= []
for l in range(int(num_of_rectangles)):
b = stdin.readline()
y = b.split()
r_lengths.insert(l,y[0])
r_widths.insert(l,y[1])
I've solved task with backtracking approach and without any non-standard modules.
Try it online!
import sys
nums = list(map(int, sys.stdin.read().split()))
pw, ph = nums[0:2]
ts = list(zip(nums[3::2], nums[4::2]))
assert len(ts) == nums[2]
if sum([e[0] * e[1] for e in ts]) != pw * ph:
print('Not possible!')
else:
def Solve(*, it = 0, p = None):
if p is None:
p = [[0] * pw for i in range(ph)]
if it >= len(ts):
for e0 in p:
for e1 in e0:
print(e1, end = ' ')
print()
return True
for tw, th in [(ts[it][0], ts[it][1]), (ts[it][1], ts[it][0])]:
zw = [0] * tw
ow = [it + 1] * tw
for i in range(ph - th + 1):
for j in range(pw - tw + 1):
if all(p[k][j : j + tw] == zw for k in range(i, i + th)):
for k in range(i, i + th):
p[k][j : j + tw] = ow
if Solve(it = it + 1, p = p):
return True
for k in range(i, i + th):
p[k][j : j + tw] = zw
return False
if not Solve():
print('Not possible!')
Example input:
4 3
3
2 3
1 2
2 2
Output:
1 1 2 2
1 1 3 3
1 1 3 3

Code fails on Test case. (InterQuartile Range)

This is a challenge from 10 Day statistics on Hackerrank.(https://www.hackerrank.com/challenges/s10-interquartile-range/problem?h_r=next-challenge&h_v=zen)
Task :
Task
The interquartile range of an array is the difference between its first (Q1) and third (Q3) quartiles (i.e., Q3 - Q1).
Given an array,X, of n integers and an array, F, representing the respective frequencies of X's elements, construct a data set, S, where each xi occurs at frequency fi. Then calculate and print S's interquartile range, rounded to a scale of 1 decimal place (i.e., 12.3 format).
Following is my code.
n = int(input())
x = list(map(int, input().split()))
f = list(map(int, input().split()))
s = []
for i in range(len(x)):
j = f[i]
for k in range(j):
s.append(x[i])
n = len(s)
s.sort()
if n%2 == 0:
Q21 = s[n//2]
Q22 = s[n//2 - 1]
Q2 = (Q21 + Q22) / 2
else:
Q2 = s[n//2]
LH = s[:n//2]
if n%2==0:
UH = s[n//2:]
else:
UH = s[n//2+1:]
Q1_len = len(LH)
Q3_len = len(UH)
if Q1_len%2 == 0:
Q11 = LH[Q1_len//2]
Q12 = LH[Q1_len//2 - 1]
Q1 = (Q11 + Q12) / 2
else:
Q1 = LH[Q1_len//2]
if Q3_len%2 == 0:
Q31 = UH[Q3_len//2]
Q32 = UH[Q3_len//2 - 1]
Q3 = (Q31 + Q32) / 2
else:
Q3 = UH[Q3_len//2]
print(round(Q3 - Q1,1))
# print(int(Q2))
# print(int(Q3))
Here is the test case: with std input.
5
10 40 30 50 20
1 2 3 4 5
Expected output:
30.0
My code output:
30.0 # I get this output on my code editor but not on Hackerrank
Can someone help me on this where I am wrong ?
I get the output what is expected but it shows as failed.
print(float(Q3 - Q1))
Basically is the answer.

I want to add two extremely large numbers in python which even bignum can't handle

I am new in python,I want to add two extremely large numbers in python which even bignum can't handle. I can take these two numbers as a string and then can calculate from the end and as like we used to do in old school addition process. we can take the carriage and add it to the next numbers and so on.
Please assist.
The question seemed interesting enough for a Christmas Day coding snack.
Here's my implementation using many of the builtins in Python.
reversed is used to iterate over the digit sequences from right to left, i.e. like we would when computing on paper
zip_longest "fills" in the sequences' ends with zeroes (as we would ignore digits on paper)
divmod computes the carried-forward value and the current digit in a single call.
The result is reversed, so it's once more reversed to be least-significant-digit-last, and stray zeroes on the left are removed using lstrip.
It does not handle negative numbers, though.
from itertools import zip_longest
def add(a, b):
out = []
a = [int(c) for c in str(a)]
b = [int(c) for c in str(b)]
carry = 0
for ca, cb in zip_longest(reversed(a), reversed(b), fillvalue=0):
carry, digit = divmod(ca + cb + carry, 10)
out.append(str(digit))
return "".join(reversed(out)).lstrip("0")
a = 9999 ** 29
b = 3725241 ** 9
assert add(a, b) == str(a + b)
I achieved that after 3 hours of work. :)
def add_func(num1,num2):
res_list = []
number1 = str(num1)
number2 = str(num2)
length1 = len(str(number1))
length2 = len(str(number2))
if(length1 > length2):
while(length1 > length2):
number2 = '0' + number2
length2 += 1
if(length2 > length1):
while(length2 > length1):
number1 = '0' + number1
length1 += 1
i = max(length1,length2)
carry = 0
while(i > 0):
if(int(number1[i-1]) + int(number2[i-1]) + carry > 9):
result = str(int(number1[i-1]) + int(number2[i-1]) + carry)
res_list.insert(0,(result[-1]))
carry = 1
if(i==1):
result = str(int(number1[i-1]) + int(number2[i-1]) + carry)
res_list[0]= result
elif(int(number1[i-1]) + int(number2[i-1]) > 9):
result = str(int(number1[i-1]) + int(number2[i-1]))
res_list.insert(0,(result[-1]))
carry = 1
else:
result = str(int(number1[i-1]) + int(number2[i-1]) + carry)
res_list.insert(0,(result[-1]))
carry = 0
i -=1
final_output = ('').join(res_list)
return final_output
print(add_func(9999**29,3725241**9))

Time and memory limit exceeded - Python3 - Number Theory

I am trying to find the sum of the multiples of 3 or 5 of all the numbers upto N.
This is a practise question on HackerEarth. I was able to pass all the test cases except 1. I get a time and memory exceeded error. I looked up the documentation and learnt that int can handle large numbers and the type bignum was removed.
I am still learning python and would appreciate any constructive feedback.
Could you please point me in the right direction so I can optimise the code myself?
test_cases = int(input())
for i in range(test_cases):
user_input = int(input())
sum = 0
for j in range (0, user_input):
if j % 3 == 0:
sum = sum + j
elif j % 5 == 0:
sum = sum + j
print(sum)
In such problems, try to use some math to find a direct solution rather than brute-forcing it.
You can calculate the number of multiples of k less than n, and calculate the sum of the multiples.
For example, with k=3 and n=13, you have 13 // 3 = 4 multiples.
The sum of these 4 multiples of 3 is 3*1 + 3*2 + 3*3 + 3*4 = 3 * (1+2+3+4)
Then, use the relation: 1+2+....+n = n*(n+1)/2
To sum the multiples of 3 and 5, you can sum the multiples of 3, add the sum of the multiples of 5, and subtract the ones you counted twice: the multiples of 15.
So, you could do it like this:
def sum_of_multiples_of(k, n):
"""
Returns the sum of the multiples of k under n
"""
# number of multiples of k between 1 and n
m = n // k
return k * m * (m+1) // 2
def sum_under(n):
return (sum_of_multiples_of(3, n)
+ sum_of_multiples_of(5, n)
- sum_of_multiples_of(15, n))
# 3+5+6+9+10 = 33
print(sum_under(10))
# 33
# 3+5+6+9+10+12+15+18 = 78
print(sum_under(19))
# 78

Resources