list,common-lisp , Trying to multiply all elements in a list of sublists with elements in another list in lisp


Trying to multiply all elements in a list of sublists with elements in another list in lisp

Question:

Tag: list,common-lisp

I'm trying to multiply a list with n sublists with a list with n scalars. It's supposed to work like this:

(kmult-matrix '((3 4 2 4) (2 5 6 9) (1 -2 8 10))   '(2 3 5)) 
=> ((6 8 4 8) (6 15 18 27) (5 -10 40 50))

Each nth sublist is multiplied with the nth scalar in the second list. Here's what I got this far:

(defun kmult-matrix (m k)
  (apply 'append (mapcar (lambda (x1)
            (mapcar (lambda (x2)
                            (mapcar (lambda (x3)
                                    (* x3 x1))
                                    x2))
                          m))
          k)))

Which results in:

((6 8 4 8) (4 10 12 18) (2 -4 16 20) (9 12 6 12) (6 15 18 27) (3 -6 24 30) (15 20 10 20) (10 25 30 45) (5 -10 40 50))

Hope it's ok to ask this as it is for an assigment and I have the feeling that I'm not far away from the solution. Btw, I have to use mapcar.


Answer:

It's a lot easier than that. Remember that mapcar can take more than one list. Thus:

(defun kmult-matrix (m k)
  (mapcar (lambda (list k)
            ;; inside here you get a list and 
            ;; it's corresponding multiplier k
            ...)
          m
          k))

The result from the outer map would be a list with as many elements as there are sublists m (and corresponding elements in k). Inside the lambda you do another map over lst that does the multiplication per element. so that inner map produces once list answer per element in the outer map.


Related:


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


python,regex,string,list,python-2.7
I have this to get input and put it in a list: def start(): move_order=[raw_input("Enter your moves: ").split()] And I only want the characters A, D, S, C, H (it's for a game >_>) to be allowed. I've tried using the regular expressions stuff: if re.match('[ADSCH]+', [move_order]) is False: print...

Convert only floating point numbers to int in list python


python,list,list-comprehension
I am trying to turn any floating point number in the list 'codes' to an int. codes = [890.0,'JFR'] codes = [int(c) for c in codes] I am getting the error: ValueError: invalid literal for int() with base 10: 'JFR' What I want the list 'codes' to be is: [890,'JFR']...

Java Get and then remove from a list


java,list,setter,getter,instances
In my code i have a list of instances of a class. And i want to get a attribute of 1 instance which is ArrayList. In this class i have implement getters and setters. So I call listofinstances.get(i).getArrayList().remove(0); in order to remove the 1st item of this list. Is this...

Python RuntimeError: maximum recursion depth exceeded in cmp


python,list,dictionary,recursion
I have a complex data structure that I'm trying to process. Explanation of the data structure: I have a dictionary of classes. The key is a name. The value is a class reference. The class contains two lists of dictionaries. Here's a simple example of my data structure: import scipy.stats...

Filter list using Boolean array


python,list
How can I use boolean array as index to filter a list? For example: >>> l = ['a','b','c'] >>> b = [True,False,False] >>> l[b] The result should be: ['a'] I know numpy support it but want to know how to solve in Python. >>> import numpy as np >>> l...

Creating a list of items with different tags + filter


javascript,html,list,filter
I have prepared an example what I would like to produce: link. I have already looked for something and I have found the way to create a filter but just for one value... In my case I need more values all together combined. So that if I wanted a flat...

Django: Handling several page parameters


python,django,list,parameters,httprequest
I have several possible parameter to process in a page. Assume x0, x1, x2,..., x1000. It seems awkward to get and process them one by one by request.GET.get('x0'), request.GET.get('x1'), ... Any idea to put them in a list, so that they can be processed in a loop....

For-loop does not go over all objects


python,list,for-loop
Why does this for-loop not go through all items: temp = 0 for br in my_list : temp +=1 #other code here #my list is not used at all, only br is used inside here my_list.remove(br) print temp assert len(my_list) == 0 , "list should be empty" So, assertion fires....

C# 2D Generic List [closed]


c#,list,nested-lists
I'm working on a talents/skills tree system for my game made with Unity and I've got a class for my 45 talents buttons that looks like this: public class SaveTalentClass { public int talId; public int talCurRank; public int talMaxRank; public SaveTalentClass(int id, int cRank, int mRank) { talId =...

ZipList with Scalaz


list,scala,scalaz,applicative
Suppose I have a list of numbers and list of functions to apply to numbers: val xs: List[Int] = List(1, 2, 3) val fs: List[Int => Int] = List(f1, f2, f3) Now I would like to use an Applicative to apply f1 to 1, f2 to 2, etc. val ys:...

EVAL/APPLY: too many arguments given to F


lisp,common-lisp,clisp
Hello why do i get *** - EVAL/APPLY: too many arguments given to F on function call with nested lists parameter. I cannot figure it out, since I passed a simple nested list. (defun f (L) (cond ((NULL l) nil) ((listp (car L)) (append (F(car L))) (F(cdr L) (car (F...

Stopping list selection in Python 2.7


python,list,python-2.7
Imagine that I have an order list of tuples: s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)] Given a parameter X, I want to select all the tuples that have a first element equal or greater than X up to but not including the first tuple that has...

Sort List of Numbers according to Custom Number Sequence


list,python-2.7,sorting
Question :A set of numbers will be passed as input. Also the redefined relationship of the digits 0-9 in ascending order will be passed as input. Based on the redefined relationship, the set of numbers must be listed in ascending order. Input Format: The first line will contain the the...

Python 2.7 “list index out of range”


python,list
I keep getting "IndexError: list index out of range", the code does fine with things like "s = 'miruxsexxzlbveznyaidekl'" but this particular length makes it throw an error. Can anyone help me understand what I did wrong here, not just give me the answer? (I'd like to not have to...

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
I have got hex values as a85b080040010000. I want it to be as a8 5b 08 00 40 01 00 00. I have done it by using below code. But I have to work with very large data. So I want computed time to be very low. import binascii import...

Reduction of list dimensions in Python


python,list,indexing,nodes
I'm trying to assign classes to a list of nodes, and separate all nodes into separate lists based on class tag. For example, if we have the following code: #define number of classes MaxC=5 index=[4 4 5 1 4 1 4 5 4 4 3 1 3 3 1 1]...

Find a single duplicate in a list of lists Netlogo


list,duplicates,netlogo
I am trying to find a duplicate between the sublists of a list , if I have this list let listA [[-9 2] [-9 1] [-9 0][-9 -1][-9 -2][-9 -3][-9 -4][-8 0][-9 0]] and it is a restriction that this list can have only one sublist that can be repeated...

print method for list changes values of items


python,list
I have problem with printing list. random_itemst_stac contains list of items (cards). Prints of elements and indexes in for loop works perfect but when I print a whole array there are X set for others items - it's strange. Card class: class Card(object): def __init__(self, r=0): self.__rank=0 self.__hidden= False if...

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


python,list,numpy,multidimensional-array
I have a list which contains 1000 integers. The 1000 integers represent 20X50 elements of dimensional array which I read from a file into the list. I need to walk through the list with an indicator in order to find close elements to each other. I want that my indicator...

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


c#,arrays,list,unity3d,gameobject
I'm currently working on a radar system for my space game, and I am trying to work out how to add gameobjects, by tag, to either a list or array that can then be used in other methods. I can't do this manually because I will be procedurally generating each...

Get element starting with letter from List


java,android,list,indexof
I have a list and I want to get the position of the string which starts with specific letter. I am trying this code, but it isn't working. List<String> sp = Arrays.asList(splited); int i2 = sp.indexOf("^w.*$"); ...

Loop by Object inside another Object in Java


java,list,oop,collections
I'm not sure how to ask this in word so here's an example : Building class have a data like this : Map<Season, List<Info>> infosBySeason = new TreeMap<Season, List<Info>>(); What I'd like to do is loop for each Building, print by Season infos. Like : Season 1 : Building 1...

How do I read this list and parse it?


python,list
I'm using requests and the output I get from the sites API is a list, I've been stuck trying to parse it to get the data from it. I use r = requests.get(urlas, params=params) r.json() to get the data I want. Here is a snippet of the list [{'relation_type': None,...

Implementing a dictionary function to calculate the average of a list


python,list,dictionary
As always, I've attempted this for awhile before I proceed to ask a question on here. I know there are several attempts at answering this, but none really worked for what I needed. Here are the instructions: Implement the following three functions (you should use an appropriate looping construct to...

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


list,split,prolog
I'm trying to split a list into two other list. List Even with the elemnts in even possition and a List Odd with the others. I've been looking over iinternet a solution, but all seem to me like chinese, i can not understand the process. So this is what i've...

Python regular expression, matching the last word


python,regex,list
I've the following problem. I'm looking to find all words in a string that typically looks like so HelloWorldToYou Notice, each word is capitalized as a start followed by the next word and so on. I'm looking to create a list of words from it. So the final expected output...

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


c#,list,text,streamreader
I have a lot of text files and want to read them all by once, how do I do this? This is my code till now: 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); But I get an ObjectDisposedException(Cannot...

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


c#,xml,winforms,list
I am trying to load data from an XML file and add it to a List. The XML file looks like this: and this is my code: public void LoadPayments(List<List<string>> list1, List<List<string>> list2) { try { if (File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RentData.xml"))) { int count = 0; XDocument doc; using (var reader =...

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


c#,list,for-loop,dimensions
I got a 4D list, and I want where I want to display only the [k][3][j][z], but this isnt working. I checked all the counts and they are all 5+, so 3[4] should work... for (int k = 0; k < lijst4D.Count; k++) { for (int i = 0; i...

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


java,list,collections,listiterator
As per Java API- IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous remove()- Removes from the list the last element that was returned by next() or previous() (optional operation). This call can only...

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


list,lisp,common-lisp
I am new to Lisp. Deletion of an item in a list by a function gets reflected outside the function but insertion doesn't. How can I do the same for insertion? For example (defun test (a b) (delete 1 a) (delete 5 b) (append '(5) b) (member '5 b)) (setq...

Grouping 0s and 1s in python


python,list,grouping
I have an array of zeros and ones like [0,0,0,1,1,1,0,0,0,1,1]. How to write a program to save neighboring 0's and 1's in different arrays. E.g. [0,0,0,1,1,1,0,0,0,1,1] giving [0,0,0],[1,1,1],[0,0,0],[1,1]....

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


python,list,python-2.7,tuples
I am starting with a list of tuples (a,all b). I want to end with a list of tuples (b,all a). For example: FROM (a1,[b1,b2,b3]) (a2,[b2]) (a3,[b1,b2]) TO (b1,[a1,a3]) (b2[a1,a2,a3]) (b3,[a1] How do I do this using Python 2? Thank you for your help....

C++ atomic list container


c++,list,stl,containers,atomic
Probably this is a stupid question and I get downvoted but I'll ask it anyways. I'm playing around with std::atomic but I think I didn't fully understand the concept. I'm wondering why there are no atomic Containers. So I played a Little bit around. First I tried the following: std::atomic<std::list<int>...

How to get a reference of the list inside the list comprehension in Python


python,list
In previous Python versions, it was possible to get a reference of the list inside the list comprehension by calling locals()['_[1]']. As it seems not to work anymore, is there another way to get it? For example, in the following code, I would like to use the result of the...

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


c#,string,list,streamreader
At the moment I am opening the .txt file twice, once to get the number of all the lines, second to add a line to a list as much as how much lines there are in the .txt file. Is there an easier/better way to do this? This is my...

join two different list by id into one list


c#,list,join,merge,automapper
I've got two different list of two different objects. Then i got one list of a viewmodel that contains properties from both the objects and i want them to be joined into that list. //Product public string id { get; set; } public string unitMeasurement { get; set; } public...

Saving elements of a list as data.frames using R


r,list,save,lapply
How can I save each element of a list in a in a separate .RData file? Consider the following example: # Generating a list containing 3 matrices set.seed(1) mylist=list(M1=matrix(LETTERS[sample(1:26,9)],3),M2=matrix(LETTERS[sample(1:26,9)],3),M3=matrix(LETTERS[sample(1:26,9)],3)) mylist[1:2] # $M1 # [,1] [,2] [,3] # [1,] "G" "U" "W" # [2,] "J" "E" "M" # [3,] "N" "S"...

group indices of list in list of lists


python,list
I am looking for an elegant solution for the following problem. I have a list of ints and I want to create a list of lists where the indices with the same value are grouped together in the order of the occurrences of said list. [2, 0, 1, 1, 3,...

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


javascript,jquery,html,list,loops
Fiddle: https://jsfiddle.net/zayjeLrk/12/ I want to iterate through an HTML nested list that is 3-layers deep. <ul> <li>animals <ul> <li>birds <ul> <li>crow</li> <li>parrot</li> </ul> </li> <li>reptiles</li> </ul> </li> <li>plants</li> <li>bugs</li> </ul> I want it to iterate through the list so that it returns the elements in this order (note, this isn't...

Python 3.4: List to Dictionary


python,list,python-3.x,dictionary
I have a string as follows : ['Total Revenue', 31821000, 30871000, 29904000, 'Cost of Revenue', 16447000, 16106000, 15685000, 'Gross Profit', 15374000, 14765000, 14219000, 'Research Development', 1770000, 1715000, 1634000, 'Selling General and Administrative', 6469000, 6384000, 6102000, 'Non Recurring', '-', '-', '-', 'Others', '-', '-', '-', 'Total Operating Expenses', '-', '-', '-',...

how to insert into python nested list


python,list,list-comprehension
I want to insert an item into a list inside a list. I'm wondering if someone can show me. list5 = [[], [(1,2,3,4), 2, 5]] print("1. list5", list5) list5.insert(0, (2,5,6,8)) print("2. list5", list5) Output: 1. list5 [[], [(1, 2, 3, 4), 2, 5]] 2. list5 [(2, 5, 6, 8), [],...

Operand order in Scala List.prepend (::)


list,scala,operators
Odersky has brilliantly optimized Java syntax, enabling object calls without dots and parenthesis. I.e. instead of list.prepend(item), you now simply write list :: item, which also turns language operators into simple object methods. Here, List defines :: (prepend) operator. However, you normally write it vice-verse in Scala, using item ::...

Zip with tuples and list


python,string,list,zip,tuples
I need to write a code that will return the characters of two strings as a list of tuples. The code should stop when either one of the strings runs out of characters. I know is a simple code but I cannot get to work where it gives me more...

Python - Using a created list as a parameter


python,list,loops,if-statement,compare
When I run my code it tells me: Type Error: unorderable types: str() < float(). I can't figure out why it won't let me compare these two numbers. The list I am using is defined, and the numbers in it have been redefined as floats, so I'm not sure what...

How to use Split() method in Android


java,android,string,list,split
I have String like this. ex:- String myString = "A=myPage{a1,b1,c1};B=myPage{a2,b2,c2};C=myPage{a3,b3,c3};" I need to put each {_,_,_} part into List. like: If List<String> list = new ArrayList() then, list[0]="a1,b1,c1", list[1]="a2,b2,c2", list[2]="a3,b3,c3" I tried to use split, but I don't know how to apply it into this for getting my result. for...

Sort when values are None or empty strings python


python,list,sorting,null
I have a list with dictionaries in which I sort them on different values. I'm doing it with these lines of code: def orderBy(self, col, dir, objlist): if dir == 'asc': sorted_objects = sorted(objlist, key=lambda k: k[col]) else: sorted_objects = sorted(objlist, key=lambda k: k[col], reverse=True) return sorted_objects Now the problem...

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


list,prolog
I was solving a problem: A list is representing an integer say 12345 by L=[12,34,5] each element should be from 0 to 99.The exercise is to write a function (sum) that sums two lists and gives the equivalent list of their sum which is representing the sum of two integers....

Update list of items in c#


c#,linq,list,updates
I would like to know if you can suggest me an efficient way to update a list of items in c#. Here is a generic example: If CurrentList is [ {Id: 154, Name: "George", Salary: 10 000} {Id: 233, Name: "Alice", Salary: 10 000}] And NewList is [ {Id: 154,...