Unable to use recursion - python

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))

Related

N Queen code (python) only working for n as 1 or 5. Doesnt return anything for anything else

So I tried coding a program to solve NQueen problem in python. It is only outputing correct response for n as 1 or 5. It doesn't throw an error or anything for the rest of numbers.
Here is the code:
import numpy as np
def isSafe(arr, row, col, n):
for ind in range(row):
if(arr[ind][col] == 1):
return False
x = row
y = col
while x >= 0 and y >= 0:
if arr[x][y] == 1:
return False
x -= 1
y -= 1
x = row
y = col
while x >= 0 and y < n:
if arr[x][y] == 1:
return False
x -= 1
y += 1
return True
def nQueen(arr, row, n):
if row >= n:
return True
for col in range(n):
if isSafe(arr,row,col,n) == True:
arr[row][col] = 1
if nQueen(arr, row+1, n) == True:
return True
return False
def main():
n = int(input("Enter the size of board: "))
arr = np.zeros((n,n)).astype(int)
if nQueen(arr, 0, n):
for x in range(n):
for y in range(n):
print(arr[x][y], end='\t')
print("\n")
else:
print("No Solution: ")
if __name__ == '__main__':
main()\
Using Lists:
import numpy as np
def isSafe(arr, row, col, n):
for ind in range(row):
if(arr[ind][col] == 1):
return False
x = row
y = col
while x >= 0 and y >= 0:
if arr[x][y] == 1:
return False
x -= 1
y -= 1
x = row
y = col
while x >= 0 and y < n:
if arr[x][y] == 1:
return False
x -= 1
y += 1
return True
def nQueen(arr, row, n):
if row >= n:
return True
for col in range(n):
if isSafe(arr,row,col,n) == True:
arr[row][col] = 1
if nQueen(arr, row+1, n) == True:
return True
return False
def main():
n = int(input("Enter the size of board: "))
arr = [[0]*n]*n
if nQueen(arr, 0, n):
for x in range(n):
for y in range(n):
print(arr[x][y], end='\t')
print("\n")
else:
print("No Solution: ")
if __name__ == '__main__':
main()
I tried using every single integer from 0 to 20 but only 1 and 5 seemed to output something while any other number just outputted "No Solution".
Also, The lists one doesnt even output an answer for 5, just 1
When you determine that an assignment arr[row][col] is not safe, you never reset it for future tests.
def nQueen(arr, row, n):
if row >= n:
return True
for col in range(n):
if isSafe(arr,row,col,n) == True:
arr[row][col] = 1 # Put a queen here
if nQueen(arr, row+1, n) == True:
return True
arr[row][col] = 0 # Take it back; it didn't work here
return False

Valid position in array

else:
res = (numbers.index(str_pos[1:]), letters.index(str_pos[0]))
return res
def is_in_board(n,pos):
letters = [chr(x + ord('a')) for x in range(n)]
numbers = [str(x) for x in range(1, n + 1)]
numbers.reverse()
pos = ''.join([letters[pos[1]], numbers[pos[0]]])
if extract_pos(n,pos) is not None:
return True
else:
return False
How can I return False when the list (pos) index is out of range ?board
At the first line of the function extract_pos function you know all that you need:
The size of the plate: n x n
The desired indexes: str_pos
So I would do something like this at the first line of the extract_pos function:
if int(str_pos[0]) >= n or int(str_pos[1]) >= n or int(str_pos[0]) < 0 or int(str_pos[1]) < 0 :
return 'Out of index'
Then you have to check that return value in the is_in_board function:
extract_pos_return_value = extract_pos(n,pos)
if extract_pos_return_value is not None and extract_pos_return_value is not 'Out of index':
return True
else:
return False
Full Code:
def extract_pos(n, str_pos):
if int(str_pos[0]) >= n or int(str_pos[1]) >= n or int(str_pos[0]) < 0 or int(str_pos[1]) < 0 :
return 'Out of index'
letters = [chr(x + ord('a')) for x in range(n)]
numbers = [str(x) for x in range(1,n+1)]
numbers.reverse()
if len(str_pos) < 2 or str_pos[0] not in letters or str_pos[1] not in numbers:
res = None
else:
res = (numbers.index(str_pos[1:]), letters.index(str_pos[0]))
return res
def is_in_board(n,pos):
letters = [chr(x + ord('a')) for x in range(n)]
numbers = [str(x) for x in range(1, n + 1)]
numbers.reverse()
pos = ''.join([letters[pos[1]], numbers[pos[0]]])
extract_pos_return_value = extract_pos(n,pos)
if extract_pos_return_value is not None and extract_pos_return_value is not 'Out of index':
return True
else:
return False
I'll try to show you a simpler solution.
First, you do not need to construct lists for letters and for numbers, it is much easier to check the parameter.
Then in your is_in_board function you have not handled your pos parameter correctly.
Please check this solution:
def extract_pos(n, str_pos):
if 1<=ord(str_pos[0])-ord('a')<=n and 1<=ord(str_pos[1])-ord('0')<=n:
return n-int(str_pos[1]), (ord(str_pos[0])-ord('a'))
else:
return None
def is_in_board(n, pos):
xpos = extract_pos(n,chr(pos[1]+ord('a'))+chr(8-pos[0]+ord('0')))
if xpos != None:
x, y = xpos
if 0<=x<n and 0<=y<n:
return True
return False

Code not giving a response (Quaternary Search Algorithm)

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

Newton Recursive Method for Square Root Problem in Python

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.

Python does not start for loop

old = [[0 for x in range(3)] for y in range(10)]
count =0
# check if the number has non-repeating digits
def different(number):
digit_list = [0] * 4
i = 0
while i:
digit_list[i] = number%10
number /= 10
i += 1
for x in range(0,3):
for y in range(x+1,3):
if digit_list[x] == digit_list[y]:
return False
return True
# save the tried numbers, plus and minus values
# for prediction of the next number
def save(number,plus,minus):
global count
old[count][0] = number
old[count][1] = plus
old[count][2] = minus
count += 1
return
# compare for plus values
def get_plus(number1,number2):
ret_value = 0
for x in range(0, 3):
if number1 % 10 == number2 % 10:
ret_value += 1
number1 /= 10
number2 /= 10
return ret_value
# compare for minus values
def get_minus(number1,number2):
temp = [[0]*4 for i in range(2)]
ret_value = 0
for x in range(0,3):
temp[0][x] = number1 % 10
temp[0][x] = number2 % 10
number1 /= 10
number2 /= 10
for x in range(0,3):
for y in range(0,3):
if x != y:
if temp[0][x] == temp[1][y]:
ret_value += 1
return ret_value
# compare the number to be asked with the numbers in the array
def control(number):
for x in range(0,count-1):
if get_plus(old[x][0],number) != old[x][1]:
return False
if get_minus(old[x][0],number) != old[x][2]:
return False
return True
def main():
flag = False
print('1023 ??')
plus = input('plus ?')
minus = input('minus ?')
save(1023, plus, minus)
print('4567 ??')
plus = input('plus ?')
minus = input('minus ?')
save(4567, plus, minus)
for i in range(1024, 9876):
if different(i):
if control(i):
print(i + ' ??')
plus = input('plus ?')
minus = input('minus ?')
save(i, plus, minus)
if plus == 4 and minus == 0:
print('I WON !!!')
flag = True
break
if not flag:
print('False')
return
main()
I am trying to make an AI for mindgame in python. But in this function it doesn't even start the for loop. Can anyone know why ?
The while loop in your different() function does nothing as while(0) will prevent the loop from running. Even if that would run, your different() function will always return false. At least in the last loop it will compare digit_list[3] == digit_list[3] as both loop range until 3. This is always true and the function will return false. Thus the code within your main loop will never be entered.
def different(number):
digit_list = [0] * 4
i = 0
while i:
digit_list[i] = number%10
number /= 10
i += 1
for x in range(0,3):
for y in range(x+1,3):
if digit_list[x] == digit_list[y]:
return False
return True
Try this one:
import random
def different(num):
digits = []
while num >= 1:
cur = num%10
if cur in digits:
return False
digits.append(cur)
num = (num - cur) / 10
return True
for i in range(0, 10000):
rand = random.randrange(1000, 10000)
if not different(rand):
print(rand)

Categories

Resources