Jump to content

Scripters &/or programmers here ?


Recommended Posts

There's no need to write your own capitalization functions, they already exist. They're also much more efficient than how you write these.

 

Secondly, if you want to write your own, you need to do them efficiently. This means not writing an insane amount of for loops for something you can do in just a few lines of code. If you wanted to do a brute force character replacement, you don't need to interact with strings. Just add or subtract the Unicode value of the character in question (the distance between lower and upper cases is 32). So you just need to loop through the characters, check if it's within a certain range, and then adjust it based on whatever it's supposed to be doing.

 

I don't understand the motivation to switch things to ~² before switching them to what they actually need to be. It seems like you're literally doubling the runtime of your program for no good reason, and it's already magnitudes larger than what it needs to be, considering you're running hundreds of for loops when you only need to run one.

 

For example:

 

ASCIITable.jpg

 

If I want lower case characters, then I loop through my string (ONCE), check if the character value is between 0041 and 0060 (in hex, which is 65 and 96 respectively). If it is, add 32. (Likewise, you can figure out how to do it backwards). The same goes for these accented sections, they're the same distance. You may have to do a little digging to figure out how to actually accomplish this in VB. I can't help, because I don't use VB.

 

I also don't recommend using VB for anything. It's quite honestly a horrible language, especially for scripting. Use something like Python or JavaScript, it's much easier to do pretty much anything than in VB.

 

I'm sorry if I'm being harsh, but it would benefit you to take a free course on programming or utilized other kinds of free resources for learning. There are plenty, like Coursera, Udacity, CodeAcademy, Khan Academy, etc.

 

Here's some examples in Python:

import os, sys# Capitalize all files in current directoryfor f in os.listdir(sys.path):    os.rename(f, f.uppercase)# De-Capitalize all files in current directoryfor f in os.listdir(sys.path):    os.rename(f, f.lowercase)# Replace all underscores with spacesfor f in os.listdir(sys.path):    os.rename(f, f.replace('_', ' '))# Make treefout = open('Tree.txt', 'w')for root, dirs, files in os.walk(sys.path):    for f in files:        fout.write(root + '\n')        fout.write('\t' + f + '\n')    fout.write('\n')
Link to comment
Share on other sites

Hey thanks for the reply. I'll check your script a little later cause I'm heading to work but quickly here's what I need to precise;

 


    I don't understand the motivation to switch things to ~² before switching them to what they actually need to be.
  I also don't recommend using VB for anything. It's quite honestly a horrible language, especially for scripting. U

 

I switch to ~2 but it could be anything else. The point is that you cannot rename ABC.jpg to abc.jpg because it will make an error and stop right there, saying the filename already exists.

 

Cannot use anything else than VB/PowerShell/Batch on the computer at work because everything is blocked. I cannot install anything ;( but I'll check Python for sure. I know C a little tho

Link to comment
Share on other sites

I switch to ~2 but it could be anything else. The point is that you cannot rename ABC.jpg to abc.jpg because it will make an error and stop right there, saying the filename already exists.

I don't really follow, unless this is a VB thing where file names are not case-sensitive and thus you are unable to directly change the case of the letters in the filename.

 

If that is correct, then you should move away from VB immediately. It is not a language designed for scripting and automation. Your code takes several orders of magnitudes longer to do tasks that are actually kind of trivial. Here's why.

 

Let's say I want to run a capitalization, your way. Let's say there are 26 characters (just for example) that are eligible for capitalization. Let's say we want to run this on 500 files. Each name is 32 characters long.

 

By your method, we create 52 for loops that iterate over every filename, replacing each instance of the substring character with a dummy character, then changing the dummy to the correct character. Note that this is bounded above by 52 * 500 * 32 (find-and-replaces) = 832000 loop iterations. If we increase it to 64 eligible characters, and say, work with a large number of files (like samples) such as 20,000, it becomes 81,920,000 loop iterations. That's wasteful, and also kind of gross (pun intended) from an analytic standpoint, since your runtime grows directly proportional to two separate independent variables.

 

By a more efficient method, we write a nested for loop. One to loop through the files, one inside to loop through their names. Now we're simply upper bounded by the number of files and how long their names are (which makes more intuitive sense). For every character we encounter, we check if it's Unicode value is in a specific range (to see if it needs to be capitalized), then subtract 32 from its value to make it a capital letter.

 

Now we're bounded in loop iterations to (note how the number of characters that will be capitalized has 0 effect on the computation time):

26 eligible capital characters: 500 * 32 = 16,000 (vs. 832,000)

64 eligible capital characters: 20,000 * 32 = 640,000 (vs. 81,920,000)

 

That's a 98% and 99.2% reduction respectively in loop iterations. In other words, your code takes ~50 times longer in the first case and ~125 times longer in the second than it needs to do the operations. What's more is that this new method isn't really limited to a simple repetitive copy and pasted procedure. You can add more conditions for what ranges of characters should be treated how, right inside the body of the one loop. Your code is now also maintainable. If you want to add or change something, you do it once, not 200 times.

Link to comment
Share on other sites

I'll try to find how to update the code with your method and do a compare test because I just did a test with 4200 "àäâabcdèêëéfghiìîïjklmnoôöòpqrstuùüûvwxyz" .txt files and it indeed took a good amount of time (about 3 minutes & 10 seconds) on my old computer (6000+ AMD). I'll give your suggestion more thought a little later this week when I get a chance.

Link to comment
Share on other sites

If you can learn C, I really think that would be better. Python is very finicky about tabbing, so if you're not an organized person, I would say, opt for C. For example:

for i in range(0, 3):    print ("Hola")    if i == 2:        print ("We have an even number")    else:        print ("This number is odd")

starts giving you errors if it looks like this:

for i in range(0, 3):    print ("Hola")if i == 2:    print ("We have an even number")    else:    print ("This number is odd")

If you write it in C, you write:

for (int i = 0; i < 3; i++){    cout << "Hola" << endl;    if(i == 2){         cout << "We have an even number" << endl;    }    else {         cout << "This number is odd" << endl;    }}

which, if it looks like this (which is horrendously bad tabbing)

for (int i = 0; i < 3; i++){    cout << "Hola" << endl;         if(i == 2){cout << "We have an even number" << endl;}    else {    cout << "This number is odd" << endl;         }}

there is no error. Just my two cents.

 

Plus, I know for sure that C is case-sensitive, so there is no need to change to ~^2 when going from a to A, for example. You can work with ASCII values like Neblix suggested, or you could even use the functions isupper or islower to check for capitalizations (granted, Python has that too, but that's not the point).

Link to comment
Share on other sites

If you can learn C, I really think that would be better. Python is very finicky about tabbing, so if you're not an organized person, I would say, opt for C. For example:

for i in range(0, 3):    print ("Hola")    if i == 2:        print ("We have an even number")    else:        print ("This number is odd")

starts giving you errors if it looks like this:

for i in range(0, 3):    print ("Hola")if i == 2:    print ("We have an even number")    else:    print ("This number is odd")

If you write it in C, you write:

for (int i = 0; i < 3; i++){    cout << "Hola" << endl;    if(i == 2){         cout << "We have an even number" << endl;    }    else {         cout << "This number is odd" << endl;    }}

which, if it looks like this (which is horrendously bad tabbing)

for (int i = 0; i < 3; i++){    cout << "Hola" << endl;         if(i == 2){cout << "We have an even number" << endl;}    else {    cout << "This number is odd" << endl;         }}

there is no error. Just my two cents.

 

Plus, I know for sure that C is case-sensitive, so there is no need to change to ~^2 when going from a to A, for example. You can work with ASCII values like Neblix suggested, or you could even use the functions isupper or islower to check for capitalizations (granted, Python has that too, but that's not the point).

 

C is not a scripting language. You need to compile C programs, and that's incredibly inconvenient if you do scripting on a regular basis. Recommending C for scripting is a bad recommendation.

JavaScript doesn't have whitespace termination, so if you want to write bad code and still have it work, you can use JS no problem. There's no need to resort to low-level compiled languages for tasks like file organization.

Link to comment
Share on other sites

My C is super basic so it wasn't hard to be "organized" here, but this is the perfect example where a repetition of the IFs could be avoided. It repeats until I get a result between 50 to 200 bpm for 1 to 20kHz. Is it simple to include a repetition until that condition is met, inside that "while", with what you posted above ? Is it simpler in Python ?

 

#include <stdio.h>#include <stdlib.h>int main(int argc, char *argv[]){ double A, B, C; A = 15; printf("Tool to find the tempo in phase with the period of a frequency \n\n");  while(1)  {   printf("Hz: ");   scanf("%lf", &;   C = A/(1/B);   if(C<50) C=2*C;   if(C>200) C=C/2;   if(C<50) C=2*C;   if(C>200) C=C/2;   if(C<50) C=2*C;   if(C>200) C=C/2;   if(C<50) C=2*C;   if(C>200) C=C/2;   if(C<50) C=2*C;   if(C>200) C=C/2;   if(C<50) C=2*C;   if(C>200) C=C/2;   if(C<50) C=2*C;   if(C>200) C=C/2;   if(C<50) C=2*C;   if(C>200) C=C/2;   if(C<50) C=2*C;   if(C>200) C=C/2;   if(C<50) C=2*C;   if(C>200) C=C/2;   if(C<50) C=2*C;   if(C>200) C=C/2;   printf("BPM = %.10f \n\n",C);  } getch(); return 0;}
Link to comment
Share on other sites

Ideally, if there is a condition you know of that would let you narrow the range in which you guess, that would make this simpler. For example, let's say you wanted the computer to guess what number you have just typed in, but without taking in the input and spitting that out as the output. You could write it so that if your guess is not right, but is above a certain floor, raise the floor by assigning the floor the value of the guess. If the guess is not right, but is below a certain ceiling, lower the ceiling by assigning the ceiling the value of the guess. Each time the guess is wrong, the guessing range narrows.

 

I think you can analogize off of the code below; instead of using the condition "is this guess equal to myNumber?", replace it with the condition that fits your need.

 

I wrote this one in C++, but I think you can understand it with the annotations I put (and C++ can import C libraries anyhow, meaning that you can incorporate C syntax as well as the newer C++ syntax):

#include <iostream> // standard, necessary library for C++#include <cstdlib> // referenced to use rand() functionusing namespace std;int main(){    /* Task: There exists a number "myNumber" in the domain ("floor", "ceiling").    The computer will guess using variable "guess", lowering "ceiling" if    "guess" is too high, and raising "floor" if "guess" is too low. */    srand(time(NULL)); // initialize randomizer seed    int guess, myNumber, ceiling, floor; // Note that rand() only works with ints, but you get the intent    cout << "Enter your number: " << endl;    cin >> myNumber; // ask for input    ceiling = 200;    floor = 50;    guess = rand() % ceiling + floor; // initialize the guess      while(guess != myNumber){        if((guess > myNumber) && (guess < ceiling)){ // If the guess happens to be in the domain (myNumber, ceiling)            ceiling = guess;            cout << "My guess was " << guess << ", which was above your number. Lowering ceiling to " << ceiling << endl;        }        else if((guess < myNumber) && (guess > floor)){ // If the guess happens to be in the domain (floor, myNumber)            floor = guess;            cout << "My guess was " << guess << ", which was below your number. Raising floor to " << floor << endl;        }        else if(myNumber < floor){            cout << "Your number is too low. Sorry!" << endl;            break; // get out of loop        }        guess = rand() % ceiling + floor; // make guess for as long as the guess is incorrect    }    if(guess == myNumber){        cout << "Your number must be " << guess << "!" << endl;    }}

Personally, I haven't used a while loop in a long time because you have to know all the conditions of your situation so you can give a condition in which it makes sense to escape the while loop; otherwise your code will continue to run until your computer slows down. Alternatively, if you want to simply increment little by little through a range, you could also try a for loop:

#include <iostream> // standard, necessary library for C++#include <cstdlib> // referenced to use rand() functionusing namespace std;int main(){    double guess, myNumber, ceiling, floor;    cout << "Your number is: " << endl;    cin >> myNumber;    ceiling = 200;    floor = 50;    for(guess = floor; guess < ceiling; guess += 1){    // for as long as the guess is                                                        // within the domain [floor, ceiling),                                                        // keep increasing by 1        cout << "My current guess for your number is: " << guess << endl;        if(guess == myNumber){            cout << "AHA! Your number is " << myNumber << endl;            break; // get out of loop once number is determined        }    }}

Does that help? If you understand the logic, I think you can translate it back to your language of choice.

Link to comment
Share on other sites

Timaeus, your code isn't relevant to the task he's trying to perform. Additionally, your program makes no sense and isn't really applicable as a teaching tool since it does a task no one would ever actually do (give a computer a number and then have it randomly try to guess the number... when it already has it).

 

Here is a cleaner one, Metal Man:

#include <stdio.h>#include <stdlib.h>int main(int argc, char *argv[]) {    double A = 15, B, C;    const int MIN = 50, MAX = 200;    printf("Tool to find the tempo in phase with the period of a frequency \n\n");    printf("Hz: ");    scanf("%lf", &;      C = A*B;    while(C < MIN || MAX < C)        C = (C<MIN)?(C*2):(C/2);    printf("BPM = %.10f \n\n",C);        getch();    return 0;}

The golden rule in programming is Don't Repeat Yourself. This shouldn't be violated when designing software architecture, and it certainly should not be violated to the point where you write literally the same code over and over again immediately on the next line. Anything that should be repeated can be solved with either conditional loops, count-controlled loops, or recursion.

 

I've here used a conditional loop ("is C not where I want it to be?") and a looped action to act on that condition. The action is to set C equal to C * 2 if it is less than 50, and C / 2 if it is not. Since the loop condition is already predicated on the fact that when you are inside the loop, C is either less than 50 or more than 200, than the simple assumption you can make is that C NOT being less than 50 means it IS greater than 200.

 

If this is hard to grasp, I do recommend you take a course on programming, or contact me privately I can teach you programming concepts. This forum isn't really the place to learn programming.

Link to comment
Share on other sites

Timaeus, your code isn't relevant to the task he's trying to perform. Additionally, your program makes no sense and isn't really applicable as a teaching tool since it does a task no one would ever actually do (give a computer a number and then have it randomly try to guess the number... when it already has it).

 

I used it merely to illustrate the principle of updating the range of your guess so that you get a better guess each time. It wasn't so important, IMO, what the actual code was, but the logic behind it that makes it more efficient than lots of repetitive if conditionals in a row. Once you understand the logic, it's easier to write the code on your own rather than modifying from templates.

 

Also, sidenote... it was an actual practice problem in the python text I used three years ago, just so you know. I didn't just think up something that was oddly redundant.

Link to comment
Share on other sites

Some really bad advice in this thread, guys.

 

If you can learn C, I really think that would be better. Python is very finicky about tabbing, so if you're not an organized person, I would say, opt for C.

 

 

C is a horrible first language in modern times. There are many, MANY, reasons that I won't get into unless someone really cares (Metal Man, the reasons will doubtless confuse you, so if Timaeus and I do have that debate, feel free to skip over it). Back in the early 80's or so, there wasn't the variety of choices in languages that we have now, so C would've been one of the reasonable choices. We've advanced a lot since then, though, so there's no reason to start with a language that doesn't have garbage collection, that exposes pointers, that doesn't have a native string type, etc) Saying, "but Python uses tabs to enforce structure" is the kind of complaint that is usually heard either from someone who doesn't know how to code well or from someone who is so stuck in the "but it should always be done this way" mentality that they're obstinately resistant to change. If someone is so unorganized that they can't handle the structure of a programming language, whether it's enforced by whitespace or specified with braces, they will have immense difficulty programming period and probably want to do something else.

 

Yes, Python *does* enforce structure through whitespace. This isn't a bad thing, and as someone who's been coding since 1993 (versions of Basic that pre-date Windows, even, let alone VB), coding in C since somewhere around 1995/1996, has two computer science degrees, and my day job is writing a COBOL compiler in C++, I wholly endorse Python as a language and, if it were possible, would be more than happy never to use C++ again. I've done a few smaller projects in Python too, so I'm not just speculating here. Python is easier to learn and it's easier to develop code that "just works" in Python than in C++. Plus, some whitespace errors are things that the Python interpreter will flag as syntax errors, and using whitespace for structure has the benefit of making all Python code equally easy to read on any machine.

 

Here's an example. You know how in many games, there's a crafting component? An Iron Sword is made from 3 Iron Bars, and an Iron Bar is made from three Iron Ores, and you gather Iron Ores by mining? Well, I wrote a general-purpose tool in C a few years ago that would take a list of items and recipes and tell you what you needed to gather to craft them, without having to do the math yourself. It would read in a file of all the items in the game (so I could, for example, see immediately where in the game I'd go to mine Iron Ores), and another file with all the recipes, and by "checking off" stuff in the master file (using (x) beside an item, instead of ( ), so the file *looks* like a checklist), I could limit which items I wanted to get information for. So, if I said I wanted to craft an Iron Sword, it would tell me to gather 9 Iron Ores, and use them to craft 3 Iron Bars, and use the bars to craft one Iron Sword.

 

I'm playing Final Fantasy XIV now, which has an official website from Square Enix that has all the game's crafting recipes on the website itself. I wrote a Python script to pull the entire crafting database from the website and format it into files usable by my C tool. This was only the second piece of Python code I'd written, and it took less time to write than the C code and had fewer bugs, despite the fact that the Python code had to parse the same files as the C code did AND parse three different formats of webpages (FF XIV has 8 crafting professions and groups recipes by every 5 levels of skill in the profession, so Level 1-Level 5 Carpentry, so for each profession, I had to get the URLs for each level, then for each level I had to load that page to get the list of recipes, and then parse the page for each recipe to get the items used to make it).

 

C is powerful and has its place, but it is not easy.

 

 

 

C is not a scripting language. You need to compile C programs, and that's incredibly inconvenient if you do scripting on a regular basis. Recommending C for scripting is a bad recommendation.

JavaScript doesn't have whitespace termination, so if you want to write bad code and still have it work, you can use JS no problem. There's no need to resort to low-level compiled languages for tasks like file organization.

 

If a tool is the right one for the job, compiling isn't a big deal. Every language has some quirks and some types of overhead. Compiling isn't a big deal, especially for smaller projects. In a decent IDE, compiling and running a program is a single keystroke anyway, so it's no worse than running your scripted program in an interpreter.

 

 

 

Personally, I haven't used a while loop in a long time because you have to know all the conditions of your situation so you can give a condition in which it makes sense to escape the while loop; otherwise your code will continue to run until your computer slows down.

 

That's a horrible reason not to use while loops. In ANY loop, you need to know what your exit conditions are. For loops make it a bit more obvious (you're generally adding one to a number and stopping at a known limit), but the first thing to do when writing any loop is figure out how and when the loop will exit.

 

 

 

Timaeus, your code isn't relevant to the task he's trying to perform. Additionally, your program makes no sense and isn't really applicable as a teaching tool since it does a task no one would ever actually do (give a computer a number and then have it randomly try to guess the number... when it already has it).

 

Here is a cleaner one, Metal Man:

#include <stdio.h>#include <stdlib.h>int main(int argc, char *argv[]) {    double A = 15, B, C;    const int MIN = 50, MAX = 200;    printf("Tool to find the tempo in phase with the period of a frequency \n\n");    printf("Hz: ");    scanf("%lf", &;      C = A*B;    while(C < MIN || MAX < C)        C = (C<MIN)?(C*2):(C/2);    printf("BPM = %.10f \n\n",C);        getch();    return 0;}

The golden rule in programming is Don't Repeat Yourself. This shouldn't be violated when designing software architecture, and it certainly should not be violated to the point where you write literally the same code over and over again immediately on the next line. Anything that should be repeated can be solved with either conditional loops, count-controlled loops, or recursion.

 

I've here used a conditional loop ("is C not where I want it to be?") and a looped action to act on that condition. The action is to set C equal to C * 2 if it is less than 50, and C / 2 if it is not. Since the loop condition is already predicated on the fact that when you are inside the loop, C is either less than 50 or more than 200, than the simple assumption you can make is that C NOT being less than 50 means it IS greater than 200.

 

If this is hard to grasp, I do recommend you take a course on programming, or contact me privately I can teach you programming concepts. This forum isn't really the place to learn programming.

 

 

Timaeus' example isn't really irrelevant, at least not any more so than any other toy program to teach something about programming. It doesn't matter if the code is relevant or useful or not; what matters is how you use it. Neblix's example is easier to understand, though, and is better-written code.

 

Metal Man, the one thing in which Neblix and Timaeus are both right is that your code isn't very good. You're a beginner, so that's expected, and you know that you won't learn without trying, but I *do* agree with the recommendations that you find an "intro to programming" course online; there'll be all kinds of stuff you can do for free. I do strongly recommend you do it in Python though.

Link to comment
Share on other sites

1. If a tool is the right one for the job, compiling isn't a big deal. Every language has some quirks and some types of overhead. Compiling isn't a big deal, especially for smaller projects. In a decent IDE, compiling and running a program is a single keystroke anyway, so it's no worse than running your scripted program in an interpreter.

 

2. Timaeus' example isn't really irrelevant, at least not any more so than any other toy program to teach something about programming. It doesn't matter if the code is relevant or useful or not; what matters is how you use it.

 

1. I specifically am talking about this task, in the context of file system scripting. The tool for this job is not C. The tool for this job is rarely C; the use of C is motivated by the need for low-level functionality and/or the in-line assembly stuff. Doing file scripting in low-level functionalities is not only a pain in the ass, it takes longer to write more advanced scripts and it affords a level of control you don't really need if you're literally just renaming files or printing directory lists. If you're scripting, using a scripting language is 9 times out of 10 more appropriate. But I think you agreed with this in your anecdotes.

 

2. In my experience teaching beginner's programming (quite a great many years), irrelevant tasks confuse beginners more than they help. That's because on top of learning the logic of how the program does its task, there's the compounded need to understand why that logic is necessary (because it's what the program is trying to do, the motivation for which is non-intuitive). I understand you may have gotten the example from a text, Timaeus, but texts are written by people, and a great many people can be bad at programming, bad at teaching, and also bad at both. (Usually just bad at teaching).

 

Offering relevant examples isn't that much harder than irrelevant ones, and it makes learning easier for the... learnee? You get the point. :P

 

 

I used it merely to illustrate the principle of updating the range of your guess so that you get a better guess each time. It wasn't so important, IMO, what the actual code was, but the logic behind it that makes it more efficient than lots of repetitive if conditionals in a row. Once you understand the logic, it's easier to write the code on your own rather than modifying from templates.

Yes, but he's not trying to guess a number nor does he need to update a range of values to guess in. He's simply trying to double or halve C until it is within the range he wants (which is a static range that does not update). It's akin to shortening a name until it can fit into something.

Link to comment
Share on other sites

 

1. I specifically am talking about this task, in the context of file system scripting. The tool for this job is not C. The tool for this job is rarely C; the use of C is motivated by the need for low-level functionality and/or the in-line assembly stuff. Doing file scripting in low-level functionalities is not only a pain in the ass, it takes longer to write more advanced scripts and it affords a level of control you don't really need if you're literally just renaming files or printing directory lists. If you're scripting, using a scripting language is 9 times out of 10 more appropriate. But I think you agreed with this in your anecdotes.

 
Yeah, C isn't a good language to use for file-system scripting. I'd usually recommend Unix shell scripts for that (if you're on a Linux or Mac system), or even Windows batch files if what you're doing is too complicated. Python or other similar languages are fine too as long as you're not trying to run a lot of command-line-level commands that Python doesn't have alternatives for. If all you're doing is moving files around, then sure, use Python; if you're trying to do the equivalent of a series of Unix commands, just use the Unix commands!

I was more trying to point out that the fact that C code must be compiled isn't really relevant to its suitability for a particular task. Unless the delivery mechanism is overly complex or there's some other important complicating factor (for example, running an interpreter or virtual machine on an embedded system may be too inefficient, because embedded systems often have very limited RAM and processing capabilities, etc.), then whether a program is compiled or interpreted or compiled to bytecode and run in a VM is usually not a relevant factor in whether to use that language or not.

 
 

 

2. In my experience teaching beginner's programming (quite a great many years), irrelevant tasks confuse beginners more than they help. That's because on top of learning the logic of how the program does its task, there's the compounded need to understand why that logic is necessary (because it's what the program is trying to do, the motivation for which is non-intuitive). I understand you may have gotten the example from a text, Timaeus, but texts are written by people, and a great many people can be bad at programming, bad at teaching, and also bad at both. (Usually just bad at teaching).

 

Offering relevant examples isn't that much harder than irrelevant ones, and it makes learning easier for the... learnee? You get the point.  :P

 

 

Relevance is extremely subjective, though. Sure, no one would write a program to feed a guess into the computer and have the computer guess that number. (I've seen similar examples where the computer has a random number and the human has to guess it, and the computer says 'higher' or 'lower' until you get it right; that at least is believable). But the problem with teaching programming is that virtually nothing you would ever write in, say, an introductory programming course is going to be in any useful in the real world to a wide variety of people. How many people need to find a tempo in phase with anything? Teaching programming is all about finding examples for people to learn the concepts so that when they come up against real-world things they want to automate, they understand how to do it. The only way you'd have a really relevant learn-to-program course is if it was targeted at a specific audience (e.g. "Learn to program C++ and eventually write your own VSTs") or if the whole course is building up a large project *and* the learner is smart enough to adapt the concepts as they learn them. For example, I've seen a book that has you build up a database-driven website as you learn to code; a smart person could take that and build up their own database-driven website without making the exact website that the book tells you to do. I'm still not sure how that would get you around the basics of learning loops or functions or other elementary topics, though; I'd imagine it'd be hard, even in that context, to say, "Here's a loop we're writing that's going to be important in the big picture of the project but is also able to stand alone and not rely on things that you don't yet understand".

Link to comment
Share on other sites

Offering relevant examples isn't that much harder than irrelevant ones, and it makes learning easier for the... learnee? You get the point. :P

I don't personally think it was irrelevant. The discussion was about loops and efficiency, and the guessing game is a classic example of such, using something similar to a binary search algorithm. The connection could have been made more explicit, though.

I also wouldn't say you'd "never" have a situation like this. First, again, it's very similar to a basic search algorithm; the logic is near-identical when you have a nonlinear but sorted data structure of some sort. Second, with encapsulation, sometimes one part of a program literally does not have access to data stored in another part, and has to go about learning it in an indirect method. I run into this sort of thing using APIs pretty frequently.

Most examples in beginners' textbooks are indeed pretty useless in and of themselves. But they can teach concepts that can be used for other things.

Link to comment
Share on other sites

Teaching programming is all about finding examples for people to learn the concepts so that when they come up against real-world things they want to automate, they understand how to do it.

 

[...]

 

or if the whole course is building up a large project *and* the learner is smart enough to adapt the concepts as they learn them.

 

Just wanted to agree with this and provide my take on what I ended up finding useful in my C++ programming class and applying to my quantum chemistry programming research:

 

- Abstract Data Types (Classes, Structs, Public/Private variables, header files)

- Arrays (declared in structs and dynamically allocated)

- Pointers (such as for implementation of CBLAS and LAPACKE libraries)

- Selective For loops (such as taking advantage of orbital point-group symmetry and class [core/active/virtual] or choosing only nonzero electron integrals and electron densities)

- Functions (of course)

- Other miscellaneous things

 

Honestly, the specific functions I had to know how to write in that class weren't nearly as important as the concepts that I got out of it. I found some of the more memorable functions to be, "is this number prime?" (literally 5 lines or so), "alphabetize this", "check the balance of parentheses" (stacks and linked lists), and "find the largest/smallest number in this list", yet I didn't use any of them specifically. The most useful unit though was the last two or three months on Abstract Data Types, IMO, and that "large project" was an ADT calculator (nightmare to program with linked lists, stacks, command line input, and such; was pretty satisfied in the end though).

 

Fun stuff. :)

Link to comment
Share on other sites

@Kanthos We're already in mutual agreement about what C is for, I don't see the need to continue harping on this point.

 

No one is suggesting to offer audio-related examples, nor is anyone attempting to design an intro to programming course. But regardless of whether useless examples are effective or not, creating examples analogous to real situations is possible, easy, and just takes some thought. It doesn't need to be complicated.

 

Here's a small one. You type in a score from 0 to 100, and the program must spit out your letter grade. Simple, but within the parameters of real life, and something people actually do without the assistance of computers. That also makes it incredibly easy to debug, and incredibly easy to show how to break when you write the conditionals incorrectly. That's because the student already entered the program with the foreknowledge of understanding how to solve the problem using simple mental steps. He doesn't have to learn the constraints of the problem itself along with learning how to solve it. That kind of stuff can come later, when he's at the point where he knows how boolean logic works, how to make the computer do things by making decisions is controlling flow through loops and whatnot.

# retrieve input, put into variable called 'score'. I'll stop at C/70 to be brief.if score >= 90:    print 'You got an A!'elif score >= 80:    print 'You got a B!'elif score >= 70:    print 'You got a C!'# This is intuitive enough, but the problem with this is when we write it differently:if score >= 70:    print 'You got a C!'elif score >= 80:    print 'You got a B!'elif score >= 90:    print 'You got an A!'# This seems the same to a beginner, but it's actually way wrong, because the structure terminates at the first condition when the score is 90.if score >= 70 and score < 80:    print 'You got a C!'elif score >= 80 and score < 90:    print 'You got a B!'elif score >= 90:    print 'You got an A!'# This has the same order as the incorrect one, but now demonstrates how conditions can be made more specific using compound boolean logic.if score < 80 and score >= 70:    print 'You got a C!'elif score < 90 and score >= 80:    print 'You got a B!'elif score >= 90:    print 'You got an A!'# Now we just simply reversed the order of the boolean conditions, and all of the sudden we can now talk about short circuit evaluation.

That's a lot of concepts demonstrated by doing variations on something real world and simple. When the first example is run, the student gets a result he was looking for. When the second is, he immediately just knows it's wrong, without someone telling him it is or being arbitrarily specified in a textbook problem. I can keep going for days if you want me to, for as introductory or advanced programming concepts as you want (advanced within my knowledge).

 

The reason why Timaeus's example was ill-placed is because first of all, you explain conditional loops before count-controlled loops, because count-controlled loops are special conditional loops (also his conclusion that while loops are somehow inconvenient because of having to know exit conditions is really bad advice and demonstrates poor understanding of a really simple concept and general lack of programming experience).

 

Secondly, a conditional loop was appropriate for the kind of task Metal Man was looking for. He presented repetitive conditional code, and asked "how does this work within the logic of a loop?" And well, first step of teaching someone effectively is answering their question, not dodging it and pulling code from a textbook.  :<

 

All again, why I said this forum is not the place to learn programming. Too many different backgrounds and not a standard level of rigor for all the people allowed to post. I'm not even sure this thread is relevant to this particular forum anyway.

Link to comment
Share on other sites

The reason why Timaeus's example was ill-placed

 

[...]

 

Secondly, a conditional loop was appropriate for the kind of task Metal Man was looking for. He presented repetitive conditional code, and asked "how does this work within the logic of a loop?" And well, first step of teaching someone effectively is answering their question, not dodging it and pulling code from a textbook.  :<

 

Why are we still talking about me? I'm pretty sure you smashed your keyboard through the desk typing my name over and over again. :lol: Move on?

Link to comment
Share on other sites

The reason why Timaeus's example was ill-placed is because first of all, you explain conditional loops before count-controlled loops, because count-controlled loops are special conditional loops (also his conclusion that while loops are somehow inconvenient because of having to know exit conditions is really bad advice and demonstrates poor understanding of a really simple concept and general lack of programming experience).

 

Secondly, a conditional loop was appropriate for the kind of task Metal Man was looking for. He presented repetitive conditional code, and asked "how does this work within the logic of a loop?" And well, first step of teaching someone effectively is answering their question, not dodging it and pulling code from a textbook.  :<

 

All again, why I said this forum is not the place to learn programming. Too many different backgrounds and not a standard level of rigor for all the people allowed to post. I'm not even sure this thread is relevant to this particular forum anyway.

 

 

I don't know; while people here have different skill levels, there are enough people with adequate skill to call out anything unreasonable. All you really need to learn from other people is knowledgeable people who will take the time to help you learn.

Link to comment
Share on other sites

I don't know; while people here have different skill levels, there are enough people with adequate skill to call out anything unreasonable. All you really need to learn from other people is knowledgeable people who will take the time to help you learn.

 

I personally disagree. In my time tutoring people who have trouble in Intro Programming (and other subjects), the issues often stem from an application of "little knowledge is worse than no knowledge at all". In other words, their professors and/or classmates explain things to them in ways that don't agree with their personal level of understanding, and their brains get sidetracked trying to reconcile the explanations they've received with what I'm trying to tell them (rather than simply learn the concepts fresh). I then first have to dismantle the things they thought they have learned before reteaching (then I send them off and they get A's or whatever).

 

A poor explanation of something can in fact damage your ability to learn it, even if someone offers something complete and correct after the fact. This is true in a lot of disciplines (I have seen this personally when helping people with not just programming, but also math, physics, martial arts, and music). It's the reason why we have a saturation of mediocre people who can write decent programs (and even more who write awful ones), but not a lot of people who truly "get it".

Link to comment
Share on other sites

  • 3 weeks later...

Hey I made a backup tool, nothing crazy but works well. I learned a few things. Try it (save it to a .VBS)

'PresentationstrMessage = "This backup tool will ensure an integral copy of your files. It will re-copy a file from scratch if any error happens, like between networks for instance." & vbCrLf & "" & vbCrLf & "You will finda report in the backup-ed folder: ""Backup Log (date & time).log""" & vbCrLf & "" & vbCrLf & "Note:" & vbCrLf & "this tool will copy the CONTENT of the folder to backup."Msgbox strMessage, 64, "Backup tool (Frederic Petitpas - 2015)"'Choosing the backup source, without the "new folder" optionSet objShell1 = CreateObject("Shell.Application")Set objFolder1 = objShell1.BrowseForFolder(0, "Choose the folder to backup", &h201, "\")If objFolder1 Is Nothing ThenWscript.QuitEnd If'Choosing the destination, with "new folder" option (by default)Set objShell2 = CreateObject("Shell.Application")Set objFolder2 = objShell2.BrowseForFolder(0, "Choose backup folder", 1, "\")If objFolder2 Is Nothing ThenWscript.QuitEnd If'RécapitulationstrMessage = "Content of the following folder:" & vbCrLf & """" & objFolder1.title & """" & vbCrLf & "found at:" & vbCrLf & objFolder1.self.path & vbCrLf & vbCrLf & "WILL BE BACKED-UP TO" & vbCrLf & vbCrLf &"the following folder:" & vbCrLf & """" & objFolder2.title & """" & vbCrLf & "found at:" & vbCrLf & objFolder2.self.pathMsgbox strMessage, 64, "Backup tool (Frederic Petitpas - 2015)"'ConfirmationIf MsgBox("To start the backup, click OK.", vbOkCancel or vbDefaultButton2, "Confirm") = vbCancel ThenMsgBox "Backup cancelled."WScript.quit()ElseEnd If'Writing the batchDim objShellSet objShell = WScript.CreateObject( "WScript.Shell" )Set wsc = WScript.CreateObject("WScript.Shell")Dim objFSO, outFileSet objFSO = CreateObject("Scripting.FileSystemObject")'Open write streamSet outFile = objFSO.CreateTextFile(wsc.SpecialFolders("desktop") & "\TmpBckpCmdFile.bat", True)'writeoutFile.WriteLine "@echo off"outFile.WriteLine "color 70"outFile.WriteLine "set x=" & objFolder1.self.pathoutFile.WriteLine "set y=" & objFolder2.self.pathoutFile.WriteLine "cls"outFile.WriteLine "echo Don't close, wait for the backup to finish..."outFile.WriteLine "Robocopy ""%x%"" ""%y%"" /E /XA:SH /XJD /R:8 /W:15 /MT:32 /V /NP /LOG:""%y%\Backup Log %date% (%time:~0,2%h%time:~3,2%m%time:~6,2%s).log"""outFile.WriteLine "(goto) 2>nul & del ""%~f0"""'close write streamoutFile.Close'Run the file and wait for completionSet shl = CreateObject("Wscript.Shell")file = shl.SpecialFolders("desktop") & "\TmpBckpCmdFile.bat"shl.Run file, 1, true'ConfirmationstrMessage = "Backup done!"Msgbox strMessage, 64, "Backup tool (Frederic Petitpas - 2015)"
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...