list,sum,lisp,iteration,clisp , Lisp Function that Returns a Sum


Lisp Function that Returns a Sum

Question:

Tag: list,sum,lisp,iteration,clisp

I am trying to write a weird function, so bear with me here. This function should take a list L as a parameter and have a sum variable. If L is not a list, it should return nil. Otherwise, it should iterate through each element of the list and do the following:

Here's the code I have, but it returns 0 regardless of arguments passed in:

(defun sigsum (L)
  (let ((sum 0))                   ;;variable sum
  (if (not (listp L))              ;;if L is not a list
      nil                          ;;return nil
      (dotimes (i (length L))      ;;otherwise loop through L
        (if (numberp (elt L i))    ;;if each element is a number
            (if (< (elt L i) 0)    ;;if is less than 0 subtract 1 from sum
                (- sum 1)
            (if (> (elt L i) 0)    ;;if greater than 0 add 1 to sum
                (+ sum 1))
            (+ sum 0))             ;;else add 0 to sum
          (+ sum 0)))              ;;not a number so add 0 to sum
  )
  sum)                             ;;return sum
)

As always, any help is greatly appreciated.


Answer:
(defun discrete (lis)
 (cond
  ((and (listp lis) (not (equal lis nil)))
   (let ((sum 0))
    (loop for item in lis do
     (cond ((or (not (numberp item)) (equal 0 item)) t)
      ((and (numberp item) (> item 1)) (setf sum (+ 1 sum)))
      ((and (numberp item) (< item 1)) (setf sum (- sum 1)))))
    sum))))

Usage:(discrete '(-1 2 3 0 2 2 -1 2 34 0 -1))=> 3

(discrete '(-4 a b))=> -1

(discrete '()) => NIL

(discrete '(a s d f))=> 0


Related:


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...

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...

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...

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...

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...

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), [],...

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,...

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 ::...

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...

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>...

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...

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...

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,...

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 =...

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...

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....

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"...

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]...

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:...

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....

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...

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...

Using Sum in If in Mysql


mysql,sql,select,sum
I want to select the sum of values of my_field. The unit of my_field is in seconds. I don't want to exceed 24 hours, so when it exceeds 24 hours, I want it to select 24*60*60 = 86400. SELECT IF(SUM(my_field) > 86400, 86400, SUM(my_field)) ... This solution doesn't seem to...

Subtract two columns of different tables


sql,postgresql,sum,aggregate-functions,subtract
I have two unrelated tables: contribution(id,amount, create_at, user_id) solicitude(id, amount, create_at, status_id, type_id, user_id) I need to subtract the sum of the amount of the contribution and of the solicitude from a user, but that result can't to be negative. How can I do this? Function or query? I tried...

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...

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...

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...

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...

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...

sum of Digits through Recursion


java,function,recursion,sum,digit
I am trying to make a recursive function which should return the sum of digits. The function should have only one argument. So far I have this; public int sumDigits(int n) { if(n%10 == n) // last digit remains return n; else{ int rightdigit; rightdigit = n%10; // taking out...

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,...

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...

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.*$"); ...

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', '-', '-', '-',...

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...

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...

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...

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 =...

Return 0 in sum when no values to sum - sql server


sql,sql-server,sql-server-2008-r2,sum
Trying to return 0 if any of these columns have no values returned, in my particular case 'Past Due' has no values to total, so it is returned, so i get the return in the second snippet here. How can I return something if these are no values to count?...

PHP, MySQL How to Sum data in two different date range


php,mysql,sum
Im having trouble doing this +------------+------------+------------+ | Name | year | Value | +------------+------------+------------+ | Name1 | 2015 | 100 | | Name1 | 2014 | 150 | | Name1 | 2013 | 200 | | Name2 | 2015 | 130 | | Name2 | 2014 | 160 | |...

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...

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...

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...

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]....

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...

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...

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...