# [WSG20] Programming Fundamentals Week 3

Posted 1 year ago
10102 Views
|
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
Sort By:
Posted 1 year ago
 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] 
Posted 1 year ago
 This should be helpful: Making definitions for functions The ordering of definitions at the tech note on "Transformation Rules and Definitions"
Posted 1 year ago
 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]."]]
Posted 1 year ago
 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]} 
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.
Posted 1 year ago
 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!"; 
Posted 1 year ago
 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"]] 
Posted 1 year ago
 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.
Posted 1 year ago
 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?
Posted 1 year ago
 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
 Quiz1PROBLEM 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}]
Posted 1 year ago
 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], " = "}] 
Posted 1 year ago
 Hi Lori,Instead of ToString[#] ~~ "." & you can use N to convert integers to real. N /@ Range[Length[someFractions]] 
Posted 1 year ago
 Rohit,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, IncP.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.
Posted 1 year ago
 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
Posted 1 year ago
 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[#] <> "." & 
Posted 1 year ago
 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 FindFile["ExampleData/elements.xls"] (* "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 purposehttp://reference.wolfram.com/language/ref/ExampleData.html
Posted 1 year ago
 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 http://life.nthu.edu.tw/~fmhsu/rasframe/SHAPELY.HTM 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] 
Posted 1 year ago
 Hi Abrita,Amino does not have a color for "I" which appears in the sequence.
Posted 1 year ago
 Right _ I just caught that too. Will add it.
Posted 1 year ago
 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]] 
Posted 1 year ago
 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"]|>; ClearAll[colorResidues]; Options[colorResidues] = {ColorScheme -> Amino}; colorResidues[sequence_, opts : OptionsPattern[{colorResidues, Framed}]] := sequence // Characters // Map[Framed[#, Background -> OptionValue[ColorScheme][#], FilterRules[{opts}, Options[Framed]]] &] // Row muc6 = StringTake[ProteinData["MUC6", "Sequence"], 75]; colorResidues[muc6] Options for Framed can be provided colorResidues[muc6, FrameStyle -> None]  colorResidues[muc6, FrameStyle -> None, RoundingRadius -> 4]  colorResidues[muc6, FrameStyle -> {Thin, Blue, Dotted}, RoundingRadius -> 4, ImageMargins -> 2] Use a random ColorScheme colorResidues[muc6, FrameStyle -> None, ColorScheme -> (Amino /. _RGBColor :> RandomColor[] // Map[Evaluate])] 
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[]] := Row@Map[Framed[#, Background -> If[OptionValue[ColorScheme] === None, None, OptionValue[ColorScheme][#]], FrameStyle -> None, FrameMargins -> OptionValue[FrameMargins]] &, Characters[seq]] Options[ColorResidues] = {ColorScheme -> None, FrameMargins -> 1}  ColorResidues[StringTake[protein, 50], ColorScheme -> Amino, FrameMargins -> 5] 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]] 
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 issueTo 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.
Posted 1 year ago
 We've tried to fix this on our end. Let us know if you continue to see issues.
Posted 1 year ago
 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.
Posted 1 year ago
 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.