Google Codejam 2020 Qualification Round: Problem 3 [closed] - python

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.

Related

Separating thousands

I have been coding for around half a year in uni and have done some side projects. This is one of them and although my code works for integers, I would like to know how it could be optimised using less lines of code. Coding at uni has taught me how to create many programs but not really how to optimise code and so any further tips would be greatly appreciated! <3
num = int(1230124013502)
def rem(num):
"""
Rem function separates the thousands in an intiger and converts to
a string. Function takes one input (num) which must be of intiger
form. Rem converts to string with commas separating the thousands
"""
num = str(num)
l = len(num)
remain = l%3
sum = ''
if remain == 0:
remain = 3
new = num[remain:]
pre = num[:remain]
#print(pre,new,remain)
l_new = len(new)
zeros = []
for i in range(3,l_new+3,3):
j = i - 3
post = new[j:i] + ','
zeros.append(post)
for i in range(len(zeros)):
sum += zeros[i]
tot = pre + ',' + sum
endpoint = len(tot) - 1
tot = tot[0:endpoint]
if l < 4:
print(num)
return num
else:
print(tot)
return tot
rem(num)

Euclid's division algorithm (to find HCF ) is there a better way? [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
#HCF
#input
C = int(input("the bigger number:" ))
D = int(input("the smaller number:" ))
#division
N = "="
M = "x"
A = "+"
#i don't know if I can add this to the while loop
Q = C//D
S = C%D
print (C,N,D,M,Q,A,S)
E = S
s = D
D = C
#Euclid's division algorithm
while S != 0:
Q = s//E
S = s%E
print(s, N,E, M, Q, A, S)
s = E
if S == 0:
print ("HCF =",E)
else :
E = S
is there a better way of writing this ?
if there is a syntax I am using incorrectly pls tell.
I don't know why I can't post this it's showing your post is mostly code pls explain ignore this last part it's only so this problem goes away.
Here's another way of writing your code
Corrects an error in posted code which provides incorrect results
Uses variables from an algorithm to provide a reference for variable names
Uses string interpolation to show formula
Euclidean Algorithm
Reference
Implementation
a, b, q, r corresponds to a, b, qi, ri in the algorithm
def euclidean_algorithm(a, b):
" Displays iterations of the euclidean algorithm "
if b > a:
# swap if necessary
# to ensure a is the larger number
a, b = b, a
while b:
q = a // b
r = a - q*b
print(f'{a} = {q} x {b} + {r}') # use string interpolation to show formula
a, b = b, r
print(f'HCF = {a}')
return a
Usage
a = int(input('First number: '))
b = int(input('Second number: '))
euclidean_algorithm(a, b)
Output
First number: 498
Second number: 222
498 = 2 x 222 + 54
222 = 4 x 54 + 6
54 = 9 x 6 + 0
HCF = 6

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 display position of an element in an array? [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 4 years ago.
Improve this question
Have an assignment where I must sort a list of names and then display it. Then have the user input one of the names and searches the array and displays the ordered number in the array. I pretty much have everything done but I cannot get that part to work.
If I type in one of the names, it just returns the same name but doesn't give me the ordered number in the index. How can the code be changed so it correctly displays the number of the name that is input into the program?
def main():
SIZE = 10
names = ['Ross Harrison', 'Hannah Beauregard', 'Bob White', 'Ava Fisher', 'Chris Rich', 'Xavier Adams', 'Sasha Ricci', 'Danielle Porter', 'Gordon Pike', 'Matt Hoyle']
searchName = str()
index = int()
selectionSort(names, SIZE)
print('Sorted order:')
for index in range (0, SIZE):
print(names[index])
searchName = input('Enter a name to search for: ')
index = binarySearch(names, searchName, SIZE)
if index != -1:
print('The ordered number of this name is ' + str(names[index]))
else:
print(searchName + 'was not found.')
def selectionSort(array, arraySize):
startScan = int(); minIndex = int(); minValue = int(); index = int()
for startScan in range (0, arraySize - 1):
minIndex = startScan
minValue = array[startScan]
for index in range (startScan + 1, arraySize):
if array[index] < minValue:
minValue = array[index]
minIndex = index
array[minIndex] = array[startScan]
array[startScan] = minValue
def binarySearch(array, value, arraySize):
position = -1
first = 0
last = arraySize - 1
found = False
middle = int()
while not found and first <= last:
middle = int((first + last) / 2)
if array[middle] == value :
found = True
position = middle
elif array[middle] > value:
last = middle - 1
else:
first = middle + 1
return position
main()
I think you have a simple, one-line change.
You get the name instead of the index, because that's exactly what you told it to print. Instead, use this:
print('The index of this name is ', index)
Your original went to the extra trouble to look up the name in that location.

Categories

Resources