Splitting number in list in K equal parts - python

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.

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.

How to go through the array halfway and then continue from the end of the array to the half array?

I'm trying to loop through the array, so that we take the first two values from the array at once, then the following iterations will take one value at a time until half of the array. When it comes to the middle of the field, it starts the same way, but from the end of the field towards the beginning. It takes first the last two values and then further iterations one value at a time to the center of the array.
I can do each part separately, the problem is putting it together
classic forward loop:
for i in a:
print(i)
output:
1
2
3
4
5
6
reverse loop:
for i in reversed(a):
print(i)
output:
6
6
5
4
3
2
1
a cycle that takes 2 values:
myList =np.array([1, 2, 3, 4, 5, 6])
for x,y in (myList[i:i+2] for i in range(0,len(myList),2)):
print(x,y)
output:
1 2
3 4
5 6
reverse loop:
for x,y in (myList[i:i+2] for i in reversed(range(0,len(myList),2))):
print(x,y)
output:
5 6
3 4
1 2
I would need such an output
example
a=np.array([1,2,3,4,5,6,7,8])
output
1 2
3
4
7 8 #or 8 7
6
5
or
a=np.array([1,2,3,4,5,6,7,])
output:
1 2 #or 1 2
3 #3
7 6 #4
5 #7 6
4 #5
the array can be of different sizes without restriction.
It is possible?
You can see the problem like that
each group of values is printed the same way
you apply to the first half and to the second half in reverse
def print_half(half_values):
print(*half_values[:2])
print(*half_values[2:], sep="\n")
def print_array(values):
print_half(values[:len(values) // 2])
print_half(list(reversed(values[len(values) // 2:])))
print_array([1, 2, 3, 4, 5, 6, 7])
print_array([1, 2, 3, 4, 5, 6, 7, 8])
The best way I can see is by storing a current index. First, the current index is 0, and after the first step it is set to 2 (first 2 items). Then, we keep incrementing while current_index < len // 2, at which point we set current_index = len - 1 and while current_index > len // 2 we decrement.
import numpy as np
def printArr(List):
for i in range(len(List)):
if i < 2:
print(List[i], end=' ')
continue
elif i == 2:
print('\n', end='')
print(List[i])
a=np.array([1,2,3,4,5,6,7,])
midle = int(len(a) / 2)
list1, list2 = a[:midle], a[-1: midle-1: -1]
printArr(list1)
printArr(list2)

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

how does result = k + tri_recursion(k-1) give me an output of triangular numbers?

I'm currently learning about functions and I came across a recursions example on w3schools.com. This code is giving me a list of triangular numbers for an argument k > 0. My question is how exactly is it printing out a list of triangular numbers with "result" defined as result = k + tri_recursion(k-1) in the body of the code. The output for an input of k = 6, for example, gives me 1, 3, 6, 10, 15, 21 but I just don't understand how I'm getting a list of triangular numbers from such a simple setting of the return variable. Help would be much appreciated :)
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nexample result")
tri_recursion(6)
you need create a list to storage numbers:
tri_list = []
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k-1)
tri_list.append(result)
print(result)
else:
result = 0
return result
print("\n\nexample result")
tri_recursion(6)
print(tri_list)
Then you have:
k = 6
6 + tri_recursion(5)
5 + tri_recursion(4)
4 + tri_recursion(3)
3 + tri_recursion(2)
2 + tri_recursion(1)
1 + tri_recursion(0)
1 + 0 = 1
2 + 1 = 3
3 + 3 = 6
4 + 6 = 10
5 + 10 = 15
6 + 15 = 21
This happens because you are printing the sum of the previous numbers in each return of each recursion

How can I used nested loops to print a matrix of numbers in Python?

For instance, if I have a function and say the input is a number n (i.e. 5)
I want a 5x5 matrix thats like:
1 2 3 4 5
2 10
3 15
4 20
5 10 15 20 25
and how can I write this if I only want the outer most square or the inner most?
(This is for python)
What I tried:
def f4(n):
for i in range(1, n):
for j in range(1, n):
print i*j,
print
To control spacing in strings, try str.format. For example:
>>> print '{:2} {:2} {:2} {:2} {:2}\n{:2} {:2} {:2} {:2} {:2}'.format(1, 2, 3, 4, 5, 10, 20, 30, 40, 50)
1 2 3 4 5
10 20 30 40 50
Another hint: it looks like you have 2 types of rows- top/bottom rows and middle rows. The top/bottom rows have a similar format that's different from the middle rows, which are themselves similar.
My solution
% cat squar.py
def squarpy(n, length=5):
fmt = "%%%dd"%(length)
sp = " "*length
square = " ".join([fmt%(i+1) for i in range(n)])
for j in range(2,n):
row = " ".join([fmt%(i*j+j) if i==0 or i==n-1 else sp for i in range(n)])
square = square +"\n" + row
tail = " ".join([fmt%(i*n+n) for i in range(n)])
square = square + "\n" + tail
return square
print squarpy(3)
print
print squarpy(5)
% python2 squar.py
1 2 3
2 6
3 6 9
1 2 3 4 5
2 10
3 15
4 20
5 10 15 20 25
%

Categories

Resources