I have to create a function that removes duplicate characters from a string. There are many questions regarding this same topic, but the difference is that when removing the string, it has to evaluate if the character is equal to the one before it. For example: if the string is "teeth", the output must be "teth". The code I have now:
def remove_duplicates(s):
result = ""
for char in s:
if char :
"".join(result)
print(char)
return result
If anyone can help, it would be appreciated.
def remove_duplicates(s):
result = ""
per_char = None
for char in s:
if per_char != char:
result += char
per_char = char
return result
Related
How to count a character occurrence in string in Nim, mainly using its native statements prior go to module ? eg.
var
str = "Hello World"
c : int
c = numChar( "o", str ) # <- illustration only ?
The earlier answer is correct but if you do not want to import any modules you can write your own procedure:
proc count_char(value: string = "Hello World", ch: char = 'o'): int =
var cnt_c: int = 0
for c in value:
if c == ch:
cnt_c += 1
result = cnt_c
var
val: string = "Mother Goose"
ch: char = 'o'
echo $count_char(val, ch)
PS: Unrelated - Need syntax highlight for nim-lang on SO.
Use the count function from strutils:
import std/strutils
let str = "Hello World"
let count = count(str, 'o')
assert count = 1
There’s also a string overload for counting sub strings as well.
I have two lines of the same length. I need to get the number of letters that match as letters and have different index in the string (without nesting loop into loop). How I can do it?
Would the following function work for you?
fun check(s1: String, s2: String): Int {
var count = 0
s2.forEachIndexed { index, c ->
if (s1.contains(c) && s1[index] != c) count++
}
return count
}
See it working here
Edit:
Alternatively, you could do it like this if you want a one-liner
val count = s1.zip(s2){a,b -> s1.contains(b) && a != b}.count{it}
where s1 and s2 are the 2 strings
So given this example:
string = "string"
for char in string:
if char = "a":
# change current character to some other character
elif char = "b"
# change current character to some other character
how can I make it so that the current character of the string is replaced with some other string
("replace()" changes all of the character of the same type
Thanks
i didn't know that string are immutable but i found a workaround for this passing trough a list:
string = 'aa String aa'
string = list(string)
for index in range(len(string)):
if string[index] == 'a':
string[index] = 'c'
string = "".join(string)
maybe other method are faster but if you need to specifically loop though the string this would work fine.
If you don't want to use replace or a regex, you can use this code:
string = "abstring"
new_chars = []
for char in string:
if char == "a":
char = "b"
elif char == "b":
char = "c"
new_chars.append(char)
new_string = "".join(new_chars)
print(string, new_string)
Or you could actually use replace which has a count option:
string = "abstringab"
new_string = string.replace("a", "o", 1)
new_string = new_string.replace("b", "x", 1)
print(new_string)
This is for streamsets, I am trying to write groovy script.
I have string of length 1500 chars. No delimiter. The pattern is first 4 characters are some code, next 4 characters are length of word followed by the word. Again it as 4 chars of some code and 4 chars of lenght of word followed by the word.
e.g.
22010005PHONE00010002IN00780004ROSE
When you decode,it will be like
2201 - code
0005 - Length of the word
PHONE - Word
0001 - code
0002 - Length of the word
IN - Word
0078 - code
0004 - Length of the word
ROSE - Word
and so on..
I need help on groovy script to create string if the code starts with 00.
Thus the final string would be INROSE.
I am trying using while loop and str:substring.
Any help is very much appreciated.
Thanks
def dtx_buf = record.value['TXN_BUFFER']
def fieldid = []
def fieldlen = []
def dtx_out = []
def i = 13
def j = 0
while (i < dtx_buf.size())
{
// values = record.value['TXN_BUFFER']
fieldid[j] = str.substring(values,j,4)
output.write(record)
}
Expected result "INROSE"
One way would be to write an Iterator that contains the rules for parsing the input:
class Tokeniser implements Iterator {
String buf
String code
String len
String word
// hasNext is true if there's still chars left in `buf`
boolean hasNext() { buf }
Object next() {
// Get the code and the remaining string
(code, buf) = token(buf)
// Get the length and the remaining string
(len, buf) = token(buf)
// Get the word (of the given length), and the remaining string
(word, buf) = token(buf, len as Integer)
// Return a map of the code and the word
[code: code, word: word]
}
// This splits the string into the first `length` chars, and the rest
private token(String input, int length = 4) {
[input.take(length), input.drop(length)]
}
}
Then, we can use this to do:
def result = new Tokeniser(buf: '22010005PHONE00010002IN00780004ROSE')
.findAll { it.code.startsWith('00') }
.word
.join()
And result is INROSE
Take 2
We can try another iterative method without an internal class, to see if that works any better in your environment:
def input = '22010005PHONE00010002IN00780004ROSE'
def pos = 0
def words = []
while (pos < input.length() - 8) {
def code = input.substring(pos, pos + 4)
def len = input.substring(pos + 4, pos + 8) as Integer
def word = input.substring(pos + 8, pos + 8 + len)
if (code.startsWith('00')) {
words << word
}
pos += 8 + len
}
def result = words.join()
I have to find the greatest even number possible using the digits of given number
Input : 7876541
Desired output : 8776514
Can anyone help me with the logic?
How about this?
convert it into string
sort the numbers in reverse order
join them and convert it as number
def n = 7876541
def newN = (n.toString().split('').findAll{it}.sort().reverse().join()) as Integer
println newN
You can quickly try it on-line demo
EDIT: Based on the OP comments, updating the answer.
Here is what you can do -
- find the permutations of the number
- find the even number
- filter it by maximum number.
There is already found a thread for finding the permutations, so re-using it with little changes. Credits to JavaHopper.
Of course, it can be simplified by groovified.
class Permutations {
static def list = []
public static void printPermutation(char[] a, int startIndex, int endIndex) {
if (startIndex == endIndex)
list << ((new String(a)) as Integer)
else {
for (int x = startIndex; x < endIndex; x++) {
swap(a, startIndex, x)
printPermutation(a, startIndex + 1, endIndex)
swap(a, startIndex, x)
}
}
}
private static void swap(char[] a, int i, int x) {
char t = a[i]
a[i] = a[x]
a[x] = t
}
}
def n = 7876541
def cArray = n.toString().toCharArray()
Permutations.printPermutation(cArray, 0, cArray.size())
println Permutations.list.findAll { it.mod(2) == 0}?.max()
Quickly try online demo
There is no need to create permutations.
Try this solution:
convert the source number into a string.
split the string into an array,
sort the numbers, for the time being, in ascending order,
find the index of the first even digit,
remove this number from the array (storing it in a variable),
reverse the array and add the removed number,
join the digits from the array and convert them into integer.
So the whole script looks like below:
def inp = 7876541
def chars1 = inp.toString().split('')
// findAll{it} drops an empty starting element from the split result
def chars2 = chars1.findAll{it}.sort()
// Find index of the 1st even digit
def n = chars2.findIndexOf{it.toInteger() % 2 == 0}
def dig = chars2[n] // Store this digit
chars2.remove(n) // Remove from the array
def chars3 = chars2.reverse() // Descending order
chars3.add(dig) // Add the temporarily deleted number
def out = (chars3.join()) as Integer // result
println out