i'm working through a hackerrank problem: https://www.hackerrank.com/challenges/kaprekar-numbers/problem
and kept having to deal with this error:
ValueError: invalid literal for int() with base 10: ''
the line 12 of code in mine that churned out error, is in the working code too. So i don't understand why mine didn't work :( please help
this is my code:
a = input()
b = input()
l = []
for i in range(a, b + 1):
s = i*i
s = str(s)
if i == 1:
l.append(i)
length = len(s)
if length <= 1:
pass
temp = int(s[0:length/2]) + int(s[length/2:]) #error came from this line
if temp == i:
l.append(i)
else:
pass
if not l:
print "INVALID RANGE"
else:
print " ".join(map(str, l))
and this is the one that works:
def kaprekar(i):
if i == 1:
return True
s = i ** 2
s = str(s)
length = len(s)
if len(s) <= 1:
return False
temp = int(s[0:length/2]) + int(s[length/2:])
if temp == i:
return True
else:
return False
a = input()
b = input()
l = []
for i in range(a, b + 1):
if kaprekar(i):
l.append(i)
if not l:
print "INVALID RANGE"
else:
print " ".join(map(str, l))
if length <= 1:
pass
pass literally doesn't do anything, so this check doesn't do anything. Whether the length is or isn't <= 1, you're proceeding to int(s[length/2:]), which will produce said error in case the string is too short.
However, return False exits the function and the following code will not execute, so that check protects you from trying to process short strings.
Related
I'm doing a coding challenge and every time I submit I get a the wrong answer with a "No response on stdout" Do you know what I can do? Here is the link to the problem: https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup
def countingValleys(n, s):
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
s = input()
result = countingValleys(n, s)
fptr.write(str(result) + '\n')
fptr.close()
N=int(input())
S = input()
L = 0
V = 0
for el in S:
if s == 'U':
L+= 1
if L == 0:
V += 1
else:
L -= 1
print(V)
You are probably returning the value instead of using the print() function. The problem specification says that you have to print it.
i have a question.
i don't know why my code is wrong
def binary_converter(decimal_number):
i = decimal_number
result = ''
while i >= 0 :
if i % 2 == 0:
result = result + "0"
i = i/2
else :
result = "1"
i = i/2
return result.strip()
it is my code. what is wrong?
There were few little mistakes in your code, olease refer to comments below for details:
def binary_converter(decimal_number):
if decimal_number==0: #corner case
return "0";
i = decimal_number
result = ""
while i>0: # while i >= 0 : //your loop was running indefinitely
if i % 2 == 0:
result = result + "0"
i = i//2 # i= i/2 was doing exact division for eg. 3/2=1.5 but 3//2=1
else :
result = result + "1" # there was a silly mistake here
i = i//2
return result[::-1].strip() # ans should be reversed before converting to integer
I learn about Reverse Polish Notation (:RPN).
I want to calculate Numerical formula by using RPN.
I managed to write following Program.
At a glance, this code work properly.
But, when I submitted this code to Programming Contest Site, (
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0109
) I got Wrong Answer.
What is wrong with my code?
# coding: utf-8
# Convert String to List
def String2List(s):
L = []
flag = True
l = len(s)
for i in range(l):
if s[i].isdigit() and flag:
t = ""
j = 0
while s[i+j].isdigit():
t += s[i+j]
if i+j == l-1:
break
j += 1
L.append(t)
flag = False
elif not s[i].isdigit():
L.append(s[i])
flag = True
return L
# generate Reverse Polish Notation
def RPN_list(L):
S, L2 = [], []
table = {"*": 1, "/": 1, "+": 0, "-": 0, "(": -1, ")": -1}
for i in L:
if i.isdigit():
L2.append(i)
elif i == "(":
S.append(i)
elif i == ")":
while S[-1] != "(":
L2.append(S.pop())
S.pop()
else:
if len(S) != 0 and (table[S[-1]] >= table[i]):
L2.append(S.pop())
S.append(i)
while len(S) != 0:
L2.append(S.pop())
return L2
# calculate Reverse Polish Notation
def RPN_cul(L):
St = []
for i in L:
if i == '+':
St.append(int(St.pop()) + int(St.pop()))
elif i == '-':
St.append(-int(St.pop()) + int(St.pop()))
elif i == '*':
St.append(int(St.pop()) * int(St.pop()))
elif i == '/':
a = int(St.pop())
b = float(St.pop())
St.append(b/a)
else:
St.append(i)
return St[0]
N = int(raw_input())
for i in range(N):
s = raw_input()
L = String2List(s[:-1])
L = RPN_list(L)
print int(RPN_cul(L))
Result
$ python reverse_polish_notation.py
2
4-2*3=
-2
4*(8+4+3)=
60
when I fixed as follows, It was accepted. Thanks to help me.
Before:
def RPN_list(L):
...
if len(S) != 0 and (table[S[-1]] >= table[i]):
L2.append(S.pop())
S.append(i)
...
After:
def RPN_list(L):
...
while len(S) != 0 and (table[S[-1]] >= table[i]):
L2.append(S.pop())
S.append(i)
...
polish_str="123*+4-"
#scan from left to right once you got the operator make the operation save the result again perform the operation
#result=3
polish_list=[]
for i in polish_str:
polish_list.append(i)
print(polish_list)
####
temp=[]
operator=['*',"+","/","-"]
def operation(o,a,b):
if o=="+":
result=a+b
if o=="-":
result=a-b
if o=="*":
result=a*b
if o=="/":
result=a/b
return result
for i,v in enumerate(polish_list):
if v in operator:
print(temp)
leng=len(temp)
arg1=temp.pop()
print("arg1==>",arg1)
arg2=temp.pop()
print("arg2==>",arg2)
result=operation(v,arg1,arg2)
print("result==>",result)
temp.append(result)
print("temp in iteration==>",temp)
else:
temp.append(i)
print("***final temp***",temp)
What I have is a string that looks for example like this {[]}{([])}()and I loop it through to find if it is an open or a close bracket and append it to the list.
What I wanna do now is to find which is the deepest nasting and print it out. So in this example i would print the middle {([ but I am confused how to do it. I can append the beginning of the open brackets and then reset it but how to compare couple of them though, and printing the biggest one
my code:
def is_nested(str):
stack = []
deepest =[]
index=1
open=0
for c in str:
if c == "{" or c == "(" or c == "[" or c =="<":
stack.append(c) # this is push
deepest.append(c)
open +=1
index +=1
elif c == "}":
x = stack.pop()
index +=1
if x != "{":
index -=1
x2=parens(x)
return "False: expected %s at character index %d, but received } instead." %(x2,index)
elif c == "]":
x = stack.pop()
index +=1
if x != "[":
index -=1
x2=parens(x)
return "False: expected %s at character index %d, but received ] instead." %(x2,index)
elif c == ">":
x = stack.pop()
index +=1
if x != "<":
index -=1
x2=parens(x)
return "False: expected %s at character index %d, but received > instead." %(x2,index)
elif c == ")":
x = stack.pop()
index +=1
if x != "(":
index -=1
x2=parens(x)
return "False: expected %s at character index %d, but received ) instead." %(x2,index)
check(str)
return True
def check(str):
deepest =[]
for c in str:
if c == "{" or c == "(" or c == "[" or c =="<":
deepest.append(c)
print deepest
def parens(x):
if x == "<":
return ">"
elif x =="(":
return ")"
elif x == "{":
return "}"
elif x == "[":
return "]"
print is_nested("{[()}")
print is_nested("([)")
print is_nested("{[]({})}")
print is_nested("<()>")
print is_nested("{(<)}")
Not sure if I understand your wishes correctly, but this finds the longest sequence of successive opening brackets:
In [20]: import re
In [21]: s = '{[]}{([])}()'
In [22]: max(re.findall("[\(\[\{]+",s),key=len)
Out[22]: '{(['
You should iterate and update the current number of open brackets and keep the max value that you had while looping. You can put all open brackets on a string that you use as a stack and update max with this string if the lenght is bigger than curren length of max.
OPEN = "<[({"
CLOSED = ">])}"
def is_nested(str):
stack = []
deepest =[]
for c in str:
if c in OPEN:
stack.append(c)
if len(stack)>len(deepest):
deepest.append(c)
elif c in CLOSED:
x = stack.pop()
if OPEN.index(x) != CLOSED.index(c):
return "Error"
return ''.join(deepest)
Something like this?
def is_nested(nested_str):
opening = ['(', '{', '[', '<']
closing = {'(':')','{':'}', '[':']', '<':'>'}
braces = []
depth = 0
max_depth = 0
max_depth_index = None
for index, char in enumerate(nested_str):
if char in opening:
braces.append(char)
depth += 1
elif char == closing[braces[-1]]:
braces.pop()
depth -= 1
else:
raise ValueError("This is not a valid str")
if depth > max_depth:
max_depth = depth
max_depth_index = index
return max_depth, max_depth_index
This function takes a string with only braces, and tells you the deepest level of nesting, and the index of the opening brace of the first instance of that level of nesting. As a bonus, it will raise an error if the string is miss-formed.
>>> is_nested('{[][]}')
(2, 1)
>>> is_nested('{[][<()()>]()}[]()')
(4, 5)
>>> is_nested('{(})')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "nesting.py", line 16, in is_nested
ValueError: This is not a valid str
I've defined any character other than a brace to be an error, but this could easily be changed by modifying the else condition.
def is_nested(in_str):
stack = []
deepest = tuple()
open_b = ('(','[','{','<')
close_b = (')',']','}','>')
for i in in_str:
print stack, i
if i in open_b:
stack.append(i)
if len(stack) > len(deepest):
deepest = tuple(stack)
else:
p = stack.pop()
print p
print open_b.index(p)
print close_b[open_b.index(p)]
if i != close_b[open_b.index(p)]:
raise Exception('Wrongly nested')
if len(stack) > 0:
raise Exception('Wrongly nested')
return deepest
So i wrote this code and it passes the first test case, and fails all the rest. However, I can't seem to find an input that breaks it. Maybe it's because I've been staring at the code too long, but i would appreciate any help.
The algorithm uses two priority queues for the smallest and largest halves of the current list. Here's the code:
#!/bin/python
import heapq
def fix(minset, maxset):
if len(maxset) > len(minset):
item = heapq.heappop(maxset)
heapq.heappush(minset, -item)
elif len(minset) > (len(maxset) + 1):
item = heapq.heappop(minset)
heapq.heappush(maxset, -item)
N = int(raw_input())
s = []
x = []
for i in range(0, N):
tmp = raw_input()
a, b = [xx for xx in tmp.split(' ')]
s.append(a)
x.append(int(b))
minset = []
maxset = []
for i in range(0, N):
wrong = False
if s[i] == "a":
if len(minset) == 0:
heapq.heappush(minset,-x[i])
else:
if x[i] > minset[0]:
heapq.heappush(maxset, x[i])
else:
heapq.heappush(minset, -x[i])
fix(minset, maxset)
elif s[i] == "r":
if -x[i] in minset:
minset.remove(-x[i])
heapq.heapify(minset)
elif x[i] in maxset:
maxset.remove(x[i])
heapq.heapify(maxset)
else:
wrong = True
fix(minset, maxset)
if len(minset) == 0 and len(maxset) == 0:
wrong = True
if wrong == False:
#Calculate median
if len(minset) > len(maxset):
item = - minset[0]
print int(item)
else:
item = ((-float(minset[0])) + float(maxset[0])) / 2
if item.is_integer():
print int(item)
continue
out = str(item)
out.rstrip('0')
print out
else:
print "Wrong!"
Your original was not so legible, so first I made it object-oriented:
MedianHeapq supports methods rebalance(), add(), remove(), size(), median(). We seriously want to hide the members minset,maxset from the client code, for all sorts of sensible reasons: prevent client from swapping them, modifying them etc. If client needs to see them you just write an accessor.
We also added a __str__() method which we will use to debug visually and make your life easier.
Also added legibility changes to avoid the indexing with [i] everywhere, rename s,x arrays to op,val, add prompts on the raw_input(), reject invalid ops at the input stage.
Your actual computation of the median confuses me (when do you want float and when integer? the rstrip('0') is a bit wack), so I rewrote it, change that if you want something else.
A discussion of the algorithm is here.
Now it is legible and self-contained. Also makes it testable.
You might be making sign errors in your code, I don't know, I'll look at that later.
Next we will want to automate it by writing some PyUnit testcases. doctest is also a possibility. TBC.
Ok I think I see a bug in the sloppiness about locating the median. Remember the minset and maxset can have a size mismatch of +/-1. So take more care about precisely where the median is located.
#!/bin/python
import heapq
class MedianHeapq(object):
def __init__(self):
self.minset = []
self.maxset = []
def rebalance(self):
size_imbalance = len(self.maxset) - len(self.minset)
if len(self.maxset) > len(self.minset):
#if size_imbalance > 0:
item = heapq.heappop(self.maxset)
heapq.heappush(self.minset, -item)
#elif size_imbalance < -1:
elif len(self.minset) > (len(self.maxset) + 1):
item = heapq.heappop(self.minset)
heapq.heappush(self.maxset, -item)
def add(self, value, verbose=False):
if len(self.minset) == 0:
heapq.heappush(self.minset,-value)
else:
if value > self.minset[0]:
heapq.heappush(self.maxset, value)
else:
heapq.heappush(self.minset, -value)
self.rebalance()
if verbose: print self.__str__()
return False
def remove(self,value,verbose=False):
wrong = False
if -value in self.minset:
minset.remove(-value)
heapq.heapify(self.minset)
elif value in maxset:
maxset.remove(value)
heapq.heapify(self.maxset)
else:
wrong = True
self.rebalance()
if verbose: print self.__str__()
return wrong
def size(self):
return len(self.minset)+len(self.maxset)
def median(self):
if len(self.minset) > len(self.maxset):
item = - self.minset[0]
return int(item)
else:
item = (-self.minset[0] + self.maxset[0]) / 2.0
# Can't understand the intent of your code here: int, string or float?
if item.is_integer():
return int(item)
# continue # intent???
else:
return item
# The intent of this vv seems to be round floats and return '%.1f' % item ??
#out = str(item)
#out.rstrip('0') # why can't you just int()? or // operator?
#return out
def __str__(self):
return 'Median: %s Minset:%s Maxset:%s' % (self.median(), self.minset,self.maxset)
# Read size and elements from stdin
N = int(raw_input('Size of heap? '))
op = []
val = []
while(len(val)<N):
tmp = raw_input('a/r value : ')
op_, val_ = tmp.split(' ')
if op_ not in ['a','r']: # reject invalid ops
print 'First argument (operation) must be a:Add or r:Remove! '
continue
op.append(op_)
val.append(int(val_))
mhq = MedianHeapq()
for op_,val_ in zip(op,val): # use zip to avoid indexing with [i] everywhere
wrong = False
if op_ == 'a':
wrong = mhq.add(val_)
elif op_ == 'r':
wrong = mhq.remove(val_)
assert (mhq.size()>0), 'Heap has zero size!'
assert (not wrong), 'Heap structure is wrong!'
if not wrong:
print mhq.__str__()