TypeError: object of type 'NoneType' has no len() when passing list as argument to function and querying about the length of array - python-3.10

Q . Maximum sum of i*arr[i] among all rotations of a given array. Trying the brute force approach. But running into error :
line 19, in add1 = add(arr)
line 10, in add for i in range(0,len(arr1)): TypeError: object of type 'NoneType' has no len()
arr = list(map(int,input().split()))
def rotation(arr,n):
left = arr[1:]
right = arr[0]
arr = left.append(right)
return arr
def add(arr1):
sum=0
for i in range(0,len(arr1)):
sum = sum+arr1[i]*i
return sum
n = len(arr)
maxm = add(arr)
for i in range(0,n-1):
arr = rotation(arr,n)
add1 = add(arr)
if maxm<add1:
maxm = add1
print(maxm)

Related

Mean, variance and standard deviation in python

n,m = map(int,input().split())
A = []
for _ in range(n):
A.append(map(int,input().split()))
A = numpy.array(A)
print (numpy.mean(A,axis = 1))
print (numpy.var(A,axis = 0))
print (round(numpy.std(A),11))
Can anyone tell me what I am doing wrong?
I am getting error : numpy.AxisError: axis 1 is out of bounds for array of dimension 1
Also, I want the user to input the array of n x m dimensions.
How can I add the m dimension check ?
Please help.
When you are trying to append elements in the array, you are taking the elements using the map function, a map function will always return a map object and you are just appending map objects as elements to the array. So, when you are trying to access axis=1 actually there is no axis=1 present in the array because the array contains a single row with map objects.
Here is the correct code without using list comprehension,
n,m = map(int,input().split())
A = []
for _ in range(n):
A.append(list(map(int,input().split())))
A = numpy.array(A)
print(A)
print (numpy.mean(A,axis = 1))
print (numpy.var(A,axis = 0))
print (round(numpy.std(A),11))
Here is the code using list comprehension,
n,m = map(int,input().split())
A = []
for _ in range(n):
A.append([int(x) for x in input().split()])
A = numpy.array(A)
print(A)
print (numpy.mean(A,axis = 1))
print (numpy.var(A,axis = 0))
print (round(numpy.std(A),11))

TypeError: 'generator' object cannot be interpreted as an integer

Traceback Error:
Traceback (most recent call last):
File "C:\trial2\trial.py", line 56, in <module>
image_stack(image)
File "C:\trial2\trial.py", line 44, in image_stack
reshaped = transposed_axes.reshape(new_arr_shape)
TypeError: 'generator' object cannot be interpreted as an integer
My problem in the code is that I can't reshape the array that transposed with a new array shape. The code takes in a path to an image which is read by cv2 and then the turned into an array. Using the length of the array the array the values for the transpose axes are calculated. Then the transposed axes values are used to transpose the array. I used numpy.prod() to a product of array values over the axes that were generated by the if statement. I wanted to reshape the transposed array with the the value of new_arr_shape, but I keep getting an error saying that 'generator' object cannot be interpreted as an integer.
import numpy as np
def image_stack(image):
imgs = np.array(cv2.imread(image).shape)
print(type(imgs))
n = len(imgs)
img = np.ones(imgs)
val_1 = list(range(1, n - 1, 2))
val_2 = list(range(0, n - 1, 2))
print(img)
if n % 2 == 0:
y_ax = val_1
x_ax = val_2
axes = (y_ax, x_ax, [n-1])
else:
y_ax = val_2
x_ax = val_1
axes = (y_ax, x_ax, [n - 1])
print(type(axes))
'''The axes need to be in form of a tuple in order to be
transposed'''
if type(axes) == tuple:
transposed_axes = np.transpose(img, axes=np.concatenate(axes))
print(transposed_axes)
new_arr_shape = [np.prod(img[x] for x in axes)]
print(type(new_arr_shape))
print(new_arr_shape)
reshaped = transposed_axes.reshape(new_arr_shape)
#print(type(reshaped))
#print(reshaped)
image = 'C:\\trial_images\\9.jpg'
image_stack(image)
'generator' object cannot be interpreted as an integer
This is because np.prod(img[x] for x in axes) returns a generator and the function reshape expects a list of integers.
To convert the generator to a list, use the list function.
list(np.prod(img[x] for x in axes))
reshape function expects a list or a tuple of integers. Also, the size (product of dimensions) should match that of the other array.
eg: transposed_axes.reshape([1446,2842,3]) or transposed_axes.reshape([1446,1421,6]) will work because the dimension of transposed_axes is (1446,2842,3)

Assign a number to each unique value in a list of lists

I have a list of lists of strings which I want to convert into a unique number per value.
list = [['a','b'],['c','a'],['c','b']]
output:
unique_value = [[1,2],[3,1],[3,2]]
I've mapped the string elements using the length of the dict here, maybe you can change it as per your requirement.
Code:
def custom_map(arr):
res = []
for ele in arr:
if ele not in cmap:
cmap[ele]=len(cmap)+1
res.append(cmap[ele])
return res
cmap = {}
x = [['a','b'],['c','a'],['c','b']]
uq_val = list(map(custom_map,x))
print(uq_val)

Getting nil error when adding elements in Array - Ruby

I am trying to get a number from the user, store this number in the array and then add everything in the array together to display a total.
names = Array.new(20)
sum = 0
x = 0
for index in 0..5
puts "Enter a number: "
data = gets.to_i
names.push data
x = x + names[index]
end
puts x
But I am getting the error rb:10:in `+': nil can't be coerced into Integer (TypeError)
I guess its not allowing me to add whatever is in the array together. Anybody know a workaround for this?
There are some issues with your code.
Array.new(20) – you probably think this creates an array of the given size. Well, it does, but it also fills the array with a default object of nil:
Array.new(3)
#=> [nil, nil, nil]
In Ruby, you just create an empty array. It will grow and shrink automatically. And instead of Array.new you can use an array literal:
names = []
for index in 0..5 – for loops are very unidiomatic. You should use one of these:
(0..5).each do |index|
# ...
end
0.upto(5) do |index|
# ...
end
6.times do |index|
# ...
end
And finally:
names.push data
x = x + names[index]
You are pushing an element to the end of the array and then fetch it from the array using an absolute index. This only works if index and array size correlate exactly.
It's more robust to either use an explicit index for both, storing and fetching:
names[index] = data
x = x + names[index]
or to fetch the last element: (note that index isn't needed)
names.push data
x = x + names.last
Ruby also provides negative indices that are relative to the array's end:
names.push data
x = x + names[-1]
Needless to say, you could just omit the fetching:
names.push data
x = x + data
It might be useful to separate the data gathering from the calculation:
numbers = []
6.times do
puts 'Enter a number: '
numbers << gets.to_i
end
and then:
numbers = [1, 2, 3, 4, 5, 6] # <- example input
numbers.sum
#=> 21
# -- or --
numbers.inject(:+)
#=> 21
# -- or --
sum = 0
numbers.each { |n| sum += n }
sum
#=> 21
You are initializing the array with 20 nil names. Then you push the first entered number to the array (position 21) and try to concat the position [0] (names[0]) that is nil.
Try to change the first line:
names = Array.new

Mapping An Array To Logical Array In Matlab

Let's say an array a=[1,3,8,10,11,15,24], and a logical array b=[1,0,0,1,1,1,0,0,0,1,1,1,1,1], how to get [1,1,3,1,3,8,1,3,8,1,2,3,8,10], see where logic becomes 1 in b, the array index of a resets so it starts from the beginning, also the same where the logic becomes 0 a array starts from beginning and continues as 1,3,8,10..etc.
you can use diff to find where b changes, then use arrayfun to generate indexes for a:
a=[1,3,8,10,11,15,24];
b=[1,0,0,1,1,1,0,0,0,1,1,1,1,1];
idxs = find(diff(b) ~= 0) + 1; % where b changes
startidxs = [1 idxs];
endidxs = [idxs - 1,length(b)];
% indexes for a
ia = cell2mat(arrayfun(#(x,y) 1:(y-x+1),startidxs,endidxs,'UniformOutput',0));
res = a(ia);
You can use a for loop and track the state (0 or 1) of the b array:
a = [1,3,8,10,11,15,24];
b = [1,0,0,1,1,1,0,0,0,1,1,1,1,1];
final = []
index = 0;
state = b(1);
for i = 1:numel(b)
if b(i) ~= state
state = b(i);
index = 1;
else
index = index+1;
end
final = [final, a(index) ];
end

Resources