So I'm new to coding, and im trying as a first project to create a quaternary search algorithm, I have tried doing it in a recursive matter but it gave me a "maximum recursion" error, so I tried doing it in an iterative manner, but this time It doesn't even give me a response and I don't know why, this is the code:
def quaternary_search(y,x):
low = 0
high = len(y) -1
mid1 = 0
mid2 = 0
mid3 = 0
while high>=low:
mid1 = int(round(high/4))
mid2 = int(round(high/2))
mid3 = int(round(3*high/4))
if y[mid1] == x:
return mid1
elif y[mid2] == x:
return mid2
elif y[mid3] == x:
return mid3
elif y[mid1] > x and y[mid2] > x and y[mid3] > x:
high = mid1 - 1
elif y[mid1] < x and y[mid2] > x and y[mid3] > x:
low = mid1 + 1
high = mid2 - 1
elif y[mid1] < x and y[mid2] < x and y[mid3] > x:
low = mid2 + 1
high = mid3 - 1
elif y[mid1] < x and y[mid2] < x and y[mid3] < x:
low = mid3 + 1
return -1
y = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
x = int(input("What are you searching?"))
result = quaternary_search(y,x)
if result != -1:
print("Element is at index",str(result))
else:
print("Element is not found")
```
just simply add +1 to the x variable when passing it into the function. list indexes start at 0, so you need to add 1.
result = quaternary_search(y,x+1)
seems to work with that small change, here when I enter 8 it says it's at the 8th index.
What are you searching?8
Element is at index 8
Related
Problem link = https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/
Was practicing on leetcode and came around the above the Q. Wrote the code written below, no idea why it is not running!
def min_num(nums,x):
f_ele = nums[0]
l_ele = nums[-1]
count = 0
if min(x - f_ele, x - l_ele ) >= 0:
count += 1
#modifying x and nums
if x - f_ele == min(x - f_ele, x - l_ele ):
x = x - f_ele
nums.remove(f_ele)
else:
x = x - l_ele
nums.remove(l_ele)
#Comparing x to use recursion or return the count
if x != 0:
min_num(nums,x)
else:
return count
elif x == 0:
return count
else:
return -1
Please help!!
When you do recursion and want to return something you need to also return the result from the recursion itself.
You also can't set the count to zero in the min_num function because then the count will constantly be set to zero when you run the recursion.
Here is your code with these two small changes:
def min_num(nums, x, count=0):
f_ele = nums[0]
l_ele = nums[-1]
if min(x - f_ele, x - l_ele) >= 0:
count += 1
# modifying x and nums
if x - f_ele == min(x - f_ele, x - l_ele):
x = x - f_ele
nums.remove(f_ele)
else:
x = x - l_ele
nums.remove(l_ele)
# Comparing x to use recursion or return the count
if x != 0:
return min_num(nums, x, count)
else:
return count
elif x == 0:
return count
else:
return -1
nums = [1, 1, 4, 2, 3]
x = 5
print(min_num(nums, x))
This returns 2
def find_min(x,arrayin):
if (len(arrayin)==0 or x==-1):
return -1
elif x==0:
return len(arrayin)
left=arrayin[0]
right=arrayin[len(arrayin)-1]
if x-min(left,right)<0:
return find_min(-1,arrayin)
if x-max(left,right)>=0:
if left>right: ##Remove left
return find_min(x-left,arrayin[1:len(arrayin)])
else:##Remove right
return find_min(x-right,arrayin[0:len(arrayin)-1])
elif x-min(left,right)>=0:
if left>right: ##Remove left
return find_min(x-right,arrayin[0:len(arrayin)-1])
else:
return find_min(x-left,arrayin[1:len(arrayin)])
nums = [3,2,20,1,1,3]
x = 10
res=find_min(x,nums)
if res==-1:
print("-1")
else:
Answer=len(nums)-res
print(str(Answer))
For a=13 and a precision epsilon=10^-7. How many times do you apply the newton recursion formula in newton_sqrt(13,10^-7)? Hint: use global variables.
My current newton_sqrt(a, epsilon) function is the following:
def newton_sqrt(a, epsilon):
global count
if a < 0:
print("Error: a < 0")
return -1
elif a == 0.0:
return 0
else:
x = abs(a)
newx = 0.5*(x + a/x)
if abs(x - newx) > epsilon:
newton_sqrt(newx, epsilon)
count = count + 1
if not abs(x-newx) > epsilon:
print (count)
return newx
newton_sqrt(13, 0.000001)
For whatever reason, I get
918488688 None
as my output.
Please help.
There is no output since you never reach the print line:
basically, you have:
if x:
if not x:
print(something)
what you want, i'm guessing is:
if x:
#do something
else:
#do somthing else
not knowing the math of your function I would change it into:
def newton_sqrt(a, epsilon, count):
if a < 0:
print("Error: a < 0")
return -1
elif a == 0.0:
return 0
else:
x = abs(a)
newx = 0.5*(x + a/x)
if abs(x - newx) > epsilon:
count = count + 1
newton_sqrt(newx, epsilon, count)
else:
print (count)
return newx
which will give you:
newton_sqrt(13, 0.000001, 0)
23
First, let's be clear that your newton_sqrt() function doesn't work. Either you're trying to instrument the recursion depth to fix it, or you're unaware it's broken.
A working newton_sqrt() would be along the lines of:
import sys
def newton_sqrt(a, epsilon, x=None):
if a < 0:
print("Error: a < 0", file=sys.stderr)
return -1
if a == 0:
return 0
if x is None: # initial guess
x = a
new_x = (x + a / x) / 2 # refine guess
if abs(new_x * new_x - a) < epsilon: # test guess
return new_x
return newton_sqrt(a, epsilon, new_x) # (better) guess again
print(newton_sqrt(13, 1e-06))
Once that's working, instrumenting the recursion depth using a global variable, count, is simple:
import sys
count = 0
def newton_sqrt(a, epsilon, x=None):
global count
count += 1
if a < 0:
print("Error: a < 0", file=sys.stderr)
return -1
if a == 0:
return 0
if x is None: # initial guess
x = a
new_x = (x + a / x) / 2 # refine guess
if abs(new_x * new_x - a) < epsilon: # test guess
return new_x
return newton_sqrt(a, epsilon, new_x) # (better) guess again
print(newton_sqrt(13, 1e-06), count)
OUTPUT
> python3 test.py
3.6055513629176015 5
>
Where 3.6055513629176015 is the square root of 13 and 5 is the recursion depth needed to compute it with an error of less than 1e-06.
At the moment, I managed to code, successfully, a simulation for a work that I need to do. However, I'm fairly new to python. And so, I'm now in the process of making the simulation more efficient.
For instance:
if random.random() < mm:
z = numpy.random.choice(pat)
if random.random() < 0.5:
if random.random() < mut:
if maleadult[z][0] == 0:
malejuv[y][x][0] = 1
elif maleadult[z][0] == 1:
malejuv[y][x][0] = 0
else:
malejuv[y][x][0] = maleadult[z][0]
else:
if random.random() < mut:
if femaleadult[z][0] == 0:
malejuv[y][x][0] = 1
elif femaleadult[z][0] == 1:
malejuv[y][x][0] = 0
else:
malejuv[y][x][0] = femaleadult[z][0]
if random.random() < 0.5:
if random.random() < mut:
if maleadult[z][1] == 0:
malejuv[y][x][1] = 1
elif maleadult[z][1] == 1:
malejuv[y][x][1] = 0
else:
malejuv[y][x][1] = maleadult[z][1]
else:
if random.random() < mut:
if femaleadult[z][1] == 0:
malejuv[y][x][1] = 1
elif femaleadult[z][1] == 1:
malejuv[y][x][1] = 0
else:
malejuv[y][x][1] = femaleadult[z][0]
where:
mm - male dispersal,
mf - female dispersal,
mut - mutations,
pat - patch,
maleadult - adult male,
femaleadult - adult female,
malejuv - juvenile male,
femalejuv - juvenile female.
As you can see, the code is big. And this is only for males and when they disperse. The rest of the code is very similar. These are standard genetic and demographic processes - but I feel like this can be improved. I feel like these processes are simple enough, so maybe code as big as this is not necessary.
Does anyone have any ideas to shorten this and, by consequence, making it more efficient?
Your example does not have any loops but it looks like it could be simplified by one:
if random.random() < mm:
z = numpy.random.choice(pat)
for i in range(2):
if random.random() < 0.5:
if random.random() < mut:
if maleadult[z][i] == 0:
malejuv[y][x][i] = 1
elif maleadult[z][i] == 1:
malejuv[y][x][i] = 0
else:
malejuv[y][x][i] = maleadult[z][i]
else:
if random.random() < mut:
if femaleadult[z][i] == 0:
malejuv[y][x][i] = 1
elif femaleadult[z][i] == 1:
malejuv[y][x][i] = 0
else:
malejuv[y][x][i] = femaleadult[z][i]
It is also possible to pass a mutable object as reference to a function which can modify it, which allows further reduction of almost redundant code. I've added some data to test it:
#!python3
#coding=utf-8
import random
maleadult = [[["male adult"], ["another male adult"], ]]
femaleadult = [[["female adult"], ["another female adult"], ]]
malejuv = [[[["male juv"],["another male juv"]]]]
mut = 0.5
mm = 1.0
x = 0
y = 0
z = 0
def some_logic(a, j):
""" does something """
if random.random() < mut:
if a[z][i] == 0:
j[y][x][i] = 1
elif a[z][i] == 1:
j[y][x][i] = 0
# added!
else:
j[y][x][i] = 0
else:
j[y][x][i] = a[z][i]
if random.random() < mm:
z = 0 #numpy.random.choice(pat)
for i in range(2):
print(i)
if random.random() < 0.5:
some_logic(maleadult, malejuv)
else:
some_logic(femaleadult, malejuv)
print(maleadult)
print(malejuv)
print(femaleadult)
Below code is taking excessively long time when executed for larger inputs such as x = 23!!!! and y = 5!!!!!. The output of the code should be comparison between x and y. small example regarding the inputs is, if input is 3!!, this means (3!)!) = 6! = 720.
def large()
t = int(input())
i = 0
fact_str = ""
fact_stry = ""
res, resy = 1, 1
counter = 0
countery = 0
while(i < t):
x = input()
y = input()
for char in x:
if char == '!' and counter == 0:
fact_str = int(fact_str)
for num in range(fact_str, 0, -1):
res = res * num
counter = counter + 1
elif counter > 0:
for num in range(res-1, 0, -1):
res = res * num
else:
fact_str = str(fact_str)
fact_str = fact_str + char
for chary in y:
if chary == '!' and countery == 0:
fact_stry = int(fact_stry)
for numy in range(fact_stry, 0, -1):
resy = resy * numy
countery = countery + 1
elif countery > 0:
for num in range(resy-1, 0, -1):
resy = resy * numy
else:
print("at esle", resy)
fact_stry = str(fact_stry)
fact_stry = fact_stry + chary
if len(str(x)) == len(str(fact_str)):
fact_str = int(fact_str)
x = fact_str
else:
x = res
if len(str(y)) == len(str(fact_stry)):
fact_stry = int(fact_stry)
y = fact_stry
else:
y = res
x = int(x)
y = int(y)
if x == y:
print("x=y")
elif x > y:
print("x>y")
else:
print("x<y")
i = i + 1
large()
can this code be optimized so that it can execute faster if inputs are large values ? Or python is limited to smaller inputs ?
I want to make a binary calculator and I have a problem with the subtraction part. Here is my code (I have tried to adapt one for sum that I've found on this website).
maxlen = max(len(s1), len(s2))
s1 = s1.zfill(maxlen)
s2 = s2.zfill(maxlen)
result = ''
carry = 0
i = maxlen - 1
while(i >= 0):
s = int(s1[i]) - int(s2[i])
if s <= 0:
if carry == 0 and s != 0:
carry = 1
result = result + "1"
else:
result = result + "0"
else:
if carry == 1:
result = result + "0"
carry = 0
else:
result = result + "1"
i = i - 1
if carry>0:
result = result + "1"
return result[::-1]
The program works fine with some binaries subtraction but it fails with others.
Can someone please help me because I can't find the mistake? Thanks a lot.
Short answer: Your code is wrong for the case when s1[i] == s2[i] and carry == 1.
Longer answer: You should restructure your code to have three separate cases for s==-1, s==0, and s==1, and then branch on the value of carry within each case:
if s == -1: # 0-1
if carry == 0:
...
else:
...
elif s == 0: # 1-1 or 0-0
if carry == 0:
...
else:
...
else: # 1-0
if carry == 0:
...
else:
...
This way you have a separate block for each possibility, so there is no chance of overlooking a case like you did on your first attempt.
I hope the answer below it helps.
def binarySubstration(str1,str2):
if len(str1) == 0:
return
if len(str2) == 0:
return
str1,str2 = normaliseString(str1,str2)
startIdx = 0
endIdx = len(str1) - 1
carry = [0] * len(str1)
result = ''
while endIdx >= startIdx:
x = int(str1[endIdx])
y = int(str2[endIdx])
sub = (carry[endIdx] + x) - y
if sub == -1:
result += '1'
carry[endIdx-1] = -1
elif sub == 1:
result += '1'
elif sub == 0:
result += '0'
else:
raise Exception('Error')
endIdx -= 1
return result[::-1]
normalising the strings
def normaliseString(str1,str2):
diff = abs((len(str1) - len(str2)))
if diff != 0:
if len(str1) < len(str2):
str1 = ('0' * diff) + str1
else:
str2 = ('0' * diff) + str2
return [str1,str2]