| |||||||||||
| |||||||||||
The fencepost problem
If you erect a fence of 10 panels, you'll need 11 fenceposts to hold it up. And if you write a program that joins together 10 elements on a line, you'll only need 9 separators between them - this is known as the "fencepost problem".
If you write a simple program loop to output each element from a list followed by a separator, you'll end with a spurious separator on the end of the line. Here's what I mean (in Python). posts = ["apple","banana","cherry"] which gives the result apple and banana and cherry and It would be possible - but long winded - to print out the connecting panel only for the second and subsequent posts: posts = ["apple","banana","cherry"] but surely there's a better way?? Yes - there is. In Python, the join method lets me connect a list of strings using another string as the glue between them. My example becomes: posts = ["kiwi","orange","pineapple"] which gives the result kiwi with orange with pineapple Link - full source code In Perl, the join function performs the same task: @salad = ("Cherry","Damson",Fig");With PHP, the function you'll use is implode: $salad = array("tangerine","pear","grape");(written 2006-01-10 03:03:12) Associated topics are indexed under Y108 - Python - String HandlingH107 - String Handling in PHP P208 - Perl - Lists
Some other Articles
Open Source training from Well House ConsultantsMerging pictures using PHP and GD Smoke and mirrors Python's Generator functions The fencepost problem ''I don't know'' is sometimes a good answer Converting between acres and hectares A new sign Colour doesn't have to mean colourful Hotel novelties 1638 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 at 50 posts per pageThis is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price. Link to Ezine home page (for reading). Link to Blogging home page (to add comments). |
| ||||||||||
PH: 01144 1225 708225 • FAX: 01144 1225 707126 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho | |||||||||||