I am trying to catch an Index out of range error with the following try and except block.
def getStepList(r, h, d):
x = len(r)-1
y = len(h)-1
list = []
while True:
try:
if x == 0 and y == 0:
break
elif x >= 1 and y >= 1 and d[x][y] == d[x-1][y-1] and r[x-1] == h[y-1]:
x = x - 1
y = y - 1
elif y >= 1 and d[x][y] == d[x][y-1]+1:
#insertion
x = x
y = y - 1
list.append(h[y])
print('insertion')
elif x >= 1 and y >= 1 and d[x][y] == d[x-1][y-1]+1:
#substitution
x = x - 1
y = y - 1
list.append(r[x])
print('substitution')
else:
#deletion
x = x - 1
y = y
list.append(r[x])
print('deletion')
except IndexError:
print('index error')
return list[::-1]
but it gets stuck in a infinite loop. I want it to ignore it and proceed appending the next instances. (For reference its a piece of code that uses a metric of another function to determine which words were inserted, substituted or deleted at each operation).
I feel like I should know this, but in all honesty I am stuck.
Don't do a while True. Change your while condition to:
while(not (x == 0 and y == 0)):
Inside your exception also add a break
except IndexError:
print('index error')
break
You could also add some checks to see what the specific Index Error might be:
d_len = len(d)
r_len = len(r)
h_len = len(h)
d_x_of_y_len = len(d[x][y])
if(x > d_len):
print("x is too big")
if(y > d_x_of_y_len):
print("y is too big")
Related
So I am learning python and there is something that bothers me. For the chunk of sample code below:
print("Test")
while True:
print("statement0")
x = input()
print(x)
if x == 1:
print("statement1")
y += input()
print(y)
elif x == 2:
print("statement2")
y += input()
print(y)
elif x == 3:
print("statement3")
y += input()
print(y)
elif x == 4:
print("statement4")
break
The if statements don't seem to be able to execute. After the value of x is printed it will loop back to statement0.
You have to first specify what will be the data type of the variable x.
Now as you are equating x to integers, you need to add int before the input() function.
Also, you have not initialized the variable y before, so python will throw an error. Define y beforehand with any integer value.
And try to keep the expressions inside parenthesis as it helps in easier understanding.
So, your final code becomes:
print("Test")
while True:
print("statement0")
x = int(input())
print(x)
y = 0 # initialize y with any value
if (x == 1): # edit
print("statement1")
y += int(input())
print(y)
elif (x == 2): # edit
print("statement2")
y += int(input())
print(y)
elif (x == 3): # edit
print("statement3")
y += int(input())
print(y)
elif (x == 4): # edit
print("statement4")
break
While taking the input, use x = int(input())
And, also y is not defined in this case, before doing something like y+=int(input()), you have to declare y above like y = 0
Thank you!
In this code there are four test cases. Three test cases are camed successfully but 4th test case was not getting expected output. Please help me.
I got 0x^3 as output in 4th test case but expected output is 0
Add two polynomials
Given two polynomials A and B, write a program that adds the given two polynomials A and B
Output
Print the addition of polynomials A and B.
If the degree of polynomial is zero and the constant term is also zero, then just print 0 to represent the polynomial.
For term Cix^Pi, if the coefficient of the term Ci is 1, simply print x^Pi instead of 1x^Pi.Explanation
We need all test cases can be came when code was run. I want exact outputs for all test cases
Here is the question and test case inputs and outputs in the below url link
https://drive.google.com/file/d/1DhE2akiG_pX_Q_EoKaEY9EapSgz3xWhY/view?usp=sharing
def check_polinom(polinom):
checked = []
while polinom:
tmp = polinom.pop(0)
if polinom:
for i in range(len(polinom)-1, -1, -1):
if polinom[i][0] == tmp[0]:
tmp[1] += polinom[i][1]
polinom.pop(i)
checked.append(tmp)
return checked
def add_polinoms(pol_1, pol_2):
added = []
while pol_1 or pol_2:
if pol_1:
tmp = pol_1.pop(0)
for i in range(len(pol_2)):
if pol_2[i][0] == tmp[0]:
tmp[1] += pol_2[i][1]
pol_2.pop(i)
break
else:
tmp = pol_2.pop(0)
added.append(tmp)
added.sort(reverse=True)
return(added)
def print_polinom(polinom):
s = ''
if polinom:
if polinom[0][1] < 0:
s += '-'
polinom[0][1] = -polinom[0][1]
if polinom[0][1] == 1:
if polinom[0][0] == 0:
s += str(polinom[0][1])
elif polinom[0][0] == 1:
s += 'x'
else:
s += 'x^' + str(polinom[0][0])
else:
if polinom[0][0] == 1:
s += str(polinom[0][1]) + 'x'
elif polinom[0][0] == 0:
s += str(polinom[0][1])
else:
s += str(polinom[0][1]) + 'x^' + str(polinom[0][0])
polinom.pop(0)
for el in polinom:
if el[1] == 0:
continue
elif el[1] < 0:
s += ' - '
el[1] = -el[1]
else:
s += ' + '
if el[1] == 1:
if el[0] == 0:
s += str(el[1])
elif el[0] == 1:
s += 'x'
else:
s += 'x^' + str(el[0])
else:
if el[0] == 1:
s += str(el[1]) + 'x'
elif el[0] == 0:
s += str(el[1])
else:
s += str(el[1]) + 'x^' + str(el[0])
print(s)
def input_data():
while True:
try:
n = int(input())
break
except:
print('enter an integer N')
continue
a = list()
i = 1
while n > i-1:
try:
tmp = list(map(int,(input()).split()))
if len(tmp) != 2:
print('enter two space separated integers')
continue
a.append(tmp)
i += 1
except:
print('enter two space separated integers')
return a
a = check_polinom(input_data())
b = check_polinom(input_data())
c = add_polinoms(a,b)
print_polinom(c)
It seems that you code does not clean up 0 coefficients. An additional phase should be added to your processing. Once you have the final coefficients of your polinomial, you should have two adjustments. You have already described one, that turns items with coefficient 1 from the form 1x to simply x. Another one is when you turn 0x to nothing. Then you only have to be careful to output something, so you should not turn every term into nothing. That is why there is a description to represent it as 0.
The easiset way to make this work would thus be:
Add a function to check if a polinomial has all zero coefficients: is_zero_polinom
Do something like this in print_polinom:
if is_zero_polinom(polinom):
print('0')
return
<here comes the current code>
Is it possible to use IF with OR to check if one condition applies to 2 or more variables?
I need it like this, but when I put or between them, it doesn't work.
I've tried like this too:
elif x OR y >0: # (for Quadrant II)
My code:
x = int(input()
y = int(input())
if x < 0 and y > 0:
print("Quadrant I")
elif x > 0 OR y > 0:
print("Quadrant II")
else:
print("Quadrant III")
In the Python, 'OR' is to be 'or'
x = int(input())
y = int(input())
if x < 0 and y > 0:
print("Quadrant I")
elif x > 0 or y > 0:
print("Quadrant II")
else:
print("Quadrant III")
you are using OR you should use or.
Also you forgot to put indent in else statement.
I hope this will help
I´ve tried like this and it worked for me.
x = int(input())
y = int(input())
if x < 0 and y > 0:
print("Cuadrant I")
elif x or y > 0:
print("Cuadrant II")
else:
print("Quadrant III")
For my homework I need to make a popty ping application, if you don't know what this is then here is a brief summary:
In popty ping, there are 3 words you can say: 'pop', 'ping' and 'popty ping'. 'Pop' is when a number can be divided into 2. 'Ping' is when a number can be divided into 3, and finally, 'Popty Ping' is when a number can be divided into 2 and 3. Let's say that you get the number 4, it would be 'Pop' since it can be divided into 2. If the number were 6 it would be 'Popty Ping' since it can be divided into 2 and 3.
Here is my code:
!!UPDATED!! The x now increased!!! Could you now give me suggestions on how I can improve the code please? THANK YOU!!!
def endValue():
x = 1
endValue = int(input("Please enter your end value: "))
main(endValue, x)
def main(endValue, x):
print(x)
poptyPingChoice = input("Is this 'ping', 'pop', 'popty ping' or 'nothing'? ")
if poptyPingChoice.lower() == "pop":
pop(endValue, x)
elif poptyPingChoice.lower() == "ping":
ping(endValue, x)
elif poptyPingChoice.lower() == "popty ping":
poptyPing(endValue, x)
elif poptyPingChoice.lower() == "nothing":
nothing(endValue, x)
def pop(endValue, x):
if x % 2 == 0 and x % 3 == 0:
return
else:
if x % 2 == 0:
print("Pop!")
x = x + 1
main(endValue, x)
def ping(endValue, x):
if x % 2 == 0 and x % 3 == 0:
return
else:
if x % 3 == 0:
print("Ping!")
x = x + 1
main(endValue, x)
def poptyPing(endValue, x):
if x % 2 == 0 and x % 3 == 0:
print("Popty Ping!")
x = x + 1
(endValue, x)
def nothing(endValue, x):
x = x + 1
main(endValue, x)
endValue()
Basically, when I type 'nothing' for the number '1', it doesn't add a + 1 to the x. I'm sure there is an obvious answer to this but I also want to know how this can be improved to be more efficient because I just know that someone will cringe at this terrible code XD.
Thank you for your help and I appreciate your opinions and suggestions on how to improve this!
Is there an equivalent of += for a string?
ie:
x = 1
while x <= 100:
y = x
if x % 3 == 0:
y = 'Fizz'
if x % 5 == 0:
y += 'Buzz'
if x % 7 == 0:
y += 'Foo'
if x % 11 == 0:
y += 'Bar'
print y
x += 1
raw_input('Press enter to exit...')
This should return a string and a second string if the same rules as with numbers applied. Is it possible to do this? Because just doing that returns TypeError: unsupported operand type(s) for +=: 'int' and 'str', even though y is a string to begin with, not an int.
If you do this:
You are concatenating a string to string:
x = 'a string'
x += '6'
print x
If you do this:
You concatenate int to string so you get error:
x = 'a string'
x += 6
print x
error:
TypeError: cannot concatenate 'str' and 'int' objects
You have to make sure variable type before doing '+' operation; based on variable type, python can add or concatenate
The following code works for me for Python 2.7.4 and Python 3.0:
a='aaa'
a+='bbb'
print(a)
aaabbb
That would be s1 += s2:
>>> s1 = "a string"
>>> s1 += " and a second string"
>>> s1
'a string and a second string'
>>>
Unlike Perl, Python mostly refuses to perform implicit conversions (the numeric types being the principal exception). To concatenate the string representation of an integer i to a string s, you would have to write
s += str(i)
I don't know, but maybe you are looking for operator
operator.iadd(a, b)¶
operator.__iadd__(a, b)
a = iadd(a, b) is equivalent to a += b.
http://docs.python.org/2/library/operator.html
x = 'a string'
x += ' and a second string'
print x
operator.iadd(x, ' and a third string')
print x
How can I concatenate a string and a number in Python?
I managed to fix it using isinstance()
x = 1
while x <= 100:
y = x
if x % 3 == 0:
y = 'Fizz'
if x % 5 == 0:
if isinstance(y, str):
y += 'Buzz'
else:
y = 'Buzz'
if x % 7 == 0:
if isinstance(y, str):
y += 'Foo'
else:
y = 'Foo'
if x % 11 == 0:
if isinstance(y, str):
y += 'Bar'
else:
y = 'Bar'
print y
x += 1
raw_input('Press enter to exit...')
Please tell me if this particularly bad code (which I have a habit of writing).
x = 1
while x <= 100:
y = str(x)
if x % 3 == 0:
y = 'Fizz'
if x % 5 == 0:
y += 'Buzz'
if x % 7 == 0:
y += 'Foo'
if x % 11 == 0:
y += 'Bar'
print y
x += 1
raw_input('Press enter to exit...')
It's quite simple.
You start off by defining X as an integer, then you increese it in a while loop.
At the very beginning of each iteration you define y = x which essentially tells python to set y into an integer.
Then depending on what x modulus <nr> you got, you add a string to the integer called y (yes, it is an integer as well).. This leads to an error because it's an illegal operation because of the way a INT and a WORD works, they're just different so you need to treat one of them prior to merging them into the same variable.
How to debug your own code: Try doing print(type(x), type(y)) and you get the differences of the two variables.. Might help you wrap your head around this.
The solution is y = str(x).
So, no.. Y is NOT a string to begin with
Because you redefine y each iteration of your while loop.
y = x <-- Makes Y a int, because that's what x is :)
Also, try using .format()
x = 1
while x <= 100:
y = x
if x % 3 == 0:
y = '{0}Fizz'.format(x)
if x % 5 == 0:
y += '{0}Buzz'.format(x)
if x % 7 == 0:
y += '{0}Foo'.format(x)
if x % 11 == 0:
y += '{0}Bar'.format(x)
print y
x += 1
raw_input('Press enter to exit...')
Another personal observation is that if x % 3 == 0 you replace y = ..., but in all other if-cases you append to y, why is this? I left it just the way you gave us the code but either do elif on the rest or why not concade on allif's