Getting the average from a list using len and avg function - average

I've created a simple list but am stuck on the formula using len to calculate the average. Any help would be welcome. Thank you.
numbers = [1, 2, 3, 4, 5]
def average(numbers):
return(numbers(sum/len))
print(average)

When I code (in Python 2.7.17):
def average (numbers): return (sum(numbers)/len (numbers))
numbers=[1, 2, 3, 4, 5]
print average (numbers)
I get the expected result, i.e. 3. Does this not work for you?

Related

Very Basic Misunderstanding of for loops in Swift

I'm new to swift. can someone please explain what I'm doing wrong here.
1.
var numbers = [1, 5, 7, 6, 6, 6, 6, 6, 2]
for i in numbers{
print(numbers[i],terminator: "")
}
why doesn't this just print the numbers in the array?
2.
Here I want to set the elements in the array to a random number from 0 to 2, and then print them.
for j in numbers{
numbers[j] = Int.random(in: 0...2)
print(numbers[j],terminator: "")
}
this seems to work, but then if, outside of the for loop, I print them again:
for k in numbers{
print(numbers[k],terminator: "")
}
It outputs different numbers, from 0 to 2
3.
OK so I try a different syntax:
for m in numbers{
print(m,terminator: "")
}
now I get the same numbers every time and they are not from 0 to 2... I'm sure my mistakes are trivial but an explanation would help me out. Thanks.
to achieve what you expect, you need to loop over the indices of the array, like this:
var numbers = [1, 5, 7, 6, 6, 6, 6, 6, 2]
for i in numbers.indices { // <-- here
print(numbers[i])
}
And as mentioned, read the basics of Swift.

How to put numbers into an array and sorted by most frequent number in java

I was given this question on programming in java and was wondering what would be the best way of doing it.
The question was on the lines of:
From the numbers provided, how would you in java display the most frequent number. The numbers was: 0, 3, 4, 1, 1, 3, 7, 9, 1
At first I am thinking well they should be in an array and sorted first then maybe have to go through a for loop. Am I on the right lines. Some examples will help greatly
If the numbers are all fairly small, you can quickly get the most frequent value by creating an array to keep track of the count for each number. The algorithm would be:
Find the maximum value in your list
Create an integer array of size max + 1 (assuming all non-negative values) to store the counts for each value in your list
Loop through your list and increment the count at the index of each value
Scan through the count array and find the index with the highest value
The run-time of this algorithm should be faster than sorting the list and finding the longest string of duplicate values. The tradeoff is that it takes up more memory if the values in your list are very large.
With Java 8, this can be implemented rather smoothly. If you're willing to use a third-party library like jOOλ, it could be done like this:
List<Integer> list = Arrays.asList(0, 3, 4, 1, 1, 3, 7, 9, 1);
System.out.println(
Seq.seq(list)
.grouped(i -> i, Agg.count())
.sorted(Comparator.comparing(t -> -t.v2))
.map(t -> t.v1)
.toList());
(disclaimer, I work for the company behind jOOλ)
If you want to stick with the JDK 8 dependency, the following code would be equivalent to the above:
System.out.println(
list.stream()
.collect(Collectors.groupingBy(i -> i, Collectors.counting()))
.entrySet()
.stream()
.sorted(Comparator.comparing(e -> -e.getValue()))
.map(e -> e.getKey())
.collect(Collectors.toList()));
Both solutions yield:
[1, 3, 0, 4, 7, 9]

Matlab -- Finding missing number in a list

I have a relatively large data set, and I'm looking for the missing number via MatLab.
For example, I have a list of numbers that might look like:
1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 5, 6, 6, 7, 7, 7, 7, 9, 10, 10.....
You can see the 8 is missing here. The list is in the thousands, and there are maybe just a couple missing numbers. How can I find out which ones are missing? My search only turned up useful results without randomly repeating numbers. Seems simple but I can't figure it out.
Thanks for help!
Use unique, like this:
B=unique(A); % A is your data
C=setdiff(1:max(A),B)
and C is your desired missing numbers.
EDIT (afetr seeing claj's answer):
If your data starts from another value (not "1"), the second line should be:
C=setdiff(min(A):max(A),B)
EDIT2: (according to Eitan's comment)
C=setdiff(min(A):max(A),A);
This line replaces the two lines from the original answer.
You could do something like this:
% Your data:
data = [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 5, 6, 6, 7, 7, 7, 7, 9, 10, 10];
for i = 1:data(end)
if (isempty(find(data==i)))
disp(['i = ',num2str(i)]);
end
end
Which will print out the values of the missing elements.
Or even simpler you could just use the ismember() function to construct
the set difference in just a single line below.
% First enter your data and construct 'set':
data = [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 5, 6, 6, 7, 7, 7, 7, 9, 10, 10];
set = data(1):data(end);
Then to determine which elements of 'set' are also in 'data':
ismember(set, data)
The output then shows the locations in 'set' where the data is missing:
ans =
1 1 1 1 1 1 1 0 1 1
Use the ismember() function to check if a number is member of the data array
% set your data array
maximum = max(data);
minimum = min(data);
for i= minimum:maximum
if ~ismember(i,data);
disp([num2str(i) , ' is missed']);
end
end
Create a unique list of values in the array.
Find the min and max numbers in this unique set (these should be the same numbers as in the array, but quicker to find).
Create a range from min to max like [min:max].
Make a set difference of the uniqued array and the range-set.
This gives you the missing numbers in decently quick way.
this is similar to a few of the above but the simplest i've found is
find(~ismember(set,data))
which will return the indices of the members of set that are not in data

Select One Element in Each Row of a Numpy Array by Column Indices [duplicate]

This question already has answers here:
NumPy selecting specific column index per row by using a list of indexes
(7 answers)
Closed 2 years ago.
Is there a better way to get the "output_array" from the "input_array" and "select_id" ?
Can we get rid of range( input_array.shape[0] ) ?
>>> input_array = numpy.array( [ [3,14], [12, 5], [75, 50] ] )
>>> select_id = [0, 1, 1]
>>> print input_array
[[ 3 14]
[12 5]
[75 50]]
>>> output_array = input_array[ range( input_array.shape[0] ), select_id ]
>>> print output_array
[ 3 5 50]
You can choose from given array using numpy.choose which constructs an array from an index array (in your case select_id) and a set of arrays (in your case input_array) to choose from. However you may first need to transpose input_array to match dimensions. The following shows a small example:
In [101]: input_array
Out[101]:
array([[ 3, 14],
[12, 5],
[75, 50]])
In [102]: input_array.shape
Out[102]: (3, 2)
In [103]: select_id
Out[103]: [0, 1, 1]
In [104]: output_array = np.choose(select_id, input_array.T)
In [105]: output_array
Out[105]: array([ 3, 5, 50])
(because I can't post this as a comment on the accepted answer)
Note that numpy.choose only works if you have 32 or fewer choices (in this case, the dimension of your array along which you're indexing must be of size 32 or smaller). Additionally, the documentation for numpy.choose says
To reduce the chance of misinterpretation, even though the following "abuse" is nominally supported, choices should neither be, nor be thought of as, a single array, i.e., the outermost sequence-like container should be either a list or a tuple.
The OP asks:
Is there a better way to get the output_array from the input_array and select_id?
I would say, the way you originally suggested seems the best out of those presented here. It is easy to understand, scales to large arrays, and is efficient.
Can we get rid of range(input_array.shape[0])?
Yes, as shown by other answers, but the accepted one doesn't work in general so well as what the OP already suggests doing.
I think enumerate is handy.
[input_array[enum, item] for enum, item in enumerate(select_id)]
How about:
[input_array[x,y] for x,y in zip(range(len(input_array[:,0])),select_id)]

MATLAB, how to evaluate multiple indices in one line?

I don't know how to explain this better than by giving you an example.
Suppose I have the following array:
a = magic(6)
And then I take a 'slice' of that like this:
a(:,1)
It will print:
35
3
31
8
30
4
Now I want the first number, so I want to write:
a(:,1)(1)
Instead of:
b = a(:,1)
b(1)
Also, is there a way to do something like this (assignment and comparison, i.e. set b, then evaluate against it):
(b = a(:,1))(1)
Ok, here's an update with a function where it isn't trivial to use a(1, 1)
come_on = sprintf('%i, ', magic(3));
come_on(1:end-2)
8, 3, 4, 1, 5, 9, 6, 7, 2
Also, what if I only want the first 4 numbers on magic(3)?
It would be better to write
sprintf('%i, ', magic(3)(1:4))(1:end-2)
instead of tens of lines, MHO.
You cannot concatenate indexing as foo(1)(2)(3). However, you can index multiple dimensions at once. So in this case, a(1,1) will give you what you want.