Flattening a collection of collections - programming-languages

I am not sure to understand what means the term "flattening" in programming languages.
More precisely, what does it mean to "flatten a collection of collections"?
Does it means something like:
Collection< Collection< Object >> --> Collection< Object >?

This is some doc.
Also, this might be helpful:
[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] => [1, 2, 3, 4, 5, 6, 7, 8]
I think an informal definition would be "recursively get all the contents of the current collection and put all the contents into one single collection". Of course, the recursively could be ignored, in which case just one layer would be faltten.

Flattening is the process of converting several collections (themselves stored in a single collection) into one single collection that contains all of the items in the collections you had before.
Say you have some lists of random strings:
["apple", "ball"], ["cat", "dog"], ["elephant", "frog"]
Then you store those three lists in a list:
[["apple", "ball"], ["cat", "dog"], ["elephant", "frog"]]
When you flatten that list, you'll end up with one list that contains all of the elements:
["apple", "ball", "cat", "dog", "elephant", "frog"]

It means to create a single collection from all the elements in another collection, regardless of wether those elements are individual items, or collections themselves. So, given something like this:
{{0, 1, 2}, 3, 4, {5, 6}, 7}
Where {0, 1, 2} and {5, 6} are collections, then you would have a resulting array like this:
{0, 1, 2, 3, 4, 5, 6, 7}

To flatten a collection means to place them into a single object.
So if I have an array with two objects that have three elements, String name, String age and Collection Children, where children has a name element and an age element like so
Array
Obj 1: Name: Kevin Age: 27 Children: [{Name: Matt Age: 6}]
Obj 2: Name: Jim Age: 22 Children: [{Name: Jake Age: 3},{Name: Jerry Age: 7}]
Flattened out it would look like:
Obj1: Name: Kevin Age: 27 Child1Name: Matt Child1Age: 6
Obj1: Name: Jim Age: 22 Child1Name: Jake Child1Age: 3 Child2Name: Jerry Child2Age: 7
The difference is that in the first group Obj1 contains an array of objects, while in the second group obj1 is one object with the objects in the children array added as elements.

I would say yes. It can be to remove just one level of collections or all levels of collection.

Related

"IndexError: list index out of range" in very simple 3 lines of Python code

I am a newbie to the programming and trying to understand how things work.
I couldn't get my program to iterate through numpy.array normally, so I decided to try one level simple iteration through list. But still it wouldn't work!
The code is as follows:
my_list = [1, 2, 3, 4, 5, 6, 7]
for i in my_list:
print(my_list[i])
The output is:
So it doesn't take the my_list[0] index of some reason and comes out of range.
Could you please help me to understand why?
It's not clear what exactly you're trying to do. When you iterate over an iterable like a list with
for i in my_list:
each i is each member of the list, not the index of the member of the list. So, in your case, if you want to print each member of the list, use
for i in my_list:
print(i)
Think about it: what if the 3rd member of the list was 9, for example? Your code would be trying to print my_list[9], which doesn't exist.
As pointed out that's not how you should iterate over the elements of the list.
But if you persist, your loop be should over the range(my_list), at the moment you're indexing by the values of the list, and since the length is 7, the last valid index is 6, not 7.
You get an IndexError, because you are looping through the values, which means, that your first value for i is 1 and the last one is 7. Because 7 is an invalid Index for this list you get an IndexError. A suitable code would be:
my_list = [1, 2, 3, 4, 5, 6, 7]
for i in my_list:
print(i)

Trouble with removing list elements that are present in another list

I am attempting to add items to a new list from a primary list, then remove those moved items from the primary list. Essentially use and discard.
I have already attempted to use list comprehensions (Remove all the elements that occur in one list from another).
Then I attempted to use a for loop as well as an if statement to check for the elements and remove them, though when I printed the original list once again, nothing changed.
Not sure what I am doing wrong but it is extremely frustrating:
your_hand_list = []
computer_hand_list = []
computer_hand_list.append (random.sample(card_list, 5))
your_hand_list.append (random.sample(card_list, 5))
print (your_hand_list, computer_hand_list)
for card in your_hand_list and computer_hand_list:
if card in card_list:
card_list.remove(card)
Edit: Adding your code made it much easier to understand your issue. Specifically, the problem is this statement:
for card in your_hand_list and computer_hand_list:
The Python and operator does not work the way you were expecting it to in this context. Instead, the Python standard itertools library has a function called chain that will solve your problem. Here is a (greatly) simplified version of your code for illustration purposes.
Example:
from itertools import chain
card_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
your_hand_list = [1, 4, 7]
computer_hand_list = [3, 9, 10]
for card in chain(your_hand_list, computer_hand_list):
if card in card_list:
card_list.remove(card)
print(card_list)
Output:
[2, 5, 6, 8]

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

How to add new dictionaries to a dictionary of dictionaries of dictionaries, through a loop, IF a condition is met?

I want to add new dictionaries (X) to a dictionary (D) of dictionaries (A_n) of dictionaries (B_m), IF a condition is met. And this has to be done through a loop (as X could be a 100,000 samples or more).
The condition for adding is: X[“POS”] == B“POS”]. All Dictionaries X have the same key names as all dictionaries B already in D.
So first, I want to check in A1 if the values of the X[“POS”] key are identical to Bn[“POS”] key. If True, I want to add Dictionary X to B, with name B_m+1 (or some other name).
If False, I want to check the same thing in A2, etc. If X[“POS”] is in none of them, I want to add a new dictionary A3 to D, of which X will then be the first dictionary and named D1.
The code I have so far for two levels is this which is falling far short of what is required, and gives an error: TypeError: string indices must be integers.
My problem is not just about adding something to a dictionary that is a few layers deep, but also in doing this using a loop.
Any suggestion what would be the simplest and most elegant way to do this?
Edit:
Example
The dictionary D could look like this:
D = {'A1': [{'B1': {'value': [2, 3, 1, 0], 'POS_Seq': [2, 3, 1, 0]}}],
'B2': {'value': [2, 3, 1, 0], 'POS_Seq': [2, 3, 1, 0]}}
The dictionary X to be added could be this:
X = {'value': [2,3,1,0], 'POS_Seq': [2,3,1,0]}
I would write the condition as something like this:
d['A1']['B1]['POS_Seq'] == X['POS_Seq']
This gives an error:
SyntaxError: invalid syntax
After this, I would do something like:
d['A1']['B3] = X
I know what I am trying to is complicated, but I wonder whether I should use dictionaries for this. Maybe lists within a DataFrame would be easier. Any suggestions would be very much appreciated.

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

Resources