Array Of Number And Finding SubArray - python

Input = 5 4 5 5 6 7 8 8 8 7 6
In This Input, The longest subarray is [6, 10] where maximum=8 and minimum are 7 and difference is 1. Difference Should be Less And Equal To 1.
a subarray such that the difference between the minimum and the maximum value in that range is at most 1
Output Should Be 7 8 8 8 7
Please Suggest Me How To Code?
#THIS IS MY CODE
n = int(input())
data = []
for _ in range(n):
data.append(int(input()))
for i in range(0,n):
maxi = max(data[i+1:])
mini = min(data[i+1:])
diff = maxi - mini
if diff <= 1:
print(data[i:])
l = len(data[i:])
print(l)
break

Here is a naive solution. Make every possible sub-list and filter out those that meet your condition.
import numpy as np
a = [5,4,5,5,6,7,8,8,8,7,6]
max_diff = 1
sub_arrays = [x for x in [a[i:j] for i in range(len(a)) for j in range(i+1, len(a))] if (max(x)-min(x) <= max_diff)]
max_sub_array = sub_arrays[np.argmax([len(sa) for sa in sub_arrays])]
On your sample input, the output is:
[7, 8, 8, 8, 7]

Related

Finding the total number of elements in list, comparisons and swaps needed to sort the numbers list using selection sort

QUESTION:
Consider the incomplete function below:
def my_selection_sort(a_list):
for I in range(len(a)_list - 1, 0, -1):
...
Complete the my_selection_sort() function above so that it returns the total number of elements, comparisons and swaps needed to sort the numbers list. The function must return these 3 values as a tuple.
Consider the following:
A list with reverse order numbers: # of elements = 8, # of comparisons = 28 (1 + 2 + 3 + 4 + 5 + 6 + 7), # of swaps = 7
A list with sorted order numbers: # of elements = 8, # of comparisons = 28 (1 + 2 + 3 + 4 + 5 + 6 + 7), # of swaps = 7
MY CODE:
def my_selection_sort(a_list):
length = len(a_list)
swaps = 0
comparisons = 0
for i in range(len(a_list)-1,0,-1):
lowest_value_index = i
for j in range(len(a_list)-1,i+1,-1):
comparisons += 1
if a_list[j] < a_list[lowest_value_index]:
lowest_value_index = j
swaps += 1
a_list[i],a_list[lowest_value_index] = a_list[lowest_value_index],a_list[i]
return (length,comparisons,swaps)
TEST:
Test 1:
nums = [6]
res = my_selection_sort(nums)
print('Length: {} Comparisons: {} Swaps: {}'.format(res[0], res[1], res[2]))
Test 2:
nums = [70, 48, 54, 79, 33]
res = my_selection_sort(nums)
print('Length: {} Comparisons: {} Swaps: {}'.format(res[0], res[1], res[2]))
EXPECTED OUTPUT:
Test 1:
Length: 1 Comparisons: 0 Swaps: 0
Test 2:
Length: 5 Comparisons: 10 Swaps: 4
ACTUAL OUTPUT:
Test 1:
Length: 1 Comparisons: 0 Swaps: 0
Test 2:
Length: 5 Comparisons: 3 Swaps: 4
A different and simple strategy. You don't need to even apply the for loops.
In selection sort, the comparisons and swapping's are fixed always. There are mathematical formulas for both that you can implement in python:
Assume length of the list = n
Total no of comparisons: Summation from 1 till n-1
Total number of swaps = n-1
Special Case : n = 0 and n=1 (You can check for this in if statements)
Other Cases : n > 1 ,
for example n = 8 ,
Comparisons = 1+2+3+4+5+6+7 = 28,
Swaps = 8-1 = 7.
for example n = 5,
Comparisons = 1+2+3+4 = 10,
Swaps = 5-1 = 4.

smallest difference of a sequence of a list

I am new to python. I am working on program to find the smallest difference of sequence of element. for example I have a input A=[7,8,9],M=3. Difference of all elements of sequence should be in this form S=(|7-7|,|7-8|,|7-9|,|8-7|,|8-8|,|8-9|,|9-7|,|9-8|,|9-9|).S=[0,1,2,1,0,1,2,1,0]. we get 9 different element in list. So the output of M smallest element of s is 0. since 0 is 3 smallest element. Does anyone know what I am doing wrong
enter code here
F=[]
A = [7, 8, 9]
M = 3
S=0
for i in range(len(A)):
for j in range(len(A)):
S = S + (abs(A[i] - A[j]))
t = F.append(S)
t.sort()
for k in range(len(t)):
if k == M:
break
print(t[k])
The right code is here:
A = [7, 8, 9]
M = 3
S=[] #
for i in range(len(A)):
for j in range(len(A)):
S.append(abs(A[i] - A[j]))
# t = F.append(S) # t is not defined before
S.sort()
print(S[M-1]) # S is sorted
Ask me if you have any questions.
Here, you can try this:
x=[7,8,9]
y=[abs(j-k) for j in x for k in x]
print(y)
What you are doing is basically a nested loop.
Here is how it goes:
for i in x:
for j in x:
#==== This is what your program needs =====
i=7
|__j=7
|__j=8
|__j=9
i=8
|__j=7
|__j=8
|__j=9
i=9
|__j=7
|__j=8
|__j=9
Now if you print the how it looks like:
x=[7,8,9]
for i in x:
print(f'The main number is {i}.')
for j in x:
print(f"{i} - {j} = {abs(i-j)}")
And that does exactly what you need
The main number is 7.
7 - 7 = 0
7 - 8 = 1
7 - 9 = 2
The main number is 8.
8 - 7 = 1
8 - 8 = 0
8 - 9 = 1
The main number is 9.
9 - 7 = 2
9 - 8 = 1
9 - 9 = 0

I wonder why range slice is not working properly in python

I made code as follows to execute binary search in sorted list for my study.
Code to find which number of values 'x' are in the list 'ss'.
Problem is, it should execute as reducing range of list, but it doesn't work.
def bin_search(ss, x):
return bin_search_range( ss, x, range(len(ss)) )
def bin_search_range(ss, x, r):
print(r)
print("len(r)", len(r))
if len(r) > 0:
mid = ((r.start) + (r.stop)) // 2
print("start", r.start)
print("stop", r.stop)
print("mid", mid)
print("x", x," ss[mid]", ss[mid])
if x == ss[mid]:
print("----[x = ss[mid]----")
return print("answer", mid)
elif x < ss[mid]:
print("----[x < ss[mid]]----")
return bin_search_range(ss, x, r[:mid])
else:
print("----[x > ss[mid]]----")
return bin_search_range(ss, x, r[mid+1:])
else: # len(r) == 0
return None
#Except "return print("answer", mid)", I just wrote down the rest of the output to know the progress.
In the manner of recursion, I repeated slicing the list through mid(which is median of list).
Until the median and 'x' match.
Below median, in other words left of median. There was no problem finding the value in.
There was a problem when finding the value on the right side of the median.
Below are the results of the execution of bin_search ([1, 2, 3, 4, 5, 6, 7], 5).
[Execution Result]
bin_search ([1, 2, 3, 4, 5, 6, 7], 5)
range(0, 7)
len(r) 7
start 0
stop 7
mid 3
x 5 ss[mid] 4
----[x > ss[mid]]----
range(4, 7)
len(r) 3
start 4
stop 7
mid 5
x 5 ss[mid] 6
----[x < ss[mid]]----
range(4, 7)
len(r) 3
start 4
stop 7
mid 5
x 5 ss[mid] 6
.
.
.
#RecursionError: maximum recursion depth exceeded while calling a Python object
Since x = 5, ss[mid] = 6, shouldn't the range of range be reduced to (4,5)?
Just like my prediction below
[Expected Result]
range(0, 7)
len(r) 7
start 0
stop 7
mid 3
x 5 ss[mid] 4
----[x > ss[mid]]----
range(4, 7)
len(r) 3
start 4
stop 7
mid 5
x 5 ss[mid] 6
----[x < ss[mid]]----
range(4, 5)
len(r) 3
start 4
stop 5
mid 4
x 5 ss[mid] 5
----[x = ss[mid]----
answer 4
Besides, when len(r) becomes 0, I thought I would print None, but I can't get any output.
Doesn't None print out when all the runs are over? I thought None would be printed because there was no range to search anymore, but I don't know why it couldn't be printed.
No matter how hard I think about it, I don't know if there's a problem with the code. If you know anything about it, I'd appreciate it if you could help me.

Splitting number in list in K equal parts

I am trying to solve a problem in which I am dividing a list stick into equal size given by K.
Input: stick = [5, 9, 7], K = 4
This means that we have three sticks with lengths as 5, 9 and 7. We would like to come up with K=4 equal length sticks by cutting these three sticks. We would like to end up with K=4 equal length sticks.
Updated Explanation:
From the first stick with length 5, we can have one stick with length 4.
From the second stick with length 9, we can have two sticks with length 4.
From the third stick with length 7, we can have one stick with length 4.
My code is below:
stick = [5,7,9]
K=4
for i in range(len(stick)):
T = stick[i]%K
if T !=0:
print (stick[i],T)
else:
print (stick[i])
My code is giving me the below output
5 1
7 3
9 1
but how I can print the number + its addition like
5 = 4 + 1
7 = 4 + 3
9 = 4*2 + 1
My code is only giving me output 1,3,1
Expected output:
Input: stick = [5, 9, 7], K = 4
Output: 4
Explanation:
Cut arr[0] = 5 = 4 + 1
Cut arr[1] = 9 = 2 * 4 + 1
Cut arr[2] = 7 = 4 + 3
Example 2:
Input: stick[] = {5, 9, 7}, K = 3
Output: 5 \
Explanation:
Cut arr[0] = 5 = 5
Cut arr[1] = 9 = 5 + 4
Cut arr[2] = 5 = 5 + 2
It is best to construct a string depending on different conditions and print that instead:
stick = [5, 7, 8, 9]
K = 4
for i in range(len(stick)):
T = stick[i] % K
D = stick[i] // K
# Construct the multiplier text (* ...) if necessary
if D > 1:
multiplier = f" * {D}"
else:
multiplier = ""
# Construct the remainder (+ ...) text if necessary
if T:
remainder = f" + {T}"
else:
remainder = ""
# Print the final result
print(f"{stick[i]} = {K}{multiplier}{remainder}")
This should print:
5 = 4 + 1
7 = 4 + 3
8 = 4 * 2
9 = 4 * 2 + 1
Update: This answer assumes that K is the desired length as hinted in the original code posted in the question. If it is the number of splits the logic must be updated accordingly, but the answer to your actual question (i.e. "how to print in a specific way") stays the same.

Returning the product of numbers betweeen max and min in list, and simplify the loop

I have some array elements which were separated by a space,
for ex: -7 5 -1 3 9, 3 14 -9 4 -5 1 -12 4, -5 1 2 3 4 5 6 7 8 -3.
The task was to find the product of numbers which are located between maximum and minimum of them. And I made something to calculate it
n = "-7 5 -1 3 9"
t = [int(i) for i in n.split()] # transform to list
if t.index(max(t)) < t.index(min(t)): # loop to cut numbers which are not
for i in range(len(t)): # between our max and min numberes in list
if t.index(max(t)) > i:
t.pop(i)
for i in range(len(t)):
if t.index(min(t)) < i:
t.pop(i)
elif t.index(min(t)) < t.index(max(t)):
for i in range(len(t)):
if t.index(min(t)) > i:
t.pop(i)
for i in range(len(t)):
if t.index(max(t)) < i:
t.pop(i)
t.pop(t.index(min(t)))
t.pop(t.index(max(t)))
def product(list): # fuction to return product of a list
p = 1
for i in list:
p *= i
return p
print(product(t)) # and print it
It looks a little cumbersome, and I have similar problem, is there any way to simplify that loop. Thank you in advance for your attention.
If you are open to using NumPy, you can solve the problem in literally two lines of code:
import numpy as np
n="-5 1 2 3 4 5 6 7 8 -3"
t = [int(i) for i in n.split()]
t = np.array(t) # Convert the list to a numpy array
t[t.argmin() : t.argmax() + 1].prod() # Get the range and the product
If you have more than one max element and want to go as far as the right-most of them, the code can be modified accordingly:
t[t.argmin() : t.size - t[::-1].argmax()].prod()
You could try something like this
n = "-7 5 -1 3 9"
n_list = n.split(" ")
n_list = list(map(int, n_list)) #In case of python3 use -- n_list = map(int, n_list)
max = max(n_list)
min = min(n_list)
result = 1
for i in range(len(n_list)):
if n_list[i] > min and n_list[i] < max:
result = result * n_list[i]
print(result);
I created a generator, which takes one argument, an iterable and yields values that are within range of min, max of this iterable. The product is computed as usual:
from itertools import chain
def values(iterable):
lst = list(int(i) for i in chain.from_iterable(i.split() for i in n))
_min, _max = min(lst), max(lst)
for i in lst:
if _min < i < _max:
yield i
n = ['7 5 -1 3 9', '3 14 -9 4 -5 1 -12 4', '-5 1 2 3 4 5 6 7 8 -3']
p = 1
for i in values(n):
p *= i
print(p)
Output:
-1234517760000

Categories

Resources