I'm about a couple weeks into learning Python.
With the guidance of user:' Lost' here on Stackoverflow I was able to figure out how to build a simple decoder program. He suggested a code and I changed a few things but what was important for me was that I understood what was happening. I understand 97% of this code except for the except: i += 1 line in the decode(). As of now the code works, but I want to understand that line.
So basically this code unscrambles an encrypted word based on a specific criteria. You can enter this sample encrypted word to try it out. "0C1gA2uiT3hj3S" the answer should be "CATS"
I tried replacing the except: i += 1 with a Value Error because I have never seen a Try/Except conditional that just had an operational and no Error clause. But replacing it with Value Error created a never ending loop.
My question is what is the purpose of writing the except: i += 1 as it is.
'Lost' if you're there could you answer this question. Sorry, about the old thread
def unscramble(elist):
answer = []
i = 0
while i <= len(elist):
try:
if int(elist[i]) > -1:
i = i + int(elist[i]) + 1
answer.append(elist[i])
except:
i += 1
return "".join(answer)
def boom():
eword = input("paste in your encrypted message here >> ")
elist = list(eword)
answer = unscramble(elist)
print (answer)
clear()
boom()
The purpose is to advance i by one, skipping the current character in case the cast to int fails, i.e. if elist[i] is not a digit.
There are a couple of errors, than can occur inside the try-Block:
i is out of index, because the while loop runs one index to far.
elist[i] is not a number, which leads to an ValueError
i = i + int(elist[i]) + 1 gets to big, and the next index access leads also to an IndexError
In either way, the except-clause will ignore the next character. And the loop goes on.
An correct implementation wouldn't need any exceptions:
def unscramble(elist):
answer = []
i = 0
while i < len(elist):
i += int(elist[i]) + 1
answer.append(elist[i])
i += 1
return "".join(answer)
Related
I am requesting data from an API that returns back end errors occasionally. I have a list of identifiers that I hand to the apifunction by index to retrieve its respective data. The returned dataframe is stored.
x=0
while x <= 13000:
file_checked = Path("path\\%05d.pkl" % (x))
if file_checked.is_file():
print(str(x) + list_of_identifiers[x])
x += 1
else:
identifier = list_of_identifiers[x]
data = apifunction
data.to_pickle("path\\\\%05d.pkl" % (x))
print(str(x) + list_of_identifiers[x])
x += 1
The print command just gives me visual feedback on the progression. Checking if the file exists makes it easier for me to restart the loop as I don't have to set the x manually when my loop breaks.
And this is my big problem. The loop breaks. Occasionally the server returns back end errors of various different types (maybe around three different error codes).
Can someone help me to make this code (or alternative ways) robust to the mentioned errors? It should simply retry the same "x" and afterwards proceed. I should mention that from my experience the errors seem to occur arbitrarily which makes it highly unlikely that one could get stuck in an endless loop of retries.
Although I have found several posts on this topic, I was not able to transfer it to my problem.
Can someone comment on my current solution:
x=0
while x <= 13073:
file_checked = Path("path\\%05d.pkl" % (x))
if file_checked.is_file():
x += 1
else:
while x <= 13073:
try:
identifier = list_of_identifiers[x]
data = apifunction
data.to_pickle("path\\%05d.pkl" % (x))
x += 1
except:
print("Error")
continue
Well, I am still learning python and trying to print letters of alphabet one per line, one per function call. This should be done using recursion.
Here I am struggling due to error. Just need another pair of eyes to see if there is something missing.
def recursive_print(cursor):
alphabet = 'abcdefghijklmnopqstuvwxyz'
index = len(alphabet) - cursor
if index > 0
recursive_print(index - 1)
letter = alphabet[index]
print letter
print recursive_print(0)
Error below:
NameError: name 'index' is not defined
sh-4.3$ python main.py
File "main.py", line 4
if index > 0:
^
Any Pointers will be very helpful.
To solve your immediate problem, you haven't indented properly. You're also missing a colon on the if statement you posted. Try this:
def recursive_print(curser):
alphabet = 'abcdefghijklmnopqstuvwxyz'
index = len(alphabet) - curser
if index > 0:
recursive_print(index - 1)
letter = alphabet[index]
print letter
print recursive_print(0)
Next, you have to worry about is the infinite recursion from not handling your index properly. I believe that the problem is a trivial mental error: change the recursion to
recursive_print(curser + 1)
This still gives you an index out of range on the base case, but I expect you can fix that.
BTW, the word is spelled "cursor", in case you care.
I defined a method, like so:
class MyDatastructure(object):
# init method here
def appending(self, elem):
self.data.append(elem)
if self.count >= self.size:
print "popping " + str(self.data[0])
print "inserting " + str(elem)
self.data.pop(0)
elif self.count < self.size:
self.count += 1
print "count after end of method " + str(self.count)
I tested it out, and it worked as supposed to.
Underneath this definition, I wanted to process some user input and use this method. However, it doesn't enter the if case anymore! Any idea why?
# in the same file
def process_input():
while True:
# getting user input
x = raw_input()
ds = MyDatastructure(x) # creating data structure of size, which was taken from user input, count initially 0
ds.appending(1)
ds.appending(2)
ds.appending(3)
# Still appending and NOT popping, even though the if in appending doesn't allow it!
# This functionality works if I test it without user input!
The problem is with this line:
x = raw_input()
Calling raw_input will return a string. If I type in the number 3, that means that the data structure will assign the string "3" to the size.
Attempting to compare a string to a number is considered undefined behavior, and will do weird things -- see this StackOverflow answer. Note that Python 3 fixes this piece of weirdness -- attempting to compare a string to an int will cause a TypeError exception to occur.
Instead, you want to convert it into an int so you can do your size comparison properly.
x = int(raw_input())
I get a syntax error in the following code:
if value[0] == "ta" or "su":
num_var = len(value)
i = 0
while value[i][0] != "-" and i <= num_var:
if i == 0 and value[0][0].isdigit():
f3["var_%s" %i] = VARFD[[value[0].split("/")[1]]
else:
f3["var_%s" %i] = VARFD[[value[0]]
f4["val_%s" %i] = "T"
i += 1
it claims that the syntax error is on line that starts with "else:". What's wrong with it?
Is your supply of new lines limited or why are you writing code like this?
Your error is here, one ] is missing:
VARFD[[value[0].split("/")[1]]
You're missing a square bracket in the
if i == 0 and value[0][0].isdigit(): f3["var_%s" %i] = VARFD[[value[0].split("/")[1]]
line. But Python code really isn't meant to be this densely written. Space and light!
It's as simple as that you're missing an end bracket on the line before the else.
VARFD[[value[0].split("/")[1]]
I suspect the expression should be
VARFD[value[0].split("/")[1]]
It's pretty much sure sign that you should break apart and simplify your code when errors like this show up :)
I´m experiencing problems with my code.
I can´t get it to append to the list not_found as well as it loops twice for some reason.
Can anyone point me in the right direction? The match works for my_track, but it doesn't when it doesn't match.
# coding: utf-8
#!/usr/bin/env python
import spotimeta
import sys
import time
my_tracks = raw_input("Please enter a sentence: ").title().split()
playlist = []
real_playlist = []
not_found = []
def check_track(track_name, my_track, track_href):
if track_name == my_track:
playlist.append(track_href)
return 1
# make sure the user does not input a single word as input
if (len(my_tracks) > 1):
path = my_tracks[1]
else:
sys.exit("Invalid input, please enter a sentence.")
# let's search
for my_track in my_tracks:
match = 0
print "Searching for '%s'\n" % (my_track),
data = spotimeta.search_track(my_track)
for result in data['result']:
if not match == 1:
try:
match = check_track(result["name"],my_track,result["href"])
except Exception, e:
error = "not available"
else:
if data['total_results'] > 0:
not_found.append(my_track)
You should try debugging it. One of the simplest ways of debugging is add the lines:
import pdb
pdb.set_trace()
Then when you run the script it will stop at the set_trace line in the debugger.
Check out http://docs.python.org/library/pdb.html for more information.
From my understanding you're trying to do something like:
for my_track in my_tracks:
print "Searching for '%s'\n" % (my_track),
data = spotimeta.search_track(my_track)
for result in data['result']:
if result['name'] == my_track:
playlist.append(result['href'])
elif data['total_results'] > 0:
not_found.append(my_track)
Will this more or less work for you?
Please help me to understand.
Right off the bat, I'm noticing two things.
First, you're checking data['total_results'] a bit late; if the total results value is greater than zero (wait, what?), then you want to add it to the list immediately and move on without parsing the data. I would, after the call from spotimeta.search_track(), check to see if this is the data you don't want (then subsequently add it into the list).
Second, I'm confused about the intention of your for loop. If you're going through it to only find one item, then you can use the in statement (my_track in result).