Partitioning a string to get a list in Groovy - string

I have the following String :
def s="txtimgtxtvdd"
i want to extract a list from the String above as following
def l=["txt","img","txt","vdd"]
Each 3 consecutive letters is an item of list

You can use collate (and toList to split the string into a list of chars)
def part = 'txtimgtxtvdd'.toList().collate( 3 )*.join()
assert part == ['txt', 'img', 'txt', 'vdd']

Related

List Comprehension with "if" is not returning the same output as when I make a For Loop when counting the number of unique letters in a word

Can someone explain to me why there is a difference in output when using nested loops vs nested list comprehension?
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def unique_english_letters (word) :
unique = []
for i in word:
if i not in unique:
unique.append(i)
return len(unique)
print(unique_english_letters("mississippi"))
# outputs 4 (my expected output)
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def unique_english_letters (word) :
unique = []
unique = [i for i in word if i not in unique]
return len(unique)
print(unique_english_letters("mississippi"))
#outputs 11 (length of mississippi"
^ Output
In the second example, this:
unique = []
unique = [i for i in word if i not in unique]
is equivalent to:
unique = [i for i in word if i not in []]
unique is an empty list while the list comprehension is evaluated, and then unique is re-assigned the results.
To do what you want in simple terms, use a set which can only contain unique values, and use set intersection(& operator) to generate the set of letters contained in word:
letters = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
def unique_english_letters(word):
return len(letters & set(word))
print(unique_english_letters("mississippi"))
# output: 4

how to add characters from array into one string python

I'm trying to change characters from x into upper or lower character depending whether they are in r or c. And the problem is that i can't get all the changed characters into one string.
import unittest
def fun_exercise_6(x):
y = []
r = 'abcdefghijkl'
c = 'mnopqrstuvwxz'
for i in range(len(x)):
if(x[i] in r):
y += x[i].lower()
elif(x[i] in c):
y += x[i].upper()
return y
class TestAssignment1(unittest.TestCase):
def test1_exercise_6(self):
self.assertTrue(fun_exercise_6("osso") == "OSSO")
def test2_exercise_6(self):
self.assertTrue(fun_exercise_6("goat") == "gOaT")
def test3_exercise_6(self):
self.assertTrue(fun_exercise_6("bag") == "bag")
def test4_exercise_6(self):
self.assertTrue(fun_exercise_6("boat") == "bOaT" )
if __name__ == '__main__':
unittest.main()
Using a list as you are using is probably the best approach while you are figuring out whether or not each character should be uppered or lowered. You can join your list using str's join method. In your case, you could have your return statement look like this:
return ''.join(y)
What this would do is join a collection of strings (your individual characters into one new string using the string you join on ('').
For example, ''.join(['a', 'b', 'c']) will turn into 'abc'
This is a much better solution than making y a string as strings are immutable data types. If you make y a string when you are constructing it, you would have to redefine and reallocate the ENTIRE string each time you appended a character. Using a list, as you are doing, and joining it at the end would allow you to accumulate the characters and then join them all at once, which is comparatively very efficient.
If you define y as an empty string y = "" instead of an empty list you will get y as one string. Since when you declare y = [] and add an item to the list, you add a string to a list of string not a character to a string.
You can't compare a list and a string.
"abc" == ["a", "b", "c'] # False
The initial value of y in the fun_exercise_6 function must be ""

Appending Elements to a List Creates List of List in Groovy

I am parsing each element of a list one by one.
def List1 = (String[]) Data[2].split(',')
Part of this list gives me a list with elements that contain a delimiter !.
List1 = [TEST1!01.01.01, TEST2!02.02.02]
I tried to iterate each element of this list and obtain a comma separated list.
def List2 = []
List1.each { List2.add(it.split('!'))}
However, the result was a list of list.
[[TEST1, 01.01.01], [TEST2, 02.02.02]]
Instead of [TEST1, 01.01.01, TEST2, 02.02.02].
How do I avoid this and obtain a list as shown above?
How about this?
def list1 = ['TEST1!01.01.01', 'TEST2!02.02.02']
println list1.collect{it.split('!')}.flatten()
When you do List2.add(it.split('!')), you are adding list to List2 instead of single string because .split() creates a list from string.
You should firstly create list by using .split() and than add each member of list to List2.
Here is solution:
def List1 = ["TEST1!01.01.01", "TEST2!02.02.02"]
​def List2 = []
List1.each { List1member ->
def subList = List1member.split('!')
subList.each { subListMember ->
List2.add(subListMember)
}
}
println(List2)​
split() returns a list. That is the reason why I got a list of list. I found that split() can carry process multiple delimiters as well when applied with an operator.
The following returns the desired output.
def List1 = (String[]) Data[2].split(',|!')

How can I make my program recognize if item is a string or an intiger?

I'm doing some python challenges for fun and I've found a challenge which tells me to make a program that takes an input and prints the numbers in the message.
but when I run the program it prints nothing but [] in the same number as the letters in the message, and also it do not recognize if a letter is actually a number or not, it just see every letter as a string and prints empty squares.
Here's the code:
WORDS = []
NUMBERS = []
Sentence = input()
for item in Sentence:
if item == str():
WORDS.append(item)
if item == int():
NUMBERS.append(item)
print(('[%s]' % ', '.join(map(str, NUMBERS))))
Have any ideas?
Here is probably what you meant. You have to split the sentence first.
All of the resulting items will be of type string, therefore isinstance will not help.
str.isdigit() checks if a string contains only digits. If it is a number, you can convert it to an integer using int.
WORDS = []
NUMBERS = []
Sentence = input()
for item in Sentence.split():
if item.isdigit():
NUMBERS.append(int(item))
else:
WORDS.append(item)
print(('[%s]' % ', '.join(map(str, NUMBERS))))
If you do not do the split first, it will work too, but give you just single characters in the WORDS list and single numbers in the NUMBERS list.
Typechecking is usually done using isinstance(obj, cls) :
x = 42
print(isinstance(x, int))
print(isinstance(x, str))
but in your case this will not work since input() always returns a string (a string composed of numeric characters is still a string), so the proper solution is to check if the string is composed only of numeric characters (and eventually build an int from it if you need proper ints).
Also, input() returns a single string, and from your namings (WORDS) I assume you want to iterate on the distinct words, not on each characters like you actually do:
words = []
numbers = []
sentence = input()
for item in sentence.strip().split():
if item.isnumeric():
numbers.append(int(item))
else:
words.append(item)
print(('[%s]' % ', '.join(map(str, numbers))))
Use the built-in isinstance function:
if isinstance(item, str):
WORDS.append(item)
if isinstance(item, int):
NUMBERS.append(item)

Groovy remove duplicate from list using unique function

I'm using soapui groovy script.
I want to remove the duplicate from a list, using the next code:
def myStr = "aaaa ; bbbb ; ccccc"
def myList = myStr.split(";")
myList = myList.unique()
but when i tun the code i get exception:
No signature of method: [Ljava.lang.String;.unique() is applicable for
argument types: () values: [] Possible solutions:
minus(java.lang.Object), minus(java.lang.Iterable),
minus([Ljava.lang.Object;), size(), use([Ljava.lang.Object;),
use(java.lang.Class, groovy.lang.Closure)
Use tokenize() instead of split() which returns an ArrayList as compared to split which return a String Array.
def myStr = "aaaa ; bbbb ; ccccc;"
def myList = myStr.tokenize(";")*.trim()
myList = myList.unique()
or use toList() if you are using split() or cast the String array to a Set.
However, based on the question you want to remove the duplicate items from list but I do not see any duplicate item. If you mean to remove duplicate strings from the list items then use:
myList = myList.unique().collect { it.toSet().join() }
Simple, .split() returns an array, you just need to convert it to a (Groovy) List. Any of the following will make the unique() method work.
def myList = myStr.split(";").collect()
or
def myList = (List)myStr.split(";")
or
def myList = myStr.split(";").toList()
If you cast it to a java.util.Set, it'll only keep unique values!
def myList = (Set)myStr.split(";")
Gotcha: Be careful though, the strings still contain the spaces!

Resources