All possible combinations of all possible length [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
All possible combinations of all possible length
I have array like this. It can have arbitrary length rows and cols, however, cols length is fixed for every row.
{
{a, b},
{c, d},
{e, f}
}
And i need all possible combinations with all possible length.
All combinations, example for array above:
a, b, c, d, e, f
ac, ad, ae, af, bc, bd, be, bf, ce, cf, de, df
ace, acf, ade, adf, bce, bcf, bde, bdf
How do i accomplish this?
Algorithm description will be enough, however, code example (preferably C++) will help me a lot. I understand there is recursion smell with for loops, but i can't do it properly.

You can proceed by levels as your formatted output in description.
For the first level, you will have your characters
Second level you do a cartesian product between each pair of adjacent rows (easy 2 for loops)
Third level : for each result in second level, do a cartesian product with the row following the 2 adjacent rows
and so on.. until level N where N is the number of rows

An algorithm for your example is:
function rec(str, array, level)
if level = array.size()
print str
else
for i in append(array[level], "")
rec(concat(str, i), array, level + 1)
endfor
endif
You would start with
rec("", {{a, b},{c, d},{e, f}}, 0)

Related

Update series of numeric values in long string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have text column with following examplary data:
5,5,0.1;6,6,0.15;7,7,0.2;8,8,0.25;9,9,0.3;10,10,0.35;11,11,0.4;12,12,0.45;13,13,0.5;14,14,0.55;15,15,0.6;16,16,0.65;17,17,0.7;18,18,0.75;19,19,0.8;20,20,0.85;
I need to add some fixed value to each of numeric values (the one before semicolon)
so for example from:
5,5,0.1;6,6,0.15; I want add 0.15 so result would be:
5,5,0.25;6,6,0.3;
I guess I should try something with regexp_replace but I have no idea how to start here
The correct solution would be fix your broken data model and not store multiple, delimited values in a single column.
I wouldn't do this with a regex, but unnesting the elements of the string, adding the value to the third element, then aggregate everything back into the broken design:
update badly_designed_table
set denormalized_column =
(select string_agg(concat_ws(',', a, b, round(c + 0.15,2)), ';' order by idx)
from (
select split_part(val, ',', 1) as a,
split_part(val, ',', 2) as b,
split_part(val, ',', 3)::numeric as c,
idx
from unnest(string_to_array(bad_column, ';')) with ordinality as x(val,idx)
-- skip the "empty" element generated by the trailing ;
where nullif(val, '') is not null
) t)

Counting number of item types in a series in Python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am getting values from an api call and it returns one json value/key pair as a string at a time. I need to count how many times items with a certain prefix (which encodes the type of the item) occur:
Lets say I am getting 'abc123' as the 1st value
def getType(nodeName):
nodeCount = 0
if "abc" in nodeName:
count = count + 1
return "ABC", count
How do I retain this nodeCount value so that next time an item with prefix 'abc' comes in from the api call, the count can be incremented to 2.
Also, I need to create other counters to keep track of the count of other node types, such as 'xyz777'.
I tried to declare nodeCount as global variable but if I add "global count", that will defeat the purpose of retaining the count value for the next api call/iteration.
I am very new to python, so please let me know if there is any easy way.
Many Thanks!
You may use a collections.Counter like this:
from collections import Counter
def getType(counter, nodeName):
nodetype= nodeName.rstrip('0123456789')
counter[nodetype] += 1
return nodetype.upper(), counter[nodetype]
c= Counter()
for n in ['abc123', 'def789', 'ghijk11', 'def99', 'abc444']:
nodetype, nodecount = getType(counter= c, nodeName= n)
print('type {} \t: {}'.format(nodetype, nodecount))
print('summary:')
print(c)

How do i do arithmetic for all elements of a list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I need to find the biggest factor of the number 600851475143
so in order for doing that i want to find all primes smaller that this number
number = input("enter max number:")
def findprime (number):
prime = [1,2]
for i in range (2,number):
if(i%)
how do i preform arithmetic's for all numbers in a list?
To find the largest factor, find the smallest one and divide. And you only need to check up to the sqrt of the number:
factor = 0
for i in range (2, int(number**0.5) + 1):
if number%i == 0:
factor = i
break
if factor: print(number/factor)
else: print number, 'is prime'

R: Find product codes using Regular Expressions [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
So I have a list of product item descriptions. I have loaded this into R. Most of these descriptions are utter nonsense and we are trying to extract a decent item code from them.
Instead of going through it line by line, can I use a regular expression in R to create a new vector that will only have integer values from the list?
I have most of the code now
JJ <- read.csv2(file.choose(),header= TRUE)
JJ$X <- gsub(pattern = "[0-9]+", replacement = "",
x = JJ$LGY_DHB_ITEM_DESCRIPTION, ignore.case = TRUE)
But I am unsure what to put in the replacement argument.
you can try replacing non (^) numerical ([:digit:]) characters with empty string :
gsub("[^[:digit:]]*", "", 'PRIVATE CONTRACT INV 710456354')
[1] "710456354"
but this wont work if you have more than one numeric in your string:
gsub("[^[:digit:]]*", "", 'PRIVATE 123 CONTRACT INV 710456354')
[1] "123710456354"
You could try to find the longest numercial in each string:
JJ <- data.frame(LGY_DHB_ITEM_DESCRIPTION=c('PRIVATE CONTRACT INV 710456354', 'PRIVATE 123 CONTRACT INV 710456354'))
m <- gregexpr("[0-9]*", JJ$LGY_DHB_ITEM_DESCRIPTION)
all_m <- regmatches(JJ$LGY_DHB_ITEM_DESCRIPTION, m)
JJ$X <- mapply(FUN =function(stri,idx) stri[idx],all_m, sapply(lapply(all_m,nchar),which.max))
JJ
LGY_DHB_ITEM_DESCRIPTION X
1 PRIVATE CONTRACT INV 710456354 710456354
2 PRIVATE 123 CONTRACT INV 710456354 710456354

R : regular expression to match pattern in only the first line [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In my R code, I have the following content of x as a result of lda prediction output.
[1] lamb
Levels: lamb cow chicken
I would like to capture the word "lamb" in the first line and not the second line.
I had the following reg expression which did not work.
if (regmatches(x,regexec(".*?([a-z]+)",x))[[1]][2]=="lamb"){
cat("It is a lamb")
}
Instead, I also got the following error :-
Error in regexec(".*?([a-z]+)", x) : invalid 'text' argument
Anyone with help ?
Thanks in advance.
mf
Direct Answer:
It is a variable type error. See ?predict.lda to learn why: The return object of a predict() when used with an object of class lda is a list. You just want the first element of the list, which is a factor for an object of type integer. Factors in R store some characters for every element in their level component, which can be accessed by levels() (Read ?factor as well.). But what you want is to access the explicit value your factor shows, which can be acheived by as.character(). By the way: The second line does not get checked by the regex. It is just standard console output of a factor, see ?print.factor.
Here's an example, based on thepredict.lda() help page:
tr <- sample(1:50, 25)
train <- rbind(iris3[tr,,1], iris3[tr,,2], iris3[tr,,3])
test <- rbind(iris3[-tr,,1], iris3[-tr,,2], iris3[-tr,,3])
cl <- factor(c(rep("s",25), rep("c",25), rep("v",25)))
z <- lda(train, cl)
x_lda <- predict(z, test)
# x_lda is a list
typeof(x_lda)
# The first element of the list, called "class", is a factor of type integer.
typeof(x_lda$class)
# Now we create a character vector from the factor:
as.character(x_lda$class)
With an explicit character object, your code works for me:
x <- "lamb"
regmatches(x,regexec(".*?([a-z]+)",x))[[1]][2]=="lamb"
[1] TRUE
So you need to coerce your object to character, and then use it as the "text" argument for the regexec function.
Actual Answer:
There are better ways to do this.
You nest and chain a lot of functions in one line. This is barely readable and makes debugging hard.
If you know that the output will always consist of certain elements (especially, since you know the input of your lda prediction and therefore know the different factor levels beforehand), you can simply check them by == and maybe any() (continuing with the example from before):
levels(cl)
[1] "c" "s" "v"
any(as.character(x_lda$class)=="c")
[1] TRUE
See the help file for ?any, if you don't know what it does.
Finally, if you just want to print "It is a lamb" in the end, and your output will always just have one element, you can simply use paste():
paste("It is a", as.character(x))
[1] "It is a lamb"