python question (about counting letters)

This is the place for queries that don't fit in any of the other categories.

python question (about counting letters)

Postby ltcy » Thu Feb 21, 2013 6:23 am

Question:
This function should count how many letters there are in the input string st, starting to count from position pos (counting the character in pos if it is a letter) and advancing one position at a time until encountering a digit or until reaching the end of the string. The string may contain letters, digits and also special characters. If pos is not a valid position in the string, the function should return 0.


For example:
countLettersFromPosUntilDigit('12abc!#456',0) should return 0
countLettersFromPosUntilDigit('abc!#456',1) should return 2


this is my code:
Code: Select all
def countLettersFromPosUntilDigit (st, pos):
count = 0
for i in range(pos, len(st)):
   if st[pos].isdigit():
      return count
   else:
      count = 0
return count


it failed and I don't know which part I did wrong, can someone please help me?
ltcy
 
Posts: 12
Joined: Sat Feb 16, 2013 1:32 am

Re: python question (about counting letters)

Postby metulburr » Thu Feb 21, 2013 6:44 am

Code: Select all
def countLettersFromPosUntilDigit (st, pos):
count = 0
for i in range(pos, len(st)):
   if st[pos].isdigit():
      return count
   else:
      count = 0
return count


well the first thing i see is you are never incrementing count. It is always 0.

This also just might be my style, but i would loop the string.
Code: Select all
   for char in st:
      if char.isdigit():

At that point though you need a way to adjust for position, which a string slice would work perfect for.
Code: Select all
   if pos:
      st = st[pos:]

assuming pos was a keyword argument defaulted to 0, and this preceding the for loop
New Users, Read This
version Python 3.3.2 and 2.7.5, tkinter 8.5, pyqt 4.8.4, pygame 1.9.2 pre
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
User avatar
metulburr
 
Posts: 1125
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 1 guest