Round G - Kick Start 2020 Problem Kick_Start Wrong Answer - python

Problem:
Ksenia is very fond of reading so she kicks off each day by reading a
fragment from her favourite book before starting with the rest of her
morning routine. A fragment is simply a substring of the text. Ksenia
is somewhat superstitious and believes that her day will be lucky if
the fragment she reads starts with the string KICK, then goes on with
0 or more characters, and eventually ends with the string START, even
if the overall fragment makes little sense.
Given the text of the book, count the number of different lucky
fragments that Ksenia can read before the book gets old and she needs
to buy another one. Two fragments are considered to be different if
they start or end at different positions in the text, even if the
fragments read the same. Also note that different lucky fragments may
overlap.
Input:
The first line of the input gives the number of test cases T. T lines
follow, each containing a single string S consisting of upper case
English letters only.
Output:
For each test case, output one line containing Case #x: y, where x is
the test case number (starting from 1) and y is the number of
different lucky fragments in the text of this test case.
Limits:
Memory limit: 1 GB. 1 ≤ T ≤ 100. S consists of upper-case English
letters only.
Test Set 1:
Time limit: 20 seconds.
1 ≤ |S| ≤ 1000.
Test Set 2:
Time limit: 40 seconds.
1 ≤ |S| ≤ 105.
Sample:
Input
3
AKICKSTARTPROBLEMNAMEDKICKSTART
STARTUNLUCKYKICK
KICKXKICKXSTARTXKICKXSTART
Output
Case #1: 3
Case #2: 0
Case #3: 5
I tried solving it using Python. The logic I tried using is to find indices for substring 'KICK' and substring 'START' and find number of START appearing after every 'KICK'.
I'm getting wrong answer I don't understand what edge cases I'm missing.
Here is the code:
import re
t = int(input())
for i in range(t):
text = input()
matches = 0
temp1 = [m.start() for m in re.finditer('KICK',text)]
temp2 = [m.start() for m in re.finditer('START',text)]
if len(temp1) == 0 or len(temp2) == 0:
matches = 0
else:
for ele in temp1:
for x in temp2:
if(x > ele):
matches = matches + 1
print("Case "+"#"+str(i+1)+": "+str(matches))

Finally I found the cases the code misses.
re.finditer() can only count non-overlapping matches and hence strings like 'KICKICK' would result in counting KICK only for 1 time rather than 2.
re.finditer(pattern, string, flags=0)
Return an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in string.The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result.

Here is my code:
t = int(input())
for x in range(t):
s = input()
ans = 0
k = 0
for i in range(len(s)-4):
if s[i:i+4] == "KICK":
k += 1
if s[i:i+5] == "START" and k != 0:
ans += k
print("Case #{}: {}".format(x+1, ans))
You are not considering all the possibilities. The code just shows how many time the KICK and START occurs

I Hope this works.
T=int(input())
for x in range(1, T + 1):
P=input()
c=0
for i in range(0,len(P)-4+1):
if (P[i:i+4]=="KICK"):
for j in range(i+4,len(P)-5+1):
if (P[j:j+5]=="START"):
c=c+1
print("Case #{}: {}".format(x, c), flush = True)

Related

Remove string character after run of n characters in string

Suppose you have a given string and an integer, n. Every time a character appears in the string more than n times in a row, you want to remove some of the characters so that it only appears n times in a row. For example, for the case n = 2, we would want the string 'aaabccdddd' to become 'aabccdd'. I have written this crude function that compiles without errors but doesn't quite get me what I want:
def strcut(string, n):
for i in range(len(string)):
for j in range(n):
if i + j < len(string)-(n-1):
if string[i] == string[i+j]:
beg = string[:i]
ends = string[i+1:]
string = beg + ends
print(string)
These are the outputs for strcut('aaabccdddd', n):
n
output
expected
1
'abcdd'
'abcd'
2
'acdd'
'aabccdd'
3
'acddd'
'aaabccddd'
I am new to python but I am pretty sure that my error is in line 3, 4 or 5 of my function. Does anyone have any suggestions or know of any methods that would make this easier?
This may not answer why your code does not work, but here's an alternate solution using regex:
import re
def strcut(string, n):
return re.sub(fr"(.)\1{{{n-1},}}", r"\1"*n, string)
How it works: First, the pattern formatted is "(.)\1{n-1,}". If n=3 then the pattern becomes "(.)\1{2,}"
(.) is a capture group that matches any single character
\1 matches the first capture group
{2,} matches the previous token 2 or more times
The replacement string is the first capture group repeated n times
For example: str = "aaaab" and n = 3. The first "a" is the capture group (.). The next 3 "aaa" matches \1{2,} - in this example a{2,}. So the whole thing matches "a" + "aaa" = "aaaa". That is replaced with "aaa".
regex101 can explain it better than me.
you can implement a stack data structure.
Idea is you add new character in stack, check if it is same as previous one or not in stack and yes then increase counter and check if counter is in limit or not if yes then add it into stack else not. if new character is not same as previous one then add that character in stack and set counter to 1
# your code goes here
def func(string, n):
stack = []
counter = None
for i in string:
if not stack:
counter = 1
stack.append(i)
elif stack[-1]==i:
if counter+1<=n:
stack.append(i)
counter+=1
elif stack[-1]!=i:
stack.append(i)
counter = 1
return ''.join(stack)
print(func('aaabbcdaaacccdsdsccddssse', 2)=='aabbcdaaccdsdsccddsse')
print(func('aaabccdddd',1 )=='abcd')
print(func('aaabccdddd',2 )=='aabccdd')
print(func('aaabccdddd',3 )=='aaabccddd')
output
True
True
True
True
The method I would use is creating a new empty string at the start of the function and then everytime you exceed the number of characters in the input string you just not insert them in the output string, this is computationally efficient because it is O(n) :
def strcut(string,n) :
new_string = ""
first_c, s = string[0], 0
for c in string :
if c != first_c :
first_c, s= c, 0
s += 1
if s > n : continue
else : new_string += c
return new_string
print(strcut("aabcaaabbba",2)) # output : #aabcaabba
Simply, to anwer the question
appears in the string more than n times in a row
the following code is small and simple, and will work fine :-)
def strcut(string: str, n: int) -> str:
tmp = "*" * (n+1)
for char in string:
if tmp[len(tmp) - n:] != char * n:
tmp += char
print(tmp[n+1:])
strcut("aaabccdddd", 1)
strcut("aaabccdddd", 2)
strcut("aaabccdddd", 3)
Output:
abcd
aabccdd
aaabccddd
Notes:
The character "*" in the line tmp = "*"*n+string[0:1] can be any character that is not in the string, it's just a placeholder to handle the start case when there are no characters.
The print(tmp[n:]) line simply removes the "*" characters added in the beginning.
You don't need nested loops. Keep track of the current character and its count. include characters when the count is less or equal to n, reset the current character and count when it changes.
def strcut(s,n):
result = '' # resulting string
char,count = '',0 # initial character and count
for c in s: # only loop once on the characters
if c == char: count += 1 # increase count
else: char,count = c,1 # reset character/count
if count<=n: result += c # include character if count is ok
return result
Just to give some ideas, this is a different approach. I didn't like how n was iterating each time even if I was on i=3 and n=2, I still jump to i=4 even though I already checked that character while going through n. And since you are checking the next n characters in the string, you method doesn't fit with keeping the strings in order. Here is a rough method that I find easier to read.
def strcut(string, n):
for i in range(len(string)-1,0,-1): # I go backwards assuming you want to keep the front characters
if string.count(string[i]) > n:
string = remove(string,i)
print(string)
def remove(string, i):
if i > len(string):
return string[:i]
return string[:i] + string[i+1:]
strcut('aaabccdddd',2)

how to reset counter when looking for a sequence of strings properly

so i am doing the cs50 dna problem and i am having a hard time with the counter as i don't know how to code to properly count the highest amount of times the sequence i am looking for has repeated without another sequence in between the two. for example i am looking for the sequence AAT and the text is AATDHDHDTKSDHAATAAT so the highest amount should be two as the last two sequence is AAT and there is no sequence between them.
here is my code:
text="TCTAGTCTAGTCTAGTCTAGTCTAGACTTGTCGCTGACTCCGAGAAGATCCTAACATTAACCAATTCCCCCTAGTCTGAGGCACGGTTACCGATCGGGTTAATGGATCTCTCACCGTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAAACGTGTAACTGTAATAATCCGCCCGAAAAAACTGATCTTAGGGTTGCGGCATCTGCACGTGACAGTGTGCTACTGTTAGATAGAGGGATCAAACGAGGTTGCAAGGATTATATCTCTCCGTGCTCGATAAGACACAGCCGGTTGCGGGCTGCTTCCTCTGGATCCAATGCAGCCGTACGTACACCGTAGAGCAAATTTAGTGGTAAAGGAACTTGCTCAAACACTACGGCTTCGGGCTACTGTTGGCGCCGGTTGGGGATCCCATTCAACGCTGGCCCTTTCGCTATGGTTCGGTGATTTTACACCGAAGCGAACCTTGAACCGTGGATTTCGGGTGTCCTCCGTTTTTAGGTACTGCGTGCAGACATGGGCACCTGCCATAGTGCGATCAGCCAGAATCCATTGTATGGGAGTTGGACTCGTTTGAATTTACCGGAAACCTCATGCTTGGTCTGTAGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGAAACTGGGCGACTTGAAGTCGGCTTGCGTATTAATAGCTCTGCAATGTAACTCGGCCCTTGGCGGCGGGCAGCTTAGTATTGAACCGCGACACACCATAGGTGCGGCAAATATTAAAAGTACGCTCGAACCGGAACCTGTCTCCATGACTGGACGACCAGCCCGGCGTCTTCTACGTAACACAGGGGGCTGTCGAGGTAGGGCGTAGGAACTTCGGGGTCACTACGCCGTAACAGCACCGAATATCATATCATCCAACTTGCTTGGTACATGCCCCGTTCTGTATCAAAAGTTTACGGCCCCGGACATACCTGCTGTCAGTTGAATACCTATGCGAGTCTGAAACACGAATAGTTCAGGCGTGCAAAGACACGCTAAGCACACGCCGCAGGCAGGGGGGGTATTTTATAAGTCGTTTTTTGGAAGGGTAATGTAAACTTATCCCATAATACCCTTTGGCTTCCCCTCACTCGTGCACTTCTCATAATGATACGTCAGGGTGATTGTAGATTCACGCGTCATCAGATTGTCCCTTTCTCGAGTCTTAGTATCTTTCCTAATCCGCTCGACTCTGCGCCATGATCGAATTCCTGACAGGCTACAAGAATAAACTGCCAGCATACTCCTTACCGATTGGCGCCTACTAATTATACGCACATGGGCATCTTCGACGTCTAAACATAGGCTCTTAGTATTCCGTAGGATGTTGAGCCGACAGGAAAGTCAAACGTCGTGGGTGACCGTAGCCTGACTCGCCCGACGCAGGATTCGCTCATATGTGTGAACGGATGCTTATGTAACTTCCTAATTGCAGCGAATGGCAGTTCCGTAGTGAAGGTTCGAAACGTACGGGGTCCGGCCATGGATTAGATCTTTCAGTGCGCTAAACTCTTAACCGCAGATACTTGGCGGACCATCTTCGTGTTGCTACTATGGTATAGACCAGGCTGTCGAATCTACTTAACACAGGTGAACCCCCAGATCGGCTAGAGCCTTCGAGGCTAGACCTTTAACAATCTTTAGACACTTCCAAATCGCGGCCGGATATGTCTCGTTGGCAGCCGCAGACAAGAGAAGAGGGTCGGCAGTGTCTGCCACGCGTGACCTGTATGATCTTAGCCTTTAAGATCACACTACTGATCACAATCTATTATGATTGCCTTAGCTAACTGAGTGATGCACCCCCACAGGCTGAGAGAAATCTGTAGTTTGACGACACGCCGTCTGGCTAAAAATGTGAATCCGCCGATCCGAGACGGTGGAAGCTTGAGACCAAATGCGGGAAACCAATGACTTCATTACGGAACAAGACATAACGGCGTGAGTTGACGACTGGGATTAACCCTTTCCCGAGTCTGTACTTCTGCTACACAATGAGGATGCGAATTATCTAAGACCTTGTACTACCTAAACTAACCCTGAGGCGGGCATTGAATTCCGGCCATCTTCAGCCCAAAGAAAGACCAAATGTGAGGAAAATGAGGGATCGGTATAAGCTTTTCACGATCTCAAGGTTCACGGCCGCCAGGGCCGTAGTTGGGGCTTCATGCACATTGCCAACCCGGACATCGACAGTCGGTACCGCAGGGGTTCGAGGAATACTCCCAGCTGTGACACCTGGTCGTCGACTGGACCCAGCTGGTGGGCGGCATAGGTAGTTAATACTGAATTAAAGCCGGGAACGTCTCTCTAACTAGAAACCTTGTGATAGGATACACAGACCTAGTGCCCCGACGTTAGCATTTGAATTCATCTATCTTGGCGTCTTTTAGTAGGCCTGGGTCAACTCCGGCGTTGGCCAAAATAACCGATCTGCGTTATGTGGCCACGCATCGAGTGACAGGGTGCATACAAATTGATGGTCAAAGAGTTTAAACAAGACAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCCCCACGCTTCTACATAGCCACACTGGAGCTAGTCCTCGTGTTAAATTTTTCGCTTGTTGCACGGTTATCATCAGAAGTGCCACTGGTATTCCTCTGTAGCTCCCGTATGCCGAAGGTTGCGGCTTAGGTACTGCTTATACACGTCTCTCAAGTTTGTCAGCCGCGTGATCTTTCTGCGGGGATAGGTGATCGTCCCTCGCTCCGGACATTGCATTAAAATTACCTAGTTGATAGGGCGGCGGAGTTGCATACCGGCGTTCAATCGCGGCTCCAGACTGGTTTGAGCTACGCGTCTGCCAGCGTGAAAAAGCTGATTTGTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCCAGGTATTATCATTTGAATCGTATGTTTTCTGCCGTACGTCAACTGCGTCGTCGGGGACTGAAATGGTCTGCCTCCAGACCCTTACCTCCCGATAAGCCATGACTAAGTATGTGAAGGATCACCTGAATTGCTGAAAGTTAACGGTAAGATATCTGAAAGAGCTCATTAGATCCAACACTTATCTACTCAAAAATTCGTCATATTTCGGTGACTTGCTAGAAAGGCTCTTGCACAGTAAGGTTATAGAGAATGCTACCGTTGAAGCACCAGCCGTTGAAGCCCGCCTTTAACCACGCGATATATCCAATTAACCAAGGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGTCGCCTTGTAATAATTACTTTGGCCCGGATTATAACGAAGGAACTCGCCATGAACTCGCAGCACGTTGTACTGGAACAATCTACTTTTTATAATATAGCGATAACTCCCAGCTTTTATGTGGGTGATATTGTCCTAGCTTTTTAAAGATACCCTCTGGCCCGGTCCAAGTAAGGTCCACATTGCCTGACGTAAGCGTACGGTCAACGGGTGCACCGGTTCCCGCTAAAGCTCGATCCTATTCTTTCAGTCGGGGGGAAATAAACTCGTATACTCTCCACCCACCCGTACGTCCCGGACTAGAATAACTACCGGGTATTTCCGGTTCGTAACACCACGCCATGACGTGTCAACATAAACGCTTCTTTTGAAAGGTGCACATGCAGATTGCACAAGCAGCAGGCACCGCCCTTATCCATATCCTGTTGAGGCCCTCGATCCTAGTGTTCCTTGTTATCAGGATATTTTCTCGCTGTACGTTATTGTCCTTTTCAAATTACAACTGACCGCTTCCTCACCCGCTAAACCCTACCTTACGCACAACCAAGGCCTTGTCCCGGATGAACCCGGCTGCTCCTATGGATAAGCAACCCAGCCCGGCAGTTTACTTCAGGTGTTATCGTCGACTGACACCCTCAGCTTTCTCCCATTACACAGCGAGTATTTTCCGCGTAGCAATGGCAGTGACTTTGAGCGCACACTCAGAAGCCGTTGGAATGGCACCGGGGACGGCCCGATTTAGCCCCGCACACCTCCTGGAATCTTAGATCGCACGGCGATCTCGGTTCAGGCACCAACCCCAAAGAGTGTTTTGAGTTTTTGGTATGGCTCGCCTCAATTATCGGTTTTCGCTGCTCTGTGCCTGTCAACTCGGCTAGCTGTCGTGTTTTGTCGATCAGTGCGTGGACACTCTCGGTCGATGGTCGTGGATGGGACTGTAGTAAGTTTCACCGAAGCAGGAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAACTTCGCTTCATATAACGTAGCCATAGTGCTGTCTGCCATCAATAAGTCTTGCTCAGTGGTGCATACGTCGGGGAGGTTTGTTCCGCCTGGTCAGAACGAGTCTAGGGCGAGCCTATAGGCCAGTCGAGAGCCAAGATTCTATGAAATTAATACGACTACTGGGTGAGAGGTCATACAATTCCCGTGGAATCTGTACCTAAGATATTTCCAGATAGGGATGGCTACTGGTTAAGTTGACAGTGTCTAGATACGTGAGAGCACCTGAGAGGACGCCACGAGTCGGAGCGTGGGCGATCACCCTTCTGAGTCATAAGTCATGTCTATATATCCCTCACTAAAAAGGGCACACGACTATACATGCTTGAGCTTTACGGTCTGGCATGTGGAATGCCCGGAGCAACCCAGTCTTACCATCCTTTACGTACATTTACCGACCCGGCAGTGGCCGGCGCGGAAACCCAGGAGAACGTCGGTCATGATACGCGCCCTCCGCCGAAAGCGTGCTCACACCTCAGGATATCAGCGCTATTACCGGACGTCCCGCGTCCACCATCTAATAATTCAGGTGCTCCTAATAAGTGGGCTGGAGAGCGAGGATTGATATACGTTGAGGAGCTCCGACGGCCCTCTCGTGCGTTTGATGTAGATTGCGTTACCGACGGAGCACGCGTTTGTCAATTTCTGTCTAGGGACGTTTATGTCCTCAATACGAATACCAGGCCTATTTTAGTGTACAAATCACTTAGCAGTCGGAATTGGAAACCTGATGGAAGCGT"
counter=0
length=len(text)
search="AGATC"
tmp=0
for i in range(length):
if text[i:i + len(search)] == search:
tmp += 1
if tmp > counter:
counter = tmp
if text[i:i + len(search)] != search:
tmp = 0
print("done")
print(counter)
try this
import re
sequence = "AATDHDHDTKSDHAATAAT"
matches = re.findall(r'(?:AAT)+', sequence)
largest = max(matches, key=len)
print(len(largest)//len('AAT'))
basically this way will find you the list of substrings in the string you are have then you choose the largest substring. The number of occurrences of the substring will be the length of the largest divide by the length of substring
First and foremost, the regex solution is the Python way to solve this. However, if you want your code repaired ...
The problem with your code is that your index fails to acknowledge that you've found a match. You have no way to recognize consecutive occurrences.
Consider the case where you've found the start of a triple-match, AATAATAAT. You get to the first A, recognize, the AAT and increment tmp. You go to the next loop iteration, and now i points at the second A. You see that it's not AAT here (it's ATA, spanning the first two occurrences), so you record one instance and reset all your status variables.
Instead, you have to jump to the end of the first match and look for a second. Since your index does not move smoothly by increments of 1, you'll want a while loop instead.
Please learn to use meaningful variable names where the variables have
any meaning. i is fine if all it does is to manage your loop. As
soon as you use it for anything else, give it a real name. Similarly,
tmp and count really need replacing.
snip_size = len(search)
pos = 0 # position in the genetic sequence
rep = 0 # number of consecutive repetitions
max_rep = 0 # longest repetition sequence found
while pos < length:
if text[pos:pos + snip_size] == search:
rep += 1
pos += snip_size
else:
max_rep = max(max_rep, rep)
rep = 0
pos += 1
print(max_rep, "repetitions found")
Output:
15 repetitions found

Python program to print the odd and even indices of an string not taking the first test case

Question
Given a string S of length N, that is indexed from 0 to N-1, print it's even indexed and odd indexed characters as 2 space separated strings on a single line. Assume input starts at index position 0(which is considered even)
Input
The first line contains an integer, T (the number of test cases). Each line i of the T subsequent lines contain a String, S.
Output
For each string S, print it's even-indexed characters, followed by space, followed by odd-indexed characters.
Sample Input
2
Hacker
Rank
Sample Output
Hce akr
Rn ak
My code is as follows
T=int(input().strip())
for i in range(T):
Str=(input().strip())
odd=""
even=""
l=len(Str)
for j in range(l):
if(j%2==0):
even += Str[j]
else:
odd += Str[j]
print(even,"",odd)
****The output I am getting is:**
Input
2
Hacker
Rank
My Output
Rn ak
please help me what I am doing wrong?**
hope this will help you.
T = list(input().split())
for j in T:
a = ""
b = ""
for i in range(0,len(j)):
if i%2 == 0:
a = a+j[i]
else :
b = b + j[i]
print(a+" "+b)
input:
hacker rank
output :
hce akr
rn ak

Finding the index at which upon removing element string becomes palindrome

I'm writing the solution to this HackerRank problem - https://www.hackerrank.com/challenges/palindrome-index
I've tried this code:
T = int(raw_input())
for t in xrange(T):
s = raw_input()
index = -1
if s != s[::-1]:
for i in xrange(len(s)):
temp = s[:i:] + s[i+1::]
if temp == temp[::-1]:
index = i
break
print index
But when I submit it, out of the 14 test cases, around 8 take a long time to compute (~5-7 seconds) and 1 of them takes more than 10 seconds, so HackerRank doesn't even show the result (whether it gave the right output).
It seems my code is inefficient. Please help me out in making it run faster.
The easiest way to speed the code would be to remove slicing for every index in case that string isn't a palindrome. In case of maximum length string which is not a palindrome following line will generate over 200000 slices: temp = s[:i:] + s[i+1::].
You could start checking the string from start and beginning until you spot a difference. Once found you can generate slice which has either first or last letter removed and check if that's a palindrome. In case you removed the first character and result wasn't a palindrome you know that last character is the correct solution since the problem statement guarantees that:
T = int(raw_input())
for t in xrange(T):
s = raw_input()
length = len(s)
for i in xrange(length / 2):
if s[i] != s[length - i - 1]:
if s[i + 1:length - i] == s[length - i - 1:i:-1]:
print i
else:
print length - i - 1
break
else:
print -1
The most efficient way would be to check from both sides left and right and break on inequality:
for i in range(int(input())):
s=input()
if s==s[::-1]:
print(-1)
else:
for i in range(int(len(s)/2)):
if s[i]!=s[len(s)-1-i]:
print(i if ((s[:i]+s[i+1:])==(s[:i]+s[i+1:])[::-1]) else len(s)-1-i)
break
Apparently I'm a member of that site as well, executed my code and it passes all test cases with 0.01 s and 0.02s

Largest Palindrome Product of 2 3 digit numbers

Problem statement:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
Here is what I've done.
for x in range(999,100,-1):
for y in range(x,100,-1):
check = str(x*y)
check_length = len(check)
if check_length % 2 == 0:
if check[0:check_length//2] == check[check_length:check_length//2:-1]:
print(check)
break
So I've cut out all repeat products (i.e. 999x998=998x999), convert it into a string and check if the two halves are the same after reversing the second string. This produces no result whatsoever. I am not looking for an answer but a hint as to the direction and also the pointing out any problems with the code. Thanks!
EDIT
for x in range(999,100,-1):
for y in range(x,100,-1):
check = str(x*y)
check_length = len(check)
if check[0:check_length//2] == check[check_length:check_length//2:-1]:
print(check)
break
Sample Output of check
580085
906609
119911
282282
853358
EDIT
Here is my final version which does the trick. Thanks for all the input.
largest_palindrome = 0
for x in range(999,100,-1):
for y in range(x,100,-1):
product = x*y
check = str(x*y)
if check == check[::-1]:
if product > largest_palindrome:
largest_palindrome = product
print(largest_palindrome)
Your check is wrong. Let’s take a look at an example:
>>> check = '123321'
>>> check_length = len(check)
>>> check[0:check_length//2]
'123'
>>> check[check_length:check_length//2:-1]
'12'
As you can see, you’re chopping off one character. That’s because you are splitting the string as check[6:3:-1] which keeps the index 3 out (because ranges are exclusive of the end). So correct would be the following:
>>> check[check_length:check_length//2 - 1:-1]
'123'
But you actually don’t need that complexity. There is no need to split the string in half and compare the halves. A palindrome is a string that reads forwards the same as backwards. So just compare the whole string with the whole string reversed:
>>> check
'123321'
>>> check[::-1]
'123321'
>>> check == check[::-1]
True
This also makes is easy to check one case which you didn’t account at all for: Uneven string lengths. A number 12321 is a palindrome too but because the string length is 5, you are completely ignoring it.
Finally there are two further issues with your code:
break from within the inner loop will not break the outer loop. So you will stop iterating y but the next iteration for x will start, so you are continuing the search for a while. You need a way to break the outer loop in that case too.
You are not looking for the largest palindrome. You are simply starting at the largest argument x and then check all possible y that make palindromes. But that will give you for example 998 * 583 as the largest palindrome, but there are easily numbers (with lower x) that will produce larger palindromes. So you should check all the palindromes you find, or iterate in another way.
def reverse(n):
Number = n
Reverse = 0
while(Number > 0):
Reminder = Number %10
Reverse = (Reverse *10) + Reminder
Number = Number //10
return Reverse
def multiple(i, j):
return i * j
def checkPalindrone(n, rn):
if (n == rn):
return True
else:
return False
def maxPalindrone():
mult = 0
returnPalidrone = []
for i in range(100,1000):
for j in range(100,1000):
mult = multiple(i,j)
if (checkPalindrone(mult, reverse(mult))):
returnPalidrone.append(mult)
else:
continue
return max(returnPalidrone)

Categories

Resources