473,322 Members | 1,431 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

My very first python program, need help

WP
Hello, below is my very first python program. I have some questions
regarding it and would like comments in general. I won't be able to get
my hands on a good python book until tomorrow at the earliest. The
program takes a string and sums all numbers inside it. I'm testing with
the following string: "123xx,22! p1" which should yield a sum of 123 +
22 + 1 = 146. My solution to this exercise was to write a function that
takes a string and splits it into a list of numbers and then I will sum
up the numbers in the list. In fact, I wrote two versions of this
function: One uses a for loop to replace all characters that is not a
digit and not a space with a space. That should leave me with the
numbers intact and with only spaces separating these numbers. Then I
call split to get a list of numbers (here I discovered I must not use a
sep equal to ' ' or the returned list would contain empty strings as
well). This is calculate_sum_1() and look at the comment in the code to
see what worries me there. The second one uses regular expressions and
the problem I have with that is that I get a list of containing not just
the numbers but empty strings as well. I'm working around that in my
loop that sums the numbers but it would be better to not have these
empty string in the list in the first place. Here's the code:

import re

def calculate_sum_1(str):
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, ' ')

mylist = str.split()

print "(for loop version) mylist after replace() and split() = ",
mylist

sum = 0

for item in mylist:
sum += long(item)

return sum

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

mylist = p.split(str)

print "(regex version) mylist after calling split(): ", mylist

sum = 0

for item in mylist:
if item.isdigit():
sum += long(item)

return sum

str = "123xx,22! p1" # Sum = 123 + 22 + 1 = 146

print "str = ", str

print "calculate_sum_1(str): %d" % calculate_sum_1(str)
print "calculate_sum_2(str): %d" % calculate_sum_2(str)

The output when run is:
str = 123xx,22! p1
(for loop version) mylist after replace() and split() = ['123', '22', '1']
calculate_sum_1(str): 146
(regex version) mylist after calling split(): ['123', '', '', '22', '',
'', '1']
calculate_sum_2(str): 146
Hope I made some sense and thanks for reading!

- Eric (WP)
Aug 10 '08 #1
2 1390
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/
Aug 10 '08 #2
WP
Wojtek Walczak wrote:
[snip]
Thanks for all your help. I've incorporated your suggestions and moved
on to my next program. See new thread. :)

- Eric (WP)
Aug 10 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Ron Adam | last post by:
Hi, I'm having fun learning Python and want to say thanks to everyone here for a great programming language. Below is my first Python program (not my first program) and I'd apreciate any...
40
by: Shufen | last post by:
Hi all, Can someone who has use PHP before and know quite well about the language, tell me what are the stuffs that Python offers and PHP doesn't. A few examples will be nice. I know about the...
14
by: Mark Dufour | last post by:
After nine months of hard work, I am proud to introduce my baby to the world: an experimental Python-to-C++ compiler. It can convert many Python programs into optimized C++ code, without any user...
6
by: planetthoughtful | last post by:
Hi All, I've written my first piece of practical Python code (included below), and would appreciate some comments. My situation was that I had a directory with a number of subdirectories that...
29
by: 63q2o4i02 | last post by:
Hi, I'm interested in using python to start writing a CAD program for electrical design. I just got done reading Steven Rubin's book, I've used "real" EDA tools, and I have an MSEE, so I know what...
7
by: wardm | last post by:
I have created a Dict object in a C++ App that calls (embedded) Python functions. The Dict is to be used to pass variable data between the C++ App and the python functions. However I cannot get...
16
by: BartlebyScrivener | last post by:
I am a mere hobbyist. Spent several hours trying to make a class, because I think this is an occasion where I need one. But I can't make it work. This code "works" (only because of the global c,...
10
by: notejam | last post by:
I am trying to get started with a interactive version of Python for windows and need some help. I have played with the tutorial, and now want to write a program. In basic language, I could write...
7
by: Chris Lasher | last post by:
Hi all, I have a simple script: --- #!/usr/bin/env python a = 1 b = 2
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.