please what is wrong with this code
def binary_converter(n):
n = int(n)
if n == 0:
return '0'
elif n not in (0,255):
return 'Invalid input'
elif n in range (0,255):
return binary_converter(n//2) + str(n%2)
else:
return 'Invalid conversion'## Heading ##
here is the test
import unittest
class BinaryConverterTestCases(unittest.TestCase):
def test_conversion_one(self):
result = binary_converter(0)
self.assertEqual(result, '0', msg='Invalid conversion')
def test_conversion_two(self):
result = binary_converter(62)
self.assertEqual(result, '111110', msg='Invalid conversion')
def test_no_negative_numbers(self):
result = binary_converter(-1)
self.assertEqual(result, 'Invalid input', msg='Input below 0 not allowed')
def test_no_numbers_above_255(self):
result = binary_converter(300)
self.assertEqual(result, 'Invalid input', msg='Input above 255 not allowed')
First, (0, 255) is a tuple not a range of numbers so 2 in (0, 255) etc.. is going to fail, ranges are half-open so range(0,255) goes from 0...254, again 255 in range (0,255) -> False. Your third test self.assertEqual(result, '111110', msg='Invalid conversion') fails as you always add a leading "0" in your base case so you get '0111110' not '111110':
def binary_converter(n):
n = int(n)
if n == 0:
return '0'
# same as checking "if n in xrange(256)"
if 0 <= n <= 255:
return (binary_converter(n // 2) + str(n % 2)).lstrip("0")
elif 0 > n or n > 255:
return 'Invalid input' ## Heading ##
return 'Invalid conversion' ## Heading ##
Once you make the changes all the tests should pass.
You could also do it iteratively:
def binary_converter(n):
if n < 0 or n > 255:
return "Invalid input"
tmp = []
while n:
n, i = divmod(n, 2)
tmp.append(str(i))
return "".join(tmp[::-1] or "0")
Related
from typing import List
# You are given an integer n, denoting the no of people who needs to be seated, and a list of m integer seats, where 0 represents a vacant seat. Find whether all people can be seated, provided that no two people can sit together
When I run this code in geeks for geeks for submission I get a error that List index is out of range.
but seems to work fine when I run it as a script.
class Solution:
def is_possible_to_get_seats(self, n: int, m: int, seats: List[int]) -> bool:
vacant_seats = 0
if len(seats) == 2:
if seats[0] or seats[1] == 1:
print(seats)
return False
else:
print(seats)
return True
else:
for x in range(len(seats)):
if x == 0:
if seats[x] == 0 and seats[x+1] == 0:
seats[x] = 1
vacant_seats += 1
elif x == len(seats)-1:
if seats[x] == 0 and seats[x-1] == 0:
seats[x] = 1
vacant_seats += 1
else:
if seats[x] == 0:
if seats[x+1] == 0 and seats[x-1] == 0:
seats[x] = 1
vacant_seats += 1
if vacant_seats < n:
return False
else:
return True
# {
# Driver Code Starts
class IntArray:
def __init__(self) -> None:
pass
def Input(self, n):
arr = [int(i) for i in input().strip().split()] # array input
return arr
def Print(self, arr):
for i in arr:
print(i, end=" ")
print()
if __name__ == "__main__":
t = int(input())
for _ in range(t):
n = int(input())
m = int(input())
seats = IntArray().Input(m)
obj = Solution()
res = obj.is_possible_to_get_seats(n, m, seats)
result_val = "Yes" if res else "No"
print(result_val)
# } Driver Code Ends
```import sys
# Function to find the smallest subarray
# with sum greater than or equal target
def minlt(arr, target, n):
# DP table to store the
# computed subproblems
dp = [[-1 for _ in range(target + 1)]\
for _ in range(len(arr)+1)]
#pf = [-1 for _ in range(len(arr)+1)]
for i in range(len(arr)+1):
# Initialize first
# column with 0
dp[i][0] = 0
for j in range(target + 1):
# Initialize first
# row with 0
dp[0][j] = sys.maxsize
for i in range(1, len(arr)+1):
for j in range(1, target + 1):
# Check for invalid condition
if arr[i-1] > j:
dp[i][j] = dp[i-1][j]
else:
# Fill up the dp table
#if dp[i-1][j] == 1 or (1 + dp[i][j-arr[i-1]]) == sys.maxsize:
dp[i][j] = min(dp[i-1][j], \
1 + dp[i][j-arr[i-1]])
return dp[-1][-1]
# Print the minimum length
if dp[-1][-1] == sys.maxsize:
return(-1)
else:
return dp[-1][-1]
# Driver Code
arr = [10,9,2,1]
target = 11
n = len(arr)
print(minlt(arr, target, n))
can anyone make change to this program such that it will print the smallest subarray not the length
This code returns only length of smallest subarray whose sum is greater or equal to given target
Thanks in Advance
Here's how In would do what you want.
#First the function definition
def minlt(arr, target):
rslt = (None, None, None) #tuple containing the (subarray_sum, subarray_start, sub_array_length)
for i in range(len(arr)-1):
for k in range(i+1, len(arr)):
arsm = sum(arr[i:k])
if arsm >= target:
if rslt[0] == None or rslt[2] > k-i+1 or (rslt[2] == k-i+1 and rslt[0] > arsm):
rslt = (arsm, i, k-i+1)
return arr[rslt[1]:rslt[2]]
Then the call setup:
arr = [10,9,2,1]
target = 11
minlt(arr, target)
Yielding:
[9, 2]
I am trying to find the median of two sorted array of same length for this I am using divide and conquer algorithm. But my code returns None instead of a value
Here is code to find median of single array:
def getmedian(li):
x = len(li)
if x%2 == 0:
return (li[x//2] + li[(x//2)-1])/2
else:
return li[(len(li)-1)//2]
and then I'm using following function for two arrays:
def TwoList(list1,list2):
if len(list1) == 1:
return (list1[0] + list2[0])/2
elif len(list2)== 2:
return (max(list1[0],list2[0]) + min(list2[1], list1[1]))/2
else:
#pdb.set_trace()
x = getmedian(list1)
y = getmedian(list2)
if x == y:
return x
elif x > y:
if len(list1)%2==0:
TwoList(list1[:len(list1)//2], list2[len(list1)//2:])
else:
TwoList(list1[:len(list1)//2+1], list2[len(list1)//2:])
else:
if len(list1)%2==0:
TwoList(list1[len(list1)//2:], list2[:len(list1)//2])
else:
TwoList(list1[len(list1)//2:], list2[:len(list1)//2+1])
Looks like you are doing it right except returning value in TwoList recursive calls.
Please see below code, commented where you have to return value.
def getmedian(li):
x = len(li)
if x%2 == 0:
return (li[x//2] + li[(x//2)-1])/2
else:
return li[(len(li)-1)//2]
def TwoList(list1,list2):
if len(list1) == 1:
return (list1[0] + list2[0])/2
elif len(list2)== 2:
return (max(list1[0],list2[0]) + min(list2[1], list1[1]))/2
else:
#pdb.set_trace()
x = getmedian(list1)
y = getmedian(list2)
if x == y:
return x
elif x > y:
if len(list1)%2==0:
return TwoList(list1[:len(list1)//2], list2[len(list1)//2:]) # return value
else:
return TwoList(list1[:len(list1)//2+1], list2[len(list1)//2:]) # return value
else:
if len(list1)%2==0:
return TwoList(list1[len(list1)//2:], list2[:len(list1)//2]) # return value
else:
return TwoList(list1[len(list1)//2:], list2[:len(list1)//2+1]) # return value
print(TwoList([1,2,3,4],[5,6,7,8]))
I have been coding this problem for HackerRank and I ran into so many problems. The problem is called "Plus Minus" and I am doing it in Python 3. The directions are on https://www.hackerrank.com/challenges/plus-minus/problem. I tried so many things and it says that "there is no response on stdout". I guess a none-type is being returned. Here is the code.:
def plusMinus(arr):
p = 0
neg = 0
z = arr.count(0)
no = 0
for num in range(n):
if arr[num] < 0:
neg+=1
if arr[num] > 0:
p+=1
else:
no += 1
continue
return p/n
The following are the issues:
1) variable n, which represents length of the array, needs to be passed to the function plusMinus
2) No need to maintain the extra variable no, as you have already calculated the zero count. Therefore, we can eliminate the extra else condition.
3) No need to use continue statement, as there is no code after the statement.
4) The function needs to print the values instead of returning.
Have a look at the following code with proper naming of variables for easy understanding:
def plusMinus(arr, n):
positive_count = 0
negative_count = 0
zero_count = arr.count(0)
for num in range(n):
if arr[num] < 0:
negative_count += 1
if arr[num] > 0:
positive_count += 1
print(positive_count/n)
print(negative_count/n)
print(zero_count/n)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr, n)
The 6 decimals at the end are needed too :
Positive_Values = 0
Zeros = 0
Negative_Values = 0
n = int(input())
array = list(map(int,input().split()))
if len(array) != n:
print(f"Error, the list only has {len(array)} numbers out of {n}")
else:
for i in range(0,n):
if array[i] == 0:
Zeros +=1
elif array[i] > 0:
Positive_Values += 1
else:
Negative_Values += 1
Proportion_Positive_Values = Positive_Values / n
Proportion_Of_Zeros = Zeros / n
Proportion_Negative_Values = Negative_Values / n
print('{:.6f}'.format(Proportion_Positive_Values))
print('{:.6f}'.format(Proportion_Negative_Values))
print('{:.6f}'.format(Proportion_Of_Zeros))
# 8-bit-binary adder
#if you have questions about the code just ask
# arrays and funtions
Array1 = []
Array2 = []
#Input A and Validation
def vaildNumberA():
a = int(input("Enter your A value:"))
if (a < 0):
print("Please Enter A Valid Number For Input A")
elif (a > 255):
print("Please Enter A Valid Number For Input A")
else:
Array1 = [int(x) for x in list('{0:08b}'.format(a))]
#Input B and Validation
def vaildNumberB():
b = int(input("Enter your B value:"))
if (b < 0):
print("Please Enter A Valid Number For Input B")
elif (b > 255):
print("Please Enter A Valid Number For Input B")
else:
Array2 = [int(x) for x in list('{0:08b}'.format(b))]
# and gate
# AND Gate
def AND (a,b):
if (a == 1 and b == 1):
return 1
else:
return 0
# or gate
#OR Gate
def OR(a,b):
if (a == 1 or b == 1):
return 1
else:
return 0
# XOR GATEE
#XOR Gate
def XOR (a,b):
if (a == b):
return 0
else:
return 1
#carry formula
def carryformula(a,b,c,d):
return OR(AND(a,b), AND(c,d))
# this is where the calculation should be done
#formula for sum
def calculateSum(Array1,Array2):
carry = ""
sumof = []
for index, in range(len(Array1)):
list2 = Array2[index]
sec_xor_form = XOR(Array1[index],Array2[index])
sumof.append(XOR(sec_xor_form,carry))
carry = carryformula(Array1[index],Array2[index],sec_xor_form,carry)
return list(reversed(sumof))
calculateSum(Array1,Array2)
def main(Array1,Array2):
vaildNumberA()
vaildNumberB()
while True:
a = Array1
b = Array2
total = calculateSum(list(reversed(Array1)),list(reversed(Array2)))
print(total)
quit = input("if want to quit type q: ")
if quit == 'q':
break
main(Array1,Array2)
in the send it prints 0
The only problem in your code is that you need to return Array1 and Array2 from your functions and assign them inside the while true loop, once you do that the code works fine.
The updated code will be
# 8-bit-binary adder
#if you have questions about the code just ask
# arrays and funtions
Array1 = []
Array2 = []
#Input A and Validation
def vaildNumberA():
Array1 = []
a = int(input("Enter your A value:"))
if (a < 0):
print("Please Enter A Valid Number For Input A")
elif (a > 255):
print("Please Enter A Valid Number For Input A")
else:
Array1 = [int(x) for x in list('{0:08b}'.format(a))]
#Return the array
return Array1
#Input B and Validation
def vaildNumberB():
Array2 = []
b = int(input("Enter your B value:"))
if (b < 0):
print("Please Enter A Valid Number For Input B")
elif (b > 255):
print("Please Enter A Valid Number For Input B")
else:
Array2 = [int(x) for x in list('{0:08b}'.format(b))]
#Return the array
return Array2
# AND Gate
def AND (a,b):
if (a == 1 and b == 1):
return 1
else:
return 0
#OR Gate
def OR(a,b):
if (a == 1 or b == 1):
return 1
else:
return 0
#XOR Gate
def XOR (a,b):
if (a == b):
return 0
else:
return 1
#carry formula
def carryformula(a,b,c,d):
return OR(AND(a,b), AND(c,d))
# this is where the calculation should be done
#formula for sum
def calculateSum(Array1,Array2):
carry = ""
sumof = []
for index in range(len(Array1)):
list2 = Array2[index]
sec_xor_form = XOR(Array1[index],Array2[index])
sumof.append(XOR(sec_xor_form,carry))
carry = carryformula(Array1[index],Array2[index],sec_xor_form,carry)
return list(reversed(sumof))
#No need of a main function
while True:
#Call the function from within the while True loop
Array1 = vaildNumberA()
Array2 = vaildNumberB()
total = calculateSum(list(reversed(Array1)),list(reversed(Array2)))
print(total)
quit = input("if want to quit type q: ")
if quit == 'q':
break
And the output will look like
Enter your A value:5
Enter your B value:5
[0, 0, 0, 0, 1, 0, 1, 1]
if want to quit type q: 7
Enter your A value:9
Enter your B value:8
[0, 0, 0, 1, 0, 0, 0, 1]
....