Wednesday, November 24, 2010

Coding bat - solutions - solution

---------------------------------------------------------------p100347.html ---------------------------------------------------------------
Given 3 int values, a b c, return their sum. However, if any of the values is a teen -- in the range 13..19 inclusive -- then that value counts as 0, except 15 and 16 do not count as a teens. Write a separate helper "def fix_teen(n):"that takes in an int value and returns that value fixed for the teen rule. In this way, you avoid repeating the teen code 3 times (i.e. "decomposition"). Define the helper below and at the same indent level as the main no_teen_sum().


no_teen_sum(1, 2, 3) → 6
no_teen_sum(2, 13, 1) → 3
no_teen_sum(2, 1, 14) → 3...Save, Compile, Run
def fix_teen(num):
  if num >12 and num <20 and not num ==15 and not num ==16:
    return 0
  else:
    return num
def no_teen_sum(a, b, c):
  return fix_teen(a) + fix_teen(b)+fix_teen(c)
Given 3 int values, a b c, return their sum. However, if any of the values is a teen -- in the range 13..19 inclusive -- then that value counts as 0, except 15 and 16 do not count as a teens. Write a separate helper "def fix_teen(n):"that takes in an int value and returns that value fixed for the teen rule. In this way, you avoid repeating the teen code 3 times (i.e. "decomposition"). Define the helper below and at the same indent level as the main no_teen_sum().


no_teen_sum(1, 2, 3) → 6
no_teen_sum(2, 13, 1) → 3
no_teen_sum(2, 1, 14) → 3...Save, Compile, Run
def fix_teen(num):
  if num >12 and num <20 and not num ==15 and not num ==16:
    return 0
  else:
    return num
def no_teen_sum(a, b, c):
  return fix_teen(a) + fix_teen(b)+fix_teen(c)
---------------------------------------------------------------p100958.html ---------------------------------------------------------------
The number 6 is a truly great number. Given two int values, a and b, return True if either one is 6. Or if their sum or difference is 6. Note: the function abs(num) computes the absolute value of a number.


love6(6, 4) → True
love6(4, 5) → False
love6(1, 5) → True...Save, Compile, Run
def love6(a, b):
  return a ==6 or b == 6 or a+b ==6 or abs(a-b) == 6
  
---------------------------------------------------------------p107010.html ---------------------------------------------------------------
Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".


first_half('WooHoo') → 'Woo'
first_half('HelloThere') → 'Hello'
first_half('abcdef') → 'abc'...Save, Compile, Run
def first_half(str):
  return str[0:len(str)/2]
---------------------------------------------------------------p107863.html ---------------------------------------------------------------
Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards the sum and values to its right do not count. So for example, if b is 13, then both b and c do not count.


lucky_sum(1, 2, 3) → 6
lucky_sum(1, 2, 13) → 3
lucky_sum(1, 13, 3) → 1...Save, Compile, Run
def lucky_sum(a, b, c):
  sum = 0
  if a == 13:
    return 0
  elif b == 13:
    return a
  elif c==13:
    return a+b
  else:
    return a+b+c
---------------------------------------------------------------p108886.html ---------------------------------------------------------------
Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.


sum67([1, 2, 2]) → 5
sum67([1, 2, 2, 6, 99, 99, 7]) → 5
sum67([1, 1, 6, 7, 2]) → 4...Save, Compile, Run
def sum67(nums):
  if len(nums) == 0:
    return 0
  
  sum = 0
  sum671 = 0
  
  for num in nums:
    if num == 6 or not sum671 == 0:
      sum671 += num
    if num ==7  and not sum671 == 0:
      sum-=sum671
      sum671=0
    
    sum +=num
    
  return sum
---------------------------------------------------------------p110166.html ---------------------------------------------------------------
Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4.


array_front9([1, 2, 9, 3, 4]) → True
array_front9([1, 2, 3, 4, 9]) → False
array_front9([1, 2, 3, 4, 5]) → False...Save, Compile, Run         
def array_front9(nums):

  loopcount = len(nums)
  if loopcount > 4:
    loopcount = 4
  for i in range(loopcount):
    if nums[i] == 9:
      return True
  
  return False
---------------------------------------------------------------p113152.html ---------------------------------------------------------------
Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".


string_bits('Hello') → 'Hlo'
string_bits('Hi') → 'H'
string_bits('Heeololeo') → 'Hello'...Save, Compile, Run         
def string_bits(str):
  ret = ''
  for i in range(len(str)):
    if (i+1) %2 == 1:
      ret += str[i]

  return ret
---------------------------------------------------------------p113659.html ---------------------------------------------------------------
Return an int array length 3 containing the first 3 digits of pi, {3, 1, 4}.


make_pi() → [3, 1, 4]...Save, Compile, Run
def make_pi():
   return [3,1,4]
---------------------------------------------------------------p115413.html ---------------------------------------------------------------
Given a string name, e.g. "Bob", return a greeting of the form "Hello Bob!".


hello_name('Bob') → 'Hello Bob!'
hello_name('Alice') → 'Hello Alice!'
hello_name('X') → 'Hello X!'...Save, Compile, Run
def hello_name(name):
  return "Hello " + name + "!"
---------------------------------------------------------------p116620.html ---------------------------------------------------------------
Given 2 ints, a and b, return their sum. However, sums in the range 10..19 inclusive, are forbidden, so in that case just return 20.


sorta_sum(3, 4) → 7
sorta_sum(9, 4) → 20
sorta_sum(10, 11) → 21...Save, Compile, Run
def sorta_sum(a, b):
  sum = a+b
  if sum >=10 and sum<20:
    return 20
  else:
    return sum
---------------------------------------------------------------p118366.html ---------------------------------------------------------------
Given a non-empty string like "Code" return a string like "CCoCodCode".


string_splosion('Code') → 'CCoCodCode'
string_splosion('abc') → 'aababc'
string_splosion('ab') → 'aab'...Save, Compile, Run         
def string_splosion(str):
  ret = ''
  for i in range(len(str)+1):
    ret += str[0:i]
    
  return ret
---------------------------------------------------------------p118406.html ---------------------------------------------------------------
We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks. This is a little harder than it looks and can be done without any loops.


make_bricks(3, 1, 8) → True
make_bricks(3, 1, 9) → False
make_bricks(3, 2, 10) → True...Save, Compile, Run
def make_bricks(small, big, goal):
  if big ==0:
    return small >=goal
  elif big*5 == goal:
    return True
  else:
    rem = 0
    if goal > big*5:
      rem = goal - (big*5)
    else:
      rem = goal % 5
    return small >= rem 
---------------------------------------------------------------p119308.html ---------------------------------------------------------------
Given an array of ints, return True if the array contains a 2 next to a 2 somewhere.


has22([1, 2, 2]) → True
has22([1, 2, 1, 2]) → False
has22([2, 1, 2]) → False...Save, Compile, Run
def has22(nums):
  for num in range(len(nums)-1):
    if nums[num] == 2 and nums[num+1] == 2:
      return True
  
  return False
---------------------------------------------------------------p119867.html ---------------------------------------------------------------
Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a boolean indicating if we are on vacation, return a string of the form "7:00" indicating when the alarm clock should ring. Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00". Unless we are on vacation -- then on weekdays it should be "10:00" and weekends it should be "off".


alarm_clock(1, False) → '7:00'
alarm_clock(5, False) → '7:00'
alarm_clock(0, False) → '10:00'...Save, Compile, Run
def alarm_clock(day, vacation):
  #weekend calculation
  if vacation:
    weekday = "10:00"
    weekend = "off"
  else:
    weekday = "7:00"
    weekend = "10:00"    
    
  if (day == 0 or day ==6):
    return weekend
  else:
    return weekday
---------------------------------------------------------------p120546.html ---------------------------------------------------------------
We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return True if we are in trouble.


monkey_trouble(True, True) → True
monkey_trouble(False, False) → True
monkey_trouble(True, False) → False...Save, Compile, Run         
def monkey_trouble(a_smile, b_smile):
  if a_smile and b_smile:
    return True
  if not a_smile and not b_smile:
    return True
  return False
---------------------------------------------------------------p124676.html ---------------------------------------------------------------
Given an int n, return True if it is within 10 of 100 or 200. Note: abs(num) computes the absolute value of a number.


near_hundred(93) → True
near_hundred(90) → True
near_hundred(89) → False...Save, Compile, Run         
def find(num,n):
  dif = abs(num-n)
  if dif <= 10:
    return True
  
  return False
  
def near_hundred(n):
  ret = find(100,n)
  if not ret:  
    ret = find(200,n)
  
  return ret
---------------------------------------------------------------p124806.html ---------------------------------------------------------------
Given an array of ints, return a new array length 2 containing the first and last elements from the original array. The original array will be length 1 or more.


make_ends([1, 2, 3]) → [1, 3]
make_ends([1, 2, 3, 4]) → [1, 4]
make_ends([7, 4, 6, 2]) → [7, 2]...Save, Compile, Run
def make_ends(nums):
  return [nums[0],nums[-1]]
---------------------------------------------------------------p124984.html ---------------------------------------------------------------
Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10.


makes10(9, 10) → True
makes10(9, 9) → False
makes10(1, 9) → True...Save, Compile, Run         
def makes10(a, b):
  if a == 10 or b == 10 or a+b ==10:
    return True
  return False
---------------------------------------------------------------p126968.html ---------------------------------------------------------------
Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except not counting the largest and smallest values in the array. Use int division to produce the final average. You may assume that the array is length 3 or more.


centered_average([1, 2, 3, 4, 100]) → 3
centered_average([1, 1, 5, 5, 10, 8, 7]) → 5
centered_average([-10, -4, -2, -4, -2, 0]) → -3...Save, Compile, Run
def centered_average(nums):
  sortednums = sorted(nums)
  sortednums.remove(sortednums[0])
  sortednums.remove(sortednums[-1])
  sum = 0
  for num in range(len(sortednums)):
    sum+=sortednums[num]
  return sum/len(sortednums)
---------------------------------------------------------------p127703.html ---------------------------------------------------------------
Given 2 strings, return their concatenation, except omit the first char of each. The strings will be at least length 1.


non_start('Hello', 'There') → 'ellohere'
non_start('java', 'code') → 'avaode'
non_start('shotl', 'java') → 'hotlava'...Save, Compile, Run
def non_start(a, b):
  return a[1:]+b[1:]
---------------------------------------------------------------p129125.html ---------------------------------------------------------------
You and your date are trying to get a table at a restaurant. The parameter "you" is the stylishness of your clothes, in the range 0..10, and "date" is the stylishness of your date's clothes. The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very stylish, 8 or more, then the result is 2 (yes). With the exception that if either of you has style of 2 or less, then the result is 0 (no). Otherwise the result is 1 (maybe).


date_fashion(5, 10) → 2
date_fashion(5, 2) → 0
date_fashion(5, 5) → 1...Save, Compile, Run         
def date_fashion(you, date):
  if you <=2 or date <=2:
    return 0
  if you >=8 or date >=8:
    return 2
  
  return 1
---------------------------------------------------------------p129981.html ---------------------------------------------------------------
Given an "out" string length 4, such as "<<>>", and a word, return a new string where the word is in the middle of the out string, e.g. "<<word>>".


make_out_word('<<>>', 'Yay') → '<<Yay>>'
make_out_word('<<>>', 'WooHoo') → '<<WooHoo>>'
make_out_word('[[]]', 'word') → '[[word]]'...Save, Compile, Run
def make_out_word(out, word):
  s = "{0}{1}{2}".format(out[0:2],word,out[2:])
  return s
---------------------------------------------------------------p132290.html ---------------------------------------------------------------
The web is built with HTML strings like "<i>Yay</i>" which draws Yay as italic text. In this example, the "i" tag makes <i> and </i> which surround the word "Yay". Given tag and word strings, create the HTML string with tags around the word, e.g. "<i>Yay</i>".


make_tags('i', 'Yay') → '<i>Yay</i>'
make_tags('i', 'Hello') → '<i>Hello</i>'
make_tags('cite', 'Yay') → '<cite>Yay</cite>'...Save, Compile, Run
def make_tags(tag, word):
  return "<{0}>{1}</{0}>".format(tag,word)
  
---------------------------------------------------------------p135290.html ---------------------------------------------------------------
Given an array of ints length 3, figure out which is larger between the first and last elements in the array, and set all the other elements to be that value. Return the changed array.


max_end3([1, 2, 3]) → [3, 3, 3]
max_end3([11, 5, 9]) → [11, 11, 11]
max_end3([2, 11, 3]) → [3, 3, 3]...Save, Compile, Run
def max_end3(nums):
  max1 = max(nums[0],nums[-1])
  return [max1,max1,max1]
---------------------------------------------------------------p135815.html ---------------------------------------------------------------
The squirrels in Palo Alto spend most of the day playing. In particular, they play if the temperature is between 60 and 90 (inclusive). Unless it is summer, then the upper limit is 100 instead of 90. Given an int temperature and a boolean is_summer, return True if the squirrels play and False otherwise.


squirrel_play(70, False) → True
squirrel_play(95, False) → False
squirrel_play(95, True) → True...Save, Compile, Run
def squirrel_play(temp, is_summer):
  upper_limit = 90
  if is_summer == True:
    upper_limit = 100
  
  return temp >= 60 and temp <=upper_limit
---------------------------------------------------------------p137202.html ---------------------------------------------------------------
You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases.


caught_speeding(60, False) → 0
caught_speeding(65, False) → 1
caught_speeding(65, True) → 0...Save, Compile, Run
def caught_speeding(speed, is_birthday):
  limit_ext = 0
  if is_birthday:
    limit_ext = 5
  
  if speed <= 60+limit_ext:
    return 0
  elif speed <= 80 +limit_ext:
    return 1
  else:
    return 2
---------------------------------------------------------------p138533.html ---------------------------------------------------------------
Given a string, return a version without the first and last char, so "Hello" yields "ell". The string length will be at least 2.


without_end('Hello') → 'ell'
without_end('java') → 'av'
without_end('coding') → 'odin'...Save, Compile, Run
def without_end(str):
  return str[1:-1]
---------------------------------------------------------------p141905.html ---------------------------------------------------------------
Given two int values, return their sum. Unless the two values are the same, then return double their sum.


sum_double(1, 2) → 3
sum_double(3, 2) → 5
sum_double(2, 2) → 8...Save, Compile, Run         
def sum_double(a, b):
  sum = a + b
  if a == b:
    return sum * 2
  
  return sum
---------------------------------------------------------------p143951.html ---------------------------------------------------------------
Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, it does not count towards the sum.


lone_sum(1, 2, 3) → 6
lone_sum(3, 2, 3) → 2
lone_sum(3, 3, 3) → 0...Save, Compile, Run
def lone_sum(a, b, c):
  list = [a,b,c]
  sorted_list = sorted(list)
  sum = 0
  if not sorted_list[0] == sorted_list[1]:
    sum += sorted_list[0] + sorted_list[1]
  
  if not sorted_list[1] == sorted_list[2]:
    sum += sorted_list[2]
  
  elif not list == sorted_list:
    sum -= sorted_list[2]
  
  return sum
---------------------------------------------------------------p145834.html ---------------------------------------------------------------
Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring).


last2('hixxhi') → 1
last2('xaxxaxaxx') → 1
last2('axxxaaxx') → 2...Save, Compile, Run         
def last2(str):
  if len(str) < 2:
    return 0
  
  last2 = str[len(str)-2:]
  count = 0
  
  for i in range(len(str)-2):
    sub = str[i:i+2]
    if sub == last2:
      count = count + 1

  return count
---------------------------------------------------------------p147755.html ---------------------------------------------------------------
Given 2 arrays of ints, a and b, return True if they have the same first element or they have the same last element. Both arrays will be length 1 or more.


common_end([1, 2, 3], [7, 3]) → True
common_end([1, 2, 3], [7, 3, 2]) → False
common_end([1, 2, 3], [1, 3]) → True...Save, Compile, Run
def common_end(a, b):
  if a[0] == b[0] or a[-1] == b[-1]:
    return True
  return False
---------------------------------------------------------------p147920.html ---------------------------------------------------------------
Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front.


front3('Java') → 'JavJavJav'
front3('Chocolate') → 'ChoChoCho'
front3('abc') → 'abcabcabc'...Save, Compile, Run         
def front3(str):
  front = str
  if len(str) >= 3:
    front = str[0:3]
  ret = ''
  for i in range(1,4):
    ret = ret + front
  
  return ret
---------------------------------------------------------------p148661.html ---------------------------------------------------------------
Given an array of ints length 3, return an array with the elements "rotated left" so {1, 2, 3} yields {2, 3, 1}.


rotate_left3([1, 2, 3]) → [2, 3, 1]
rotate_left3([5, 11, 9]) → [11, 9, 5]
rotate_left3([7, 0, 0]) → [0, 0, 7]...Save, Compile, Run
def rotate_left3(nums):
  nums.append(nums[0])
  nums.remove(nums[0])
  return nums
---------------------------------------------------------------p148853.html ---------------------------------------------------------------
Given a string, return a new string made of 3 copies of the last 2 chars of the original string. The string length will be at least 2.


extra_end('Hello') → 'lololo'
extra_end('ab') → 'ababab'
extra_end('Hi') → 'HiHiHi'...Save, Compile, Run
def extra_end(str):
  s = str[-2:]
  return 3*s
---------------------------------------------------------------p149391.html ---------------------------------------------------------------
Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not.


xyz_there('abcxyz') → True
xyz_there('abc.xyz') → False
xyz_there('xyz.abc') → True...Save, Compile, Run
def xyz_there(str):
  str = str.replace('.xyz','')
  index = str.find('xyz')
  
  return index >= 0 and not str[index-1] == "."
---------------------------------------------------------------p149524.html ---------------------------------------------------------------
Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..len(str)-1 inclusive).


missing_char('kitten', 1) → 'ktten'
missing_char('kitten', 0) → 'itten'
missing_char('kitten', 4) → 'kittn'...Save, Compile, Run         
def missing_char(str, n):
  if n > len(str):
    return str

  return str[:n] + str[n+1:] 
  
---------------------------------------------------------------p153599.html ---------------------------------------------------------------
Given a string, return a new string where the first and last chars have been exchanged.


front_back('code') → 'eodc'
front_back('a') → 'a'
front_back('ab') → 'ba'...Save, Compile, Run         
def front_back(str):
  if len(str) <=1: 
    return str
  s = str[-1] + str[1:len(str)-1] + str[0]
  return s
---------------------------------------------------------------p158497.html ---------------------------------------------------------------
Given a number n, return True if n is in the range 1..10, inclusive. Unless "outsideMode" is True, in which case return True if the number is less or equal to 1, or greater or equal to 10.


in1to10(5, False) → True
in1to10(11, False) → False
in1to10(11, True) → True...Save, Compile, Run
def in1to10(n, outside_mode):
  a=n
  if outside_mode:
    if a <=1 or a >=10:
      return True
    else:
      return False
  else:
    if a >=1 and a <=10:
      return True
    else:
      return False
---------------------------------------------------------------p160533.html ---------------------------------------------------------------
Given three ints, a b c, return True if one of b or c is "close" (differing from a by at most 1), while the other is "far", differing from both other values by 2 or more. Note: abs(num) computes the absolute value of a number.


close_far(1, 2, 10) → True
close_far(1, 2, 3) → False
close_far(4, 1, 3) → True...Save, Compile, Run
def close_far(a, b, c):
  abs_b = abs(b-a)
  abs_c = abs(c-a)
  abs_c2 = abs(c-b)
  if abs_b <=1:
    return abs_c >=2 and abs_c2 >=2
  elif abs_c <=1:
    return abs_b >=2 and abs_c2 >=2
  else:
    return False
---------------------------------------------------------------p160545.html ---------------------------------------------------------------
Given a string, return a "rotated left 2" version where the first 2 chars are moved to the end. The string length will be at least 2.


left2('Hello') → 'lloHe'
left2('java') → 'vaja'
left2('Hi') → 'Hi'...Save, Compile, Run
def left2(str):
  return str[2:] + str[0:2]
---------------------------------------------------------------p162058.html ---------------------------------------------------------------
Given 2 int values, return True if one is negative and one is positive. Unless the parameter "negative" is True, then they both must be negative.


pos_neg(1, -1, False) → True
pos_neg(-1, 1, False) → True
pos_neg(1, 1, False) → False...Save, Compile, Run         
def pos_neg(a, b, negative):
  if negative and a<0 and b<0:
    return True
  elif not negative and ((a<0 and b > 0) or (a>0 and b < 0)):
    return True
  
  return False
---------------------------------------------------------------p164876.html ---------------------------------------------------------------
Return True if the string "cat" and "dog" appear the same number of times in the given string.


cat_dog('catdog') → True
cat_dog('catcat') → False
cat_dog('1cat1cadodog') → True...Save, Compile, Run
def cat_dog(str):
  catcount = 0
  dogcount = 0
  for i in range(len(str)-2):
    if str[i:i+3] =='cat':
      catcount+=1
    if str[i:i+3] =='dog':
      dogcount+=1

  return catcount == dogcount
---------------------------------------------------------------p165097.html ---------------------------------------------------------------
Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front;


front_times('Chocolate', 2) → 'ChoCho'
front_times('Chocolate', 3) → 'ChoChoCho'
front_times('Abc', 3) → 'AbcAbcAbc'...Save, Compile, Run         
def front_times(str, n):
  ret = ''
  front = str[0:3]
  for i in range(n):
    ret += front
    
  return ret
---------------------------------------------------------------p165321.html ---------------------------------------------------------------
Given a non-negative number "num", return True if num is within 2 of a multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2.


near_ten(12) → True
near_ten(17) → False
near_ten(19) → True...Save, Compile, Run
def near_ten(num):
  a =  num % 10
  return a <=2 or a >=8
---------------------------------------------------------------p166170.html ---------------------------------------------------------------
Given an array of ints, return the number of 9's in the array.


array_count9([1, 2, 9]) → 1
array_count9([1, 9, 9]) → 2
array_count9([1, 9, 9, 3, 9]) → 3...Save, Compile, Run         
def array_count9(nums):
  ret = 0
  for i in range(len(nums)):
    if nums[i] == 9:
      ret+=1
  
  return ret
---------------------------------------------------------------p166884.html ---------------------------------------------------------------
We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return True if we are in trouble.


parrot_trouble(True, 6) → True
parrot_trouble(True, 7) → False
parrot_trouble(False, 6) → False...Save, Compile, Run         
def parrot_trouble(talking, hour):
  if talking and (hour < 7 or hour > 20):
    return True
  return False
---------------------------------------------------------------p167246.html ---------------------------------------------------------------
Return the number of times that the string "hi" appears anywhere in the given string.


count_hi('abc hi ho') → 1
count_hi('ABChi hi') → 2
count_hi('hihi') → 2...Save, Compile, Run         
def count_hi(str):
  count = 0
  for i in range(len(str)-1):
    if str[i:i+2] =='hi' and not i == len(str):
      count+=1
  
  return count
---------------------------------------------------------------p170842.html ---------------------------------------------------------------
Given a string, return a string where for every char in the original, there are two chars.


double_char('The') → 'TThhee'
double_char('AAbb') → 'AAAAbbbb'
double_char('Hi-There') → 'HHii--TThheerree'...Save, Compile, Run         
def double_char(str):
  finalstr =''
  for s in str:
    finalstr += 2*s
  return finalstr
---------------------------------------------------------------p171011.html ---------------------------------------------------------------
Given 2 int arrays, a and b, each length 3, return a new array length 2 containing their middle elements.


middle_way([1, 2, 3], [4, 5, 6]) → [2, 5]
middle_way([7, 7, 7], [3, 8, 0]) → [7, 8]
middle_way([5, 2, 9], [1, 4, 5]) → [2, 4]...Save, Compile, Run
def middle_way(a, b):
  return [a[1],b[1]]
---------------------------------------------------------------p173401.html ---------------------------------------------------------------
The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in.


sleep_in(False, False) → True
sleep_in(True, False) → False
sleep_in(False, True) → True...Save, Compile, Run         
def sleep_in(weekday, vacation):
  if(weekday and not vacation):
    return False
  return True
---------------------------------------------------------------p174314.html ---------------------------------------------------------------
Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: s.lower() returns the lowercase version of a string.


end_other('Hiabc', 'abc') → True
end_other('AbC', 'HiaBc') → True
end_other('abc', 'abXabc') → True...Save, Compile, Run         
def end_other(a, b):
  a =a.lower()
  b = b.lower()
  if a[-len(b):] == b:
    return True
  if b[-len(a):] == a:
    return True
  return False
---------------------------------------------------------------p177892.html ---------------------------------------------------------------
Given an int array length 2, return True if it contains a 2 or a 3.


has23([2, 5]) → True
has23([4, 3]) → True
has23([4, 5]) → False...Save, Compile, Run
def has23(nums):
  a= nums
  if a[0] == 2 or a[1] == 2 or a[0] == 3 or a[1] == 3:
    return True
  return False
---------------------------------------------------------------p179078.html ---------------------------------------------------------------
Given an array of ints, return True if the array is length 1 or more, and the first element and the last element are the same.


same_first_last([1, 2, 3]) → False
same_first_last([1, 2, 3, 1]) → True
same_first_last([1, 2, 1]) → True...Save, Compile, Run
def same_first_last(nums):
  if len(nums) > 0 and (nums[0] == nums[len(nums)-1]):
    return True
  return False
---------------------------------------------------------------p179960.html ---------------------------------------------------------------
For this problem, we'll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more, so 15 rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, so 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, write a separate helper "def round10(num):" and call it 3 times. Write the helper entirely below and at the same indent level as round_sum().


round_sum(16, 17, 18) → 60
round_sum(12, 13, 14) → 30
round_sum(6, 4, 4) → 10...Save, Compile, Run
def round10(num):
  if (num % 10) >= 5:
    return num +  10 - (num%10)
  if (num % 10) < 5:
    return num -  (num%10)
def round_sum(a, b, c):
  return round10(a)+round10(b)+round10(c)
---------------------------------------------------------------p181624.html ---------------------------------------------------------------
Given an array of ints, return True if 6 appears as either the first or last element in the array. The array will be length 1 or more.


first_last6([1, 2, 6]) → True
first_last6([6, 1, 2, 3]) → True
first_last6([3, 2, 1]) → False...Save, Compile, Run
def first_last6(nums):
  if nums[0] == 6 or nums[len(nums)-1]==6:
    return True
  return False
---------------------------------------------------------------p182144.html ---------------------------------------------------------------
Given two strings, a and b, return the result of putting them together in the order abba, e.g. "Hi" and "Bye" returns "HiByeByeHi".


make_abba('Hi', 'Bye') → 'HiByeByeHi'
make_abba('Yo', 'Alice') → 'YoAliceAliceYo'
make_abba('x', 'y') → 'xyyx'...Save, Compile, Run
def make_abba(a, b):
  return a + b + b + a
---------------------------------------------------------------p182414.html ---------------------------------------------------------------
Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.


string_match('xxcaazz', 'xxbaaz') → 3
string_match('abc', 'abc') → 2
string_match('abc', 'axc') → 0...Save, Compile, Run         
def string_match(a, b):
  loopcount = len(a)
  if len(b) < loopcount:
    loopcount = len(b)
  ret = 0
  for i in range(loopcount-1):
    if a[i:i+2] == b[i:i+2]:
      ret+=1
  
  return ret
---------------------------------------------------------------p184816.html ---------------------------------------------------------------
Given a string, return the string made of its first two chars, so the String "Hello" yields "He". If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "".


first_two('Hello') → 'He'
first_two('abcdefg') → 'ab'
first_two('ab') → 'ab'...Save, Compile, Run
def first_two(str):
  if len(str) > 2:
    return str[0:2]
  return str
---------------------------------------------------------------p184853.html ---------------------------------------------------------------
Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values.


big_diff([10, 3, 5, 6]) → 7
big_diff([7, 2, 10, 9]) → 8
big_diff([2, 10, 7, 2]) → 8...Save, Compile, Run
def big_diff(nums):
  sortednum = sorted(nums)
  return sortednum[-1] - sortednum[0]
---------------------------------------------------------------p186048.html ---------------------------------------------------------------
Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.


count_code('aaacodebbb') → 1
count_code('codexxcode') → 2
count_code('cozexxcope') → 2...Save, Compile, Run
def count_code(str):
  count = 0
  for i in range(len(str)-3):
    if str[i:i+2] =='co' and str[i+3:i+4] == 'e':
      count+=1
  return count
---------------------------------------------------------------p189441.html ---------------------------------------------------------------
Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged.


not_string('candy') → 'not candy'
not_string('x') → 'not x'
not_string('not bad') → 'not bad'...Save, Compile, Run         
def not_string(str):
  ret = 'not '+str
  if str[0:3] == 'not':
    ret = str
  return ret
---------------------------------------------------------------p189616.html ---------------------------------------------------------------
Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.


count_evens([2, 1, 2, 3, 4]) → 3
count_evens([2, 2, 0]) → 3
count_evens([1, 3, 5]) → 0...Save, Compile, Run         
def count_evens(nums):
  count = 0
  for num in nums:
    if num%2 ==0:
      count+=1
  return count
---------------------------------------------------------------p191645.html ---------------------------------------------------------------
Given an array of ints length 3, return the sum of all the elements.


sum3([1, 2, 3]) → 6
sum3([5, 11, 2]) → 18
sum3([7, 0, 0]) → 7...Save, Compile, Run
def sum3(nums):
  return nums[0]+nums[1]+nums[2]
---------------------------------------------------------------p192589.html ---------------------------------------------------------------
Given an array of ints, return the sum of the first 2 elements in the array. If the array length is less than 2, just sum up the elements that exist, returning 0 if the array is length 0.


sum2([1, 2, 3]) → 3
sum2([1, 1]) → 2
sum2([1, 1, 1, 1]) → 2...Save, Compile, Run
def sum2(nums):
  if len(nums) == 0:
    return 0
    
  if len(nums) == 1:
    return nums[0]
  return nums[0]+nums[1]
---------------------------------------------------------------p192962.html ---------------------------------------------------------------
Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}.


reverse3([1, 2, 3]) → [3, 2, 1]
reverse3([5, 11, 9]) → [9, 11, 5]
reverse3([7, 0, 0]) → [0, 0, 7]...Save, Compile, Run
def reverse3(nums):
  nums.reverse()
  return nums
---------------------------------------------------------------p193507.html ---------------------------------------------------------------
Given a string and a non-negative int n, return a larger string that is n copies of the original string.


string_times('Hi', 2) → 'HiHi'
string_times('Hi', 3) → 'HiHiHi'
string_times('Hi', 1) → 'Hi'...Save, Compile, Run         
def string_times(str, n):
  ret = ''
  for i in range(1,n+1):
    ret = ret + str
  
  return ret
---------------------------------------------------------------p193604.html ---------------------------------------------------------------
Given an array of ints, return True if .. 1, 2, 3, .. appears in the array somewhere.


array123([1, 1, 2, 3, 1]) → True
array123([1, 1, 2, 4, 1]) → False
array123([1, 1, 2, 1, 2, 3]) → True...Save, Compile, Run         
def array123(nums):
  str = "".join(["%s" % el for el in nums])
  if str.find('1') >= 0 and str.find('2') >= 0 and str.find('3') >= 0:
    return True
  return False
---------------------------------------------------------------p194053.html ---------------------------------------------------------------
Given 2 strings, a and b, return a string of the form short+long+short, with the shorter string on the outside and the longer string on the inside. The strings will not be the same length, but they may be empty (length 0).


combo_string('Hello', 'hi') → 'hiHellohi'
combo_string('hi', 'Hello') → 'hiHellohi'
combo_string('aaa', 'b') → 'baaab'...Save, Compile, Run
def combo_string(a, b):
  s = sorted([a,b],key=len)
  return s[0]+s[1]+s[0]
---------------------------------------------------------------p195669.html ---------------------------------------------------------------
When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return True if the party with the given values is successful, or False otherwise.


cigar_party(30, False) → False
cigar_party(50, False) → True
cigar_party(70, True) → True...Save, Compile, Run         
def cigar_party(cigars, is_weekend):
  if cigars >=40 and (cigars <=60 or is_weekend == True):
    return True
  return False
---------------------------------------------------------------p197466.html ---------------------------------------------------------------
Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21.


diff21(19) → 2
diff21(10) → 11
diff21(21) → 0...Save, Compile, Run         
def diff21(n):
  diff = abs(n - 21)
  if n > 21:
    diff = diff * 2
  return diff
  

Coding bat - solutions - Code

Now that the solutions are downloaded, i dont know how to attach them as a file link here, so i need to extract all the QUESTION - ANSWER part and post it ....there goes the parsing again.....

this is the program that i used to parse the output and save the contents...
import sys
import re
import os

directory = 'd:\\scripts\\myhack\\'
filelist = os.listdir(directory)

f = open(r'd:\full.html','w')
for filename in filelist:
    print filename
    file = open(os.path.join(directory,filename),'r')
    content = file.read()
    sindex = content.find('
')
    endIndex = content.find('')
    newcon = content[sindex:endIndex+11].replace('textarea','pre').replace('button','button style=\"visibility:hidden\"')+'
'
    f.write('---------------------------------------------------------------')
    f.write(''+filename+'')
    f.write('\n')
    f.write('---------------------------------------------------------------')
    f.write('\n')
    f.write(newcon)
    f.write('\n')
f.close()

Parse Hyperlinks - Python

 While doing my previous post (downloading content from codingbat) i got this script for parsing the url links


urls = re.findall(r'href=[\'"]p?([^\'" >]+)', line)

r - is provided to denote the string is a rawstring(we dont need to specify escape charcters)
href=[\'"] - the string must start with "HREF=" and can either have any of the characters (' - single quote, " - double quote) next to it.
p? - the next character must be a p
([^\'" >]+) - it must end with a greater than symbol which must be preceeded either by single or double quote.

Coding bat - Post Soutions

I am not sure whether this is a intellectual property right, but these are the exercises that I solved in coding bat, a site by Nick Parlante ( who was a inspiration for me to seriously look at Python )

ok I have been trying for an hour to hack into coding bat with my user name and password - using python urllib2 module, there seems to something that keeps me out of their pages.

I am just trying to download their tutorials and post it in my blog (the actual reason for creating this particular blog post), so i have downloaded this python module called mechanize which is very promising, have to try it out and see whether it works...

[EDIT:]
and it works !!! this is the download link for the web site

http://wwwsearch.sourceforge.net/mechanize/
and here is the coding that I used to get access to the web site and download the content

#/usr/bin/env python
import sys, os, re
from urllib2 import HTTPError

import mechanize
assert mechanize.__version__ >= (0, 0, 6, "a")
mech = mechanize.Browser()
mech.set_handle_robots(False)

try:
    mech.open("http://codingbat.com")
except HTTPError, e:
    sys.exit("%d: %s" % (e.code, e.msg))

mech.select_form(nr=0)
mech["uname"] = "your registered email id"
mech["pw"] =  "password"
mech.submit()

#s = mech.retrieve('http://codingbat.com','d:/aa.html')
#[EDIT]
#this page will throw up error stating the user or tag is expired, what you need to do is login to the web site and copy the link for the "DONE" page here
mech.retrieve('http://codingbat.com/done','d:/url.html')

content = open('d://url.html','r').readlines()
i=0
for line in content:
    urls = re.findall(r'href=[\'"]p?([^\'" >]+)', line)
    for url in urls:
            if url[0:4] == '/pro':
                i+=1
                print "Processing",'http:/codingbat.com'+url
                mech.retrieve(r'http://codingbat.com'+url,'d://myhack//'+str(i)+'.html')

#make sure you create a folder d:\myHack which will used to save the files.

Database access - GUYI - Part I - Server Auth Page

3:43So, we have two class that can be used to connect to the database and retrieve records based on a query (see my previous two posts).

Now let us start forming the basics of the GUI, a page/screen which will be used to get & store the connection string settings, option to load the saved connection string settings.

Following will be a summary of the functionality which needs to be done.
-> Select existing connection strings
->select database type (MY SQL/MS SQL/ORACLE)
->IP address/severname
-> database name
-> user name and password


After getting these details validate the connection setting and save them in a FLAT file.

Monday, November 22, 2010

PyGame and GUI Programming - Multiple Database Access - Part II

This is the connect_server.py file. This module will be imported in the connection py file(previous post), this is just a common piece of coding, which connects to the database and returns a connection object, being a C# programmer i can see only the DATA as a DATATABLE rather than a recordset...:-)

so a method getDataTable will retun a record set for the query passed.

and ofcourse a main method to test the code(which is executed only during command line execution of this file and not during IMPORTS)

import MySQLdb

class databaseOps():
    '''
    This class is used to connect to the database, the connection object is accessed
    with the variable db
    '''
    def __init__(self,hosts,username,password,database):
    #open a connection if it does not have one already
        self.db = MySQLdb.connect(host=hosts, user=username , passwd=password, db=database)

    def get_data_table(self,query):
        cursor = self.db.cursor()
        try:
            cursor.execute(query)
            return cursor
        except MySQLdb.Error, e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            sys.exit (1)

def main():
    f = databaseOps('localhost','root','1234','MyFirst')
    print 'Connection successful !!!'

if __name__ == '__main__':
    main()

PyGame and GUI Programming - Multiple Database Access - Part I

OK!! now that I have started with the actual coding part of it. Here is my folder structure

scripts/m_db_access/
server.py
connect_server.py

the server.py file will contain the scripts that i am using to identify the type of database that i will connect, I have just made a sample of MYSQL(because that is the only database that I have). here is the coding part of it



class init_connection():
    '''
    This class is used to initialize the connection to any kind of database,based on the database that we set in the variable "server_type" the respective module will be loaded
    '''
    def get_connection(self,server_type):
        '''
        server_type -> the type of the server to connect (MYSQL/ORACLE/MSSQL)
        '''
        if server_type == 'MYSQL':
            import connect_server
            return connect_server.databaseOps('localhost','root','xxxx','DBNAME')
        else:
            import somethingelse #some other import statements

       
def main():
    '''
    Test method to check the module is working or not, we can add more cases as the class grows
    '''
    conn_type = init_connection()
    conn = conn_type.get_connection('MYSQL')

    print conn.db
    print 'Connection successful !!!'

#this peice of code is to tell the interpreter that execute the MAIN method only# when accessed through command line and not during IMPORT
if __name__ == '__main__':
    main()

PyGame and GUI Programming - Multiple Database Access

Its been a while since I have started learning. What was fun in the beginning is more fun now. Python seems to be exceptionally powerful, and I have started getting the heart of it. So now I am planning to do an interface for accessing multiple databases. This will be the kind of real time project of me in Python, my way of saying "Hello World".


What?
An interface (first in command line and in GUI), that will be used to access databases.

Components ?
A server configuration screen where you can enter select Server type(Oracle/MySQL/MSSQL), enter server name, user name/password, select database.

After a database is selected, list all the tables that the database holds along with information of each object...

The easy part?
going to write in Python

The difficult part?
Everything else....

So python Enthusiast, help me with some of your thoughts, suggestions, i will try to post more code over here, once the project is in a good shape, i will codeplex it...

Happy Python !!!! 

Sunday, November 21, 2010

Running Python scripts from Python

During my start up days of learning Python, i had the necessity to shuttle between python prompt and command script (terminal), because of the reason i did not know how to run python files(.py files) from Python.


this is how to do it...
import os
os.system('python somefile.py')
#simple...

Wednesday, November 17, 2010

Python - GUI programming script - Tkinter

This is a sample script which is used to create a label and display it in a window. The script uses Tkinter library for GUI programming. There are several other GUI tools that are available, you can use anything that suits your needs, but this small script is to understand the basics of what python GUI is all about. I will be writing more scripts on GUI with Python,

import Tkinter
from Tkinter import *

def create_label(caption):
    widget = Label(text=caption)
    return widget

def main():
    root = Tk()
    labelfont = ('times', 24, 'italic')
    widget = Label(root, text='Eat At JOES')
    widget.config(bg='black', fg='red')
    widget.pack(expand=YES, fill=BOTH)
    root.mainloop( )

if __name__ == '__main__':
    main()

Tuesday, November 16, 2010

Download files - Python

use of this code is primarily to download imaes from a certain url(say you have the urls saved as a text file...sample would be something like this...

**i got this from the site gnome arts** where the second part of a line is a image

////////////////////
[IMG] ABSTRACT-AbstractChaos_1280x1024.jpg                          19-May-2006 06:05  893K 
[IMG] ABSTRACT-AbstractChaosgold_1024x768.jpg                       19-May-2006 06:05  411K 
[IMG] ABSTRACT-AbstractChaosgold_1280x1024.jpg                      19-May-2006 06:06  794K 
[IMG] ABSTRACT-AbstractGNOME_1024x768.png                           22-Dec-2006 06:05  1.4M 
[IMG] ABSTRACT-Abstract_1024x768.png                                15-Jun-2007 14:06  843K 
[IMG] ABSTRACT-AnotherBlueRidge_1024x768.png                        26-Jul-2007 14:05  929K 
///////////////////

the python script that is used to download the images and save it to a folder "scripts/downloads" is given below

import urllib,os
import os

#the name of the file where you have the url in the above defined format
f = open('./scripts/url.txt','r')
lines = f.read()
#changing the directory so that you downloaded files can be saved here
os.chdir('./scripts/download/')

#loop thru
for line in lines.split('\n'):
    if not line == "":
    #the url link from where you have to download
        url = 'http://ftp.gnome.org/pub/GNOME/teams/art.gnome.org/backgrounds/'+line.split(' ')[1]
        message = urllib.urlretrieve(url,line.split(' ')[1])
        print "Downloaded :",message

print "downloaded..."


# iam sorry for the poor formatting(which is non-python)...the editor actually removes all the indentation part of the text