I have a string like this:
val a = "some random test message"
I have a list like this:
val keys = List("hi","random","test")
Now, I want to check whether the string a contains any values from keys. How can we do this using the in built library functions of Scala ?
( I know the way of splitting a to List and then do a check with keys list and then find the solution. But I'm looking a way of solving it more simply using standard library functions.)
Something like this?
keys.exists(a.contains(_))
Or even more idiomatically
keys.exists(a.contains)
The simple case is to test substring containment (as remarked in rarry's answer), e.g.
keys.exists(a.contains(_))
You didn't say whether you actually want to find whole word matches instead. Since rarry's answer assumed you didn't, here's an alternative that assumes you do.
val a = "some random test message"
val words = a.split(" ")
val keys = Set("hi","random","test") // could be a List (see below)
words.exists(keys contains _)
Bear in mind that the list of keys is only efficient for small lists. With a list, the contains method typically scans the entire list linearly until it finds a match or reaches the end.
For larger numbers of items, a set is not only preferable, but also is a more true representation of the information. Sets are typically optimised via hashcodes etc and therefore need less linear searching - or none at all.
Related
I have a simple problem. I'm new to python and programming so I think i miss something.
The variable "account_info" is assigned earlier and is a list of lists with 4 elements each. The variable current is a user input value, which (should) appear as the first element of the lists in the list account_info.
I want to iterate over the lists in the list and compare if the first element is equal to "current".
This is the code:
for i in account_info:
if current == account_info[i][0]:
email = account_info[i][1]
additional = account_info[i][2]
pw = account_info[i][3]
print(email)
I get an error in pycharm, when running that code. It seems that I can't iterate over the lists like that, can please someone explain and show a different solution?
Thank you
As #ForceBru commented, your issue is due to how for loops in Python work. The value you get from the loop is not an index into the iterable object you're looping on, rather, it's a value from the iterable. That makes your indexing with it later almost certainly wrong (though in certain contexts it might make sense, if you have a list that contains indexes into itself).
In your case, you probably want to do something more like this:
for account in accounts_info:
if current == account[0]: # note, only the inner indexing is needed
email = account[1]
additional = account[2]
pw = account[3]
Since you're expecting the inner lists to contain four values, you could even unpack the account values that you get from iterating directly into the inner variables. Though this would happen unconditionally, so it might not do what you want. Here's what that would look like, with the print call you were doing after the loop instead moved inside the conditional (so you only print the one email address that corresponds to the value in current):
for account_id, email, additional, pw in account_info: # unpack unconditionally
if account_id == current: # use the convenient name here
print(email) # print only in the conditional
In the rare case where you really do need to iterate over indexes, you can use the range type, which behaves like a sequence of integers (starting at zero by default). So you could replace your loop with this version and the body would work as you had intended (though this is less idiomatic Python than the previous versions).
for i in range(len(accounts_info)):
If you need both the index and the current value, you can use the enumerate function, which yields 2-tuples of index and value as you iterate over it. This is often handy when you need to reassign values in a list some times:
for i, account in enumerate(accounts_info):
if account[0] == current:
accounts_info[i] = new_value # replace the whole account entry
I have this list and string
list_var=(['4 3/4','6','6 3/4'])
string_var='there are 6 inches of cement inside'
i want to check through and find if any of the elements of the list is in the string
if list_var in strin_var (wont work of course due to the fact its a list but this is what i want to achieve is to compare all of the values and if any match return true)
i tried using any function but this not seem to work i would also like to achieve this without using loops as the code i will be using this in contains extracting data from a lot of files so execution speed is an issue
you will have to iteratre over the list at least once as you are trying a search operation.
is_found = any(True for i in list_var if i in string_var)
works perfectly for this scenario.
I need to find if any word from a word list (which could be a Set or List or another structure) is contained (as a sub-string) in another String and I need the best possible performance.
This could be an example:
val query = "update customer set id=rand() where id=1000000009;"
val wordList = Set("NOW(", "now(", "LOAD_FILE(", "load_file(", "UUID(", "uuid(", "UUID_SHORT(",
"uuid_short(", "USER(", "user(", "FOUND_ROWS(", "found_rows(", "SYSDATE(", "sysdate(", "GET_LOCK(", "get_lock(",
"IS_FREE_LOCK(", "is_free_lock(", "IS_USED_LOCK(", "is_used_lock(", "MASTER_POS_WAIT(", "master_pos_wait(",
"RAND(", "rand(", "RELEASE_LOCK(", "release_lock(", "SLEEP(", "sleep(", "VERSION(", "version(")
What is the best option to achieve the best performance? I have read about the contains method but it doesn't work for sub-strings. Is the only option to iterate through the list and to use the method indexOf or there is a better option?
For Scala collections, the method to use in order to answer a question like "is there an item in this collection that satisfies my condition?" is exists (scroll up slightly when you get there because the scaladoc pages are weird about linking directly to methods).
Your condition is "does the string (query) contain this item (word)?" For this, you can use String's contains method, which comes from Java.
Putting it together, you'll get
wordList.exists { word => query.contains(word) }
// or, with some syntax sugar
wordList exists { query.contains }
You can also use .find instead of .exists, which will return an Option containing the first match that was found, instead of just a Boolean indicating whether or not something was found.
scala> wordList.exists(query.contains)
res1: Boolean = true
scala> wordList.find(query.contains)
res2: Option[String] = Some(rand()
This is advice for solution:
Check that you need to optimize it. "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."
Array is collection with fastest access to element. Use it to increase access's speed.
Sometimes use a ParArray may increase performance.
If it's acceptable, for best performance first cast string to lower case, and remove all UPPER_CASE from set.
You can use own "contains" method to find any of substring. E.g., you can group some words by their prefixes (or suffixes) and don't pass all group if next (prev) symbol is different.
Use native Java to increase performance (Scala can wrap array)
First find all positions of (, because all variants related to it. Than you can check last word's symbol.
Sorry for my English. It is not best advice, but I know small amount of people (e.g. on acm.timus.ru) which can write more faster functions at Scala.
I have an assignment, similar to scrabble. I have to check if a subset is in the set. can only use a letter once. so if subset has 2t and the set has 1t it is false.
My problem is, I used 2 inputs to allow people to enter the subset and set, but that create a string no breaks between the letters which mean split or list won't create a LIST with individual letters. (at least I can't find any way.)
My plan was something like
wordset = word.lower().split()
subset = letters.lower()
for i in range(len(subset)):
if i in subset and in set:
set.remove(i)
I know that properly won't work but until I can get it into a list or someone gives me a hint how to do it with string I can't start testing it. Sorry for so much writing.
If you wish to get a list of characters in a given string you can use a list comprehension:
characters = [x for x in some_string]
I am trying to add the current dictionary to a Redis list using a dictionary comprehension and then to print out the first (aka current) keys and values of that list. I say current because this is a process I will be continuing with a while loop to have the list building over time, but I have to always access the first keys/values.
I am sure I am totally butchering this, but this is what I have:
adict = {"a":1,"b":2,"c":3}
{rserver.rpush("list",value) for value in adict}
print(float(rserver.lindex("list",0)))
I need to get a list of both keys and values back.
Help would be MUCH appreciated. Thanks!
I am not quite positive on what your redis-list should contain (please include your expected result in the question), but assuming it should at the end of inserts look something like this ["a:1", "b:1", "c:1"], you can achieve this with
adict = {"a":1,"b":2,"c":3}
for key,value in adict.items():
rserver.rpush("list", ":".join([key, value]))
print(float(rserver.lindex("list",0))) #>>> "a:1"
(as you have not included what interface rserver exactly is, it is a bit hard to guess on its exact behavior)