I'm trying to make a recursive function, which calculates the biggest sub-palindrome.
For example the biggest sub.Pal. for "character" is "carac".
So far I've achieved my goal but only with a global variable "length" where i'm adding my values, but it would be nice if someone could show me how to do this with only recursive calls. I first tried to give the function a second parameter (length=0) and to add the value to it when i'm calling the function,but i'm not getting it to work properly.
Here's my Code:
length = 0
def subpalindrom(s):
global length
if len(s) == 1:
length += 1
return True, length
if len(s) == 0:
return True, length
elif s[0] != s[-1]:
for i in range(len(s) - 1, int(len(s) / 2) - 1, -1): # search right half, if there is smth. equal
if s[0] == s[i]:
length += 2
return subpalindrom(s[1:i]) # if smth. is equal slice it, add length
elif i == int(len(s) / 2):
# if index i is at half of the string and nothing was found, continue with next val on left half
return subpalindrom(s[1:])
else:
length += 2
return subpalindrom(s[1:-1])
print(subpalindrom("character"))
And if anyone could tell me how i can see which time complexity this function has it would be more than great. I would say that it is O(log n) but it's just a guess.
Edit: T(n) = T(n-2) + n/2 ?
T(n-2) for recursive calls (because we slice 2 elements away) and + n/2 because of the for loop?
Thank you for your Time !
Sry for the late share,but if anyone is interested, here is how i handled it:
def subpalindrom(l, r, w):
if l == r:
return 1
if l > r:
return 0
if w[l] == w[r]:
return 2 + subpalindrom(l + 1, r - 1, w)
else:
return max(subpalindrom(l + 1, r, w), subpalindrom(l, r - 1, w))
print(subpalindrom(0, len("character")-1, "character"))
Related
In python 3 I am trying to write a function that takes two natural numbers 𝑘 and 𝑛 as inputs and returns the set of all tuples of size 𝑘 that sum to 𝑛.
I have built the following functions:
def get_tuples(length, total):
if length == 1:
yield (total,)
return
for i in range(total + 1):
for t in get_tuples(length - 1, total - i):
yield (i,) + t
which with, e.g., list(get_tuples(2, 8)) returns the correct results, and:
def get_tuples(length, total):
if length == 1:
return [(total,)]
comp = []
for i in range(total + 1):
for t in get_tuples(length - 1, total - i):
comp.append((i,) + t)
return comp
which however returns a wrong result (i.e. a single tuple).
Can anybody please explain why, and how to fix the second function?
Simply place the return one indent out:
def get_tuples(length, total):
if length == 1:
return [(total,)]
comp = []
for i in range(total + 1):
for t in get_tuples(length - 1, total - i):
comp.append((i,) + t)
return comp
Edit: Make sure you understand why
owninggreendragsdude's answer is the right one, because it shows exactly the one thing you need to change in your code to make it work.
However, if you were wondering how to get rid of the recursion and make the code faster at the same time, here's a solution:
def get_tuples_optimized(length, total):
comp = []
# Stack of partial tuples to process, initialized with an empty tuple
todo = [(total, tuple())]
# Loop as long as we have partial tuples on our stack
while todo:
# Take the next partial tuple
amount_left, partial_tuple = todo.pop()
if len(partial_tuple) == length - 1:
# Put all that is left as the last element
comp.append(partial_tuple + (amount_left,))
else:
# Add all possible extensions-by-one to our stack
for i in range(amount_left + 1):
extended_tuple = partial_tuple + (i,)
todo.append((amount_left - i, extended_tuple))
return comp
Here you go:
def get_tuples(length, total):
if length == 1:
return [(total,)]
comp = []
for i in range(total + 1):
for t in get_tuples(length - 1, total - i):
comp.append((i,) + t)
return comp
Take the return statement out of the loop.
I am working on a python algorithm to find the most frequent element in the list.
def GetFrequency(a, element):
return sum([1 for x in a if x == element])
def GetMajorityElement(a):
n = len(a)
if n == 1:
return a[0]
k = n // 2
elemlsub = GetMajorityElement(a[:k])
elemrsub = GetMajorityElement(a[k:])
if elemlsub == elemrsub:
return elemlsub
lcount = GetFrequency(a, elemlsub)
rcount = GetFrequency(a, elemrsub)
if lcount > k:
return elemlsub
elif rcount > k:
return elemrsub
else:
return None
I tried some test cases. Some of them are passed, but some of them fails.
For example, [1,2,1,3,4] this should return 1, buit I get None.
The implementation follows the pseudocode here:
http://users.eecs.northwestern.edu/~dda902/336/hw4-sol.pdf
The pseudocode finds the majority item and needs to be at least half. I only want to find the majority item.
Can I get some help?
Thanks!
I wrote an iterative version instead of the recursive one you're using in case you wanted something similar.
def GetFrequency(array):
majority = int(len(array)/2)
result_dict = {}
while array:
array_item = array.pop()
if result_dict.get(array_item):
result_dict[array_item] += 1
else:
result_dict[array_item] = 1
if result_dict[array_item] > majority:
return array_item
return max(result_dict, key=result_dict.get)
This will iterate through the array and return the value as soon as one hits more than 50% of the total (being a majority). Otherwise it goes through the entire array and returns the value with the greatest frequency.
def majority_element(a):
return max([(a.count(elem), elem) for elem in set(a)])[1]
EDIT
If there is a tie, the biggest value is returned. E.g: a = [1,1,2,2] returns 2. Might not be what you want but that could be changed.
EDIT 2
The pseudocode you gave divided into arrays 1 to k included, k + 1 to n. Your code does 1 to k - 1, k to end, not sure if it changes much though ? If you want to respect the algorithm you gave, you should do:
elemlsub = GetMajorityElement(a[:k+1]) # this slice is indices 0 to k
elemrsub = GetMajorityElement(a[k+1:]) # this one is k + 1 to n.
Also still according to your provided pseudocode, lcount and rcount should be compared to k + 1, not k:
if lcount > k + 1:
return elemlsub
elif rcount > k + 1:
return elemrsub
else:
return None
EDIT 3
Some people in the comments highligted that provided pseudocode solves not for the most frequent, but for the item which is present more that 50% of occurences. So indeed your output for your example is correct. There is a good chance that your code already works as is.
EDIT 4
If you want to return None when there is a tie, I suggest this:
def majority_element(a):
n = len(a)
if n == 1:
return a[0]
if n == 0:
return None
sorted_counts = sorted([(a.count(elem), elem) for elem in set(a)], key=lambda x: x[0])
if len(sorted_counts) > 1 and sorted_counts[-1][0] == sorted_counts[-2][0]:
return None
return sorted_counts[-1][1]
I am currently working on this code and the only thing that seems to work is the "no solution." Also it seems that the code has an infinite loop and I can't seem to figure out how to solve it. If someone could point out my mistake it would be appreciated.
def greedySum(L, s):
""" input: s, positive integer, what the sum should add up to
L, list of unique positive integers sorted in descending order
Use the greedy approach where you find the largest multiplier for
the largest value in L then for the second largest, and so on to
solve the equation s = L[0]*m_0 + L[1]*m_1 + ... + L[n-1]*m_(n-1)
return: the sum of the multipliers or "no solution" if greedy approach does
not yield a set of multipliers such that the equation sums to 's'
"""
if len(L) == 0:
return "no solution"
sum_total = (0, ())
elif L[0] > k:
sum_total = greed(L[1:], k)
else:
no_number = L[0]
value_included, take = greed(L, k - L[0])
value_included += 1
no_value, no_take = greed(L[1:], k)
if k >= 0:
sum_total = (value_included, take + (no_number,))
else:
sum_total = (value_included, take + (no_number,))
return sum_total
sum_multiplier = greed(L, s)
return "no solution" if sum(sum_multiplier[1]) != s else sum_multiplier[0]
Second method:
def greedySum(L, s):
answer = []
try:
while (s >= L[0]):
total = s// L[0]
s -= (total * L[0])
answer.append(total)
L = L[1:]
return(str(answer)[1:-1])
except:
return("no solution")
Here is something that works:
def greedySum(L, s):
multiplier_sum = 0
for l in L:
(quot,rem) = divmod(s,l) # see how many 'l's you can fit in 's'
multiplier_sum += quot # add that number to the multiplier_sum
s = rem # update the remaining amount
# If at the end and s is 0, return the multiplier_sum
# Otherwise, signal that there is no solution
return multiplier_sum if s == 0 else "no solution"
I would offer more help on what is wrong with your code, but that is for the moment a moving target - you keep changing it!
>>> greedySum([4,2],8)
2
>>> greedySum([4,2],9)
'no solution'
>>> greedySum([4,2,1],9)
3
I'm having trouble getting the right output on my "Majority Element" divide and conquer algorithm implementation in Python 3.
This should be relatively correct; however, it would still appear that I'm missing something or it is slightly off and I cannot figure out why that is.
I've tried some debugging statement and different things. It looks like on the particular case listed in the comment above the code, it's resolving -1 for "left_m" and 941795895 for "right_m" when it does the recursive calls. When it compares the element at each index to those variables, the counter will obviously never increment.
Am I going about this the wrong way? Any help would be greatly appreciated.
Thanks.
# Input:
# 10
# 2 124554847 2 941795895 2 2 2 2 792755190 756617003
# Your output:
# 0
#
# Correct output:
# 1
def get_majority_element(a, left, right):
if left == right:
return -1
if left + 1 == right:
return a[left]
left_m = get_majority_element(a, left, (left + right - 1)//2)
right_m = get_majority_element(a, (left + right - 1)//2 + 1, right)
left_count = 0
for i in range(0, right):
if a[i] == left_m:
left_count += 1
if left_count > len(a)//2:
return left_m
right_count = 0
for i in range(0, right):
if a[i] == right_m:
right_count += 1
if right_count > len(a)//2:
return right_m
return -1
if __name__ == '__main__':
input = sys.stdin.read()
n, *a = list(map(int, input.split()))
if get_majority_element(a, 0, n) != -1:
print(1)
else:
print(0)
When counting the appearance of left and right major elements, your loops go over the range(0, right). Instead, they should be going over the range(left, right). Starting from 0 may, and will cause returning incorrect major elements in the smaller subproblems.
Also, in addition to the problem of having incorrect starting indices in ranges your for loops cover, you seem to have a problem in your recursive call arguments, probably due to your intuition causing you to overlook some details. Throughout the get_majority_element function, you treat parameter right to be the first index that is not in the list, as opposed to right being the index of the rightmost element in the list.
However, in your first recursive call, you give the third argument as if it is the last element included in that list. If right is the index of the first element not in that list, it should actually be the same with the second parameter of the second recursive call you're making in the following line. So, the third argument of the first recursive call you're making is less than it should be, by 1, causing you to overlook 1 element each time you recursively go down.
Thirdly, you have an error in the if statements following the for loops, similar to the problem you had with loop ranges. You are dividing the occurances of the element for all len(a) elements, although you should only care about the subproblem you are currently working on. So, you should divide it by the number of elements in that subproblem, rather than len(a). (i.e. (right - left)//2)
You can find the working code below, and look here in order to observe it's execution.
def get_majority_element(a, left, right):
if left == right:
return -1
if left + 1 == right:
return a[left]
left_m = get_majority_element(a, left, (left + right - 1)//2 + 1)
right_m = get_majority_element(a, (left + right - 1)//2 + 1, right)
left_count = 0
for i in range(left, right):
if a[i] == left_m:
left_count += 1
if left_count > (right-left)//2:
return left_m
right_count = 0
for i in range(left, right):
if a[i] == right_m:
right_count += 1
if right_count > (right-left)//2:
return right_m
return -1
if __name__ == '__main__':
input = sys.stdin.read()
n, *a = list(map(int, input.split()))
print("n=" + str(n))
if get_majority_element(a, 0, len(a)) != -1:
print(1)
else:
print(0)
I am trying to use Boyers and Moore's algorithm to find the majority element among a list. I am using a inbuilt function, count; so, if the majority element is greater than half size of the list then it gives output of 1, otherwise 0. You can find more in this link about Boyers and Moore's Algorithm on finding majority Algorithm information here
# Uses python3
import sys
def get_majority_element(a,n):
maximum = a[0]
amount = 1
for i in (a[1:]):
if not maximum == i:
if amount >= 1:
amount = amount - 1
else:
maximum = i
amount = 1
else:
amount = amount + 1
output = a.count(maximum)
if output > n//2:
return 1
return 0
if __name__ == '__main__':
input = sys.stdin.read()
n, *a = list(map(int, input.split()))
print (get_majority_element(a,n))
Okay. I give up. I've been trying to implement the median of medians algorithm but I am continually given the wrong result. I know there is a lot of code below, but I can't find my error, and each chunk of code has a fairly process design. Quicksort is what I use to sort the medians I get from the median of medians pivot selection. Should be a straightforward quicksort implementation. getMean simply returns the mean of a given list.
getPivot is what I use to select the pivot. It runs through the list, taking 5 integers at a time, finding the mean of those integers, placing that mean into a list c, then finding the median of c. That is the pivot I use for the dSelect algorithm.
The dSelect algorithm is simple in theory. The base case returns an item when the list is 1 item long. Otherwise, much like in quickSort, I iterate over the list. If the number I am currently on, j, is less than the pivot, I move it to the left of the list, i, and increment i. If it is larger, I move it to the right of the list, i + 1, and do not increment i. After this loops through the entire list, I should have the pivot in its proper index, and print statements indicate that I do. At this point, I recurse to the left or the right depending on whether the pivot is greater than or less than the position I am trying to find.
I am not sure what other print statements to test at this point, so I'm turning to anyone dedicated enough to take a stab at this code. I know there are related topics, I know I could do more print statements, but believe me, I've tried. What should be a simple algo has got me quite stumped.
def quickSort(m, left, right):
if right - left <= 1:
return m
pivot = m[left]
i = left + 1
j = left + 1
for j in range(j, right):
if m[j] < pivot:
m[j], m[i] = m[i], m[j]
i += 1
elif m[j] == pivot:
m[j], m[i] = m[i], m[j]
print m
m[left], m[i-1] = m[i-1], m[left]
m = quickSort(m, left, i-1)
m = quickSort(m, i, right)
print m
return m
def getMedian(list):
length = len(list)
if length <= 1:
return list[0]
elif length % 2 == 0:
i = length/2
return list[i]
else:
i = (length + 1)/2
return list[i]
def getPivot(m):
c = []
i = 0
while i <= len(m) - 1:
tempList = []
j = 0
while j < 5 and i <= len(m) - 1:
tempList.append(m[i])
i = i + 1
j = j + 1
tempList = quickSort(tempList, 0, len(tempList) - 1)
c.append(getMedian(tempList))
c = quickSort(c, 0, len(c) - 1)
medianOfMedians = getMedian(c)
return medianOfMedians
def dSelect(m, position):
pivot = getPivot(m)
i = 0
j = 0
if len(m) <= 1:
return m[0]
for j in range(0, len(m)):
if m[j] < pivot:
m[j], m[i] = m[i], m[j]
i += 1
elif m[j] == pivot:
m[j], m[i] = m[i], m[j]
print "i: " + str(i)
print "j: " + str(j)
print "index of pivot: " + str(m.index(pivot))
print "pivot: " + str(pivot) + " list: " + str(m)
if m.index(pivot) == position:
return pivot
elif m.index(pivot) > position:
return dSelect(m[0:i], position)
else:
return dSelect(m[i:], position - i)
The biggest issue is with this line here:
i = (length + 1)/2
if list = [1, 2, 3, 4, 5, 6, 7] the answer should be 4 which is list[3]. Your version looks like the following:
i = (7 + 1) / 2
and so i is equal to 4 instead of 3. Similar problem with the even length list part although that shouldn't be as big of an issue.