sepp2k 378 Practically a Master Poster

Consider this:

int f() {
    puts("F was called\n");
    return 0;
}

int g() {
    puts("G was called\n");
    return 0;
}

int h() {
    puts("H was called\n");
    return 1;
}

int main() {
    int res1 = (f() && g()) || h();
    int res2 = f() && (g() || h());
    return 0;
}

The order in which the functions are called will be: f, h for res1 and just f for res2. The results will be res1 = 1 and res2 = 0. There is no way to parenthesize the expressions, so that "G was called" or "H was called" would be printed before "F was called".

sepp2k 378 Practically a Master Poster

one step back of the first element of the array

I think that's undefined. As far as I know, the only exception is one past the end of the array. In any other case, any pointer arithmetic invokes undefined behavior if the resulting pointer does not point inside the object that the original pointer pointed into.

3 step back from the first element of array and then taking it back to the 1st or 2nd element

Definitely undefined.

then in my example, what's the difference between order of precedence and order of evaluation ?

If || had higher precedence than &&, we'd get int m = ((i++ || ++j) && k--);. This behaves differently from int m = (i++ || (++j && k--)) in the following way:

In the first case k-- gets evaluated if i++ is true or if ++j is true. In the second case, k++ only gets evaluated if i++ is false and j++ is true. This also means that in the first case it is possible for k-- to be evaluated when ++j was not evaluated, but in the second case k-- can only be evaluated if both i++ and ++j have been evaluated.

So you see: the meaning (and thus the result) of the expression changes with different precedence rules, but the order in which the operations happen stays the same. That is i++ will always happen before ++j (assuming ++j happens at all) and ++j will always happen …

nitin1 commented: awesome !! +2
sepp2k 378 Practically a Master Poster

According to the standard, you may have a pointer that points one past the last element of an array, but no further. So if you have an array of size n and p points to that array, you may do p+n (though you may not dereference it), but doing p + n + 1 will invoke undefined behavior. So, assuming that sizeof(int) is 4, (p += sizeof(int))[-1] would be okay, but (p += sizeof(int) + 2)[-3] would invoke undefined behavior (since p points to an array of four elements in your example).

That said, I'm not aware of any implementation where having a pointer that points past the end of an array will produce anything but the expected outcome (assuming, of course, you don't dereference the pointer).

sepp2k 378 Practically a Master Poster

First note that foo += bar is an expression that increments foo by bar and then evaluates to foo. So t += (p += sizeof(int))[-1]; can be rewritten as:

p += sizeof(int);
t += p[-1];

that should be a little clearer already. Next note that foo[bar] is simply a syntactic shortcut for *(foo + bar), i.e. it adds an offset to a pointer and then dereferences it. So p[-1] accesses the value that's at the address one before the address that p points to now.

Since the value of p is never used again in this function, the fact that p was incremented doesn't really matter. So the clearest way to rewrite the function would be:

void fun(char **p)
{
    char *t;
    t += p[ sizeof(int) - 1 ]; // line xyz
    printf("%s\n",t);
}

Note that, since t is never initialized, the whole thing invokes undefined behavior. I think that the += is an error and what was intended might be:

void fun(char **p)
{
    char *t;
    t = p[ sizeof(int) - 1 ]; // line xyz
    printf("%s\n",t);
}
sepp2k 378 Practically a Master Poster

rubberman, your conditional logic code has breaking problems when entering an illegal operator.

So does yours (after fixing the assignment issue). As I pointed out earlier, you need to make it so that the result only gets printed, if a legal operator has been entered.

sepp2k 378 Practically a Master Poster

Another thing to note is that your ifs are all indepenedent (i.e. they're not else ifs). So the else only applies to the last if. That means that once you've fixed the = vs. == issue, the else will execute whenever you entered an operator other than *.

Anothernother thing to note is that you print the result of the calculation even if the else executed. In that case result would be uninitialized invoking undefined behavior (most likely printing a garbage value to the screen).

sepp2k 378 Practically a Master Poster

There's nothing wrong with the code per se. From your output it looks like $mean_data_sorted[$i] is a string that ends with a line break. So the quickest way to fix your issue would be to chomp @mean_data_sorted before you iterate over it.

Depending on how you create mean_data_sorted, it might also be possible to simply not put an line breaks in there in the first place.

sepp2k 378 Practically a Master Poster

Instead, it is acting as if the temperaturef used in the top-level code has already been set to a float value, as it is on line 52.

It is on line 52, but since line 52 runs before the display_temp function is called on line 55, the variable has indeed already been set when line 25 executes.

This shouldn't be in scope inside of display_temp().

Variables set at the top level are global and thus always in scope unless they're being shadowed by a local variable.

sepp2k 378 Practically a Master Poster

To make the approach used in the code posted in this thread work, you'd write a recursive function that calls readline and then recurses until readline returns eof. That said, it would be much easier to just use in-lines.

sepp2k 378 Practically a Master Poster

You can't compare char*s using the == operator. You need strcmp from the cstring header for that, but a better solution would be to use std::strings instead of char*s. std::strings can be compared using ==.

sepp2k 378 Practically a Master Poster

If you just write int sum or int sub, you'd be using those variables uninitialized in your loop, which would invoke undefined behavior. So don't do that.

Your while loop will run until value is either equal to 'q' or 'Q'. This will only happen if the user enters 113 or 81 as the input because value is an int, not a char. If the user entered q or Q, that would simply be discarded as invalid input and value would not change.

sepp2k 378 Practically a Master Poster

If you want a better answer, you should point out what's wrong with the existing answer, so that I (or people in general) know what to improve on.

sepp2k 378 Practically a Master Poster

Okay, so the fact that you don't 0-terminate inputNumber doesn't seem to bite you here (presumably because the unitialized elements of inputNumber happens to be 0 on your system). You should definitely still do that though - something as trivial as adding a function call to your code might break it.

The problems you are encountering seem to be the result of the second problem that I described.

sepp2k 378 Practically a Master Poster

When do you get the segmentation fault? Right away or do you get some output before the segmentation fault? And when you input a 2-digit number, do you get wrong output for both "The inputNumber variable is :" and the result or only the latter?

One problem I see is that you don't 0-terminate inputNumber.

Another problem is that your while loop can cause backwardsCounter to become negative. If strlen(inputNumber) is 1 for example, the following happens:

Your while loop runs for the first time with strlen(inputNumber) and backwardCounter both being 1. It will copy inputNumber[1] (which will be the 0-terminator) to inputNumber[2]. Note that inputNumber[1] still contains the 0-terminator, so strlen(inputNumber) is still 1. You decrement backwardCounter by 1, so it is now 0 and inputNumber[0] is set to '0'.

Now the loop runs a second time with strlen(inputNumber) being 1 and backwardCounter being 0. inputNumber[0] (which is '0' because you just set it to that) is copied to inputNumber[1]. backwardNumber is decremented.

Now backwardNumber is -1 and strlen(inputNumber) is 2, so the loop runs a third time. inputNumber[-1] is copied ... BAM! Segmentation fault!

sepp2k 378 Practically a Master Poster

== is an operator that takes two operands and produces the value true if the operands are equal and false if they're not. The boolean values produced by == aren't any different than the boolean values stored in your variables. There is no context in which using == would be okay, but using a boolean variable would not be (assuming there isn't some stupid operator== overload in play that returns something other than a boolean). A boolean expression is a boolean expression.

Same goes for !: you can use it anywhere you can use any other boolean expression.

sepp2k 378 Practically a Master Poster

No, it's perfectly fine to write if(variable1 && variable2). What makes you think that doesn't work?

sepp2k 378 Practically a Master Poster

Making a local variable static means that it will remember its value between multiple calls of the same function. It does not mean that other function can access that function. A variable that is defined within one function can't be accessed from other functions (at least not directly - it's possible through pointers or references of course). Making the variable static doesn't change that.

sepp2k 378 Practically a Master Poster

don't like the whites pace rule.does ruby has it?

Ruby does not have significant indentation. However it does have a couple of instances where spaces between tokens matter (like a[b] meaning "access the bth element of the variable or nullary method a" while a [b] means call the method a with the array [b] as its argument).

sepp2k 378 Practically a Master Poster

You set ret to minsol even if minsol was never assigned in the loop. This means that when you reach a point where all items in the list cost more money than you have (which will happen eventually if no perfect solution is found), ret will be set to an empty vector.

You should only set ret to minsol if minsol has been assigned to at least once (or you could initialize minsol to ret, which would have the same effect and would be somewhat analogous to initializing min to desired).

PS: In the future it would be nice if you explained in what way your program failed (i.e. "the part of the output on the left side of the equals sign is empty, but the right side is correct") instead of just saying that it failed. That way I wouldn't have to copy your code onto my machine, compile and run it just to see what the problem is.

sepp2k 378 Practically a Master Poster

When defining template functions or member functions of template classes, you can't put the definitions in a separate file from the declaration. Both the declaration and the definition need to be visible to the code that uses your functions. So you need to put the contents of Dynqueue.cpp into Dynqueue.h instead.

And yes, that's the complete opposite of what you're usually supposed to do, but that's how it is.

sepp2k 378 Practically a Master Poster
if (desired-options[i]>0.0)

You never check whether desired - options[i] == 0. You should push the item on the vector and return 0 in that case.

PS: Is there a specific reason that you're using 0.0 and not just 0? I realize you want the code to work with all types of numbers, but, unless I'm missing something, that would still be the case when using 0 and using 0 would avoid unnecessary conversions to double.

No NP-complete problems are not unsolveable... its just that they are unsolveable in POLYNOMIAL time

Unless P=NP.

sepp2k 378 Practically a Master Poster

It will not import both. When you import a module it searches through the available modules and imports the first one it finds with the given name. The order in which it goes through the modules is explained in this section of the docs:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  • the directory containing the input script (or the current directory).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • the installation-dependent default.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

So since sys is a built-in module, it will always be found before your sys.py.

sepp2k 378 Practically a Master Poster

Including the newline character?

Yes, input consumes the newline character at the end of the line. If it didn't, you'd have to call some other function to discard the newline, every time after you use input. That would be absolutely stupid. I've never seen any "read the whole line" function that didn't consume the newline (that is either return it as part of the string or just read it and throw it away -- the latter being what input does).

The problem that you're describing generally only occurs if you mix input methods that don't discard leading whitespace (like C's getchar, fgets or scanf("%c",...), C++'s getline or Python's input) with ones that do (like C's scanf("anything else") or C++'s istream.operator>>). So if someone only ever uses input, there will be no problem.

sepp2k 378 Practically a Master Poster

I would assume that input() has a similar problem as you'd see with scanf() in C. Something gets left in the input stream that a subsequent call to input() will terminate successfully on without blocking for the user.

input reads a whole line. Nothing can get left in the input stream.

Ok, now I get... [an error about 'Christopher' not being defined]

According to that error message, you must be using Python 2, not Python 3. In Python 2 input will try to evaluate the input as a Python expression, so if you enter Christian, it thinks that that's a variable and complains about it not being defined. Use raw_input to read a string without evaluating it. In Python 3, input acts like Python 2's raw_input, so this wouldn't happen in Python 3.

sepp2k 378 Practically a Master Poster

these are input to me

Input how? The problem description doesn't clarify that. Do you just write your function with a given signature and the online judge provides a main function that calls your function? Or do you read the input from stdin (which is what you'd do in most online judge systems that I'm familiar with)? In the latter case you can just keep track of how many items you've read from stdin.

if you have participated in any Topcoder SRM then you will better 'understand' this.

I haven't.

Edit: Oh, I hadn't seen the second page of your link. Looks like it's the former version (i.e. you write the function only and the main function is supplied). Then it's just not possible (unless a constant N were defined for you, but you already said that's not the case). No idea how others could submit a working solution for that problem.

sepp2k 378 Practically a Master Poster

Alternatively, you can add a request for input at the end of your program to force the process from terminating until input is provided.

But he already did that:

input("\n\nPress the enter key to exit.")
sepp2k 378 Practically a Master Poster
u_char * newdata[raw_len]

C++ does not allow variable length arrays, that is when declaring an array like this, the length must be a constant. So raw_len is not allowed as the length. There is no standard way to create arrays of unknown size on the stack. However some C++ compilers do allow variable length arrays as an extension and many libcs also contain an alloca function that allocates memory on the stack instead of the heap.

PS: If the above code did work, it would declare an array of u_char pointers, not an array of u_chars. It should be u_char newdata[raw_len] to create an array of u_chars.

sepp2k 378 Practically a Master Poster

so the if statement isn't required?

You only need the if statement if you want your code to act differently depending on whether it's imported or run as a program.

what is the __name__ by default?

If the Python file is run as a program (i.e. using python bla.py, a double click in the file manager (assuming you have set it up, so that that actually runs the program rather than opening it in an editor), using ./my_file.py in combination with chmod +x and a shebang line -- whichever), __name__ will be "__main__". If it is imported from another Python file or from the Python shell by writing import my_module, __name__ will be "my_module" where my_module is the name of your file without the .py extension.

I don't understand what you mean when you say "if the Python file is invoked directly" does that mean double clicking on a .py file

See above.

or can I run a .py file using python?

That too.

Basically running it directly refers to any means of running your Python code other than using it from other Python code.

I think import can be used to access functions from another .py file

Yes.

sepp2k 378 Practically a Master Poster

You can name your function anything you want, but the name has to be "__main__". That's not about the function being called. "__main__" is simply the value that __name__ gets if the Python file is invoked directly instead of being imported.

PS: Calling your function both inside and outside of the if means that your function will be called once if the file is imported and twice if the file is run directly. That doesn't seem like what you'd want.

sepp2k 378 Practically a Master Poster

i have already tried i<N but this is giving error as N is undefined.

Locally or on the online compiler? Can you post the exact wording of the assingment? Or post a link to it if it's publically accessible?

by the way in CSHARP ,Length is giving the length of the array.

Yes, but C++ isn't C#. C++ arrays simply don't know their length. They're just a chunk of memory with no assoicated metadata.

sepp2k 378 Practically a Master Poster

The error message is saying that you specified the default value for find_words both in the declaration and the definition of the function. You're only supposed to do it in the declaration.

sepp2k 378 Practically a Master Poster

A Python file can either be run as a program or it can be imported by another Python file as a library. if __name__ == "__main__": means "only run the following code, if this file was run as a program - not imported as a library".

This is useful if you want other program's to be able to import this program's functions without actually running the program.

sepp2k 378 Practically a Master Poster

i dont know what is 'N' so i cant use it in loop.

What do you mean? Can't you just literally write i < N? Did you try it?

If the problem description says that the size is N, then I'm going to assume that they define a constant N that you can then use. Otherwise writing that would be nonsense.

sepp2k 378 Practically a Master Poster

in input specification it is mentioned both of array size will be equal to 'N' and nothing else.

That's enough, isn't it? So, just use i < N as your loop condition.

sepp2k 378 Practically a Master Poster

Maybe the question says something about the array ending with a specific number? Like the last element of the array might be 0 or -1? In that case you can find out the size of the array by going through the array until you encounter that number. Or possibly it says that the arrays will have a specific size. If the question doesn't mention anything like that, it's simply not solvable.

sepp2k 378 Practically a Master Poster

The items sys.argv are strings. So if the user gives 949 as the argument, code will be the string '949', not the number 949. Since == does not automatically convert between different types, 949 == '949' will be false -- only '949' == '949' would be true. So if you change it to code == '949', it will work.

You should not use code in '949'. That will not do what you want. in checks whether the left string is a substring of the right string. So if code would be '9' for example, code in '949' would be true.

sepp2k 378 Practically a Master Poster

Even if you could define methods within methods, why would you expect Fnction to become a static method of the Stuff class? The definition is not inside the Stuff class - not even indirectly.

sepp2k 378 Practically a Master Poster

I think you may have misunderstood my suggestion. re.sub can be called with a function (or method or other callable object) as an argument. That function will be called with a match object as its argument for every occurrence of the pattern.

So you can define a function (or method) that keeps track of a counter to decide whether to perform the replacement or not. Then you can call re.sub with that function as its argument. No loop necessary.

I'm not sure whether that's the simplest solution to your problem, but it's the first that I thought of.

The only other simplish alternative that I can think of would be to loop over all indices in the string, check whether the pattern occurs at that index, increase the counter if so and add the replacement string to the result string and skip a number of character equal to the replacement's string's length if the counter is equal to your n - otherwise add the character at the current index to the result string (which is probably best represented as a list of strings that is joined after the loop). The version using re.sub is probably easier to implement though.

sepp2k 378 Practically a Master Poster

One way to do it would be to use re.sub with a function argument. That function could increase a counter every time it's called and then either return the given string unchanged or return the replacement string depending on whether the counter is equal to your n.

sepp2k 378 Practically a Master Poster

`autodetect': Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)

Do you have one of the runtimes listed at the URL installed? If not, that's your problem. You need to install one of them.

If you do have one of them installed, it might not be in your $PATH. Change your $PATH or create a symlink in one of the directories that is in your $PATH, so execjs can find it.

sepp2k 378 Practically a Master Poster

Your second example just catches one specific exception.

It catches all exceptions that are a subclass of Exception. Since every exception is a subclass of Exception, that means it catches all exceptions -- just like the first one.

sepp2k 378 Practically a Master Poster

That's not true. item is every element from the list of dictionaries p so item is a dictionary.

Right, my mistake, the error was that you called sum on the result of get_average. get_average returns a float, but sum expects an iterable.

sepp2k 378 Practically a Master Poster

You get that error because you call with get_average with item as its argument, but item is a float and get_average expects to get a list, not a single float.

sepp2k 378 Practically a Master Poster

You came across what error? If you're getting an error message, please post it. If your code acts differently than you want it to, please explain what you expect and in what way it acts differently.

PS: Using return inside a for loop like you're doing, will likely not do what you want (though that does of course depend on what you want). return leaves the function immediately, so when you do it in a loop (without an if around it), that means you will exit the loop after the first element and never even look at the other elements.

PPS: On line 26 you misspelled return. You can tell because it's not highlighted as a keyword.

sepp2k 378 Practically a Master Poster

You defined your methods using the names Area and Perimeter with a capital A and P respectively. You tried to call them as area and perimeter with a lower case a and p. Since Python is case sensitive, that does not work.

Also: If you want to call a function or method you need to use parentheses, like this: a.Area(). Without the parentheses, you only get is a reference to the method without calling it.

sepp2k 378 Practically a Master Poster

Maybe it would be more fruitful to attempt to learn Python rather than hoping that someone will do your homework for you (spoiler alert: noone will).

PS: Please don't post the same question on multiple sites on the internet at the same time. It's against the rules here and it's rude.

sepp2k 378 Practically a Master Poster

You're invoking undefined behavior, the output could be anything (notably gcc will produce different output with -O1 than with -O2). It is highly unlikely that your compiler writes a specific byte sequence into bytes used for padding. Rather I'd expect it simply leaves them untouched, so they will just have whatever value previously resided in that memory location. If you move your code into a function, you'll probably notice that the value of b will change depending on whether or not you call other functions before calling your function.

For example the following code, compiled with gcc without optimizations, will produce different results on my system depending on whether or not I comment out the call to g():

#include <stdio.h>

void f()
{       
    union u
    {   
        struct s{int a;int b}n;
        struct ss{int c;long d}ni;
    } uu;
    uu.ni.c=42;
    uu.ni.d=23;
    printf("%d %d",(uu.n.a),(uu.n.b));
}

void g() {
    int x=1, y=2, z=3, a=4;
    printf("%d %d %d %d\n", x, y, z, a);
}

int main() {
    g();
    f();
    return 0;
}

When I compile without optimizations and call g, b will have the same value that z had in g -- changing z will change the value of b. When compiled with optimizations, b will always be 0 -- whether I call g or not.

sepp2k 378 Practically a Master Poster

%c reads any character, including whitespace. So since you still have a space or newline in the buffer from the last scanf, it will just read that. If you use the format string " %c" with a space in front of the %c, it will discard all whitespace before it reads a character.

Oh and your initial error was because you had an else after an opening brace, but I suppose you've figured that out already.

sepp2k 378 Practically a Master Poster

It means "Text means a character array of size 80", yes. There's no such thing as an array of typedefs because typedefs are a compile-time concept only - they're not something that can be stored in arrays.

The syntax of a typedef is basically the same as that of a variable definition (except for the keyword typedef in front obviously). The name of the typedef goes where the variable name would usually go and the type that that variable would have is the type that's being aliased. So since char Text[80]; would define a variable named Text that stores a character array of size 80, typedef char Text[80]; defines a typedef named Text that describes character arrays of size 80.

sepp2k 378 Practically a Master Poster

What do you mean by "oops"? I assume the oop part stands for Object Oriented Programming. What does the s stand for?

Anyway object oriented programming in Ruby isn't fundamentally different than in other languages, though obviously the fact that Ruby is dynamically typed and otherwise also very dynamic makes it quite a bit different from C# and Java in general. It's object orientation is also much more inspired by small talk than the languages you mentioned, but that affects the terminology more than anything else. It's also different from Java that every value (including integers) is an object with methods.

The exact semantics of private and protected methods also differ from those in C# and Java. Specifically private in Ruby means that a method can only be called on the current object (and not on other objects of the same class) and protected means that the method can also be called on other objects of the same class (or a subclass). You can always access superclass methods from a subclass even if they're private.