Maximum Number in Mountain Sequence - python-3.x

Given a mountain sequence of n integers which increase firstly and then decrease, find the mountain top.
Example
Given nums = [1, 2, 4, 8, 6, 3] return 8
Given nums = [10, 9, 8, 7], return 10
class Solution:
"""
#param nums: a mountain sequence which increase firstly and then decrease
#return: then mountain top
"""
def mountainSequence(self, nums):
# write your code here
if nums == []:
return None
if len(nums) <= 1:
return nums[0]
elif len(nums) <= 2:
return max(nums[0], nums[1])
for i in range(len(nums) -2):
if nums[i] >= nums[i + 1]:
return nums[i]
return nums[-1]
it stuck at [3,5,3]. Based on my analysis, it went wrong after running the for loop. But I cannot figure it out why the for loop failed.

this should be more efficient than your approach. it is a binary search customized for your use-case:
def top(lst):
low = 0
high = len(lst)
while low != high:
i = (high+low)//2
if lst[i] < lst[i+1]:
low = i+1
else:
high = i
return low
it starts in the middle of the list and checks if the series is still increasing there. if it is it sets low and will ignore all indices below low for the rest of the algorithm. if the series decreases already, high is set to the current index and all the elements above are ignored. and so on... when high == low the algorithm terminates.
if you have two or more of the same elements at the maximum of your list (a plateau) the algorithm will not even terminate.
and i skipped the tests for empty lists or lists of length 1.

This will get all triplets from your input, isolate all that are higher in the middle then left or right and return the one that is highest overall:
def get_mountain_top(seq):
triplets = zip(seq, seq[1:], seq[2:])
tops = list(filter(lambda x: x[0] < x[1] > x[2], triplets))
if tops:
# max not allowed, leverage sorted
return sorted(tops, key = lambda x:x[1])[-1]
# return max(tops,key = lambda x:x[1])
return None
print(get_mountain_top([1,2,3,4,3,2,3,4,5,6,7,6,5]))
print(get_mountain_top([1,1,1]))
Output:
(6,7,6)
None
It does not handle plateaus.
Doku:
zip(), filter() and max()

Related

How to add each element in list to another element of same list in less time?

Input : l1 = [1,2,3,4,5,6]
Output : [7, 8, 9, 10, 11, 11]
To find the maximum sum of each pair of all elements in a list.
In general, i have to add each element in list to another element (not to itself).
Below is the code what i tried. I know this is complexity of (n^2)
Any better way to reduce complexity (can be both time and space) ?
Any better approach (may be with some modules or with just single for loop) ?
list l1 need not to be in sorted.
l2=[]
l3=[]
for i in range(len(l1)):
for j in range(len(l1)):
if i!=j:
l2.append(l1[i]+l1[j])
l3.append(max(l2))
l2.clear()
print(l3)
[7, 8, 9, 10, 11, 11]
Update:
Submitted this solution in hackerrank, but it fails for few cases.
Reason for failure is TimeLimitExceed (TLE). I assume, it's failing because of large numbers.
**Constraints:**
n = size_of_list
1<= n <= 4*10^4
1<= l1[i] <= 1024
1<= i <= n
1<= j <= n
j != i
Is it because of time-complexity, failing to handle these scenarios in above snippet ?
you can do something like this:
l1 = [1,2,3,4,5,6]
l2=[]
for i in range(len(l1)):
for j in range(i+1,len(l1)):
l2.append(l1[i]+l1[j])
l3=set(l2)
l2=list(l3)
print(l2)
output:
[3, 4, 5, 6, 7, 8, 9, 10, 11]
Sorting your list before processing it also helps.
Let me know if i have made any mistake.
You can do this in O(n).
The basic idea is to get the indices of the maximum element and the second maximum element in the list. Then for each element in the list, append the element + max_element, if the element is not the max_element. Otherwise, append the max_element + second_max_element.
I used the get_first_second_max_index to get the indices of the maximum element and the second maximum element because there might be identical elements in the list.
The code should look like this:
def get_first_second_max_index(nums):
if len(nums) < 2:
return None, None
first_max_index = 0 if nums[0] > nums[1] else 1
second_max_index = 0 if nums[0] <= nums[1] else 1
for index in range(2, len(nums)):
if nums[index] > nums[first_max_index]:
first_max_index, second_max_index = index, first_max_index
elif nums[index] > nums[second_max_index]:
second_max_index = index
return (first_max_index, second_max_index)
def max_sum_pair(nums):
res = []
if len(nums) >= 2:
first_max_index, second_max_index = get_first_second_max_index(nums)
for index in range(len(nums)):
if index == first_max_index:
res.append(nums[index] + nums[second_max_index])
else:
res.append(nums[index] + nums[first_max_index])
return res
nums = [1,2,3,4,5,6]
res = max_sum_pair(nums)
print(res)
For starters, we can use sorting to our advantage. The Python sorting method, sorted, operates in O(n log n) time. (See this question: What is the complexity of this python sort method?)
Once our numbers are sorted, the maximum sums are trivial. The maximum for a number is simply that number added to the last element in the sorted list or, if the number is the maximum element, the second to last element. Rewriting your code we could obtain:
l3 = []
l1 = sorted(l1)
for i in range(len(l1)):
if i + 1 == len(l1):
l3.append(l1[i] + l1[i - 1])
else:
l3.append(l1[i] + l1[-1])
print(l3)
I hope this helps. Let me know if I've misunderstood your question.

Function that fills in missing numbers to create complete sequence

I'm trying to create a function that will fill in any missing numbers in between two numbers in a list. The original list must be altered and cannot be new.
For example: [13,15,20] would return [13,14,15,16,17,18,19,20].
Note that I am not allowed to use a range function.
Here's my code:
def complete(list1):
i= 0
if len(list1) > 1:
for number in list1:
if number - list1[i+1] != -1:
number += 1
list1.insert(i + 1, number)
i += 1
return list1
else:
return list1
I got a "list index out of range" error.
Here is the source of your error:
...
for number in list1:
if number - list1[i+1] != -1:
...
i += 1
Basically, there comes a point (that point being the last number in list1) when i+1 gets you out of bounds and you are not doing anything to prevent that from happening. Indexing is tricky like that, so I would like to offer an indexing-free (well, almost) approach. By the way, from your comment to Bonfire's answer, I see that the task is to change original lists in-place. While mutating arguments is considered a very poor coding practice these days, here is a relatively efficient way of doing that:
import typing as t
def complete_sequence(partial: t.List[int]) -> t.List[int]:
# edge case
if len(partial) < 2:
return partial
# a lookup table for numbers we already have
observed = set(partial)
# append numbers we don't have
start = partial[0]
stop = partial[-1]
num = start + 1
while num < stop:
if not num in observed:
partial.append(num)
num += 1
# in-place sort
partial.sort()
return partial
As you see, instead of inserting values between existing numbers (paying O(n) time for each insertion), we can simply append everything (O(1) per insertion) and sort. This not only simplifies the logic (we no longer have to track those pesky indices), but also reduces computational time-complexity from O(n^2) to O(n*log(n)).
To achieve what you want to do I have made some changes to the logic:
def complete(list1):
if len(list1) < 2 : return list1
num = list1[0]
i = -1
while num < list1[-1]:
num += 1
i += 1
if num in list1: continue
if i < len(list1) - 1:
list1.insert(i + 1, num)
else:
list1.append(num)
return list1
print(complete([13, 14, 20]))
# [13, 14, 15, 16, 17, 18, 19, 20]
print(complete([13, 14, 15]))
# [13, 14, 15]

How does a value from a previous level in recursion go back up?

I'm trying to make a recursive function to get minimum number of coins for change, but I think my understanding of what each layer's return value in the stack is wrong. What I want is for the coin amount to be passed back up when the recursion reaches it's base case, but looking at the debugger, the coin case decreases on the way back up.
I've already tried to look at solutions for this problem, but they all seem to use dynamic programming, and I know that it's more efficient in terms of complexity, but I want to figure out how to do the recursion before adding the dynamic programming portion
def min_coin(coin_list, value, counter = 0):
if value == 0:
return 0
else:
for coin in coin_list:
if coin <= value:
sub_result = value - coin
min_coin(coin_list, sub_result, counter)
counter +=1
return counter
#counter += 1 #should add returning out from,
#return counter
coin_list = [5, 2, 1]
value = 8
print(min_coin(coin_list,value))
I want an output of 3, but the actual output is 1 no matter the value
You need to increment the counter before calling min_coin().
def min_coin(coin_list, value, counter = 0):
if value == 0:
return counter
else:
for coin in coin_list:
if coin <= value:
sub_result = value - coin
return min_coin(coin_list, sub_result, counter+1)
You can solve your task without recursion, answer from geekforcoders
# Python 3 program to find minimum
# number of denominations
def findMin(V):
# All denominations of Indian Currency
deno = [1, 2, 5, 10, 20, 50,
100, 500, 1000]
n = len(deno)
# Initialize Result
ans = []
# Traverse through all denomination
i = n - 1
while(i >= 0):
# Find denominations
while (V >= deno[i]):
V -= deno[i]
ans.append(deno[i])
i -= 1
# Print result
for i in range(len(ans)):
print(ans[i], end = " ")
# Driver Code
if __name__ == '__main__':
n = 93
print("Following is minimal number",
"of change for", n, ": ", end = "")
findMin(n)

Binary Search implementation in Python

I am trying to implement a solution using binary search. I have a list of numbers
list = [1, 2, 3, 4, 6]
value to be searched = 2
I have written something like this
def searchBinary(list, sval):
low = 0
high = len(list)
while low < high:
mid = low + math.floor((high - low) / 2)
if list[mid] == sval:
print("found : ", sval)
elif l2s[mid] > sval:
high = mid - 1
else:
low = mid + 1
but when I am trying to implement this, I am getting an error like: index out of range. Please help in identifying the issue.
A few things.
Your naming is inconsistent. Also, do not use list as a variable name, you're shadowing the global builtin.
The stopping condition is while low <= high. This is important.
You do not break when you find a value. This will result in infinite recursion.
def searchBinary(l2s, sval): # do not use 'list' as a variable
low = 0
high = len(l2s)
while low <= high: # this is the main issue. As long as low is not greater than high, the while loop must run
mid = (high + low) // 2
if l2s[mid] == sval:
print("found : ", sval)
return
elif l2s[mid] > sval:
high = mid - 1
else:
low = mid + 1
And now,
list_ = [1, 2, 3, 4, 6]
searchBinary(list_, 2)
Output:
found : 2
UPDATE high = len(lst) - 1 per comments below.
Three issues:
You used l2s instead of list (the actual name of the parameter).
Your while condition should be low <= high, not low < high.
You should presumably return the index when the value is found, or None (or perhaps -1?) if it's not found.
A couple other small changes I made:
It's a bad idea to hide the built-in list. I renamed the parameter to lst, which is commonly used in Python in this situation.
mid = (low + high) // 2 is a simpler form of finding the midpoint.
Python convention is to use snake_case, not camelCase, so I renamed the function.
Fixed code:
def binary_search(lst, sval):
low = 0
high = len(lst) - 1
while low <= high:
mid = (low + high) // 2
if lst[mid] == sval:
return mid
elif lst[mid] > sval:
high = mid - 1
else:
low = mid + 1
return None
print(binary_search([1, 2, 3, 4, 6], 2)) # 1

Prime factorization of a number

I'm trying to write a program to find all the prime factors of a given number, and tried the following:
def factors(nr):
i = 2
factors = []
while i<nr:
if (nr%i)==0:
factors.append(i)
nr = nr/i
else:
i = i+1
return factors
My idea is the following. Start with i = 2, while i < the number, check if the module of the number and i = 0. If this is the case, add i to a list, and run the algorithm again, but now with the new number. However, my algorithm doesn't work. Any idea why?
I know that several right answers are posted on the site, but I would like to know why my program is incorrect.
Update
So if I let the programm run for example:
factors(38), yields [2].
factors(25), yields [5].
So it stops after it has added one number to the list.
The simplest change you can make to fix your problem is to change your while loop condition:
def factors(nr):
i = 2
factors = []
while i <= nr:
if (nr % i) == 0:
factors.append(i)
nr = nr / i
else:
i = i + 1
return factors
print factors(8)
print factors(9)
print factors(10)
Output
[2, 2, 2]
[3, 3]
[2, 5]
def ba(n):
pfa=[]
y=n
for i in range(n):
if (i!=0 and i!=1):
while (y%i==0):
pfa.append(i)
y=y/i
print(pfa)

Resources