How to turn the duplicate part in my code to a checking function? - python-3.x

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

Related

658. Find K Closest Elements - for loop 'comp' comparison variable not updating as expected

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]

What am I doing wrong with this code for hackerrank?

I have been coding this problem for HackerRank and I ran into so many problems. The problem is called "Plus Minus" and I am doing it in Python 3. The directions are on https://www.hackerrank.com/challenges/plus-minus/problem. I tried so many things and it says that "there is no response on stdout". I guess a none-type is being returned. Here is the code.:
def plusMinus(arr):
p = 0
neg = 0
z = arr.count(0)
no = 0
for num in range(n):
if arr[num] < 0:
neg+=1
if arr[num] > 0:
p+=1
else:
no += 1
continue
return p/n
The following are the issues:
1) variable n, which represents length of the array, needs to be passed to the function plusMinus
2) No need to maintain the extra variable no, as you have already calculated the zero count. Therefore, we can eliminate the extra else condition.
3) No need to use continue statement, as there is no code after the statement.
4) The function needs to print the values instead of returning.
Have a look at the following code with proper naming of variables for easy understanding:
def plusMinus(arr, n):
positive_count = 0
negative_count = 0
zero_count = arr.count(0)
for num in range(n):
if arr[num] < 0:
negative_count += 1
if arr[num] > 0:
positive_count += 1
print(positive_count/n)
print(negative_count/n)
print(zero_count/n)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr, n)
The 6 decimals at the end are needed too :
Positive_Values = 0
Zeros = 0
Negative_Values = 0
n = int(input())
array = list(map(int,input().split()))
if len(array) != n:
print(f"Error, the list only has {len(array)} numbers out of {n}")
else:
for i in range(0,n):
if array[i] == 0:
Zeros +=1
elif array[i] > 0:
Positive_Values += 1
else:
Negative_Values += 1
Proportion_Positive_Values = Positive_Values / n
Proportion_Of_Zeros = Zeros / n
Proportion_Negative_Values = Negative_Values / n
print('{:.6f}'.format(Proportion_Positive_Values))
print('{:.6f}'.format(Proportion_Negative_Values))
print('{:.6f}'.format(Proportion_Of_Zeros))

solve n which is an integer above 0 in python

This code works but it is not very efficient is there any help on a faster code in python to find n knowing that n is an integer above 0 and that n has no upper bound, how(x) will return you 1 if x>n, 0 if x = n, and -1 if x
def how(x):
if x > n:
return 1
elif x < n:
return -1
else:
return 0
def find(how):
if how(1) == 1:
return 1
x = 2
while how(x) != 1:
x = x**x
v = x
while how(x) != 0:
if how(x) == 1:
v = x
x = (x+1)//2
else:
x += (v-x+1)//2
return x
Rebecca, I've added some print statements so you can see where goes what wrong. As Patrick Artner said... its a bit confusing which way to go so I've tried to clean-up some things that enable you to continue exploring comparison of two variables against each other (and fake error catching (0).
Lets start and remove the confusing lingo and produce something workable code. With current below script it runs and with value = 1, reference = 1 you get the below print result in a continues loop until YOU stop the script manually:
v1 = n: error
loop1 1
def selector(v1, n):
if v1 > n:
print 'v1 > n', v1, n
return 1
elif v1 < n:
print 'v1 < n', v1, n
return -1
else:
print 'v1 == n: error'
return 0
def find(value, reference):
if selector(value, reference) == 1:
return 1
while selector(value, reference) != 1:
x = value**value
print 'loop1', x
v = x
while selector(value, reference) != 0:
print 'loop2'
if selector(value, reference) == 1:
v = value
x = (value+1)/2
print 'loop2-if', v, x
else:
x += (v-(value+1))/2
print 'loop2-else', x
print ' Almost done...'
return x
if __name__ == '__main__':
n = 1
print find(1, 1)
Happy exploring,....

List Index out of range, trying to get the [-1] position

I've tested to see if the list is empty and I'm sure it's not empty. So why this error continues?
The code is to find the smallest amount of factorial to a sum is equal to N.
def fat(n):
if n == 0 or n == 1:
return 1
else:
return n * fat(n - 1)
n = int(input())
ns = [x+1 for x in range(n)]
listaFat = []
l = []
for x in ns:
if fat(x) < n:
listaFat.append(x)
maior = max(listaFat)
listaFat.remove(maior)
print(listaFat)
print(len(listaFat))
while (fat(listaFat[-1]) + fat(maior)) < n:
l.append(listaFat[-1])
if len(listaFat) > 0:
listaFat.remove(listaFat[-1])
continue
else: break
print(l)
print(listaFat)

Puzzler solver program: How many different solutions are there to (1/a)+(1/b)+(1/c)+(1/d)+(1/e)+(1/f)+(1/g) = 1?

I wrote the python code below that solves and prints each possible solution for anything under 6 unit fractions, but given how I programmed it, it takes infinitely long to check for 7 fractions. Any ideas on how to modify the code to find all the possible solutions more efficienty?
import sys
from fractions import Fraction
import os
#myfile = open('7fractions.txt', 'w')
max = 7 #>2 #THIS VARIABLE DECIDES HOW MANY FRACTIONS ARE ALLOWED
A = [0] * max
A[0] = 1
def printList(A):
return str(A).strip('[]')
def sumList(A):
sum = 0
for i in A:
if i != 0:
sum += Fraction(1, i)
return sum
def sumTest(A):
sum = 0
v = 0
for i in range(0, len(A)):
if A[i] == 0 and v == 0:
v = Fraction(1,A[i-1])
if v != 0:
sum += v
else:
sum += Fraction(1, A[i])
return sum
def solve(n, A):
if n == max - 2:
while (sumTest(A) > 1):
print(A)
if sumList(A) < 1:
e = 1 - sumList(A)
if e.numerator == 1 and e.denominator>A[n-1]:
A[n+1] = e.denominator
#myfile.write(printList(A) + '\n')
print(A)
A[n+1] = 0
A[n] += 1
else:
while (sumTest(A) > 1):
if sumList(A) < 1:
A[n+1] = A[n] + 1
solve(n+1, A)
A[n+1] = 0
A[n] += 1
#execute
solve(0, A)

Resources