Difference between revisions of "Python:Accumulate with Various Operations"

From Progzoo
Jump to: navigation, search
(List it nicely)
Line 135: Line 135:
 
<answer>
 
<answer>
 
def f(list):
 
def f(list):
   sep = ","
+
   sep = ""
 
   acc = "f("
 
   acc = "f("
 
   for v in list:
 
   for v in list:
 
     acc = acc+sep+v
 
     acc = acc+sep+v
 +
    sep = ","
 
   return acc+")"
 
   return acc+")"
 
</answer>
 
</answer>
 
</question>
 
</question>
 
{{Accumulator Tutorial}}
 
{{Accumulator Tutorial}}

Revision as of 17:07, 12 July 2017

Using an Accumulator


Concatenate

Concatenate the string array

Concatenate means stick the strings together.


[Font] [Default] [Show] [Resize] [History] [Profile]

List it

Put commas in front of each element.

Change the line to

acc = acc+","+v;


[Font] [Default] [Show] [Resize] [History] [Profile]

Concatenate with brackets

Concatenate the string array - put angle brackets around each item:

 f({"a","b","c","d"})  -> <a><b><c><d>
 f({"x","y"})          -> <x><y>
 f({"yes","but","no"}) -> <yes><but><no>


[Font] [Default] [Show] [Resize] [History] [Profile]

Reverse Concatenate

Concatenate the string array, backwards


[Font] [Default] [Show] [Resize] [History] [Profile]

Front and back

Palindrome it

f({"a","b","c","d"}) ->dcbaabcd                 
f({"x","y"})         ->yxxy                     
f({"yes","but","no"})->nobutyesyesbutno  


[Font] [Default] [Show] [Resize] [History] [Profile]

List it nicely

Put commas between the elements of the string array

  • Notice that the separator sep has is "=" for the first iteration, therafter it will always be "#".
  • The "-" is added in the return statement.
  • Replace "=", "#" and "-" with appropriate strings.


[Font] [Default] [Show] [Resize] [History] [Profile]