Jump to content

Comma quibbling: Difference between revisions

→‎{{header|Python}}: Second example without the need to reverse a string.
(Complete Rust output for no input words)
(→‎{{header|Python}}: Second example without the need to reverse a string.)
Line 186:
 
=={{header|Python}}==
===replace() whilst reversed===
# replace(..) can only replace the first X occurrences not the last
# Hencehence the replace is done on the reverse of the intermediate string
# then reversed back.
<lang python>>>> def strcat(sequence):
return '{%s}' % ', '.join(sequence)[::-1].replace(',', 'dna ', 1)[::-1]
# replace(..) can only replace the first X occurrences not the last
# Hence the replace is done on the reverse of the intermediate string
# then reversed back.
return '{%s}' % ', '.join(sequence)[::-1].replace(',', 'dna ', 1)[::-1]
 
>>> for seq in ([], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]):
print('Input: %-24r -> Output: %r' % (seq, strcat(seq)))
 
Line 201 ⟶ 202:
Input: ['ABC', 'DEF', 'G', 'H'] -> Output: '{ABC, DEF, G and H}'
>>> </lang>
 
===Counted replacement===
replace() will replace nothing if the count of items to replace is zero, (and negative integer counts act to replace all occurrences).
This combines with the length of the input sequence to allow this to work:
<lang python>def commaQuibble(s):
return '{%s}' % ' and '.join(s).replace(' and ', ', ', len(s) - 2)
 
for seq in ([], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]):
print('Input: %-24r -> Output: %r' % (seq, commaQuibble(seq)))</lang>
 
{{out}}
<pre>Input: [] -> Output: '{}'
Input: ['ABC'] -> Output: '{ABC}'
Input: ['ABC', 'DEF'] -> Output: '{ABC and DEF}'
Input: ['ABC', 'DEF', 'G', 'H'] -> Output: '{ABC, DEF, G and H}'</pre>
 
=={{header|PL/I}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.