0

So I'm currently solving a problem. The instructions are:

accum("abcd") -> "A-Bb-Ccc-Dddd"
accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") -> "C-Ww-Aaa-Tttt"

I've written the following program:

def accum(s):
dope = []
i = 0
while i < len(s):
    dope.append(list(s)[i].upper())
    dope.append(list(s)[i].lower() * i) 
    i += 1
dope.pop(1)
return dope

But it returns ['A', 'B', 'b', 'C', 'cc', 'D', 'ddd'] instead

So is it another method I should use instead of .append or how do I combine the upper case letters with the lower case ones?

Aintripin
  • 43
  • 4
  • 1
    `return '-'.join((c * i).title() for i, c in enumerate(s, 1))` — Something like this should do, and be very pythonic… – deceze Apr 25 '21 at 12:33
  • It was hard to answer this properly, because the title does not ask the question that you actually have. You don't want to "add an item to a list" at all, because you are trying to make *a string*. "Without separating it from the previous one" is hard to understand; it seems like you didn't want to have each string as a separate element of the list, but that's what a list *is*. So the real question is how to *join strings together*, which is also something you can [look up with a search engine](https://duckduckgo.com/?q=python+join+strings). – Karl Knechtel Apr 25 '21 at 12:45
  • Thanks! But what's the '1' in the `enumerate` method? – Aintripin Apr 25 '21 at 12:50
  • The `1` is so it starts at 1. Otherwise it’d start at 0. – deceze Apr 25 '21 at 13:04
  • `[(v*(k+1)).capitalize() for k, v in enumerate(s)]` – khelili miliana Apr 25 '21 at 14:09

2 Answers2

0

You need to understand what data type you need to return. You are working with lists and want to return a String. dope is a list type. In order to convert it to a str you can either:

  1. use str(dope), but this will keep all the commas and [] symbols
  2. use "-".join() with the correct join pattern (according to your needs)
Tamir
  • 1,224
  • 1
  • 5
  • 18
-1

You create a list, you should convert the list to a string. This can be done in multiple ways. You could use approach:

def accum(s):
  dope = []
  dope_str = ''
  i = 0
  while i < len(s):
      dope.append(list(s)[i].upper())
      dope.append(list(s)[i].lower() * i) 
      i += 1
  for i in dope:
    dope_str = dope_str + i  
  dope.pop(1)
  return dope_str

The output is:

CWwAaaTttt
John Mommers
  • 140
  • 7
  • Thanks! It changed it a little bit and this worked: `def accum(s): dope = [] dope_str = '' i = 0 while i < len(s): dope.append(list(s)[i].upper()) dope.append(list(s)[i].lower() * i) dope.append('-') i += 1 dope.pop(-1) for i in dope: dope_str = dope_str + i dope.pop(1) return dope_str` – Aintripin Apr 25 '21 at 12:49
  • Great. Happy my answer was useful for you. – John Mommers Apr 25 '21 at 13:15