Python CodeBat¶
List-2 problems¶
def count_evens(nums):
result = 0
for num in nums:
if num % 2 == 0:
result += 1
return result
def big_diff(nums):
smallest = nums[0]
biggest = nums[0]
for num in nums:
if num > biggest:
biggest = num
if num < smallest:
smallest = num
return biggest - smallest
def centered_average(nums):
smallest = nums[0]
biggest = nums[0]
totalSum = 0
for num in nums:
if num < smallest:
smallest = num
if num > biggest:
biggest = num
totalSum += num
totalSum = totalSum - smallest - biggest
mean = totalSum / (len(nums) - 2)
return mean
def sum13(nums):
result = 0
skip = False
for num in nums:
if num == 13:
skip = True
elif skip:
skip = False
else:
result += num
return result
def sum67(nums):
result = 0
skip = False
for num in nums:
if num == 6:
skip = True
elif num == 7 and skip:
skip = False
elif not(skip):
result += num
return result
def has22(nums):
twoFound = False
for num in nums:
if num == 2 and twoFound:
return True
elif num == 2:
twoFound = True
else:
twoFound = False
return False
String-2 problems¶
def double_char(string):
result = ''
for char in string:
result += char * 2
return result
def count_hi(string):
hFound = False
result = 0
for char in string:
if char == 'i' and hFound:
result += 1
hFound = False
elif char == 'h':
hFound = True
else:
hFound = False
return result
def cat_dog(string):
cats = 0
dogs = 0
for x in range(0, len(string)):
if x + 2 < len(string):
if (
string[x] == 'c'
and string[x + 1] == 'a'
and string[x + 2] == 't'
):
cats += 1
if (
string[x] == 'd'
and string[x + 1] == 'o'
and string[x + 2] == 'g'
):
dogs += 1
return cats == dogs
def count_code(string):
codes = 0
for x in range(0, len(string)):
if x + 3 < len(string):
if (
string[x] == 'c'
and string[x + 1] == 'o'
and string[x + 3] == 'e'
):
codes += 1
return codes
def end_other(a, b):
turn_a = a[::-1].lower()
turn_b = b[::-1].lower()
length = min(len(a), len(b))
for x in range(0, length):
if turn_a[x] != turn_b[x]:
return False
return True
def xyz_there(string):
for ix in range(0, len(string) - 2):
if (
string[ix] == 'x'
and string[ix + 1]== 'y'
and string[ix + 2] == 'z'
):
if ix == 0:
return True
elif string[ix - 1] != '.':
return True
return False