Python code for deleting a list is not working [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
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

Related

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

For loop not carrying on till the end [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 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

How to multiply a value each month? [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 4 years ago.
Improve this question
I just started taking classes of python and I am trying to make a code in where the value of the first month = 1 and multiply its value by 2 next month, and then by 3 next month, and 2 next month and so on. Until it reaches 6 months. I am using this code but it only gives me Month 1 = 1 which is the initial value.
P = 1
count = 12
print ("month 1: ",P)
for month in range(count-1):
if month %2 == 0:
P = P*2
else:
P = P*3
print:("month", month+2 ,":",P)
Change
print:("month", month+2 ,":",P)
to
print("month", month+2 ,":",P)
I'm not sure why python didn't complain about the colon. You can actually put anything there
weird: ("month", month+2 ,":",P)
And it won't complain. Awesome mistake, thanks!
Remember that range(count-1) will return numbers between 0 and 11 (the last number is non-inclusive)
Your logic could be like this:
(a) A counter that starts at 1 (cnt)
(b) A loop that watches for the counter to reach 6, then exits
(c) A running total (month_val or some such)
cnt = 1
month_val = 1
while cnt < 7:
month_val = month_val * cnt
print(month_val)
cnt += 1
The above assumes that you retain the new value of month_num -- but re-reading your question, you might just want to print the values 1 to 6, in which case the month_num value should just remain 1 all the time:
cnt = 1
month_val = 1
while cnt < 7:
print(month_val * cnt)
cnt += 1
You can define a dictionary for your problem like
month_values={}
for i in range(1,7):
if i == 1:
month_values['Month'+str(i)]=1
elif i%2 == 0:
month_values['Month'+str(i)]=i*2
elif i%2 == 1:
month_values['Month'+str(i)]=i*3
print(month_values)
prints
{'Month1': 1, 'Month2': 4, 'Month3': 9, 'Month4': 8, 'Month5': 15, 'Month6': 12}

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

Categories

Resources