Retrieve an answer from a list in prolog - list

Hello I am a beginner in Prolog and i have stuck in the following problem.
Here it goes , I have a "database" which gives me information about the school schedule
something like this :
school(NameOfTeacher,([(Course,Day) ......]).
When asking the following
-? find(staff(NameOfTeacher,Course),Day)
the answer should be Day = (the day the course takes place). I manage to take an answer like Day = (Course,Day) but that it not what I want. Has anyone any idea of how to do this? Thank you in advance.

Remember that Prolog unification is a kind of bi-directional pattern matching, so you can use it to both create and decompose data structures:
?- Pair = (maths,monday), (_,Day) = Pair.
Pair = (maths, monday)
Day = monday
Yes

Related

How to convert list into DataFrame in Python (Binance Futures API)

Using Binance Futures API I am trying to get a proper form of my position regarding cryptocurrencies.
Using the code
from binance_f import RequestClient
request_client = RequestClient(api_key= my_key, secret_key=my_secet_key)
result = request_client.get_position()
I get the following result
[{"symbol":"BTCUSDT","positionAmt":"0.000","entryPrice":"0.00000","markPrice":"5455.13008723","unRealizedProfit":"0.00000000","liquidationPrice":"0","leverage":"20","maxNotionalValue":"5000000","marginType":"cross","isolatedMargin":"0.00000000","isAutoAddMargin":"false"}]
The type command indicates it is a list, however adding at the end of the code print(result) yields:
[<binance_f.model.position.Position object at 0x1135cb670>]
Which is baffling because it seems not to be the list (in fact, debugging it indicates object of type Position). Using PrintMix.print_data(result) yields:
data number 0 :
entryPrice:0.0
isAutoAddMargin:True
isolatedMargin:0.0
json_parse:<function Position.json_parse at 0x1165af820>
leverage:20.0
liquidationPrice:0.0
marginType:cross
markPrice:5442.28502271
maxNotionalValue:5000000.0
positionAmt:0.0
symbol:BTCUSDT
unrealizedProfit:0.0
Now it seems like a JSON format... But it is a list. I am confused - any ideas how I can convert result to a proper DataFrame? So that columns are Symbol, PositionAmt, entryPrice, etc.
Thanks!
Your main question remains as you wrote on the header you should not be confused. In your case you have a list of Position object, you can see the structure of Position in the GitHub of this library
Anyway to answer the question please use the following:
df = pd.DataFrame([t.__dict__ for t in result])
For more options and information please read the great answers on this question
Good Luck!
you can use that
df = pd.DataFrame([t.__dict__ for t in result])
klines=df.values.tolist()
open = [float(entry[1]) for entry in klines]
high = [float(entry[2]) for entry in klines]
low = [float(entry[3]) for entry in klines]
close = [float(entry[4]) for entry in klines]

Exact match of string in pandas python

I have a column in data frame which ex df:
A
0 Good to 1. Good communication EI : tathagata.kar#ae.com
1 SAP ECC Project System EI: ram.vaddadi#ae.com
2 EI : ravikumar.swarna Role:SSE Minimum Skill
I have a list of of strings
ls=['tathagata.kar#ae.com','a.kar#ae.com']
Now if i want to filter out
for i in range(len(ls)):
df1=df[df['A'].str.contains(ls[i])
if len(df1.columns!=0):
print ls[i]
I get the output
tathagata.kar#ae.com
a.kar#ae.com
But I need only tathagata.kar#ae.com
How Can It be achieved?
As you can see I've tried str.contains But I need something for extact match
You could simply use ==
string_a == string_b
It should return True if the two strings are equal. But this does not solve your issue.
Edit 2: You should use len(df1.index) instead of len(df1.columns). Indeed, len(df1.columns) will give you the number of columns, and not the number of rows.
Edit 3: After reading your second post, I've understood your problem. The solution you propose could lead to some errors.
For instance, if you have:
ls=['tathagata.kar#ae.com','a.kar#ae.com', 'tathagata.kar#ae.co']
the first and the third element will match str.contains(r'(?:\s|^|Ei:|EI:|EI-)'+ls[i])
And this is an unwanted behaviour.
You could add a check on the end of the string: str.contains(r'(?:\s|^|Ei:|EI:|EI-)'+ls[i]+r'(?:\s|$)')
Like this:
for i in range(len(ls)):
df1 = df[df['A'].str.contains(r'(?:\s|^|Ei:|EI:|EI-)'+ls[i]+r'(?:\s|$)')]
if len(df1.index != 0):
print (ls[i])
(Remove parenthesis in the "print" if you use python 2.7)
Thanks for the help. But seems like I found a solution that is working as of now.
Must use str.contains(r'(?:\s|^|Ei:|EI:|EI-)'+ls[i])
This seems to solve the problem.
Although thanks to #IsaacDj for his help.
Why not just use:
df1 = df[df['A'].[str.match][1](ls[i])
It's the equivalent of regex match.

erlcloud- dynamodb2, manage counters (update_item)

I'm having a bit of a hard time finding an answer to the problem- how can i update a value in aws ddb2 using erlang and erlcloud library.
i am managing a table for different counters, and i neet to add one (i++), to one of the records.
in the doc they suggest
{ok, Item} =
erlcloud_ddb2:update_item(
<<"Thread">>, <br>
[{<<"ForumName">>, {s, <<"Amazon DynamoDB">>}},
{<<"Subject">>, {s, <<"How do I update multiple items?">>}}],
<<"set LastPostedBy = :val1">>,
[{condition_expression, <<"LastPostedBy = :val2">>},
{expression_attribute_values,
[{<<":val1">>, <<"alice#example.com">>},
{<<":val2">>, <<"fred#example.com">>}]},
{return_values, all_new}]),
i guess that what i need to do is use ADD statement as used in this example, but i don't know any more than that.
i can see in their code:
dynamize_action(add) ->
{<<"Action">>, <<"ADD">>};
but i'm not sure how the UpdatesOrExpression value should be written
thank you very much!
after deep diving to erlcloud library, this is the answer for my question:
erlcloud_ddb2:update_item(<<"table_name">>,
[{"hash_col_name",
{n,"hash_col_value"}}],
{"field_name", 1, add},
[] ,AWSConfig).
for zeroing the index:
erlcloud_ddb2:update_item(<<"table_name">>,
[{"hash_col_name",
{n,"hash_col_value"}}],
{"field_name", delete},
[] ,AWSConfig).

Make list from list of lists with condition

I'm currently stucked with recursion over lists of lists.
The task is quite simple in any imperative language: iterate over every professor, iterate over professor's course list, and get every course that matches CourseNumber given as predicate argument to output var CourseList.
I have simple solution (other ones just fail with out of stack or returns empty list), but as you can see, it checks only if the head of the course's list matches cond.
get_teaching_courses(CourseNumber, CourseList) :-
findall(Course,
(
professor(_, [Course | _]),
member(CourseNumber, Course)
),
CourseList).
professor fact has next struct:
professor(Name, [ [CourseName , CourseNumber], .... ]).
I am thinking of making predicate over predicate, but I can't achieve it (something wrong with append I guess).
It's been like 2 days I've started learning prolog, and if you can give me any help, advice or link that can help me, I'd appreciate it.
example:
assertz(
professor(
'Bob',
[
['Math', 2],
['PE', 3]
]
)
).
Solution:
get_teaching_courses(CourseNumber, CourseList) :-
findall(CourseName,
(
professor(_, Course),
member([CourseName, CourseNumber], Course)
),
CourseList).
thanks to #CapelliC and his answer.
the problem is the incorrect pattern matching applied in member/2. Try
member([_,CourseNumber], Course)

counting occurrence of name in list of namedtuple (the name is in a nested tuple)

As the title says, i'm trying to count the occurrence of a name in a list of namedtuples, with the name i'm looking for in a nested tuple.
It is an assignment for school, and a big part of the code is given.
The structure of the list is as follows:
paper = namedtuple( 'paper', ['title', 'authors', 'year', 'doi'] )
for (id, paper_info) in Summaries.iteritems():
Summaries[id] = paper( *paper_info )
It was easy to get the number of unique titles for each year, since both 'title' and 'year' contain one value, but i can't figure out how to count the number of unique authors per year.
I don't expect you guys to give me the entire code or something, but if you could give me a link to a good tutorial about this subject this would help a lot.
I did google around a lot, but i cant find any helpful information!
I hope i'm not asking too much, first time i ask a question here.
EDIT:
Thanks for the responses so far. This is the code i have now:
authors = [
auth
for paper in Summaries.itervalues()
for auth in paper.authors
]
authors
The problem is, i only get a list of all the authors with this code. I want them linked to the year tough, so i can check the amount of unique authors for each year.
For keeping track of unique objects, I like using set. A set behaves like a mathematical set in that it can have at most one copy of any given thing in it.
from collections import namedtuple
# by convention, instances of `namedtuple` should be in UpperCamelCase
Paper = namedtuple('paper', ['title', 'authors', 'year', 'doi'])
papers = [
Paper('On Unicorns', ['J. Atwood', 'J. Spolsky'], 2008, 'foo'),
Paper('Discourse', ['J. Atwood', 'R. Ward', 'S. Saffron'], 2012, 'bar'),
Paper('Joel On Software', ['J. Spolsky'], 2000, 'baz')
]
authors = set()
for paper in papers:
authors.update(paper.authors) # "authors = union(authors, paper.authors)"
print(authors)
print(len(authors))
Output:
{'J. Spolsky', 'R. Ward', 'J. Atwood', 'S. Saffron'}
4
More compactly (but also perhaps less readably), you could construct the authors set by doing:
authors = set([author for paper in papers for author in paper.authors])
This may be faster if you have a large volume of data (I haven't checked), since it requires fewer update operations on the set.
If you don't want to use embeded type set() and want to understand the logic, use a list and if bifurcation.
If we don't use set() in senshin's code:
# authors = set()
# for paper in papers:
# authors.update(paper.authors) # "authors = union(authors, paper.authors)"
authors = []
for paper in papers:
for author in paper.authors:
if not author in authors:
authors.append(author)
You can get similar result as senshin's. I hope it helps.