My very first python program, need help

Wojtek Walczak gminick at nie.ma.takiego.adresu.w.sieci.pl
Sun Aug 10 10:21:27 EDT 2008


Dnia Sun, 10 Aug 2008 15:52:37 +0200, WP napisa³(a):

Hi,

> import re
>
> def calculate_sum_1(str):
                      ^^^
               this word is reserved, better use some other name

>      for c in str:
>          if c.isdigit() == False and c != ' ':
>              # That we assign to the variable we're looping over worries 
> me...
>              str = str.replace(c, ' ')

It's good that it worries you. AFAIR python behavior when assigning to
a variable that is used in for loop is undefined, so you can't count
on it. Better introduce second variable.

>
>      mylist = str.split()
>
>      print "(for loop version) mylist after replace() and split() = ", 
> mylist
>
>      sum = 0
>
>      for item in mylist:
>         sum += long(item)

You could use list comprehensions and sum function in here.



> def calculate_sum_2(str):
>      #print "In replace_nondigits_2(), str = ", str
>      p = re.compile('[^0-9]')

or: p = re.compile('\d+')
'\d+' is for one or more digits

>      mylist = p.split(str)

You don't have to split this string. Just search through it.
Findall method seems appropriate.

A bit more pythonic approaches to both of your functions:

=======================
import re

a="123xx,22! p1"

# Note that 'string' isn't the best name too. It may be shadowed by
# or shadow 'string' module if it's imported.
def calculate_sum_1(string):
   result = ''

   for i in string:
      if i.isdigit():
         result += i
      else:
         result += ' '

   return sum([int(i) for i in result.split()])


def calculate_sum_2(string):
   pat = re.compile('\d+')
   digits = [int(i) for i in re.findall(pat, string)]
   return sum(digits)


print calculate_sum_1(a)
print calculate_sum_2(a)
===========================


-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/



More information about the Python-list mailing list