Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

With all due respect, AD, I think you've misread the code (it happens to the best of us...). There is no class declaration; that's a using namespace directive. Furthermore, even were it a class declaration, there would still be code there which isn't inside of a method.

Ancient Dragon commented: you are correct :) +17
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The code as written isn't valid; unlike in some languages, you cannot have a code block that isn't part of a function in C++.

Mind you, it is generally inadvisable to have code (as opposed to declarations) in a header file, but that's not the cause of the problem, per se.

So, what was this code supposed to do?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Let's break this down somewhat; the increment operator isn't specific to for() loops, and for that matter, for() loops don't necessarily use an increment.

Let's take the simplest case of a separate increment expression:

i++;

Now, whether this compiles to a single assembly language operation or not depends on the processor type, and on how the compiler optimizes the variables as well. On most processors, incrementing a register is a single, atomic operation, but incrementing a memory value may require a separate load and store, which would mean at least two and possibly three operations. Even if the CPU type has an 'increment memory' operation (like the x86 that most people use), it may be slower than the equivalent register operation, sometimes by orders of magnitude depending on all sorts of things such as cache misses. Thus, it all comes down to what processor it is on, and how the compiler paints the registers, and to some extent where in the memory the variable is.

Note that all of this isn't necessarily relevant to algorithmic time complexity; that's usually stated in a manner that abstracts away the actual time for the operations, focusing instead on how many repetitions are needed by the algorithm.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You don't have any return value for the case where counter does not equal 5, so the caller basically gets whatever junk happens to be in the returned value register - and since any value other than zero (false) evaluates to true, the return value is almost always going to be true.

Actually, I'm surprised that this compiled at all - at the very least it should have given you a warning that not all paths end in a returned value. While C++ is a lot looser than some other languages about this sort of thing - it goes on the assumption that the you know what you're doing - it still should have at least checked to make sure this wasn't an oversight.

Also, in the conditional, the result variable is unnecessary, as is the ' == true ' part, and the winner assignment as well; you could simplify the whole thing as just:

if((checkFlush(checkCards)))
    {
        return 5;
    }
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Just noticed a careless error on my part:

movl    4(%ebp), %ecx
         movl    8(%ebp), %edx

should be

movl    12(%ebp), %ecx
         movl    16%ebp), %edx

I forgot to take the return address and %ecx into consideration. Sloppy of me.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I haven't tested this, but I believe it should work as a power function for integer values. You may want to test it yourself in a separate program.

int_pow:
         pushl   %ecx
         pushl   %ebp
         movl    %esp, %ebp
         movl    4(%ebp), %ecx
         movl    8(%ebp), %edx
         movl    $ecx, %eax         

power_loop:
         imul    %ecx
         decl    %edx
         jnz     power_loop   /* repeat until %edx is zero */

power_end:
         popl    %ebp
         popl    %ecx
         ret
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Regarding the numeric string, while "1234\0" is correct, in that it will work, you don't actually need the trailing null, as the string is declared .asciz already (which means a null is inserted at the end automatically by the assembler).

As for the %ebx, I think you'll still want to get a count of the elements in the string, as you'll need that to terminate the conversion loop. Also, you don't seem to see that the whole point of pushing the digits onto the stack is that you want to convert the string from the highest decimal place to the lowest; therefore, you need to start with the largest magnitude, and decrease it rather than increase it.

I think that this code should do what you want, though you'll need to replace the call to pow() with your own exponentiation function (the standard power function takes a double, not an int):

main:	
	movl	$1, %edi
	movl	$0, %ebx
	movl	$String, %ecx

character_push_loop:
	
	movb	(%ecx), %dl	/*Take one byte from the string and put in %dl*/
	cmpb	$0, %dl
	je	conversion_loop
	movb	%dl, (%eax)
	pushl	%eax		/*Push the byte on the stack*/
	incl	%ecx
	incl	%ebx
	jmp	character_push_loop

conversion_loop:

	decl	%ebx
        pushl   %ebx
        pushl   $10
        call    pow
        movl    %eax, %edi
        addl    8, %esp         /* clean up stack */     
	popl	%eax		/*pop off a character from the stack*/
	subl	$48, %eax	/*convert to integer*/
	imul	%edi		/* eax = eax*edi */
	addl	%eax, Intg
	cmpl	$0, %ebx
	je	end		/*When …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Note also that multiplying by %ebx is not enough; you need to take 10 to the power of %ebx - 1. Does the assignment allow you to use the pow() function?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I think that the issue the line

imul	%ecx		/* eax = eax*ecx */

Here you should be multiplying by %ebx rather than %ecx, as %ecx still holds a pointer to the end of the string, whereas %ebx should be holding the decimal place which you want to multiply by.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You really can't write a boot-loader in C++, at least not entirely; the first stage, at the very least, would have to be in assembly language, and given that most C++ compilers produce only 32-bit code, you'd probably have to set the system into 32-bit protected mode before you could even run a C++ program. Even with a 16-bit compiler, you'd be limited to the very core of the language, and have to avoid any libraries you hadn't implemented yourself. Even the core C++ has features which require run-time support (e.g., memory management), making it a difficult language to do systems programming in compared to its parent language, C (which has very minimal run-time requirements, having been designed for the purpose of OS implementation).

All in all, one year of C++ with no experience in assembly and C is unlikely to be enough for this purpose. At the very least, you'll need to learn assembly language for the assembler of your choice (even for the same system, every assembler has a different syntax - the three most common x86 assemblers used for this purpose are MASM, NASM and gas), as well as understanding the boot loading process well enough to write the loader.

You may want to review the information and advice at the OS Dev Wiki, as it covers the requirements of a boot loader. You might also consider using an existing bootloader such as GRUB, which …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I agree with Narue's advice, if it is possible - if you don't have a backup of the earlier version, and aren't using version control, it will be much harder to undo the changes. However, I was wondering if your course of study has covered classes yet; given the number of functions needed for the stack structure, it would make sense to wrap it all up into a class.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If you have any choice in the matter (and I realize you might not), I would suggest getting a more modern compiler and IDE. I personally find Code::Blocks to be very good, though Visual C++ Express has a superior debugger. If all else fails, and you can afford to pay for it, C++ Builder XE2 is the modern descendant of the Borland compiler. Given that you are writing what is essentially standard C++ code, it should compile and run under any of these, so which to use boils down to personal preference.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If you don't mind me asking, what compiler are you using, and what version? The console I/O library isn't a standard one (which is fortunate, as you don't actually use it and can remove it from the include list), and the modern C++ header for the standard library is <cstdlib> , not <stdlib> . Also, most of the newer IDEs (including Code::Blocks and the newer versions of Visual C++) all pause after the end of a console program automatically, obviating the need for the system() call (and in turn the include for the standard library). Finally, any newer C++ compiler would require you to use the std namespace for the <iostream> and <string> objects and functions.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I'm not sure why it would give that specific error message; it is more typical of certain types of header problems. You might try using 'g++' rather than 'gcc'; by default, gcc assumes that you're compiling a C program, while g++ is specific to C++.

I would also recommend always using the '-Wall' switch with gcc and g++, like so:

g++ -Wall testing.cpp -o test

This option turns on all of the warnings which the compiler can give you - by default, most of the diagnostic warnings are turned off, but having them turned on is very helpful in debugging.

As for the second shell command, the reason it can't find the file is because you aren't in the directory the file is in, and you haven't told it which directory to look for it. By default, when you open a terminal in Linux, it starts off in your home directory, '/home/john/' in this instance. If the source file is in a folder on your Desktop, you need to either give it the path to the file, or else change directories so that you are in the same folder as the file. In this case, the latter can be done with the simple command cd Desktop/C++ , which should change your current working directory to '/home/john/Desktop/C++/'. If you get confused as to where you are, you can use the command pwd to get your working directory.

BTW, the tilde ('~') in the path of …

anirudh33 commented: informative and its solved :) +2
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The logical OR operator is a short-circuiting operator; when a true result is found in the first clause of the operation, it does not process the second clause. This applies to the clauses as a whole. Operator precedence doesn't enter into it, in this instance.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Having tested this out, I found that the problem is in the conditional of the inner loop. As it is, it not only is skipping possible reverses because it only goes up to i, it is overrunning the end of the array. A workable solution would be

for(j=0;j < n - 1;j++)

You can also shave some run time off by checking for whether any swaps were made on a given pass; if there weren't any, you have sorted the list and can stop.

void bubblesort(char** list, int length)
{
    int i, j, swapped;

    for (i = 0; i < length - 1; i++)
    {
        swapped = 0;

        for (j = 0; j < length - 1; j++)
        {
            if(strcmp(list[j], list[j+1]) > 0)
            {
                swapped = 1;
                swap(&list[j], &list[j+1]);
            }
        }
        if (!swapped)
        {
            break;    /* no swaps made on last pass, sorted */
        }
    }

   /* printf("\nCompleted in %d passes\n", i); */
}

Oh, as a matter of note: please place code-tags around your code samples in the future. So far, the moderators have been kind enough to supply them for you, but formatting the code yourself would go far in gaining your their goodwill.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I think that the problem lies with the getmodelno() function itself, and what you are expecting it to do. As it is written right now, it prints the model number to the screen, but does not return it's value. If you want the function to act as an accessor (also called a getter), then you'd have to write it as:

char* getmodelno()
{
    return lmodelno;
}

You might want to use the string class instead of C-strings, however, as they are much easier to work with.

On an unrelated note: while void main() is accepted by some compilers, strictly speaking the correct usage is int main() according to the standard. While the standard allows compilers to accept void main() for those cases where there is no OS to return to, it is considered a non-portable extension.

I was also curious as to why you were using such an outdated compiler. VC++ 6.0 is from 1998, and there are several more modern compilers available for free, including the newest version of Visual C++ Express. Are you required to use the older version for class? I know several schools use older compilers as a matter of standards (Turbo C++ being the most notorious), but it is in my arrogant opinion a poor practice.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Hmmn, the results were quite different from what I'd expected, for the first line in particular (I suspect my old Lisp biases are showing through on that one). I may need to go back to review certain aspects of the language.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

While I am ordinarily very much in the 'high level first' camp, I have to admit that today's Daily WTF gives a strong argument in favor of making sure new programmers get a strong grasp of low-level techniques.

Then again, the Daily WTF taken as a whole is a strong argument in favor of shotgun mouthwash (especially the notorious 'Tossing Your Cookies' article), so I suppose that taking it too seriously will only be excessively depressing.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

That looks like what I would expect from java.util.Date , NormR1. Good work testing that, however, as it demonstrates that the OP isn't using the standard Date class.

I did some checking, and the SQL Date class ought to print the date in YYYY-MM-DD format by default. I'm wondering just what Date class the OP is using. Again, if you could post the import list, it would be very helpful for us in figuring this out.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Using a DateFormat is not a workaround; is the intended solution when formatting the standard Java Date object to a String . Mind you there are two very different Date classes in the standard Java library: java.util.Date , which is used to hold a generic date and time (as a millisecond counter from 1 Jan 1970 00:00.00, the same as a Unix time_t ), and java.sql.Date , which holds a SQL date value and cannot be used as a general date value. My guess is that you've imported the SQL Date by mistake (something which is easy to do in Eclipse, given how the auto-import tool works), as the utility Date class does in fact have a usable (if not very useful) toString() method. You should be able to tell by looking at the list of imports at the top of your source file.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The issue is that you aren't getting a string value from your Date object; as a result, it is printing the class and hash for today , rather than an useful information. At minimum, you need to use today.toString() , which would give the time and date in UTC format; better would be to use a SimpleDateFormat object to format the date in the manner you need it to appear in.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I was assuming that the sorting was part of the assignment, i.e., something that had to be done manually.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oops. I was so caught up in fixing the syntactic problem that I completely ignored the logical flaws.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

the if statements are incorrect; in Java, you cannot compare a range the way you are trying to do. This is a common misunderstanding, as it makes sense mathematically, but doesn't work in most programming languages.

You need to write out a full clause on each side of the or operator:

import java.io.*;
public class Konata {
    public static void main(String args []) {
        BufferedReader br=newInputStreamReader(System.in);
        int grade,answer=0;

        do {
            System.out.print ("\n Enter grade");
            grade=Integer.parseInt(br.readline());

            if ((grade>=90)||(grade<=100)) {
                System.out.print("\n A");
            }
            else if ((grade>=80)||(grade<=89)) {
                System.out.print("\n B");
            }
            else if ((grade>=70)||(grade<=79)) {
                System.out.print("\n C");
            }
            else if ((grade>=0)||(grade<=69)) {
                System.out.print("\n F");
            }
            else { 
                System.out.print("\n out of range");
            }

            System.out.print("\n Do you want to try again? Press 1 for Yes and Press 0 for No:");
            answer=Integer.parseInt(br.readLine());
        }while (answer==1);
    }
}

Note that I reformatted the code according to the Java standard. You should generally follow this standard, as it makes the code more familiar and more readable.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Could you start by showing us what you've already done?

The heart of this problem is writing a sorting function; however, since there is a small, fixed number of items to compare, it might be easier to do it ad hoc than to write a full function. You could simply do something like this:

set up an integer array of size three
read in the first two numbers
compare the numbers, and put the larger in the array slot 2
put the smaller in the array slot 0
read in the third number
if the third number is smaller than the array[0]
    copy array[0] into array[1]
    copy the third number into array[0]
else if the third number is larger than array[2]
    copy array[2] into array[1]
    copy the third number into array[2]
else
    copy the third number into array[1]

print out the results
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Do you happen to know why they want things in DOS?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Thank you for pointing those errors out, Tonyjv; you are completely correct, and I had overlooked them this whole time.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Well, aside from the fact that you don't declare the eight variables you use to get the bit values, it should work - if that's what you need it to do.

However, assignments like these more often involve converting a binary number in a string, which works a bit differently. Fortunately, there is a fairly easy algorithm for converting strings of any base to a standard integer, and vis versa. The general algorithms (in Python, though they should be understandable well enough if you treat it as pseudo-code) can be found here; you'll want to use the second algorithm, the one titled 'str2int()'.

sergent commented: Helpful +4
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Valid point; I misspoke myself. Thank you for the correction.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

To answer the last question first, the solution is simply to add #include <time.h> at the top of the code file. This automatically copies the structure definition into your code, without setting off alarm bells with the compiler.

Oh, and itoa() is deprecated, and is not part of the standard library; a better solution is to use

sprintf(time1, "%d", tm_min);

As for the original question, well, as I said earlier, chances are a linked list would be what you want. You would re-define the struct as

struct jatekos
{
	char nev[20];
	int dob1;
	int dob2;
	int dob3;
        struct jatekos* next;  
        /* You might use 'kov', perhaps? I don't know Hungarian, I just checked Google Translate for an equivalent and it gave 'következő' */
};

jatekos* head;

You would need to define functions for adding, removing, searching, etc., but those aren't too difficult to write.

The other alternative is to use an extensible array, which Ancient Dragon already explained the basics of.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

What Narue said is pretty much on the money, but the way the answers are given may be a bit confusing. Allow me to re-post an old piece I wrote on DevShed many moons ago:

http://forums.devshed.com/showpost.php?p=2001351&postcount=14

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

actually, I suspect that what he's really looking for with the first question is not to be able to add members to the struct, but to be able to dynamically allocate new structs which would be associated with some other data structure, such as a linked list or a tree.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, there is a project to write a 32-bit version of FreeDOS, called (naturally enough) FreeDOS-32. I don't know if it is an active project or not, but you might consider contributing to it if you are genuinely interested in it.

However, as Ancient Dragon said, DOS is pretty much a dead topic, even where OS development is concerned.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I'm not sure why you're having trouble passing strings, but it certainly ought to work. For example:

def printString(my_str):
    print(my_str)

I suspect where you're having trouble is in passing values to methods, but that too should be straightforward; you simply put the arguments after the self argument.

class Player():
    def __init__(self, inithealth = 10):
        self.inv = []
        self.health = inithealth
        
    def hurt(self, damage):
        print "Hurting player for {0} damage.".format(damage)
        self.health -= damage
        
    def use(self, item):
        if type(item) is not str:
            raise TypeError
        elif self.inv.count(item) < 1:
            print 'There is no {0} in your inventory.'.format(str(item))
        else:
            item.use()
            self.inv.remove(item)
            
    def print_inv(self):
        for slot, count in enumerate(inv):
            print count, + '. ' + str(slot)


if __name__ == '__main__':
    player = Player()
    player.hurt(2)
    print r"Player's health is now at", player.health
    player.use('apple')

(BTW, it is a convention in Python to capitalize the first letter in the name of a class. While you don't have to follow this convention, it will probably save you trouble and confusion if you do. For more on Python typographical rules, see PEP 8.)

TrustyTony commented: Nice work! +13
vegaseat commented: good help +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I recently explained the Python equivalent of the pointer-to-member operator here, and you may want to read through that; however, I suspect that what you want is a reference to the function itself, rather than to call the member function.

In Python, the simple solution is to use... the name of the function. That's it. If you pass the function name without any parameters, it's the same (more or less) as a pointer to a function in C++.

The real problem I see is that you're passing a method rather than a regular function, which means that you would also have to pass an object of that class along with it, assuming you don't know ahead of time the class it is meant to operate on. Alternately, you could write a function that returns a closure containing the method invocation:

New = QtGui.QAction('New',self)
    New.setShortcut('Ctrl+N')
    New.setStatusTip('New File')
    
      
    self.connect(New,QtCore.SIGNAL('triggered()'),QtCore.SLOT('lambda x: x.close()'))

Whether this will work is uncertain to me, given the way Qt passes the functions to the slot. Perhaps an explicit function would work better, I'm not sure - I just don't know enough about Qt to say. Looking at the documentation, however, makes me think that something involving the pyqtSlot() decorator would be called for, and for all I know is already part of the textEdit object you are using.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Would you mind telling us what the different strings represent? (My initial impression was that they were the names of genes and gene complexes, but I'm not certain.) Having some idea of what the data represents might give us some new ideas as to how to manipulate it more effectively.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The single vertical bar is for the bitwise OR operator. What the code is doing is taking the S_IFDIR flag (which indicates if a given file handle is actually for a directory), and overlaying the bitfield for the desired file permissions, which results in the overall file mode value. See here and here for more details.

BLUEC0RE commented: Very informative post +2
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

WolfShield: You've omitted some crucial details here, starting with, what GUI library you're using (I'd normally assume TkInter, since that's bundled with Python, but this doesn't seem like Python/Tk code). While it is not exactly relevant to the code section in question, it does make it harder to judge where the error is occurring.

Tonyjv: If you look, WS is in fact passing the values as parameters when calling calculate() in the equPressedF() event handler. The problem is, the function doesn't seem to be using the passed values, for some reason.

Or perhaps not... I suspect that the error is coming up in equPressedF() rather than in calculate() . WolfShield, could you please post the traceback that you get when you omit the globals?

Where are the values being passed to equPressedF() meant to be coming from? I am guessing that you intend for them to be read from a pair of textboxes, correct? so where are you reading the values in those?

You might want to decompose the code a bit more, separating the implementation of the calculate() function from the GUI code. This should make testing the parts easier. I tried the following successfully:

def calculate(num1, num2, oper):
    """ Function to act as a simple six-function calculator.
    
    arguments:
        num1 -- first argument of the operation
        num2 -- second argument of the operation
        oper -- string representing the operation to perform
    """
    print("calculate() called")
    if(oper=="+"):
        answ = num1 + num2
        return answ
    elif(oper=="-"):
        pass …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

While Gribouillis's answer is correct, it could probably use more explanation, because the dot-member notation is used somewhat differently in C++ than in Python and it may be somewhat confusing.

In C++, variables have an explicit type, unlike in Python, where variables are typeless (type being a property of the objects which variables reference, not the variables which reference them). There are many different types in C++, but for our purposes there are two broad categories that matter: value variables and pointer variables.

All local named variables in C++ are stored on the stack, a system data structure which keeps track of function calls. When a function in C++ is called, all the information needed for that function - both where it needs to return to, and what variables and arguments it has - is pushed onto the stack, and access to the variables is done by offsets into the stack area. Most of the time, you have variables whose values are the actual data you are working with - for example, if you have an integer value, the integer is stored in the very location on the stack which the variable name refers to. You usually don't need to know all of this - the compiler does this part for you - but it is important to understand that the amount of local memory you have for the function is fixed when the function call is made, and that the local values only exist during the lifetime …

TrustyTony commented: You put your heart in it +13
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The easiest solution would be to use a list, and simply append each new object to the list in a loop. To follow your book list example, here's a sample program that does what you seem to be looking for:

class Book (object):
    def __init__(self, title):
        self.title = title


titles = ("The Joy of Snackes", "Tales of Beedle the Bard", "One Human Minute",
          "The King in Yellow", "The Fragile Path", "The Necronomicon")

books = []
for index, title in enumerate(titles):
    books.append(Book(title))
    print(books[index].title)

(I included the part about enumerating the loop just to show how you could then access the individual objects with an index, even in the loop that creates them if needed. You probably don't need to do it quite this way.)

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Is it safe to assume that there is more to this code somewhere? I ask this because the index values never get changed in the code as given, which would result in an endless loop.

As for initializing the arrays to zero, the best approach is the one given by Gerard4143 earlier: iterate through the array of arrays and clear all of the values, before using them arrays. If you want a general solution to clearing blocks of memory (which is exactly what arrays are), you can use memset().

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You have to keep in mind that the goal is to get the month, not the amount. To get that, you need to actually iterate through the months where the rainfall occurred, and save the one which had the highest rainfall. That having been said, this version will return both the month and the amount:

def main ():
    rainfall = rainInput ()
    totalRain = totalRainfall (rainfall)
    average_Rainfall = averageRainfall (totalRain)
    highestMonth, highestMonthly = highestMonthNumber (rainfall)
    print #this is for spacing output
    print 'The total rainfall for the year was: ' +str(totalRain) + ' inche(s)'
    print #this is for spacing output
    print 'The average rainfall for the year was: ' +str(average_Rainfall) +\
          ' inche(s)' 
    print #this is for spacing in output
    print 'The highest amount of rain was', highestMonthly, 'in' , highestMonth


def highestMonthNumber (rainfall):
    month = ['January','Febuary','March','April','May','June','July','August'\
                ,'September','October','November','December']
    highestMonthly = 0
    for m, n in enumerate(rainfall):
        if n > highestMonthly:
            highestMonthly = n
            highestMonth = m
    return month[highestMonth], highestMonthly
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, I'm confused; you appear to have switched suddenly from selection sort to quicksort. Any particular reason?

Selection sort is considerably simpler to implement. Here's a simple variant of it:

def selectionSort(unsorted):
    if len(unsorted) <= 1:
        return unsorted
    else:
        sorted = list()
        element = min(unsorted)
        sorted.append(element)
        unsorted.remove(element)
        sorted.extend(selectionSort(unsorted))
        return sorted

Whereas what you're doing now is more like this:

def qsort(unsorted):
    if len(unsorted) <= 1:
        return unsorted
    
    pivotPos = len(unsorted) // 2
    pivot = unsorted[pivotPos]
    smallerlist = list()
    largerlist = list()
    
    unsorted.remove(pivot)
    
    for x in unsorted:
        if x <= pivot:
            smallerlist.append(x)
        else:
            largerlist.append(x)

    sorted = list()
    sorted.extend(qsort(smallerlist))
    sorted.append(pivot)
    sorted.extend(qsort(largerlist))
    return sorted

Any particular reason for the switch?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The min() function finds the smallest element of a list. If you type min([4, 3, 5, 7, 11, 9, 22]) , at the Python interactive prompt, it returns 3. So you can use it to find the smallest element, as you are saying.

With the selection sort, the idea is not to compare the smallest value with the other values - you already know it is the smallest - but to replace the lowest element with the smallest, then the next lowest with the next smallest, and so on until you have a sorted list. In this case, it is easiest to make a new list rather than moving the elements around, because lists are so inexpensive in Python.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The easiest solution is to use min(), which finds the object in a list that sorts lowest. You can then use remove() on the original list and call selsort() on the remaining part of the original, which can be added to the sorted list with the extend() method.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I found two serious problems with the convert() function. First, you are returning a pointer into a local variable, a variable which is likely to be partially or wholly overwritten by the time you are trying to print it. The solution to this is to one more character buffer and pass that as an argument to convert(); even if the buffer is not used directly, it will hold the data even after the convert() function ends, allowing you to use pointers to walk through it.

More seriously, the function does not address whitespace characters at all. This is a serious problem, because even if you haven't deliberately added any whitespace, the fgets() function will read in the trailing newline character, meaning that the whole function stalls out. Adding another clause to the function to test for spaces and newlines, and walking past them, appears to fix the problems you are experiencing.

char *convert(struct stack *s,char *source, char* dest)  //converting source into prefix
{
    char *t,opr;
    dest[0]='\0';                              //Null added at end of dest
    t=&dest[1];
    while((*source)!='\0')
    {
        if(*source == ' ' || *source == '\n')
        {
            source++;
        }
        else if(isdigit(*source)||isalpha(*source))
        {
            while(isdigit(*source)||isalpha(*source))
            {
                *t=*source;
                t++;
                source++;
            }
        }
        else if(*source==')')
        {
            push(s,*source);
            source++;
        }
        else if(*source=='+'||*source=='*'||*source=='-'||*source=='/'||*source=='$'||*source=='%')
        {
            if(s->top==-1)
                push(s,*source);
            else
            {
                opr=pop(s);
                while(priority(opr)>priority(*source))
                {
                    *t++=opr;
                    opr=pop(s);
                }
                push(s,opr);
                push(s,*source);
            }
            source++;
        }
        else if(*source=='(')
        {
            opr=pop(s);
            while(opr!=')')
            {
                *t++=opr;
                opr=pop(s);
            }
            source++;
        }
    }
    while(s->top!=-1)
    {
        opr=pop(s);
        *t=opr;
        t++;
    }
    t--;
    return t;
}

I've only tested this with some …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I'll look over the code and see if I can find anything that stands out but there is one thing I can say: you would be wise to use fgets(str1, 10, stdin) with instead of gets(str1) , as gets() can all too easily have a buffer overrun and crash the program. The gets() function has been consider deprecated for some time now, though it presumably isn't getting removed from the standard I/O library for reasons of backward compatibility.

As I said, I'll try to find something more relevant to the problem at hand.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

One of the things you need to see as well about segment:offset addressing is that segments can overlap; a segment can begin on any 16-byte paragraph boundary (not page, that was a careless error on my part). It has to do with the particular way in which addresses are calculated in real mode, where the physical address is computed by the system by adding the value of the 16-bit segment offset to a 16-bit local address, with the segment value being offset by four bits:

0000 0000 0000 0000          segment address
     0000 0000 0000 0000     offset address (local address)
------------------------
0000 0000 0000 0000 0000     20-bit linear address

(There is actually a 64Kbyte-16byte section of addressing space that was lost this way in the original design, when the addresses added up to more than 1Mbyte; later systems, which had 24bits and eventually 32-bits of physical addressing would call this the Real Mode High Memory Area, and MS-DOS was hacked to allow it to be used for part of the system software.)

Anyway, the point is that segment addressing in the original x86 was not a straightforward matter of having a series of separate segments one following the other, as one might assume. One aspect of this is that most linear addresses had more than one segment:offset address which could refer to it. For example, both 0000:00f0 and 000f:0000 refer to linear address 000f0.

You might ask why this was done this way. Well, at the time, …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

It depends on how you're handling the inserts, and whether you're using the list as a queues or not. If you are inserting to the end of the list, then having a pointer to the last element is a practical way of speeding up insertions. However, how you insert may depend on how you are using the list.

If you are using the list as a first-in-first-out queue, then it makes sense to have an end pointer, as you would need rapid access to both ends of the list, and would want to insert to the end.

However, if you're using the list as a stack, it would make more sense to insert to and remove from the top of the list, in which case having an end pointer isn't helpful.

If it is an ordered list, you can use the end pointer to see if an inserted element sorts higher than the current end of the list, in which case you can insert to the end directly; otherwise, you would have to traverse the list to find the insertion point. Whether this optimization is worth the trouble would depend on whether you expect most new elements to come at the end of the list or not.