How to delete substring from a list and have a full string of it present in list? - python-3.x

I have a python list having many sub-strings of a full string including the full string. Can someone help me to remove all the sub-strings from the list and have only full string.
lists = ['ab','bcd','cd','abcd','ef']
For the above input, i want the output to be as:
lists = ['abcd','ef']
Please note, not to consider the string length from this example since my actual list items length is much fluctuating.

This is not python code, but my algorithm. Hope it works
Let have 2 arrays, array1 for input and array2 for result
Find longest length element in array
For each element in array1, check with shorter elements:
if included [duplicate] -> Remove
if not keep
Add this long element in new array2 and
remove from array1
For those kept elements
Do step 2 again until finish
if only 1 element left in array1
. just add it to array2

import copy
listA = ['abc','bcd','abcd', 'ef', 'eef']
listB=copy.deepcopy(listA) # create 2nd copy of main list
new_list=[]
global longest_str
longest_str=max(listA, key=len)
l_len=len(listA)
while l_len>0:
for l in listB:
if l in longest_str and len(l)<len(longest_str):
listA.remove(l) # remove the sub-string
if longest_str == l:
new_list.append(l) #append longest string in new_list
listA.remove(l) #remove from the main list
l_len=len(listA)
if l_len>0:
longest_str=max(listA, key=len)
print(new_list)

Related

string appears as subset of character in list element python

So far, I have:
my_list = ['hello', 'oi']
comparison_list = ['this hellotext', 'this oitext']
for w in my_list:
if w in comparison_list: print('yes')
However, nothing prints because no element in my_list equals any element in comparison_list.
So how do I make this check as a subset or total occurance?
Ideal output:
yes
yes
You are checking the occurrence of the complete string in the list currently. Instead you can check for the occurrence of the string inside each comparison string and make a decision. A simple approach will be to re-write the loop as below
for w in my_list:
# Check for every comparison string. any() considers atleast 1 true value
if any([True for word in comparison_list if w in word]):
print('yes')
It's because you're comparing w to the list elements. If you wanna find w in each string in your comparison_list you can use any:
my_list = ['hello', 'oi', 'abcde']
comparison_list = ['this hellotext', 'this oitext']
for w in my_list:
if any(w in s for s in comparison_list):
print('yes')
else:
print('no')
I added a string to your list and handle the 'no' case in order to get an output for each element
Output:
yes
yes
no
Edited Solution:
Apologies for older solution, I was confused somehow.
Using re module , we can use re.search to determine if the string is present in the list of items. To do this we can create an expression using str.join to concatenate all the strings using |. Once the expression is created we can iterate through the list of comparison to be done. Note | means 'Or', so any of the searched strings if present should return bool value of True. Note I am assuming there are no special characters present in the my_list.
import re
reg = '|'.join(my_list)
for item in comparison_list:
print(bool(re.search(reg, item)))

How a Python code to store integer in list and then find the sum of integer stored in the List

List of integer value passed through input function and then stored in a list. After which performing the operation to find the sum of all the numbers in the list
lst = list( input("Enter the list of items :") )
sum_element = 0
for i in lst:
sum_element = sum_element+int(i)
print(sum_element)
Say you want to create a list with 8 elements. By writing list(8) you do not create a list with 8 elements, instead you create the list that has the number 8 as it's only element. So you just get [8].
list() is not a Constructor (like what you might expect from other languages) but rather a 'Converter'. And list('382') will convert this string to the following list: ['3','8','2'].
So to get the input list you might want to do something like this:
my_list = []
for i in range(int(input('Length: '))):
my_list.append(int(input(f'Element {i}: ')))
and then continue with your code for summation.
A more pythonic way would be
my_list = [int(input(f'Element {i}: '))
for i in range(int(input('Length: ')))]
For adding all the elements up you could use the inbuilt sum() function:
my_list_sum = sum(my_list)
lst=map(int,input("Enter the elements with space between them: ").split())
print(sum(lst))

Matching character lists of unequal length

I want to match two lists from which one list is smaller while other is a bigger one. If a match occurs between two lists then put the matching element in a new list at the same index instead of putting it another index. You can understand my question from the code given below:
list1=['AF','KN','JN','NJ']
list2=['KNJ','NJK','JNJ','INS','AFG']
matchlist = []
smaller_list_len = min(len(list1),len(list2))
for ind in range(smaller_list_len):
elem2 = list1[ind]
elem1 = list2[ind][0:2]
if elem1 in list2:
matchlist.append(list1[ind])
Obtained output
>>> matchlist
['KNJ', 'NJK', 'JNJ']
Desired Output
>>> matchlist
['AFG', 'KNJ', 'JNJ', 'NJK']
Is there a way to get the desired output?
Use a nested loop iterating over the 3-char list. When an item in that list contains the current item in the 2-char list, append it and break out of the inner loop:
list1=['AF','KN','JN','NJ']
list2=['KNJ','NJK','JNJ','INS','AFG']
matchlist = []
smaller_list_len = min(len(list1),len(list2))
for ind in range(smaller_list_len):
for item in list2:
if list1[ind] in item:
matchlist.append(item)
break
Given the question doesn't specify any constraints, in a more pythonic way, using a list comprehension:
list1=['AF','KN','JN','NJ']
list2=['KNJ','NJK','JNJ','INS','AFG']
matchlist=[e2 for e1 in list1 for e2 in list2 if e2.startswith(e1)]
produces
['AFG', 'KNJ', 'JNJ', 'NJK']

How do I iterate through a list I'm converting to a matrix from a string?

I'm very new to Python, and I'm currently going through the Matrix problem on Exercism. It's been pretty simple to this point, but I'm having trouble figuring out the best way to iterate through this list. I've been scouring through the web trying to figure it out on my own.
What I have to do is convert the string provided at the bottom to a matrix at the /n break, then to an integer so that I can use numpy to return either the rows or columns.
class Matrix(object):
def __init__(self, matrix_string):
self.matrix = matrix_string.replace(' ', '').split('\n')
self.temp = [int(i) for i in self.matrix[0]]
matrix = Matrix("1 2\n3 4")
print(matrix.temp)
I've gotten as far as converting the list, but now I need to return the entire list, not just a particular index as shown above, into a new temp list. That's where I'm stuck.
While you could convert your list as you are doing there are some problems with the following line
self.temp = [int(i) for i in self.matrix[0]]
Consider converting "12 1" your result would be 1, 2, 1 rather than 12, 1
Instead you should split on newlines and then split each line on spaces (without replacing ' ' with '')
It would be a good exercise to try to do this by yourself but I will give you a hint and a solution for if you get stuck
Hint: initialize temp as an empty list first, then append lists to it one by one
More in depth hint approach: Initialize temp as an empty list. Split matrix on newlines. Append each line to temp, split on spaces.
solution:
self.temp = []
self.matrix = matrix_string.split('\n')
for element in self.matrix:
self.temp.append(element.split(' '))
this can be simplified to one line of list comprehension
you can try that yourself or use the below
self.temp = [element.split(' ') for element in matrix_string.split('\n')]

How to iterate over each element in a list?

I have a list of strings and I am iterating over each element by using a for loop, but it seems that what I am doing is iterating over each character instead of each element of the list. For instance:
names = list(input('Enter list of names:')).upper()))
result = []
for i in names:
if 'A' not in i and 'C' in i:
result.append('membership')
elif 'A' in i and 'C' not in i:
result.append('no_membership')
else:
result.append('unknow'):
print(result)
But what I am getting is a list in which the for loop is evaluating each character in the list of strings instead of each name. Am I doing something wrong in the code or do I need to split the elements of the list?
Logically you are just trying to add the entire input into one item of the list
So the first line should read something like:
names = input('Enter list of names:').upper().split()
This will split the inputted string by spaces into a list of separate strings.

Resources