I need to write a function in #lang racket that determines the amount of divisors a positive integer has. (Ex: 6 has 4 divisors; 1,2,3,6)
So far I have:
(define (divides a b) (if (= 0 (modulo a b)) #t #f))
I need to use this helper function to write the function (divisors-upto n k) that that computes the number of divisors n has between 1 and k (so it computes the number of divisors of n
up to the value k).
This is easiest done1 with a for loop, in particular for/fold, given that you already have your divides function.
(define (divisors num)
(for/fold ([acc 0]
[n (in-range num)])
(if (divides n num) <acc+1> <acc>)))
Basically, you are looping over the list, and keeping an accumulator, and whenever a number is dividable, increment your accumulator. See if you can fill in the expressions for <acc+1> and <acc> in the code above.
1You could also do this with list length and filter. See if you can figure out how.
Related
This question already has answers here:
I'm trying to figure out how to incorporate 3 variables into my tail recursion code for racket
(2 answers)
Closed 3 years ago.
Here's the question:
Write a tail recursive function that takes as input two non-negative integers P and k and outputs a list of the first 10 years of a population that has initial population P and multiplies the population by k every year. Your function can have helper variables if you want.
I was trying to get code to form a list with ten numbers. I assumed that the input for number would be 10. I tried to go in the direction of making the base case empty instead of 0. Does anyone have any advice on how to fix this code or to make it better?
(define (pop2 P k number)
(cond
[(= number 0) '()]
[else
(append (pop2 k (* P k)(- number 1)(list P)))]))
A recursive function definition is tail-recursive if nothing needs to be done after recursive call(s). But pop2 has append around the recursive call! To make sure that the function returns exactly what the recursive call returns, that keeps track of the result using an extra parameter to the function (an accumulator).
In the recursive call, the arguments don't match up with their corresponding meaning, and there is an extra arg too:
(pop2 k (* P k) (- number 1) (list P))
(pop2 P k number ???)
Here's something that can get you started:
;; pop2-acc : Nat Nat Nat [Listof Nat] -> [Listof Nat]
(define (pop2-acc P k number acc)
(cond
[(= number 0) <???>]
[else (pop2-acc P k (- number 1) <???>)]))
;; pop2 : Nat Nat Nat -> [Listof Nat]
;; initial-population (P), factor (k), years (number)
(define (pop2 P k number)
(pop2-acc P k number acc))
Note that acc is "the result so far." The helper pop2-acc could be turned into a local function within pop2, and we wouldn't have to pass in k into pop2-acc (because it stays the same).
I need to remove the last two elements from a list in common list, but I can remove only one. What's the way?
(defun my-butlast (list)
(loop for l on list
while (rest l)
collect (first l)))
Simple: reverse, pop, pop, reverse ;-) 1
More efficiently, the following works too:
(let ((list '(a b c d)))
(loop
for x in list
for y in (cddr list)
collect x))
This can also be written, for some arbitrary L and N:
(mapcar #'values L (nthcdr N L))
It works because iteration over multiple lists is bounded by the shortest one. What matters here is the length of the second list (we don't care about its values), which is the length of the original list minus N, which must be a non-negative integer. Notice that NTHCDR conveniently works with sizes greater than the length of the list given in argument.
With the second example, I use the VALUES function as a generalized identity function; MAPCAR only uses the primary value of the computed values, so this works as desired.
The behavior is consistent with the actual BUTLAST2 function, which returns nil for N larger than the number of elements in the list. The actual BUTLAST function can also deal with improper (dotted) lists, but the above version cannot.
1. (alexandria:compose #'nreverse #'cddr #'reverse)
2. BUTLAST is specified as being equivalent to (ldiff list (last list n)). I completely forgot about the existence of LDIFF !
There's a function in the standard for this: butlast, or if you're willing to modify the input list, nbutlast.
butlast returns a copy of list from which the last n conses have been omitted. If n is not supplied, its value is 1. If there are fewer than n conses in list, nil is returned and, in the case of nbutlast, list is not modified.
nbutlast is like butlast, but nbutlast may modify list. It changes the cdr of the cons n+1 from the end of the list to nil.
Examples:
CL-USER> (butlast '(1 2 3 4 5) 2)
(1 2 3)
CL-USER> (nbutlast (list 6 7 8 9 10) 2)
(6 7 8)
The fact that you called your function my-butlast suggests that you might know about this function, but you didn't mention wanting to not use this function, so I assume it's still fair game. Wrapping it up is easy:
CL-USER> (defun my-butlast (list)
(butlast list 2))
MY-BUTLAST
CL-USER> (my-butlast (list 1 2 3 4))
(1 2)
Hi I am a bit new to Clojure/Lisp programming but I have used recursion before in C like languages, I have written the following code to sum all numbers that can be divided by three between 1 to 100.
(defn is_div_by_3[number]
(if( = 0 (mod number 3))
true false)
)
(defn sum_of_mult3[step,sum]
(if (= step 100)
sum
)
(if (is_div_by_3 step)
(sum_of_mult3 (+ step 1 ) (+ sum step))
)
)
My thought was to end the recursion when step reaches sum, then I would have all the multiples I need in the sum variable that I return, but my REPL seems to returning nil for both variables what might be wrong here?
if is an expression not a statement. The result of the if is always one of the branches. In fact Clojure doesn't have statements has stated here:
Clojure programs are composed of expressions. Every form not handled specially by a special form or macro is considered by the compiler to be an expression, which is evaluated to yield a value. There are no declarations or statements, although sometimes expressions may be evaluated for their side-effects and their values ignored.
There is a nice online (and free) book for beginners: http://www.braveclojure.com
Other thing, the parentheses in Lisps are not equivalent to curly braces in the C-family languages. For example, I would write your is_div_by_3 function as:
(defn div-by-3? [number]
(zero? (mod number 3)))
I would also use a more idiomatic approach for the sum_of_mult3 function:
(defn sum-of-mult-3 [max]
(->> (range 1 (inc max))
(filter div-by-3?)
(apply +)))
I think that this code is much more expressive in its intention then the recursive version. The only trick thing is the ->> thread last macro. Take a look at this answer for an explanation of the thread last macro.
There are a few issues with this code.
1) Your first if in sum_of_mult3 is a noop. Nothing it returns can effect the execution of the function.
2) the second if in sum_of_mult3 has only one condition, a direct recursion if the step is a multiple of 3. For most numbers the first branch will not be taken. The second branch is simply an implicit nil. Which your function is guaranteed to return, regardless of input (even if the first arg provided is a multiple of three, the next recurred value will not be).
3) when possible use recur instead of a self call, self calls consume the stack, recur compiles into a simple loop which does not consume stack.
Finally, some style issues:
1) always put closing parens on the same line with the block they are closing. This makes Lisp style code much more readable, and if nothing else most of us also read Algol style code, and putting the parens in the right place reminds us which kind of language we are reading.
2) (if (= 0 (mod number 3)) true false) is the same as (= 0 (mod number 3) which in turn is identical to (zero? (mod number 3))
3) use (inc x) instead of (+ x 1)
4) for more than two potential actions, use case, cond, or condp
(defn sum-of-mult3
[step sum]
(cond (= step 100) sum
(zero? (mod step 3)) (recur (inc step) (+ sum step))
:else (recur (inc step) sum))
In addition to Rodrigo's answer, here's the first way I thought of solving the problem:
(defn sum-of-mult3 [n]
(->> n
range
(take-nth 3)
(apply +)))
This should be self-explanatory. Here's a more "mathematical" way without using sequences, taking into account that the sum of all numbers up to N inclusive is (N * (N + 1)) / 2.
(defn sum-of-mult3* [n]
(let [x (quot (dec n) 3)]
(* 3 x (inc x) 1/2)))
Like Rodrigo said, recursion is not the right tool for this task.
I am fairly new to lisp and this is one of the practice problems.
First of all, this problem is from simply scheme. I am not sure how to answer this.
The purpose of this question is to write the function, count-odd that takes a sentence as its input and count how many odd digits are contained in it as shown below:
(count-odd'(234 556 4 10 97))
6
or
(count-odd '(24680 42 88))
0
If possible, how would you be able to do it, using higher order functions, or recursion or both - whatever gets the job done.
I'll give you a few pointers, not a full solution:
First of all, I see 2 distinct ways of doing this, recursion or higher order functions + recursion. For this case, I think straight recursion is easier to grok.
So we'll want a function which takes in a list and does stuff, so
(define count-odd
(lambda (ls) SOMETHING))
So this is recursive, so we'd want to split the list
(define count-odd
(lambda (ls)
(let ((head (car ls)) (rest (cdr ls)))
SOMETHING)))
Now this has a problem, it's an error for an empty list (eg (count-odd '())), but I'll let you figure out how to fix that. Hint, check out scheme's case expression, it makes it easy to check and deal with an empty list
Now something is our recursion so for something something like:
(+ (if (is-odd head) 1 0) (Figure out how many odds are in rest))
That should give you something to start on. If you have any specific questions later, feel free to post more questions.
Please take first into consideration the other answer guide so that you try to do it by yourself. The following is a different way of solving it. Here is a tested full solution:
(define (count-odd num_list)
(if (null? num_list)
0
(+ (num_odds (car num_list)) (count-odd (cdr num_list)))))
(define (num_odds number)
(if (zero? number)
0
(+ (if (odd? number) 1 0) (num_odds (quotient number 10)))))
Both procedures are recursive.
count-odd keeps getting the first element of a list and passing it to num_odds until there is no element left in the list (that is the base case, a null list).
num_odds gets the amount of odd digits of a number. To do so, always asks if the number is odd in which case it will add 1, otherwise 0. Then the number is divided by 10 to remove the least significant digit (which determines if the number is odd or even) and is passed as argument to a new call. The process repeats until the number is zero (base case).
Try to solve the problem by hand using only recursion before jumping to a higher-order solution; for that, I'd suggest to take a look at the other answers. After you have done that, aim for a practical solution using the tools at your disposal - I would divide the problem in two parts.
First, how to split a positive integer in a list of its digits; this is a recursive procedure over the input number. There are several ways to do this - by first converting the number to a string, or by using arithmetic operations to extract the digits, to name a few. I'll use the later, with a tail-recursive implementation:
(define (split-digits n)
(let loop ((n n)
(acc '()))
(if (< n 10)
(cons n acc)
(loop (quotient n 10)
(cons (remainder n 10) acc)))))
With this, we can solve the problem in terms of higher-order functions, the structure of the solution mirrors the mental process used to solve the problem by hand:
First, we iterate over all the numbers in the input list (using map)
Split each number in the digits that compose it (using split-digits)
Count how many of those digits are odd, this gives a partial solution for just one number (using count)
Add all the partial solutions in the list returned by map (using apply)
This is how it looks:
(define (count-odd lst)
(apply +
(map (lambda (x)
(count odd? (split-digits x)))
lst)))
Don't be confused if some of the other solutions look strange. Simply Scheme uses non-standard definitions for first and butfirst. Here is a solution, that I hope follows Simply Scheme friendly.
Here is one strategy to solve the problem:
turn the number into a list of digits
transform into a list of zero and ones (zero=even, one=odd)
add the numbers in the list
Example: 123 -> '(1 2 3) -> '(1 0 1) -> 2
(define (digit? x)
(<= 0 x 9))
(define (number->digits x)
(if (digit? x)
(list x)
(cons (remainder x 10)
(number->digits (quotient x 10)))))
(define (digit->zero/one d)
(if (even? d) 0 1))
(define (digits->zero/ones ds)
(map digit->zero/one ds))
(define (add-numbers xs)
(if (null? xs)
0
(+ (first xs)
(add-numbers (butfirst xs)))))
(define (count-odds x)
(add-numbers
(digits->zero/ones
(number->digits x))))
The above is untested, so you might need to fix a few typos.
I think this is a good way, too.
(define (count-odd sequence)
(length (filter odd? sequence)))
(define (odd? num)
(= (remainder num 2) 1))
(count-odd '(234 556 4 10 97))
Hope this will help~
The (length sequence) will return the sequence's length,
(filter proc sequence) will return a sequence that contains all the elements satisfy the proc.
And you can define a function called (odd? num)
Hey i've been stuck on the following problem and cant seem to come up with the correct function.
Write a recursive function that, given a positive integer k, computes the product k:
(1-1/2)(1-1/3)(1-1/k)... as k decreases by one.
I cant seem to come up with the correct function i the program usually runs till it has no more memory left. Here is my method:
(define (fraction-product k)
(if (= k 0)
0
(* (- 1 (/ 1 (fraction-product (- k 1)))))))
thanks for any help in advance...
Do small cases by hand first.
Without trying to code it, hand-calculate what the answer should be for:
(fraction-product 1)
(fraction-product 2)
(fraction-product 3)
You should at least have three concrete examples in hand before you do these kinds of problems: not only does it help to clarify some confusion, but they can serve as sanity test cases when you get to actual code.
Is there a relationship between the answer you hand calculate between (fraction-product 1) and (fraction-product 2)? How about between (fraction-product 2) and (fraction-product 3)?
Do we have to worry about (fraction-product 0)? Check your problem statement.
Don't go straight to code when you see problems like this. Do small examples by hand first: compute what the answer should be. It will help kickstart your intuition on what the program is really trying to compute, and how to do it mechanically.
If you have time, see a book like How to Design Programs, which describes a systematic approach on designing these kinds of functions.
What are the arguments of the product? There is only one!
The product is therefore useless, since (* n) == (* n 1) == n.
This should tell you immediately that your algorithm doesn't do what you want.
A good strategy to find such bugs is to write all the parameters of function of separate lines…
Also, when k == 0, (fraction-product 0) returns 0.
Then (fraction-product 1) will compute (/ 1 (fraction-product 0)) == (/ 1 0) which is probably not what you want to do again…
Actually, it seems that you want to compute something completely different from a product of fractions… rather a recursive fraction (I forgot the name of such things).
Anyway, to do (1 - 1/2) * (1 - 1/3) * ... * (1 - 1/k) you could do something like
(define (f-p k)
(define (aux n) (- 1 (/ 1 n)))
(let loop ((i 2))
(if (> i k)
1 ;; base case: multiply by 1, i.e. "do nothing"
(* (aux i) (loop (+ i 1))))))
This can be optimised to use constant stack space, but it isn't the point, is it?
You got wrong the base case: it should state that if k is 1, then return 1 - when you're multiplying recursively you have to make sure that the recursion stops when the number 1 is reached, if you multiply by 0 the result will always be 0.
The recursive call is also mistaken, notice that you must multiply (- 1 (/ 1 k)) times the result of the recursion. Try something like this:
(define (fraction-product k)
(if (<= k 1)
1
(* (- 1 (/ 1 k))
(fraction-product (- k 1)))))
As suggested in #Axioplase's answer, the same procedure can be written in such a way that it uses constant stack space by using tail recursion - the recursive call is the last thing the procedure executes before returning and is thus in tail position:
(define (fraction-product k)
(let loop ((acc 1)
(k k))
(if (<= k 1)
acc
(loop (* acc (- 1 (/ 1 k))) (- k 1)))))
And just for fun, it's easy to realize that the same procedure can be written as simple as this:
(define (fraction-product k)
(/ 1 k))