Julia: concat strings with separator (equivalent of R's paste) - string

I have an array of strings that I would like to concatenate together with a specific separator.
x = ["A", "B", "C"]
Expected results (with sep = ;):
"A; B; C"
The R's equivalent would be paste(x, sep=";")
I've tried things like string(x) but the result is not what I look for...

Use join. It is not clear if you want ";" or "; " as a separator.
julia> x = ["A", "B", "C"]
3-element Array{String,1}:
"A"
"B"
"C"
julia> join(x, ';')
"A;B;C"
julia> join(x, "; ")
"A; B; C"
If you just want ; then just use a character ';'as a separator, if you also want the space, you need to use a string: "; "

Related

How to correctly read column from file when first element is empty

I have a data file data.txt
a
5 b
3 c 7
which I would like to load and have as
julia> loaded_data
3×3 Matrix{Any}:
"" "a" ""
5 "b" ""
3 "c" 7
but it is unclear to me how to do this. Trying readdlm
julia> using DelimitedFiles
julia> readdlm("data.txt")
3×3 Matrix{Any}:
"a" "" ""
5 "b" ""
3 "c" 7
does not correctly identify the first element of the first column as empty space, and instead reads "a" as the first element (which of course makes sense that it would). The closest I think I've gotten to what I want is using readlines
julia> readlines("data.txt")
3-element Vector{String}:
" a "
"5 b "
"3 c 7"
but from here I'm not sure how to proceed. I can grab one of the rows with all the columns and split it, but not sure how that helps me identify the empty elements in other rows.
Here's a possibility:
cnv(s) = (length(s) > 0 && all(isdigit, s)) ? parse(Int, s) : s
cnv.(stack(split.(replace.(eachline("data.txt")," "=>" "), " "), dims=1))
If the contents of the columns are sufficiently distinguishable to make the parsing uniquely defined, I'd use a regex on each line:
julia> lines
3-element Vector{String}:
" a "
"5 b "
"3 c 7"
julia> [match(r"\s*(\d*)\s*([a-z]*)\s*(\d*)", s).captures for s in lines]
3-element Vector{Vector{Union{Nothing, SubString{String}}}}:
["", "a", ""]
["5", "b", ""]
["3", "c", "7"]
You can then proceed to parse and concatenate as you wish, e.g.
julia> mapreduce(vcat, lines) do line
x, y, z = match(r"\s*(\d*)\s*([a-z]*)\s*(\d*)", line).captures
[tryparse(Int, x) y tryparse(Int, z)]
end
3×3 Matrix{Any}:
nothing "a" nothing
5 "b" nothing
3 "c" 7
In Julia 1.9, I think you should be able to write this as
stack(lines; dims=1) do line
x, y, z = match(r"\s*(\d*)\s*([a-z]*)\s*(\d*)", line).captures
(tryparse(Int, x), y, tryparse(Int, z))
end
This problem may have many edge cases to clarify.
Here is a longer option than the other answer, but perhaps better suited to tweak for the edge cases:
function splittable(d)
# find all non-space locations
t = sort(union(findall.(!isspace, d)...))
# find initial indices of fields
tt = t[vcat(1,findall(diff(t).!=1).+1)]
# prepare ranges to extract fields
tr = [tt[i]:tt[i+1]-1 for i in 1:length(tt)-1]
# extract substrings
vs = map(s -> strip.(vcat([s[intersect(r,eachindex(s))] for r in tr],
tt[end]<=length(s) ? s[tt[end]:end] : "")), d)
# fit substrings into matrix
L = maximum(length.(vs))
String.([j <= length(vs[i]) ? vs[i][j] : ""
for i in 1:length(vs), j in 1:L])
end
And:
julia> d = readlines("data.txt")
3-element Vector{String}:
" a "
"5 b "
"3 c 7"
julia> dd = splittable(d)
3×3 Matrix{String}:
"" "a" ""
"5" "b" ""
"3" "c" "7"
To get the partial parsing effect:
function parsewhatmay(m)
M = tryparse.(Int, m)
map((x,y)->isnothing(x) ? y : x, M, m)
end
and now:
julia> parsewhatmay(dd)
3×3 Matrix{Any}:
"" "a" ""
5 "b" ""
3 "c" 7

Find and print vowels from a string using a while loop

Study assignment (using python 3):
For a study assignment I need to write a program that prints the indices of all vowels in a string, preferably using a 'while-loop'.
So far I have managed to design a 'for-loop' to get the job done, but I could surely need some help on the 'while-loop'
for-loop solution:
string = input( "Typ in a string: " )
vowels = "a", "e", "i", "o", "u"
indices = ""
for i in string:
if i in vowels:
indices += i
print( indices )
while-loop solution:
string = input( "Typ in a string: " )
vowels = "a", "e", "i", "o", "u"
indices = ""
while i < len( string ):
<code>
i += 1
print( indices )
Would the use 'index()' or 'find()' work here?
Try This :
string = input( "Typ in a string: " )
vowels = ["a", "e", "i", "o", "u"]
higher_bound=1
lower_bound=0
while lower_bound<higher_bound:
convert_str=list(string)
find_vowel=list(set(vowels).intersection(convert_str))
print("Vowels in {} are {}".format(string,"".join(find_vowel)))
lower_bound+=1
You can also set higher_bound to len(string) then it will print result as many times as len of string.
Since this is your Study assignment you should look and practice yourself instead of copy paste. Here is additional info for solution :
In mathematics, the intersection A ∩ B of two sets A and B is the set
that contains all elements of A that also belong to B (or
equivalently, all elements of B that also belong to A), but no other
elements. For explanation of the symbols used in this article, refer
to the table of mathematical symbols.
In python :
The syntax of intersection() in Python is:
A.intersection(*other_sets)
A = {2, 3, 5, 4}
B = {2, 5, 100}
C = {2, 3, 8, 9, 10}
print(B.intersection(A))
print(B.intersection(C))
print(A.intersection(C))
print(C.intersection(A, B))
You can get the character at index x of a string by doing string[x]!
i = 0 # initialise i to 0 here first!
while i < len( string ):
if string[i] in vowels:
indices += str(i)
i += 1
print( indices )
However, is making indices a str really suitable? I don't think so, since you don't have separators between the indices. Is the string "12" mean that there are 2 vowels at index 1 and 2, or one vowel index 12? You can try using a list to store the indices:
indices = []
And you can add i to it by doing:
indices.append(i)
BTW, your for loop solution will print the vowel characters, not the indices.
If you don't want to use lists, you can also add an extra space after each index.
indices += str(I) + " "

How can I format this list into one string?

I have a list that contains a word. Each letter is separated by a space (as seen below).
word = ["h", " ", "e", " ", "l", " ", "l", " ", "o", " "]
I am trying to get it to print in the format:
h e l l o
I tried using a print statement (among other things) but it just came out:
["h", " ", "e", " ", "l", " ", "l", " ", "o", " "]
How do I fix this?
You could str.join(iterable) to join them together as one string:
"".join(word)
This will join all elements of the array with empty strings, essentially concatenating the strings together into one. Then you can print it:
print("".join(word))
This will produce
h e l l o
Just use the join function to convert the List into a string:
print ("".join(my_word))
The "" before .join means that between the characters an empty space will be added. If you want you can put whatever you like, even spaces or digits or strings.

How do I split a string with multiple separators in lua?

I want to split a string into an array divided by multiple delimiters.
local delim = {",", " ", "."}
local s = "a, b c .d e , f 10, M10 , 20,5"
Result table should look like this:
{"a", "b", "c", "d", "e", "f", "10", "M10", "20", "5"}
Delimiters can be white spaces, commas or dots.
If two delimiters like a white space and comma are coming after each other, they should be collapsed, additional whitespaces should be ignored.
This code splits the string as required by building a pattern of the complement of the delimiter set.
local delim = {",", " ", "."}
local s = "a, b c .d e , f 10, M10 , 20,5"
local p = "[^"..table.concat(delim).."]+"
for w in s:gmatch(p) do
print(w)
end
Adapt the code to save the "words" in a table.

Password generator function in R

I am looking for a smart way to code a password generator function in R:
generate.password (length, capitals, numbers)
length: the length of the password
capitals: a vector of defining where capitals shall occur, vector reflects the corresponsing password string position, default should be no capitals
numbers: a vector defining where capitals shall occur, vector reflects the corresponsing password string position, default should be no numbers
Examples:
generate.password(8)
[1] "hqbfpozr"
generate.password(length=8, capitals=c(2,4))
[1] "hYbFpozr"
generate.password(length=8, capitals=c(2,4), numbers=c(7:8))
[1] "hYbFpo49"
There is function which generates random strings in the stringi (version >= 0.2-3) package:
require(stringi)
stri_rand_strings(n=2, length=8, pattern="[A-Za-z0-9]")
## [1] "90i6RdzU" "UAkSVCEa"
So using different patterns you can generate parts for your desired password and then paste it like this:
x <- stri_rand_strings(n=4, length=c(2,1,2,3), pattern=c("[a-z]","[A-Z]","[0-9]","[a-z]"))
x
## [1] "ex" "N" "81" "tsy"
stri_flatten(x)
## [1] "exN81tsy"
Here's one approach
generate.password <- function(length,
capitals = integer(0),
numbers = integer(0)) {
stopifnot(is.numeric(length), length > 0L,
is.numeric(capitals), capitals > 0L, capitals <= length,
is.numeric(numbers), numbers > 0L, numbers <= length,
length(intersect(capitals, numbers)) == 0L)
lc <- sample(letters, length, replace = TRUE)
uc <- sample(LETTERS, length(capitals), replace = TRUE)
num <- sample(0:9, length(numbers), replace = TRUE)
pass <- lc
pass[capitals] <- uc
pass[numbers] <- num
paste0(pass, collapse = "")
}
## Examples
set.seed(1)
generate.password(8)
# [1] "gjoxfxyr"
set.seed(1)
generate.password(length=8, capitals=c(2,4))
# [1] "gQoBfxyr"
set.seed(1)
generate.password(length=8, capitals=c(2,4), numbers=c(7:8))
# [1] "gQoBfx21"
You can also add other special characters in the same fashion. If you want repeated values for letters and numbers, then add replace =TRUE in sample function.
I liked the solution given by #Hadd E. Nuff... and What I did, is the inclusion of digits between 0 and 9, at random... here is the modified solution...
generate.password <- function(LENGTH){
punct <- c("!", "#", "$", "%", "&", "(", ")", "*", "+", "-", "/", ":",
";", "<", "=", ">", "?", "#", "[", "^", "_", "{", "|", "}", "~")
nums <- c(0:9)
chars <- c(letters, LETTERS, punct, nums)
p <- c(rep(0.0105, 52), rep(0.0102, 25), rep(0.02, 10))
pword <- paste0(sample(chars, LENGTH, TRUE, prob = p), collapse = "")
return(pword)
}
generate.password(8)
This will generate very strong passwords like:
"C2~mD20U" # 8 alpha-numeric-specialchar
"+J5Gi3" # 6 alpha-numeric-specialchar
"77{h6RsGQJ66if5" # 15 alpha-numeric-specialchar

Resources