def main():
get_value =get_display_info('5 6 0','7 0 0 0 5')
print(get_value)
def get_display_info(dice_to_roll_again_str, dice_set_aside_str):
length1 =len(dice_to_roll_again_str)
d = dice_set_aside_str
if dice_set_aside_str == None:
return 0
else :
return len(dice_set_aside_str)
if length1 and dice_set_aside_str > 0:
return "(Dice to roll again:" + str(dice_to_roll_again_str) +','+
"Dice set aside:" + str(d) + ')'
elif length1 > 0:
return "(Dice to roll again:" + str(dice_to_roll_again_str) + ')'
elif dice_set_aside_str > 0:
return "(Dice set aside:" + str(d) + ')'
Why does my program stop executing upon reaching this statement?
if length1 and dice_set_aside_str > 0:
Your code will return unconditionally after this block:
def get_display_info(dice_to_roll_again_str, dice_set_aside_str):
length1 =len(dice_to_roll_again_str)
d = dice_set_aside_str
if dice_set_aside_str == None:
return 0
else :
return len(dice_set_aside_str)
Hello Adrian,
Solution
Try this below code,
def main():
get_value =get_display_info('5 6 0','7 0 0 0 5')
print "Value : ",get_value
def get_display_info(dice_to_roll_again_str, dice_set_aside_str):
length1 = len(dice_to_roll_again_str)
d = dice_set_aside_str
if dice_set_aside_str == "":
return 0
else :
return len(dice_set_aside_str)
if length1 and dice_set_aside_str > 0:
return "(Dice to roll again:{}".format(str(dice_to_roll_again_str))+",Dice set aside:{}".format(str(dice_set_aside_str))+")"
elif length1 > 0:
return "(Dice to roll again:{}".format(str(dice_to_roll_again_str))+")"
elif dice_set_aside_str > 0:
return "Dice set aside:{}".format(str(dice_set_aside_str))+")"
# Call the main() function
main()
# Call and Print get_display_info() function.
print "Display information : ",get_display_info("mayur","vora")
I hope my answer is helpful.
If any query so comment please.
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
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))
I tried to add some time.sleep(.1) to a loop I'm using, but it seems to stuck the execution (after hitting CTRL+C on my IDLE I get time.sleep(.1)... KeyboardInterrupt which confirms my thoughts)
I tried playing with the code, and found that adding a print() after that line prevents the pause, but I still don't understand why it happened in the first place...
I have no problems whatsoever running this without the sleep, so I think there are no other problems that can cause that. Another thing that worked for me is using sleep(0). Any positive value I entered stuck the execution again.
The suspicious line is at the end of the loop.
This is the whole code:
import time
def main():
with open(r'txt.bin') as f:
code = f.read()
data = [0 for i in range(22)]
data_p = 0
code_p = 0
reverse_code = code[::-1]
l = len(code)
flag = False
while code[code_p] != '.':
if data_p == 1:
#print('char read {0} {1}: {2}'.format(c, data_p,data[1]))
pass
c = code[code_p]
if c == '+':
data[data_p] += 1
data[data_p] %= 256
elif c == '-':
data[data_p] -= 1
if data[data_p] < 0:
data[data_p] = 255
elif c == '>':
data_p += 1
elif c == '<':
data_p -= 1
elif c == ',':
old = int(data[data_p])
data[data_p] = int(input('enter value at {0} (current value is {1}): '.format(data_p, data[data_p])))
print('replaced {0} with {1} at {2}'.format(old, data[data_p],data_p))
flag = True
elif c == '[':
if data[data_p] is 0:
old = int(code_p)
code_p = code.find(']', code_p)
print('started at loc {0} with val {1}\nnow at loc {2} with val {3}'.format(old, code[old], code_p, code[code_p]))
elif c == ']':
if data[data_p] is not 0:
reverse_code_p = l-1-code_p
old = int(code_p)
code_p = l-1-reverse_code.find('[', reverse_code_p)
print('started at loc {0} with val {1}\nnow at loc {2} with val {3}'.format(old, code[old], code_p, code[code_p]))
if flag:
time.sleep(1)
code_p += 1
print(data[data_p])
main()
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")
so I am trying to solve the next problem from UVa Online Judge: https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1415
I've written a program in Python3. My problem is that I keep getting "Wrong Answer" when I submit my program. I have checked it a million times with different inputs, including the one from uDebug. I get the exact same output as expected in every case. It is very frustrating because I think it may be a format error, since I know the judge is very picky. However, I can't find the problem with my code. I would appreciate if someone could help. My code:
import math
#Binary_search (recursive)
def binary_search(the_array, the_key, imin, imax):
if (imax < imin):
return None
else:
imid = imin + ((imax - imin) / 2)
imid = math.floor(imid)
if the_array[imid] > the_key:
return binary_search(the_array, the_key, imin, imid-1)
elif the_array[imid] < the_key:
return binary_search(the_array, the_key, imid+1, imax)
else:
return imid
#problem solution
case = 1
while True:
canicas = [ ]
queries = [ ]
N, Q = input().split(' ')
N = int(N)
Q= int(Q)
if(N == 0 and Q == 0):
break
else:
for i in range(N):
x = int(input())
canicas.append(x)
for j in range(Q):
x = int(input())
queries.append(x)
canicas.sort()
print ("CASE# %d:" % case)
for q in queries:
pos = binary_search(canicas, q, 0, N-1)
if(pos != None):
if(pos == 0):
print("%d found at 1" % q)
break
if(canicas[pos-1] == q):
print("%d found at %d" % (q, pos))
else:
print("%d found at %d" % (q, pos+1))
else:
print("%d not found" % q)
case += 1