Is there a way this can be done in list comprehension - python-2.7

I am trying to do this using list comprehension. I am using a subset of python 2.7 that does not allow the use of the command any or all
string_list1 = ['James Dean', 'Mr. James Dean', 'Jon Sparrow', 'Timothy Hook', 'Captain Jon Sparrow']
string_list2 = []
# Get elements that are a substring of other elements
for str1 in string_list1:
for str2 in string_list1:
if str1 in str2 and str1 != str2:
string_list2.append(str1)
print('Substrings: ', string_list2)
# remove element if another element is within it
for str2 in string_list2:
for str1 in string_list1:
if str2 in str1 and str2 != str1:
string_list1.remove(str1)
print('Desired: ', string_list1) # all elements that are unique
The result should be ['James Dean', 'Jon Sparrow', 'Timothy Hook'] basically the substrings and non substring elements

You could apply the same algorithm with list comprehension like this:
lst = ['James Dean', 'Mr. James Dean', 'Jon Sparrow', 'Timothy Hook', 'Captain Jon Sparrow']
res = [primitive for primitive in lst
if primitive not in (superstr for superstr in lst
if [substr for substr in lst if substr in superstr and substr != superstr]
)
]
print(res)
But an interpreter will not see that the inner expression (superstr ...) has to be evaluated only once, not for every iteration of the outer loop. So I would prefer to do this in two steps:
lst = ['James Dean', 'Mr. James Dean', 'Jon Sparrow', 'Timothy Hook', 'Captain Jon Sparrow']
exclude = [superstr for superstr in lst
if [substr for substr in lst if substr in superstr and substr != superstr]
]
res = [primitive for primitive in lst if primitive not in exclude]
print(res)

Related

how to print list all first name

I had a list with string first name and last name
val dataList = List("Narendra MODI","Amit SHA","Donald TRUMP","Ratan TATA","Abdul KALAM")
I want to print all the first from the list like Narendra,Amit,Donald,Ratan,Abdul
could you please help me on this in scala
The simplest option is to take the initial non-space characters from each string:
dataList.map(_.takeWhile(!_.isSpaceChar))
you can map over your list and use split on space and select the 1st index.
scala> val dataList = List("Narendra MODI","Amit SHA","Donald TRUMP","Ratan TATA","Abdul KALAM")
dataList: List[String] = List(Narendra MODI, Amit SHA, Donald TRUMP, Ratan TATA, Abdul KALAM)
scala> dataList.map( _.split(" ").headOption.getOrElse(None))
res2: List[java.io.Serializable] = List(Narendra, Amit, Donald, Ratan, Abdul)

Replace occurence in a String in Kotlin

I have two list of Strings. Now I want to replace every occurence of a word in the first list at index i with a word in the second list at index i of a sentence.
So if I have
list a=("am","I","my")
and
list b=("are","You","your")
I want the sentence "I am an amateur"
to become "You are an amateur"
What is cleanest way to do that in Kotlin (without for loop)?
First split the string to a list of its words and then map each word if it exists in list a to the corresponding word in list b. Finally rejoin the string:
val a= listOf("am","I","my")
val b= listOf("are","You","your")
val str = "I am an amateur"
val new = str
.split("\\s+".toRegex())
.map { val i = a.indexOf(it); if (i < 0) it else b[i] }
.joinToString(" ")
Another way of doing the same thing is:
var new = " $str "
a.forEachIndexed { i, s -> new = new.replace(" $s ", " ${b[i]} ") }
new = new.trim()
although this is closer to a for loop.
I assume there is no punctuation, all whitespaces are spaces and so on.
val m = a.zip(b).toMap()
return s.split(' ').joinToString(" ") { m[it] ?: it }
First you create a map m for more efficient... mapping. Then
Split the string to get a list of words
Map all words: if m contains the word, then return the value (i.e. the replacement), otherwise return the original word (since we shouldn't replace it).
Join all words, separate them by spaces.
You can use the regular expression \b\w+\b to match words in a sentence and then call replace function with the lambda that provides a replacement string for each match:
val input = "I am an amateur, alas."
val wordsToReplace = listOf("I", "am", "my")
val wordsReplaceWith = listOf("You", "are", "your")
val wordRegex = """\b\w+\b""".toRegex()
val result = wordRegex.replace(input) { match ->
val wordIndex = wordsToReplace.indexOf(match.value)
if (wordIndex >= 0) wordsReplaceWith[wordIndex] else match.value
}
println(result)
If there are a lot of word in your lists, it makes sense to build a map of them to speed up searches:
val replaceMap = (wordsToReplace zip wordsReplaceWith).toMap()
val result = wordRegex.replace(input) { match ->
replaceMap[match.value] ?: match.value
}
I think the simplest way is to create a set of regex you want and replace the string by iteration. Let's say you want to replace the word "am", your regex will be "\bam\b". You can use "(?i)\bam\b" if you want it not to be case sensitive. To make "I am an amateur" to "You are an amateur"
val replacements = setOf("\\bam\\b" to "are",
"\\bI\\b" to "You",
"\\bmy\\b" to "your")
replacements.forEach {
str = str.replace(Regex(it.first), it.second)
}

Capitalize the first string in list using python

I have a list containing strings and I want capitalize the first letter of first string using Python and not the entire list.
I have attempted the following but every first letter in the list is capitalized:
L = ("hello", "what", "is", "your", "name")
LCaps = [str.capitalize(element) for element in L)
print LCaps
So, you want to capitalize the first string and only the first string of a tuple. Use:
>>> L = ("hello", "what", "is", "your", "name")
>>> (L[0].capitalize(),) + L[1:]
('Hello', 'what', 'is', 'your', 'name')
Key points:
Strings have methods. There is no need to use the string module: just use the strings capitalize method.
By running L[0].capitalize(), we capitalize the first string but none of the others.
Because L is a tuple, we can't change the first string in-place. We can however capitalize the first string and concatenate it with the rest.
(L[0].title(),) + L[1:]
You can use title() too.

converting a list to string and printing it out python

I am trying to convert the first letter of each word of a string to uppercase in python. But i keep getting a generator object at 0x10315b8> no post before this seems to answer my question.
def capitalize(str):
newstr = str.split(' ')
newlist = []
for word in newstr:
if word[0][0] == word[0][0].upper():
newlist.append(word[0][0].upper())
newlist.append(word[0][1:])
newlist.append(" ")
convert_first = (str(w) for w in newlist)
print(convert_first)
capitalize(input("enter some string"))#calling the function
Your problem lies in how you are trying to make a string out of a list of strings. The opposite of "splitting" a string into a list is "joining" a list into a string.
def capitalize(str):
newstr = str.split(' ')
newlist = []
for word in newstr:
newlist.append(word[0].upper() + word[1:])
convert_first = ' '.join(newlist)
print(convert_first)
capitalize(input("enter some string"))#calling the function
Note: I made an attempt to have my code be as close as possible to that in the question.
Also, why is there an if statement in your code? With that in place you're really just capitalizing all the words that are already capitalized and discarding the rest since they never make it into newlist.
There are a few issues with your code:
The error message you got is for trying to print convert_first, which is a generator, not a string.
newstr is a list of words, so word is a string and word[0] is already the first character. Meaningless for word[0][0] or word[0][1:].
if word[0][0] == word[0][0].upper(): just filters all the words whose first character is not uppercase...
So simply some code will do what you described:
def capitalize(str):
newstr = str.split(' ')
newlist = []
for word in newstr:
newlist.append(word[0].upper())
newlist.append(word[1:])
newlist.append(" ")
convert_first = ''.join(w for w in newlist)
print(convert_first)
capitalize(input("enter some string"))
Or those who favors short code and generator expressions:
def capitalize(str):
print(' '.join(word[0].upper() + word[1:] for word in str.split(' ')))
capitalize(input("enter some string"))
This also removes the tailing space of the generated string, which may (not) be what you intended.

Classic ASP comparison of comma separated lists

I have two comma separated lists:-
36,189,47,183,65,50
65,50,189,47
The question is how to compare the two in classic ASP in order to identify and return any values that exist in list 1 but that don't exist in list 2 bearing in mind that associative arrays aren't available.
E.g., in the above example I would need the return value to be 36,183
Thanks
Something like this (untested):
str1 = "36,189,47,183,65,50"
str2 = "65,50,189,47"
arr1 = Split(str1, ",")
arr2 = Split(str2, ",")
for i = 0 to UBound(arr1)
found = false
for j = 0 to UBound(arr2)
if arr1(i) = arr2(j) then
found = true
end if
next
if found = false then
Response.Write(arr1(i))
end if
next
In order to solve this with regular expression you can use lookaheads (both positive and negative) and references, for example:
(zyx:~) % echo '36,189,47,183,65,50;65,50,189,47' | grep -oP '((?>(?<![^,;])[^,;]+))(?=.*;)(?!.*;(|.*,)\1(?=,|$))'
36
183
Other variant (works in PCRE but not in perl):
(zyx:~) % echo '36,189,47,183,65,50' | grep -oP '((?!(?<=,|^)65|50|189|47(?=,|$))(?<=,|^)[^,]+(?=,|$))'
36
183
Have no idea whether any of these works in asp.
VBScript has associative arrays in the form of the Dictionary object.
Dim list1, list2
list1 = "36,189,47,183,65,50"
list2 = "65,50,189,47"
Dim arr1, arr2
arr1 = Split(list1, ",")
arr2 = Split(list2, ",")
' oDict will hold values from list1
Dim oDict, i
Set oDict = Server.CreateObject("Scripting.Dictionary")
For i = 0 To UBound(arr1)
oDict(arr1(i)) = 1
Next
' Now loop through list2 and remove matching items from list1
For i = 0 To UBound(arr2)
If oDict.Exists(arr2(i)) Then
oDict.Remove arr2(i)
End If
Next
Response.Write Join(oDict.Keys, ",") ' should be "36,183"