In Prolog, if I am taking a list such as [hello,this,is,a,sentence] as a parameter for a predicate, how do I get a return value Y such that it will return that list as a string with spaces? e.g. [hello,this,is,a,sentence] will return hello this is a sentence.
makesentence([H|T],Y):- % some code here
I was able to run through the list recursively and have Y return the same list input with this:
makesentence([],[]). % base case returns an empty list
makesentence([X],[X]). % one list element returns that element in a list
makesentence([H|T],Y):- % a list of more than one element
makesentence(T,Result), % recursively call function on the tail
append([H],Result,Y). % append the head to the rest of the list
But when I try to make the output without a list and with spaces I faulter. I have tried this:
makesentence([],'').
makesentence([X],X).
makesentence([H|T],Y):-
makesentence(T,Result),
append(H,Result,Y).
I think it has to do with the fact the append predicate in Prolog only deals with appending a list, but I am unsure. How would I procede? Thanks in advance.
SWI-Prolog has a specialized built-in for that: atomic_list_concat/3
?- atomic_list_concat([hello,this,is,a,sentence],' ',A).
A = 'hello this is a sentence'.
figured it out with the help of Daniel. To put a list into a string with spaces use atomics_to_string/3. In my case:
makesentence([X],X).
makesentence([H|T],Y):-
makesentence(T,Result),
atomics_to_string([H,Result],' ',Y).
In the line atoms_to_string([H,Result],' ',Y)., the first parameter is the list, the second is what I want to add in between each entry, in this case a space ' ' and the third parameter is the assignment of the output, which in my case is Y. Thanks to Daniel for pointing me in the right direction.
Related
Question:
Fill in the function body for the Python3 function longestWord (you should leave the function header as it appears).
The function takes a single input argument which we assume is a list of strings, with each string forming one English word. The output should be a word from the list which has the greatest number of letters.
You must use a for loop to write this function.
Answer:
def longestWord(listOfWords):
biggestWord = listOfWords[0]
biggestNum = len(biggestWord)
for word in listOfWords:
num = len(word)
if num>biggestNum:
biggestNum=num
biggestWord=word
return biggestWord
print(longestWord(["Hello", "Goodbye"]))
I understand the first three lines. It takes the first value in the list and saves the length of the word inputted. However i don't understand the rest of the code. How does it compare the two inputted words to output the longest one. What is num and word?. Thank you.
I'd like to inform you that this question is about Python3 and not C++. Anyways, what the code is doing is it's taking the first word and stores it in a variable called biggestWord. and storing the length of biggestWord in a variable called biggestNum. Then for each word in listOfWords, it stores the word in a variable called word and stroing the length of it in variable called num. Then it compares num and biggestNum. If the length of some word i.e. num is bigger than the biggest length up until now, i.e. biggestNum, then it puts num in biggestNum to indicate that that's the biggest number up until now. and puts word in biggestWord replacing the old word. Then it returns the word with the biggest length, i.e. biggestWord.
I have a list of strings, and I'm trying to find the position of the first letter of the substring I am searching for in the list of strings. I'm using the find() method to do this, however when I try to print the position of the first letter Python returns the correct position but then throws a -1 after it, like it couldn't find the substring, but only after it could find it. I want to know how to return the position of the first letter of he substring without returning a -1 after the correct value.
Here is my code:
mylist = ["blasdactiverehu", "sdfsfgiuyremdn"]
word = "active"
if any(word in x for x in mylist) == True:
for x in mylist:
position = x.find(word)
print(position)
The output is:
5
-1
I expected the output to just be:
5
I think it may be related to the fact the loop is searching for the substring for every string in the list and after it's found the position it still searches for more but of course returns an error as there is only one occurrence of the substring "active", however I'm not sure how to stop searching after successfully finding one substring. Any help is appreciated, thank you.
Indeed your code will not work as you want it to, since given that any of the words contain the substring, it will do the check for each and every one of them.
A good way to avoid that is using a generator. More specifically, next()
default_val = '-1'
position = next((x.find(word) for x in mylist if word in x), default_val)
print(position)
It will simply give you the position of the substring "word" for the first string "x" that will qualify for the condition if word in x, in the list 'mylist'.
By the way, no need to check for == True when using any(), it already returns True/False, so you can simply do if any(): ...
Im fairly new to python and want to know how to add one to the last value in a list such as [1,5,9] or [44,45,20] I know it needs a for loop somewhere but how?
you can do this my_list[-1] += 1 .
the negative index let you start from the ending of a list (or any other iterable object), so -1 index is the last element in your list.
If by "adding" you mean arithmetic addition (i.e. +), do:
mylist[-1] += 1
If by "adding" you mean appending a new item to the list, do:
mylist.append(1)
I am new to python, and when I search for a way to get a string length without using "len()", I found this answer:
sum([1 for _ in "your string goes here"])
Can someone help me understand this line,what's the '1' doing there for example?
This is basically equivalent to this:
lst = []
for dontCareAboutTheName in "your string goes here":
lst.append(1)
print(sum(lst))
The list comprehension basically collects the number 1 for each character it finds while looping through the string. So the list will contain exactly as many elements as the length of the string. And since all those list elements are 1, when calculating the sum of all those elements, you end up with the length of the string.
I am passsing an argument through robot framework. The argument is a string. "Detroit".
I want the code to break down that string to "D", "De", "Det", "Detr", "Detro","Detroi", and "Detroit". Of course if another string is entered, say "Flint" it would only break it down into the 5 elements. F, Fl, Fli, Flin, Flint.
(Pseudo Code)
def checkCity (self, x):
(take x which is the string, and make it a list of elements containing the letters as above).
(Then take each element and check it against data provided by the device(using a loop for each iteration)
(Once any of the elements are matched to the data, return another function that acts as a key press)
I'm familiar enough with python (and programming) in general to have the theory, just don't know how to code it.
I'm not familiar with the programming language that you are using but I will help out as much as I can.
For breaking down the string, you could use a while loop or a for loop, whichever you prefer. The ending condition being the length of the string that you put into the second parameter. In the loop, you can use substring method to break down the string and store each element into an array list.
Then for checking if any of the elements are matched, you would (as you have said) use a loop for each iteration.
In python you can access individual parts of a string by using
string[5:7]
That would give the 5th and 6th characters
This function in python will return a list like the one you want
def toSubLists(string):
sublists = []
for i in range(1, len(string)+1):
sublists.append(string[0:i])
return sublists