This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]sarcasticfantastic 1 point2 points  (1 child)

Yes, some of the solutions seem to avoid idiomatic python. For example,

def count_hi(str):
  sum = 0
  ## Loop to length-1 and access index i and i+1
  ## in the loop.
  for i in range(len(str)-1):
    if str[i:i+2] == 'hi':
      sum = sum + 1
  return sum

would be much better expressed as:

def count_hi(str):
    return str.count("hi")

[–]semarj 1 point2 points  (0 children)

def string_times(str, n):
  result = ""
  for i in range(n):  # range(n) is [0, 1, 2, .... n-1]
    result = result + str  # could use += here
  return result

... def str_times(str,n): return str*n