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
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))
I need to write an algorithm, that can represent a number as a min sum of prime numbers:
For example:
8 -> [2, 2, 2, 2], [3, 5], [2, 3, 3]
and I need get min len of this => 2
I've written the code, but it takes a lot of time, because it contains recursion. How can I change it to improve time?
import sys
x = int(sys.stdin.readline())
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
def decomposition(x):
result = []
for a in range(2, int(x/2 + 1)):
if x-a >= 2:
b = x - a
pair = [a, b]
result.append(pair)
return result
def f(elem):
list_of_mins = []
if is_prime(elem) == True:
return 1
else:
pairs = decomposition(elem)
print(pairs)
for a,b in pairs:
list_of_mins.append(f(a)+f(b))
return min(list_of_mins)
if str(int(x)).isdigit() and 2 <= int(x) <= 10 ** 9:
sum = []import sys
x = int(sys.stdin.readline())
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
def decomposition(x):
result = []
for a in range(2, int(x/2 + 1)):
if x-a >= 2:
b = x - a
pair = [a, b]
result.append(pair)
return result
def f(elem):
list_of_mins = []
if is_prime(elem) == True:
return 1
else:
pairs = decomposition(elem)
print(pairs)
for a,b in pairs:
list_of_mins.append(f(a)+f(b))
return min(list_of_mins)
if str(int(x)).isdigit() and 2 <= int(x) <= 10 ** 9:
sum = []
print(f(x))
Your is_prime function only needs to test divisors up to pow(n, 0.5)+1. This means your code would be:
def is_prime(n):
for i in range(2, int(pow(n, 0.5)+1):
if n % i == 0:
return False
return True
This should speed your algorithm up significantly.
Here's a possible solution:
import math
class Foo():
def __init__(self, n):
self.n = n
self.primes = self.prime_sieve(n)
def prime_sieve(self, sieve_size):
sieve = [True] * sieve_size
sieve[0] = False
sieve[1] = False
for i in range(2, int(math.sqrt(sieve_size)) + 1):
pointer = i * 2
while pointer < sieve_size:
sieve[pointer] = False
pointer += i
primes = []
for i in range(sieve_size):
if sieve[i] == True:
primes.append(i)
return primes
def sum_to_n(self, n, size, limit=None):
if size == 1:
yield [n]
return
if limit is None:
limit = n
start = (n + size - 1) // size
stop = min(limit, n - size + 1) + 1
for i in range(start, stop):
for tail in self.sum_to_n(n - i, size - 1, i):
yield [i] + tail
def possible_sums(self):
for i in range(2, self.n):
result = list(self.sum_to_n(self.n, i))
result = (
[v for v in result if all([(p in self.primes) for p in v])])
if result:
yield result
def result(self):
for i in self.possible_sums():
return i
raise Exception("Not available result!")
if __name__ == '__main__':
obj = Foo(8)
print(list(obj.possible_sums()))
print('-' * 80)
try:
v = obj.result()
print("{} , length = {}".format(v[0], len(v[0])))
except Exception as e:
print(e)
Result:
[[[5, 3]], [[3, 3, 2]], [[2, 2, 2, 2]]]
--------------------------------------------------------------------------------
[5, 3] , length = 2
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)
It's supposed to find out if the given input is a prime number or not.
def is_prime(x):
if x <= 1:
return False
elif x == 2 or x == 3:
return True
else:
for n in range(2, x-1):
if x % n == 0:
return False
else:
return True
But
is_prime(9)
gives True where it should return False.
I can't find the bug, need help.
You return True the moment you find a factor that doesn't divide x evenly. 2 doesn't divide 9 so you return True then:
>>> x = 9
>>> n = 2
>>> if x % n == 0:
... print False
... else:
... print True
...
True
You need only return True when you determined that no factors exist, so outside your loop:
for n in range(2, x-1):
if x % n == 0:
return False
return True
You don't need to test up to x - 1, testing up to int(x ** 0.5) + 1 is enough (so up to the square root):
def is_prime(x):
if x <= 1:
return False
if x in (2, 3):
return True
for n in range(2, int(x ** 0.5) + 1):
if x % n == 0:
return False
return True
I am a newbie in python .
Guys I have written one function which checks that the list is palindrome or not but I wanted to replace it with pure looping statements .Do u have any solution or do I have to use recursive function compulsorily .
import json
def reverse(x):
if isinstance(x, list):
return [reverse(x) for x in x[::-1]]
return x
def palindrome(x):
return x == reverse(x)
st=raw_input("Enter List : ")
lst=json.loads(st)
print palindrome(lst)
check this...
>>> def palindrome(n):
return n == n[::-1]
>>> palindrome('chk')
False
>>> palindrome('chc')
True
>>>
Check this out:
def is_palindrome(lst):
n = len(lst)
p, q = 0, n - 1
while p <= q:
pitem, qitem = lst[p], lst[q]
if isinstance(pitem, list) and isinstance(qitem, list):
if len(pitem) != len(qitem):
return False
if p == q:
lst[p:p+1] = pitem
q = p + len(pitem) - 1
else:
lst[p:p+1] = pitem
q += len(pitem) - 1
lst[q:q+1] = qitem
q += len(qitem) - 1
continue
elif pitem != qitem:
return False
p += 1;
q -= 1
return True
Above code also passes for nested list:
assert is_palindrome([1, 2, 3, 2, 1])
assert not is_palindrome([[0, 1]])
assert not is_palindrome([[0, 1, 1]])
assert is_palindrome([[0, 1, 0]])
assert is_palindrome([1, [1, 2], 3, [2, 1], 1])
You can do it with a simple loop:
def is_palindrome(s):
n = len(s)
for i in range(n / 2):
if s[i] != s[n - 1 - i]:
return False
return True
It's worth to mention, that above function uses only n / 2 comparisons and the below solution uses n comparisons:
def is_palindrome(s):
return s == s[::-1]
def palindrome(x):
q = [x]
while q:
x = q.pop()
if isinstance(x, list) and x:
if isinstance(x[0], list) and isinstance(x[-1], list):
q.append(x[0] + x[-1])
elif x[0] != x[-1]:
return False
q.append(x[1:-1])
elif isinstance(x, str):
q.append(list(x))
return True
def palindrome(x):
q = [x]
while q:
x = q.pop()
if isinstance(x, (str, list)):
for i in range(len(x) + 1 // 2):
if isinstance(x[i], list) and isinstance(x[-i-1], list):
q.append(x[i] + x[-i-1])
elif x[i] != x[-i-1]:
return False
return True
>>> palindrome('cat')
False
>>> palindrome('yay')
True
>>> palindrome([1, 2,3,[2],1])
False
>>> palindrome([1, [2,3,[4]],[[4],3,2],1])
True
>>> palindrome([[2,3], [2,3]])
False