#Help with Transpose

7 messages · Page 1 of 1 (latest)

alpine elbow
#

I've been stuck in the Python transpose exercise for almost a month now.

Here's my code:

def transpose(lines):
    lines = lines.split('\n')
    res = []
    
        
    max_len = 0
    for i, col in enumerate(lines):
        max_len = len(col) if len(col) > max_len else max_len

    for i in range(max_len):
        res.append([])
        
    for j, row in enumerate(lines):
        for i, col in enumerate(row.ljust(max_len, " ")):
            if not col.strip() and i == (max_len - 1) and j == len(lines) - 1:
                continue
            print(i, repr(col), max_len)
            res[i].append(col)
    return "\n".join(map(lambda x: "".join(x), res))

It solves all the test cases except lines = ["The longest line.", "A long line.", "A longer line.", "A line."].

Here's the diff between what's expected and what my function returns:

  TAAA
  h   
  elll
   ooi
  lnnn
  ogge
  n e.
- glr 
?    -
+ glr
- ei  
?    -
+ ei 
- snl 
?    -
+ snl
- tei 
?    -
+ tei
-  .n 
?    -
+  .n
- l e 
?    -
+ l e
- i . 
?    -
+ i .
- n   
- e   
- .  + n
+ e
+ .

I'm guessing it's some subtle bug - could you help me out here?

Thanks!

twin elbow
#

The space padding/justification isn't fixed across all lines. Line lengths can shrink.

#

Shrink but not grow

alpine elbow
#

Uh, so how would I apply this to my code? I tried or i, col in enumerate(row.ljust(len(row), " ")): but that doesn't work.

twin elbow
#

The approach I used is to ||reverse the lines and track the max seen so far; then use that max value to space pad so line length isn't constant but can decrease||

#

It's not very clean and presentable, but this is my solution: https://github.com/IsaacG/exercism/blob/master/python/transpose/transpose.py

serene dock
#

Rather than doing the transpose manually, you might want to check out zip() and it's variant in itertools. I found both very very handy in working through this problem.