Implementation of a list-like array This is a follow up question for this question:

  Implementation of a dynamic list-like array

This is an implementation of an array that behaves like a list, granting me an easy and quick way to:

quickly add items
iterate over them without caring for empty spots in the array
quickly remove iterated items

After following user rolfl answer I revised my class to this

import java.lang.reflect.Array;
import java.util.Iterator;
import java.util.stream.IntStream;

public class BucketArray<T> implements Iterable<T> {

    private final T[] mItems;
    private final int[] mSlots;
    private int mSlotsTop = -1;

    public final int size;

    private int mIteratedIndex = -1;

    @SuppressWarnings("unchecked")
    public BucketArray(Class<T> cast, int size) {
        this.size = size;
        mItems = (T[]) Array.newInstance(cast, size);
        mSlots = IntStream.range(0, size).toArray();
        mSlotsTop = size - 1;
    }

    public int add(T item) {
        if (item == null)
            return -1;
        if (mSlotsTop < 0)
            return -1;
        final int slot = popSlot();
        mItems[slot] = item;
        return slot;
    }

    public void addAll(T... items) {
        for (T item : items)
            add(item);
    }

    public T get(int i) {
        if (i < 0 || i >= size)
            throw new IndexOutOfBoundsException();
        return mItems[i];
    }

    public int getIteratedIndex() {
        return mIteratedIndex;
    }

    public boolean remove(int i) {
        if (i < 0 || i > size)
            return false;
        if (mItems[i] == null)
            return false;
        mItems[i] = null;
        pushSlot(i);
        return true;
    }

    public void remove(T item) {
        remove(indexOf(item));
    }

    public boolean removeIterated() {
        return remove(mIteratedIndex);
    }

    public boolean isFull() {
        return mSlotsTop == -1;
    }

    public boolean isEmpty() {
        return mSlotsTop == size - 1;
    }

    public int numFreeSlots() {
        return mSlotsTop + 1;
    }

    public int indexOf(T item) {
        for (int i = 0; i < size; i++)
            if (item == mItems[i])
                return i;
        return -1;
    }

    private int popSlot() {
        return mSlots[mSlotsTop--];
    }

    private void pushSlot(int s) {
        mSlots[++mSlotsTop] = s;
    }

    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {
            private int index = -1;
            {
                if (mIteratedIndex != -1)
                    index = mIteratedIndex;
            }

            @Override
            public boolean hasNext() {
                do {
                    index++;
                    if (index >= size) {
                        mIteratedIndex = -1;
                        return false;
                    }
                } while (mItems[index] == null);
                return true;
            }

            @Override
            public T next() {
                mIteratedIndex = index;
                return mItems[index];
            }
        };
    }
}

Major changes:

add() method now ignores null and returns the index of the
inserted item so it can be used with get() and remove().
After some thought, the remove() method mostly used in the context of an iteration, so I added  removeIterated() method that removes the currently iterated item in the scope of an iteration being made.
Name of the class changed to BucketArray from BagArray because it sounds better.

Usage example in deleting duplicated integer values:

public static void main(String[] args) {
        BucketArray<Integer> mBucket = new BucketArray<Integer>(Integer.class,20);
        mBucket.addAll(10, 20, 30, 20, 20, 30, 10, 40);
        // bucket is: 40, 10, 30, 20, 20, 30, 20, 10
        for (int a : mBucket)
            for (int b : mBucket)
                if (a == b)
                    mBucket.removeIterated();
        // bucket is now: 40, 10, 30, 20
    }

Potential bug #1

The problem of using a class variable mIteratedIndex that is modifiable in every new Iterator instance created is simply, multiple such instances cannot iterate through the contents reliably.

Potential bug #2

This is also related to Iterator in the hasNext() method: calling it twice without a next() effectively skips one element. Usually, the iteration state should not be modified when doing a hasNext(), but you have a index++ inside it.

Potential bug #3

The other problem with having index++ inside the hasNext() is that callers cannot reliably retrieve the next() element without calling hasNext() first.

Illustrating all bugs

public static void main(String[] args) {
    BucketArray<String> instance = new BucketArray<>(String.class, 3);
    instance.addAll("first", "middle", "last");
    Iterator<String> i1 = instance.iterator();
    i1.hasNext();
    i1.hasNext();
    System.out.println(i1.next());
    Iterator<String> i2 = instance.iterator();
    i2.hasNext();
    System.out.println(i2.next());
    System.out.println(i2.next());
    i2.hasNext();
    System.out.println(i2.next());
}

Output:

middle
first
first
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

i1.hasNext() has to be called before i1.next(), else there will be an ArrayIndexOutOfBoundsException: -1 error. When i1.hasNext() is called twice in succession, "middle" is returned from calling i1.next(), skipping the first element.

When we have a new i2 Iterator, it starts from where i1 left off, which bizarrely returns "first" since that was stored as the final element of the internal array - is this expected? Regardless, calling i2.next() twice returns the same value, when it shouldn't. Finally, calling the pair of hasNext()/next() methods triggers the ArrayIndexOutOfBoundsException: 3 error as i2 would have iterated past the contents of the array.

Try using ArrayList:

import java.util.ArrayList;

It's a dynamic array and has features such as insertion, deletion, etc.


Ohms law calculator + whitelist of user. Learning use I've been learning a ton of c++ lately on Codecademy and I'm soon done with the course of c++.

(Still need to learn classes, object-oriented programming and harder projects.)

But I wanted to get a review of my recent program.

And I also wanted to know if its possible to make an Unique ID, that only fits me, kinda like the cicada.

Psst, the program is to solve Ohm's Formular in physics and actively takes input to solve exactly your case.

Leave suggestions on what I could do better in this project + what I should try to program next too.

//Include
#include <iostream>
#include <string>
using namespace std;

 int main(){

    //Declare variables
    double Wolt;
    double Ohm;
    double Amp;
    std::string Formular;
    std::string Username;
    std::string Whitelist;

    //Login sequence:
    std::cout << "Hvad er dit username?: ";
    cin >> Username;

    //Whitelist
    Whitelist = "Fred267s", "Seb4572s", "Popp4593s";

    //Check if username is on whitelist
    if (Username == Whitelist){

        std::cout << "Velkommen til fysik formel udregner til strøm " << Username << " \n";
        std::cout << "Lavet af Frederik Schmidt 1.S \n";
    }

    //If username is NOT on the whitelist
    else if (Username != "Fred267s", "Seb4572s", "Popp4593s" ){

        std::cout << "Sorry, you do not have access! \n";
        return 0;
    }

    //Questions
    std::cout << "Hvad er det du skal udregne? ";
    cin >> Formular;

    //Wolt formular

    if (Formular == "Wolt"){

        //Questions
        std::cout << "Hvad er Ohmen?: ";
        cin >>Ohm;
        std::cout << "Hvad er Amperen?: ";
        cin >> Amp;

        //Formular
        Wolt = Ohm*Amp;

        //Return
        std::cout << "Volten er: " << Wolt << " \n";
    }

    //Amp formular

    else if (Formular == "Amp"){

        //Questions
        std::cout << "Hvad er Volten?: ";
        cin >>Wolt;
        std::cout << "Hvad er Ohmen?: ";
        cin >>Ohm;

        //Formular
        Amp = Wolt/Ohm;

        //Return
        std::cout << "Amperen er: " << Amp << " \n";
    }

    //Ohm formular

    else if (Formular == "Ohm"){

        //Questions
        std::cout << "Hvad er Volten?: ";
        cin >>Wolt;
        std::cout << "Hvad er Amperen?: ";
        cin >>Amp;

        //Formular
        Ohm = Wolt/Amp;

        //Return
        cout << "Ohmen er: " << Ohm << " \n";
    }

    //If the Formular inputtet is NOT on the list.

    else {

        cout << "Error in the formular, please try again!";

    }
}

Don't

using namespace std;

This doesn't do what you want (only first one works):

    //Whitelist
    Whitelist = "Fred267s", "Seb4572s", "Popp4593s";

    //Check if username is on whitelist
    if (Username == Whitelist){

[It's also a VERY dodgy access control mechanism!]

I don't like asking user for a string describing the "Formula". How does the user know they should type "Wolt"? What if they type "wolt" instead? I think it would be more reasonable to show 3 choices:

1 - Wolt    2 - Amp    3 - Ohm

Please Enter (1-3):

And then clean the user input checking if it is a valid integer between 1-3 and then represent the choice internally using a Class enum in your code.

This will open up a range of oppotunities to use functions in your code.

enum class Formula ( wolt = 1, amp = 2, ohm = 3 );

...

Formula prompt_formula() {
  // code to read from std::cin clean input and cast to enum class
}

Then try to find a way to add even more structure to your program rather than one huge if/elseif/else statement. I am not going to give you the code, because that would defeat the purpose, but your main function should be more like this:

int main() {
  explain_usage();
  Formular form = prompt_formular();
  auto [label, answer] = compute(form);
  print_answer(label, answer);
}

I could go on, but that's probably plenty to get on with for now.

People are so weird about using namespace std;. If it's a main.cpp file and you promise not to rename it like main.h to include into something else, it's fine and reduces noise. Are you seriously worried about needing to write colliding names like cout or string? It's a reasonable habit to build to qualify names since it will be necessary in larger codebases, but that rationale is premature for single file learning code.

Mixing std::cout with cin is a mistake though. To a reader, that implies there's some sort of significant difference between the two, like cin is not of the std:: namespace because otherwise why would the author specifically qualify cout?

Use a formatter like clang-format. Your main function is indented by 1 which I'm pretty sure is unintentional. You should never need to think too much about formatting in any language.

Compile your code with warnings on, e.g. -Wall. I got:

<source>: In function 'int main()':

<source>:21:41: warning: right operand of comma operator has no effect [-Wunused-value]

   21 |     Whitelist = "Fred267s", "Seb4572s", "Popp4593s";

      |                                         ^~~~~~~~~~~

<source>:21:52: warning: right operand of comma operator has no effect [-Wunused-value]

   21 |     Whitelist = "Fred267s", "Seb4572s", "Popp4593s";

      |                                                    ^

<source>:31:50: warning: right operand of comma operator has no effect [-Wunused-value]

   31 |     else if (Username != "Fred267s", "Seb4572s", "Popp4593s" ){

      |                                                  ^~~~~~~~~~~

Which would have clued you into that issue automatically.


CommandBinding refresh on parameter changed I need the command I am executing on a datagrids context menu to know which column was clicked on.

XAML

<DataGrid x:Name="dataGrid" ItemsSource="{Binding Table}" ContextMenuOpening="DataGrid_ContextMenuOpening">
    <DataGrid.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Add Column" Command="{Binding AddColumn}"/>
            <MenuItem Header="Remove Column" Command="{Binding RemoveColumn}"/>
        </ContextMenu>
    </DataGrid.ContextMenu>

</DataGrid>

Code behind:

private void DataGrid_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
    var current = e.OriginalSource as DependencyObject;
    while(current != null && !(current is DataGridCell))
    {
        current = VisualTreeHelper.GetParent(current);
    }
    var cell = current as DataGridCell;
    foreach (var item in dataGrid.ContextMenu.Items.OfType<MenuItem>())
    {
        item.CommandParameter = cell.Column.DisplayIndex;
        (item.Command as DelegateCommand<object>)?.RaiseCanExecuteChanged();
    }
}

I'm having to break MVVM by having the view tell the VM command that its execution has changed because the command binding doesn't seem to refresh on the parameter changing. Is there a better way to do this?

I'm having to break MVVM by having the view tell the VM command that its execution has changed because the command binding doesn't seem to refresh on the parameter changing.

The fundamental problem here seems to be that MenuItem tests whether (in effect) Command.CanExecute(CommandParameter) to update its own Enabled property when Command changes, but not when CommandParameter changes.

It seems to me that the least inelegant way of working around this (IMO) bug in WPF is to subclass MenuItem and use DependencyProperty.OverrideMetadata to register a callback on CommandParameterProperty which updates an overridden IsEnabledCore property. To really do it properly you'd want to also override metadata for CommandTargetProperty and handle RoutedCommand specially, as in CommandHelpers.CanExecuteCommandSource.

An alternative approach, which would be hackier and require more XAML but wouldn't get quite so deep into the inner workings of WPF, would be an IMultiValueConverter which takes two parameters (the command and the parameter) and returns a parameterless command. Then you could set up multibindings such that a change in the parameter causes the MenuItem's Command to change, triggering its CanExecute test.

Both of these approaches would require changes in the XAML of all the grids, but no per-grid codebehind. They would also eliminate the assumption, which IMO is one of the nastiest problems of the codebehind in the question, that all commands are instances of DelegateCommand<object>.

(The other nasty problem is that if the while loop is broken because current == null, the body of the second loop will throw a NullReferenceException).

Here's an example using the CommandParameter. It's a little verbose, but ContextMenu bindings often are.

<DataGrid x:Name="dataGrid" ItemsSource="{Binding Table}">
    <DataGrid.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Remove Column" Command="{Binding RemoveColumn}"
                      CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.CurrentColumn.DisplayIndex}" />
        </ContextMenu>
    </DataGrid.ContextMenu>
</DataGrid>


Pythonic way to count if a value is 'NaN' in a dictionary of dictionaries I have a dictionary of dictionaries with several values. I want to count all the entries that do not contain 'NaN' (Not a Number in a string).

for each in enron_data:
    if enron_data[each]["salary"] !='NaN':
        counter += 1

    if enron_data[each]['email_address']!='NaN':
        valid_email +=1

I'm not familiar with list comprehensions, but I'm pretty sure there's might be a more pythonic way to achieve this.

Can anyone share pythonic advice?

Thank you

If you want this to use a comprehension, you need to get the sum of each each in enron_data, where eachs salary is not 'NaN'. As highlighted by the word exercise, you should notice that each is probably not the best variable name for this. Take the following example:

  you need to get the sum of each boat in boats, where the boats cost is not 'NaN'.

Which is easier to read. With Python it's the same, and is why good variable names are advised.

And so you'd want to do:

counter += sum(enron_data[each]["salary"] !='NaN' for each in enron_data)
valid_email += sum(enron_data[each]["email_address"] !='NaN' for each in enron_data)

If enron_data has a function like dict.values, or better dict.itervalues, then you'd want to use that instead. The latter one is simply a version of the former with better memory usage.

And so you could instead use:

counter += sum(each["salary"] !='NaN' for each in enron_data.itervalues())
valid_email += sum(each["email_address"] !='NaN' for each in enron_data.itervalues())

I don't think this approach is that much better than your current, but you could make it a function, to reduce code duplication, but whether it's better ultimately comes down to how you're using it.

But it's definitely better than the answer you provided. There's no need to create a new dictionary, it changes memory usage from \$O(1)\$ to \$O(n)\$, is harder to read, and is slower, as it requires more effort to create a dictionary, then to sum booleans.

The answer is the following:

how_many = len(dict((key, value) for key, value in enron_data.items() if value["salary"] == 'NaN'))

I had a classmate explain it to me. Suggested answer in the comment sections above don't meet the requirements.


Finding the average of each row in a CSV file I am getting back into python after a year of not doing it at all. I just wrote a bit of code to create a file that looks like this:

1,2
1,1,1,1
-1,0,1
42,17

Then I decided to take the average of each line and put it into a list. For this I wrote the following:

def line_averages():
    out_file = open("data.csv", "w") #create data file
    out_file.write("1,2\n1,1,1,1\n-1,0,1\n42,17") #write numbers into data file
    out_file.close()

    f = open("data.csv", "r") #read data file
    lines = f.readlines()
    avLines= [] #create a list to put averages into
    for line in lines:
        line2 = line.replace("\n", "") #remove /n from lines
        line2 = line2.split(",") #split the lines by commas
        Nlines = [] #create a list to put floats into
        for i in line2:
            i = float(i)
            Nlines.append(i) #put the floats into the list
        sums = sum(Nlines) #total up each line from the file
        avLines.append(sums/len(line2)) #put the averages of each line into a list
    return avLines

I'm pretty happy as this does exactly what I wanted but I can't help but wonder if it can't be shortened/simplified. It seems a bit inefficient to me to have lots of "placeholders" (like  Nlines or line2) which are used to do an operation rather than being able to do the operation directly on them. What would you guys do (if anything) to make this more compact? I'm sure it could be done more succinctly!

Firstly, note that you are not closing the file after opening it. A Better way to read from a file would be to use the with statement. Read What is the python “with” statement designed for? to know more about the with statement.

The code would be,

with open("data.csv") as filename:
    # Code Follows

Other things to note here are

The mode of the open statement is 'r' by default and hence, you don't need to explicitly mention it.
Use a meaningful variable name like filename. This is to help your future self from not asking What is the f?

Now coming to the core of the problem. You can use the fileobject directly to iterate over the lines, You do not need to read the entire file into a list. This is helpful for large files. The code will be

for line in filename:
     # Code follows

The line line2 = line.replace("\n", "") is quite inadequate as there might be other whitespace like a trailing space or a \r. To solve all these issues, you can use str.strip.

stripped_line = line.strip()

Again, Note the name of the variable. Coming to this code block

line2 = line2.split(",")
Nlines = []
for i in line2:
    i = float(i)
    Nlines.append(i)
sums = sum(Nlines)

You can solve this issue using split and a generator expression.

stripped_line  = stripped_line .split(',')
line_sum = sum(float(i) for i in stripped_line)

Alternatively you can use map

line_sum = sum(map(float,stripped_line))

(You can use literal_eval to directly do sum(literal_eval(stripped_line)), But the string functions are the right (and preffered way))

Hence the complete code will be reduced to (excluding the data creation part)

def line_averages():
    with open("test.csv", "r") as filename:
        avLines= []
        for line in filename:
            stripped_line  = line.strip()
            stripped_line  = stripped_line.split(',')
            line_sum = sum(float(i) for i in stripped_line )
            avLines.append(line_sum/len(stripped_line ))
        return avLines

Code Golfing the solution, We can use a List Comprehension. Read this to kow more about the list comprehensions.

def line_averages():
    with open("test.csv", "r") as filename:
        lines = [[float(i) for i in line.strip().split(',')] for line in filename]
        return [sum(i)/len(i) for i in lines]

Just for the "average" part.

with open('data.csv', 'r') as fo:
    lines = fo.readlines()
    av_lines = []
    for line in lines:
        n_lines = map(lambda x: float(x), line.split(','))
        av_lines.append(sum(n_lines) / len(n_lines))


Bubble Sort in Objective-C Following is Objective-C method implementation I did for one of the most simplest sorting algorithms, Bubble Sort to sort an array of integers.

Note:- I have defined it as a static method in the SimpleAlgorithms class.

/**
 * When given jumbled or discending ordered array of integers, following bubble sort method will give you
 * an array ordered in ascending order.
 */
+ (NSArray *) bubbleSort:(NSArray *) arrayToBeSorted {
    // As we can't swap integers in a static array, make a mutable array out of the given static array.
    NSMutableArray *muArrRaw = [[NSMutableArray alloc] initWithArray:arrayToBeSorted];

    // iterate through the array as rounds
    for (int i = 0; i < [muArrRaw count]; i++) {
        // iterate through each element of the array with the given range
        for (int j = 0; j < [muArrRaw count] - i; j++) {
            // comparison
            if (j < ([muArrRaw count] - 1) && [[muArrRaw objectAtIndex:j] intValue] > [[muArrRaw objectAtIndex:(j + 1)] intValue]) {
                int temp = [[muArrRaw objectAtIndex:j] intValue];   // taken the value to be swapped first

                // then do the swapping
                [muArrRaw replaceObjectAtIndex:j withObject:[muArrRaw objectAtIndex:(j + 1)]];
                [muArrRaw replaceObjectAtIndex:(j + 1) withObject:[NSNumber numberWithInt:temp]];
            }
        }
    }

    // return the sorted array
    return [muArrRaw mutableCopy];
}

I call this method as follows:

NSArray *array = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:5], [NSNumber numberWithInt:3], [NSNumber numberWithInt:4], [NSNumber numberWithInt:1], [NSNumber numberWithInt:2], nil];
NSArray *sortedArray = [SimpleAlgorithms bubbleSort:array];

I know this seems to be silly for asking for improvements for something like this. But I like to find out even smallest improvements that we can made to this kind of things also because sometimes I might have done something stupid in the above implementation also. That's where we can embed power and value to the implementation.

So please give your suggestions and improvements to this Algorithm implementation.

I would be grateful if you can point out the improvements in the following areas:

Objective-C Language oriented improvements, reasoning and suggestions
Algorithm implementation techniques, simplifiable code lines.

Returning a mutable copy of the temporary array makes no sense to me,
perhaps you meant

return [muArrRaw copy];

to return an immutable array (as the return type of the method indicates).

The "proper" data type for array indices is NSUInteger, not int.

In

if (j < ([muArrRaw count] - 1) && [[muArrRaw objectAtIndex:j] intValue] > [[muArrRaw objectAtIndex:(j + 1)] intValue]) {

you can get rid of the extra check j < ([muArrRaw count] - 1) if the
outer loop starts with i = 1.

Also [muArrRaw objectAtIndex:j] can be shortened to muArrRaw[i],

for (NSUInteger i = 1; i < [muArrRaw count]; i++) {
    for (NSUInteger j = 0; j < [muArrRaw count] - i; j++) {
        if ([muArrRaw[j] intValue] > [muArrRaw[j + 1] intValue]) {
            // ...
        }
    }
}

Swapping two elements in the array can be simplified by using
the existing method:

[muArrRaw exchangeObjectAtIndex:j withObjectAtIndex:j+1];

If no elements were swapped at all in some pass then the array is
already sorted and there is no need to continue:

BOOL swapped;
NSUInteger n = [muArrRaw count];
do {
    swapped = NO;
    for (NSUInteger j = 0; j + 1 < n; j++) {
        if ([muArrRaw[j] intValue] > [muArrRaw[j + 1] intValue]) {
            [muArrRaw exchangeObjectAtIndex:j withObjectAtIndex:j+1];
            swapped = YES;
        }
    }
    n--;
} while (swapped);

Your method is limited to arrays of integers. If you compare two
array elements with

if ([muArrRaw[j] compare:muArrRaw[j+1]] == NSOrderedDescending) { ... }

instead then it applies to all element types which have a compare:
method (e.g. NSNumber, NSString, NSDate ...).

Even more general, you can add a comparator argument, as suggested in this
answer:

My own method for sorting numbers in array

What you have written is working well. I just compared your method vs NSArray sortedArrayUsingComparator .  Please look at the benchmark result.

NSArray *numbers = @[@100, @210, @120, @200, @134, @156, @400, @500 , @450 , @475];

NSArray *yourSort = [SimpleAlgorithms bubbleSort:numbers];

NSLog(@"Your sort ..%@  ", yourSort);

//Sort using sortedArrayUsingComparator
NSArray *comparatorSort =[numbers sortedArrayUsingComparator:^(id ob1, id ob2){

    if ([ob1 integerValue] > [ob2 integerValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    if ([ob1 integerValue] < [ob2 integerValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];

NSLog(@"After sort ..%@  ", comparatorSort);

time took to sort the arrays

yourSort - 9 milli seconds

comparatorSort - 1 milli second

My suggestion is you can still improve alot your code.  Cheers!


Small tree generator If one enters, say, "2, j" then it prints:

j
jj

If there is no second it should be *, so if it's just 2, it's * **.

#include <iostream>
#include <string>
#include <vector>

using std::string; using std::cin; using std::cout; using std::endl; using std::ostream; using std::vector;

class tree {
public:
    friend ostream &output(tree &oTree, ostream &os);
    bool makeTree(int, const string&);
private:
    vector<string> Tree;
};

bool tree::makeTree(int newBase, const string &newCont = "*") {
    if (!Tree.empty())
        Tree.clear();
    string tempString;
    for(int tempbase = 0; tempbase != newBase; ++tempbase) {
        tempString += newCont;
        Tree.push_back(tempString);
    }
  return 1;
}

ostream &output(tree &oTree, ostream &os) {
    for (auto c: oTree.Tree) {
        os << c << endl;
    }
    return os;
}

int main() {

}

Don't do this (its not readable).

using std::string; using std::cin; using std::cout; using std::endl; using std::ostream; using std::vector;

One declaration per line.

using std::string;
using std::cin;
using std::cout;
using std::endl;
using std::ostream;
using std::vector;

But actually prefer not to do it at all. If you must do it then confine it to the most narrow scope possible. The whole reason that the standard library is std:: is so that it does not cost much to prefix members by it.

std::cout << "Hello World" << std::endl; // Not that hard

It cost nothing to clear an empty tree.

if (!Tree.empty())  // Why do this test. Just call clear.
    Tree.clear();

In C++ the & and * are usually placed with the type (its type information). This is different from C.

bool tree::makeTree(int newBase, const string &newCont = "*") {
                                             ^^^  Looks strange.

// I would write it like this:
// Note: I also put the const the other side (but that's more a personal
// preference and there is no clear better style there).
bool tree::makeTree(int newBase, string const& newCont = "*") {

Don't use integers to represent bools. At the end of makeTree() I see.

return 1;

// Use a boolean value.
return true;

But there is no failure value so why return anything at all?

Prefer '\n' over std::endl. The difference between the two is that std::endl does an extra flush. This can make using it very inefficient. The whole point of using the buffer is to make printing efficient and the streams are flushed at optimal points automatically and forcing a flush will make the use of stream less optimal.

In addition to the other answers, I see some things that could be improved. Here are a few suggestions:
Naming
It's confusing to name the class tree and name a member variable Tree. The member variable represents the "branches" of the tree so maybe a better name would be branches?
Speaking of naming, you should add names to the prototype of the makeTree() method. It will be confusing to users who want to call the method what the inputs are if there are no names.
In the loop where the strings are created you have tempString and tempbase. While these are accurate names, they are not very good names. The string held by tempString is going to be the next "branch" in the tree, so you could name it branch or nextBranch. It's not clear what "base" means in either newbase or tempbase. I would change all instances of base to length. I'd rename newbase to maxLength and tempbase to branchLength.
Use of friend
I dislike the use of friend in this case. I'd prefer that there was an accessor to retrieve a const reference to oTree.Tree, and then you could just write a normal stream insertion operator function. friend should be used sparingly as it breaks the rule of data hiding.
Construction
You have a makeTree() method, but no constructor. It seems like makeTree() should just be a constructor for the class (and hence should be called tree()). As it stands, a caller could make an instance of tree and it would be invalid (or at least empty). If the only public constructor was one which required them to pass in the depth of the tree and the character, they'll never create an empty tree.


Primality predicate in Haskell I wrote a primality test for UniHaskell however, it seems complicated in terms of conditionals.

Here it is, rewritten to not use Unicode and other functions in the code:

-- Primality predicate
isPrime  :: Int -> Bool
isPrime 2 = True
isPrime 3 = True
isPrime n
    | n `mod` 2 == 0 = False
    | n `mod` 3 == 0 = False
    | otherwise      = check 5 2
  where check i w
            | i * i <= n = if n `mod` i == 0
                           then False
                           else check (i + w) (6 - w)
            | otherwise = True

The algorithm is simple: return True if n is 2 or 3, False if n is a multiple of 2 or 3, and then perform trial division over numbers that are not multiples of 2 or 3.

All in all, that is some good looking, idiomatic Haskell. Well done!

You seem to be using the mod n x == 0 idiom quite often, so let's extract that to its own function.

divides :: Integral a => a -> a -> Bool
n `divides` m = m `mod` n == 0

You could also make your predicate polymorphic. No need to restrict yourself to Int, any Integral will do the trick.

isPrime :: Integral a => a -> Bool
isPrime 2 = True
-- and so on

I've often read that rem is faster than mod, but I've never checked... maybe it does give you some speed.

Through clever reordering of the guards, you can get rid of the if then else.

Instead of having a simple comment to explain the function, consider writing actual Haddock documentation.

Putting it together:

-- | @divides n m@ checks whether @n@ evenly
--   divides @m@, meaning that @m `mod` n == 0@.
divides :: Integral a => a -> a -> Bool
n `divides` m = m `rem` n == 0

-- | Checks whether a given number is prime.
isPrime :: Integral a => a -> Bool
isPrime 2 = True
isPrime 3 = True
isPrime n
    | 2 `divides` n = False
    | 3 `divides` n = False
    | otherwise     = check 5 2
  where check i w
      | i * i > n     = True
      | i `divides` n = False
      | otherwise     = check (i + w) (6 - w)

Maybe check 5 2 deserves a comment, as I couldn't see why these numbers are there on a first glance.

Replace recursion by control structures.

isPrime n = elem n [2,3] || all ((/=0) . mod n)
  (takeWhile (\i -> i * i <= n) $ 2 : 3 : concat [[i, i+2] | i <- [5,11..]])


Python implementation for contains pattern in text This is an implementation of contains, which returns a boolean indicating whether a pattern occurs in text.

I encountered this question while I was implementing find_all_index. For example, contains('abc', 'b') returns True and contains('abc', 'c') returns True.

I ran the following unit test cases, and it passed against all test cases, so the code seems to be working fine.

Implementation

Test

def contains(text, pattern):
    assert isinstance(text, str), 'text is not a string: {}'.format(text)
    assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)

    """create a pattern variable name """
    pattern = list(pattern)
    p_len = len(pattern)

    clean_text = list(filter(str.isalnum, text))
    t_len = len(clean_text)

    print("Searching contains")
    for i in range(t_len):
        # If the first letter matches, check the rest of string
        if clean_text[i] == pattern[0]:

            for j in range(p_len):
                if i+j >= t_len:
                    return False
                if pattern[j] != clean_text[i+j]:
                    break
                if j == p_len-1:
                    return True

    return False

def test_string_algorithms(text, pattern):
    found = contains(text, pattern)
    print('contains({!r}, {!r}) => {}'.format(text, pattern, found))

def main():
    test_string_algorithms(text, pattern)

if __name__ == '__main__':
    main()

PEP8 and readability

You have a few great docstrings, there is no need for block-comments and docstrings.
In contains you have this assert isinstance(text, str) but don't use it.

Code changes

Your contains(text, pattern) could be a lot more simplified. Because contains checks whether a pattern occurs in text and returns a boolean indicating .

def contains(text, pattern):
    """Return a boolean indicating whether pattern occurs in text."""
    # If our pattern index is equal to our pattern length
    # then we found a match and we can return True
    # If our current text character is not our pattern character
    # and if we were checking for a pattern
    # If we have not found our pattern then we return False

    text_index = 0
    pattern_index = 0

    text_length = len(text)
    pattern_length = len(pattern)

    while text_index < text_length:
        if text[text_index] == pattern[pattern_index]:
            pattern_index += 1
        elif pattern_index > 0:
            pattern_index = 0
            continue
        if pattern_index + 1 > pattern_length:
            return True
        text_index += 1
    return False

Advice 1

if clean_text[i] == pattern[0]: You don't need this. Consider this version:

def contains_v2(text, pattern):
    for i in range(len(text)):
        do_continue = False

        for j in range(len(pattern)):
            if text[i + j] != pattern[j]:
                do_continue = True
                break

        if do_continue:
            continue
        return i;
    return -1

Advice 2

In your version, you do clean_text = list(filter(str.isalnum, text)). That is doing 2 things in a single function. I suggest you remove it, and if you need it in your version, you filter first, and only then pass it to your implementation.


PHP, Is creating a class for templates to much? I am new to using classes heavily, and was wondering if going so far as to create a class specifically for templates was going to far. Here is a simplified version of my class template. Yes, I know I the use of unset is not necessary, but I like it there so don't give me any grief for it.

class template{
    private $templateString = "";
    private $templatePlaceholderStrings = array();
    private $templatePlaceholderValueStrings = array();

    function fillTemplateString($string){
        $this->templateString = $string;
        unset($string);
    }

    function fillTemplatePlaceholderStrings($array){
        $this->templatePlaceholderStrings = $array;
        unset($array);
    }

    function filltemplatePlaceholderValueStrings($array){
        $this->templatePlaceholderValueStrings = $arrray;
        unset($array);
    }

    function buildTemplate(){
        return preg_replace($this->templatePlaceholderStrings,
                    $this->templatePlaceholderValueStrings,
                    $this->templateString);
    }
}

This definitely wouldn't be going too far.  Any business logic that your program has to capture is best kept in a class.  Preferably, the class would have automated tests running against it as well to ensure that it is functioning properly.

In your example, the class isn't doing anything drastically different than what the preg_replace method does itself.  Rather than simply duplicating the built-in functionality of this method, I would suggest trying to think of what business goal you are trying to achieve and create methods that more closely mirror it.

class template {
    private $_templateText;

    // Initialize the template with this method, as an instance of
    // template doesn't make much sense without some text.
    public static function factory($templateText) {
        $template = new template();
        $template->_templateText = $templateText;

        return $template;
    }

    // This can be called as many times as needed.  Alternatively, you could add a
    // method that would take two arrays, with the idea that the two array's keys
    // are coupled and paired off.  If you choose to couple the two arrays, I would
    // recommend avoiding passing them in to two different methods.  Make the coupling
    // as obvious as possible by passing them in to the same method.
    public function replacePlaceholderTextWithString($placeholderText, $string) {
        // ...
    }

    // This could have some additional error handling code that would verify that
    // all placeholder text has been replaced and throw an exception if it hasn't.
    // Otherwise, it would simply format the template text based on what had
    // previously been passed in to replacePlaceholderTextWithString(...)
    public function getFormattedTemplateText() {
        // ...
    }
}

Lastly, I would add that a big advantage to using your own class for this is that you are able to change how you would like to implement this functionality in the future.  You could change from using preg_replace to using the MessageFormatter, or any number of other solutions.  It adds a great deal of flexibility and provides you the opportunity to put automated tests around it that can quickly notify you when it no longer works as expected.

As a suggestion for a personal exercise, consider implementing this without using any of PHP's object oriented features.  Then compare the two solutions side by side.


Project Euler #1 Sum of all the multiples of 3 or 5 below 1000 If we list all the natural numbers below 10 that are multiples of 3 or
  5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

  Find the sum of all the multiples of 3 or 5 below 1000.

My solution:

#include <stdio.h>
#define TOP_LIMIT 1000

float sum_of_series(float start_from,float position,float difference)
{
    return (position/2) *
        ( 2 * start_from + (position-1) * difference);
}

int find_last_multiple(int limit,int multiplier){
    return limit - (limit % multiplier);
}

void main(void){

    float last_position_3 =
        find_last_multiple( TOP_LIMIT-1 , 3 ) / 3;

    float last_position_5 =
        find_last_multiple( TOP_LIMIT-1 , 5 ) / 5;

    float last_position_15 =
        find_last_multiple( TOP_LIMIT-1 , 15 ) / 15;

    float sum_of_series_3 = sum_of_series(3,last_position_3,3);
    float sum_of_series_5 = sum_of_series(5,last_position_5,5);
    float sum_of_series_15 = sum_of_series(15,last_position_15,15);

    float answer = sum_of_series_3 + sum_of_series_5 - sum_of_series_15;

    printf("sum of all the multiples of 3 or 5 below 1000\n");
    printf("answer = %f\n",answer);

}

I compiled it with: gcc (GCC) 4.8.3 20140624 (Red Hat 4.8.3-1)

In general, your algorithm/solution is clever. It is an \$O(1)\$ solution which I like, when most other solutions would be an \$O(n)\$ and do a modulo on 3 and 5. The trick for subtracting the double-count is something that should have a clear comment, including the reason why.

The find_last_multiple is also a neat solution. No issues with that, and it is simple enough to not require a comment.

Unfortunately the sum_of_series has some problems.... it should be commented, for a start... the logic is far from obvious.... I have not figured it out... yet.

Also, at this point it becomes float based calculations, and that threw me for a second. I immediately started thinking int-based math because the code has int constants, and it does int values in the find_last_multiple but it then does implicit casts to float. Very confusing.

Finally, it makes the assumption that that the series starts from 3, 5, or 15, but the question description starts from somewhere else.... I suggest you discard the starts_from parameter, and simply use the difference instead.

So, using float-based logic, and returning a float based solution is unexpected.... and I would expect there to be some comment as to why the sum of integers in a series is a float.

Finally, your sum_of_series should represent the standard formula for the sum-of-a-series (see the alternate form in wikipedia):

$$
\frac{n}{2}(2a + (n - 1)d)
$$

where n is the number of terms in the series, a is the start value, and d is the difference.

That can be simplified by setting a to be 0 (eliminating the 2a term), and for int math by doing:

$$
\frac{n(n - 1)}{2}d
$$

Mathematically, any multiple of an even number is always going to be even. Now, either \$n\$ or \$n - 1\$ is even.... so, \$n(n-1)\$ will be even, and safe to divide by 2.

I would also start from 0. Using integer math, the problem is simpler:

int sum_of_series(int limit, int difference)
{
    // from: http://en.wikipedia.org/wiki/Arithmetic_progression
    // formula for calculating the sum of a progression from 0 to a 'limit'
    // in steps of 'difference'. e.g. limit 10, difference 2 adds 0, 2, 4, 6, 8, 10 = 30
    int n = 1 + limit / difference; // integer math gives number of terms including term 0
    return ((n * (n - 1)) / 2) * difference;
}

So, you can use the above safely as:

int sum = sum_of_series(999, 15);

which will give the result 15 * (67 * 66) / 2 or  33165

Note that the problem statement requires the sum of values less than 1000, and the sum_of_series formula calculates inclusive of the limit, so we use the limit of 999, not 1000

Additionally, using the int-based logic, there is no need for there to be the find-limit method at all. This reduces your main method to:

int main(void){

    int sum_of_series_3 = sum_of_series(999,3);
    int sum_of_series_5 = sum_of_series(999,5);
    int sum_of_series_15 = sum_of_series(999,15);

    int answer = sum_of_series_3 + sum_of_series_5 - sum_of_series_15;

    printf("sum of all the multiples of 3 or 5 below 1000\n");
    printf("answer = %d\n",answer);

    return 0;

}

I put the above together in a working Ideone

Why a so complicated algorithm when you can keep it as simple as:

#include <stdio.h>

int main() {
  int sum=0;
  for (int i=1;i<1000;i++) {
    if (i % 3 == 0 || i % 5 == 0)
      sum += i;
  }
  printf("%d\n",sum); // 233168
}

Since you have no input every solution is \$O(1)\$.


Conversion between enum and string in C++ class header I have the following redundant-feeling design to convert between enums and strings regarding a class that stores enums. The approach doesn't scale if there are more enums and in any event, less-redundant code is also better.

Questions

If there will be more enums, would it be possible to avoid defining two explicit conversion functions per enum type and device a system where the caller sees just one (i.e. convert) or two different function names (i.e. convertto/convertfrom for all the enums, not just per enum type)? Perhaps using some kind deduction magic with auto and decltype? It looks like ambiguity sets in since only the return value can be used to separate the different functions overloads (even if done with function templates).
Is the following design of separating the conversion functions and putting them to an anonymous namespace good design (I've thought about putting the conversion functions to a file, say conversions.incl and including it)?

The idea would be make the multiple (i.e. more enums than the one presented here) conversions as implicit as possible

The conversions would be used like this:

random.cpp

string token_string = "none"; //In reality this will be externally, user, generated.
some_class_instance->set_type(enum_conversion(token_string));
token_string = enum_conversion(some_class_instance->get_type());

And to present one enum and related conversions (but there could be more):

some_class.h

class some_class
{
    public:
         enum class enum_type
         {
             none   = 0,
             type1  = 1,
             type2  = 2
         }

     void set_type(enum_type);
     enum_type get_type() const;

   private:
       enum_type type_;
};

namespace
{
    std::array<std::pair<std::string, some_class::enume_type>, 3> type_map;

    bool initialize_map()
    {
       type_map[0] = std::make_pair("none", some_class::enum_type::none);
       type_map[1] = std::make_pair("type1", some_class::enum_type::type1);
       type_map[2] = std::make_pair("type2", some_class::enum_type::type2);
    }

    bool initialization_result = initialize_map();

    some_class::enum_type enum_conversion(std::string const& enum_type)
    {
        for(auto val: type_map)
        {
            if(val.first == enum_type)
            {
                return val.second;
            }
        }

        return type_map[0].second;
    }

    std::string enum_conversion(some_class::enum_type enum_type)
    {
        for(auto val: type_map)
        {
            if(val.second == enum_type)
            {
                return val.first;
            }
        }

        return type_parameter_map[0].first;
    }
}

I would use some template logic to achieve the affect in a more scalable way:

#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>

// This is the type that will hold all the strings.
// Each enumeration type will declare its own specialization.
// Any enum that does not have a specialization will generate a compiler error
// indicating that there is no definition of this variable (as there should be
// be no definition of a generic version).
template<typename T>
struct enumStrings
{
    static char const* data[];
};

// This is a utility type.
// Created automatically. Should not be used directly.
template<typename T>
struct enumRefHolder
{
    T& enumVal;
    enumRefHolder(T& enumVal): enumVal(enumVal) {}
};
template<typename T>
struct enumConstRefHolder
{
    T const& enumVal;
    enumConstRefHolder(T const& enumVal): enumVal(enumVal) {}
};

// The next two functions do the actual work of reading/writing an
// enum as a string.
template<typename T>
std::ostream& operator<<(std::ostream& str, enumConstRefHolder<T> const& data)
{
   return str << enumStrings<T>::data[data.enumVal];
}

template<typename T>
std::istream& operator>>(std::istream& str, enumRefHolder<T> const& data)
{
    std::string value;
    str >> value;

    // These two can be made easier to read in C++11
    // using std::begin() and std::end()
    //
    static auto begin  = std::begin(enumStrings<T>::data);
    static auto end    = std::end(enumStrings<T>::data);

    auto find   = std::find(begin, end, value);
    if (find != end)
    {
        data.enumVal = static_cast<T>(std::distance(begin, find));
    }
    return str;
}

// This is the public interface:
// use the ability of function to deduce their template type without
// being explicitly told to create the correct type of enumRefHolder<T>
template<typename T>
enumConstRefHolder<T>  enumToString(T const& e) {return enumConstRefHolder<T>(e);}

template<typename T>
enumRefHolder<T>       enumFromString(T& e)     {return enumRefHolder<T>(e);}

Then you can use it like this:

// Define Enum Like this
enum X {Hi, Lo};
// Then you just need to define their string values.
template<> char const* enumStrings<X>::data[] = {"Hi", "Lo"};

int main()
{
    X   a=Hi;

    std::cout << enumToString(a) << "\n";

    std::stringstream line("Lo");
    line >> enumFromString(a);

    std::cout << "A: " << a << " : " << enumToString(a) << "\n";
}

If I customise my enum like hi = 10, low = 20, it gives me en error ..

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

// Define Enum Like this
enum X {Hi = 10, Lo = 20};
// Then you just need to define their string values.
template<> char const* enumStrings<X>::data[] = {"Hi", "Lo"};


Get methods in module, Python Goal: extract methods/functions defined in module. This excludes:

Imports
Lambda methods
Magic methods
Builtin methods
Class methods
Classes
Non-original definitions (i.e. function assignments, alt_name = orig_fn)

My approach + test below. Any room for improvement, or false positives/negatives? (In particular I wonder if we can get away without typechecks, e.g. isinstance(method, types.LambdaType))

Code: live demo

import utils

def get_module_methods(module):
    def is_module_function(obj):
        return ('<function' in str(obj) and
                module.__name__ in getattr(obj, '__module__', ''))

    def not_lambda(obj):
        return not ('<lambda>' in getattr(obj, '__qualname__', ''))

    def not_magic(obj):
        s = getattr(obj, '__name__', '').split('__')
        return (len(s) < 2) or not (s[0] == s[-1] == '')

    def not_duplicate(name, obj):
        return name == getattr(obj, '__name__', '')

    def cond(name, obj):
        return (is_module_function(obj) and not_lambda(obj) and
                not_magic(obj) and not_duplicate(name, obj))

    objects = {name: getattr(module, name) for name in dir(module)}
    m_methods = {}

    for name, obj in objects.items():
        if cond(name, obj):
            m_methods[name] = obj
    return m_methods

mm = get_module_methods(utils)
_ = [print(k, '--', v) for k, v in mm.items()]

Test:

# utils.py
import random
import numpy as np
from inspect import getsource

def fn1(a, b=5):
  print("wrong animal", a, b)

class Dog():
  meow = fn1
  def __init__(self):
    pass

  def bark(self):
    print("WOOF")

d = Dog()
barker = d.bark
mewoer = d.meow
A = 5
arr = np.random.randn(100, 100)

def __getattr__(name):
  return getattr(random, name, None)

magic = __getattr__
duplicate = fn1
_builtin = str
lambd = lambda: 1

# main.py
import utils

# def get_module_methods(): ...

mm = get_module_methods(utils)
_ = [print(k, '--', v) for k, v in mm.items()]

fn1 -- <function fn1 at 0x7f00a7eb2820>

Edit: additional test case for a lambda surrogate:

import functools

def not_lambda():
    return 1
functools.wraps(lambda i: i)(not_lambda).__name__

Code in question and answer catch not_lambda as a lambda - false positive.

pyclbr

The standard library includes the pyclbr module, which provides functions for building a module browser.  pyclbr.readmodule_ex() returns a tree of nested dicts with the functions (defstatements) and classes (class statements) in a module.  So you just need to check the top level dict for items of class pyclbr.Function.

Note that readmodule_ex takes the name of the module (a str), not the actual module.

Just tested this, and it prints out imported functions and dunder functions as well, so those need to be filtered out.

import pyclbr

module = 'tutils'

for k,v in pyclbr.readmodule_ex(module).items():
    if (    isinstance(v, pyclbr.Function)
        and v.module==module
        and not v.name.startswith('__')):
        print(f"{v.name} -- {v.file} at {v.lineno}")

Thanks to @Peilonrayz for the original answer, but I figure it's worth including a more complete version of the working function:
from types import LambdaType

def get_module_methods(module):
    output = {}
    for name in dir(module):
        obj = getattr(module, name)
        obj_name = getattr(obj, '__name__', '')
        if ((str(obj).startswith('<function')
             and isinstance(obj, LambdaType)) # is a function
            and module.__name__ == getattr(obj, '__module__', '')  # same module
            and name in str(getattr(obj, '__code__', ''))  # not a duplicate
            and "__%s__" % obj_name.strip('__') != obj_name  # not a magic method
            and '<lambda>' not in str(getattr(obj, '__code__'))  # not a lambda
        ):
            output[name] = obj
    return output

Lambda detection taken from this Q&A. Note that we can omit the isinstance(obj, LambdaType) typecheck, but with caveats:

str(obj).startswith('<function') is insufficient to tell whether obj is a function, since we can define a class whose __str__ returns '<function' (as pointed by Peilonrayz). However, __str__ is effective on a class instance, which fails the # not a duplicate check - so we can "luck out". This is unlikely in practice, but here's where a typecheck may be necessary:

class Dog():
    def __init__(self):
        self.__name__ = 'd'
d = Dog()

Edit: changed # not a duplicate check, which would falsely exclude not_lambda.


Clearing the screen using FillConsoleOutputAttribute() I'm currently clearing my console window with this piece of code:

void clrScr()
{
    COORD cMap =
    {
        0, 3
    };
    if(!FillConsoleOutputAttribute(hCon, 0, 2030, cMap, &count))
    {
        std::cout << "Error clearing the console screen." << std::endl;
        std::cout << "Error code: " << GetLastError() << std::endl;
        std::cin.get();
    }
}

, which I call once in the main loop.
But since my window is quite large (70x35), it's flickering quite a bit.

I was wondering if there are any faster methods of doing this?

Here is an idea; ANSI escape codes work on Windows, Linux and OSX:

cout << "\033c";

\033 - stands for octal ESC,
c    - resets the device (terminal is default) to the initial state ( clear the screen,clear the buffer also so it is not possible to scroll, reset the fonts and so on).

In some cases it may be more useful than well known which simply adds some empty lines and puts the cursor in the upper left corner:

cout << "\033[2J\033[1;1H"

How about

system("cls");

This clears the entire console nicely


Merging Overlapping Intervals A while back I was asked the following question in a phone interview, and to be honest it stumped me. After many long nights of rolling the problem around in my head I think I came up with a decent solution.

The Question:

  Given a list of intervals like:

  [(5, 7), (11, 116), (3, 6), (10, 12), (6, 12)]

  Write a function that will merge overlapping intervals.

My solution:

def merge_intervals(intervals):
    """
    A simple algorithm can be used:
    1. Sort the intervals in increasing order
    2. Push the first interval on the stack
    3. Iterate through intervals and for each one compare current interval
       with the top of the stack and:
       A. If current interval does not overlap, push on to stack
       B. If current interval does overlap, merge both intervals in to one
          and push on to stack
    4. At the end return stack
    """
    si = sorted(intervals, key=lambda tup: tup[0])
    merged = []

    for tup in si:
        if not merged:
            merged.append(tup)
        else:
            b = merged.pop()
            if b[1] >= tup[0]:
                new_tup = tuple([b[0], tup[1]])
                merged.append(new_tup)
            else:
                merged.append(b)
                merged.append(tup)
    return merged

if __name__ == '__main__':

    l = [(5, 7), (11, 116), (3, 4), (10, 12), (6, 12)]
    print("Original list of ranges: {}".format(l))
    merged_list = merge_intervals(l)
    print("List of ranges after merge_ranges: {}".format(merged_list))

My questions are:

Run time: Without counting sorting I believe this runs in \$O(n)\$. With counting sorting that would go up to \$O(n*\log(n))\$. Is this correct?
Stylistically does anything need to be improved?
Is there a more efficient way of solving this problem?

This code has a bug. Consider merge_intervals([(0, 3), (1, 2)]). This returns [(0, 2)] although it should be [(0, 3)]. This can be solved through

new_tup = (b[0], max(b[1], tup[1]))

Your code is nice, and implements the simplest thing that works. However, you might want to work on improving your variable names. Neither l, b, or si are very descriptive, and tup and new_tup unnecessarily refer to their type name rather than their meaning. In contrast, merged is a very clear name. A rewrite of the function body might be:

sorted_by_lower_bound = sorted(intervals, key=lambda tup: tup[0])
merged = []

for higher in sorted_by_lower_bound:
    if not merged:
        merged.append(higher)
    else:
        lower = merged[-1]
        # test for intersection between lower and higher:
        # we know via sorting that lower[0] <= higher[0]
        if higher[0] <= lower[1]:
            upper_bound = max(lower[1], higher[1])
            merged[-1] = (lower[0], upper_bound)  # replace by merged interval
        else:
            merged.append(higher)
return merged

Notice that I decided not to use an explicit tuple(…) constructor – that's mostly useful for converting to tuples from iterables. For tuple literals, you can use the (…, …) syntax.

I also put the comments inside the code, rather than into the docstring. Docstrings are good, but they are intended to explain how to use the function (e.g. what the expected type of parameters is, what the function returns, …). To document implementation details, use normal comments.

You have correctly identified the (average and worst-case) algorithmic complexity as \$O(n \log n)\$. You must consider the sorting. However, best-case complexity is \$O(n)\$, as the Tim Sort used by Python detects already-sorted input.

While your code provides a simple and robust solution, it would be certainly possible to reduce average algorithmic complexity. I expect a kind of self-merging interval tree to have average complexity closer to \$O(n \log m)\$ where \$m\$ is the number of intervals after merging.

This may be a better solution than what is posted above, I even added a unit test:

def compresoneadjtuple(s):
    """useful to compress adjacent entries"""
    if len(s)<1:return s,True
    finals=[]
    for pos in range(len(s)-1):
        firstt, secondt=s[pos],s[pos+1]
        if (firstt[1]==secondt[0]) or (firstt[1]+1==secondt[0]):
            finals.append((firstt[0],secondt[1]))
            finals.extend(s[pos+2:])
            return finals,False
        else:
            finals.append(firstt)
    finals.append(s[-1])
    return finals,True

def merge_intervals(intervals):
    s = sorted(intervals, key=lambda t: t[0])
    m = 0
    for  t in s:
        if t[0] >= s[m][1]:
            m += 1
            s[m] = t
        else:
            s[m] = (s[m][0], t[1])
    done=False
    s=s[:m+1]
    while(not done):
        s,done=compresoneadjtuple(s)
    return s

def testmergeint():
    assert(merge_intervals([])==[])
    assert(merge_intervals([(4,8)])==[(4, 8)])
    assert(merge_intervals([(6,10)])==[(6, 10)])
    assert(merge_intervals([(4,8),(6,10)])==[(4, 10)])
    assert(merge_intervals([(4,8),(6,10),(11,12)])==[(4, 12)])
    assert(merge_intervals([(4,8),(6,10),(11,12),(15,20)])==[(4, 12), (15, 20)])
    assert(merge_intervals([(4,8),(6,10),(11,12),(15,20),(20,25)])==[(4, 12), (15, 25)])


shared_ptr code implementation I have never used std::shared_ptr before and I don't really know how this smart pointer actually works but I decided to create one to verify my knowledge. Here is my code :

namespace myStd
{
    template<class T>
    class shared_ptr
    {
        public :

        shared_ptr() : refCount(nullptr), t(nullptr) {}
        shared_ptr(T *p) : refCount(new int(1)), t(p) {}

        ~shared_ptr()
        {
            this->destroy();
        }

        shared_ptr(const shared_ptr &p) : refCount(nullptr), t(nullptr)
        {
            if(p.isvalid())
            {
                refCount = p.refCount;
                t = p.t;

                if(isvalid())
                (*this->refCount)++;
            }
        }

        void destroy()
        {
            if(isvalid())
            {
                --(*refCount);
                if((*refCount) <= 0)
                {
                    delete refCount;
                    delete t;
                }

                refCount = nullptr;
                t = nullptr;
            }
        }

        shared_ptr& operator =(const shared_ptr &p)
        {
            if(this != &p)
            {
                if(!p.isvalid())
                {
                    this->destroy();
                    this->refCount = p.refCount;
                    this->t = p.t;

                    if(isvalid())
                    (*this->refCount)++;

                    return (*this);
                }

                if(!isvalid())
                {
                    this->refCount = p.refCount;
                    this->t = p.t;

                    if(isvalid())
                    (*this->refCount)++;

                    return (*this);
                }
                else
                {
                    this->destroy();
                    this->refCount = p.refCount;
                    this->t = p.t;

                    if(isvalid())
                    (*this->refCount)++;
                }
            }
            return (*this);
        }

        bool isvalid() const {return (t != nullptr && refCount != nullptr);}
        int getCount() const {if(refCount != nullptr) return (*refCount); else return 0;}

        T* operator ->() {return t;}
        T& operator *() {return *t;}

        private :
        int *refCount;
        T *t;
    };
}

What am I missing? Did I implement this smart pointer right?
Your suggestions would be appreciated.

What am I missing?

Several things.

constructor that takes object of type std::nullptr_t
constructor that takes object of type shared_ptr<U> where U is derived from T
boolean conversion operator.
swap operator
move semantics

Sure there is more. In Smart pointers you always forget something.

  Did I implement this smart pointer right?

YOu implemented the rule of three. So barring any bugs it should be good.

  Your suggestions would be appreciated.

I go into a lot of detail in my articles:

Unique Pointer
Smart Pointer
Constructors

Don't use this.

It is not very normal to see this-> in C++ code (unlike Java).

I actually consider the use of this-> as bad practice. You only need to use this->member if there is some ambiguity between local/parameters and member names.

If you have some ambiguity then you have done a bad job at naming and you are using this-> to cover up the problem. Prefer to fix the problem as some poor maintainer is going to come along later and use the wrong variable because of your laziness.

I normally turn on the compiler warning that tells my if a local variable is shadowing another thus forcing me to have unique (and meaningful names).

One Line One Statement

shared_ptr(const shared_ptr &p) : refCount(nullptr), t(nullptr)

To me this looks exactly like multiple assignments packed onto the same line.

varOne = 5; varTwo = 6; theOtherOne = doStuff(5);

I think it is well accepted that one line should have one statement. Why not apply this to your parameter list. It will make reading the code much easier and also validating order of initialization problems.

shared_ptr(const shared_ptr &p)
    : refCount(nullptr)
    , t(nullptr)
{
    /* Stuff */
}

Construct with a null ptr

    shared_ptr(T *p) : refCount(new int(1)), t(p) {}

What happens if you I build with a nullptr?

X*            ptr = nullptr;
shared_ptr<X> data1(ptr);
shared_ptr<X> data2(nullptr); // should have its own constructor.

Double Check of isvalid() is wastefull

If p.isvalid() is true then isvalid() will be true after the copy.

    shared_ptr(const shared_ptr &p) : refCount(nullptr), t(nullptr)
    {
        if(p.isvalid())
        {
            refCount = p.refCount;
            t = p.t;

            if(isvalid())
            (*this->refCount)++;
        }
    }

Also this could be much simplified.

    shared_ptr(const shared_ptr &p)
        : refCount(p.refCount)
        , t(p.t)
    {
        if(isvalid()) {
            (*refCount)++;
        }
    }

Prefer Copy/Swap Idiom for assignment.

    shared_ptr& operator =(const shared_ptr &p)
    {
        if(this != &p)
        {
            /* This LOOKS LIKE A BUG */
            /* Don't think the ! should be there. */
            if(!p.isvalid())
            {
                this->destroy();
                this->refCount = p.refCount;
                this->t = p.t;

                if(isvalid())
                (*this->refCount)++;

                return (*this);
            }

            if(!isvalid())
            {
                this->refCount = p.refCount;
                this->t = p.t;

                if(isvalid())
                (*this->refCount)++;

                return (*this);
            }
            else
            {
                this->destroy();
                this->refCount = p.refCount;
                this->t = p.t;

                if(isvalid())
                (*this->refCount)++;
            }
        }
        return (*this);
    }

Sorry that function is big and clumsy and hard to read. It also does not provide the strong exception guarantee. You modify the content of this object doing exception dangerous work (call destroy) before updating the content of this object.

To do any work in exception safe way you need to follow a three step processes.

Make a copy into temp. -> Dangerious as exceptions can fly.
Swap the temp and current. -> Safe as swap should not throw exceptions.
Destroy then temp. -> Safe as the state of current is now good.

This 3 step process is ipitimized by the copy and swap idiom.

 shared_ptr& operator =(const shared_ptr &p)
 {
     shared_ptr  temp(p);    // Constructor copies. Destructor destoryes.
     temp.swap(*this);       // Perform an exception safe transfer of state.
     return *this;
 }

Lots of people take this one step further. And do the copy in the parameter:

 shared_ptr& operator =(shared_ptr p)  // Notice the pass by value.
 {                                     // this gets your copy.
     p.swap(*this);
     return *this;
 }

Const correctness

These two functions do not mutate the state of the object.

    T* operator ->() {return t;}
    T& operator *() {return *t;}

So they should probably be marked as const.

The operator=() method has four return statement. I’d prefer a single one, or perhaps another early return for this == &p.
Code duplication in operator =.
The destroy method is not needed, IMO.
getCount() should call isValid.
isValid only has to check the pointer. The refcount != nullptr if and only if the pointer != nullptr.
The copy constructor does not need to check this->isvalid(), right?
Same thing in operator=
assert(refCount >= 0) in destroy().
Some more asserts() would be nice, e.g. in operators -> and *.


Calculate the cost of cement for a project I am a newbie in a programming, and I just randomly chose a task for training from some group on Facebook. The task is to calculate the cost of cement for a construction project. The input is the number of pounds of cement required (guaranteed not to be a multiple of 120). The store sells cement in 120-pound bags, each costing $45.

Example input: 295.8
Output: 135

#include <stdio.h>
#include <stdlib.h>

#define PRICE 45
#define CAPACITY 120
#define MAXDIGITS 5

int sum(int);

int main(int argc, char *argv[])
{
    int val = 0;
    char inp[MAXDIGITS];

    if ((argc > 1) && (argv[1] > 0))
        val = strtol(argv[1], NULL, 0);
    else
    {
        do
        {
            printf("Please input the value of cement: ");
            scanf("%s", inp);
            val = strtol(inp, NULL, 0);
        }
        while (!val);
    }

    if (val)
        printf("Money you need: %d\n", sum(val));

    return 0;
}

int sum(int need)
{
    int mon = PRICE;
    int n = CAPACITY;

    while (n < need)
    {
        n += CAPACITY;
        mon += PRICE;
    }

    return mon;
}

I'm interested in code style, rational memory usage, etc.

Buffer overflow
Consider what entering "295.8" does.
#define MAXDIGITS 5
char inp[MAXDIGITS];
printf("Please input the value of cement: ");
scanf("%s", inp);

Code used the dangerous scanf("%s", inp); with no width limits.  scanf("%s", inp); being ignorant of the size of inp[], stored the 5 read characters and the appended null character.
This results in undefined behavior (UB).  Code may work as expected today and fail in strange ways tomorrow.
I recommend to only use fgets() for user input.  After reading a line of user input, it is saved as a string.  Then parse the string.
No need for such a tight buffer size.  Recommend twice the expected max width needed.
#define BUFFER_SIZE (2*MAXDIGITS + 1)
char buffer[BUFFER_SIZE];

printf("Please input the value of cement: ");
fflush(stdout);  // Insure output is seen before reading

fgets(buffer, sizeof buffer, stdin);
double val = strtod(buffer, NULL);

Welcome on Code Review

Review

#define PRICE 45
#define CAPACITY 120
#define MAXDIGITS 5

You define PRICE and CAPATITY as integers, but a price can have cents, and a bag can maybe contains more than a plain amount in pounds, maybe some ounces more. So you should use decimals here.

if ((argc > 1) && (argv[1] > 0))

Don't compare a char* to an int. This check doesn't insure that argv[1] is a valid number.
If the parameter isn't what you want, you can either print the usage and quit, or silently continue and ask for input.

val = strtol(argv[1], NULL, 0);

You don't validate the program argument. strtol can silently fail and return "0". In this case, a good option would be to ask for a good input.
You parse the string to an unsigned integer; but the asked task stand asking a decimal number (and show "295.8" in the example). You could use strtod or atof but since you are a conscientious programmer, you want to check for validity.

So the combo scanf/sscanf (with "%f" or "%lf")` are the solution.

do
{
    printf("Please input the value of cement: ");

Try to put a \nbefore your request. It will make the output more clear. Otherwise, it will print on the same line as last output.

scanf("%s", inp);
val = strtol(inp, NULL, 0);

As above, use scanf("%lf", ...) instead (shorter, and you can check for errors)

int sum(int need)

Once what i said above is fixed (price and capacity as double) your function work fine. However, you can simplify it, by doing the computation in only one line (which can be simplified even more, with libmath).

Here's my corrected version:

#include <stdio.h>
#include <stdlib.h>

#define PRICE 45.
#define CAPACITY 120.

int sum(int);

int main(int argc, char *argv[])
{
    double need = 0.;

    if (argc < 2 || sscanf(argv[1], "%lf", &need) != 1) {
        while (printf("\nPlease input the amount of cement you need (e.g. 295.8): ") && scanf("%lf", &need) != 1) {
            for(int c = 0; c != '\n' && c != EOF; c = getchar());
        }
    }
    printf("For %.02lf pounds you need: $%.02lf!\n", need, PRICE * ((int)((int)(need / CAPACITY) * CAPACITY < need) + (int)(need / CAPACITY)));

    // or with "#include <math.h>" and the compiler/linker flag "-lm"
    //printf("For %.02lf pounds you need: $%.02lf!\n", need, PRICE * ceil(need / CAPACITY));
    return 0;
}