python target string key count invalid syntax - python

Why am i getting an "invalid syntax" when i run below code. Python 2.7
from string import *
def countSubStringMatch(target,key):
counter=0
fsi=0 #fsi=find string index
while fsi<len(target):
fsi=dna.find(key,fsi)
if fsi!=-1:
counter+=1
else:
counter=0
fsi=fsi+1
fsi=fsi+1
#print '%s is %d times in the target string' %(key,counter)
def countSubStringMatch("atgacatgcacaagtatgcat","atgc")

In the line:
def countSubStringMatch("atgacatgcacaagtatgcat","atgc")
You should remove the def. def is used when defining a function, not when calling it.

for string count you could just do:
target = "atgacatgcacaagtatgcat"
s = 'atgc'
print '%s is %d times in the target string' % (s, target.count(s))

Other things wrong with your code:
You don't use and don't need anything in the string module. Don't import from it.
Don't do from somemodule import * unless you have a very good reason for it.
Your code rather slowly and pointlessly struggles on after the first time that find returns -1 ... your loop should include
if fsi == -1: return counter
so that you return immediately with the correct count.
Be consistent: you use counter += 1 but fsi = fsi + 1
... which reminds me: find 'PEP 8' (style guide) at www.python.org, and read it -- your space bar must be feeling unloved ;-)
HTH
John

Related

Python3 print statement prints 0 instead of the actual return value of the function

I am doing AOC 2020 and I am seeing something weird with python3 print statement and I don't understand what's going on.
This question is day 6 part 1 and it is suppose to count a bunch of chars in a file and basically find out how many is counted.
This is my code below, and when I run it on my Pycharm 2020.3 in Win 10 with Python 3.5, these two print statements gives wildly different results:
The print(a) line gives me what I expect, the value returned from process_customs_data.
The print(process_customs_data(customs_data)) gives me 0 which makes no sense shouldn't it print the return value of the function?
and just as an extra test I changed total_count =total_count + a with total_count =total_count + process_customs_data(customs_data) and both scenarios works. I can see my total count updated correctly.
import pprint
from aocd.models import Puzzle
from aocd import submit
import time
def process_customs_data(data):
pprint.pprint(set(data))
return len(set(data))
puzzle = Puzzle(year=2020, day=6)
raw = puzzle.input_data
data = raw.splitlines()
total_count = 0
customs_data = ""
for line in data:
if line == '':
a = process_customs_data(customs_data)
total_count =total_count + a
customs_data = ''
print(a)
print(process_customs_data(customs_data))
time.sleep(5)
else:
customs_data = customs_data + line.strip()
print(total_count)
#submit(total_count, part="a", day=6, year=2020)
You print(process_customs_data(customs_data)) command prints the actual return value of the expression process_customs_data(customs_data).
And if you are wondering, why that's different from a, then just see that you updated function argument customs_data = '' before calling your function.
In your function process_customs_data(data) you create a set that will contain all possible different characters from your string. For the call with the empty data it will be the empty set, so the len of the empty set is 0. And print prints this 0.

Please help me better understand this one "except"conditional line

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)

Run Time Error Exited with error status 1

The problem is this :
I tried to solve it and I think I did too but when I mailed it for evaluation it says
We have tested your solution, and while doing so we unfortunately
discovered the following error:
Run Time Error
Exited with error status 1
Here is my code :
import re
import sys
def fun():
for ind in ratio:
max_num = ratio_list[0]
if ratio[ind] == max_num:
print ind
ratio_list.remove(ratio_list[0])
hits = []
song = []
n,m = raw_input().split(' ',1)
for i in range(0,int(n)):
h,n = raw_input().split(" ",1)
is_number = isinstance( int(h), int )
is_string = len(n)<=30 and bool(re.match('[a-z_0-9]+$', n))
if not(is_number and is_string):
sys.exit("Error");
hits.append(int(h))
song.append(n)
ratio = {}
ratio_list = []
f_of_i = hits[0]
counter = 1
index = 0
for hit in hits:
ratio_list.append(hit*counter)
ratio[song[index]] = hit*counter
index = index +1
counter = counter +1
ratio_list.sort()
ratio_list.reverse()
for j in range(0,int(m)):
fun()
What am I doing wrong ? I am curious why the solution is unacceptable killing me.
I suspect you're hitting
sys.exit("Error");
As explained in the documentation:
Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1.
Might be worth relaxing your input validation a little? Right now it's so strict it would reject inputs that to me appear within the spec (say if there were two spaces between the play count and the song title).
Another possibility is that your code raises an exception. On my machine this also results in an exit code of 1.
Finally, while not a bug, I think the way you reuse the variable called n is questionable style.

Replacement value not working?

So I've got a try/except block set up, which will go through a database dependent on certain conditions:
try:
for searchnumber in itertools.count(0):
print searchnumber
c.execute("""SELECT words from searchterms where onstate = 1 AND progid = %d;""") % searchnumber
searchterms = (c.fetchall())
searchterms = [",".join(x) for x in searchterms]
print searchterms
except:
pass
For some reason, it isn't iterating on progid, in fact, it isn't even getting the first value assigned to it (0). Why would this be? As far as I know, %d should be replaced by the integer value of searchnumber
You're probably hiding a TypeError because you're trying to use the % operator on whatever object or value is equivalent to c.execute("string"). You might've caught it if you hadn't hidden all errors with the bare except. You'll note this is a specific antipattern in the official Python Dos and Don'ts page.
Never use except: pass, it hides information.
The information it's currently hiding is probably a failure from this code:
c.execute("""SELECT words from searchterms where onstate = 1 AND progid = %d;""") % searchnumber

Can't get my loop & match to append to correct list

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).

Categories

Resources