Appending Elements From Left/Start of List/Array - python-3.x

I came across appending elements to array from left. and it has two solution
Solution 1:
List = [2,3,4,5,6]
List.insert(0,1) # Using insert
List = [1,2,3,4,5,6]
Solution 2:
List = [2,3,4,5,6]
[1] + List # Concatenation of array
List = [1,2,3,4,5,6]
I'm new to Python So please can any one explain the time complexity of both solution according to me both solution takes O(n) am I right or wrong?

Related

How can I do this with list comprehension? Or how can I extract every even position element from list and store it in a list?

p = [i.text.strip() for i in soup.select('p.card-text')]
j = []
for i in p:
if p.index(i)%2 == 0:
j.append(i)
I am doing this because I only want to extract even position element from my list p.
Is there any other way to do this (to get only even position element from list)?
If not, how can I write the code above using list comprehension? I have extracted even position element using this code. I want to know of any other method I can apply or how to write list comprehension for the above code?
You can try the following by using list comprehension along with enumerate in python
p = [i.text.strip() for index,i in enumerate(soup.select('p.card-text')) if index%2==0]
Um... simply slice:
j = p[::2]
Or if select returns a list (looks like it does), do it earlier to save work:
soup.select('p.card-text')[::2]

Python 3: Add string to OBJECTS within a list

I am sure it is a very trivial question but I can not seem to find anything online, perhaps because I am not using the right terminology..
I have a list that looks like so:
list = ["abc",
"ded"]
I know how to append elements to this list, how to add elements to the beginning, etc.
What I need to do is to add a string (more specifically an asterisk (*)) before and after each object in this list. So it should look like:
list = ["*abc*",
"*ded*"]
I have tried:
asterisk = '*'
list = [asterisk] + list[0]
list = asterisk + List[0]
list = ['*'] + list[0]
list = * + list[0]
asterisk = list(asterisk)
list = [asterisk] + list[0]
and I always get:
TypeError: can only concatenate list (not "str") to list
Then of course there is the problem with adding it before and after each of the objects in the list.
Any help will be appreciated.
Just string interpolate it in as follows:
[f'*{s}*' for s in ["abc","ded"]]
Output
['*abc*', '*ded*']
Note this is for Python 3.6+ only.
For your list you use this beautiful syntax, called "list comprehension":
lst = ['abc', 'ded']
lst = ['*'+s+'*' for s in lst]
print(lst)
This would get you:
['*abc*', '*ded*']
Have you tried using a list comprehension to adjust
[('*'+i) for i in asterix]
you can give it a name just for good measure so that you can call it later
You can join the asterisks with each word
asterisked = [w.join('**') for w in lst]
The trick here is to remember that strings are iterables, so you can pass a string that contains two asterisks to the word's join method to let it prepend the word with the first asterisk and append the second one

How can I compute the average number of a nested list in Python?

I have a list:
a = [[1,2,3],[4,5,6],[7,8,9]]
And I want the average of the 3rd element of each list: (3 + 6 + 9)
Which function should i create in order to do this??
It is always better to let others know what you have tried yourself when asking questions on Stackoverflow.
Anyway, try the below code:
def third_avg(a_list):
list_of_third = [i[2] for i in a_list]
return sum(list_of_third)/len(list_of_third)
print(third_avg([[1,2,3],[4,5,6],[7,8,9]]))
Output:
6.0
This function basically creates a new list with only the third values of the sublists. Then returns the average (sum of all elements/num of elements).

List comprehension of 3 nested loops and the output is based on if-else condition

Is it possible to convert this into a list comprehension? For example, I have a list v. On the source code below, v = dictionary.keys()
v = ["naive", "bayes", "classifier"]
I have the following nested list t.
t = [["naive", "bayes"], ["lol"]]
The expected output O should be:
O = [[1 1 0], [0 0 0]]
1 if the dictionary contains the word and 0 if not. I'm creating a spam/ham feature matrix. Due to the large dataset, I'd like to convert the code below into a list comprehension for a faster iteration.
ham_feature_matrix = []
for each_file in train_ham:
feature_vector = [0] * len(dictionary)
for each_word in each_file:
for d,dicword in enumerate(dictionary.keys()):
if each_word == dicword:
feature_vector[d] = 1
ham_feature_matrix.append(feature_vector)
I couldn't test this, but this translates as:
ham_feature_matrix = [[[int(each_word == dicword) for dicword in dictionary] for each_word in each_file] for each_file in train_ham]
[int(each_word == dicword) for dicword in dictionary] is the part which changes the most compared to your original code.
Basically, since you're iterating on the words of the dictionary, you don't need enumerate to set the matching slots to 1. The comprehension builds the list with the result of the comparison which is 0 or 1 when converted to integers. You don't need to get the keys since iterating on a dictionary iterates on the keys by default.
The rest of the loops is trivial.
The issue I'm seeing here is that you're iterating on a dictionary to create a list of booleans, but the order of the dictionary isn't fixed, so you'll have different results each time (like in your original code) unless you sort the items somehow.

merging some entries in a python list based on length of items

I have a list of about 20-30 items [strings].
I'm able to print them out in my program just fine - but I'd like to save some space, and merge items that are shorter...
So basically, if I have 2 consecutive items that the combined lengths are less than 30, I want to join those to items as a single entry in the list - with a / between them
I'm not coming up with a simple way of doing this.
I don't care if I do it in the same list, or make a new list of items... it's all happening inside 1 function...
You need to loop through the list and keep joining items till they satisfy your requirement (size 30). Then add them to a new list when an element grows that big.
l=[] # your new list
buff=yourList[0] if len(yourList)>0 else "" # hold strings till they reach desired length
for i in range(1,len(yourList)):
# check if concatenating will exceed the size or not
t=yourList[i]
if (len(buff) + len(t) + 1) <= 30:
buff+="/"+t
else:
l.append(buff)
buff=t
l.append(buff) # since last element is yet to be inserted
You can extend method of list as follows:
a = [1,2,3]
b = [4,5,6]
a.append('/')
a.extend(b)
You just need to check the size of two list a and b as per your requirements.
I hope I understood your problem !
This code worked for me, you can check to see if that's what you wanted, it's a bit lenghty but it works.
list1 = yourListOfElements
for elem in list1:
try: # Needs try/except otherwise last iteration would throw an indexerror
listaAUX = [] # Auxiliar list to check length and join smaller elements. You can probably eliminate this using list slicing
listaAUX.append(elem)
listaAUX.append(list1[list1.index(elem)+1])
if len(listaAUX[0]) + len(listaAUX[1]) < 30:
concatenated = '/'.join(listaAUX)
print(concatenated)
else:
print(elem)
except IndexError:
print(elem)

Resources