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

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)

Related

haskell function to take list of integer or string and return a list of integer [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 been trying to create a function in Haskell that takes a list of integers or strings as input. It then checks the first index and it is numerical value e.g. 0-9 returns [0] if it is string value returns 1. I tried to use the function elem but got this error:
Ambiguous use of operator "elem" with "(==)"
My code is:
I am not looking for a solution which includes importing modules
The code doesn't have to follow this structure; It could be different. Output that I am looking for:
f "abcd efgh ijkl" returns [1]
f [1,2,3,4,5,6] returns [0]
Thanks!
I think you are a bit confused. Haskell doesn't do "I don't know what type that thing is".
However, if you want to write instead a function which can be cast to take a list of integers or cast to take a list of strings (contrast: "takes a list of integers or strings"), you may use a typeclass. For example:
class IsInteger a where isInteger :: proxy a -> Bool
instance IsInteger Char where isInteger _ = False
instance IsInteger Integer where isInteger _ = True
Try it out in ghci:
> isInteger "abcdefg"
False
> isInteger [0,1,2,3]
True

How to remove a given element from a list of tuples and update it in Haskell? [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
Given a list of tuples, suppose all first elements of the tuples in the list are unique, that is, there are no duplicates.
Ex. xs = [("a",4), ("f",9), ("l",4)] is valid but ys = [("a",4), ("f",9), ("a",7)] is not.
I would like to implement two functions. The first one takes the first element of a tuple, and removes that tuple from the list. Suppose a tuple with the given first element already exists in the list.
Ex. remove "f" xs returns [("a",4), ("l",4)].
Another one takes the first and second elements of a tuple respectively. Again suppose a tuple with the given first element already exists in the list. If the given second element is different from the one in the original list, update it.
Ex. update "l" 7 xs returns [("a",4), ("f",9), ("l",7)].
How should I do this?
Don't consider this an answer, but a long comment. Not all code is written because this looks like a classroom exercise and you should solve it yourself.
First, consider using Data.Map since it provides this kind of functionality. If you need to implement it with lists you should go like below:
remove key [] = -- what list should return if the given one is empty?
remove key ((k,v):xs)
| key == k = -- what should I return If input key and comparing key are equal
| otherwise = -- and if they are not? use recursion
update key value [] = -- what list should return if the given one is empty?
update key value ((k,v):xs)
| key == k = -- what should I return If input key and comparing key are equal
| otherwise = -- and if they are not? use recursion

counting up in list.generate, short flutter question

i recently started learning flutter and dart, so my apologies if this is a really simple problem, i am trying to generate a list with values from another list, as follows:
List transactions = List.generate(15, (index)=>{
“name”: names[1],
“dp”: “assets/cm1.jpeg”,
});
but i want the numbers 1 to increase by 1 with every new entry. so the list should be outputting the names in my names list 1 by 1 and cm1.jpeg, cm2.jpeg etc. similar to the i+1 code.
Thanks in advance!
You can use the index variable to get the index of the current element you are generating. So first element will run the generate method with an index value of 0, the second will have the value 1 and so on.
With this knowledge you can write something like:
List transactions = List.generate(15, (index)=>{
“name”: names[1 + index],
“dp”: “assets/cm${1 + index}.jpeg”,
});

Search an array of structs for a string variable [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 4 years ago.
Improve this question
consider:
const int CAP = 20;
struct bookType
{
string bookTitle = "EMPTY";
string ISBN = "EMPTY";
string author = "EMPTY";
string publisher = "EMPTY";
string dateAdded = "EMPTY";
int qty = 0;
double wholesale = 0.00;
double retail = 0.00;
};bookType book[CAP];
What I need to do here is hopefully simple, though I can't seem to get a straight answer on it. I want to search this array of structs (book[]) for a matching bookTitle. for instance, if I have a book named "Star Wars" I need to be able to search the array of structs by typing in "star" and finding a book, "Star Wars". I've been searching for hours, but all the solutions I've found don't seem to actually work.
I don't know the rest of you code so I'll try to give a generic answer.
It seems like you are looking for the find() function for string objects. The find function will return std::string::npos if it does not find anything.
So inside a loop, test:
Booktype[x].bookTitle.find("Star")!=std::string::npos
Change Star to the whatever you are searching for. If this condition is true then you haave a match.
Just a heads up, this is case sensitive so you might want create temporary variables and convert the titles and queries into lowercases and run the loop on them.
Hope this helps.

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"