Menu
  • HOME
  • TAGS

Checking a relation of a prolog list element

Tag: list,prolog

Lets say I have a relations

Happy(james)
Happy(harry)
unhappy(Tom)
unhappy(Ben)
unhappy(Dick)

And then a list of people

[Ben, James, Harry, Tom, Dick]

How can I iterate the list and check the boolean of each list element as to whether they are happy or not?

Best How To :

Well, first of all, in Prolog, if a word starts with a capital letter, it means that it is a variable. So you should be careful with that.

This is my database after the correction:

happy(james).
happy(harry).
unhappy(tom).
unhappy(ben).
unhappy(dick).

and I added a recursive rule that helps me see who is happy and who is not from a given list:

emotion([]).
emotion([H|T]):- happy(H),emotion(T),
                 write(H),write(' is happy.'),
                 nl;
                 unhappy(H),emotion(T),
                 write(H),write(' is unhappy.'),
                 nl.

Here is the result:

4 ?- emotion([ben, james, harry, tom, dick]).
dick is unhappy.
tom is unhappy.
harry is happy.
james is happy.
ben is unhappy.
true.

Reduction of list dimensions in Python

python,list,indexing,nodes

Change your last line to: nodeclass[k].extend(nodeindex) The two extra list wrappings you're creating are happening in: The list comprehension inside the indices function. The [nodeindex] wrap in the append call. ...

ZipList with Scalaz

list,scala,scalaz,applicative

pure for zip lists repeats the value forever, so it's not possible to define a zippy applicative instance for Scala's List (or for anything like lists). Scalaz does provide a Zip tag for Stream and the appropriate zippy applicative instance, but as far as I know it's still pretty broken....

Implementing a dictionary function to calculate the average of a list

python,list,dictionary

I think you want something more like: print("Enter positive, negative or zero to determine the average: ") # get list of values/numbers from the user values = [i for i in iter(lambda: int(input("Enter a number (-9999 to end): ")), -9999)] -9999 is the sentinel value to break the loop def...

chunk of data into fixed lengths chunks and then add a space and again add them all as a string

regex,list,join,ironpython,findall

You can simply do x="a85b080040010000" print re.sub(r"(.{2})",r"\1 ",x) or x="a85b080040010000" print " ".join([i for i in re.split(r"(.{2})",x) if i]) ...

How can I iterate through nested HTML lists without returning the “youngest” children?

javascript,jquery,html,list,loops

You could just check the nesting level by counting parents $("ul li").each(function() { if ( $(this).parents('ul').length < 3 ) { // do stuff } }); FIDDLE To make it more dynamic one could simply find the deepest nesting level and filter based on that var lis = $("ul li"); var...

C++ atomic list container

c++,list,stl,containers,atomic

The first and most important problem: this can't possibly work. You need synchronization around the execution of the member functions, not around retrieving the list. std::atomic doesn't even begin to resemble what you need. Regarding your attempted implementation, casting an atomic<T> to T& can't do anything reasonable. And even if...

Avoid recursion in predicate

prolog

OK, this is a complex issue. You assume it is a trick question, but is it really one? How can we be sure? I will let library(clpfd) do the thinking for me. First I will rewrite your program: :- use_module(library(clpfd)). fx([],0). fx([H|T],S):- fx(T,S1), S1 #> 2, S #= S1 +...

Why cant I refer to a random index in my 4D list, while I know it exists?

c#,list,for-loop,dimensions

Based on your code where you're filling your 4D list: List<string> Lijst1D = new List<string>(); Lijst2D.Add(Lijst1D); Here you're creating new List<string> and adding it to parent 2D list. But Lijst1D itself doesn't contains any elements (you haven't added anything to it), so Lijst4D[0] will throw that IndexOutOfRangeException as well as...

How do I read this list and parse it?

python,list

Your list contains one dictionary you can access the data inside like this : >>> yourlist[0]["popularity"] 2354 [0] for the first item in the list (the dictionary). ["popularity"] to get the value associated to the key 'popularity' in the dictionary....

How can I call a function random inside other function in prolog?

prolog,prolog-assert

In prolog there is no concept of functions like you are trying to do in your code. You should do: random(N), assert(fact(N)) I recommend reading at least first two chapters Learn Prolog Now! to better understand search and unification....

Python - Using a created list as a parameter

python,list,loops,if-statement,compare

I believe you are incorrectly referencing to num instead of line which is the counter variable in your for loops, you either need to use num as the counter variable, or use line in the if condition. def countGasGuzzlers(list1, list2): total = 0 CCount = 0 HCount = 0 for...

prolog rules as arguments

prolog,artificial-intelligence,expert-system

It works, at least in SWI-Prolog version 6.6.6. Let's have both rules defined: rule((fix(Advice) :- (bad_component(X), fix(X, Advice))), 100). rule((fix(Advice) :- (bad_component(X); fix(X, Advice))), 100). If we ask for available rules we obtain both of them: ?- rule((A :- B), C). A = fix(_G2329), B = (bad_component(_G2334), fix(_G2334, _G2329)), C...

Create array/list of many objects(initially unknown amount) by tag

c#,arrays,list,unity3d,gameobject

public List<GameObject> myListofGameObject = new List<GameObject>(); Start(){ myListofGameObject.AddRange(GameObject.FindGameObjectsWithTag("TagName")); myListofGameObject.AddRange(GameObject.FindGameObjectsWithTag("TagName2")); myListofGameObject.AddRange(GameObject.FindGameObjectsWithTag("TagName3")); foreach(GameObject gc in myListofGameObject){ Debug.Log(gc.name); } } Works Perfectly fine for me, Make sure to add the System class for linq generics....

Filter list using Boolean array

python,list

Python does not support boolean indexing but you can use the itertools.compress function. In [49]: from itertools import compress In [50]: l = ['a','b','c'] In [51]: b = [True,False,False] In [52]: list(compress(l,b)) Out[52]: ['a'] ...

Python 2.7 “list index out of range”

python,list

I can try to explain what is going on. You are trying to find the longest substring in alphabetical order by looking for the end of the substring. Your definition of end is that there is a character less than the last character in the string -- something in descending...

Loop by Object inside another Object in Java

java,list,oop,collections

This will solve the problem, seasonMap contains values in the order you need (assuming classes implement Comparable) Map<Season, Map<Building, List<Info>>> seasonMap = new TreeMap<>(); for (Building building : buildings) { for (Map.Entry<Season, List<Info>> e : building.infosBySeason.entrySet()) { Season season = e.getKey(); List<Info> infos = e.getValue(); if (!seasonMap.containsKey(season)) { seasonMap.put(season, new...

Zip with tuples and list

python,string,list,zip,tuples

To correct your code, here is the fix: def twoStrings(string1,string2): return zip(string1,string2) ...

Stopping list selection in Python 2.7

python,list,python-2.7

You can simply filter the tuples from the list as a generator expression and then you can stop taking the values from the generator expression when you get the first tuple whose second element is -1, like this >>> s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)] >>>...

Python regular expression, matching the last word

python,regex,list

Use the alternation with $: import re mystr = 'HelloWorldToYou' pat = re.compile(r'([A-Z][a-z]*)') # or your version with `.*?`: pat = re.compile(r'([A-Z].*?)(?=[A-Z]+|$)') print pat.findall(mystr) See IDEONE demo Output: ['Hello', 'World', 'To', 'You'] Regex explanation: ([A-Z][a-z]*) - A capturing group that matches [A-Z] a capital English letter followed by [a-z]* -...

Can I put StreamReaders in a list? Or any other way to read a lot of text files at once?

c#,list,text,streamreader

You are not using curly braces, so you cannot see where the object is disposed. You code is identical to this code: List<StreamReader> lijst = new List<StreamReader>(); using (StreamReader qwe = new StreamReader("C:\\123.txt")) { using (StreamReader qwer = new StreamReader("C:\\1234.txt")) { lijst.Add(qwe); } } lijst.Add(qwer); This means that when you...

Sort List of Numbers according to Custom Number Sequence

list,python-2.7,sorting

This matches your input/output examples, but I had to use descending numbers to get the example answers. Are you sure your explanation is correct? If not, just use 0123456789 instead of 9876543210 in the code below. The algorithm is to provide a sorting key based on translating the digits of...

How to use XDocument to get attributes and add them to a List

c#,xml,winforms,list

The attributes you're trying to get aren't attribute of Payments element. You need to go one level deeper to get them. Try this way : ...... doc = XDocument.Load(reader); var data = doc.Root .Elements() .Elements("Payments"); foreach(var d in data) { var patti = d.Element("Patti"); list1.Add(new List<string>() { patti.Attribute("Rent").Value, patti.Attribute("Water").Value, patti.Attribute("Electricity").Value,...

List of tuples from (a, all b) to (b, all a)

python,list,python-2.7,tuples

You can use collections.defaultdict: tups = [ ('a1',['b1','b2','b3']), ('a2',['b2']), ('a3',['b1','b2']) ] d = collections.defaultdict(list) for a, bs in tups: for b in bs: d[b].append(a) Then: >>> d.items() [('b1', ['a1', 'a3']), ('b2', ['a1', 'a2', 'a3']), ('b3', ['a1'])] ...

prolog misunderstanding. Split list into two list with even and odd positions. where is my mistake?

list,split,prolog

The answer by CapelliC is perfect. Just to explain: When you have a Prolog clause like this: foo([H|T], [H|Z]) :- foo(T, Z). which you then call like this: ?- foo([a,b,c], L). from: foo([H| T ], [H|Z]) with H = a, T = [b,c], L = [a|Z] call: foo([a|[b,c]], [a|Z]) which...

Python RuntimeError: maximum recursion depth exceeded in cmp

python,list,dictionary,recursion

It's a bug. Fixed in 0.15.0 You're passing in empty arrays, and the function handles it incorrectly. Either update your Scipy, or skip if the arrays are empty (though check that your data isn't wrong and that it makes sense to have an empty array there). Some suggestions for your...

Django: Handling several page parameters

python,django,list,parameters,httprequest

Since, request.GET is a dictionary, you can access its values like this: for var in request.GET: value = request.GET[var] # do something with the value ... Or if you want to put the values in a list: val_list = [] for var in request.GET: var_list.append(request.GET[var]) ...

Prolog rules and query

prolog

You can use findall followed by sort to collect unique results of a query (you don't want duplicate invoices in your list), and length to check the length of the collected results. For example: findall(X, (invoice(X, C, P, _), customer(C, _, f, _), cleanProd(P)), Xs), sort(Xs, InvoicesOfWomenBuyingCleanProducts), length(InvoicesOfMenBuyingCleanProducts, N). Also,...

print method for list changes values of items

python,list

From this comment: @user2357112 her is initialization of deck of card (its source for random_itemst_stac): self.__talia = 8 * [Card(j) for j in range(1,14)] This means that you have multiple references to the same cards in your random_itemst_stac. You should be making a new Card for each card you need...

Update list of items in c#

c#,linq,list,updates

I would do something like this: (for ordinairy lists) // the current list var currentList = new List<Employee>(); currentList.Add(new Employee { Id = 154, Name = "George", Salary = 10000 }); currentList.Add(new Employee { Id = 233, Name = "Alice", Salary = 10000 }); // new list var newList =...

I need to make sure that only certain characters are in a list?

python,regex,string,list,python-2.7

With such a small range you could just iterate the move_order and check if each element exists in the allowed moves def start(): move_order=[c for c in raw_input("Enter your moves: ")] moves = ['A','D','S','C','H'] for c in move_order: if c not in moves: print "That's not a proper move!" return...

Operand order in Scala List.prepend (::)

list,scala,operators

Any operator with a : on its right side has its operands flipped. There's other operators that make use of this to (can't think of any examples off the top of my head though).

Get element starting with letter from List

java,android,list,indexof

The indexOf method doesn't accept a regex pattern. Instead you could do a method like this: public static int indexOfPattern(List<String> list, String regex) { Pattern pattern = Pattern.compile(regex); for (int i = 0; i < list.size(); i++) { String s = list.get(i); if (s != null && pattern.matcher(s).matches()) { return...

why java API prevents us to call add and remove together?

java,list,collections,listiterator

You're reading the wrong documentation: you should read ListIterator's javadoc. It says: Throws: ... IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous Now, if you want a reason, it's rather simple. You're playing...

Java Get and then remove from a list

java,list,setter,getter,instances

Removing with listOfInstances.get(1).getArrayList().remove(1); is enough and valid. In order to demonstrate this, I've written a test code for you. I've just removed the second object's ArrayList's second String element, you can compare the initial and updated states; import java.util.ArrayList; import java.util.Arrays; public class TestQuestion { public static void main(String[] args)...

represent an index inside a list as x,y in python

python,list,numpy,multidimensional-array

According to documentation of numpy.reshape , it returns a new array object with the new shape specified by the parameters (given that, with the new shape, the amount of elements in the array remain unchanged) , without changing the shape of the original object, so when you are calling the...

Sort when values are None or empty strings python

python,list,sorting,null

If you want the None and '' values to appear last, you can have your key function return a tuple, so the list is sorted by the natural order of that tuple. The tuple has the form (is_none, is_empty, value); this way, the tuple for a None value will be...

Syntax Error, Operator Expected

sql-server,prolog

Try: lemmas:- odbc_query('my_db', 'SELECT * ,case \ when ActualCost<EstimatedCost then \'true\' \ else \'false\' \ end as Value \ from Work_Order ' ). ...

Prolog: Summing elements of two lists representing an integer(restrictions inside not regular sum!!)

list,prolog

Your list is for all intents and purposes a base-100 number. The easy way to solve it is to do the arithmetic in the same way in which you would evaluate it long hand: start with the least significant digit, working to the most significant digit, sum each pair of...

Easiest way to Add lines wrong a .txt file to a list

c#,string,list,streamreader

I want to put all the lines of the file in a list Then you are working currently working too hard. You can use File.ReadLines, which yields an IEnumerable<string> and pass that into a List<string>: var allTextLines = new List<string>(File.ReadLines(path)); ...

Python 3.4: List to Dictionary

python,list,python-3.x,dictionary

You can use unpacking operation within a dict comprehension : >>> my_dict={i:j for i,*j in [l[i:i+4] for i in range(0,len(l),4)]} >>> my_dict {'Non Recurring': ['-', '-', '-'], 'Total Other Income/Expenses Net': [33000, 41000, 39000], 'Selling General and Administrative': [6469000, 6384000, 6102000], 'Net Income From Continuing Ops': [4956000, 4659000, 4444000], 'Effect...

ANSI escape characters in gprolog

prolog,escaping,iso-prolog

write('\33\[1mbold\33\[0m'). That is, octal escape sequences (and hexadecimal which start with \x) need to be closed with a \ too. En revanche, a leading zero is not required, but possible. This is in no way specific to GNU, in fact, probably all systems close to ISO Prolog have it....

join two different list by id into one list

c#,list,join,merge,automapper

Join them on id and then call ToList: var productResponses = from p in products join pd in productDescriptions on p.id equals pd.id select new ProductResponse { id = p.id, language = pd.language, // ... } var list = productResponses.ToList(); ...

Find a single duplicate in a list of lists Netlogo

list,duplicates,netlogo

This is quick and dirty, but find-dup should return the first duplicated item (in this case a sublist) in the list. to go let listA [[-9 2] [-9 1] [-9 0][-9 -1][-9 -2][-9 -3][-9 -4][-8 0][-9 0]] show find-dup listA end to-report find-dup [ c ] ;returns the first duplicated...

Solving constraints with string concatenations in Prolog

prolog,swi-prolog

If you do experiments as a beginner, better stick to using the prolog-toplevel. In this manner you can rapidily identify the problem. Since you are most probably using SWI7 - like so: ?- append("hello ", B, FinalString), append(A, "world", FinalString), append(A, B, FinalString). false. So if this is false, lets...

Insertion into a list doesn't reflect outside function whereas deletion does?

list,lisp,common-lisp

Append isn't supposed to modify anything Why doesn't append affect list y? The first sentence of the documentation on append is (emphasis added): append returns a new list that is the concatenation of the copies. No one ever said that append is supposed to modify a list. You can't change...

how to insert into python nested list

python,list,list-comprehension

The problem is you are trying to insert as the first element of the list, list5 which is incorrect. You have to access the first element of the list and insert it to that list. This can be done using the following code >>> list5 = [[], [(1,2,3,4), 2, 5]]...

group indices of list in list of lists

python,list

Use collections.OrderedDict: from collections import OrderedDict od = OrderedDict() lst = [2, 0, 1, 1, 3, 2, 1, 2] for i, x in enumerate(lst): od.setdefault(x, []).append(i) ... >>> od.values() [[0, 5, 7], [1], [2, 3, 6], [4]] ...

Saving elements of a list as data.frames using R

r,list,save,lapply

You can loop using names of the list object and save lapply(names(mylistdf), function(x) { x1 <- mylistdf[[x]] save(x1, file=paste0(getwd(),'/', x, '.RData')) }) ...