I was assigned in a edx python course to create a program that print out the longest substring that is in alphabetical order from a given string. I have written my code, but when i ran it I got "ERROR: Internal Python error in the inspect module.". I don't understand why. If someone could help me figure it out it would be great. This is the code:
s = 'azcbobobegghakl'
start=0
temp=0
while start<len(s):
initial=start
while True:
if ord(s[start])<=ord(s[start+1]):
start+=1
else:
start+=1
if len(s[initial:start])>temp:
sub=s[initial:start]
temp=len(sub)
break
print sub
and this is the full error:
Traceback (most recent call last):
File "C:\Users\Yoav\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.5.4.3105.win-x86_64\lib\site-packages\IPython\core\ultratb.py", line 776, in structured_traceback
records = _fixed_getinnerframes(etb, context, tb_offset)
File "C:\Users\Yoav\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.5.4.3105.win-x86_64\lib\site-packages\IPython\core\ultratb.py", line 230, in wrapped
return f(*args, **kwargs)
File "C:\Users\Yoav\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.5.4.3105.win-x86_64\lib\site-packages\IPython\core\ultratb.py", line 267, in _fixed_getinnerframes
if rname == '<ipython console>' or rname.endswith('<string>'):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 3: ordinal not in range(128)
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.
Unfortunately, your original traceback can not be constructed.
Thanks!
Looks like the code mostly works, however when you call break, it only breaks out of the else block, and continues to run the while, with a value for start that is greater than the max index for s.
Try putting this code in a function, and using a return when you find the correct substring
Good luck!
def sub_finder(s):
start=0
temp=0
while start<len(s):
initial=start
while True:
if (start < len(s) - 1):
if ord(s[start])<=ord(s[start+1]):
start+=1
else:
start+=1
if len(s[initial:start])>temp:
sub=s[initial:start]
temp=len(sub)
break
else:
start+=1
if len(s[initial:start])>temp:
sub=s[initial:start]
temp=len(sub)
return sub
test = 'abcdaabcdefgaaaaaaaaaaaaaaaaaaaaaaaaaaaabbcdefg'
print sub_finder(test)
whoops, try this on for size.
Related
Let me first start this off by stating that I am a complete beginner to coding and my attempts to fix this have been limited. I am trying to follow this Arduino controlled piano robot. It takes a textified midi file and uses python to translate it into 8-bit. The code is attached near the bottom of the link, I had some formatting issues when placing it here.
This link to the textified midi file used. before running the code I changed the input_file = open to text file path like so,
input_file = open("C:\\Users\\nby20\\Downloads\\megalovania.txt")
After running the code I get a text output file as expected however it is blank and I get a few errors:
Traceback (most recent call last):
File "C:\Users\nby20\Downloads\python_code_for_translation.py", line 184, in <module>
main()
File "C:\Users\nby20\Downloads\python_code_for_translation.py", line 23, in main
result[-1] = str(temp_time) + "," + set_bit_prev(on_off_finder(a), note_finder(a), -1)
File "C:\Users\nby20\Downloads\python_code_for_translation.py", line 178, in on_off_finder
end = in_string.index("ch=") - 1
ValueError: substring not found
Any suggestions on how to fix this would be greatly appreciated.
The Traceback is like debugging information you can use to trace which functions were called when the error was thrown. It seems the error occurred when it was executing this bit of conditional logic, lines 22-23, of the main function:
elif time_finder_comm(result[-1]) == temp_time:
result[-1] = str(temp_time) + "," + set_bit_prev(on_off_finder(a), note_finder(a), -1)
which called the on_off_finder function which just tries to figure out if the line says 'On' or 'Off'.
It seems the file reader only expects lines like this:
55248 Off ch=10 n=40 v=64
However, in the file you uploaded, there also lines like this:
55248 Meta TrkEnd
TrkEnd
The index function throws ValueError: substring not found if the substring passed in does not exist in the string, which in this case (line 178 below) is the string "ch":
end = in_string.index("ch=") - 1
Try removing those kind of lines and re-run the script? Find all lines with "Trk" and and remove them, or make 3 separate files because there seem to be 3 blocks of lines in 'megalovania.txt' that will trip up the script:
(starting at line 2469):
55248 Meta TrkEnd
TrkEnd
MTrk
...
(starting at line 4071):
58368 Meta TrkEnd
TrkEnd
MTrk
...
(starting at line 6431):
55296 Meta TrkEnd
TrkEnd
Why does my program work in PyCharm but in online interpreter gives this error:
Traceback (most recent call last): File "Solution.py", line 4, in
s = input() EOFError: EOF when reading a line
Here's the part of code that matters:
i = 0
while True:
s = input()
if s == '':
break
else:
...
I'm trying to input strings until empty string occurs but it always gets stuck on line with empty string.
Thanks in advance and sorry if I'm sloppy with my question (my 1st question).
Perhaps you can handle there exception with try and except:
while True:
try:
s = input()
...
except EOFError:
break
...
I'm trying to make a text game in python and i'm trying to debug the game right now.
I think this code I'm writing is supposed to type out the letters/characters one by one and make a typing effect.
here it is:
def setup_game():
### BACKSTORY TELLING
backstory = "something something boring backstory"
typeout(backstory)
def typeout(x):
time.sleep(0.03)
sys.stdout.write(char)
sys.stdout.flush()
option = input('> ')
if option.lower() == '> ok':
title_screen()
else:
print("please try again\n")
option = input('> ')
#Actual game
def start_game():
print_location()
main_game_loop()
setup_game()
but whatever i do it always gives me an error and i don't know how to fix it.
here it is:
Traceback (most recent call last):
File "textgame.py", line 612, in <module>
setup_game()
File "textgame.py", line 600, in setup_game
typeout(backstory)
File "textgame.py", line 604, in typeout
sys.stdout.write(char)
NameError: name 'char' is not defined
all the lines referenced in the error are in the code from the top.
I did find another post about the:
time.sleep(0.03)
sys.stdout.write(char)
sys.stdout.flush()
part and i tried doing what the answer said but instead it just gave me a different error which is what i have now.
help would be appreciated, thanks
You need to do something like:
sys.stdout.write(x)
Because char is not defined in your code. You're passing x to the function.
Hi I tried to generate the genesis file but get this error:
C:\Python34>python mk_genesis_block.py --extradata 0x11bbe8db4e347b4e8c937c1c837
0e4b5ed33adb3db69cbdb7a38e1e50b1b82fa > genesis_block.json
File "mk_genesis_block.py", line 293
print json.dumps(evaluate(), indent=4)
^
SyntaxError: invalid syntax
Edit:
Here is the surrounding lines:
if __name__ == '__main__':
print json.dumps(evaluate(), indent=4)
Then it's EOF. The whole file can be viewed here
Since the offending line seems to be only output, I commented it and got another error:
C:\Python34>python -tt mk_genesis_block.py --extradata 0x11bbe8db4e347b4e8c937c1
c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa > genesis_block.json
Traceback (most recent call last):
File "mk_genesis_block.py", line 124, in <module>
EXTRADATA = (d[2:] if d[:2] == '0x' else d).decode('hex')
AttributeError: 'str' object has no attribute 'decode'
which in conjunction with the other error makes me wonder whether a string instead of a json object is being operated on? Here is the whole arg parsing part:
# Grab the extra data command line argument
if '--extradata' in sys.argv:
d = (sys.argv+[None])[sys.argv.index('--extradata') + 1]
EXTRADATA = (d[2:] if d[:2] == '0x' else d).decode('hex')
else:
EXTRADATA = ''
I also made a test file importing the json package, dumps and decode methods work.
print in python3 is a method not a statement print( "text" ) ... also I believe str.decode was remove in python3 ... instead use codecs.decode(my_str,encoding)
I'm trying to find the cause of a crash in of our python scripts.
The main structure is this:
def main()
try:
dostuff
except Exception as ex:
import traceback
tb = traceback.format_exc()
import platform
node = platform.node()
sendMail([DEBUG_EMAIL], "Alarm exception on %s" % node, str(tb), [])
I get this stacktrace in our main error handling, not in an error email which I'm supposed to.
Traceback (most recent call last):
File "/usr/lib/python2.6/logging/__init__.py", line 799, in emit
stream.write(fs % msg.encode("UTF-8"))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 66: ordinal not in range(128)
From what I see all of the write-calls to logger are inside the try-block, but since it's not caught and handled in my email sending exception block it seems I've missed something. I've checked and the sendMail function doesn't use the logging module at all. So the exception shouldn't originate in my except-block.
I tried adding
sys.tracebacklimit = 10
at the top of the file see where the exception originates but that didn't affect anything. And now I'm out of ideas on how to find where the problem originates.
The script runs once every hour and only crashes about once per week, which makes me assume that it's something related to the input data, but that's only handled by dostuff().
UPDATE:
I've figured out why I only get one row of the stacktrace. Inside the emit() I found this.
try:
... doing stuff, something goes boom with encoding...
except UnicodeError:
stream.write(fs % msg.encode("UTF-8")) Here it goes Boom again
self.flush()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record) Which means it ends up here
And the relevant part of the handleError function looks like this:
ei = sys.exc_info()
try:
traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr)
Which only prints the last part of the stacktrace.
Basically your problem is twofold
One log stream does not accept 8-bit strings with extended characters, and throws UnicodeError
There is a silly bug in logging module which make it lose the original traceback
The exact cause of the exception is this:
>>> 'ä'.encode('UTF-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
But this exception is not the real problem. This is the part of the 2.6 logging code; the 799 is the last line of the block. The last line is the one causing the problems. Basically something logs a message in a 8-bit byte string, UTF-8 encoded, containing Latin-1 extended letters; but the stream does not like that, and throws an UnicodeError within the try block;
try:
if (isinstance(msg, unicode) and
getattr(stream, 'encoding', None)):
# .... the string is NOT an unicode instance, so ignored
# for brevity
else:
# this line throws the original exception
# fs is a bytestring "%s\n", and msg is a bytestring
# with extended letters, most probably Latin 1.
# stream.write spits out an UnicodeError on these values
stream.write(fs % msg)
except UnicodeError:
# now we get a useless exception report from this code
stream.write(fs % msg.encode("UTF-8"))
So to debug this you'd want to set up a breakpoint on the aforementioned line 799, and try all loggers if they accept the following string:
logging.getLogger(name).critical('Testing logger: ä')
If you hit line 799 then get the backtrace of the exception, it can shed some light on what is happening...