Underscore GroupBy Sort - node.js

I have a question regarding programming in function style.
I use underscore.js library.
Let's consider some use-case. I have an array of some labels with repetitions I need to count how many occurrences of each label is in array and sort it according to the number of occurrences.
For counting, how many labels I can use countBy
_.countBy([1, 2, 3, 4, 5], function(num) {
return num % 2 == 0 ? 'even': 'odd';
});
=> {odd: 3, even: 2}
But here, as result I have a hash, which doesn't have meaning for order, so there is no sort. So here, I need to convert the hash to array then to sort it and convert backward to hash.
I am pretty sure there is an elegant way to do so, however I am not aware of it.
I would appreciate any help.

sort it and convert backward to hash.
No, that would loose the order again.
You could use
var occurences = _.countBy([1, 2, 3, 4, 5], function(num) {
return num % 2 == 0 ? 'even': 'odd';
});
// {odd: 3, even: 2}
var order = _.sortBy(_.keys(occurences), function(k){return occurences[k];})
// ["even", "odd"]
or maybe just
_.sortBy(_.pairs(occurences), 1)
// [["even", 2], ["odd", 3]]

Related

How to add numbers within a list

the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
def count_cans():
print(len(the_list))
So in this list there are 15 cans of food. how do I make a function that counts and returns the total amount of cans in the list.
Create a dictionary then sum the values in your dictionary:
the_list = {'diced tomatoes': 3, 'olives': 2, 'tomato soup': 3, 'tuna': 7}
sum(the_list.values())
Here you go
total_cans = 0
for food in the_list:
if (isinstance(food,int)): total_cans += food
print(total_cans)
With O(n) performance, goes through the list once.
Hi and welcome to StackOverFlow! As a general tip, it would be a lot more helpful for us to answer your question if you added what you've done so far like #Victor Wilson said, but nonetheless, we will try to help.
Think about what you may need to "increment" a "counter" variable (major hint here!). Since you are working with a list, you know that it is an iterable so you know you can use iterative processes like for-loops/while-loops and range() function to help you.
Once you find the "number of cans" (hint: type int), then you can increment that with your counter variable (hint: addition here).
Knowing what data types you're working with and what built-in methods that can be used with those types can be extremely helpful when learning to debug your own code.
And... by the time I finished my post, #bashBedlam seems to have answered you with a full program already ;). Hope this helps!
If you want to add only the numbers in a list, you can extract numbers from that list and then sum that sublist. That would mean something like,
def get_number(whatever):
try:
return float(whatever)
except ValueError:
return 0
your_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
total = sum([get_number(i) for i in your_list])
However, if you tell us your actual problem statement, I feel we can tackle the problem more efficiently. You should more likely use a different data structure. Use a hash-map/dictionary if you know that the items (condiments) in your list are unique or maybe use tuple/namedtuple to provide a structure to your input data - name-of-item: count-of-item. And then you can use more efficient techniques to extract your desired data.
I feel like this is some homework problem, and I am not quite sure about the policy of SO regarding that. Regardless of that, I would suggest focusing on the ideas provided by the answers here and apply yourself instead of copy-pasting the (pseudo-)solutions.
Yes you can use range function with loop to count numbers. Range function return sequence of numbers and takes 3 parameters
Syntax
range(start, stop, step).
start and step are optional.
To learn about range function, visit
https://www.w3schools.com/python/ref_func_range.asp
the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
def count_cans():
count=0
for i in range(1,len(the_list)+1,2):
count+=int(the_list[i])
return count
Pick out the numbers and then add them up.
the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
def count_cans (list) :
sum = 0
for element in list :
if type (element) == int :
sum += element
return sum
print (count_cans (the_list))
the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
sum([the_list[i] for i in range(1,len(the_list),2)])
It works by :
creating a new list using a comprehension of the_list index by a range
starting with 1 and iterating every other value
then passing that to the sum() function

Is there a way to sort an unsorted list with some repeated elements?

I am trying to sort an unsorted list [4, 5, 9, 9, 0, 1, 8]
The list has two repeated elements. I have tried to approach the question by having a loop that goes through each element comparing each element with the next in the list and then placing the smaller element at the start of the list.
def sort(ls:
ls[x]
x = [4, 5, 9, 9, 0, 1, 8]
while len(x) > 0:
for i in the range(0, len(x)):
lowest = x[i]
ls.append(lowest)
Please, could someone explain where I am going wrong and how the code should work?
It may be that I have incorrectly thought about the problem and my reasoning for how the code should work is not right
I do not know, if this is exactly what you are looking for but try: sorted(ListObject).
sorted() returns the elements of the list from the smallest to the biggest. If one element is repeated, the repeated element is right after the original element. Hope that helped.
Yes, you can try x.sort() or sorted(x). Check this out https://www.programiz.com/python-programming/methods/built-in/sorted. Also, in your program I don't see you making any comparisons, for example, if x[i] <= x[i+1] then ...
This block of code is just gonna append all the elements in the same order, till n*n times.
Also check this https://en.wikipedia.org/wiki/Insertion_sort
For a built-in Python function to sort, let y be your original list, you can use either sorted(y) or y.sort().Keep in mind that sorted(y) will return a new list so you would need to assign it to a variable such as x=sorted(y); whereas if you use x.sort() it will mutate the original list in-place, so you would just call it as is.
If you're looking to actually implement a sorting function, you can try Merge Sort or Quick Sort which run in O (n log n) in which will handle elements with the same value. You can check this out if you want -> https://www.geeksforgeeks.org/python-program-for-merge-sort/ . For an easier to understand sorting algorithm, Insertion or Bubble sort also handle duplicate as well but have a longer runtime O (n^2) -> https://www.geeksforgeeks.org/python-program-for-bubble-sort/ .
But yea, I agree with Nameet, what you've currently posted looks like it would just append in the same order.
Try one of the above suggestions and hopefully this helps point you in the right direction to if you're looking for a built-in function or to implement a sort, which can be done in multiple ways with different adv and disadv to each one. Hope this helps and good luck!
There are several popular ways for sorting. take bubble sort as an example,
def bubbleSort(array):
x = len(array)
while(x > 1): # the code below make sense only there are at least 2 elements in the list
for i in range(x-1): # maximum of i is x-2, the last element in arr is arr[x-1]
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
x -= 1
return array
x = [4, 5, 9, 9, 0, 1, 8]
bubbleSort(x)
your code has the same logic as below
def sorts(x):
ls = []
while len(x) > 0:
lowest = min(x)
ls.append(lowest)
x.remove(lowest)
return ls
x = [4, 5, 9, 9, 0, 1, 8]
sorts(x)
#output is [0, 1, 4, 5, 8, 9, 9]

python 3 vector subtraction with out numpy

I'm fairly new to coding in the python3 language. I'm trying to construct a function that takes two vectors and subtracts them. Any help would be great. Thank you in advance.
Write a function vecSubtract(vector01, vector02) which takes in two vectors as arguments, and returns the vector which is equal to vector01-vector02.
def vecSubtract(vector01,vector02):
for i in range(min(len(vector01), len(vector02))):
result = [vector01[i]-vector02[i] ]
return result
vector01 = [3, 3, 3]
vector02 = [4, 4, 4]
print(vecSubtract(vector01,vector02))
While you are looping over the vectors (lists actually), you are overwriting your result variable every time.
You probably want to use a list comprehension instead.
def vecSubtract(vector01, vector02):
result = [vector01[i] - vector02[i] for i in range(min(len(vector01), len(vector02)))]
return result
vector01 = [3, 3, 3]
vector02 = [4, 4, 4]
print(vecSubtract(vector01,vector02))
If you really want to use a for loop, you should use result.append() instead of overwriting the variable every time.
Also, it is probably not right to allow subtraction of vectors of different lengths by ignoring the surplus elements in the longer vector. Instead you should probably test that the two vectors are the same length and have the script throw an error if they are not.

How to find how many items are in the same position in two lists?python

I need to be able to check if any items in one list are also in another list but in the same position. I have seen others but they return true or false. I need to know how many are in the same position.
So compare them directly!
This of course is assuming both lists are the same length:
a = [1, 1, 2, 3, 4, 5, 7, 8, 9]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
matches = 0
for index in range(len(a)):
if a[index] == b[index]:
matches += 1
print mat
Try it here!
overlap = set(enumerate(listA)).intersection(set(enumerate(listB))
print(len(overlap))
enumerate pairs up elements with their index, so you can check how many common element/ index pairs exist between the two lists.
One advantage of this approach (as opposed to iterating through either list yourself) is that it automatically takes care of the case where the lists have different lengths.
demo

Groovy - Get first elements in multi-dimensional array

I have a groovy list of lists i.e.
list = [[2, 0, 1], [1, 5, 2], [1, 0, 3]]
I would like to get a subset of just the first elements of each array
sublist = [2, 1, 1]
I know I can loop through the and just get the first element and add, but I am trying to avoid this since I have a huge array of values. I'm trying to avoid this solution
def sublist = []
list.each {
sublist.add(it[0])
}
Thanks.
A more readable version:
list*.first()
You could try:
list.collect { it[0] }
Although that still involves iteration (although somewhat hidden). However, it's likely that any solution is going to involve iteration somewhere down the line, whether it be written by you or the library/API method you call.
If you're worried about copying the data, a better approach might be to create a custom iterator, rather than copying the data into another list. This is a great approach if you only need to traverse through the sublist once. Also, if you don't traverse to the end of the sublist, you haven't wasted any effort on the elements you never processed. For example:
bigList = [[2, 0, 1], [1, 5, 2], [1, 0, 3]]
bigListIter = bigList.iterator()
firstOnlyIter = [
hasNext: { -> bigListIter.hasNext() },
next: { -> bigListIter.next().first() }
] as Iterator
for (it in firstOnlyIter) {
println it
}
You can always turn the iterator back into a list with Iterator.toList().

Resources