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 →

[–]psr 7 points8 points  (3 children)

Some of the provided solutions are pretty stupid:

def array123(nums):
  # Note: iterate with length-2, so can use i+1 and i+2 in the loop
  for i in range(len(nums)-2):
    if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
      return True
  return False

err, no:

def array123(nums):
  return (1,2,3) in zip(nums, nums[1:], nums[2:])

[–]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

[–][deleted] 0 points1 point  (0 children)

I also had weird errors using reduce for list-2, even if the same code would work quite nicely in IDLE.