For loop not carrying on till the end [closed] - python

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

Related

Extract n first consecutive numbers from a string in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Let's consider this string :
st = 'text1text6253text'
How could I please extract the two first consecutive figures ?
Expected output :
62
You can either use regex with \d{2}and return that, or go over the string:
st = 'text1text6253text'
for i in range(len(st)-1):
if st[i].isdigit() and st[i+1].isdigit():
print(st[i]+st[i+1])
break
import re
def find_con(n, s):
result = re.search('\d{%s}'%n, s)
return result.group(0) if result else result
st = 'text1text6253text'
print(find_con(2, st))
st = 'text1text6253text'
lst = list(st)
lst2 = []
for i,v in enumerate(lst):
if lst[i].isdigit() and lst[i+1].isdigit():
lst2.append(lst[i])
lst2.append(lst[i+1])
ans = int(lst2[0] + lst2[1])
print(ans)
Thanks to your answers, I built a general function that I propose you below :
def extract_n_consecutive_numbers(st,nb):
for i in range(len(st)-nb+1):
is_numeric = True
for j in range(nb):
is_numeric = is_numeric & st[i+j].isdigit()
if is_numeric :
output = ""
for j in range(nb):
output += st[i+j]
return output
return ""
Example :
extract_n_consecutive_numbers('text1text6253text',2)
Out[1]: 62

Google Codejam 2020 Qualification Round: Problem 3 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
This is for the Third Problem on Google's Codejam Qualification Round 2020
The Judging System says this solution gives a wrong answer, but I could not figure out why. Any insights would be much appreciated.
num_test_cases = int(input())
def notOverlap(activity, arr):
# returns true if we have no overlapping activity in arr
for act in arr:
if not (act[0] >= activity[1] or act[1] <= activity[0]):
return False
return True
def decide(act, num_act):
C, J = [], []
result = [None]*num_act
for i in range(num_act):
if notOverlap(act[i], C):
C.append(act[i])
result[i] = "C"
elif notOverlap(act[i], J):
J.append(act[i])
result[i] = "J"
else:
return "IMPOSSIBLE"
return "".join(result)
for i in range(num_test_cases):
num_act = int(input())
act = []
for _ in range(num_act):
act.append(list(map(int, input().split())))
print("Case #" + str(i+1) + ": " + decide(act, num_act))
You implemented a brute force way to solve it. Your code runs slow, Time complexity O(N^2), but you can do it in O(N*log(N))
Instead of check with notOverlap(activity, arr), sort the array and check with the last ending time activity of C or J. ( Greedy Way to solve it )
You have to store the index of activity before sorting the array.
Here is my solution, but before reading the solution try to implement it yourself
for testcasei in range(1, 1 + int(input())):
n = int(input())
acts = []
for index in range(n):
start, end = map(int, input().split())
acts.append((start, end, index)) # store also the index
acts.sort(reverse=True) # sort by starting time reversed
# so the first activity go to the last
d = ['']*n # construct the array for the answer
cnow = jnow = 0 # next time C or J are available
impossible = False # not impossible for now
while acts: # while there is an activity
start_time, end_time, index = acts.pop()
if cnow <= start_time: # C is available to do the activity
cnow = end_time
d[index] = 'C'
elif jnow <= start_time:
jnow = end_time
d[index] = 'J'
else: # both are'nt available
impossible = True
break
if impossible:
d = 'IMPOSSIBLE'
else:
d = ''.join(d) # convert the array to string
print("Case #%d: %s" % (testcasei, d))
I hope you find this informative and helped you to understand, and keep the hard work.

How can I print the string "aaabbbccaa" as a3b3c2a2 [closed]

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

Basic Python - Extracting Strings [closed]

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

is there possible to resolve this star pyramid [closed]

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 8 years ago.
Improve this question
Today, i have trying to resolve a small star pyramid :
Input:
5 1
Output:
*
**
***
****
Code:
x = 1
y = 0
m, e = map(int, raw_input().split())
while x < m:
print "\n" * y, "*" * e
m -= 1
e += 1
I did that but there is a better solution?? Thanks =)
I think this can be solved more easily:
stop, first = map(int, raw_input().split())
for i in range(stop - 1):
print '*' * (i + first)
just for fun >:)
class c:
def __init__(s,m,e):
s.e , s.m = sorted([e, m])
s.r = 42
def __iter__(s):
return s
def next(s):
if s.m < s.e:
t = "".join(chr(s.r) for _ in range(s.m))
s.m += 1
return t
else:
raise StopIteration
print "\n".join(c(*map(int,raw_input().split())))
n = int(raw_input())
for i in range(n): print "*"*i
This appears to do what your program intends to do, however I can't quite tell because of the issues I raised in my comment above.

Categories

Resources