[WSG20] Programming Fundamentals Week 3

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.

3 Likes

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

fib[0]:=1
fib[1]:=1
fib[x_]:=fib[x]=fib[x-1]+fib[x-2]

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.

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]}

4 Likes
2 Likes

That’s clear and concise code :slight_smile:

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}]]}]
2 Likes
4 Likes

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.

2 Likes

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!";

1 Like

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

Any Colour (e.g CMYK etc.):
poly[x_Integer, 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].”]]

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"]]

3 Likes

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.

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.

Quiz1

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?

Manipulate[Plot[f[x],{x,0,2Pi}],{f,{Sine,Cosine,Tangent},ControlTypePopupMenu}]

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

Manipulate[Plot[f[x],{x,0,2Pi}],{f,{Sin“Sine”,Cos“Cosine”,Tan“Tangent”}}]

Manipulate[Plot[f[x],{x,0,2Pi}],{f,{Sine,Cosine,Tangent}}]

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}]
Print@Column@
  MapThread[
   Row[{Defer[#1 + #2], " = "}] &, {RandomSample[someFractions], 
    RandomSample[someFractions]}]

BUT regular Thread with Grid is aligned more neatly:

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

NUMBERED:

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

3 Likes

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?

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.

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

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]