As was foretold, we've added advertisements to the forums! If you have questions, or if you encounter any bugs, please visit this thread: https://forums.penny-arcade.com/discussion/240191/forum-advertisement-faq-and-reports-thread/
Options

The beginner programming thread

145791063

Posts

  • Options
    jarekjarek Registered User regular
    edited November 2007
    Janin wrote: »
    Since I'm talking about C (there are better ways to do loops in C++), the variable must be declared outside the for loop.

    Actually the 1999 revision of the standard (aka C99) made it acceptable to declare variables within the for statement (so "for(int i = 0; i < n; i++)" is ok). But wherever you put the variable declaration, that sort of a loop is enough of an idiom that anyone seeing it would know exactly what it's supposed to do; the same can't be said for the "while (i --> 0)" trick.

    [So count me as another vote for "Please don't do that if anyone else has to look at your code."]

    jarek on
  • Options
    LewishamLewisham Registered User regular
    edited November 2007
    Jragghen wrote: »
    So the most recent reply made me curious (because I see Whitesmith's Style so rarely) - what Indent style do you guys prefer, and why do you prefer it? I use Allman style, but mostly because that's how I was originally taught it, and it stuck via intertia. I just find it much simpler to read.

    Allman 4 lyfe.

    In the end, they're all fine, but some people who use K&R are also prone to doing silly crap like:

    if (somethingreallyimportant){
    if (blah){
    // A WHOLE BUNCH OF CODE
    } elsif (shtishitshit) {
    }
    }

    Because they think that indenting all of it is unnecessary because it's such a large block it looks ugly. I usually have to go through and convert it all to Allman to have any idea where the control flow goes. I could put it into properly K&R indentation, but if I'm going to do that, I may as well spend the time making it exactly as I like.

    Whenever I see someone who uses Allman, they don't take stupid shortcuts like that. I think it must be the way different people's brains work.

    Lewisham on
  • Options
    EtheaEthea Registered User regular
    edited November 2007
    I used to use K&R while in University. but over the last eight months, I have moved Whitesmith for a couple reasons. One I do allot of python coding at work and it has become very natural for everything to be indented. Also because the rest of my c++ code right now is part of a project whose coding standard require it. For awhile I tried to just run the code through a cleaner before I committed, but I have slowly changed.

    Ethea on
  • Options
    JaninJanin Registered User regular
    edited November 2007
    Mostly like Allman, except:
    • I put a space before function parameters, around operators, and wherever else I feel one might be useful - the e-trees are plentiful.
    • I mix tabs and spaces regularly. In my opinion, tabs are for indentation, and spaces are for alignment. This allows the tab size to be set to any value without destroying the alignment.

    In this screenshots, tabs are yellow, alignment spaces are green:
    highlightingng9.png

    Janin on
    [SIGPIC][/SIGPIC]
  • Options
    JasconiusJasconius sword criminal mad onlineRegistered User regular
    edited November 2007
    Visual Studio formats my code for me.


    It's pretty nice.

    Jasconius on
  • Options
    ASimPersonASimPerson Cold... and hard.Registered User regular
    edited November 2007
    Janin wrote: »
    Perhaps it's just me, but I find the first and third loops cleaner to read than the second. By moving the decrement operator over, the arrow formed makes it obvious that "count" is being decremented to 0.

    I think it is just you. Every time I see a "->" I think it's dereferencing an object and confuses the hell out of me, even though I know it's low on the order of operations. I think it's terrible style.

    And speaking of style, OTBS for life. To quote Linus Torvalds: "[A]ll right-thinking people know that (a) K&R are _right_ and (b) K&R are right."

    ASimPerson on
  • Options
    LoneIgadzraLoneIgadzra Registered User regular
    edited November 2007
    ASimPerson wrote: »
    And speaking of style, OTBS for life. To quote Linus Torvalds: "[A]ll right-thinking people know that (a) K&R are _right_ and (b) K&R are right."

    Wow, I never realized there were names for these conventions. I sort of always just did what felt the best, with the general leaning that more whitespace and logical separation = more readable code, so I prefer to put an opening bracket on its own line, unless it's something really obvious and I'd rather save space. K&R usually just seems so cramped to me.

    Also, I like things symmetrical, and the trailing bracket not lining up with the opening bracket always bugs the shit out of me. Makes the whole thing seem top heavy.

    LoneIgadzra on
  • Options
    ZackSchillingZackSchilling Registered User regular
    edited November 2007
    So I have a question. I'm using the Microsoft Speech Library to do speech recognition in a C# program. I created a wrapper class for the speech stuff, so this question doesn't involve the specifics of that.

    The wrapper class has event handlers in it, so when a recognized word shows up on the mic, an event triggers and it invokes a little piece of code that I wrote inside the class. This is all well and good, but I'd really like the wrapper class to invoke an event in the main program, not just in its own code. I assume the easiest way to do this is to give the class its own outgoing event thing and invoke it from the existing incoming event handler. I'm a super-beginner at C# so most of what I do is based on knowledge of programming concepts and the little intellisense menu in Visual Studio. Can someone give me a rundown of how to do this whole delegate/event thing in a custom class that's not inherited from anything?

    All the tutorials I find online are hard to follow for me. They're more concerned with good programming practice than showing the bare-bones concept. Thanks in advance.

    (I could post the code, but it's complex and not really helpful. I'm really looking for some generic, basic stuff.)

    ZackSchilling on
    ghost-robot.jpg
  • Options
    jothkijothki Registered User regular
    edited November 2007
    Whatever they may be, I hate conventions that allow single-line code inside an if statement to not be enclosed in brackets. It's slightly less clear and has a chance to screw you up if you need to add in more lines later.

    In general, if I'm going to be modifying someone else's code I need to go through the sections I'm using first and add a bunch of newlines, tabs and brackets.

    jothki on
  • Options
    LoneIgadzraLoneIgadzra Registered User regular
    edited November 2007
    So I have a question. I'm using the Microsoft Speech Library to do speech recognition in a C# program. I created a wrapper class for the speech stuff, so this question doesn't involve the specifics of that.

    The wrapper class has event handlers in it, so when a recognized word shows up on the mic, an event triggers and it invokes a little piece of code that I wrote inside the class. This is all well and good, but I'd really like the wrapper class to invoke an event in the main program, not just in its own code. I assume the easiest way to do this is to give the class its own outgoing event thing and invoke it from the existing incoming event handler. I'm a super-beginner at C# so most of what I do is based on knowledge of programming concepts and the little intellisense menu in Visual Studio. Can someone give me a rundown of how to do this whole delegate/event thing in a custom class that's not inherited from anything?

    All the tutorials I find online are hard to follow for me. They're more concerned with good programming practice than showing the bare-bones concept. Thanks in advance.

    (I could post the code, but it's complex and not really helpful. I'm really looking for some generic, basic stuff.)

    I dunno if there's some proper C# way to implement that, but the way I've always seen a class communicating with the rest of the program is by having a reference the program's primary "controller" type object, which can either have a method that the other object can call directly, or you can implement some kind of event posting scheme, so all your classes can use one method in the controller to "post" the event and then the controller decides what to do. The latter is what I've done in a roguelike I'm writing in Python, and it works fine and is pretty convenient since the language makes setting that kind of thing up easy (e.g. an event system needs a bunch of enum values for all the event types, and Python's way of doing that is pretty sweet). Objective-C/Cocoa tends to do a bit of the "directly call a method" thing, where, say, clicking a button will call in IBAction type method (specifically for that button) in your controller.

    One caveat: Don't implement anything where an in-application event posted by one method could potentially cause methods to be called that somehow call the original method all over again (perhaps by another part of the programming being triggered to "post" an event by the original event) because then you'll have some undesirable recursion on your hands. I did this accidentally in my game, and Python hit its recursion limit quite quickly, but I suspect that limit might be a lot higher (if it exists at all) for a language like C#.

    LoneIgadzra on
  • Options
    JaninJanin Registered User regular
    edited November 2007
    Recursion limits exist in all languages. Python will raise an exception, C/C++ will blow the stack and segfault, not sure what C#/Java will do but probably abort the program.

    If you want a secondary class to call back to the main class, try some code like this. I assume you have somewhere in the main class where it creates the secondary.
    class Main
    {
    	void create_secondary ()
    	{
    		Secondary secondary (this);
    	}
    	
    	void do_something ()
    	{
    		Console.WriteLine ("Something done\n");
    	}
    }
    
    class Secondary
    {
    	Main main;
    	
    	Secondary (Main main_reference)
    	{
    		main = main_reference;
    	}
    	
    	void my_event ()
    	{
    		main.do_something ();
    	}
    }
    

    Janin on
    [SIGPIC][/SIGPIC]
  • Options
    mausmalonemausmalone Registered User regular
    edited November 2007
    I also don't have any real experience with C# ... but if it works like the rest of windows then you're posting events to the window, not the object. If one is part of a child window, then you can use Windows API calls to get the parent window and then post the event to that.

    Is C# more like C/C++ Win32 API or C/C++ MFC API? Or none of the above?

    mausmalone on
    266.jpg
  • Options
    jackaljackal Fuck Yes. That is an orderly anal warehouse. Registered User regular
    edited November 2007
    Janin wrote: »
    Recursion limits exist in all languages. Python will raise an exception, C/C++ will blow the stack and segfault, not sure what C#/Java will do but probably abort the program.

    If you want a secondary class to call back to the main class, try some code like this. I assume you have somewhere in the main class where it creates the secondary.
    class Main
    {
    	void create_secondary ()
    	{
    		Secondary secondary (this);
    	}
    	
    	void do_something ()
    	{
    		Console.WriteLine ("Something done\n");
    	}
    }
    
    class Secondary
    {
    	Main main;
    	
    	Secondary (Main main_reference)
    	{
    		main = main_reference;
    	}
    	
    	void my_event ()
    	{
    		main.do_something ();
    	}
    }
    

    That is not completely true. An important feature of functional programming languages is that tail recursion does not take up stack space.

    jackal on
  • Options
    JaninJanin Registered User regular
    edited November 2007
    That doesn't help you much if you're using non-tail recursion. Even Scheme will complain if you have a function that calls itself too many times.

    Janin on
    [SIGPIC][/SIGPIC]
  • Options
    jonxpjonxp [E] PC Security Registered User regular
    edited November 2007
    So I have a question. I'm using the Microsoft Speech Library to do speech recognition in a C# program. I created a wrapper class for the speech stuff, so this question doesn't involve the specifics of that.

    The wrapper class has event handlers in it, so when a recognized word shows up on the mic, an event triggers and it invokes a little piece of code that I wrote inside the class. This is all well and good, but I'd really like the wrapper class to invoke an event in the main program, not just in its own code. I assume the easiest way to do this is to give the class its own outgoing event thing and invoke it from the existing incoming event handler. I'm a super-beginner at C# so most of what I do is based on knowledge of programming concepts and the little intellisense menu in Visual Studio. Can someone give me a rundown of how to do this whole delegate/event thing in a custom class that's not inherited from anything?

    All the tutorials I find online are hard to follow for me. They're more concerned with good programming practice than showing the bare-bones concept. Thanks in advance.

    (I could post the code, but it's complex and not really helpful. I'm really looking for some generic, basic stuff.)

    I'm not sure I understand the question, you can use the delegate events anywhere within your code, you don't just have to have it in the wrapper class.

    jonxp on
    Every time you write parallel fifths, Bach kills a kitten.
    3DS Friend Code: 2707-1614-5576
    PAX Prime 2014 Buttoneering!
  • Options
    ASimPersonASimPerson Cold... and hard.Registered User regular
    edited November 2007
    ASimPerson wrote: »
    And speaking of style, OTBS for life. To quote Linus Torvalds: "[A]ll right-thinking people know that (a) K&R are _right_ and (b) K&R are right."

    Wow, I never realized there were names for these conventions. I sort of always just did what felt the best, with the general leaning that more whitespace and logical separation = more readable code, so I prefer to put an opening bracket on its own line, unless it's something really obvious and I'd rather save space. K&R usually just seems so cramped to me.

    Also, I like things symmetrical, and the trailing bracket not lining up with the opening bracket always bugs the shit out of me. Makes the whole thing seem top heavy.

    Well, if there weren't names for them, it'd be a lot harder for generations of C coders to argue about them. :)

    As soon as I started coding C I thought it was dumb to waste a line on the opening brace. Thankfully, the company I work for uses K&R, so yeah.

    So moving on to the text flamewar topic: vi sucks! Emacs fo life! :D

    (Also, if you recurse too many times in Java it'll throw an uncatchable StackOverFlowException, IIRC.)

    ASimPerson on
  • Options
    .:Orion.:Orion Registered User regular
    edited November 2007
    So I have a question. I'm using the Microsoft Speech Library to do speech recognition in a C# program. I created a wrapper class for the speech stuff, so this question doesn't involve the specifics of that.

    The wrapper class has event handlers in it, so when a recognized word shows up on the mic, an event triggers and it invokes a little piece of code that I wrote inside the class. This is all well and good, but I'd really like the wrapper class to invoke an event in the main program, not just in its own code. I assume the easiest way to do this is to give the class its own outgoing event thing and invoke it from the existing incoming event handler. I'm a super-beginner at C# so most of what I do is based on knowledge of programming concepts and the little intellisense menu in Visual Studio. Can someone give me a rundown of how to do this whole delegate/event thing in a custom class that's not inherited from anything?

    All the tutorials I find online are hard to follow for me. They're more concerned with good programming practice than showing the bare-bones concept. Thanks in advance.

    (I could post the code, but it's complex and not really helpful. I'm really looking for some generic, basic stuff.)

    Since you want your main program to react to events occuring in the wrapper class (I assume), you probably already have a reference to it in the main program, then, what you can do is this :

    In your wrapper class, define the events that you want to dispatch

    public event EventHandler<EventArgs> RecognizeWord;
    public event EventHandler<EventArgs> SomethingElse;

    now, a good practice for raising events is this :

    for each event you defined, create a protected Method called On*EventName*(...), i.e.

    protected void OnRecognizeWord(...)
    {
    //RecognizeWord is null when there is no registered observer, and this would throw an exception without the if.
    if ( RecognizeWord != null ) { RecognizeWord(this, EventArgs.Empty); } // this notifies potential observers
    }

    protected void OnSomethingElse(...)
    {
    if (SomethingElse != null) { SomethingElse(this, EventArgs.Empty); } // this notifies potential observers
    }

    This way, subclasses will be able to raise the event and/or override them.

    Whenever you find that the conditions are met for the event to be raised, just called these methods to raise the events.

    Now, we defined those event with EventHandler<EventArgs> as their type, if you want to pass along informations to observers, like if your main program wanted to know which word was recognized, etc... you'll want to replace EventArgs with a custom class you'll have to create that subclasses EventArgs and just pass it along when you raise the event :

    protected void OnRecognizeWord(string word)
    {
    //this might become
    if (...) { RecognizeWord(this, new RecognizeWordEventArgs(word)) }
    }

    After you've done that, registering your main program so it gets notified shouldn't be a problem.

    If you have a reference to the wrapper class, you just do

    my_wrapper.RecognizeWord += ... (just like any other event, i dont remember the syntax at the moment);
    my_wrapper.SomethingElse += ...;

    .:Orion on
  • Options
    jonxpjonxp [E] PC Security Registered User regular
    edited November 2007
    .:Orion wrote: »
    So I have a question. I'm using the Microsoft Speech Library to do speech recognition in a C# program. I created a wrapper class for the speech stuff, so this question doesn't involve the specifics of that.

    The wrapper class has event handlers in it, so when a recognized word shows up on the mic, an event triggers and it invokes a little piece of code that I wrote inside the class. This is all well and good, but I'd really like the wrapper class to invoke an event in the main program, not just in its own code. I assume the easiest way to do this is to give the class its own outgoing event thing and invoke it from the existing incoming event handler. I'm a super-beginner at C# so most of what I do is based on knowledge of programming concepts and the little intellisense menu in Visual Studio. Can someone give me a rundown of how to do this whole delegate/event thing in a custom class that's not inherited from anything?

    All the tutorials I find online are hard to follow for me. They're more concerned with good programming practice than showing the bare-bones concept. Thanks in advance.

    (I could post the code, but it's complex and not really helpful. I'm really looking for some generic, basic stuff.)

    Since you want your main program to react to events occuring in the wrapper class (I assume), you probably already have a reference to it in the main program, then, what you can do is this :

    In your wrapper class, define the events that you want to dispatch

    public event EventHandler<EventArgs> RecognizeWord;
    public event EventHandler<EventArgs> SomethingElse;

    now, a good practice for raising events is this :

    for each event you defined, create a protected Method called On*EventName*(...), i.e.

    protected void OnRecognizeWord(...)
    {
    //RecognizeWord is null when there is no registered observer, and this would throw an exception without the if.
    if ( RecognizeWord != null ) { RecognizeWord(this, EventArgs.Empty); } // this notifies potential observers
    }

    protected void OnSomethingElse(...)
    {
    if (SomethingElse != null) { SomethingElse(this, EventArgs.Empty); } // this notifies potential observers
    }

    This way, subclasses will be able to raise the event and/or override them.

    Whenever you find that the conditions are met for the event to be raised, just called these methods to raise the events.

    Now, we defined those event with EventHandler<EventArgs> as their type, if you want to pass along informations to observers, like if your main program wanted to know which word was recognized, etc... you'll want to replace EventArgs with a custom class you'll have to create that subclasses EventArgs and just pass it along when you raise the event :

    protected void OnRecognizeWord(string word)
    {
    //this might become
    if (...) { RecognizeWord(this, new RecognizeWordEventArgs(word)) }
    }

    After you've done that, registering your main program so it gets notified shouldn't be a problem.

    If you have a reference to the wrapper class, you just do

    my_wrapper.RecognizeWord += ... (just like any other event, i dont remember the syntax at the moment);
    my_wrapper.SomethingElse += ...;

    Also, be careful if you're trying to update a .NET UI element with a threaded event. Windows.Forms is not very happy about threads other than the thread the UI element was instantiated on trying to change its properties.

    Too complicated to write up how to avoid the problem here, but it's just a little pitfall to look out for so you don't get surprised.

    jonxp on
    Every time you write parallel fifths, Bach kills a kitten.
    3DS Friend Code: 2707-1614-5576
    PAX Prime 2014 Buttoneering!
  • Options
    NightslyrNightslyr Registered User regular
    edited November 2007
    Re: indent style -- I never knew that there were standardized styles of indenting. According to the Wikipedia link, I use a mutant form of OTBS. My general habits:
    <?php
       //Since I do mostly PHP coding, I keep everything inside the PHP tags at least 1 indent in.
    
       if(!empty($_POST['thingie'])){
          //do something
       }
       else{
          //don't do something
       }
    
       if(/* some big conditional */){
          if(/* another conditional */){
             //do something
          }
          else{
             //do another thing
          }
       }
       else{
          //do thing
       }
    
       if(/* conditional */){/* do one-line thing */}
    
       //Loops follow the same structure, see?
    
       while($you != $yoMomma){
          //do something
          $you++;
       }
    
       //a more realistic example
    
       while($row = mysql_fetch_assoc($queryResult)){
          $arrayVar["{$row['social_security']}"] = $row["name"]; //create a simple hash -- each SSN is connected to a name
       }
    
       $html = "<table cellspacing='0' cellpadding='5'><tr><th>SSN</th><th>Name</th></tr>";
    
       foreach($arrayVar as $ssn => $name){
          $html .= "<tr><td>$ssn</td><td>$name</td></tr>";
       }
    
       $html .= "</table>";
    
       if(!empty($html)){ //who knows -- maybe the query (which I neglected to write) was bad, and error reporting is turned off
          echo "$html";
       }
    ?>
    

    I tend to keep else's/else-if's only one line down from the closing bracket of the first if-conditional. I put an extra space between the end of a conditional series and the start of a new one. That way, I can tell what else/else-if clauses are related to what if-conditional, as they're separate from other conditionals. I do the same with loops.

    tldr; I code too...am I cool?

    Nightslyr on
  • Options
    ZackSchillingZackSchilling Registered User regular
    edited November 2007
    .:Orion wrote: »
    So I have a question. I'm using the Microsoft Speech Library to do speech recognition in a C# program. I created a wrapper class for the speech stuff, so this question doesn't involve the specifics of that.

    The wrapper class has event handlers in it, so when a recognized word shows up on the mic, an event triggers and it invokes a little piece of code that I wrote inside the class. This is all well and good, but I'd really like the wrapper class to invoke an event in the main program, not just in its own code. I assume the easiest way to do this is to give the class its own outgoing event thing and invoke it from the existing incoming event handler. I'm a super-beginner at C# so most of what I do is based on knowledge of programming concepts and the little intellisense menu in Visual Studio. Can someone give me a rundown of how to do this whole delegate/event thing in a custom class that's not inherited from anything?

    All the tutorials I find online are hard to follow for me. They're more concerned with good programming practice than showing the bare-bones concept. Thanks in advance.

    (I could post the code, but it's complex and not really helpful. I'm really looking for some generic, basic stuff.)

    Since you want your main program to react to events occuring in the wrapper class (I assume), you probably already have a reference to it in the main program, then, what you can do is this :

    In your wrapper class, define the events that you want to dispatch

    public event EventHandler<EventArgs> RecognizeWord;
    public event EventHandler<EventArgs> SomethingElse;

    now, a good practice for raising events is this :

    for each event you defined, create a protected Method called On*EventName*(...), i.e.

    protected void OnRecognizeWord(...)
    {
    //RecognizeWord is null when there is no registered observer, and this would throw an exception without the if.
    if ( RecognizeWord != null ) { RecognizeWord(this, EventArgs.Empty); } // this notifies potential observers
    }

    protected void OnSomethingElse(...)
    {
    if (SomethingElse != null) { SomethingElse(this, EventArgs.Empty); } // this notifies potential observers
    }

    This way, subclasses will be able to raise the event and/or override them.

    Whenever you find that the conditions are met for the event to be raised, just called these methods to raise the events.

    Now, we defined those event with EventHandler<EventArgs> as their type, if you want to pass along informations to observers, like if your main program wanted to know which word was recognized, etc... you'll want to replace EventArgs with a custom class you'll have to create that subclasses EventArgs and just pass it along when you raise the event :

    protected void OnRecognizeWord(string word)
    {
    //this might become
    if (...) { RecognizeWord(this, new RecognizeWordEventArgs(word)) }
    }

    After you've done that, registering your main program so it gets notified shouldn't be a problem.

    If you have a reference to the wrapper class, you just do

    my_wrapper.RecognizeWord += ... (just like any other event, i dont remember the syntax at the moment);
    my_wrapper.SomethingElse += ...;

    Thanks, that helps a lot. I'm doing a written design review for this project right now so your information will come in handy for this document, then I'll try my hand at actually implementing it a bit later. And yeah, creating the subclass of EventArgs and adding the handler to my form is no problem for me, it was the other bit with defining the event in the class and getting all the particulars in line.

    jonxp, I've seen some of this unhappy behavior firsthand. Basically, my program is combining 3 inputs, GUI button events, these voice events, and Wii remote events to control a robot wirelessly over Bluetooth. I have each event set its own flag when words are recognized, GUI buttons are clicked, or the Wii remote gets a button state change. A timer then comes in and uses these flags to drive a state machine that sends off serial communications to the robot. It's complex, but this way, I don't have events fighting, accidental clicks are ignored, and all 3 input devices can co-exist without having to be aware of each other.

    ZackSchilling on
    ghost-robot.jpg
  • Options
    RohaqRohaq UKRegistered User regular
    edited November 2007
    Quick question about switch statements in C++ please:
    How do you specify ranges? Can you specify ranges? i.e. 0 to 39, 40 to 49, etc?

    I can see on Wikipedia that there are examples in other languages where you can do this, but only cases of exact values on C, and none of the methods I'd tried have worked :(

    Rohaq on
  • Options
    SmasherSmasher Starting to get dizzy Registered User regular
    edited November 2007
    Rohaq wrote: »
    Quick question about switch statements in C++ please:
    How do you specify ranges? Can you specify ranges? i.e. 0 to 39, 40 to 49, etc?

    I can see on Wikipedia that there are examples in other languages where you can do this, but only cases of exact values on C, and none of the methods I'd tried have worked :(

    Some compilers apparently support it as an extension, but in ANSI c or c++ you can't. Sorry.

    You might be able to work around it in some instances, such as if you wanted to group the cases in blocks of tens, but most of the time it would end up being much more cumbersome than simply using if() statements.

    Smasher on
  • Options
    RohaqRohaq UKRegistered User regular
    edited November 2007
    Smasher wrote: »
    Rohaq wrote: »
    Quick question about switch statements in C++ please:
    How do you specify ranges? Can you specify ranges? i.e. 0 to 39, 40 to 49, etc?

    I can see on Wikipedia that there are examples in other languages where you can do this, but only cases of exact values on C, and none of the methods I'd tried have worked :(

    Some compilers apparently support it as an extension, but in ANSI c or c++ you can't. Sorry.

    You might be able to work around it in some instances, such as if you wanted to group the cases in blocks of tens, but most of the time it would end up being much more cumbersome than simply using if() statements.
    Nope, that's fine, I'll just use ifs and else if's :)

    Thanks!

    Rohaq on
  • Options
    falsedeffalsedef Registered User regular
    edited November 2007
    Smasher wrote: »
    You might be able to work around it in some instances, such as if you wanted to group the cases in blocks of tens, but most of the time it would end up being much more cumbersome than simply using if() statements.
    This?
    switch( num/10 ){
     case 0:
     case 1:
     case 2:
     case 3:
       ...
      break;
     case 4:
      ...
      break;
    }
    
    which should correspond to:
    i.e. 0 to 39, 40 to 49, etc?

    Even if the groupings aren't consistent, it might be preferable. The advantage is that contiguous switch cases are O(1), and O(lgn) for non contiguous (same if your range quantities aren't consistent). If-else chains are typically O(n), though you could format it to be O(lgn).

    falsedef on
  • Options
    SmasherSmasher Starting to get dizzy Registered User regular
    edited November 2007
    falsedef wrote: »
    Smasher wrote: »
    You might be able to work around it in some instances, such as if you wanted to group the cases in blocks of tens, but most of the time it would end up being much more cumbersome than simply using if() statements.
    This?
    switch( num/10 ){
     case 0:
     case 1:
     case 2:
     case 3:
       ...
      break;
     case 4:
      ...
      break;
    }
    
    which should correspond to:
    i.e. 0 to 39, 40 to 49, etc?
    Even if the groupings aren't consistent, it might be preferable. The advantage is that contiguous switch cases are O(1), and O(lgn) for non contiguous (same if your range quantities aren't consistent). If-else chains are typically O(n), though you could format it to be O(lgn).

    I don't know about you, but I'd consider a big block of case statements to be more cumbersome than a few ranges in if() statements. Not only would it be annoying to type out more than a dozen or two cases (even if you copy and paste you still have to change the numbers), but if you accidentally miss one you'll very likely introduce a subtle bug into the code as it goes to the default case instead. The switch statement is probably the better solution if your ranges are small, but other than that they'll just be a hassle. For the example he gave us we're comparing two if() statements to 50 cases.

    As for speed, the vast majority of the time the minor difference between the two will be completely insignificant. The only exceptions I can think of are if you have a huge number of discrete ranges or if this is right in the middle of your innermost code loop in a CPU intensive program. Computers are fast enough now that avoiding premature optimization is very often a good idea.

    Smasher on
  • Options
    RohaqRohaq UKRegistered User regular
    edited November 2007
    Smasher wrote: »
    falsedef wrote: »
    Smasher wrote: »
    You might be able to work around it in some instances, such as if you wanted to group the cases in blocks of tens, but most of the time it would end up being much more cumbersome than simply using if() statements.
    This?
    switch( num/10 ){
     case 0:
     case 1:
     case 2:
     case 3:
       ...
      break;
     case 4:
      ...
      break;
    }
    
    which should correspond to:
    i.e. 0 to 39, 40 to 49, etc?
    Even if the groupings aren't consistent, it might be preferable. The advantage is that contiguous switch cases are O(1), and O(lgn) for non contiguous (same if your range quantities aren't consistent). If-else chains are typically O(n), though you could format it to be O(lgn).

    I don't know about you, but I'd consider a big block of case statements to be more cumbersome than a few ranges in if() statements. Not only would it be annoying to type out more than a dozen or two cases (even if you copy and paste you still have to change the numbers), but if you accidentally miss one you'll very likely introduce a subtle bug into the code as it goes to the default case instead. The switch statement is probably the better solution if your ranges are small, but other than that they'll just be a hassle. For the example he gave us we're comparing two if() statements to 50 cases.

    As for speed, the vast majority of the time the minor difference between the two will be completely insignificant. The only exceptions I can think of are if you have a huge number of discrete ranges or if this is right in the middle of your innermost code loop in a CPU intensive program. Computers are fast enough now that avoiding premature optimization is very often a good idea.
    He was actually talking about dividing the value by 10 first, then having 10 case statements, which I don't think would work, because the number I'm using is a double, and wouldn't round to an integer.

    Rohaq on
  • Options
    SmasherSmasher Starting to get dizzy Registered User regular
    edited November 2007
    Rohaq wrote: »
    Smasher wrote: »
    falsedef wrote: »
    Smasher wrote: »
    You might be able to work around it in some instances, such as if you wanted to group the cases in blocks of tens, but most of the time it would end up being much more cumbersome than simply using if() statements.
    This?
    switch( num/10 ){
     case 0:
     case 1:
     case 2:
     case 3:
       ...
      break;
     case 4:
      ...
      break;
    }
    
    which should correspond to:
    i.e. 0 to 39, 40 to 49, etc?
    Even if the groupings aren't consistent, it might be preferable. The advantage is that contiguous switch cases are O(1), and O(lgn) for non contiguous (same if your range quantities aren't consistent). If-else chains are typically O(n), though you could format it to be O(lgn).

    I don't know about you, but I'd consider a big block of case statements to be more cumbersome than a few ranges in if() statements. Not only would it be annoying to type out more than a dozen or two cases (even if you copy and paste you still have to change the numbers), but if you accidentally miss one you'll very likely introduce a subtle bug into the code as it goes to the default case instead. The switch statement is probably the better solution if your ranges are small, but other than that they'll just be a hassle. For the example he gave us we're comparing two if() statements to 50 cases.

    As for speed, the vast majority of the time the minor difference between the two will be completely insignificant. The only exceptions I can think of are if you have a huge number of discrete ranges or if this is right in the middle of your innermost code loop in a CPU intensive program. Computers are fast enough now that avoiding premature optimization is very often a good idea.
    He was actually talking about dividing the value by 10 first, then having 10 case statements, which I don't think would work, because the number I'm using is a double, and wouldn't round to an integer.

    Oops. Good thing I didn't take the SAT today, because I would have failed the reading comprehension section. For some reason I thought he was arguing with me.

    Wait, you're using doubles? I'm not even sure if that works with switch statements. Might make sense if you actually could use ranges, but since you can't they'd rarely work right if you even can.

    Smasher on
  • Options
    RohaqRohaq UKRegistered User regular
    edited November 2007
    Smasher wrote: »
    Rohaq wrote: »
    Smasher wrote: »
    falsedef wrote: »
    Smasher wrote: »
    You might be able to work around it in some instances, such as if you wanted to group the cases in blocks of tens, but most of the time it would end up being much more cumbersome than simply using if() statements.
    This?
    switch( num/10 ){
     case 0:
     case 1:
     case 2:
     case 3:
       ...
      break;
     case 4:
      ...
      break;
    }
    
    which should correspond to:
    i.e. 0 to 39, 40 to 49, etc?
    Even if the groupings aren't consistent, it might be preferable. The advantage is that contiguous switch cases are O(1), and O(lgn) for non contiguous (same if your range quantities aren't consistent). If-else chains are typically O(n), though you could format it to be O(lgn).

    I don't know about you, but I'd consider a big block of case statements to be more cumbersome than a few ranges in if() statements. Not only would it be annoying to type out more than a dozen or two cases (even if you copy and paste you still have to change the numbers), but if you accidentally miss one you'll very likely introduce a subtle bug into the code as it goes to the default case instead. The switch statement is probably the better solution if your ranges are small, but other than that they'll just be a hassle. For the example he gave us we're comparing two if() statements to 50 cases.

    As for speed, the vast majority of the time the minor difference between the two will be completely insignificant. The only exceptions I can think of are if you have a huge number of discrete ranges or if this is right in the middle of your innermost code loop in a CPU intensive program. Computers are fast enough now that avoiding premature optimization is very often a good idea.
    He was actually talking about dividing the value by 10 first, then having 10 case statements, which I don't think would work, because the number I'm using is a double, and wouldn't round to an integer.

    Oops. Good thing I didn't take the SAT today, because I would have failed the reading comprehension section. For some reason I thought he was arguing with me.

    Wait, you're using doubles? I'm not even sure if that works with switch statements. Might make sense if you actually could use ranges, but since you can't they'd rarely work right if you even can.
    Yep, I'm not even sure why - We've just been asked to code the function that way. I don't know why - I'm using the function, and casting it as an integer, because I'm populating an array that's full of integer values.

    No idea why, really.

    Rohaq on
  • Options
    Shazkar ShadowstormShazkar Shadowstorm Registered User regular
    edited November 2007
    I'm not sure I understand the Command/Action pattern. I get the general idea of making commands as objects, but I'm not sure why or how to implement it.
    I'm trying to figure it out in the context of having a little frame/scene that I made, where I have buttons that add little objects and shapes to the frame that you can move around and select and remove with another button, but I need to use the action pattern to make it so that it disables a button when there are say, 5 of a given shape. Hmm.. and all the different shape objects are just stored in an arraylist.

    (java)

    Shazkar Shadowstorm on
    poo
  • Options
    jothkijothki Registered User regular
    edited November 2007
    Rohaq wrote: »
    Smasher wrote: »
    Rohaq wrote: »
    Smasher wrote: »
    falsedef wrote: »
    Smasher wrote: »
    You might be able to work around it in some instances, such as if you wanted to group the cases in blocks of tens, but most of the time it would end up being much more cumbersome than simply using if() statements.
    This?
    switch( num/10 ){
     case 0:
     case 1:
     case 2:
     case 3:
       ...
      break;
     case 4:
      ...
      break;
    }
    
    which should correspond to:
    i.e. 0 to 39, 40 to 49, etc?
    Even if the groupings aren't consistent, it might be preferable. The advantage is that contiguous switch cases are O(1), and O(lgn) for non contiguous (same if your range quantities aren't consistent). If-else chains are typically O(n), though you could format it to be O(lgn).

    I don't know about you, but I'd consider a big block of case statements to be more cumbersome than a few ranges in if() statements. Not only would it be annoying to type out more than a dozen or two cases (even if you copy and paste you still have to change the numbers), but if you accidentally miss one you'll very likely introduce a subtle bug into the code as it goes to the default case instead. The switch statement is probably the better solution if your ranges are small, but other than that they'll just be a hassle. For the example he gave us we're comparing two if() statements to 50 cases.

    As for speed, the vast majority of the time the minor difference between the two will be completely insignificant. The only exceptions I can think of are if you have a huge number of discrete ranges or if this is right in the middle of your innermost code loop in a CPU intensive program. Computers are fast enough now that avoiding premature optimization is very often a good idea.
    He was actually talking about dividing the value by 10 first, then having 10 case statements, which I don't think would work, because the number I'm using is a double, and wouldn't round to an integer.

    Oops. Good thing I didn't take the SAT today, because I would have failed the reading comprehension section. For some reason I thought he was arguing with me.

    Wait, you're using doubles? I'm not even sure if that works with switch statements. Might make sense if you actually could use ranges, but since you can't they'd rarely work right if you even can.
    Yep, I'm not even sure why - We've just been asked to code the function that way. I don't know why - I'm using the function, and casting it as an integer, because I'm populating an array that's full of integer values.

    No idea why, really.

    Thinking about it, it's a basic hash. You're taking an input value, running it through a hashing function (in this case, divide by 10 and rounding down), and then using the output to find a result, in this case the code that you want to run.

    jothki on
  • Options
    JasconiusJasconius sword criminal mad onlineRegistered User regular
    edited November 2007
    Here's a C#.NET problem that vexed me long ago.

    I had a series of products that were printed out in a DataList.

    Each product had ImageButton's associated with it for Add to Cart, etc.

    I wanted to rig these links so that the click even would cause it to perform the appropriate action based on what item the ImageButton belonged to.

    To do that I would have had to pass a specific value to the click even handler, since, as far as I know, you can't tailor a unique event handler for each Item in a datalist.

    I ended up not being very successful in this endeavor, and wound up creating a querystring system to compensate... however, it's not quite as zippy as it could be.

    I tried a lot of Googling on the subject but the only thing I found was setting up a ridiculous system of delegates, which.. I don't even want to bother with.

    Jasconius on
  • Options
    .:Orion.:Orion Registered User regular
    edited November 2007
    Jasconius wrote: »
    Here's a C#.NET problem that vexed me long ago.

    I had a series of products that were printed out in a DataList.

    Each product had ImageButton's associated with it for Add to Cart, etc.

    I wanted to rig these links so that the click even would cause it to perform the appropriate action based on what item the ImageButton belonged to.

    To do that I would have had to pass a specific value to the click even handler, since, as far as I know, you can't tailor a unique event handler for each Item in a datalist.

    I ended up not being very successful in this endeavor, and wound up creating a querystring system to compensate... however, it's not quite as zippy as it could be.

    I tried a lot of Googling on the subject but the only thing I found was setting up a ridiculous system of delegates, which.. I don't even want to bother with.

    I kinda know how to do this but it depends on what your Product objet is like.

    To pass information around you can just set the CommandName and CommandArgument properties of your ImageButton, and add an event handler on the DataList's ItemCommand event.

    But a query string system could be even better. Less post-backs and all. As long as it's well done.

    .:Orion on
  • Options
    JasconiusJasconius sword criminal mad onlineRegistered User regular
    edited November 2007
    .:Orion wrote: »
    Jasconius wrote: »
    Here's a C#.NET problem that vexed me long ago.

    I had a series of products that were printed out in a DataList.

    Each product had ImageButton's associated with it for Add to Cart, etc.

    I wanted to rig these links so that the click even would cause it to perform the appropriate action based on what item the ImageButton belonged to.

    To do that I would have had to pass a specific value to the click even handler, since, as far as I know, you can't tailor a unique event handler for each Item in a datalist.

    I ended up not being very successful in this endeavor, and wound up creating a querystring system to compensate... however, it's not quite as zippy as it could be.

    I tried a lot of Googling on the subject but the only thing I found was setting up a ridiculous system of delegates, which.. I don't even want to bother with.

    I kinda know how to do this but it depends on what your Product objet is like.

    To pass information around you can just set the CommandName and CommandArgument properties of your ImageButton, and add an event handler on the DataList's ItemCommand event.

    But a query string system could be even better. Less post-backs and all. As long as it's well done.

    I wasn't aware of the CommandName and CommandArgument properties. That sounds about right. The majority of the system operates off of the productID which is used to dig up the rest of the product info. Implementing the QueryString system was less than pleasurable because I actually have a very warped product system which requires two seperate ID's, one for actual product, one for the "format". Getting both the ProductID from the data object, and then the FormatID from a nested RadioButtonList at the same time, and THEN passing both to an ImageButton event handler was.. at the time I created it, very D:

    Fortunately I have a month or two to redesign the system to better support the concept of "product and format" because I wasn't aware there needed to be two separate entities until I had already started working.

    Jasconius on
  • Options
    marty_0001marty_0001 I am a file and you put documents in meRegistered User regular
    edited November 2007
    Okay I'm very very new to the whole programming thing so please forgive the extreme simplicity of this/any other question.

    Using Python.

    The question asks for you to make a program that calculates wages for a shift. You enter the rate, you enter the hours worked, and bam, it multiplies the two and outputs the answer. So simple! And yet for some reason I am getting an error.

    Here is my program:
    def totalPay():
    
        total = 0
        Rate = raw_input("Please enter the rate of pay per hour: ")
        Hours = raw_input("Please enter the number of hours worked: ")
        if Rate < 0 or Hours < 0:
            print "The total pay for this shift is: ", 0
        else:
            total = Rate * Hours
            print "The total pay for this shift is: ", total
    
    
    totalPay()
    

    And here is the error I receive:
    >>> 
    Please enter the rate of pay per hour: 20
    Please enter the number of hours worked: 2
    
    Traceback (most recent call last):
      File "C:/Documents and Settings/Marty/My Documents/Python Programs/Exam Q6a.py", line 15, in -toplevel-
        totalPay()
      File "C:/Documents and Settings/Marty/My Documents/Python Programs/Exam Q6a.py", line 11, in totalPay
        total = Rate * Hours
    TypeError: can't multiply sequence to non-int
    

    Non-int! There's no decimal places, how can it not be an int? Even so, Python would usually perform an int/float conversion itself.
    I think what's happening is rather than treating my inputs as numbers, it's treating them like non-literals. For example if I replaced the multiply with a plus, and it gave the answer 202, rather than 22?

    Also, the 'less than zero' stuff is for when a negative number is entered, it returns an answer of zero. I think this is wrong but I'll work on that.

    Sigh, exams! Thanks for your help everyone.

    marty_0001 on
  • Options
    EtheaEthea Registered User regular
    edited November 2007
    marty_0001 wrote: »
    Okay I'm very very new to the whole programming thing so please forgive the extreme simplicity of this/any other question.

    Using Python.

    The question asks for you to make a program that calculates wages for a shift. You enter the rate, you enter the hours worked, and bam, it multiplies the two and outputs the answer. So simple! And yet for some reason I am getting an error.

    Here is my program:
    def totalPay():
    
        total = 0
        Rate = raw_input("Please e:nter the rate of pay per hour: ")
        Hours = raw_input("Please enter the number of hours worked: ")
        if Rate < 0 or Hours < 0:
            print "The total pay for this shift is: ", 0
        else:
            total = Rate * Hours
            print "The total pay for this shift is: ", total
    
    
    totalPay()
    

    And here is the error I receive:
    >>> 
    Please enter the rate of pay per hour: 20
    Please enter the number of hours worked: 2
    
    Traceback (most recent call last):
      File "C:/Documents and Settings/Marty/My Documents/Python Programs/Exam Q6a.py", line 15, in -toplevel-
        totalPay()
      File "C:/Documents and Settings/Marty/My Documents/Python Programs/Exam Q6a.py", line 11, in totalPay
        total = Rate * Hours
    TypeError: can't multiply sequence to non-int
    

    Non-int! There's no decimal places, how can it not be an int? Even so, Python would usually perform an int/float conversion itself.
    I think what's happening is rather than treating my inputs as numbers, it's treating them like non-literals. For example if I replaced the multiply with a plus, and it gave the answer 202, rather than 22?

    Also, the 'less than zero' stuff is for when a negative number is entered, it returns an answer of zero. I think this is wrong but I'll work on that.

    Sigh, exams! Thanks for your help everyone.

    Python input is typed as a string. convert the the input inside a try except block

    Something like this
    try:
      temp = float(rate)
    except ValueError:
      print 'You have entered a non numeric item, please try again'
      #recurse call or whatever
    else:
      rate = temp
    

    Edit: Here is how I would handle it:
    Edit2: just noticed you want to zero out any number is negative so added a max check
    def userInput(message):
      value = raw_input(message)
      try:
        temp = float(value)
      except ValueError:
        print 'You have entered a non-numeric value, please try again'
        return userInput(message)
      else:
        return max(0,temp)
    
    def totalPay():
      rate=userInput('Please enter the rate of pay per hour:')
      hours=userInput('Please enter the number of hours worked:')
      total = rate * hours
      print 'The total pay for this shift is: ', total
    

    Ethea on
  • Options
    LoneIgadzraLoneIgadzra Registered User regular
    edited November 2007
    Edit: Beaten

    LoneIgadzra on
  • Options
    JaninJanin Registered User regular
    edited November 2007
    Since Python doesn't collapse recursive calls, I would write the userInput function more like this:
    def userInput (message):
    	while True:
    		try:
    			return max (0, float (raw_input (message)))
    		except ValueError:
    			print 'You have entered a non-numeric value, please try again'
    

    Janin on
    [SIGPIC][/SIGPIC]
  • Options
    EtheaEthea Registered User regular
    edited November 2007
    Janin wrote: »
    Since Python doesn't collapse recursive calls, I would write the userInput function more like this:
    def userInput (message):
    	while True:
    		try:
    			return max (0, float (raw_input (message)))
    		except ValueError:
    			print 'You have entered a non-numeric value, please try again'
    

    Do you have any links to articles on how python handles recursion, I would love to read more about it.

    Ethea on
  • Options
    JaninJanin Registered User regular
    edited November 2007
    Ethea wrote: »
    Janin wrote: »
    Since Python doesn't collapse recursive calls, I would write the userInput function more like this:
    def userInput (message):
    	while True:
    		try:
    			return max (0, float (raw_input (message)))
    		except ValueError:
    			print 'You have entered a non-numeric value, please try again'
    

    Do you have any links to articles on how python handles recursion, I would love to read more about it.

    Sadly most of the articles on recursion in Python are not of much use. The most interesting one I found was a decorator for implementing tail-call optimization. It uses exceptions, so it's not really suitable for a speed increase, but can be used to transliterate a Scheme algorithm into Python if needed.

    Janin on
    [SIGPIC][/SIGPIC]
  • Options
    beefbeef Registered User regular
    edited November 2007
    I am supposed to make this Minesweeper clone:

    http://hopper.unco.edu/course/CG120/F07/lab9.exe

    but using Python. It is supposed to be a 30 x 30 playing field and for the life of me I can't figure out how to make the board. If anyone could help me out I would appreciate it.

    The profs advice was to do it using

    board = [[ ?????

    but he was purposely vague.

    beef on
This discussion has been closed.