I am new to python. I got below code, but my main function doesn't work. Can anyone help? Thank you!
The quetion is:
Given a string s, return the last substring of s in lexicographical order.
Example 1:
Input: "abab"
Output: "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".
The IDE said;
Traceback (most recent call last):
File "F:/!!!PDF/!!!PyCharmWorkspace/LeetCode/AA1163LastSubstringInLexicographicalOrder3.py", line
1, in <module>
class Solution:
File "F:/!!!PDF/!!!PyCharmWorkspace/LeetCode/AA1163LastSubstringInLexicographicalOrder3.py", line
20, in Solution
print(lastSubstring(s))
TypeError: lastSubstring() missing 1 required positional argument: 's'
Below is my code.
class Solution:
def lastSubstring(self, s: str) -> str:
i, indexes = 0, list(range(len(s)))
while len(indexes) > 1:
new = []
mx = max([s[i + j] for j in indexes if i + j < len(s)])
for k, j in enumerate(indexes):
if k - 1 >= 0 and indexes[k - 1] + i == j:
continue
if i + j >= len(s):
break
if s[i + j] == mx:
new.append(j)
i += 1
indexes = new
return s[indexes[0]:]
if __name__ == '__main__':
s = "leetcode"
print(lastSubstring(s))
You are trying to use class function while you didn't create an instance of this class.
There are two ways to solve this issue.
First - Declare the lastSubstring as classmethod:
classmethod() methods are bound to class rather than an object. Class
methods can be called by both class and object. These methods can be
call with class or with object. Below examples illustrates above
clearly.
class Solution:
#classmethod
def lastSubstring(self, s: str) -> str:
i, indexes = 0, list(range(len(s)))
while len(indexes) > 1:
new = []
mx = max([s[i + j] for j in indexes if i + j < len(s)])
for k, j in enumerate(indexes):
if k - 1 >= 0 and indexes[k - 1] + i == j:
continue
if i + j >= len(s):
break
if s[i + j] == mx:
new.append(j)
i += 1
indexes = new
return s[indexes[0]:]
if __name__ == '__main__':
s = "leetcode"
print(Solution.lastSubstring(s))
Second - Create an instance from the Solution class first:
if __name__ == '__main__':
s = "leetcode"
sol= Solution()
print(sol.lastSubstring(s))
Related
So I am working on problem 658 'Find K Closest Elements'(https://leetcode.com/problems/find-k-closest-elements/), which asks to return a list from the given list, 'arr'. This return list will be the length of 'k' and will contain the 'k' # of values closest to the given 'x' value. I've created all the base cases and constraints, and am now stuck on the comparison part below:
I've created an empty list, 'a'. While the length of 'a' is not 'k', the function will go through the list and compare abs(i - x) < abs(comp - x), 'comp' starting at 'arr[0]' and updating to 'i' if the comparison is true. The problem is that the comparison is not working correctly. Here is an example case I'm trying to figure out:
arr = [1,1,1,10,10,10], k = 4, x = 9
Below is the portion of the code I am focusing on:
a = []
comp = arr[0]
iteration = 0
i_index = 0
while len(a) != k:
for i in arr:
comp_1 = abs(i - x)
comp_2 = abs(comp - x)
if comp_1 < comp_2:
comp == i
print(f"comp: {comp}")
arr.pop(arr.index(comp))
a.append(comp)
return a
I am including the entirety of the code just in case below:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# Constraints
if k < 1 or k > len(arr):
return "k must be greater than 0 and less than the arr length"
if len(arr) < 1 or len(arr) > 10**4:
return "arr length must be greater than 0 and less than 10^4"
if x > 10**4:
return "x must be less than 10^4"
if sorted(arr) != arr:
return "arr must be sorted"
for i in arr:
if i < -10**4:
return "arr item cannot be less than -10^4"
#Variables 1
begin = arr[:k]
end = arr[-k:]
# Base cases
if len(arr) == k:
return arr
if x < arr[0]:
return begin
elif x > arr[-1]:
return end
try:
x_index = arr.index(x)
half_k = int(k/2)
#if k == x and x_index != None:
# return [x]
# Captures all other lists that begin at arr[0] or end at arr[-1]
if x_index - half_k < 0:
return begin
elif x_index + half_k > len(arr) - 1:
return end
# Create list out of interior of arr if necessary
else:
return arr[x_index - half_k : x_index + half_k]
# Means x is not in arr
except ValueError:
a = []
comp = arr[0]
iteration = 0
i_index = 0
while len(a) != k:
for i in arr:
print(f"{iteration} - {i_index}:")
print(f"i: {i}")
print(f"comp_1: {abs(i - x)}")
print(f"comp_2: {abs(comp - x)}")
comp_1 = abs(i - x)
comp_2 = abs(comp - x)
if comp_1 < comp_2:
comp == i
print(f"comp: {comp}")
i_index += 1
print("\n")
iteration += 1
arr.pop(arr.index(comp))
a.append(comp)
return a
I would take the approach of:
finding the shortest distance from x to the elements of arr.
sorting arr by the distances.
So, this is a good method:
arr = [1,1,1,10,10,10]
k = 4
x = 9
distances = [abs(x - n) for n in arr]
Z = [a for _,a in sorted(zip(distances,arr))]
print(Z[:k])
result
[10, 10, 10, 1]
I'm trying to implement a partial brute force approach in python for Leetcode Beautiful Arrangements. I'm struggling to update my "counter" variable during the recursive calls.
I've tried multiple approaches with global variables and passing it in as a function parameter, no matter what I've done, I'm not getting the correct return value even though the if L == len(numbers) condition is met.
class Solution:
def countArrangement(self, n: int) -> int:
def count_beautiful_arranges(N: int, counter):
numbers = [0]*N
# start index at 1
# loop creates the array of 1 to N for initial list
for i in range(1, N+1):
numbers[(i-1)] = i
# call recursive permutation function
permutation(numbers, 0, counter)
return counter
def permutation(numbers: list, L: int, counter):
# check each recursive call
#print(L)
#print(len(numbers))
if L == len(numbers):
counter = counter + 1
for j in range(L, len(numbers)):
swap(numbers, j, L)
if numbers[L] % (L+1) == 0 or (L+1) % numbers[L] == 0:
permutation(numbers, L+1, counter)
swap(numbers, j, L)
def swap(numbers: list, x: int, y: int):
#pythonic code
numbers[x], numbers[y] = numbers[y], numbers[x]
count_beautiful_arranges(n, 0)
I fixed it by using Python's ability to attach a variable to a function. with
<Function_Name>. method I was able to attach a counter and increment it in the recursive stack.
I declared permutation.countser before calling the recursive functions then returned the value after the calls were completed.
This StackOverflow answer helped me.
def count_beautiful_arranges(N: int, counter):
numbers = [0]*N
# start index at 1
# loop creates the array of 1 to N for initial list
for i in range(1, N+1):
numbers[(i-1)] = i
permutation(numbers, 0)
def permutation(numbers: list, L: int):
if L == len(numbers):
permutation.countser += 1
for j in range(L, len(numbers)):
swap(numbers, j, L)
if numbers[L] % (L+1) == 0 or (L+1) % numbers[L] == 0:
permutation(numbers, L+1)
swap(numbers, j, L)
def swap(numbers: list, x: int, y: int):
#pythonic code
numbers[x], numbers[y] = numbers[y], numbers[x]
permutation.countser = 0
count_beautiful_arranges(n, 0)
return permutation.countser
I come up a solution for leetcode "5. Longest Palindromic Substring" with parts of duplicate codes. One of good ways to solve duplicate code is to make a function. How do I write my check here to a function? I am confused what I should return to make both variables - longest and ans - being updated. Thanks!
The part of duplicate code:
if len(s[l:r+1]) > longest:
longest = len(s[l:r+1])
ans = s[l:r+1]
Full code:
class Solution:
def longestPalindrome(self, s: str) -> str:
if len(s) == 0:
return ''
if len(s) == 1:
return s
longest = 0
ans = ''
for pos in range(len(s)-1):
l, r = pos, pos
if pos > 0 and pos < len(s) - 1 and s[pos-1] == s[pos+1]:
l, r = pos-1, pos+1
while l > 0 and r < len(s) - 1 and s[l-1] == s[r+1]:
l -= 1
r += 1
# duplicate code 1
if len(s[l:r+1]) > longest:
longest = len(s[l:r+1])
ans = s[l:r+1]
if s[pos] == s[pos+1]:
l, r = pos, pos+1
while l > 0 and r < len(s) - 1 and s[l-1] == s[r+1]:
l -= 1
r += 1
# duplicate code 2
if len(s[l:r+1]) > longest:
longest = len(s[l:r+1])
ans = s[l:r+1]
if ans == '' and len(s) > 0:
return s[0]
return ans
The if statements and while loops before the duplicate code blocks are mostly duplicated as well, as is using the longest variable to keep track of the length of ans when you already have ans -- here's one way you could simplify things via another function:
class Solution:
def find_longest(self, s, left, right):
if s[left] == s[right]:
if right - left + 1 > len(self.ans):
self.ans = s[left:right + 1]
if left > 0 and right < len(s) - 1:
self.find_longest(s, left - 1, right + 1)
def longestPalindrome(self, s: str) -> str:
if len(s) == 1:
return s
self.ans = ''
for pos in range(len(s) - 1):
self.find_longest(s, pos, pos)
self.find_longest(s, pos, pos + 1)
return self.ans
I am studying the Bioinformatics course at Coursera, and have been stuck on the following problem for 5 days:
Implement GreedyMotifSearch.
Input: Integers k and t, followed by a collection of strings Dna.
Output: A collection of strings BestMotifs resulting from applying GreedyMotifSearch(Dna, k, t).
If at any step you find more than one Profile-most probable k-mer in a given string, use the
one occurring first.
Here's my attempt to solve this (I just copied it from my IDE, so pardon any print statements):
def GreedyMotifSearch(DNA, k, t):
"""
Documentation here
"""
import math
bestMotifs = []
bestScore = math.inf
for string in DNA:
bestMotifs.append(string[:k])
base = DNA[0]
for i in window(base, k):
newMotifs = []
for j in range(t):
profile = ProfileMatrix([i])
probable = ProfileMostProbable(DNA[j], k, profile)
newMotifs.append(probable)
if Score(newMotifs) <= bestScore:
bestScore = Score(newMotifs)
bestMotifs = newMotifs
return bestMotifs
The helper functions are these:
def SymbolToNumber(Symbol):
"""
Converts base to number (in lexicograpical order)
Symbol: the letter to be converted (str)
Returns: the number correspondinig to that base (int)
"""
if Symbol == "A":
return 0
elif Symbol == "C":
return 1
elif Symbol == "G":
return 2
elif Symbol == "T":
return 3
def NumberToSymbol(index):
"""
Finds base from number (in lexicographical order)
index: the number to be converted (int)
Returns: the base corresponding to index (str)
"""
if index == 0:
return str("A")
elif index == 1:
return str("C")
elif index == 2:
return str("G")
elif index == 3:
return str("T")
def HammingDistance(p, q):
"""
Finds the number of mismatches between 2 DNA segments of equal lengths
p: first DNA segment (str)
q: second DNA segment (str)
Returns: number of mismatches (int)
"""
return sum(s1 != s2 for s1, s2 in zip(p, q))
def window(s, k):
for i in range(1 + len(s) - k):
yield s[i:i+k]
def ProfileMostProbable(Text, k, Profile):
"""
Finds a k-mer that was most likely to be generated by profile among
all k-mers in Text
Text: given DNA segment (str)
k: length of pattern (int)
Profile: a 4x4 matrix (list)
Returns: profile-most probable k-mer (str)
"""
letter = [[] for key in range(k)]
probable = ""
hamdict = {}
index = 1
for a in range(k):
for j in "ACGT":
letter[a].append(Profile[j][a])
for b in range(len(letter)):
number = max(letter[b])
probable += str(NumberToSymbol(letter[b].index(number)))
for c in window(Text, k):
for x in range(len(c)):
y = SymbolToNumber(c[x])
index *= float(letter[x][y])
hamdict[c] = index
index = 1
for pat, ham in hamdict.items():
if ham == max(hamdict.values()):
final = pat
break
return final
def Count(Motifs):
"""
Documentation here
"""
count = {}
k = len(Motifs[0])
for symbol in "ACGT":
count[symbol] = []
for i in range(k):
count[symbol].append(0)
t = len(Motifs)
for i in range(t):
for j in range(k):
symbol = Motifs[i][j]
count[symbol][j] += 1
return count
def FindConsensus(motifs):
"""
Finds a consensus sequence for given list of motifs
motifs: a list of motif sequences (list)
Returns: consensus sequence of motifs (str)
"""
consensus = ""
for i in range(len(motifs[0])):
countA, countC, countG, countT = 0, 0, 0, 0
for motif in motifs:
if motif[i] == "A":
countA += 1
elif motif[i] == "C":
countC += 1
elif motif[i] == "G":
countG += 1
elif motif[i] == "T":
countT += 1
if countA >= max(countC, countG, countT):
consensus += "A"
elif countC >= max(countA, countG, countT):
consensus += "C"
elif countG >= max(countC, countA, countT):
consensus += "G"
elif countT >= max(countC, countG, countA):
consensus += "T"
return consensus
def ProfileMatrix(motifs):
"""
Finds the profile matrix for given list of motifs
motifs: list of motif sequences (list)
Returns: the profile matrix for motifs (list)
"""
Profile = {}
A, C, G, T = [], [], [], []
for j in range(len(motifs[0])):
countA, countC, countG, countT = 0, 0, 0, 0
for motif in motifs:
if motif[j] == "A":
countA += 1
elif motif[j] == "C":
countC += 1
elif motif[j] == "G":
countG += 1
elif motif[j] == "T":
countT += 1
A.append(countA)
C.append(countC)
G.append(countG)
T.append(countT)
Profile["A"] = A
Profile["C"] = C
Profile["G"] = G
Profile["T"] = T
return Profile
def Score(motifs):
"""
Finds score of motifs relative to the consensus sequence
motifs: a list of given motifs (list)
Returns: score of given motifs (int)
"""
consensus = FindConsensus(motifs)
score = 0.0000
for motif in motifs:
score += HammingDistance(consensus, motif)
#print(score)
return round(score, 4)
It seems fine to me. However, when I run this code for quiz problems, it gives an incorrect answer. Their code grading system shows this error:
Failed test #3. Your indexing may be off by one at the beginning of each string in Dna.
I have tried everything I can think of and run this code on all their sample data and debug data, but I simply can't figure out how to make this code work. Please help me with any possible solutions to this.
You have a few problems. I think this should address them all. I've included comments explaining each change along with your original code and a reference to the relevant Pseudocode in the debug data page you linked to.
def GreedyMotifSearch(DNA, k, t):
"""
Documentation here
"""
import math
bestMotifs = []
bestScore = math.inf
for string in DNA:
bestMotifs.append(string[:k])
base = DNA[0]
for i in window(base, k):
# Change here. Should start with one element in motifs and build up.
# As in the line "motifs ← list with only Dna[0](i,k)"
# newMotifs = []
newMotifs = [i]
# Change here to iterate over len(DNA).
# Should go through "for j from 1 to |Dna| - 1"
# for j in range(t):
for j in range(1, len(DNA)):
# Change here. Should build up motifs and build profile using them.
# profile = ProfileMatrix([i])
profile = ProfileMatrix(newMotifs)
probable = ProfileMostProbable(DNA[j], k, profile)
newMotifs.append(probable)
# Change to < rather < = to ensure getting the most recent hit. As referenced in the instructions:
# If at any step you find more than one Profile-most probable k-mer in a given string, use the one occurring **first**.
if Score(newMotifs) < bestScore:
#if Score(newMotifs) <= bestScore:
bestScore = Score(newMotifs)
bestMotifs = newMotifs
return bestMotifs
I am having some issues with this question for which i have tried to make 2 solutions.The first one works partially but the second one does not.Here is the question
Question with which i am having the issue.Has sample input and output
Here are the 2 codes which i have written
number=int(input())
S=input()
w=list(S[:])
w_count=0
other_count=0
v_count=0
vv_count=0
i=0
while(i<(len(w))):
try:
if w[i]=='w':
w_count+=1
elif w[i]=='v' and w[i+1]=='v':
vv_count+=1
i+=1
else:
other_count+=1
except IndexError:
pass
i+=1
max_length=w_count*2+other_count+v_count
min_length=0
min_length=w_count+other_count+vv_count
print(min_length,max_length)
The other Logic has been implemented with the help of a for loop for which 3 test cases are passing
for value in range(len(w)):
try:
if w[value]=='w':
w_count+=1
elif w[value]=='v' and w[value+1]=='v':
vv_count+=1
else:
other_count+=1
except IndexError:
pass
If think you can keep it simple with:
my_string = "avwvb"
max_len = len(my_string.replace("w", "vv"))
min_len = len(my_string.replace("w", "vv").replace("vv", "w"))
print(max_len, min_len)
Or a little faster:
my_string = "avwvb"
max_string = my_string.replace("w", "vv")
min_string = max_string.replace("vv", "w")
max_len = len(max_string)
min_len = len(min_string)
print(max_len, min_len)
You can try this. It's similar to your for loop solution but uses string indexing a bit better.
For the first problem I'm just expanding the string as much as possible changing all ws into 2 vs.
The second is a bit trickier. I first expand the string using the previous method, and then build a new string where any vv combinations can be turned into w. I use 2 indexes, i for the longer string and j for the shorter version of the string, in order to avoid index errors.
def longer(s):
for i in range(0,len(s)):
x = s[i]
if x == 'w':
new_str = s[:i] + 'v' + s[i+1:]
if (i + 1 >= len(s)):
new_str = new_str + 'v'
else:
new_str = new_str[:i] + 'v' + new_str[i:]
s = new_str
return s
def shorter(s):
long_str = longer(s)
short_str = long_str[0]
j = 1
for i in range(1,len(long_str)):
x = long_str[i]
if x == 'v' and short_str[j-1] == 'v':
short_str = short_str[:j-1] + 'w'
j = j -1
else:
short_str = short_str + x
j = j +1
return short_str
print len(longer("avwvb"))
print len(shorter("avwvb"))