Count-Trailing-Zeros(1200) ==> 2 _________ in Scheme, Gauche, Common Lisp ?

20 views
Skip to first unread message

Hen Hanna

unread,
Sep 7, 2022, 2:15:30 PMSep 7
to

Count-Trailing-Zeros(x) ----- Can I use Log(x) to see if X is equal to ( Integer * 10 ^ k) ???

How do you do this in Scheme, Gauche, Common Lisp ?


--------- is there a simple string function that counts the leftmost 0's ???



__________________
Count how many zeros are at the end of an int:

def end_zeros(num):
s = str(num)
return len(s) - len(s.rstrip("0"))


print(end_zeros(10)) # ==> 1
print(end_zeros(101)) # ==> 0
print(end_zeros(245)) # ==> 0
print(end_zeros(100100)) # ==> 2

Hen Hanna

unread,
Sep 7, 2022, 6:28:18 PMSep 7
to
two ideas:

1. i can use string-skip-right to imitate the Python code above.

2. The following works:

(define (Count-end-0 x)
(cdr (fold-right ce0 '(#t . 0) (string->list (number->string x)))))

(define (ce0 c y)
(if (car y)
(if (char=? c #\0)
(cons #t (+ 1 (cdr y)))
(cons #f (cdr y)))
y))

Paul Rubin

unread,
Sep 7, 2022, 8:20:00 PMSep 7
to
Hen Hanna <henh...@gmail.com> writes:
> --------- is there a simple string function that counts the leftmost
> 0's ???

1. I think you mean rightmost zeros.
2. Converting to a string and counting the '0' chars is pretty ugly.

I'd just use simple arithmetic and tail recursion (the Scheme-ish way
to implement a loop):

(define (nz n)
(define (go n a)
(if (= (remainder n 10) 0)
(go (quotient n 10) (1+ a))
a))
(go n 0))

Hen Hanna

unread,
Sep 9, 2022, 9:53:29 PMSep 9
to
Thank you.... i wonder where internal definittions (5.3.2. Internal definitions in R7RS)
originally came from.....

Were they in MacLISP ?

Paul Rubin

unread,
Sep 10, 2022, 7:17:50 PMSep 10
to
Hen Hanna <henh...@gmail.com> writes:
> Thank you.... i wonder where internal definittions (5.3.2. Internal
> definitions in R7RS) originally came from..... Were they in MacLISP ?

I think was possible to write an internal lambda in Maclisp using FLET
but it wouldn't have been idiomatic. Using internal functions like that
is typical of functional programming though, and Scheme was one of the
early promoters of that style.

I never used Maclisp but at least originally, it ran on machines that we
would now consider quite memory constrained. So it might have been more
conventional (though uglier) to use a mutable cell. This is Emacs Lisp
which sort of resembles Maclisp:

(defun nz (n)
(let ((a 0))
(while (= (mod n 10) 0)
(setq a (1+ a)
n (/ n 10)))
a))
Reply all
Reply to author
Forward
0 new messages