Message Boards Message Boards


[WSG20] Programming Fundamentals Week 3

Posted 1 year ago
39 Replies
36 Total Likes

This week we will be looking at the following topics:

  • Monday May 18: Defining Functions - Part I
  • Tuesday May 19: Defining Functions - Part II
  • Wednesday May 20: Evaluation Control
  • Thursday May 21: Entities and Weekly Review Session
  • Friday May 22: No study group (Day off at Wolfram)

Please post your questions on this thread and look out for daily challenges.

39 Replies

Would you post links to documentation on overloading functions and remembering calculated values? The code I captured looks like


This should be helpful:

  • Making definitions for functions
  • The ordering of definitions

at the tech note on "Transformation Rules and Definitions"

May 18 & 19 Challenge (Topic: Defining Your Own Functions)

Define a function poly that takes an integer, and makes a picture of an orange regular polygon with that number of sides.

Extra credit:

Modify your function to accept a second argument (and ensure its an RGBColor) to set the color of the regular polygon.

Posted 1 year ago

RGB Colour Only: poly[nsidesInteger, xRGBColor : Black] := Block[{[ScriptCapitalR]}, [ScriptCapitalR] = RegularPolygon[nsides]; Graphics[{x, [ScriptCapitalR]}]]

Any Colour (e.g CMYK etc.): poly[xInteger, y__?ColorQ /; Length[{y}] <= 1] := Which[ x > 2 && y === {}, Graphics[{GrayLevel[0], RegularPolygon[x]}], x > 2, Graphics[{y, RegularPolygon[x]}], True, Print["Function arguments should be of the form: [Integer>2] or \ [Integer>2,Colour]."]]

The extra credit is somewhat unclear, so let us begin with this code:

poly[n_Integer /; n >= 3, c_RGBColor : RGBColor[1, 0.5, 0]] := 
 Graphics[Style[RegularPolygon[n], c]]
poly[___] := " Enter an integer \[GreaterEqual] 3 "

Function applications:

{poly[3, Red], poly[7]}

enter image description here

Posted 1 year ago

That's clear and concise code :)

I didn't realise there is RegularPolygon function in Wolfram language, so here's a bit longer way to do the same with trigonometric approach:

poly[n_Integer/;n>2]:=Graphics[{Orange,Polygon[Table[{Cos[2 Pi k/n],Sin[2Pi k/n]},{k,1,n}]]}]

and with the extra color argument:

poly[n_Integer/;n>2, c_RGBColor:RGBColor[1, 0.5, 0] ]:=Graphics[{c,Polygon[Table[{Cos[2 Pi k/n],Sin[2Pi k/n]},{k,1,n}]]}]
Posted 1 year ago
Posted 1 year ago
Posted 1 year ago

Had some difficulties using FilterOptions directly with Polygon, since an empty option list will be interpreted as the indexing form of polygon definition. So I had to use an index list as second argument and FilterRules as third argument.

Hello, all! Nothing fancy, just the straight dope with an error message if necessary.

poly[n_] /; If[TrueQ[n >= 3], True, Message[poly::badint, n]; False] := Graphics[{Darker@Orange, RegularPolygon[n]}]

poly::badint = 
  "OOPS! The integer `1` should be greater than 2. TRY AGAIN!";

enter image description here

poly::badarg = "Your number should be an integer bigger than 2";
poly[n_?IntegerQ /; n > 2] := 
 Show[Graphics[{Orange, RegularPolygon[Evaluate[n]]}], 
  PlotLabel -> 
   StringJoin["Your polygon with ", ToString[n], " sides"], 
  LabelStyle -> {GrayLevel[0], 20}]
poly[___] := Message[poly::badarg]

poly[Input["Please input a positive integer >2"]]

An example of evaluation

Is Wolfram Alpha Notebook Edition supposed to be adequate for the programming you're discussing?

I get "No Wolfram Language translation found" when I try to define a function with a name longer than one character.

I need to know if this is how Wolfram Alpha Notebook Edition is supposed to be, or if there's something wrong with my copy of it.

Hi Thomas,

Our recommendation for this particular Wolfram Study Group on Programming Fundamentals would be to use Wolfram One. It would be best-suited for the topics we are covering in this series.

Posted 1 year ago

What is the link to the exercises for this week?

Will be handed out tomorrow during the study group session and will also be included in the end-of-the-week email with links to all the notebooks, recordings and Q&A transcripts.

Posted 1 year ago


PROBLEM 6 Which of the following will create a popup menu to allow the user to choose from among theoptions {“Sine”,“Cosine”,“Tangent”} to select the function for the plot?





None of them work correctly! Your example uses [OpenCurlyDoubleQuote] vs "!

This causes the error: Manipulate[Plot[f[x], {x, 0, 2*Pi}], {{f, Sin}, {Sin -> CurlyDoubleQuote[Sine], Cos -> \ CurlyDoubleQuote[Cosine], Tan -> CurlyDoubleQuote[Tangent]}, ControlType -> PopupMenu}]

in the PopupMenu in the Manipulate panel..

This works:

Manipulate[Plot[f[x], {x, 0, 2 Pi}], {f, {Sin -> Sine, Cos -> Cosine, Tan -> Tangent}, ControlType -> PopupMenu}]

Using Defer to leave expressions unevaluated for a quick quiz. Code is spelled out so the process is obvious:

someFractions := Table[r, {r, 1/10, 9/10, 1/20}]
   Row[{Defer[#1 + #2], " = "}] &, {RandomSample[someFractions], 

enter image description here

BUT regular Thread with Grid is aligned more neatly:

Grid@Thread[{RandomSample[someFractions], " + ", 
   RandomSample[someFractions], " = "}]

enter image description here


Grid@Thread[{ToString[#] ~~ "." & /@ Range[Length[someFractions]], 
   RandomSample[someFractions], " + ", RandomSample[someFractions], 
   " = "}]

enter image description here

Hi Lori,

Instead of

ToString[#] ~~ "." &

you can use N to convert integers to real.

N /@ Range[Length[someFractions]]


What happened to us just inspiring each other with our creativity?!?! When you answer questions that haven’t been asked you steal the joy of figuring things out. It is also condescending to assume that another person hasn’t already found that particular solution and just decided not to post it here. When you do it to a WOMAN, it’s called MANSPLAINING. Don’t do it, no matter how much you are itching to ‘solve’ someone else’s perceived problems, DO NOT DO IT unless you have been invited.

So, let’s go back to where we just feed on each others’ ideas and forget it ever happened.

Cheers, Lori Johnson, CEO Mathhead Tutoring, Inc

P.S. I teach everything from fractions to number theory and beyond, and students aged two-and-one-half years to 60+, so, yes, I meant to have fractions in that code.

Hi Lori,

I certainly did not intend to offend you in any way. If I did, I sincerely apologize.

However, I think you misunderstood my response, which has nothing to do with fractions. I was just showing an alternative way of generating the row numbers (1., 2., ...) for the numbered version of the Grid.

There are usually many ways to solve a problem in WL. If I know of a different way, I usually share that. If you look the history of my responses on this site you will see many examples of this. I also really appreciate it when someone responds to one of my posts with an alternative solution. It is a great learning experience for me.

Regards, Rohit

Hi Rohit, I welcome your suggestions. And certainly wouldn’t take offense at any tips being offered. Keep them coming. Great training material by the way, Ian

Posted 1 year ago

Instead of StringExpression

ToString[#] ~~ "." &

use StringJoin to concatenate string fragments.

ToString[#] <> "." &

Hi, Does anyone know how mathematica find their "example data?" For example: Import["ExampleData/elements.xls"] This gives me an element table but suppose I want an earlier version of the element table this is not what I want.. Also is there any database for those examples?

Posted 1 year ago

ExampleData is a file archive in the Mathematica installation layout


(* "C:\Program Files\Wolfram Research\Mathematica\12.1\Documentation\English\System\ ExampleData\elements.xls" *)

ExampleData is also a curated data function with the same name but serving a slightly different purpose

Last challenge for this week: From Paul Wellin's "Essentials of Programming in Mathematica"

Create a function ColorResidues[seq] that takes an amino acid sequence seq and returns a visualization like that below where the amino acids are colored according to a scheme such as Amino, where more polar residues are brighter and more nonpolar residues are colored darker. In addition to a color scheme option add options to control the frame around each residue.

enter image description here

enter image description here

Note: Changing Amino to an Association. I think that will work better. Also for reference, I got the colors from

Amino = <|"D" -> RGBColor["#E60A0A"],
  "E" -> RGBColor["#E60A0A"],
  "C" -> RGBColor["#E6E600"],
  "M" -> RGBColor["#E6E600"],
  "K" -> RGBColor["#145AFF"],
  "R" -> RGBColor["#145AFF"],
  "S" -> RGBColor["#FA9600"],
  "T" -> RGBColor["#FA9600"],
  "F" -> RGBColor["#3232AA"],
  "Y" -> RGBColor["#3232AA"],
  "N" -> RGBColor["#00DCDC"],
  "Q" ->  RGBColor["#00DCDC"],
  "G" -> RGBColor["#EBEBEB"],
  "I" -> RGBColor["#0F820F"], 
  "L" -> RGBColor["#0F820F"],
  "V" -> RGBColor["#0F820F"],
  "A" -> RGBColor["#C8C8C8"],
  "W" -> RGBColor["#B45AB4"],
  "H" -> RGBColor["#8282D2"],
   "P" -> RGBColor["#DC9682"]|>

muc6 = StringTake[ProteinData["MUC6", "Sequence"], 75]

Hi Abrita,

Amino does not have a color for "I" which appears in the sequence.

Right _ I just caught that too. Will add it.

Here's something very basic we could start with (no options and no error-handling at all):

ColorResidues[seq_String] := 
 With[{aa = Characters[seq]}, 
  Row[Panel[#, Background -> Amino[#]] & /@ aa]]
Amino = <|"D" -> RGBColor["#E60A0A"], "E" -> RGBColor["#E60A0A"], 
   "C" -> RGBColor["#E6E600"], "M" -> RGBColor["#E6E600"], 
   "K" -> RGBColor["#145AFF"], "R" -> RGBColor["#145AFF"], 
   "S" -> RGBColor["#FA9600"], "T" -> RGBColor["#FA9600"], 
   "F" -> RGBColor["#3232AA"], "Y" -> RGBColor["#3232AA"], 
   "N" -> RGBColor["#00DCDC"], "Q" -> RGBColor["#00DCDC"], 
   "G" -> RGBColor["#EBEBEB"], "I" -> RGBColor["#0F820F"], 
   "L" -> RGBColor["#0F820F"], "V" -> RGBColor["#0F820F"], 
   "A" -> RGBColor["#C8C8C8"], "W" -> RGBColor["#B45AB4"], 
   "H" -> RGBColor["#8282D2"], "P" -> RGBColor["#DC9682"]|>;

Options[colorResidues] = {ColorScheme -> Amino};

colorResidues[sequence_, opts : OptionsPattern[{colorResidues, Framed}]] :=
  sequence // Characters //
       Background -> OptionValue[ColorScheme][#],
       FilterRules[{opts}, Options[Framed]]] &] //

muc6 = StringTake[ProteinData["MUC6", "Sequence"], 75];


enter image description here

Options for Framed can be provided

colorResidues[muc6, FrameStyle -> None]

enter image description here

colorResidues[muc6, FrameStyle -> None, RoundingRadius -> 4]

enter image description here

colorResidues[muc6, FrameStyle -> {Thin, Blue, Dotted},
  RoundingRadius -> 4, ImageMargins -> 2]

enter image description here

Use a random ColorScheme

colorResidues[muc6, FrameStyle -> None, 
 ColorScheme -> (Amino /. _RGBColor :> RandomColor[] // Map[Evaluate])]

enter image description here

Posted 1 year ago

The function works after a fashion but am slightly confused about how spacing works in graphics row.To make matters worse, I seem to be able to select and drag the image to achieve whatever spacing I desire. Perhaps you can advise on what is lacking. colorResidue[proteinSeqNameString, seqStartPosInteger, seqEndPosInteger, spacingInteger, colSchemeList /; MatchQ[colScheme, {Rule[String, _?ColorQ] ..}]] := GraphicsRow[ Characters[ StringTake[ ProteinData[ToUpperCase[proteinSeqName], "Sequence"], {seqStartPos, seqEndPos}]] /. x_String :> Style[Framed[x, FrameStyle -> {Black, Thick}], ColorNegate[x /. colScheme], Background -> x /. colScheme] , Spacings -> spacing]

Posted 1 year ago
ColorResidues[seq_String, OptionsPattern[]] := 
Background -> 
If[OptionValue[ColorScheme] === None, None, 
OptionValue[ColorScheme][#]], FrameStyle -> None, 
FrameMargins -> OptionValue[FrameMargins]] &, Characters[seq]]

Options[ColorResidues] = {ColorScheme -> None, FrameMargins -> 1}

enter image description here

ColorResidues[StringTake[protein, 50], ColorScheme -> Amino, 
FrameMargins -> 5]

enter image description here

Color scheme in this format works also with bar chart:

    aminoCounts = protein // Characters // Counts // KeySort;
BarChart[KeyValueMap[Style[#2, Amino[#1]] &,  aminoCounts], 
 ChartLabels -> Keys[aminoCounts]]

enter image description here

Posted 1 year ago

Hi folks - I just did Quiz 3 there and noticed that there were issues in selecting certain answers. Particularly in being able to choose answer a. for Problem 3. I could select b, c or d without any problems but when trying to select a. the cursor changes to the font edit cursor and thus does not allow clicking of the button.

I tried in Chrome and in Firefox and both had the same issue

To get around this, I clicked "Make Your Own Copy" of the Quiz and then in that was able to edit the problem questions in that file. All I had to do was hit return between the question text and the answers, then answer a. was able to be selected again normally.

I saw someone mentioned this the other day during one of the lectures, so this is a workaround if anyone is experiencing this same issue. Also, I guess the Wolfram staff could edit the master so as to avoid this issue? I believe Problems 2, 3 and 9 have the same issue and in all three cases it's because the answers are too close to the question text.

We've tried to fix this on our end. Let us know if you continue to see issues.

For May 18 & 19 Challenge:

A slightly different approach. You can select the number of sides n via a slider. The default color is Orange, RGBColor[1,0.65,0]. A different color can be chosen via the color slider.

c = RGBColor[1, 0.65, 0];
c -> Dynamic[c];
Manipulate[Graphics[Style[RegularPolygon[n], c]], {n, 3, 20, 1}, 
 Column[{ColorSlider[Dynamic[c]]}], LocalizeVariables -> False]

After playing with numbers and colors, the number of sides and the RGBColor can be extracted.

n // InputForm
ColorConvert[{c}, "RGB"] // InputForm
Posted 1 year ago

Hi, I was wondering when and where we can find the exercises that we should complete to get the Level I certification. I thought we would receive an email, but so far I haven't gotten anything. Deadline of June 5th is coming up fast.

The June 5th deadline is for the four quizzes that you must complete for the Certificate of Program Completion.

We have not yet sent out the link to the exercises that need to be completed for the Level I certification. You will have at least two weeks to complete the exercises.

Posted 1 year ago

Okay. Thanks for the clarification. I thought the 5th was for both. Again, great webinar. I learned a lot.

Dear Wolfram Study Group,

I'm trying to solve the auto-graded tasks for the Wolfram Technology Certified Level 1 Certificate and I guess there are technical issues with some of them. Task 1.4 asks for random strings so my solution (being random) does not match the expected output. I am quite sure that my code is correct. Can I maybe send it to you somehow (in order to not reveal solutions I did not post it here in the forum)? The same problem occures with task 1.8 (the spheres are randomly positioned). Suprisingly, my solution, despite not matching the expected output, is marked as correct for task 1.7 which also involves randomness. For task 1.11 I get the expected output on my local machine using Mathematica 11 but the exact same code throws many errors like "GenomeData::notent : 381 is not a known entity, class, or tag for GenomeData. Use GenomeData[] for a list of entities." when executed in the online notebook. For task 1.13, my code executes in the cloud notebook, yielding the expected output (or at least output which is visually not distinguishable from it), but is still marked as incorrect. The same seems to happen for task 1.14 (altough I can not compare the images by hand), 1.15., 1.18 and 1.20. What should I do? Can I maybe send you my solutions in my own notebook?

Best regards

Yorick Zeschke

Sorry for asking again, I found the discussion in the other thread.

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract