Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to extract what's between parenthesis (including parenthesis) recursively.
This is my solution:
def paren(txt):
if txt[1] == ")":
return ''
if txt[0] == "(":
if len(txt) > 2:
return txt[1] + paren(txt[:1] + txt[2:])
return txt[1]
if len(txt) > 2:
return paren(txt[1:])
return ""
But it doesn't include any parenthesis. How can I fix it?
Example:
print paren("h(ello)o")
Output: (ello)
print paren("(hello)")
Output: (hello)
If you have a single pair of parenthesis, I would recommend to go with Halcyon Abraham Ramirez's answer. Otherwise, try this method:
def paren(text):
pstack = 0
start = 0
end = len(text)
for i, c in enumerate(text):
if c == '(':
if pstack == 0:
start = i
pstack += 1
elif c == ')':
pstack -= 1
if pstack == 0:
end = i
break
return text[start:end]
And here is an example:
>>> paren("h(ello)")
'(ello)'
If you do not need the root parenthesis, you can modify the return statement like this:
return text[start+1:end-1]
And again:
>>> paren("h(ello)")
'ello'
use index
word = "hehlllllllll(ooooo)jejejeje"
def extract(word):
return word[word.index("("):word.index(")") + 1]
output:
(ooooo)
taking it further.
if there are multiple parenthesis:
a = "h((el(l))o"
def extract_multiple_parenthesis(word):
closing_parenthesis = word[::-1].index(")")
last_parenthesis_index = (len(word) - closing_parenthesis)
return word[word.index("("):last_parenthesis_index]
output:
((el(l))
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am given a user entered string 'aaabbbccaa'.
I want to find the duplicates and print the string back as 'a3b3c2a2'
Maybe with this way:
from itertools import groupby
s = "aaabbbccaa"
# group by characters
groups = groupby(s)
# process result
result = "".join([label + str(len(list(group))) for label, group in groups])
print(result)
Output:
a3b3c2a2
def process_string(source):
new = ''
while source:
counter = 0
first_char = source[0]
while source and source[0] == first_char:
counter += 1
source = source[1:]
new += f'{first_char}{counter}'
return new
print(process_string('aaabbbccaa'))
'a3b3c2a2'
this kind of solution could mabye solve it, it does what you specify, however if you are able to put it into your context, no idea :)
hope it helps!
c = 0
foo = "aaabbbccaa"
bar = ""
prev = None
for counter, index in enumerate(foo):
print(c)
if prev == None:
print("first")
elif prev == index:
print("second")
elif prev != index:
c = 0
c += 1
prev = index
try:
if index in foo[counter+1]:
print("third")
else:
print("fourth")
bar += index + str(c)
except:
print("fifth")
bar += index + str(c)
print("foo is {}".format(foo)) # will output aaabbbccaa
print("bar is {}".format(bar)) # will output a3b3c2a2
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
The following function should delete a element in an list if it has an overlap with a first list.
However it only works with the first example(a and b1). With others it does not even send an error message and I have no idea where there problem lies. Can someone point me in the right direction?
def funct(firstone, secondone):
counter = 0
while secondone != [] and counter < len(firstone):
if firstone[counter] in secondone:
del(secondone[secondone.index(firstone[counter])])
counter += 1
return secondone
a = [0, 1, 2]
b1 = [1, 2, 0]
b2 = [-1, 1, 1]
b3 = [0, 0, 2]
print(funct(a, b1))
print(funct(a, b2))
print(funct(b3, a))
i think last line in your code "return" must be in the same level with "while" loop like that
def funct(firstone, secondone ):
counter = 0
while secondone != [] and counter < len(firstone):
if firstone [counter] in secondone :
del(secondone[ secondone .index(firstone[counter ])])
counter += 1
return secondone
You need to continue the for loop when the condition is False otherwise you will always return on the first iteration
while secondone != [] and counter < len(firstone):
if firstone[counter] in secondone :
del(secondone[secondone.index(firstone[counter])])
counter += 1
else:
continue
return secondone
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
def HydrogenCount(Compound):
HydrogenNo = 0
for i in range(0, len(Compound)):
Compound[i] == "H":
print(Compound[i+1])
Temp = Compound[i+1]
Temp = int(Temp)
HydrogenNo = HydrogenNo + Temp
return HydrogenNo
HydrogenNo = HydrogenCount(Compound)
print ("HydrogenCount = ", HydrogenNo)
for an input like CH3CH2CH3 it should output hydrogen count = 8
but instead it outputs hydrogen count = 3 as it stops at the first h
Unindent the return statement. It's currently inside of the for loop and needs to be executed after. Otherwise it will only count the first.
def HydrogenCount(Compound):
HydrogenNo = 0
for i in range(0, len(Compound)):
Compound[i] == "H":
print(Compound[i+1])
Temp = Compound[i+1]
Temp = int(Temp)
HydrogenNo += Temp
return HydrogenNo
What if the H in the molecule has more than 9 atoms, say sugar compound C12H22O11 or glucose C6H12O6?
May I suggest you revamp the code this way:
import re
regex = re.compile('H([0-9]*)')
def HydrogenCount(Compound):
try:
return sum([int(i) for i in regex.findall(Compound)])
except:
return(0)
You may run this as:
print(HydrogenCount("CH3CH2CH3"))
print(HydrogenCount("C6H12O6"))
I still see one more flaw in the question and therefore all answers, which is how about molecules like CH3COOH, where H followed by no number implies 1 atom. So, this is the revised code to handle that too:
import re
regex = re.compile('H([0-9]*)')
def HydrogenCount_v2(Compound):
try:
res = [i if i != '' else '1' for i in regex.findall(Compound)]
return sum([int(i) for i in res])
except:
return(0)
print(HydrogenCount_v2("CH3CH2CH3"))
print(HydrogenCount_v2("C6H12O6"))
print(HydrogenCount_v2("CH3COOH"))
You can refactor your code like this:
def calculate_hydrogen_count(compound):
hydrogen_count = 0
for i in range(0, len(compound) - 1):
if compound[i] == "H":
hydrogen_count += int(compound[i + 1])
return hydrogen_count
compound = "CH3CH2CH3"
hydrogen_count = calculate_hydrogen_count(compound)
print ("HydrogenCount = ", hydrogen_count)
Outputting
8
This question already has answers here:
python return - "name not defined"
(3 answers)
Closed 5 years ago.
I'm writing a program that parses through a text matching a pattern to the text using the BoyerMoore algorithm. I managed to get the code to find all matches, and print out the position of the matches.
Now I also tried to get the length of the match_table and the number of comparisons. I'm quite unfamiliar with python, and the program tells me "NameError: name 'comparison' is not defined, even though it is used in the def boyer_moore.
The program apparently doesn't save the variables for later use. I'm sorry if this sounds confusing, I'm quite new to python. The text that is being matched to can be found here
def make_bad_match_table(pattern):
length = len(pattern)
table = {}
for i, c in enumerate(pattern):
if i == length-1 and not c in table:
table[c] = length
else:
table[c] = length - i - 1
return table
def boyer_moore(pattern, text):
comparison = 0
match_table = []
pattern_length = len(pattern)
text_length = len(text)
if pattern_length > text_length:
return match_table
table = make_bad_match_table(pattern)
index = pattern_length - 1
pattern_index = pattern_length - 1
while index < text_length:
if pattern[pattern_index] == text[index]:
if pattern_index == 0:
match_table.append(index)
pattern_index = pattern_length - 1
index += (pattern_length * 2 - 1)
comparison +=1
else:
pattern_index -= 1
index -= 1
else:
index += table.get(text[index], pattern_length)
pattern_index = pattern_length - 1
return match_table
return comparison
if __name__ == '__main__':
file = open("CNN.txt", "r")
target = file.read()
pattern = "NASA"
print(pattern,boyer_moore(pattern, target))
print(len(match_table))
print(comparison)
1.Firstly instead of
return match_table
return comparison
just do
return (match_table, comparison)
2.Instead of this:
print(pattern,boyer_moore(pattern, target))
print(len(match_table))
print(comparison)
just do:
match_table, comparsion = boyer_moore(pattern, target)
print(pattern)
print(comparison, len(match_table))
Hope it may help you now.
You also can't have a statement after a return statement so you'll have to remove one of the returns at the end of the boyer_moore function.
return match_table
return comparison
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
New in programming and need to find out what will be the following function in python3?
void expand (char s1 [], char s2[])
{
char c;
int i,j;
i=j=0;
while ((c=s1[i++]) != '\0')
if (s1[i] =='-' && s1[i+1] >=c {
i++;
while (c<s1 [i])
s2 [j++] = c++;
}
else
s2 [j++] =c;
s2 [j] = '\0';
}
The direct translation, working on byte objects only, would be:
def expand(s1):
i = 0
s2 = bytearray()
while i < len(s1):
c = s1[i]
i += 1
if (i + 1) < len(s1) and s1[i] == ord(b'-') and s1[i + 1] >= c:
i += 1
while c < s1[i]:
s2.append(c)
c += 1
else:
s2.append(c)
return bytes(s2)
This appears to expand ranges in the form of a-f into abcdef:
>>> expand(b'a-f')
b'abcdef'
You can use regular expressions to do the same:
import re
_range = re.compile(rb'(.)-(.)')
def _range_expand(match):
start, stop = match.group(1)[0], match.group(2)[0] + 1
if start < stop:
return bytes(range(start, stop))
return match.group(0)
def expand(s1):
return _range.sub(_range_expand, s1)
or, for unicode strings (type str) instead:
import re
_range = re.compile(r'(.)-(.)')
def _range_expand(match):
start, stop = ord(match.group(1)), ord(match.group(2)) + 1
if start < stop:
return ''.join([chr(i) for i in range(start, stop)])
return match.group(0)
def expand(s1):
return _range.sub(_range_expand, s1)