Whats wrong with this code? I fail to see the error. The compiler shows this output.(N.B: I'm new to python)
output:Enter element no: 1
None
no_of_zeros = 0
for i in range(0, 5):
array[i] = input(print("Enter element no:", i+1))
if(array[i]==0):
array[i] = 1
is_zero += 1
sum = 0
for j in range(0, 5):
sum = sum + array[j]
print(sum)
print(no_of_zeros)
You can't access an index that doesn't exist. Pre-allocate array or use array.append.
array = list(range(0,5))
no_of_zeros = 0
for i in range(0, 5):
array[i] = int(input("Enter element no{}:".format(i+1)))
if(array[i]==0):
array[i] = 1
is_zero += 1
sum = 0
for j in range(0, 5):
sum = sum + array[j]
print(sum)
print(no_of_zeros)
Also that is a very C-ish way of doing things (which is fine). Python can make that code much simpler. Once you catch on to the Python way of doing things you will see why Python is so popular. Learn list comprehension for instance.
Your code can be reduced to three lines ...
array = [ int(input("Enter element no{}:".format(i+1))) for i in range(5) ]
print(sum(array))
print(sum([ 1 for x in array if x==0 ]))
Related
I was looking through the other threads concerning the Insertion Sort but didn't find the answer that relates to the specific part of it which I do not understand.
My full Insertion Sort algorithm can be seen below. It works as intended, but I cannot figure out the purpose of that last line.
array[position] = value
Let me explain through an example:
When the 'for' loop starts, index = 1.
=> value = array[1] = 3
=> position = 1
=> Since 4 > 3, the item at index 1, is swapped with the item at index 0.
=> position -= 1
=> position = 0
We now get to the line which confuses me:
array[0] = value
=> value = array[index] = array[0] = 3
However, when the 'for' loop goes through its second iteration, index = 2.
And so immediately value = array[2] and position = 2 ?
Even though I know that this last line of code is necessary I just cannot see what purpose it serves.
Could someone please explain to me this final logical step?
Thank you in advance for your time and help.
array = [4,3,5,6,12,9,8,6]
for index in range (1, len(array)):
value = array[index]
position = index
while position > 0 and array[position - 1] > value:
array[position] = array[position - 1]
position -= 1
array[position] = value
The position variable represents (at the end) where you will eventually insert the number. Without the last line, you are not inserting the number at 'position' at the correct place (it will result in the 1 index after). Below is my code for insertion sort.
def insertionSort(arr):
length = len(arr)
for i in range(1, length):
currNum = arr[i]
j = i - 1
while j >= 0 and currNum < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j+1] = currNum
return arr
You wouldn't have really swapped the numbers without that line, would you?
index 1:
-> [4,3,5,6,12,9,8,6] (enters while loop)
-> [4,4,5,6,12,9,8,6] ("pushes" 4 to position 1)
-> <waits for while loop to finish>
-> [3,4,5,6,12,9,8,6] (assigns 3 to position 0 since there are no other elements > 3)
index 2:
...
I think is not really needed at start in for loop, because it was used to index inside the loop. Looks the picture
I'm stuck on an algorithm for a function called adjacentElementsProduct that accepts an array as the argument. It's supposed to return the largest product of adjacent numbers in the array. For example, if the argument is [2,4,1,3,2,6] it would return 12 because of the pair of 2 and 6.
my code is
def adjacentElementsProduct(inputArray)
idx1 = 0
idx2 = 1
while idx2 < inputArray.length
pair = [inputArray[idx1], inputArray[idx1 + 1]]
next_pair = [inputArray[idx2], inputArray[idx2 + 1]]
if next_pair.reduce(:+) > pair.reduce(:+)
pair = next_pair
idx1 += 1
idx2 += 1
else
idx1 += 1
idx2 += 1
end
end
pair.reduce(:+)
end
I just can't figure out where my code is not working. I'm just looking for a push in the right direction because I know just being given the answer won't help me as much. Can anyone help me?
The code makes no sense :).
You are using + instead of *
And in the loop you always assign pair = [inputArray[idx1], inputArray[idx1 + 1]].
So you always return the last pair or the previous. If the maximum product is at the beginning, you still keep advancing the pair variable until the end of the loop.
Besides, the solution is quite complicated.
def adjacentElementsProduct(inputArray)
index = 0
length = inputArray.length
max = 0
while index < length-1 do
result = inputArray[index] * inputArray[index+1]
max = result if result > max
index += 1
end
max
end
I have a matrix A of dimension m-by-n composed of zeros and ones, and a matrix J of dimension m-by-1 reporting some integers from [1,...,n].
I want to construct a matrix B of dimension m-by-n such that for i = 1,...,m
B(i,j) = A(i,j) for j=1,...,n-1
B(i,n) = abs(A(i,n)-1)
If sum(B(i,:)) is odd then B(i,J(i)) = abs(B(i,J(i))-1)
This code does what I want:
m = 4;
n = 5;
A = [1 1 1 1 1; ...
0 0 1 0 0; ...
1 0 1 0 1; ...
0 1 0 0 1];
J = [1;2;1;4];
B = zeros(m,n);
for i = 1:m
B(i,n) = abs(A(i,n)-1);
for j = 1:n-1
B(i,j) = A(i,j);
end
if mod(sum(B(i,:)),2)~=0
B(i,J(i)) = abs(B(i,J(i))-1);
end
end
Can you suggest more efficient algorithms, that do not use the nested loop?
No for loops are required for your question. It just needs an effective use of the colon operator and logical-indexing as follows:
% First initialize B to all zeros
B = zeros(size(A));
% Assign all but last columns of A to B
B(:, 1:end-1) = A(:, 1:end-1);
% Assign the last column of B based on the last column of A
B(:, end) = abs(A(:, end) - 1);
% Set all cells to required value
% Original code which does not work: B(oddRow, J(oddRow)) = abs(B(oddRow, J(oddRow)) - 1);
% Correct code:
% Find all rows in B with an odd sum
oddRow = find(mod(sum(B, 2), 2) ~= 0);
for ii = 1:numel(oddRow)
B(oddRow(ii), J(oddRow(ii))) = abs(B(oddRow(ii), J(oddRow(ii))) - 1);
end
I guess for the last part it is best to use a for loop.
Edit: See the neat trick by EBH to do the last part without a for loop
Just to add to #ammportal good answer, also the last part can be done without a loop with the use of linear indices. For that, sub2ind is useful. So adopting the last part of the previous answer, this can be done:
% Find all rows in B with an odd sum
oddRow = find(mod(sum(B, 2), 2) ~= 0);
% convert the locations to linear indices
ind = sub2ind(size(B),oddRow,J(oddRow));
B(ind) = abs(B(ind)- 1);
I have an array of hashes, where every hash has a size key:
blocks = [{size: 1},{size: 3},{size: 4}]
Now I want to split this array into subarrays by aggregating the size value, and defining an upper limit of 4. In every subarray the summed up values of the size key should be less than 4.
I have this solution, but it's not pretty or elegant:
arr = []
tmp = []
sum = 0
blocks.each do |block|
sum += block[:size]
tmp.push(block)
if sum >= 4
arr.push(tmp)
sum = 0
tmp = []
end
end
Maybe someone knows a more ruby-like, elegant solution.
There is a way using slice_when:
sum = 0
blocks.slice_when do |elt_before, _|
sum += elt_before[:size]
sum >= 4 ? (sum = 0; true) : false
end.to_a
Edit: As per #CarySwoveland suggestion
It can get even simpler if using slice_after:
sum = 0
blocks.slice_after do |elt|
sum += elt[:size]
sum >= 4 ? (sum = 0; true) : false
end.to_a
As a note both slice_when & slice_after first appeared in Ruby v.2.2
I am trying to learn how to iterate over arrays and therefore made up my own scenarios to practise on.
Let's say my given matrix is a two-dimensional, therefore an two-dim. Array.
mat =[[1,2,300,-400],[0,3,-1,9],[3,4,-5,1]]
Task 1) Return the Array with the highest sum of the values.
Task 2) Given that this Array could produce a nxm matrix, return the value of the row and column for which the sum of the enclosing number is the highest.
To make it easier to understand let us use a different matrix here.
mat= [[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4]]
So it would look like this:
1111
2222
3333
4444
And the result would be [2,1] or [2,2]
since the sum for those numbers (2+2+2+3+3+4+4+4) = 24 would be the highest.
Here are my implementations so far:
Task 1)
I only can solve this with adding a sum function to the class Array.
def max_row(mat)
return mat.max{|a,b| a.sum <=> b.sum }
end
class Array
def sum
sum = 0
self.each(){|x|
sum += x
}
return sum
end
end
I do want to solve it without using an extra method so, but I do not know how to.
my idea so far :
def max_row(mat)
sum_ary = []
mat.each(){|ary|
sum = 0
ary.each(){|x|
sum += x
}
sum_ary << [sum]
}
I tried find_index on my sum_ary, but as implemented it returns the first value which is not false, therefore I cannot use it to search for the biggest value.
Implementation Task 2):
mat = [[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4]]
def max_neighbor_sum(mat)
sum_result = []
for n in 0...mat.size()
for m in 0...mat.size()
sum = 0
for a in (n-1)..(n+1)
for b in (m-1)..(m+1)
if m != nil && n !=nil && a>=0 && b>=0 && a<= (mat.size()-1)
# print "n:#{n} m:#{m} a:#{a} b:#{b} \n"
# p mat[a][b]
if mat[a][b] !=nil && !(n==a && m==b)
sum += mat[a][b]
end
end
end
end
sum_result << sum
# p sum_result
end
end
return sum_result
end
I calculated all the sums correctly, but have no idea how I get the index for the row and column now.
I hope you can understand where I need some help.
Problem 1:
arrays.map(&:sum).max
Calls sum for each of the arrays, then chooses the biggest of them
Problem 2 can't be solved so easily, but this should work:
max_sum = 0
max_index = []
for n in 0...mat.size
for m in 0...mat.size
sum = 0
for a in (n-1)..(n+1)
for b in (m-1)..(m+1)
sum += mat[a][b] unless mat[a].nil? || mat[a][b].nil?
end
end
if sum > max_sum
max_sum = sum
max_index = [n,m]
end
end
end
max_sum # => maximum sum of all neighbours
max_index # => a pair of indexes which have the max sum
If you want to keep all of max indexes, just replace it with an array of pairs and push if the sum is equal to max_sum.
Here is my solution to task 2 which I came up with thanks to Piotr Kruczek.
Thanks for the kind help!
def max_neighbour_sum(mat)
sum_result = []
max_sum = 0
for n in 0...mat.size()
for m in 0...mat.size()
sum = 0
for a in (n-1)..(n+1)
for b in (m-1)..(m+1)
if m != nil && n !=nil && a>=0 && b>=0 && a<= (mat.size()-1)
# print "n:#{n} m:#{m} a:#{a} b:#{b} \n"
# p mat[a][b]
if mat[a][b] !=nil && !(n==a && m==b)
sum += mat[a][b]
end
end
end
end
if sum > max_sum
max_sum = sum
sum_result = [n,m]
end
# p sum_result
end
end
return sum_result
end