In nim language, how to search for the index of the first appearance of an object - seq

Newbie in nim here.
While experimenting in nim, I didn't find a proc to be able to find the first occurrence of an item in a sequence.
What I practically want to do is, given a seq, to remove the first instance of a known string, and return the same sequence, with the item removed. So I was thinking, to break it in a two-step work: first find the index and then remove the item at the specific index.
Of course I can write my own helper function for this, but I am surprised that I couldn't find in the system or sequtils modules any similar solution.

That would just be:
var s = #["a", "b", "c"]
s.del(s.find("b"))
The del function modifies the sequence in place. You would start with a copy of the sequence if you want a new value.

Related

I don't understand how the following expression works

This is the part of the code I have copied to see the output,
def check(string,sub_str):
if(string.find(sub_str)==-1):
print('no')
else:
print('yes)
# driver code for testing the above function
string='geeks for geeks'
sub_str='geeks'
I specifically wanted to understand how this expression works :
if(string.find(sub_str)==-1): . Also this code is for finding substrings in a given strings can some one tell if this is the optimal way, I know it is tutorial code but I have an easier way to find the substrings. Just wanted to know if that would make passing test cases easier hence the above code. Anyways thanks y'all for your answers.
The method find() returns the index of the string you are looking for. The string in front of find() is the one in which you are looking for the second string.
SentenceThatIsCompletelySearched.find(ForThisPartHere)
If the string you are looking for is present it will return the index (a number on which position of the sentence the string has been found).
If the string is not inside the sentence then find() will return -1 (a number).
So in your case you are checking if sub_str is inside string and if it is not present (return of -1) you will print "no". If it is you will print "yes".

iterating over list in list; python

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

Extract substring using index in Pharo Smalltalk

I'm trying to get a substring from an initial string in Smalltalk. I'm wondering if there's a way to do it. For example in Java, the method aStringObject.substring(index), allows you to trim a String object using an index (or its position in the array). I've been looking in the browser for something that works in a similar way, but couldn't find it. So far every trimming method uses a character or string to do the separation.
As an example of what I'm looking for:
initialString:='Hello'.
finalString:=initialString substring: 1
The value of finalString should be 'ello'.
In Smalltalk a String is a type of SequencableCollection so you can use the copying protocol messages as well.
For example you could use:
copyFrom: start to: stop
allButFirst (will not copy the first character)
allButFirst: n (more generally answer a copy of the receiver containing all but the first n elements.

Add Dictionary Keys and Values to Redis List

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)

Checking if values in List is part of String

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.

Resources