If-else statement trouble - list

My project uses an if-else statement to determine if a random image from a list of images matches to an image in another list. I'm trying to find a piece of code that will allow me to set the if-else statement so when it asks: if randomImage == list[?]. In the question mark I need code that will go through the entire list and see if the randomImage matches from ANY of the elements in the list. Here's a snippet of code: trash[randomTrash] generate a random image from the list trash. I need it so it checks if the random image of trash is equal to an image in another list. It needs to go through recycle list and determine if an element is equal to it.

There is probably an easier way to do this depending on your project specifics, but you should be able to use a for loop that loops through each element in your list.
for (int element = 0; element < list.length; element++) {
if (randomImage == list[element]) {
// randomImage matches with an element in the list. Assuming you are using some boolean variable 'match' which is initialized to be false.
match = true;
}
}

it's really helpful if you tag the language you're using, so people know how exactly to address the issue in particular.
The most common and straightforward approach you would see is looping through the whole list by index, and comparing each image to the one from it, and that's a solid working one.
If you're on a language supporting list comprehension you could take an approach similar to this,
[x for x if x==image...]
then check if the list is empty for your if/else condition.
Please let us know in particular if it's something more specific you're looking for.

Related

Prolog recursively checking if an item is in a list

So I am trying to write a piece of code that checks to see if an item is in a list or not.
is_member(_,[]).
is_member(X,[X|_]).
is_member(X,[_|tail]):- is_member(X,tail).
this is currently what I have for the code. It works if the item is in the first position but doesn't check the rest of the list. Can anyone help me figure out what i'm doing wrong? Thanks.
Your predicates faces the following two problems:
The base case is_member(_,[]). will always return true for an empty list, which is not correct; and
Your variable should start with an Uppercase character: Tail.
An example how to implement a predicate that solves these two issues:
is_member(X,[X|_]).
is_member(X,[_|Tail]):- is_member(X,Tail).

Returning an index of an alphabetical list python

So I'm working on a homework for a beginning python class. I'm asked to write a function taking two parameters, one a string and one of a list in alphabetical order. The function is to return the integer index as to where the string would be placed in order for the list to stay alphabetized.
I am not allowed to insert anything into the list, or append the list in any matter (I tried just adding the string to the list, resorting and then returning the index for where the string now lived) All the function is to return is the integer index value. I could use some direction as to where to start without using an insert and resorting... Thanks.
Because I dont want to write your homework for you, here is one way to do it in pseudo-code:
def insert_index(string, list)
for every item in your list:
if the item is greater than your string:
return index of item
else:
go to next item
weirdly enough, because of the way python is written, this is very close to actual code...
because strings are comparable, you can actually do something like 'a'<'b' and return a valid bool. and since your list is alphabetical, as soon as you hit an item that is greater than your string, then you know thats where you want your string to go.
also, it would be useful to use enumerate function for your loop structure (HINT HINT)
I would iterate over the list and compare the current string in the list with the string you are trying to insert ( < > comparators work on strings, with 'b' > 'a'. Without giving too much away, take advantage of the fact that the list you are given is already in alphabetical order to determine which index the passed in string would be placed in.
One cool thing in python is that letters are of a higher value if they are farther along in the alphabet. For example, 'b' > 'a'. In fact, you can type 'b' > 'a' into an interpreter and it will tell you 'true'. So simply loop through the alphabetical list comparing the first letter in the list item to the first letter in the string.
Something like this (I haven't checked it, so it may not work perfectly, but try to get the gist of it)
for i in range(0,len(list)):
if (list[i][0] < str[0]):
print(i)
break

Erlang - Can one use Lists:append for adding an element to a string?

Here is my function that parses an addition equation.
expr_print({num,X}) -> X;
expr_print({plus,X,Y})->
lists:append("(",expr_print(X),"+",expr_print(Y),")").
Once executed in terminal it should look like this (but it doesn't at the moment):
>math_erlang: expr_print({plus,{num,5},{num,7}}).
>(5+7)
Actually one could do that, but it would not work the way wish in X in {num, X} is a number and not string representation of number.
Strings in Erlang are just lists of numbers. And if those numbers are in wright range they can be printed as string. You should be able to find detail explenation here. So first thing you wold like to do is to make sure that call to expr_print({num, 3}). will return "3" and not 3. You should be able to find solution here.
Second thing is lists:append which takes only one argument, list of list. So your code could look like this
expra_print({num,X}) ->
lists:flatten(io_lib:format("~p", [X]));
expr_print({plus,X,Y})->
lists:append(["(", expr_print(X),"+",expr_print(Y), ")"]).
And this should produce you nice flat string/list.
Another thing is that you might not need flat list. If you planning to writing this to file, or sending over TCP you might want to use iolist, which are much easier to create (you could drop append and flatten calls) and faster.

Autocompletion library in C++

I need an auto-completion routine or library in C++ for 1 million words. I guess I can find a routine on the net like Rabin–Karp. Do you know a library that does this. I don't see it in Boost.
Also, is it a crazy idea to use MySql LIKE SQL request to do that ?
Thank you
EDIT: It is true that it is more suggestions than auto-completion that I need (propose ten words when the user typed the first 2 letters). I actually also have expressions "Nikon digital camera". But for a first version, I only need suggestions on "Ni" of Nikon and not on "digital camera".
You don't have to use any crazy algorithm if you begin by preparing an index.
A simple Trie/Binary Search Tree structure, that keeps the words ordered alphabetically, would allow efficient prefix searches.
In C++, for example, the std::map class has the lower_bound member which would point in O(log N) to the first element that could possibly extend your word.
hmmmm, if you're thinking about using like, it means that most probably, you want to have classical autocompletion (begin of word is matching).
What about organising (nicely) your data into a 26-tree (one entry per letter, or if you support other than letters, an well chosen x-tree). That way, you organize your data once and then, you have quick result by tree parsing. if you want to limit the amount of results proposed into your autocompletion, you can adapt your tree parsing algorithm. Seems simple and efficient (a like syntax in SQL will have to compare all your items in your table each time, whereas my solution is much quicker once the data is correctly set)
Other solution, you can peek at Qt implementation of QCompleter (might be overkill to depend on Qt on your code, I don't know)
I worked on a project once that did something like this using CLucene. It worked fine.
You can use a trie (prefix tree) to store your words.
struct trie
{
std::map<char, trie*> next;
bool is_word;
void insert(std::string w)
{
trie * n = this;
for (int i = 0; i < w.size(); ++i) {
if (n->next.find(w[i]) == n->next.end()) {
n->next[w[i]] = new trie();
}
n = n->next[w[i]];
}
n->is_word = true;
}
};
Then you can easily get prefix matches iterating on subtrees.
You could write your own simple auto-completion function with using Damerau-Levenshtein distance.

Prolog permutations with repetition

I'm having a hard time wrapping my head around the concept of logic programming. I'm trying to get all permutations with repetition into a give list.
I can put what I have, but I don't know what I'm doing!
perms_R(List,[]).
perms_R([X|Xt],[Y|Yt],Out) :- perms_R([Y|Xt],Yt),perms_R(Xt,[Y|Yt])
.
The idea was to go through each element in the second list and put it in my first list. I'm trying to figure this out, but I'm stuck.
I need to call perms_R([a,b,c,d],[1,2,3,4]). and get:
1,1,1,1
1,1,1,2
1,1,1,3
1,1,1,4
1,1,2,1
etc....
I understand the first list seems useless and I could just do it with a list length, but I actually need it for the remainder of my code, so I'm trying to model this after what I need. Once I get past this part, I will be putting extra logic in that will limit the letters that can be replaced in the first list, but don't worry about that part!
What you are looking for is not a permutation. You want to create a list of a given size using items from a given set.
You may do it with this snippet:
perms_R([], _).
perms_R([Item|NList], List):-
member(Item, List),
perms_R(NList, List).
You would need to pass a semi instantiated list and the source items:
perms_R([A,B,C,D],[1,2,3,4]).