I haven't found a way to solve this. I have a list of integer, where which element of the list is a binary digit (0 or 1) so I need to design a function which transforms this list of integers into the proper decimal number.
Example:
Input: [0,1,0]
Output: 2
But there is a specific condition, it is neccesary to use list of comprehension and you can't use recursivity.
The problem it is, when I need to know the position of the digit for apply the transform because I can't save the position in the list of comprehension.
Thank you
The problem it is, when I need to know the position of the digit for apply the transform because I can't save the position in the list of comprehension.
You can, by using zip and a range, you generate 2-tuples that carry the index, like:
[(idx, val) | (idx, val) <- zip [0..] bin]
will produce a list of 2-tuples: the first element containing the element, and the second the element of data at that position.
So if bin = [0,1,0], then the above list comprehension will result in:
Prelude> [(idx, val) | (idx, val) <- zip [0..] bin]
[(0,0),(1,1),(2,0)]
Since this seems to be the "core problem", I propose that you aim to solve the rest of the problem with the above strategy, or ask a question (edit this one, or ask a new one) if you encouter other problems.
Related
I've been seeing this syntax, but I'm not quite sure what it means. It's when two square brackets are next to the name of one list. I'm assuming this does some type of list slicing?
mylist[x][y]
mylist[][]
These are just some examples of what I've seen. (I've used variables x&y to represent an arbitrary number)
This notation can be used when the list contains some other lists as elements, which is helpful to represent the matrices. For example:
a=[[1,2,3],[4,5,6],[7,8,9]]
a[0][0] #This gives the number 1.
In this case, a[0] (the first index) chooses the 1st element, which is [1,2,3]. Then the second index (a[0][0]) chooses the first element of the list defined by a[0], thus giving the answer 1.
The top line just indexes into a list within a list. So for example, you could have
mylist = [
[1,2,3],
[4,5,6],
[7,8,9],
]
value = mylist[1][2]
which will get the value 6.
The bottom line doesn't look like valid Python to me.
EXPLANATION:
Consider that mylist[1] just extracts the second element from mylist (second because of 0-based indexing), which is [4,5,6]. Then adding [2] looks up the third item in that list, which is 6. You could also write
inner_list = mylist[1]
value = inner_list[2]
or
value = (mylist[1]) [2]
which both do the same thing.
positions :: Eq a => a -> [a] -> [Int]
positions x xs = [i | (x',i) <- zip xs [0..], x == x']
i need to create a Test function for the positions function, which passes the quickcheck.
Does someone has an idea?
A possible test could perform the following operations:
randomly generate xs, ys :: [Int] and y :: Int
define list = xs ++ y : ys
test length xs `elem` positions y list
You might also want to write tests for missing elements.
That being said, it's weird to craft tests from the code. One should design test using the specification used to write the code instead. Otherwise, if the code has some quirks, they end up in tests as well: instead of checking for what the code should do, we check for what the code does, which can be pointless.
Good question! I had a bit of trouble with this too when I started using QuickCheck, but as I used it more I started to get a feel for what sort of properties you should test. Often, a good place to start is to think about what sort of relationships should hold between the input(s) and output. Your function finds the indices of an element in a list; now what properties should hold in this case? Here's two which I can think of:
The list of indices should have the same number of elements as there are occurrences of the value in the list.
Each index should correspond to the correct value.
And here's an outline of how these properties could be tested:
Generate a random list, apply positions to it, then count the number of indices returned and check that it matches with the number of occurrences of the searched value.
Generate a random list, then apply positions to it and check that the element at each of the returned indices is the value which was searched for.
I also think that #chi's answer makes a good point in saying that you should design tests from the specification rather than the code; this ties in with what I was saying above, in that a specification can help you find relationships between input(s) and output which may not be immediately apparent from the code.
in my code i have created a nested list via list comprehension containing hex numbers. My next step was to calculate the decimal value of these hex numbers.
My last step was removing the () brackets of each element, because my former method created tupels for each list element.
My question here is, can i combine all three steps into one big step and if yes, will it be more efficient in computing ?
My code looks like this:
from struct import unpack
from codecs import decode
self.step1 = [[self.inputlist[self.otherlist[i]+k] for i in range(len(self.otherlist))]
for k in range(asd)]
self.step2 = [[unpack("<B",decode(x,"hex")) for x in y] for y in self.step1]
self.step3 = [[p[0] for p in q] for q in self.step2]
this code worked fine (i shortened it and am not showing how self.inputlist,otherlist,asd are defined). I am just curious if i can put self.step1, self.step2,self.step3 into one nested list comprehension.
Hey guys I am having a problem with my code. The code below supposed to remove the first 2 in the list and then concatenate them.So the result answer would be 1,2.
first = [1,2,4,5,6,7] !! 0
second = [1,2,4,5,6,7] !! 1
newans = first ++ second
You can not remove elements from a list: Haskell is declarative meaning once you construct a list a, a will always work with the same list.
You can however construct a new list without the first two elements, and create a new list with the first two elements. For example:
get_remove_2 :: [a] -> ([a],[a])
get_remove_2 (a:b:cs) = ([a,b],cs)
We thus construct a new list with the first two elements with the [a,b] expression.
This function will take as input a list [a] and return a 2-tuple with as first element a list with two elements: the first two elements of the original list, and as second element the list where the first two elements are not present.
Note that this function will only work if the given list contains at least two elements. Otherwise it will error.
I have the following Scala code :
val res = for {
i <- 0 to 3
j <- 0 to 3
if (similarity(z(i),z(j)) < threshold) && (i<=j)
} yield z(j)
z here represents Array[String] and similarity(z(i),z(j)) calculates similarity between two strings.
This problems works like that similarity is calculated between 1st string and all the other strings and then similarity is calculated between 2nd string and all other strings except for first and then similarity for 3rd string and so on.
My requirement is that if 1st string matches with 3rd, 4th and 8th string, then
all these 3 strings shouldn't participate in loops further and loop should jump to 2nd string, then 5th string, 6th string and so on.
I am stuck at this step and don't know how to proceed further.
I am presuming that your intent is to keep the first String of two similar Strings (eg. if 1st String is too similar to 3rd, 4th, and 8th Strings, keep only the 1st String [out of these similar strings]).
I have a couple of ways to do this. They both work, in a sense, in reverse: for each String, if it is too similar to any later Strings, then that current String is filtered out (not the later Strings). If you first reverse the input data before applying this process, you will find that the desired outcome is produced (although in the first solution below the resulting list is itself reversed - so you can just reverse it again, if order is important):
1st way (likely easier to understand):
def filterStrings(z: Array[String]) = {
val revz = z.reverse
val filtered = for {
i <- 0 to revz.length if !revz.drop(i+1).exists(zz => similarity(zz, revz(i)) < threshold)
} yield revz(i)
filtered.reverse // re-reverses output if order is important
}
The 'drop' call is to ensure that each String is only checked against later Strings.
2nd option (fully functional, but harder to follow):
val filtered = z.reverse.foldLeft((List.empty[String],z.reverse)) { case ((acc, zt), zz) =>
(if (zt.tail.exists(tt => similarity(tt, zz) < threshold)) acc else zz :: acc, zt.tail)
}._1
I'll try to explain what is going on here (in case you - or any readers - aren't use to following folds):
This uses a fold over the reversed input data, starting from the empty String (to accumulate results) and the (reverse of the) remaining input data (to compare against - I labeled it zt for "z-tail").
The fold then cycles through the data, checking each entry against the tail of the remaining data (so it doesn't get compared to itself or any earlier entry)
If there is a match, just the existing accumulator (labelled acc) will be allowed through, otherwise, add the current entry (zz) to the accumulator. This updated accumulator is paired with the tail of the "remaining" Strings (zt.tail), to ensure a reducing set to compare against.
Finally, we end up with a pair of lists: the required remaining Strings, and an empty list (no Strings left to compare against), so we take the first of these as our result.
If I understand correctly, you want to loop through the elements of the array, comparing each element to later elements, and removing ones that are too similar as you go.
You can't (easily) do this within a simple loop. You'd need to keep track of which items had been filtered out, which would require another array of booleans, which you update and test against as you go. It's not a bad approach and is efficient, but it's not pretty or functional.
So you need to use a recursive function, and this kind of thing is best done using an immutable data structure, so let's stick to List.
def removeSimilar(xs: List[String]): List[String] = xs match {
case Nil => Nil
case y :: ys => y :: removeSimilar(ys filter {x => similarity(y, x) < threshold})
}
It's a simple-recursive function. Not much to explain: if xs is empty, it returns the empty list, else it adds the head of the list to the function applied to the filtered tail.