发现每一个给定的阵列的第(n-1)的子集的产物子集、阵列、产物、发现

2023-09-11 22:57:18 作者:叽里呱啦▽说说说

对不起,我删除了原来的问题,那就是: 我们有一个袋子或正整数数组,我们需要找到每个第(n-1)的子集的产物。例如:

I'm sorry for deleting the original question, here it is: We have a bag or an array of n integers, we need to find the product of each of the (n-1) subsets. e.g:

S = {1,0,3,6} ps的[1] = 0 * 3 * 6 = 0; PS [2] = 1 * 3 * 6 = 18;等等。

S = {1, 0, 3, 6} ps[1] = 0*3*6 = 0; ps[2] = 1*3*6 = 18; etc.

在讨论中,我们需要采取三种情况照顾,他们是图解如下:

After discussions, we need to take care of the three cases and they are illustrated in the following:

1. S is a set (contains one zero element)
  for i=1 to n
    if s[i]=0
      sp[i] = s[1] * s[2] * ...* s[i-1] * s[i+1] *.....*s[n]
    else
      sp[i] = 0;

2. S is a bag (contains more than one zero element) 
  for i=1 to n
      sp[i] = 0;

3. S is a set (contains no zero elements)
   product = 1
   for i=1 to n
     product *= s[i];
   for i=1 to n
     sp[i] = product / s[i];

感谢。

推荐答案

如果设置的是非常大的,它可能是方便的:

If the set is very large, it may be convenient to:

计算所有的元件的产品P预先,然后 的每个元素的x,获得第(n-1)产物的P / X

如果该集合包含零(即P = 0,X = 0),则必须处理它作为一个特例。

If the set contains zero (i.e. P=0, x=0), you must deal with it as a special case.

修改。这里是在方案中的溶液,同时考虑到andand的回答。我是一个完整的初学者 - 有人可以帮助我提高以下code(使之更有效率,更具可读性,更口齿不清杂交)? (随意编辑我的答案。)

EDIT. Here is a solution in Scheme, taking into account andand's answer. I'm a complete beginner - can someone help me improve the following code (make it more efficient, more readable, more lisp-ish)? (Feel free to edit my answer.)

#!/usr/bin/env guile !#
(use-modules (ice-9 pretty-print))

(define (count-zeros l)
    (cond ((null? l) 0)
          ((= 0 (car l)) (+ 1 (count-zeros (cdr l))))
          (else (count-zeros (cdr l)))))

(define (non-zero-product l)
    (define (non-zero-product-loop l product)
        (cond ((null? l) product)
              ((= 0 (car l)) (non-zero-product-loop (cdr l) product))
              (else (non-zero-product-loop (cdr l) (* (car l) product)))))
    (non-zero-product-loop l 1))

(define (n-1-products l)
    (let ((nzeros (count-zeros l)))
         (cond ((> nzeros 1)
                   (map (lambda (x) 0) l))
               ((= 1 nzeros)
                   (map (lambda (x) (if (= 0 x) (non-zero-product l) 0)) l))
               (else 
                   (map (lambda (x) (/ (non-zero-product l) x)) l)))))

(pretty-print (n-1-products '(1 2 3 4 5)))
(pretty-print (n-1-products '(0 1 2 3 4)))
(pretty-print (n-1-products '(0 1 2 3 0)))
 
精彩推荐
图片推荐