473,671 Members | 2,501 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Small problem with print and comma

Hi,

I have a small problem with my function: printList. I use print with a
',' . Somehow the last digit of the last number isn't printed. I wonder
why.

import random

def createRandomLis t(param):
length = param

a = []
"""" creating random list"""
for i in range(0,length) :
a.append(random .randrange(100) )
return a

def printList(param ):
#doesn't work
#2 sample outputs
# 30 70 68 6 48 60 29 48 30 38
#sorted list
#6 29 30 30 38 48 48 60 68 7 <--- last character missing

#93 8 10 28 94 4 26 41 72 6
#sorted list
#4 6 8 10 26 28 41 72 93 9 <-- dito
for i in range(0,len(par am)):
print a[i],
#works
#for i in range(0,len(par am)-1):
# print a[i],
#print a[len(param)-1]
if __name__ == "__main__":
length = 10
a = createRandomLis t(length)
printList(a)

for j in range(1,len(a)) :
key = a[j]
i = j-1
while i -1 and a[i]>key:
a[i+1] = a[i]
i = i-1
a[i+1] = key

print "\n sorted list"
printList(a)

Jul 30 '06 #1
4 1377
why don't you iterate over the list instead of indices?
for elem in L: print elem,

you don't need the 0 when you call range: range(0, n) == range(n)
the last element of a range is n-1: range(n)[-1] == n-1
you don't need while to iterate backwards. the third argument to range
is step.
range(n-1, -1, -1) == [n-1, n-2, n-3, ..., 1, 0]

be************* @blawrc.de wrote:
Hi,

I have a small problem with my function: printList. I use print with a
',' . Somehow the last digit of the last number isn't printed. I wonder
why.

import random

def createRandomLis t(param):
length = param

a = []
"""" creating random list"""
for i in range(0,length) :
a.append(random .randrange(100) )
return a

def printList(param ):
#doesn't work
#2 sample outputs
# 30 70 68 6 48 60 29 48 30 38
#sorted list
#6 29 30 30 38 48 48 60 68 7 <--- last character missing

#93 8 10 28 94 4 26 41 72 6
#sorted list
#4 6 8 10 26 28 41 72 93 9 <-- dito
for i in range(0,len(par am)):
print a[i],
#works
#for i in range(0,len(par am)-1):
# print a[i],
#print a[len(param)-1]
if __name__ == "__main__":
length = 10
a = createRandomLis t(length)
printList(a)

for j in range(1,len(a)) :
key = a[j]
i = j-1
while i -1 and a[i]>key:
a[i+1] = a[i]
i = i-1
a[i+1] = key

print "\n sorted list"
printList(a)
Jul 30 '06 #2
I have a small problem with my function: printList. I use print with a
',' . Somehow the last digit of the last number isn't printed. I wonder
why.
Posting actual code might help...the code you sent has a horrible
mix of tabs and spaces. You've also got some craziness in your
"creating random list" string. First off, it looks like you're
using a docstring, but they only go immediately after the def
line. I'd recommend putting it where it belongs, or changing the
line to a comment.

There are some unpythonic bits in here:

printList() would usually just idiomatically be written as

print ' '.join(a)

although there are some int-to-string problems with that, so it
would be written as something like

print ' '.join([str(x) for x in listOfNumbers])

which is efficient, and avoids the possibility of off-by-one
errors when range(0,length) .

Another idiom would be the list-building of createRandomLis t:

return [random.randrang e(100) for x in xrange(0,length )]

Additionally, this can be reduced as range/xrange assume 0 as the
default starting point

return [random.randrang e(100) for x in xrange(length)]

(using xrange also avoids building an unneeded list, just to
throw it away)

Additionally, rather than rolling your own bubble-sort, you can
just make use of a list's sort() method:

a.sort()

Other items include sensibly naming your parameters rather than
generically calling them "param", just to reassign them to
another name inside.

Taking my suggestions into consideration, your original program
condenses to

############### ############### ##########

import random

def createRandomLis t(length):
return [random.randrang e(100) for x in xrange(length)]

def printList(listO fNumbers):
print ' '.join([str(x) for x in listOfNumbers])

if __name__ == "__main__":
length = 10
a = createRandomLis t(length)
printList(a)
a.sort()
print "sorted list"
printList(a)

############### ############### ##########

one might even change createRandomLis t to allow a little more
flexibility:

def createRandomLis t(length, maximum=100):
return [random.randrang e(maximum) for x in xrange(length)]
So it can be called as you already do, or you can specify the
maximum as well with

createRandomLis t(10, 42)

for future use when 100 doesn't cut it for you in all cases.

Just a few thoughts.

-tkc


Jul 30 '06 #3
Dennis Lee Bieber wrote:
for i in range(0,len(par am)):
print a[i],

for it in param:
print it,
That's one way. However, if you need the position (this is for future
reference; you don't need the position number here):

for i in range(len(param )+1):
print a[i],

The last position was excluded because you forgot the '+1' part,
creating an off-by-one bug.

Jul 31 '06 #4
Dustan wrote:
Dennis Lee Bieber wrote:
for i in range(0,len(par am)):
print a[i],

for it in param:
print it,

That's one way. However, if you need the position (this is for future
reference; you don't need the position number here):

for i in range(len(param )+1):
print a[i],

The last position was excluded because you forgot the '+1' part,
creating an off-by-one bug.
No, your code creates that bug.

However, the above is not very pythonic - if param is a iterator and not a
sequence-protocol-adherent object, it fails. The usual way to do it is
for i, a in enumerate(param ):
print a,
Diez
Jul 31 '06 #5

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

Similar topics

9
4953
by: Penn Markham | last post by:
Hello all, I am writing a script where I need to use the system() function to call htpasswd. I can do this just fine on the command line...works great (see attached file, test.php). When my webserver runs that part of the script (see attached file, snippet.php), though, it doesn't go through. I don't get an error message or anything...it just returns a "1" (whereas it should return a "0") as far as I can tell. I have read the PHP...
9
23498
by: ted | last post by:
I'm having trouble using the re module to remove empty lines in a file. Here's what I thought would work, but it doesn't: import re f = open("old_site/index.html") for line in f: line = re.sub(r'^\s+$|\n', '', line) print line
9
22168
by: Paul Watson | last post by:
I thought that using a comma at the end of a print statement would suppress printing of a newline. Am I misunderstanding this feature? How can I use print and not have a newline appended at the end? C:\src\projects\test1>python -c "import sys;print sys.version, 'running on', sys.platform" 2.3.4 (#53, May 25 2004, 21:17:02) running on win32 C:\src\projects\test1>python -c "print 'here'," >jjj
15
1889
by: Judi Keplar | last post by:
I am currently taking a course to learn Python and was looking for some help. I need to write a Python statement to print a comma- separated repetition of the word, "Spam", written 511 times ("Spam, Spam, … Spam"). Can anybody help me get started? I am completely new to programming! Thanks in advance!
9
3694
by: Ksenia Marasanova | last post by:
Hi, I have a little problem with encoding. Was hoping maybe anyone can help me to solve it. There is some amount of data in a database (PG) that must be inserted into Excel sheet and emailed. Nothing special, everything works. Except that non-ascii characters are not displayed properly. The data is stored as XML into a text field. When I use pgsql it's displayed good in the terminal. Now I run my script and print data
2
5125
by: jamesthiele.usenet | last post by:
I recently ran into the issue with 'print' were, as it says on the web page called "Python Gotchas" (http://www.ferg.org/projects/python_gotchas.html): The Python Language Reference Manual says, about the print statement, A "\n" character is written at the end, unless the print statement ends with a comma. What it doesn't say is that if the print statement does end with a
4
1500
by: Jeff Hamilton | last post by:
I want to copy the following data from field Owner to field PropertyOwner: Desired Result HAMILTON,JEFF JEFF HAMILTON JOHNSON, JIMMY JIMMY JOHNSON JONES, MARY & DAVID MARY & DAVID JONES SMITHSON INDUSTRIES SMITHSON INDUSTRIES GONZALES, TRUST GONZALEZ TRUST DAVIDIAN,TR DAVIDIAN TR CHO,TR ET AL CHO TR ET AL
9
1528
by: TY | last post by:
Hi all, I have this little simple script: for i in range(10): for j in range(5000000): pass # Timing-delay loop print i When you run it, it behaves as you would expect -- it prints 0 <pause> on the next line prints 1 <pause> on the next line prints 2 <pause>
1
5889
by: sigkill9 | last post by:
I'm new to Python and am trying to figure out how to streamline the code at bottom to get it more simple but am having trouble. I was hoping that someone here could help me out? The program I am trying to create simply asks the terminal operator for five different celsius temperatures, processes them into fahrenheit values and outputs them to the screen. The results should look something like this: This is a program that converts celsius...
0
8478
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8919
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8670
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7439
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6230
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5696
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4409
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2052
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1810
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.