How to handle long strings on hackerrank in python - python

How to handle long strings in hackerrank in python as it shows an error:
Terminated due to timeout.
Written code in python:
s = 'NANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANAN'
def calculate(s):
result = []
for num in range(1,len(s)+1):
for i in range(0,len(s)):
temp = s[i:i+num]
if(len(temp) == num):
result.append(temp)
return(result)
resultlist = calculate(s)
print(resultlist)
resultset = set(resultlist)
resultdict = {}
for elem in resultset:
resultdict[elem] = resultlist.count(elem)
countVowel = 0
countcons = 0
for elem in resultdict.keys():
if elem[0] in 'AEIOU':
countVowel += resultdict[elem]
else:
countcons += resultdict[elem]
if(countVowel > countcons):
print("Kevin "+str(countVowel))
elif(countVowel < countcons):
print("Stuart "+str(countcons))
else:
print("draw")
The expected result should print string, but it's showing an error of terminated due to timeout.

There is no problem with long strings in Python, only with algorithms with O(nĀ³) complexity (two nested loops plus string slicing) that are applied to inputs with size n=5000.
It seems like you want to compare how many substrings of the input s start with a vowel vs. how many start with a non-vowel. For this you do not really need to calculate all those substrings -- you only need to know how many substrings there are starting at the current position!
countVowel = 0
countcons = 0
for i, a in enumerate(s):
if a in 'AEIOU':
countVowel += len(s) - i
else:
countcons += len(s) - i
And that's all you need. No calculate, not resultlist, -set and -dict. For a shorter test input, this yielded the same result as your algorithm, just much, much faster, in O(n).
For example, if you have the string ABCDE and you are currently at position B, you have the substrings [B, BC, BCD, BCDE]. You do not have to actually calculate all those substrings to know that (a) there are four of them (the length of the string minus the current position) and (b) all of those start with a B. Thus, just iterate the characters in the string, calculate the number of substrings from that position, and add that number to the counter corresponding to the current character.

Try this: (global s is renamed to inp)
inp = 'NANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANAN'
def calculate(s):
result = {}
s_len = len(s)
for num in range(1, s_len + 1):
for i in range(0, s_len - num + 1):
temp = s[i:i + num]
count = result.setdefault(temp, 0)
result[temp] = count + 1
return result
resultdict = calculate(inp)
countVowel = 0
countcons = 0
for elem in resultdict.keys():
if elem[0] in 'AEIOU':
countVowel += resultdict[elem]
else:
countcons += resultdict[elem]
if countVowel > countcons:
print("Kevin " + str(countVowel))
elif countVowel < countcons:
print("Stuart " + str(countcons))
else:
print("draw")
I got result Stuart 7501500
If you provide more input examples and expected results - it could be possible to check :)

Related

Removing substring from string in Python

I want to write a function that takes 2 inputs: a string and a substring, then the function will remove that part of the substring from the string.
def remove_substring(s, substr):
"""(str, str) -> NoneType
Returns string without string substr
remove_substring_from_string("Im in cs", "cs")
Im in
"""
other_s = ''
for substr in s:
if substr in s:
continue
How do I continue on from here? Assuming my logic is sound.
Avoiding the use of Python functions.
Method 1
def remove_substring_from_string(s, substr):
'''
find start index in s of substring
remove it by skipping over it
'''
i = 0
while i < len(s) - len(substr) + 1:
# Check if substring starts at i
if s[i:i+len(substr)] == substr:
break
i += 1
else:
# break not hit, so substr not found
return s
# break hit
return s[:i] + s[i+len(substr):]
Method 2
If the range function can be used, the above can be written more compactly as follows.
def remove_substring_from_string(s, substr):
'''
find start index in s of substring
remove it by skipping over it
'''
for i in range(len(s) - len(substr) + 1):
if s[i:i+len(substr)] == substr:
break
else:
# break not hit, so substr not found
return s
return s[:i] + s[i+len(substr):]
Test
print(remove_substring_from_string("I have nothing to declare except my genuis", " except my genuis"))
# Output: I have nothing to declare'
This approach is based on the KMP algorithm:
def KMP(s):
n = len(s)
pi = [0 for _ in range(n)]
for i in range(1, n):
j = pi[i - 1]
while j > 0 and s[i] != s[j]:
j = pi[j - 1]
if s[i] == s[j]:
j += 1
pi[i] = j
return pi
# Removes all occurences of t in s
def remove_substring_from_string(s, t):
n = len(s)
m = len(t)
# Calculate the prefix function using KMP
pi = KMP(t + '\x00' + s)[m + 1:]
r = ""
i = 0
while i + m - 1 < n: # Before the remaining string is smaller than the substring
if pi[i + m - 1] == m: # If the substring is here, skip it
i += m
else: # Otherwise, add the current character and move to the next
r += s[i]
i += 1
# Add the remaining string
r += s[i:]
return r
It runs in O(|s| + |t|), but it has a few downsides:
The code is long and unintuitive.
It requires that there is no null (\x00) in the input strings.
Its constant factors are pretty bad for short s and t.
It doesn't handle overlapping strings how you might want it: remove_substring_from_string("aaa", "aa") will return "a". The only guarantee made is that t in remove_substring_from_string(s, t) is False for any two strings s and t.
A C++ example and further explanation for the KMP algorithm can be found here. The remove_substring_from_string function then only checks if the entire substring is matched at each position and if so, skips over the substring.
I would do this using re.
import re
def remove_substring(s, substr):
# type: (str, str) -> str
return re.subn(substr, '', s)[0]
remove_substring('I am in cs', 'cs')
# 'I am in '
remove_substring('This also removes multiple substr that are found. Even if that substr is repeated like substrsubstrsubstr', 'substr')
# 'This also removes multiple that are found. Even if that is repeated like '
def remove_substring(s, substr):
while s != "":
if substr in s:
s = s.replace(substr, "")
else:
return s
if s == "":
return "Empty String"
The idea here is that we replace all occurrences of substr within s, by replacing the first instance of substr and then looping until we are done.

How can i remove the break from find_frequent(s) code since our teacher told us we can't use it on the test and I'm trying to practice not using it?

I wrote this code, and I'm struggling to replace using break since it says in the homework that we are not allowed to use continue/break statements in our loops.
The code's goal is:
finds the character that appears most frequently in the input parameter string and returns it. For Example, if the string is "Canada day" the function returns the string "a"
If there are two characters or more with the same frequency, the function should return the first of many values with the same frequency.
def find_frequent(s):
"""
-------------------------------------------------------
description
Use:
-------------------------------------------------------
Parameters:
name - description (type)
Returns:
name - description (type)
------------------------------------------------------
"""
L = []
count = 0
char = 0
i = 0
words = True
while i < 1 and words:
x = s[i]
for j in range(len(L)):
if x == L[j]:
words = False
L[j + 1] = L[j + 1] + 1
else:
L.append(x)
L.append(1)
for i in range(1, len(L), 2):
if L[i] > count:
count = L[i]
char = L[i - 1]
return char
the output should look like this
`Enter a string: Hello Hi`
output should be
`Most frequent characters: H`
I'm getting this output
Enter a string: canada
Most frequent character: c
You can replace the break statement in a for loop with a while loop.
print("using for loop + break")
for i in range(0, 5):
print(i)
if i == 3:
break
print("using while")
i = 0
keep_searching = True
while i < 5 and keep_searching:
print(i)
if i == 3:
keep_searching = False
i += 1
The output is:
using for loop + break
0
1
2
3
using while
0
1
2
3
I think you can figure it out from here, but if you need help with finding the most frequent character (a different issue from the break), take a look here and here.
No need for a break if you don't use a loop in the first place :-)
def find_frequent(s):
return max(s, key=s.count)
(I'm actually serious... forbidding break sounds to me like your teacher didn't want you to write it with such nested loops.)
Or if you want to teach your teacher a lesson (the lesson being that they shouldn't forbid stuff), you could fake the break:
for i in range(0, len(s), 1):
x = s[i]
it = iter(range(len(L))) # make it an iterator
for j in it:
if x == L[j]:
L[j + 1] = L[j + 1] + 1
*it, # exhaust the iterator
it = None # make it false
if it: # instead of `else`
L.append(x)
L.append(1)

Given a string of digits, return the longest substring with alternating odd/even or even/odd digits

So I was doing this python challenge for fun, but for some reason it is saying I am incorrect and I have no idea why. The challenge prompt said this:
Given a string of digits, return the longest substring with alternating odd/even or even/odd digits. If two or more substrings have the same length, return the substring that occurs first.
Examples
longest_substring("225424272163254474441338664823") āžž "272163254"
# substrings = 254, 272163254, 474, 41, 38, 23
longest_substring("594127169973391692147228678476") āžž "16921472"
# substrings = 94127, 169, 16921472, 678, 476
longest_substring("721449827599186159274227324466") āžž "7214"
# substrings = 7214, 498, 27, 18, 61, 9274, 27, 32
# 7214 and 9274 have same length, but 7214 occurs first.
Notes
The minimum alternating substring size is 2.
The code I wrote for a solution was this:
def longest_substring(digits):
substring = []
final = []
loop = 0 # just loops through the for loop
start = 0
loop2 = 0
while loop+1 < len(digits):
num = int(digits[loop])
num2 = int(digits[loop+1])
if (num + num2)%2 != 0 and start == 0:
substring.append(num)
substring.append(num2)
start += 1
elif (num + num2)%2 != 0:
substring.append(num2)
else:
start = 0
loop2 += 1
final.append(substring.copy())
substring.clear()
loop += 1
sorted_list = list(sorted(final, key=len))
if len(sorted_list[-1]) == len(sorted_list[-2]):
index1 = final.index(sorted_list[-1])
index2 = final.index(sorted_list[-2])
if index1 < index2: # because the larger than not first
sorted_list = sorted_list[-1]
else:
sorted_list = sorted_list[-2]
sorted_list = str(sorted_list)
sorted_list = sorted_list.replace('[','')
sorted_list = sorted_list.replace(']', '')
sorted_list = sorted_list.replace(', ','')
return str(sorted_list) # or print(str(sorted_list)) neither works
If you're curious the challenge is here
I would actually prefer using a shorter code. It's easier to look for errors IMO.
Does this work for you?
def longest_substring(digits):
max_len = 0
ans = ''
for i in range(len(digits)):
temp = digits[i]
for x in range(i+1, len(digits)):
if int(digits[x])%2 != int(digits[x-1])%2:
temp += digits[x]
else:
break
if len(temp) > max_len:
max_len = len(temp)
ans = temp
return ans
Here's something a bit simpler:
def longest_substring(digits):
current = longest = digits[0]
for digit in digits[1:]:
if int(digit)%2 != int(current[-1])%2:
current += digit
else:
longest = longest if len(longest) >= len(current) else current
current = digit
longest = longest if len(longest) >= len(current) else current
return longest
The bit about how you're picking the indexes at the end doesn't always work, leading to cases where your list ends up with all of the possibilities in it. If, instead you modify the code to be explicit, and run through the entire list after you create sorted_list:
best = []
for cur in sorted_list:
if len(cur) > len(best):
best = cur
return "".join([str(x) for x in best])
The rest of your implementation will work.
And for kicks, I took a pass at simplifying it:
def longest_substring(digits):
possible, best = "", ""
for x in digits + " ":
if x == " " or (len(possible) > 0 and int(possible[-1]) % 2 == int(x) % 2):
best = possible if len(possible) > len(best) else best
possible = ""
possible += x
return best

count an occurrence of a string in a bigger string

I am looking to understand what I can do to make my code to work. Learning this concept will probably unlock a lot in my programming understanding. I am trying to count the number of times the string 'bob' occurs in a larger string. Here is my method:
s='azcbobobegghakl'
for i in range(len(s)):
if (gt[0]+gt[1]+gt[2]) == 'bob':
count += 1
gt.replace(gt[0],'')
else:
gt.replace(gt[0],'')
print count
How do I refer to my string instead of having to work with integers because of using for i in range(len(s))?
Try this:
def number_of_occurrences(needle, haystack, overlap=False):
hlen, nlen = len(haystack), len(needle)
if nlen > hlen:
return 0 # definitely no occurrences
N, i = 0, 0
while i < hlen:
consecutive_matching_chars = 0
for j, ch in enumerate(needle):
if (i + j < hlen) and (haystack[i + j] == ch):
consecutive_matching_chars += 1
else:
break
if consecutive_matching_chars == nlen:
N += 1
# if you don't need overlap, skip 'nlen' characters of 'haystack'
i += (not overlap) * nlen # booleans can be treated as numbers
i += 1
return N
Example usage:
haystack = 'bobobobobobobobobob'
needle = 'bob'
r = number_of_occurrences(needle, haystack)
R = haystack.count(needle)
print(r == R)
thanks. your support help to birth the answer in. here what I have :
numBobs = 0
for i in range(1, len(s)-1):
if s[i-1:i+2] == 'bob':
numBobs += 1
print 'Number of times bob occurs is:', numBobs

first time programming-exercise

First time programming ever... I'm trying to do this exercise to.. :
Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
I was here..before starting to freak out:
s = 'abcdezcbobobegghakl'
n = len(s)
x = 0
x += 1
lengh = s[x-1]
if s[x] >= s[x-1]:
lengh = lengh + s[x]
if s[x+1] < s[x]:
n = len(lengh)
if x > n:
break
print('Longest substring in alphabetical order is: ' + str(lengh))
I know this code is bad..I m trying to find substring in alphabetical order and is some way keep the longest one! I know could be normal, because I never programmed before but i feel really frustrated...any good idea/help??
First try to decompose your problem into little problems (do not optimize ! until your problem is solved), if you have learned about functions they are a good way to decompose execution flow into readable and understandable snippets.
An example to start would be :
def get_sequence_size(my_string, start):
# Your code here
return size_of_sequence
current_position = 0
while current_position < len(my_string):
# Your code here using get_sequence_size() function
The following code solves the problem using the reduce method:
solution = ''
def check(substr, char):
global solution
last_char = substr[-1]
substr = (substr + char) if char >= last_char else char
if len(substr) > len(solution):
solution = substr
return substr
def get_largest(s):
global solution
solution = ''
reduce(check, list(s))
return solution
def find_longest_substr(my_str):
# string var to hold the result
res = ""
# candidate for the longest sub-string
candidate = ""
# for each char in string
for char in my_str:
# if candidate is empty, just add the first char to it
if not candidate:
candidate += char
# if last char in candidate is "lower" than equal to current char, add char to candidate
elif candidate[-1] <= char:
candidate += char
# if candidate is longer than result, we found new longest sub-string
elif len(candidate) > len(res):
res= candidate
candidate = char
# reset candidate and add current char to it
else:
candidate = char
# last candidate is the longest, update result
if len(candidate) > len(res):
res= candidate
return res
def main():
str1 = "azcbobobegghaklbeggh"
longest = find_longest_substr(str1)
print longest
if __name__ == "__main__":
main()
These are all assuming you have a string (s) and are needing to find the longest substring in alphabetical order.
Option A
test = s[0] # seed with first letter in string s
best = '' # empty var for keeping track of longest sequence
for n in range(1, len(s)): # have s[0] so compare to s[1]
if len(test) > len(best):
best = test
if s[n] >= s[n-1]:
test = test + s[n] # add s[1] to s[0] if greater or equal
else: # if not, do one of these options
test = s[n]
print "Longest substring in alphabetical order is:", best
Option B
maxSub, currentSub, previousChar = '', '', ''
for char in s:
if char >= previousChar:
currentSub = currentSub + char
if len(currentSub) > len(maxSub):
maxSub = currentSub
else: currentSub = char
previousChar = char
print maxSub
Option C
matches = []
current = [s[0]]
for index, character in enumerate(s[1:]):
if character >= s[index]: current.append(character)
else:
matches.append(current)
current = [character]
print "".join(max(matches, key=len))
Option D
def longest_ascending(s):
matches = []
current = [s[0]]
for index, character in enumerate(s[1:]):
if character >= s[index]:
current.append(character)
else:
matches.append(current)
current = [character]
matches.append(current)
return "".join(max(matches, key=len))
print(longest_ascending(s))
def longest(s):
buff = ''
longest = ''
s += chr(255)
for i in range(len(s)-1):
buff += s[i]
if not s[i] < s[i+1]:
if len(buff) > len(longest):
longest = buff
buff = ''
if len(buff) > len(longest):
longest = buff
return longest

Categories

Resources