Message Boards Message Boards

GROUPS:

[WSG20] Programming Fundamentals Week 1

Posted 7 months ago
5055 Views
|
58 Replies
|
51 Total Likes
|

During week 1 of Daily Wolfram Study Group, May 2020, we will be looking at the following topics:

  • Day 1: Working with Data
  • Day 2: Building Interfaces
  • Day 3: Functional Programming
  • Day 4: Tips for Writing Fast Code

We will look at lecture videos from the Wolfram U archives and also work on simple coding examples and mini projects.

Feel free to post questions on the material we cover in these sessions here.

58 Replies

Daily Challenge (May 4): A challenge in the spirit of "May the fourth be with you".

Chart the production budget against the release date of the Star Wars movies (from the WL EntityClass "StarWarsFranchise"). Which movie had the lowest production budget?

Posted 7 months ago

"Star Wars: The Clone Wars" 8.5 million USD

Posted 7 months ago

Please send the link of the study group to regster

POSTED BY: M al
Answer

You can register for study groups at https://www.wolfram.com/wolfram-u/special-event/study-groups/

For this week specifically: sign up here

Could you please post links to the quizzes mentioned in the session today. Thank you.

@Sviatoslav Archava could you please email wolfram-u@wolfram.com and we will send the link to you.

Hi Abrita,

Hope, I understood correctly the challenge.

My PieChart[]:

PieChart[EntityClass["Movie", "StarWarsFranchise"][
  EntityProperty["Movie", "ProductionBudget"]], 
 ChartLabels -> 
  Placed[EntityClass["Movie", "StarWarsFranchise"][
    EntityProperty["Movie", "ReleaseDate"]], "RadialCallout"]]

enter image description here

The movie with the lowest production budget:

In[2]:= data = EntityClass["Movie", "StarWarsFranchise"][{EntityProperty["Movie", "ProductionBudget"], EntityProperty["Movie", "ReleaseDate"]}]; Select[data, #[[1]] == Min[data[[All, 1]]] &][1]

Out[2]= {Quantity[8.5`6.*^6, "USDollars"], DateObject[{2008, 8, 15}, "Day", "Gregorian", 3.]}

Hi Valeriu, I had a DateListPlot in mind. But the fun of using the Wolfram Language is that there are so many ways of doing the same thing. And your chart highlights the information just as well. Thanks for sharing.

Sure, Abrita, with DateListPlot[] it's much more simpler:

DateListPlot[
 EntityClass["Movie", 
   "StarWarsFranchise"][{EntityProperty["Movie", "ReleaseDate"], 
   EntityProperty["Movie", "ProductionBudget"]}]]

enter image description here

Posted 7 months ago

I wanted to upload my Notebook, but I can't because I have to log in to my Wolfram Cloud account. I am logged in another tab in my browser, but I don't know how to link that to this group, can you help me please?

In the meantime, here is my code:

a = EntityClass["Movie", "StarWarsFranchise"]["Name"];

y = EntityClass["Movie", "StarWarsFranchise"]["ProductionBudget"]

x = EntityClass["Movie", "StarWarsFranchise"]["ReleaseDate"]

BarChart[y, ChartLabels -> Placed[{x, a}, {Before, After}], BarOrigin -> Left, AxesLabel -> {"Date of release", "Production budget [USD]"}]

Perfectly ok to copy paste code snippets. Notebook not needed.

Posted 7 months ago

Hi Abrita, where can I access to the weekly quizzes and videos of the session? Can you give me any page link?

You should receive the links in the daily reminder email for the webinars. If you are not receiving those emails kindly write to wolfram-u@wolfram.com.

A DateListPlot with labels added in:

movies = EntityClass["Movie", 
"StarWarsFranchise"][{EntityProperty["Movie", "ReleaseDate"], 
EntityProperty["Movie", "ProductionBudget"], "Name"}] // Sort;
least = SortBy[movies, #[[2]] &, Min] // First;
DateListPlot[
Callout[#[[{1, 2}]], #[[3]], Automatic, #[[1]], 
LeaderSize -> {15, 125 \[Degree], -10}] & /@ movies, 
PlotMarkers -> Automatic, ImageSize -> Full, 
Epilog :> 
Text["Lowest Budget", {DateList@least[[1]], 
QuantityMagnitude@least[[2]] - 1.5 10^7}, Background -> Green], 
PlotRange -> {{{1958, 1, 1}, Today}, {-3 10^7, Automatic}}, 
FrameLabel -> {{"Production Budget", None}, {"Release Dates", None}},
PlotLabel -> Style["Star Wars Movie Franchise", "Subsubsection"]]

enter image description here

Posted 7 months ago

An actual analysis or comparison of production costs should include the time value of money referenced to some date, otherwise the comparison is invalid... right?

Q: (I'm new to Wolfram curated datasets) Is there a document or notebook associated with each curated dataset that describes how the data was curated? And, like the "daily challenge" problem, how would we know if the money values are referenced to some year's dollars or are just the time value of money for the given date? Besides a document/notebook describing the curation process and source for datasets, it would be nice to have a separate document/notebook that describes the particulars of a given dataset (like how money values should be interpreted), etc.

POSTED BY: Dave M
Answer

Good point.

So the the entities are part of the continuously updated Wolfram Knowledgebase also used in Wolfram|Alpha. Here are some of the data sources used for the knowledgebase: https://reference.wolfram.com/language/ref/entity/Source.html

You'll find more information about each entity on its associated documentation page. For e.g. https://reference.wolfram.com/language/ref/entity/Movie.html. The curated data can be a result of pulling in information from multiple sources and the specifics of the curation process are not usually included.

Meanwhile for the datasets on the Wolfram Data Repository you will find the "Source Metadata" at the bottom of each data resource that gives you more detailed information.

Posted 7 months ago

Here is a class that can be used to get the inflation-adjusted values of production budget at a single valuation date so the resulting comparison is fair:

enter image description here

Now after extracting and massaging the data from this class it can be visualized and compared on a DateHistogram:

enter image description here

Here is a comparison using the value of the dollar, based on Today:

enter image description here

Here is a comparison using the value of the dollar at the time of the release of Mathematica:

enter image description here

My god, the dollar has lost 55% of its value in the past 31 years!

Daily Challenge (May 5): Make an interactive version of the visualization from the previous day that allows your reader to explore the data--select and compare various features against each other. (Explore a bit yourself and select a few meaningful properties for the list of choices you'd like to offer your reader; don't include ALL the entity properties of the Movie entity).

A simple snippet to get you started:

Manipulate[
 ImageResize[movie["Image"], Medium], 
 {movie, EntityList[EntityClass["Movie", "StarWarsFranchise"]]}]
Posted 7 months ago

Looking at the coding on this page for the daily challenge from yesterday, many of these things are far more advanced than what was covered in the first lecture yesterday. I think these long pieces of code can bamboozle people, it certainly does for me.

I feel like we went from fairly basic concepts to the multiple lines of code very quickly. For me there needs to be a bit more of a smooth transition.

Hi Colin, Yes - does seem like a lot of code. But this was also meant to be a fun challenge to encourage people to experiment. The simplest version of the solution would be what @Valeriu Ungureanu or @Regina Cervantes posted above:

DateListPlot[EntityClass["Movie", "StarWarsFranchise"]
  [{EntityProperty["Movie", "ReleaseDate"], 
   EntityProperty["Movie", "ProductionBudget"]}]]

For this week we are focusing on "Practical Programming" - things we feel many people would like to be able to use in day-to-day work - import data, visualize it, or build an interface to explore data. Maybe look at the code this week as a showcase of examples and then in the next three weeks we will pick up again with more fundamental aspects of programming in WL. Thanks.

Posted 7 months ago

I can make a collage of the leading actors of each movie.

Here's the code for ten actors (based on Abrita's code):

Manipulate[ ImageCollage[PersonData[movie["Cast"][[Range[10]]], "Image"]],

{movie, EntityList[EntityClass["Movie", "StarWarsFranchise"]]} ]

That results in:

StarWars-Episode1

Posted 7 months ago

A desktop version of the previous post:

Manipulate[
 Column[{Row[{Column[{Style["Release Title:", color], 
       EntityList[EntityClass["Movie", "StarWarsFranchise"]][[
        releaseNumber]]}], "  ",
     Column[{Style["Director:", color], 
       EntityList[EntityClass["Movie", "StarWarsFranchise"]][[
          releaseNumber]][EntityProperty["Movie", "Director"]][[1]]}],
      "   ",
     Column[{Style["Producer:", color], 
       EntityList[EntityClass["Movie", "StarWarsFranchise"]][[
          releaseNumber]][EntityProperty["Movie", "Producers"]][[1]]}],
     "   ",
     Column[{Style["Production Budgent:", color], 
       EntityClass["Movie", "StarWarsFranchise"][
         EntityProperty["Movie", "ProductionBudget"]][[
        releaseNumber]]}]}],
   Style["Cast and Roles:", color], 
   Grid@Partition[
     Column /@ 
      Transpose[{Keys[
         EntityList[EntityClass["Movie", "StarWarsFranchise"]][[
           releaseNumber]][EntityProperty["Movie", "CastAndRoles"]]], 
        First /@ 
         Values[EntityList[
             EntityClass["Movie", "StarWarsFranchise"]][[
            releaseNumber]][
           EntityProperty["Movie", "CastAndRoles"]]]}], 4]}],
 {releaseNumber, Range@10, ControlType -> Setter}, {releaseNumber, 
  Range@10, Slider}, {color, Purple}]

enter image description here

[WSG20] Programming Fundamentals Week 1

Attachments:

Hi! Is it possible to watch the earlier lessons from this week? Thanks, Garfield

Yes, absolutely. We'll send all the relevant links (to the videos and the download locations for the notebooks) in a consolidated email at the end of the week to all the registered attendees.

Daily Challenge (Day 3): Give "Pig Latin" a shot https://challenges.wolfram.com/challenge/pig-latin

We didn't get to patterns on Thrusday. We'll look at them tomorrow and then get back to the challenge.

Hi Abrita,

To initiate the challenge, let's start with the following code:

PigLatin[text_String] := 
 Block[{vowels = {"a", "e", "i", "o", "u"}, consonants},
  consonants = Complement[Alphabet[], vowels];
  consonants = Join[consonants, ToUpperCase@consonants];
  StringReplace[text,
   {
    x__ /; 
      StringMatchQ[x, 
       Flatten[{consonants, ToUpperCase@vowels}] .. ~~ vowels ~~ 
        LetterCharacter ...] :> 
     StringTake[x, StringPosition[x, vowels][[1, 1]] ;; -1] <> 
      StringTake[x, StringPosition[x, vowels][[1, 1]] - 1] <> "ay",
    x__ /; 
      StringMatchQ[x, 
       Flatten@{consonants, ToUpperCase[Alphabet[]]} ~~ 
        LetterCharacter ...] :> x,
    x__ /; StringMatchQ[x, vowels ~~ LetterCharacter ...] :> x <> "way"
    }
   ]
  ]
Posted 7 months ago

Hi Abrita,

Using RegularExpression rather than StringPattern.

This converts a single word

pigWord[word_String] := Which[
  ! StringContainsQ[word, RegularExpression["[aeiou]"]],
  word,
  StringMatchQ[word, RegularExpression["^[aeiou].*"]],
  word <> "way",
  True,
  StringReplace[word, RegularExpression["^([^aeiou]+)(.+)"] -> "$2$1ay"]]

To work with the sentence example with punctuation from the challenges page, we have to preserve the punctuation by calling pigWord on the consecutive word characters.

pigLatin[string_String] := StringReplace[string, w : RegularExpression["\\w+"] :> pigWord[w]]

Test cases

pigTests =
  <|
   "Or" -> "Or",
   "owl" -> "owlway",
   "string" -> "ingstray",
   "Aura" -> "uraAay",
   "Ochre" -> "eOchray",
   "or" -> "orway",
   "Agree" -> "eeAgray",
   "agree" -> "agreeway",
   "If the word contains no lowercase vowels, nothing is changed." ->
    "If ethay ordway ontainscay onay owercaselay owelsvay, othingnay isway angedchay.",
   "moves that collection of consonants to the end of the word" ->
    "ovesmay atthay ollectioncay ofway onsonantscay otay ethay endway ofway ethay ordway"
   |>;

Run the test cases

pigTests // KeyValueMap[pigLatin[#1] == #2 &] // FreeQ[False]
(* True *)
Posted 7 months ago

enter image description here

I feel like we are wrapping layer after layer, forming a snowball of code that I hope doesn't melt. This is "brakety" and "wrappery" hence I get lost in the brackets and can't visualize what is happening underneath very well. Having said that I find all this valuable and instructive!

Posted 7 months ago

Hi Aaron,

Languages that use a Lisp-like syntax (Lisp, Scheme, Racket, Clojure, WL, ...) suffer from "bracket/parenthesis hell". I find it hard to understand deeply nested expressions. Good formatting and indenting helps, but you still have to comprehend it from "inside out".

In WL you can use Postfix (//), Composition (@*), RightComposition (/*) and operator forms of functions to write expressions in a left to right order that I find easier to understand..

Consider: "Which of the first 100 prime numbers have digits whose sum is also prime?" Here is one way to answer it using infix notation

Select[Table[Prime[n], {n, 100}], PrimeQ[Total[IntegerDigits[#]]] &]

I find this to be much easier to understand

Table[Prime[n], {n, 100}] // Select[IntegerDigits /* Total /* PrimeQ]

From left to right I read this as "From the first 100 primes select those whose digits when totaled is prime".

Experiment with both styles and see what works best for you.

Posted 7 months ago

Abrita Here's my solution to the PigLatin challenge, It works on all of the sample words and sentences given in the challenge, but when I try and upload it too the Wolfram Challenge Web page it says it runs too slow, but on my machine the timing is all but instantaneous. Any hints on what I've done wrong would be appreciated. I've updated the code, which appears to work, but not on the Wolfram Challenge Web page

PigLatin[text_String] := Module[{s = text},

  vlclst = {"a", "e", "i", "o", "u"};
  vuclst = {"A", "E", "I", "O", "U"};
  lst = TextWords[s];

  StrngReorder[strRO_] := 
   StringTake[strRO, 1 - StringLength[strRO]] <> StringPart[strRO, 1];

  StrngStartConsonant[strSC_] := 
   StringFreeQ[StringPart[strSC, 1], vlclst, IgnoreCase -> True];

  StrngProcess4[str_] := Module[{sg = str},
    sg = StringTake[sg, 1 - StringLength[sg]] <> StringTake[sg, 1];
    NestWhile[StrngReorder[#] &, sg, StrngStartConsonant[#] &] <> "ay"
    ];

  StrngRule2[str2_] := 
   If[StringStartsQ[str2, vlclst], str2 <> "way", str2];

  StrngRule3[str3_] := If[StrngStartConsonant[str3],
    NestWhile[StrngReorder[#] &, str3, StrngStartConsonant[#] &] <> 
     "ay", str3];

  StrngRule4[str4_] := If[
    StringStartsQ[str4, vuclst] && 
     StringContainsQ[StringTake[str4, {2, StringLength[str4]}], 
      vlclst],
    StrngProcess4[str4], str4
    ];

  lst = StrngRule4 /@ StrngRule3 /@ StrngRule2 /@ lst;
  lstjoin = lst[[1]];
  Do[lstjoin = lstjoin <> " " <> lst[[i]], {i, 2, Length[lst]}];
  lstjoin

  ]
Posted 7 months ago

Hi Stuart,

There are a few cases that your solution does not handle correctly. If you take pigTests from my solution above and run your code against those tests there are three failures.

pigTests // 
 KeyValueMap[
  If[(r = PigLatin[#1]) == #2, True, Print["Expected: ", #2, " Got:", r]; False] &]

Expected: eOchray Got:Ochre

Expected: eeAgray Got:Agree

Expected: If ethay ordway ontainscay onay owercaselay owelsvay, othingnay isway angedchay. Got:If ethay ordway ontainscay onay owercaselay owelsvay othingnay isway angedchay

Thanks for the posts folks. We'll continue the discussion on the "Pig Latin" challenge here.

Follow the Wolfram Study Group discussions for "Programming Fundamentals Week 2" at https://community.wolfram.com/groups/-/m/t/1970834

A very unproductive way of doing this challenge but I am not familiar with If statements in Wolfram

Attachments:
Posted 7 months ago

Hi Yuliia,

Use pigTests from my answer above to test your solution.

pigTests // 
 KeyValueMap[If[(r = textpiglatin[#1]) == #2, True, Print["Expected: ", #2, " Got: ", r]; False] &]

Expected: If ethay ordway ontainscay onay owercaselay owelsvay, othingnay isway angedchay.

Got: If ethay ordway ontainscay onay owercaselay owels,vay othingnay isway anged.chay

It fails on the sentence with punctuation test.

Thank you. I fixed the code to account for punctuation and cleaned everything up a bit.

Attachments:

Thank you. I fixed the code to account for punctuation and cleaned everything up a bit.

Attachments:
Posted 7 months ago

My final attempt at the PigLatin challenge. The code is much improved since my last submission. It passes all of the tests on the specification, including preserving punctuation + Rohit NamJoshi's Test procedure. I haven't tried to submit to the challenge web page, but will do so later. Any comments welcome: Having never really had a need to process strings before, I found this to be a difficult task...

PigLatin[text_String] := Module[{s = text},

  vlclst = {"a", "e", "i", "o", "u"};
  vuclst = {"A", "E", "I", "O", "U"};
  punclist = {".", ",", ";", ":", "!"};
  lst = StringExtract[s, All];

  StrngReorder[strRO_] :=
   StringInsert[
    StringTake[strRO, 1 - StringLength[strRO]],
    StringPart[strRO, 1],
    If[StringEndsQ[strRO, punclist], -2, -1]
    ];

  StrngStartConsonant[strSC_] :=
   StringFreeQ[
    StringPart[strSC, 1],
    vlclst,
    IgnoreCase -> True
    ];

  StrngAddWay[strAW_] :=
   StringInsert[strAW,
    "way",
    If[StringEndsQ[strAW, punclist], -2, -1]
    ];

  StrngAddAy[strAY_] :=
   StringInsert[
    NestWhile[StrngReorder[#] &, strAY, StrngStartConsonant[#] &],
    "ay",
    If[StringEndsQ[strAY, punclist], -2, -1]
    ];

  StrngMoveFirstVowel[strFV_] :=
   StringInsert[
    StringTake[strFV, 1 - StringLength[strFV]],
    StringTake[strFV, 1],
    If[StringEndsQ[str, punclist], -2, -1]
    ];

  StrngAddAy2[strAY2_] := Module
    [{str = strAY2},
    str = StrngMoveFirstVowel[strAY2];
    StrngAddAy[str]
    ];

  StrngRule2[str2_] := If[
    StringStartsQ[str2, vlclst],
    StrngAddWay[str2],
    str2];

  StrngRule3[str3_] := If[
    StrngStartConsonant[str3],
    StrngAddAy[str3],
    str3];

  StrngRule4[str4_] := If[
    StringStartsQ[str4, vuclst] && 
     StringContainsQ[StringTake[str4, {2, StringLength[str4]}], 
      vlclst],
    StrngAddAy2[str4],
    str4
    ];

  lst = StrngRule4 /@ StrngRule3 /@ StrngRule2 /@ lst;

  StringRiffle[lst]
  ]

Can we download the notebooks in this series? If so where can we find the links too the notebooks?

Can we download the notebooks in this series? If so where can we find the links too the notebooks?

HI Charles, Links to notebook downloads have been shared with registered participants. If you haven't already, please feel free to sign up at https://wolfr.am/MRRR3lFC

Thanks

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

Group Abstract Group Abstract