在球拍中转置矩阵(列表列表

时间:2015-06-11 08:04:41

标签: list matrix scheme racket transpose

我在球拍中得到了一份列表,并且必须转置它们。

(: transpose ((list-of(list-of %a)) -> (list-of (list-of %a))))

(check-expect (transpose (list (list 1 2 3)
                               (list 4 5 6)))
              (list (list 1 4)
                    (list 2 5)
                    (list 3 6)))

(define transpose
  (lambda (xs)
    (cond
      ((empty? xs)empty)
      ((pair? xs)(make-pair  (make-pair (first(first xs))  (make-pair (first(first(rest xs)))empty)) (transpose (rest(rest xs))))))))

这是我目前的代码。 我认为问题在于递归调用(如果我错了请纠正我)。

实际结果为(list (list 1 4))。其余的似乎有点被忽视了。

如果有人知道这个问题,或者有提示,这对我真的有帮助。

3 个答案:

答案 0 :(得分:13)

transpose最简单的定义是:

(define (transpose xss)
  (apply map list xss))

为什么会这样?

  (apply map list '((a b) (d e))
= (apply map List '((a b) (d e))    ; use List rather than list
= (map List '(a b) '(d e))
= (list (List 'a 'd) (List 'b e))
= '((a d) (b e))

此处List拼写为大写字母,仅显示用户提供的list以及map生成的(define transpose (lambda (xss) (cond [(empty? xss) empty] [(empty? (first xss)) empty] [else (define first-column (map first xss)) (define other-columns (map rest xss)) (cons first-column (transpose other-columns))])))

这是一个更少"聪明的"解。它使用了第一列 矩阵成为转置矩阵中的第一行。

  public class Second {
  private WebDriver driver;
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();

  @BeforeClass
  public void beforeClass() {
  driver = new FirefoxDriver();
  driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  }


 @Test
  public void testSecond() throws Exception {
  driver.get("url");
  System.out.println("test two");
  Thread.sleep(5000);

 }

 @AfterClass
 public void afterClass() throws Exception{
  driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
      fail(verificationErrorString);
    }
 }
}

答案 1 :(得分:1)

可以按顺序使用

wstring myString; getline(wcin, myString); //... wcin >> myString; //... wcout << myString; 来创建包含转置项的列表列表:

for/list

测试:

(define (transpose_ lol)                    ; lol is list of lists
  (for/list ((i (length (list-ref lol 0)))) ; loop for length of first inner list
    (for/list ((il lol))                    ; for each inner list (il)
      (list-ref il i))))                    ; get its item

输出:

(transpose_ (list (list 1 2 3)
                  (list 4 5 6)))

答案 2 :(得分:-1)

(define (tr ls)
  (if (empty? (car ls)) empty
 (if (null? ls) empty
     (cons (map car ls) (tr (map cdr ls))))))