smallest difference of a sequence of a list - python

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

Related

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.

Python: How to make numeric triangle with recursion

while I was working on the Python practice, I found a question that I cannot solve by myself.
The question is,
Input one integer(n), and then write the codes that make a triangle using 1 to 'n'. Use the following picture. You should make only one function, and call that function various times to solve the question. The following picture is the result that you should make in the codes.
Receive one integer as an argument, print the number from 1 to the integer received as a factor in a single line, and then print the line break character at the end. Once this function is called, only one line of output should be printed.
So by that question, I found that this is a question that requires the
recursion since I have to call your function only once.
I tried to work on the codes that I made many times, but I couldn't solve it.
global a
a = 1
def printLine(n):
global a
if (n == 0):
return
for i in range(1, a + 1):
print(i, end=" ")
print()
a += 1
for k in range(1, n+1):
print(k, end=" ")
print()
printLine(n - 1)
n = int(input())
printLine(n)
Then I wrote some codes to solve this question, but the ascending and descending part is kept overlapping. :(
What I need to do is to break two ascending and descending parts separately in one function, but I really cannot find how can I do that. So which part should I have to put the recursive function call?
Or is there another way can divide the ascending and descending part in the function?
Any ideas, comments, or solutions are appreciated.
Thx
You can use the below function:
def create_triangle(n, k: int = 1, output: list = []):
if n == 1:
output.append(n)
return output
elif k >= n:
output.append(" ".join([str(i) for i in range(1, n + 1)]))
return create_triangle(n - 1, k)
else:
output.append(" ".join([str(i) for i in range(1, n + 1)[:k]]))
return create_triangle(n, k + 1)
for i in create_triangle(5):
print(i)
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
# function to print all the numbers from 1 to n with spaces
def printLine(k):
# create a range. if k is 4, will create the range: 1, 2, 3, 4
rng = range(1, k + 1)
# convert each number to string
str_rng = map(lambda x: str(x), rng)
# create one long string with spaces
full_line = " ".join(str_rng)
print(full_line)
# capture input
n = int(input())
# start from 1, and up to n, printing the first half of the triangle
for i in range(1, n):
printLine(i)
# now create the bottom part, by creating a descending range
for i in range(n, 0, -1):
printLine(i)
Using default parameter as a dict, you can manipulate it as your function variables, so in that way, you can have a variable in your function that keeps the current iteration you are at and if your function is ascending or descending.
def triangle_line(n, config={'max':1, 'ascending':True}):
print(*range(1, config['max'] + 1))
if config['ascending']:
config['max'] += 1
else:
config['max'] -= 1
if config['max'] > n:
config['ascending'] = False
config['max'] = n
elif config['max'] == 0:
config['ascending'] = True
config['max'] = 1
Each call you make will return one iteration.
>>> triangle_line(4)
1
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1
Or you can run on a loop, two times your input size.
>>> n = 4
>>> for i in range(0,n*2):
... triangle_line(n)
...
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1

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

Array Of Number And Finding SubArray

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]

Function returning incomplete value

def sum_2_array(list1):
item = 10
numlist = list()
for i in list1:
num = list1.pop()
diff = item-num
if diff in list1:
return num, diff
print sum_2_array([2,3,5,8,7])
This function computes the minimum absolute diff between the elements of an array.The error is that it is returning just one value .
Can anayone please check and tell me where I am going wrong
Please run below code & see if it works. I have Used simple logic
def sum_2_array(list1):
item = 10
j = 0
for i in list1:
print "this is value of J = ", j
num = list1[j]
print "this is value of num = ", num
diff = item - num
print "this is vale of diff = ", diff
if diff in list1:
print num
print diff
j += 1
print sum_2_array([2, 3, 5, 8, 7])
Code you were running in that when it comes to third item in the list i.e 5. At the same time it pops out this item from the list. Because you are using list1.pop(). So it unable to find 5 in the list that's why you are getting only two values. Use code I gave & check if it works.
I got following result from that
this is value of J = 0
this is value of num = 2
this is vale of diff = 8
2
8
this is value of J = 1
this is value of num = 3
this is vale of diff = 7
3
7
this is value of J = 2
this is value of num = 5
this is vale of diff = 5
5
5
this is value of J = 3
this is value of num = 8
this is vale of diff = 2
8
2
this is value of J = 4
this is value of num = 7
this is vale of diff = 3
7
3

Categories

Resources