Weighing bags of money I have made a program to weigh bags of money, and calculate whether too many/little coins are in the bags, and the difference.

bagWeight = 0
totalCoinsAdd = 0
totalCoinsRemoved = 0
totalBagsChecked = 0

def inputs():
    global bagWeight
    global totalCoinsAdd
    global totalCoinsRemoved
    #The above grabs the global variables for use in the function
    bagWeight = int(input("How much does the bag weigh? "))
    denomination = ""
    denom = ['0.01', '0.02', '0.05', '0.10', '0.20', '0.50', '1', '2']
    while denomination not in denom:
        denomination = input("What denomination is the money? £")

    idealWeight = {    '2' : 120,    '1' : 190,    '0.50' : 160,    '0.20' : 250,   '0.10' : 325,    '0.05' : 325,   '0.02' : 356,    '0.01' : 356,    }
    #This dictionary stores the ideal weight of each bag.
    bagCoins = {    '2' : 10,    '1' : 20,    '0.50' : 20,    '0.20' : 50,   '0.10' : 50,    '0.05' : 100,   '0.02' : 50,    '0.01' : 100,    }
    #This dictionary stores how many coins are in each bag.
    coinWeight = {    '2' : 12,   '1' :  9.5,   '0.50' : 8,  '0.20' : 5,   '0.10' :  6.5,  '0.05' : 3.25,'0.02' : 7.12, '0.01' : 3.56, }
    #This dictionary stores how much the 1 of each coin weighs. The values are in grams.
    AddCoins = True     #This defines a variable for whether to add/remove coins.
    differentWeight = idealWeight[denomination] - bagWeight
    #This calculation works out how the difference in weight between the 'ideal' bag weight and the actual bag weight.
    coinInBag = bagWeight/coinWeight[denomination]
    #This calculation works out how many coins are in each bag. It does this by, dividing the bag weight by how much each coin weighs.
    coinChange = bagCoins[denomination] - coinInBag
    #Calculating the amount of coin difference in the bag

    if differentWeight < 0:
        AddCoins = False
        differentWeight = differentWeight  * -1
        coinChange = coinChange * -1

    if AddCoins == True:
        print('The bag is ',str(differentWeight), 'g less than it should be')
        print('Add ', int(coinChange), ' coin(s)')
        totalCoinsAdd = totalCoinsAdd + coinChange

    if AddCoins == False:
        print('The bag is ',str(differentWeight), 'g more than it should be')
        print('Remove ', int(coinChange), ' coin(s)')
        totalCoinsRemoved = totalCoinsRemoved + coinChange

again = 'yes'
while again != 'no':
    inputs()
    totalBagsChecked = totalBagsChecked + 1
    again = input('Would you like to weight another bag? ("no" to quit)')

print('Total coins added: ', int(totalCoinsAdd))
print('Total coins removed: ', int(totalCoinsRemoved))
print('Total bags checked:', int(totalBagsChecked))

Multiple source of information

You have 4 data structures (1 list and 3 dictionnaries) whose content needs to be kept in sync because values in the list need to be keys of the dictionnaries and keys from the dictionnaries not in the list are pointless.

Maybe thing would be clearer if you had only a single source of truth. For instance, you could have a single dictionnary mapping values to idealWeight, bagCoins and coinWeight (whatever it means). Python offer simple ways to do so via tuples or namedtuples.

FOr instance, you could do something like:

from collections import namedtuple
bagWeight = 0
totalCoinsAdd = 0
totalCoinsRemoved = 0
totalBagsChecked = 0

CoinInfo = namedtuple('CoinInfo', ['idealWeight', 'bagCoins', 'coinWeight'])

COINS = {
    '2':    CoinInfo(120,  10, 12),
    '1':    CoinInfo(190,  20,  9.5),
    '0.50': CoinInfo(160,  20,  8),
    '0.20': CoinInfo(250,  50,  5),
    '0.10': CoinInfo(325,  50,  6.5),
    '0.05': CoinInfo(325, 100,  3.25),
    '0.02': CoinInfo(356,  50,  7.12),
    '0.01': CoinInfo(356, 100,  3.36),
}

def inputs():
    global bagWeight
    global totalCoinsAdd
    global totalCoinsRemoved
    #The above grabs the global variables for use in the function
    bagWeight = int(input("How much does the bag weigh? "))
    denomination = ""
    while denomination not in COINS:
        denomination = input("What denomination is the money? £")
    coin = COINS[denomination]
    AddCoins = True     #This defines a variable for whether to add/remove coins.
    differentWeight = coin.idealWeight - bagWeight
    #This calculation works out how the difference in weight between the 'ideal' bag weight and the actual bag weight.
    coinInBag = bagWeight/coin.coinWeight
    #This calculation works out how many coins are in each bag. It does this by, dividing the bag weight by how much each coin weighs.
    coinChange = coin.bagCoins - coinInBag
    #Calculating the amount of coin difference in the bag

The AddCoinss variable

The comment This defines a variable for whether to add/remove coins. is very verbose and could be a simple Add/remove coins.

By the way, there is a style guide for Python code called PEP 8 which is definitly worth reading and worth following if you don't have any good reason not to do it (legacy project, company code style, etc). Among other things, it says that snake_case should be used for variable (instead of CamelCase).

Also, the way we check it later on can be improved for 2 reasons :

when a variable (or any expression) is known to be a boolean, it is better to write if var (resp. if not var) instead of if var == True (resp. if var == False). In a real life situation, you'd say "if it rains" rather than "if it is True that it is raining".
you check if AddCoins == True and then just after if AddCoins == False without changing the value of AddCoins. This is exactly what the else keyword is for. It makes the code much clearer to the reader because one knows at first glance that we'll go though one and only one of the block.

So far, we have:

add_coins = True  # Whether to add/remove coins.
if differentWeight < 0:
    add_coins = False
    differentWeight = differentWeight  * -1
    coinChange = coinChange * -1

if add_coins :
    print('The bag is ',str(differentWeight), 'g less than it should be')
    print('Add ', int(coinChange), ' coin(s)')
    totalCoinsAdd = totalCoinsAdd + coinChange
else:
    print('The bag is ',str(differentWeight), 'g more than it should be')
    print('Remove ', int(coinChange), ' coin(s)')
    totalCoinsRemoved = totalCoinsRemoved + coinChange

Now, this variable is not so useful at all because we are performing the test that really matters (differentWeight < 0) just before and we could handle the different processing directly here.

Also, here again, variable name can be improved and you could use var *= -1 instead of var = var * -1.

The code would look like:

if different_weight < 0:
    different_weight *= -1
    coinChange *= -1
    print('The bag is ',str(different_weight), 'g more than it should be')
    print('Remove ', int(coinChange), ' coin(s)')
    totalCoinsRemoved = totalCoinsRemoved + coinChange
else:
    print('The bag is ',str(different_weight), 'g less than it should be')
    print('Add ', int(coinChange), ' coin(s)')
    totalCoinsAdd = totalCoinsAdd + coinChange

As pointed out in Mathias Ettinger's comment, you might as well get rid of the multiplication altogether and just consider the negative value when printing :

if different_weight < 0:
    print('The bag is ',str(-different_weight), 'g more than it should be')
    print('Remove ', int(-coinChange), ' coin(s)')
    totalCoinsRemoved = totalCoinsRemoved - coinChange
else:
    print('The bag is ',str(different_weight), 'g less than it should be')
    print('Add ', int(coinChange), ' coin(s)')
    totalCoinsAdd = totalCoinsAdd + coinChange

String formatting

Python offers different nice ways to format string and providing multiple arguments to print is not the favorite way to do this. You can find documentation online about string formatting but pyformat.info provides a very nice summary.

Using this, you could write something like:

    if different_weight < 0:
        print('The bag is {}g more than it should be'.format(-different_weight))
        print('Remove {} coin(s)'.format(-coinChange))
        totalCoinsRemoved = totalCoinsRemoved - coinChange
    else:
        print('The bag is {}g less than it should be'.format(different_weight))
        print('Add {} coin(s)'.format(coinChange))
        totalCoinsAdd = totalCoinsAdd + coinChange

again = 'yes'
while again != 'no':
    inputs()
    totalBagsChecked = totalBagsChecked + 1
    again = input('Would you like to weight another bag? ("no" to quit)')

print('Total coins added: {}'.format(totalCoinsAdd))
print('Total coins removed: {}'.format(totalCoinsRemoved))
print('Total bags checked: {}'.format(totalBagsChecked))

Global variables

In general, it is a bad idea to use global variables and it tends to show that there is a problem in the way your code is organised.

In any case, bagWeight does not need to be a global variable.


C++ Heap Sort Implementation Just checking if I could still do it:

#include <iostream>
#include <algorithm>

std::size_t getParent(std::size_t n)
{
    return (n - 1) / 2;
}

template<typename I>
void heapify(I begin, I end)
{
    std::size_t size    = std::distance(begin, end);
    for(std::size_t loop = 1;loop < size; ++loop)
    {
        std::size_t current = loop;
        std::size_t parent  = getParent(current);
        while(current != 0 && *(begin + parent) < *(begin + current))
        {
            std::swap(*(begin + parent), *(begin + current));
            current = parent;
            parent  = getParent(current);
        }
    }
}

template<typename I>
void heapPop(I begin, I end)
{
    I   last = end - 1;
    std::swap(*begin, *last);

    std::size_t size    = std::distance(begin, last);
    std::size_t current = 0;
    while(current < size)
    {
        std::size_t child1  = current * 2 + 1;
        std::size_t child2  = current * 2 + 2;
        std::size_t goodChild = current;

        if (child2 < size)
        {
            goodChild   = (*(begin + child1) > *(begin + child2)) ? child1 : child2;
        }
        else if (child1 < size)
        {
            goodChild   = child1;
        }
        if (*(begin + current) < *(begin + goodChild))
        {
            std::swap(*(begin + current), *(begin + goodChild));
            current = goodChild;
            continue;
        }
        break;
    }
}

template<typename I>
void heap_sort(I begin, I end)
{
    heapify(begin, end);
    while(begin != end)
    {
        heapPop(begin, end);
        --end;
    }
}

int main()
{
    int  data[] = {6,5,3,1,8,7,2,4};
    heap_sort(std::begin(data), std::end(data));
    std::copy(std::begin(data), std::end(data), std::ostream_iterator<int>(std::cout, ", "));
    std::cout << "\n";
}

The heapify and parentfunctions can be avoided:

You just need the sinking logic that you already implemented. But instead of having current always starting at 0 you can set it as a parameter:

template<typename I>
void sink(I begin, I end, std::size_t index)
{

    std::size_t size = std::distance(begin, end);
    std::size_t current = index;
    while (current < size)
    {
        std::size_t child1 = current * 2 + 1;
        std::size_t child2 = current * 2 + 2;
        std::size_t goodChild = current;

        if (child2 < size)
        {
            goodChild = (*(begin + child1) > *(begin + child2)) ? child1 : child2;
        }
        else if (child1 < size)
        {
            goodChild = child1;
        }
        if (*(begin + current) < *(begin + goodChild))
        {
            std::swap(*(begin + current), *(begin + goodChild));
            current = goodChild;
            continue;
        }
        break;
    }
}

Due to the fact that the elements  are leafs you can ignore them, so you just need to apply sink

times to build the heap:

template<typename I>
void heap_sort(I begin, I end)
{
    std::size_t size = std::distance(begin, end);
    for (int i = size / 2 - 1; i > -1; --i)
    {
        sink(begin, end, i);
    }
    while (begin != --end)
    {
        std::swap(*begin, *end);
        sink(begin, end, 0);
    }
}

Alternative sink implementation:

IMO this implementation is more concise:

template<typename I>
void sink(I begin, I end, std::size_t index)
{

    std::size_t size = std::distance(begin, end);
    std::size_t current = index;
    std::size_t child;

    std::less<decltype(*begin)> less;

    while ((child = 2 * current + 1) < size)
    {
        I itr_child   = begin + child;
        I itr_current = begin + current;

        if(child < size - 1
            && less(*itr_child, *(itr_child + 1))
        {
            ++itr_child;
        }

        if (!less(*itr_current, *itr_child))
        {
            break;
        }
        std::swap(*itr_current, *itr_child);
        current = child;
    }
}


Date and time columns conversion to Time(WithZone) I have two columns representing a date and a time.

{dateproc: '2012-03-23', horproc: '2000-01-01 16:15:23 UTC'}

Both are read as a TimeWithZone by Rails. I need to combine them.

This is what I've done. It works, but it doesn't feel elegant, and it just doesn't seem readable.

date_time_combined = dateproc + horproc.seconds_since_midnight.seconds

Any advice on improving it?

Nope. That's about as clean as it'll get, though like Flambino said, you can skip the last .seconds call. It's a bit clunky, but that's just how it works out.


Scraper for Redmart.com I've written a script which is scraping  a webpage encrypted within javascript. The scraper is extracting name, price and image link of certain products from that page. I used selenium in combination with vba to accomplish that. Hope I did it nicely.

Sub Redmart_scraping()
Dim driver As New WebDriver
Dim posts As Object, post As Object

Set driver = New WebDriver
driver.Start "Phantomjs", "https://redmart.com"
driver.get "/bakery"
Set posts = driver.FindElementsByXPath("//li[@class='productPreview  ']")
On Error Resume Next
For Each post In posts
    i = i + 1
    Cells(i, 1) = post.FindElementByXPath(".//h4/a").Text
    Cells(i, 2) = post.FindElementByXPath(".//span[@class='ProductPrice__price___3BmxE']").Text
    Cells(i, 3) = post.FindElementByXPath(".//img[contains(@class,'showImage')]").Attribute("src")
Next post
End Sub

I would improve on handling class attributes. They are multi-valued attributes per definition and your way of checking the class values in the XPath expressions can potentially cause problems.

For instance, @class='productPreview  ' check would fail if there will be one space less at the end of the value. Or, you would also match an element with class="showImageDescription" with the contains(@class,'showImage') check.

One way of dealing with that is to use this workaround which involves using concat().

I would though simply switch to CSS selectors which are generally faster, more concise and handle class attributes naturally:

Set posts = driver.FindElementsByCss("li.productPreview")
On Error Resume Next
For Each post In posts
    i = i + 1
    Cells(i, 1) = post.FindElementByCss("h4 > a").Text
    Cells(i, 2) = post.FindElementByCss("span[class^=ProductPrice__price]").Text
    Cells(i, 3) = post.FindElementByCss("img.showImage").Attribute("src")
Next post

Note the span[class^=ProductPrice__price] selector - I don't think the ___3BmxE part of the class matters much and provides any relevant information - plus, it sounds like a good subject for a change. That's why I've switched to a partial match with "starts with" (^=).


Finding indices of numbers that sum to a target I've taken this algorithm question, which is to find the indexes of any two numbers in an array that sum to a given number. It is quite a simple problem to solve. But it is the execution time of my code algorithm that bugs me.

#include <iostream>
#include <vector>
using namespace std;

class TwoSum
{
public:
  static std::pair<int, int> findTwoSum(const std::vector<int>& list, int TargetSum)
  {
    for (int increment = 0; increment < list.size(); increment++)
    {
        for (int i = 0; i < list.size(); i++)
        {
            if (list.at(increment) + list.at(i) == TargetSum)
            {
                return make_pair(increment, i);
            }
        }
    }
    return make_pair(-1, -1);
  }
};

int main(int argc, const char* argv[])
{
   vector<int> list = {1, 3, 5, 7, 9 };
   int targetSum = 12;
   pair<int, int> indices = TwoSum::findTwoSum(list, targetSum);

   indices.first == -1 && indices.second == -1 ?
   cout << "No vector elements can be added to achieve the target sum" << endl :
   cout << "The target sum can be achieved by adding the vector element " << indices.first << " and " << indices.second;
   cout << endl;

   return 0;
}

It is guaranteed correct as I tested it with the website's compiler (or whatever you call it), they can test your code just by pasting and running it on their code editor. I tested this on my IDE as well, and it worked fine.

The problem is, my code failed the performance test when dealing with large number of vector elements as it took longer than the website's expectation. For me, the function named findTwoSum()is already straightforward. And I don't have any idea how to optimize this function. Note that the test's focus here is the function itself and how fast it executes.

Any modifications in function's return type and parameter is not allowed. As the website stated that you cannot modify the main function's contents, implying that you cannot also change how the function is called.

But I slightly modified the main function for you to know what the program is trying to achieve.

Not quite right

First off, you're checking every cross pair of indices against each other. But that means that findTwoSum({1, 3, 4}, 6) will succeed, even though there is no pair of elements that sum to 6 - because you count the 3 twice. You need: "any two distinct elements".

Iterating over vectors

list is a confusing name for a vector. increment is a poor variable name for this - since it's not incrementing anything, it's just another index, so you really should use i and j instead. Also you don't need at() - that member function does range checking. But your indices will all definitely be in range, so you could simply write:

for (size_t i = 0; i < v.size(); ++i) {
    for (size_t j = i+1; j < v.size(); ++j) { // correcting initial bug
        if (v[i] + v[j] == target) {
            return std::make_pair(i, j);
        }
    }
}
return std::make_pair(-1, -1);

Failure case

Rather than using sentinel values, I prefer to use something like Boost.Optional to indicate failure, so that:

boost::optional<std::pair<int, int>> findTwoSum(const std::vector<int>&, int target);

Classes

Why is findTwoSum a static member function? Just make it a free function. There's no reason for a class. You could instead make TwoSum a namespace but I don't see the point of that either.

The Algorithm

You are checking every pair of indices - that's \$O(n^2)\$. We can do way better. Consider that once we have our first index - there is one unique element that we need to find to see if we have a success case: target - v[i].

We could simply throw all of our indices into a map:

std::unordered_map<int, size_t> indices;
for (size_t i = 0; i < v.size(); ++i) {
    indices.insert(std::make_pair(v[i], i));
}

And then simply search if target - v[i] is in indices for each such i:

for (size_t i = 0; i < v.size(); ++i) {
    auto j = indices.find(target - v[i]);
    if (j != indices.end()) {
        return std::make_pair(i, j->second);
    }
}

This will be \$O(n)\$ to create the hashtable, and then another \$O(n)\$ to do all the searching... for a grand total of \$O(n)\$.


C++ lock wrapper class around pointer I have created a class which wraps pointers and behaves like a pointer would behave, minus a few cases. It is a lock wrapper class which simply locks before usage of the pointer and unlocks once the pointer usage is done.

It must behave exactly like a pointer EXCEPT in the following cases:

It cannot be implicitly converted to the pointer type it is pointing to
It does not handle any implicit memory allocation/deallocation (it provides a method to delete the pointer to the object)
When compared to another wrapper object, it compares their pointers to see if they are the same

Here is what I have so far:

template <class PtrType, class LockType>
class ELockWrapper {
public:
    class Proxy {
    public:
        Proxy(PtrType* p, LockType* lock) : ptr(p), mLock(lock)  { mLock->Lock(); }
        ~Proxy()                                                 { mLock->Unlock(); }
        PtrType* operator->()                                    { return ptr; }
        PtrType  operator*()                                     { return *ptr; }
    private:
        PtrType*    ptr;
        LockType*   mLock;
    };

    ELockWrapper()                            : ptr(nullptr), lock(nullptr) {}
    ELockWrapper(nullptr_t t)                 : ELockWrapper()   {}
    ELockWrapper(PtrType *p, LockType* l)     : ptr(p), lock(l)  {}
    ELockWrapper(PtrType *p, LockType& l)     : ptr(p), lock(&l) {}
    ELockWrapper(const ELockWrapper& copy) = default;

    ELockWrapper& operator=(const ELockWrapper& x) = default;
    bool operator==(const ELockWrapper& cmp) { return cmp.ptr == ptr; }
    bool operator!=(const ELockWrapper& cmp) { return !operator==(cmp); }
    bool operator==(PtrType* t)              { return ptr == t; }
    bool operator!=(PtrType* t)              { return ptr != t; }
    bool operator==(bool b)                  { return (ptr && b) || (!ptr && !b); }
    bool operator!=(bool b)                  { return !operator==(b); }
    operator bool() const                    { return ptr; }

    Proxy operator->() {
        return Proxy(ptr, lock);
    }

    PtrType operator*() {
        return *Proxy(ptr, lock);
    }

    void Delete() {
        Proxy(ptr, lock);
        delete ptr;
    }

private:
    PtrType*    ptr;
    LockType*   lock;
};

Here is it in action with some test cases.

Any mistakes/suggestions would be much appreciated.

One quick thing I want to ask: if ANY of the methods on ELockWrapper can be called concurrently, should I wrap each overloaded boolean operator with a lock? I'm thinking perhaps the delete method will be called, which a thread was interrupted in one of the operators might be problematic. Just a confirmation if this is the right thing to do?

operator== and operator!= should be const.
You need to #include <cstddef> to use nullptr_t.
You are defaulting the copy constructor and assignment operator, but not the move constructor and move assigment operator. That's fine because the defaults are generated anyway, but it is inconsistent, I think.
What is the point of operator==(bool)?
Proxy should be private. You don't want to have users create Proxys.
ELockWrapper does not actually own the pointer it holds. It is copyable and will just copy the pointer it holds. It also does not create anything or delete anything in the constructor/destructor. Nontheless you provide a Delete member. That seems very wrong to me. You don't know how the memory you point to was aquired, it could be with static storage or an array. In both cases calling Delete would cause undefined behavior. The object creating the pointer with new should also be responsible for deleteing it. Calling Delete on two copies of ELockWrapper also causes undefined behavior.
The fact that the pointer is not owned seems to be a major flaw here anyway. Currently the user of your class needs to gurantee that the object pointed to keeps in scope until all ELockWrapper's holding it are destroyed and then it has to take care of proper deletion. Using it outside of ELockWrapper is not allowed. So why not move the responsibility of managing the pointer to ELockWrapper?
The same holds true for the lock. Currently the user needs to provide a suitable lock and keep it live until no ELockWrapper references it anymore. Why not create the lock/mutex inside the constructor from pointer? Though I realize if you do it like this you need to manage references to the lock and you end up with fully reimplementing std::shared_ptr. Therefore I will just assume that this wrapper is explicitly only about locking and not managing ressource lifetime and that the user is required to run the destructors properly.
operator-> is fine if copy elision is performed (not required in C++11, but in C++17), but operator* is not either way. The Proxy object you create in operator* is destroyed before the function returns. That means that Unlock is called before the caller expression using the pointer ends.
operator* currently returns a copy. It should return a reference. At least that is the usual way this operator is interpreted.
In general the approach with operator* and operator-> has some limitations. You may not call either twice in one expression or you have deadlock. But you are also not allowed to save the pointer returned by operator* or a pointer/reference to the object referred because these are not guarded any more by the lock.
I guess it would be much better to let the caller call a aquire which returns a Proxy. Access to the holding pointer is then only allowed via operator* and operator-> of this Proxy. As soon as Proxy goes out of scope its destructor releases the lock, similar to std::lock_guard.

This still allows the user to misuse a saved reference/pointer to the raw object, but at least more than one usage can me made in the same lock aquisition.

An implementation via C++11 standard library would be similar to this (not tested):

template<typename T, typename Mutex>
class ELockWrapper {
    T* t;
    Mutex* mut;

    class Proxy {
        T* t;
        std::unqiue_lock<Mutex> lock;
        Proxy(ELockWrapper& wr) : t(wr->t), lock(wr->mut) { }
        friend ELockWrapper;
    public:
        T& operator*() { return *t; }
        T* operator->() { return t; }
    };

public:
    ELockWrapper() : t(nullptr), mut(nullptr) {}
    ELockWrapper(nullptr_t) : ELockWrapper() {}
    ELockWrapper(T* t, Mutex* mut) : t(t), mut(mut) {}
    ELockWrapper(T* t, Mutex& mut) : t(t), mut(&mut) {}

    Proxy aquire() { return {*this}; }
};


Beginner's simple calculator What do you think about this simple calculator?

while True:
    print('Options:')
    print('Enter \'a\' to add two numbers')
    print('Enter \'s\' to subtract two numbers')
    print('Enter \'m\' to multiply two numbers')
    print('Enter \'d\' to divide two numbers')
    print('Enter \'q\' to quit the program')
    response=str(input(':')).lower()
    if response=='q':
        break
    elif response=='a':
        while True:
           try:
               num1=float(input('Enter a number:'))
               break
           except(TypeError,ValueError):
               print('*(Input Error) Enter valid number*')
               continue
        while True:
            try:
                num2=float(input('Enter another number:'))
                break
            except(TypeError,ValueError):
                print('*(Input Error) Enter valid number*')
                continue
        result=num1+num2
        print('The answer is '+str(result))
        print()
    elif response=='s':
        while True:
            try:
                num1=float(input('Enter a number:'))
                break
            except(TypeError,ValueError):
                print('*(Input Error) Enter valid number*')
                continue
        while True:
            try:
                num2=float(input('Enter another number:'))
                break
            except(TypeError,ValueError):
                print('*(Input Error) Enter valid number*')
                continue
        result=num1-num2
        print('The answer is '+str(result))
        print()
    elif response=='m':
        while True:
            try:
                num1=float(input('Enter a number:'))
                break
            except(TypeError,ValueError):
                print('*(Input Error) Enter valid number*')
                continue
        while True:
            try:
                num2=float(input('Enter another number:'))
                break
            except(TypeError,ValueError):
                print('*(Input Error) Enter valid number*')
                continue
        result=num1*num2
        print('The answer is '+str(result))
        print()
    elif response=='d':
        while True:
            try:
                num1=float(input('Enter a number:'))
                break
            except(TypeError,ValueError):
                print('*(Input Error) Enter valid number*')
                continue
        while True:
            try:
                num2=float(input('Enter another number:'))
                break
            except(TypeError,ValueError):
                print('*(Input Error) Enter valid number*')
                continue
        result=num1/num2
        print('The answer is '+str(result))
        print()
    else:
        print('*Unknown input*')
    continue

Welcome to the world of beginner Python programming, and programming in general!  Python is a nice language to learn and start out with!

Allow me to give you some tips and pointers, with the hope that you will be able to learn a little from them.

Also, allow me to apologize in advance for this massive wall of text.  I may have gone a little bit overboard in my review and analysis, but I wanted to make sure you would understand my revisions and some of the code I've added, in the event you are unfamiliar with the functionality I implement and use in the reviewed and revised code.

Add white space for readability, and obey PEP8 rules for whitespace around assignment and equality operators

Python is extremely indentation-based.  This means an indent usually indicates a code block that needs executed underneath of another one (such as your if statements have, etc).

However, Python also benefits from having white space added at logical locations for readability.  I usually define these locations as between loops and other sections of code, between functional statements (addition, subtraction, etc.) and output, between the end of an if statement and the beginning of its elif or else blocks, after the end of an entire if block, etc.

There is also a rule for Python code style, called the PEP8 which dictates whitespace around assignment statements, equality operators (such as ==), and also arithmetic operators (+, -, *, /, and others), stating that a space is necessary around them.

This is your code with the whitespace per my guidelines and the PEP8 guidelines.  My further reviews from here will be using this as a base.

while True:
    print('Options:')
    print('Enter \'a\' to add two numbers')
    print('Enter \'s\' to subtract two numbers')
    print('Enter \'m\' to multiply two numbers')
    print('Enter \'d\' to divide two numbers')
    print('Enter \'q\' to quit the program')

    response = str(input(':')).lower()

    if response == 'q':
        break

    elif response == 'a':
        while True:
            try:
                num1 = float(input('Enter a number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        while True:
            try:
                num2 = float(input('Enter another number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        result = num1 + num2

        print('The answer is ' + str(result))
        print()

    elif response == 's':
        while True:
            try:
                num1 = float(input('Enter a number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        while True:
            try:
                num2 = float(input('Enter another number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        result = num1 - num2

        print('The answer is ' + str(result))
        print()

    elif response == 'm':
        while True:
            try:
                num1 = float(input('Enter a number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        while True:
            try:
                num2 = float(input('Enter another number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        result = num1 * num2

        print('The answer is ' + str(result))
        print()

    elif response == 'd':
        while True:
            try:
                num1 = float(input('Enter a number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        while True:
            try:
                num2 = float(input('Enter another number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        result = num1 / num2

        print('The answer is ' + str(result))
        print()

    else:
        print('*Unknown input*')

    continue

Move non-quit responses to separate "if" block, so we can do some tasks without repeating code.

One of the major guidelines of programming is that if you are doing something that requires you to copy and paste code in all the time to do the same thing, chances are there's a better implementation.

You currently do this in every single block of code under each conditional check for the response entered, except for quitting and invalid responses:

while True:
    try:
        num1 = float(input('Enter a number:'))
        break
    except(TypeError, ValueError):
        print('*(Input Error) Enter valid number*')
        continue

while True:
    try:
        num2 = float(input('Enter another number:'))
        break
    except(TypeError, ValueError):
        print('*(Input Error) Enter valid number*')
        continue

We can easily move this to outside the if block, if we separate the a, s, m, and d response checks to somewhere else, so we don't have to repeat all the code, which actually will save you a lot of lines of code.  This is the new set of if/elif statements, with the 'quit' response checked before we even begin to look at other responses, and the deletion of the "else" clause that you had in there:

if response == 'q':
    break

while True:
    try:
        num1 = float(input('Enter a number:'))
        break
    except(TypeError, ValueError):
        print('*(Input Error) Enter valid number*')
        continue

while True:
    try:
        num2 = float(input('Enter another number:'))
        break
    except(TypeError, ValueError):
        print('*(Input Error) Enter valid number*')
        continue

if response == 'a':
    result = num1 + num2

elif response == 's':
    result = num1 - num2

elif response == 'm':
    result = num1 * num2

elif response == 'd':
    result = num1 / num2

Note that while I drop the "Unknown Input" check (that else statement at the end), we're going to add it back in elsewhere in the code in my next recommendation.

Move "Invalid Input" check to second thing checked in the if/elif block for "Quit" checking

This recommendation builds from the previous recommendation above this one; it should not be implemented without the previous recommendation, as it builds off of the previous recommendation

You'll note that I removed the else block that handled "Unknown Input" captures in my earlier recommendation.  That's because we can implement it in a better place, and earlier on in the code, and handle things as a "Check if input is valid before anything else" approach, which is what we'll cover in this section.

Basically, we don't need to put the "Invalid Input" check at the bottom.  Instead, we can check it at the beginning!

This is the code that will do that:

if response == 'q':
    break
elif response not in 'asmd':
    print('*Unknown input*')
    continue

Because you're a beginner, let me break down the elif here.  Basically this says "Is the value of response contained within this string of valid response characters?", and if it is not, then it will print the "Unknown Input" error, and continue on to the next iteration of the loop - skipping all other code below it.

Unnecessary continue statement at end of loop

In your original code, you have the continue statement at the end of the code underneath the while loop.  This is unnecessary - when the end of the code under the loop is reached, it will automatically continue on to the next iteration, and you don't need the continue statement here.

You can just remove that continue statement.

Improper checking of 'length' of response

This builds off my two earlier recommendations for changing your if and elif blocks for "Quit" and "Invalid Response" to their own block at the beginning, and then have a separate if/elif block for response checking only.

So, in my recommendations, I don't properly check the length of the response provided.  That means I potentially introduce breakage where it's listed as "unknown input"  So, let's do that as part of "Invalid Input" checks, by checking if the length of the response is greater than one, or if it's not in the 'valid responses' we defined.  The code below does that.

if response == 'q':
    break
elif len(response) > 1 or response not in 'asmd':
    print('*Unknown input*')
    continue

Make Output and Options Prompt a little cleaner

This is more or less up to each programmer, but I believe that the output and prompts you use are a little... cluttered, and harder to read.  I also believe input could be better handled in terms of providing users with the prompt.

Let's start with the options prompt first.  We can reorganize and revise these to make output a little nicer, and grab the option in a nicer way than just a colon and a prompt line:

print('Enter \'a\' to add two numbers')
print('Enter \'s\' to subtract two numbers')
print('Enter \'m\' to multiply two numbers')
print('Enter \'d\' to divide two numbers')
print('Enter \'q\' to quit the program')

response = str(input('Select an option: ')).lower()

Note that we got rid of that first print("Options:") item.  You can add it back in if you want.

Next, let's work on the prompts for the two numbers being worked with, and the output.  I think it would benefit from some line breaks to sort of 'separate up' the content to make it a little more readable.

I'd like to introduce you to an escaped character sequence: \n.  In a string, \n is interpreted as a line break, which generates a blank line in the usages I'm putting in place here when actually displayed to the user.

The following lines should be changed accordingly, to make your output a little nicer:

num1 = float(input('Enter a number:')) should become num1 = float(input('\nEnter a number: '))
num2 = float(input('Enter another number:')) should become num2 = float(input('\nEnter another number: '))
print('The answer is ' + str(result)) should become print('\nThe answer is ' + str(result) + '\n')
print() should become print('------------------\n').

This results in program output a little like this, then (using a, 1, and 1):

Enter 'a' to add two numbers
Enter 's' to subtract two numbers
Enter 'm' to multiply two numbers
Enter 'd' to divide two numbers
Enter 'q' to quit the program
Select an option: a

Enter a number: 1

Enter another number: 1

The answer is 2.0

------------------

Enter 'a' to add two numbers
Enter 's' to subtract two numbers
Enter 'm' to multiply two numbers
Enter 'd' to divide two numbers
Enter 'q' to quit the program
Select an option: q

Avoid escaping ' characters, by using " around the strings containing them

This was originally pointed out in comments by Dex'ter.

In your print statements where you print out the list of available options for the user, you can avoid having to use \' to escape the 's by using the quotation marks around the entire string instead of apostrophes., like so:

print("Enter 'a' to add two numbers")
print("Enter 's' to subtract two numbers")
print("Enter 'm' to multiply two numbers")
print("Enter 'd' to divide two numbers")
print("Enter 'q' to quit the program")

Complete Code, After Recommendations

This is the code, after all my recommendations from above implemented, in its entirety:

while True:
    print("Enter 'a' to add two numbers")
    print("Enter 's' to subtract two numbers")
    print("Enter 'm' to multiply two numbers")
    print("Enter 'd' to divide two numbers")
    print("Enter 'q' to quit the program")

    response = str(input('Select an option: ')).lower()

    if response == 'q':
        break
    elif len(response) > 1 or response not in 'asmd':
        print('*Unknown input*\n')
        continue

    while True:
        try:
            num1 = float(input('\nEnter a number: '))
            break
        except(TypeError, ValueError):
            print('*(Input Error) Enter valid number*')
            continue

    while True:
        try:
            num2 = float(input('\nEnter another number: '))
            break
        except(TypeError, ValueError):
            print('*(Input Error) Enter valid number*')
            continue

    if response == 'a':
        result = num1 + num2

    elif response == 's':
        result = num1 - num2

    elif response == 'm':
        result = num1 * num2

    elif response == 'd':
        result = num1 / num2

    print('\nThe answer is ' + str(result) + '\n')
    print('------------------\n')


Eliminating empty spreadsheet cells from a range I am copying data, that is one long list, into an excel sheet and I want to use a macro to organize it visually.  The problem is that the data I am copying has empty cells that are unnecessary and will inhibit my code later in the macro and I want to get rid of them.  This is what I came up with, but I am hoping there is a more efficient way to do it.  The main problem I ran into in trying other methods is I couldn't set a value to a variable to end the second "For" statement before it tried to select a cell that doesn't exist. After it got to the first row it would keep running and would return an error on "ActiveCell.Offset(-1, 0).Range("A1").Select" because there was no cell to select.

Data example:

1, ,2, ,1, ,3, ,1, ,2, ,1, ,4, ,1, ,2, ,1, ,3, ,1, ,2, ,1,...

1, , ,1, , ,2, , ,1, , ,1, , ,2, , ,1, , ,1, , ,3, , ,1, ,...

Each comma represents a new cell, with the numbers and spaces (empty cells) in the same column.

My code:

Sub Organize_Data()

Dim n As Integer
Dim h As Integer
Dim t As Integer
h = 1000
t = h - 1

Cells(h, 1).Select
For n = 1 To t
    If IsEmpty(ActiveCell) Then
    ActiveCell.Offset(-1, 0).Range("A1").Select
    h = h - 1
    Else
    n = t
    End If
Next n

t = h - 1

For n = 1 To t
    If IsEmpty(ActiveCell) Then
    Selection.Delete Shift:=xlUp
    ActiveCell.Offset(-1, 0).Range("A1").Select
    h = h - 1
    Else
    ActiveCell.Offset(-1, 0).Range("A1").Select
    h = h - 1
    End If
Next n

End Sub

Data After Macro:

1,2,1,3,1,2,1,4,1,2,1,3,1,2,1,...

1,1,2,1,1,2,1,1,3,1,...

Possibilities:

I was thinking that in place of the first "For" statement I could use

Selection.End(xlUp).Select

but I don't know how I would set the variable "t" so that the "For" Statement would end before it tried to select a cell that didn't exist.
The other thing I can think of is maybe there is code that I could use for a third part to the "If" statement in the second "For" statement that will stop the "For" statement when it is in the first row.

You're working off Selection. That's "good enough" for macro-recorder code, which mimicks a user's interactions with a worksheet.

VBA code can do that, sure. But why merely mimick a user's interactions with a worksheet when you have the entire Excel object model in your hands?

But before we look at different/better ways to accomplish what this code does, let's take a look at what it's doing:

h is initialized at an arbitrary value of 1000. See this SO answer for a very detailed explanation of various ways to locate the last row that contains data on a worksheet. For example this would set h to the last row with data in column A:

h = ActiveSheet.Range("A" & ActiveSheet.Rows.Count).End(xlUp).Row

By working off the actual last row, you avoid extraneous iterations later, and avoid having to modify your code if/when the worksheet starts containing more than 1000 rows.
We Select the first cell in the 999th row, and then start looping from 1 to 999.

If the ActiveCell is empty, we move up a row; else, we... wait a minute... we reassign the loop variable back to 999??

It's pretty hard to understand what's happening here, and more importantly, why - and explaining why something is happening is exactly what comments are for!

'this loop sets n to the last row with data (right?)

Okay, let's stop here, and look again at what we're trying to accomplish.

We want to delete rows where column A is empty. By adapting this answer to Conditionally deleting rows in a worksheet, we can enormously simplify what's going on here - the key being this little function:

Private Function CombineRanges(ByVal source As Range, ByVal toCombine As Range) As Range
    If source Is Nothing Then
        Set CombineRanges = toCombine
    Else
        Set CombineRanges = Union(source, toCombine)
    End If
End Function

Equipped with this simple tool, we can now iterate our rows once, "union" all empty cells, and delete them all at once:

Public Sub CleanUpActiveSheet()

    Dim target As Worksheet
    Set target = ActiveSheet

    Dim lastRow As Long
    lastRow = target.Range("A" & target.Rows.Count).End(xlUp).Row

    Dim toDelete As Range

    Dim currentRow As Long
    For currentRow = 1 To lastRow
        If IsEmpty(target.Cells(currentRow, 1)) Then
            Set toDelete = CombineRanges(toDelete, target.Cells(currentRow, 1))
        End If
    Next

    If Not toDelete Is Nothing Then toDelete.Delete xlUp

End Sub

Notice:

Consistent indentation makes it easier to identify where code blocks begin and end.
Meaningful variable names make it easier to understand what's going on and why.
Variables being declared closer to their usage (as opposed to "at the top of the procedure") makes reading the code more fluid.
Working with object references instead of against the current Selection makes the code much more straightforward.
Variables meant to hold a row number are declared as Long, because a 64-bit worksheet can have [many] more than 65,535 rows.
Procedure names are PascalCase; avoid using underscores in procedure names, VBA uses them for private Object_EventName handlers and Interface_Member implementation procedures.


Movie repository for storing movies based on country The domain model of my application revolves around movies.

Use case:

We have a movie for which only one title (in one country) is known and we want to know titles of this movie in other countries. To get that information, we call external movie repositories.

The Movie class has a map of titles in countries. It also has a list of external IDs. For example, we might know that IMDB's ID for the movie Breakfast at Tiffany's is tt0054698.

class Movie {

    private Map<Country, String> titles;
    private Year yearOfRelease;
    private Map<ExternalMovieRepository, String> externalIds;

    public Map<Country, String> titles() {
        return titles;
    }

    public Year yearOfRelease() {
        return yearOfRelease;
    }

    public Map<ExternalMovieRepository, String> externalIds() {
        return externalIds;
    }

}

The ExternalMovieRepository enum is used as a key to which external ID value is mapped.

enum ExternalMovieRepository {

    IMDB, ROTTEN_TOMATOES;

}

The classes representing the external movie repositories will be able to find additional information only for Movie instances carrying some information the repository requires.

For example, RottenTomatoesMovieRepository requires the Movie instance either to have a US movie title (<Country, String> map entry) or the Rotten Tomatoes' external ID in its externalIds map.

Here is a draft for an interface that could represent the external repositories:

/**
 * Finds movie title for other countries using information from Movie.
 *
 */
interface MovieTitleFinder {

    boolean accepts( Movie m );

    Map<Country, String> findTitles( Movie m );

}

An implementation could look like this:

class RottenTomatoesTitleFinder implements MovieTitleFinder {

    private final String US_ISO = "us";

    private CountryRepository countryRepository;

    RottenTomatoesTitleFinder( CountryRepository countryRepository ) {
        this.countryRepository = countryRepository;
    }

    @Override
    public boolean accepts( Movie m ) {
        return ( getUSTitle( m ) != null || getRTId( m ) != null );
    }

    @Override
    public Map<Country, String> findTitles( Movie m ) {
        String rtId = getRTId( m );
        if ( rtId != null ) {
            return findByRTid( rtId );
        }
        String usTitle = getUSTitle( m );
        if ( usTitle != null ) {
            return findByUSTitle( usTitle );
        }
        return Collections.emptyMap();
    }

    private String getUSTitle( Movie m ) {
        Country us = countryRepository.findByIso( US_ISO );
        return ( m.titles().get( us ) );
    }

    private String getRTId( Movie m ) {
        return ( m.externalIds().get( ExternalMovieRepository.ROTTEN_TOMATOES ) );
    }

    private Map<Country, String> findByUSTitle( String usTitle ) {
        // call some collaborating object
    }

    private Map<Country, String> findByRTid( String rtId ) {
        // call some collaborating object
    }

}

Could this design be improved?

One thing - this design is based on a false premise - that there is only ever a single title within a given country. See for example this movie which has 3 USA titles (albeit only one, final, official title). This can be fixed by changing the Country key of the hash map to a TitleType (which will often be just a country).

Another problem is that Movie isn't really an object - it doesn't implement any member functions. In fact, your RottenTomatoesTitleFinder works by directly manipulating Movie properties rather than calling Movie member functions. This is a violation of basic OO principles.


Simple atomic pseudo-random number generation I like to use a single global PRNG in my c programs (similar to Javascript's Math.random) because it simplifies things and the unpredictable nature of a global is quite fitting for a PRNG. I recently started using multithreading more so I adapted my global PRNG by making it atomic.

Besides the obvious, it is meant to be atomic in such a way that two threads requesting a pseudo-random number simultaneously won't get the same number in the sequence of pseudo-random numbers. Using a CAS-loop seems to be the only way of accomplishing this, if there is a better way do let me know.

Primarily I'm looking for confirmation that it actually is atomic. Note that struct randomic isn't the same as randomic, the latter is a typedef of _Atomic struct randomic. Admittedly not the best naming ever.

The real magic happens in randomicNext but the whole thing is pretty small so I've included all of it. It can also be found on github.

//include only once
#ifndef RANDOMIC_H
#define RANDOMIC_H

//process configuration
#ifdef RANDOMIC_STATIC
    #define RANDOMIC_IMPLEMENTATION
    #define RADEF static
#else //RANDOMIC_EXTERN
    #define RADEF extern
#endif

//includes
#include <stdatomic.h>
#include <stdint.h>

//types
typedef _Atomic struct randomic {
    uint32_t a, b, c, d;
} randomic;

//function declarations
RADEF void randomicSeed(randomic*, uint32_t);
RADEF float randomicFloat(randomic*, float, float);
RADEF double randomicDouble(randomic*, double, double);
RADEF uint32_t randomicNext(randomic*);

//implementation section
#ifdef RANDOMIC_IMPLEMENTATION

//function declarations
static struct randomic randomicInternal(struct randomic);

//public functions
RADEF void randomicSeed (randomic* rdic, uint32_t seed) {
    struct randomic ctx;
    ctx.a = 0xf1ea5eed;
    ctx.b = ctx.c = ctx.d = seed;
    for (int i = 0; i < 20; i++)
        ctx = randomicInternal(ctx);
    atomic_store(rdic, ctx);
}
RADEF float randomicFloat (randomic* rdic, float a, float b) {
    return a + (b-a)*((float)randomicNext(rdic)/(float)UINT32_MAX);
}
RADEF double randomicDouble (randomic* rdic, double a, double b) {
    return a + (b-a)*((double)randomicNext(rdic)/(double)UINT32_MAX);
}
RADEF uint32_t randomicNext (randomic* rdic) {
    struct randomic ctx = atomic_load(rdic), ntx;
    while (!atomic_compare_exchange_weak(rdic, &ctx, (ntx = randomicInternal(ctx))));
    return ntx.d;
}

//internal functions
static struct randomic randomicInternal (struct randomic ctx) {
    uint32_t e = ctx.a - ((ctx.b << 27)|(ctx.b >> 5));
    ctx.a = ctx.b ^ ((ctx.c << 17)|(ctx.c >> 15));
    ctx.b = ctx.c + ctx.d;
    ctx.c = ctx.d + e;
    ctx.d = e + ctx.a;
    return ctx;
}

#endif //RANDOMIC_IMPLEMENTATION
#endif //RANDOMIC_H

Primarily I'm looking for confirmation that it actually is atomic.

Yes, it appears atomic.

Other issues

Range and precision

randomicDouble() needs more functional explanation about  range and precision.  It seems to attempt an about linear distribution between [a...b]   (b included).

A range of [a...b)  (b excluded) is quite common.  So detailing the coding goal is important.

The code fails to provide a full precision random number.  Simple example: randomicDouble(1.0, 2.0) typically has about 253 different values in the [1.0...2.0) range and this code only supplies 232 different values.

With randomicDouble(), perhaps sometimes 2 calls to randomicNext() are needed.

To provide a linear distribution with randomicDouble(1.0, 4.0) is trickier given the change in absolute precision between  [1.0...2.0) and  [2.0...4.0). randomicDouble(0.0, 1.0) is even tricker.

Initialization

Code passes in only a 32-bit initialization whereas the state is 128-bit.  I'd expect at least a 64-bit initialization if not a full 128-bit one.

Mnior

20 is a magic number in for (int i = 0; i < 20; i++) and deserves explanation.


Convert roman to arabic I started to teach myself Haskell recently. Here is some code I wrote to convert a roman numeral into an arabic numeral:

import Control.Arrow ((>>>))
import Data.Maybe (fromJust)

fromRoman :: String -> Int
fromRoman = translateFromRoman >>> applyNegationRule >>> sum

translateFromRoman :: String -> [Int]
translateFromRoman = map (\r -> fromJust $ lookup r [('I',1),('V',5),('X',10),('L',50),('C',100),('D',500),('M',1000)])

applyNegationRule :: [Int] -> [Int]
applyNegationRule [x]      = [x]
applyNegationRule (x:y:xs) = (if x < y then -x else x) : applyNegationRule (y:xs)

I like it quite a bit. But some questions remain. First of all I never (at least I can't remember) came across (>>>) in other code so far. Everyone seems to use:

fromRoman :: String -> Int
fromRoman = sum . applyNegationRule . translateFromRoman

It produces the same output, but for me as someone used to read from top left to bottom right the first variant is just more readable. You could also write it like this:

fromRoman :: String -> Int
fromRoman = translateFromRoman
        >>> applyNegationRule
        >>> sum

To make it even more text like readable. So where's the catch?

Another question arising from this code is: Should I define the functions translateFromRoman and applyNegationRule in fromRoman ... where? Again I see it quite a lot but IMHO it also lacks readability. At the moment readability is one of the most important metrics for me to determine code quality.

And last but note least: Am I doing something bad in translateFromRoman and applyNegationRule or are there some better (faster/shorter or ofcourse more readable) alternatives?

Since the Roman numerals are fixed and known in advance, it would be more efficient to write:

translateRomanDigit :: Char -> Int
translateRomanDigit 'I' = 1
translateRomanDigit 'V' = 5
...

translateFromRoman = map translateRomanDigit

The compiler can implement translateRomanDigit as a jump table or as a binary search. Using lookup will always perform a linear search.

As for >>> vs . - there should be no difference except that >>> requires you to import Control.Arrow whereas . is provided for in the Prelude.


Filter out URLs with any of some given file extensions I wrote some code to filter a list of links, URLs, with multiple conditions given by file extensions. I want to remove every URL that is not an HTML file. The code is:

avoid = [".pptx", ".ppt", ".xls", ".xlsx", ".xml", ".xlt", ".pdf",
         ".jpg", ".png", ".svg", ".doc", ".docx", ".pps"]

links = ["http://www.abc.com", "http://www.abc.com/file.pdf",
         "http://www.abc.com/file.png"]

def analyse_resource_extension(url):
    match = [ext in url for ext in avoid]
    return any(element is True for element in match)

links = list(filter(lambda x: analyse_resource_extension(x) is False, links))

so that links finishes with ["http://www.abc.com"] as only value. This solution seems kind of wordy for me. Is there any way to perform the same action without using the analyse_resource_extension function?

Strictly speaking, there is no direct correlation between the URL string and the type of the content you are going to get when following the URL - there can be, for instance, redirects; or the url leading to a, say, image file would not have the filename with an extension in it (example). And, keeping the list of disallowed extensions does not scale well.

An alternative, slower, but more reliable way would be to actually visit the URLs (we can use "lightweight" HEAD requests for it) and check the Content-Type header. Something like:

import requests

links = ["http://www.abc.com", "http://www.abc.com/file.pdf",
         "http://www.abc.com/file.png"]

with requests.Session() as session:
    links = [link for link in links
             if "text/html" in session.head(link).headers["Content-Type"]]
    print(links)

Note that to improve on speed, we are also using the same Session object, which reuses the underlying TCP connection:

  ..if you're making several requests to the same host, the underlying TCP
  connection will be reused, which can result in a significant
  performance increase..

Demo (using httpbin):

In [1]: import requests

In [2]: links = ["https://httpbin.org/html",
   ...:          "https://httpbin.org/image/png",
   ...:          "https://httpbin.org/image/svg",
   ...:          "https://httpbin.org/image"]

In [3]: with requests.Session() as session:
   ...:     links = [link for link in links
   ...:              if "text/html" in session.head(link).headers["Content-Type"]]
   ...:     print(links)
   ...:
['https://httpbin.org/html']

You can even take it a step further and solve it with asyncio and aiohttp:

import asyncio

import aiohttp

@asyncio.coroutine
def is_html(session, url):
    response = yield from session.head(url, compress=True)
    print(url, "text/html" in response.headers["Content-Type"])

if __name__ == '__main__':
    links = ["https://httpbin.org/html",
             "https://httpbin.org/image/png",
             "https://httpbin.org/image/svg",
             "https://httpbin.org/image"]
    loop = asyncio.get_event_loop()

    conn = aiohttp.TCPConnector(verify_ssl=False)
    with aiohttp.ClientSession(connector=conn, loop=loop) as session:
        f = asyncio.wait([is_html(session, link) for link in links])
        loop.run_until_complete(f)

Prints:

https://httpbin.org/image/svg False
https://httpbin.org/image False
https://httpbin.org/image/png False
https://httpbin.org/html True


Implementing a word-chain checker This is web exercise 3.1.45. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:

Write a program that reads in a list of words from the command line
and prints true if they form a word chain and false otherwise. In a
word chain, adjacent words must differ in exactly one letter, e.g.,
HEAL, HEAD, DEAD, DEED, DEER, BEER.

Here is my program:
public class WordChainChecker
{
    public static boolean checkWordCouple(String word1, String word2)
    {
        int counter = 0;
        int wordLength = word1.length();
        for (int i = 0; i < wordLength; i++)
        {
            if (word1.charAt(i) != word2.charAt(i)) counter++;
        }
        if (counter > 1) return false;
        else             return true;
    }
    public static void main(String[] args)
    {
        String word1 = StdIn.readString();
        String word2 = StdIn.readString();
        boolean truth = true && checkWordCouple(word1,word2);
        while (!StdIn.isEmpty())
        {
            word1 = StdIn.readString();
            truth = truth && checkWordCouple(word1,word2);
            word2 = word1;
        }
        System.out.println(truth);
    }
}

StdIn is a simple API written by the authors of the book. I checked my program and it works.
Is there any way that I can improve my program?
Thanks for your attention.

Requirements
Number of words
Are you guaranteed to have at least 2 words?  If so, you could simplify your loop, by removing the first read; the loop will take care of the second & subsequent words:
    String word2 = StdIn.readString();
    boolean truth = true;
    while (!StdIn.isEmpty())
    {
        String word1 = StdIn.readString();
        truth = truth && checkWordCouple(word1,word2);
        word2 = word1;
    }

Although now if given a single word, it will produce true.  This may be an improvement, but you’d need to check the exact requirements to be sure.
Word Length
Is HEAD, HEAL, TEA, TO a word chain?  Your program says it is!
What about HEAD, HEAL, HEALTHY?  That input causes your program to crash!
Your program should handle mismatched word length, unless the problem statement guarantees all inputs will be the same length.
Number of Differences
The problem description says:

In a word chain, adjacent words must differ in exactly one letter

but HEAD, HEAD, HEAD, HEAD is reported as "true".  Clearly, counter > 1 is not the correct "false" condition.  Borrowing Doi9t's suggestion, and further improving it, the correct line would read:
return counter == 1;

Self Documenting Code
You read word1, then word2, and compare the first to the second (let’s call that “forward”), then read a third into word1, and compare the third to the second (comparison in the “reverse” direction).  You are testing for one difference, so it works, but what if you were checking for one additional character?  By reversing the word order, you’d actually be testing for character removal!
Instead of word1 & word2, maybe previous_word and next_word would help keep things clearer.
    String previous_word = StdIn.readString();
    boolean truth = true;
    while (!StdIn.isEmpty())
    {
        String next_word = StdIn.readString();
        truth = truth && checkWordCouple(previous_word, next_word);
        previous_word = next_word;
    }


Usage of the ternary "?:" operator with functions listening to click events I've recently been doing some mods to some old code I've been maintaining for a couple of years now.

As part of a wider set of scripts using YAHOO YUI 2.2 (yes, that old) for dialog-style panels, I have a function that listens to click events on 3 buttons in a given panel set:

addFooListeners = function (panelType) {

    YAHOO.util.Event.addListener("show" + panelType, "click", showFoo, eval(ns + ".panel_" + panelType), true);
    YAHOO.util.Event.addListener("hide" + panelType, "click", hideFoo, eval(ns + ".panel_" + panelType), true);
    YAHOO.util.Event.addListener("commit" + panelType, "click", commitFoo, eval(ns + ".panel_" + panelType), true);

}

This code is the result of a number of panels/dialogs having near identical behaviour.

For this round of development I've needed to add the ability to do things a little differently from time to time, so I added an object, overrides which allows me to point the show, hide and commit actions elsewhere.  I came up with the following:

addFooListeners = function (panelType, overrides) {

    var handlers = {
        show: ( overrides != null ? ( overrides.show != null ? overrides.show : showFoo ) : showFoo ),
        hide: ( overrides != null ? ( overrides.hide != null ? overrides.hide : hideFoo ) : hideFoo ),
        commit: ( overrides != null ? ( overrides.commit != null ? overrides.commit : commitFoo ) : commitFoo )
    }

    YAHOO.util.Event.addListener("show" + panelType, "click", handlers.show, eval(ns + ".panel_" + panelType), true);
    YAHOO.util.Event.addListener("hide" + panelType, "click", handlers.hide, eval(ns + ".panel_" + panelType), true);
    YAHOO.util.Event.addListener("commit" + panelType, "click", handlers.commit, eval(ns + ".panel_" + panelType), true);
}

As you can see I'm enforcing default behaviour unless an appropriate attribute in the overrides object is set with another function (named or anonymous).

Is there a cleaner / more readable way to concisely setup the handlers object?  The nested ternary seems to my eyes to be cluttering things a bit but other approaches like if ( overrides != null ) { ... } seem just as messy.

Let's do some fixing. First, this is how you pass optional (non-boolean) parameters in JS (the Good Waytm):

addFooListeners = function (panelType, handlers) {
    handlers        = handlers        || {};
    handlers.show   = handlers.show   || showFoo;
    handlers.hide   = handlers.hide   || hideFoo;
    handlers.commit = handlers.commit || commitFoo;

The above can be rewritten in a neater way using jQuery (not sure what the name of YUI equivalent to extend is):

handlers = $.extend({
    show  : showFoo,
    hide  : hideFoo,
    commit: commitFoo
}, handlers || {})

Now, using eval for this code is criminal. Say the object ns refers to is module, then you can do this instead of eval:

YAHOO.util.Event.addListener("show" + panelType, "click", handlers.show, module["panel_" + panelType], true);
YAHOO.util.Event.addListener("hide" + panelType, "click", handlers.hide, module["panel_" + panelType], true);
YAHOO.util.Event.addListener("commit" + panelType, "click", handlers.commit, module["panel_" + panelType], true);

Now, as you can see, you are assigning a lot of events in a similar fashion. Did you think of defining an addPanelListener function within your function?

function addPanelListener (event, panelType, handler) {
    YAHOO.util.Event.addListener(event + panelType, "click", handler, module["panel_" + panelType], true);
}

addPanelListener("show"  , panelType, handlers.show);
addPanelListener("hide"  , panelType, handlers.hide);
addPanelListener("commit", panelType, handlers.commit):

Hope it helps.


UIButton subclass with animated 'shimmer' effect In earlier versions of iOS the lock screen had a 'slide to unlock' element which I'm referencing as a 'shimmer' effect.

The effect I'm looking for is simpler:

Button starts with single color (e.g. blue)
a band of color (e.g. red) sweeps across the text label from left to right
Repeat

Here's an example of my ShimmerButton class in action, and the code itself:

class ShimmerButton: UIButton {

    private let wrapperLayer = CALayer()
    private let gradientLayer = CAGradientLayer()

    var gradientColors: [UIColor] = [] {
        didSet {
            gradientLayer.colors = gradientColors.map({ $0.cgColor })
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // only needs to be set once, but no harm (?) in setting multiple times
        gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
        wrapperLayer.addSublayer(gradientLayer)
        layer.insertSublayer(wrapperLayer, at: 0)
        wrapperLayer.mask = titleLabel?.layer

        // update sublayers based on new frame
        wrapperLayer.frame = frame
        gradientLayer.frame.size = CGSize(width: frame.width * 4, height: frame.height)

        // remove any existing animation, and re-create for new size
        let animationKeyPath = "position.x"

        gradientLayer.removeAnimation(forKey: animationKeyPath)

        let animation: CABasicAnimation = CABasicAnimation(keyPath: animationKeyPath)

        animation.fromValue = bounds.width - gradientLayer.bounds.width / 2
        animation.toValue = gradientLayer.bounds.width / 2
        animation.duration = 3

        animation.repeatCount = HUGE
        animation.fillMode = kCAFillModeForwards
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)

        gradientLayer.add(animation, forKey: animationKeyPath)
    }
}

Example usage:

let shimmer = ShimmerButton(frame: .zero)
shimmer.backgroundColor = .white
shimmer.setTitle("Find new skills...", for: .normal)
shimmer.titleLabel?.font = UIFont.systemFont(ofSize: 24, weight: UIFontWeightHeavy)
shimmer.sizeToFit()
shimmer.gradientColors = [.blue, .blue, .red, .blue, .blue]

Some questions:

Code that only needs to be once off is happening in layoutSubviews so will be called multiple times. I did this so I didn't have to override init?(coder:) and init(frame:). Is this acceptable, or just lazy on my part?
I'm animating the position of a CAGradientLayer to get the visual effect, but found that I needed to use another layer as a wrapper otherwise the text itself would move. Am I overlooking a solution that involves fewer layers?

Okay, so sometimes posting a question is the best way to figure out an  answer yourself .

I was looking for an alternative to having the gradient colors evenly spaced (my hack was to repeat the colors e.g. "blue blue red blue blue") and found the locations property on CAGradientLayer which is also animatable.

Animating this property feels like a much better approach because with the position not changing I can remove the wrapper layer.

Then, with without the wrapper layer I realized that I could override layerClass so the buttons backing layer is a gradient layer, which will also resize as needed when the view frame changes so that I don't even need to override layoutSubviews.

The only thing that feels a little strange is the forced requirement for for gradient colors to have three colors (otherwise I'd need to figure some formula to derive values for locations).

Edit: I've updated answer so instead of directly setting the colors, I've exposed gradientTint and gradientHighlight properties that are used to set the gradients colors array.

I've created a protocol that captures the properties used to define the shimmer effect, and also provide a default implementation of the animation.

It wasn't a requirement from my original question, but moving this code out of a specific subclass makes this snippet of code reusable (and maintainable) across other subclasses (e.g. UIView, UILabel).

protocol ShimmerEffect {
    var animationDuration: TimeInterval { set get }
    var animationDelay: TimeInterval {set get }

    var gradientTint: UIColor { set get }
    var gradientHighlight: UIColor { set get }

    //// Expects value between 0.0—1.0 that represents
    //// the ratio of the gradient highlight to the full
    //// width of the gradient.
    var gradientHighlightRatio: Double { set get }

    //// The layer that the gradient will be applied to
    var gradientLayer: CAGradientLayer { get }
}

Default implementation:

extension ShimmerEffect {

    /// Configures, and adds the animation to the gradientLayer
    func addShimmerAnimation() {

        // `gradientHighlightRatio` represents how wide the highlight
        // should be compared to the entire width of the gradient and
        // is used to calculate the positions of the 3 gradient colors.
        // If the highlight is 20% width of the gradient, then the
        // 'start locations' would be [-0.2, -0.1, 0.0] and the
        // 'end locations' would be [1.0, 1.1, 1.2]
        let startLocations = [NSNumber(value: -gradientHighlightRatio), NSNumber(value: -gradientHighlightRatio/2), 0.0]
        let endLocations = [1, NSNumber(value: 1+(gradientHighlightRatio/2)), NSNumber(value: 1+gradientHighlightRatio)]
        let gradientColors = [gradientTint.cgColor, gradientHighlight.cgColor, gradientTint.cgColor]

        // If the gradient highlight ratio is wide, then it can
        // 'bleed' over into the visible space of the view, which
        // looks particularly bad if there is a pause between the
        // animation repeating.
        // Shifting the start and end points of the gradient by the
        // size of the highlight prevents this.
        gradientLayer.startPoint = CGPoint(x: -gradientHighlightRatio, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1+gradientHighlightRatio, y: 0.5)
        gradientLayer.locations = startLocations
        gradientLayer.colors = gradientColors

        let animationKeyPath = "locations"

        let shimmerAnimation = CABasicAnimation(keyPath: animationKeyPath)
        shimmerAnimation.fromValue = startLocations
        shimmerAnimation.toValue = endLocations
        shimmerAnimation.duration = animationDuration
        shimmerAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)

        let animationGroup = CAAnimationGroup()
        animationGroup.duration = animationDuration + animationDelay
        animationGroup.repeatCount = .infinity
        animationGroup.animations = [shimmerAnimation]

        // removes animation with same key (if exists) then adds
        // the new animation
        gradientLayer.removeAnimation(forKey: animationKeyPath)
        gradientLayer.add(animationGroup, forKey: animationKeyPath)
    }
}

In the UIButton subclass I've added property observers to each of the properties that calls addShimmerAnimation() with any property change.

I also considered just supplying default values and requiring addShimmerAnimation() to be called manually once properties were configured. Another route was not having any public properties exposed and instead passing everything in through an initializer, but that would remove the possibility of these classes being used in a storyboard (which is an option I like to leave open) and having properties exposed through tagging  the properties with IBInspectable.

class ShimmerButton: UIButton, ShimmerEffect {

    override static var layerClass: AnyClass {
        return CAGradientLayer.self
    }

    var gradientLayer: CAGradientLayer {
        return layer as! CAGradientLayer
    }

    var animationDuration: TimeInterval = 3 {
        didSet { addShimmerAnimation() }
    }
    var animationDelay: TimeInterval = 1.5 {
        didSet { addShimmerAnimation() }
    }

    var gradientHighlightRatio: Double = 0.3 {
        didSet { addShimmerAnimation() }
    }

    var gradientTint: UIColor = .black {
        didSet { addShimmerAnimation() }
    }

    var gradientHighlight: UIColor = .white {
        didSet { addShimmerAnimation() }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        gradientLayer.mask = titleLabel?.layer
        addShimmerAnimation()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        gradientLayer.mask = titleLabel?.layer
        addShimmerAnimation()
    }
}

Example usage:

let shimmer = ShimmerButton()
shimmer.setTitle("Find new skills", for: .normal)
shimmer.titleLabel?.font = UIFont.systemFont(ofSize: 24, weight: UIFontWeightHeavy)
shimmer.gradientTint = darkBlue
shimmer.gradientHighlight = lightBlue
shimmer.sizeToFit()

What I like about this approach is that the complexity is moved out of the subclass making it super easy to duplicate over other views.

What frustrates me is that UIView, UILabel and UIButton only have minor differences. I wish there was a way for the computed properties to be extracted into a common place.

Example of ShimmerButton and ShimmerView (a UIView subclass) being used together:


Solution for kth row of Pascal's triangle for a job interview Question:

  Given an index \$k\$, return the \$k^{th}\$ row of the Pascal's triangle.

  For example, given \$k = 3\$, return \$[1,3,3,1]\$.  Bonus points for using \$O(k)\$ space.

Can it be further optimized using this way or another?

class Solution {
   public:
    long long C(int n, int r) {
       if(r > n / 2) r = n - r; // because C(n, r) == C(n, n - r)
       long long ans = 1;
       int i;

       for(i = 1; i <= r; i++) {
           ans *= n - r + i;
           ans /= i;
       }

       return ans;
   }

       vector<int> getRow(int rowIndex) {
           vector<int> v;
           long long sol;
           for(int i=0;i<=rowIndex;i++)
           {sol=C(rowIndex,i);
           v.push_back(sol);}

          return v;
       }
   };

For one thing, the inconsistency with whitespace use and curly brace placing may demonstrate a lack of attention to detail.  Before you attack the actual problem, make sure your code is written cleanly.

This:

for(int i=0;i<=rowIndex;i++)

should use some whitespace:

for (int i = 0; i <= rowIndex; i++)

You already do this in other places, and it should be done everywhere.

Also, this:

for(int i=0;i<=rowIndex;i++)
{sol=C(rowIndex,i);
v.push_back(sol);}

looks a bit sloppy and is harder to read.  Again, use more whitespace, but also separate the loop body from the curly braces.

for (int i = 0; i <= rowIndex; i++) {
    sol = C(rowIndex, i);
    v.push_back(sol);
}


Remove continuous duplicate I've made a little function to eliminate continuous duplicate from a std::vector. I have to use C++03.

For example, if a vector of ints is composed of: 1,1,2,3,,3,1,1,2 my function should return 1,2,3,1,2. I've tried to use templates (I've just began to use c++) and made it as fast as possible!

template<class T>
vector<T> remove_duplicate(vector<T>& vec) {
    int length = vec.size();
    vector<T> result(length);
    result[0] = vec[0];
    int last = 0;
    for(int i=0; i<length; i++)
        if(vec[i] != result[last]){
            last++;
            result[last] = vec[i];
        }
    result.resize(last+1);
    return result;
}

Here's a simple test case:

static
void test_remove_duplicate() {
    vector<int> v;
    v.push_back(1); //123131
    v.push_back(1);
    v.push_back(2);
    v.push_back(2);
    v.push_back(3);
    v.push_back(1);
    v.push_back(3);
    v.push_back(3);
    v.push_back(1);
    v.push_back(1);

    vector<int> v1;
    v1 = remove_duplicate(v);
    for(int i=0; i<v1.size(); i++) {
        cout << v1[i];
    } cout << endl;
}

What do you think about it?

Let's go through mechanical errors:

use size_t instead of int

int length = vec.size();

what if there is no zero element?

result[0] = vec[0];

the same as first:

int last = 0;

the same as 1, 3:

for(int i=0; i<length; i++)

Optimization errors:

Is there any reason why do you need to return a COPY of vector? If you need return copy, so why do you pass it by reference?
Extra resize of vector is extremely heavy and slow operation.

result.resize(last+1);

Prefer pre-increment to post-increment
use reserve and push_back, instead of resize and []. In you case result.size() <= v.size(). So, make following:

std::vector<T> result;
result.reserve(v.size);
result.push_back( vec[0] );

In the loop:

result.push_back( vec[i] );

So, including all comments above:

template<class T>
std::vector<T> remove_duplicate(const std::vector<T>& vec)
{
    std::vector<T> result;

    if(!vec.empty())
    {
        result.reserve(vec.size());
        result.push_back(vec.front());

        for(size_t i = 0; i< vec.size(); ++i)
            if(vec[i] != result.back())
                result.push_back( vec[i] );
    }

    return result;
}


"Tic Tac Toe" game in Python I'm relatively new to Python. Here is a Tic Tac Toe game I've created in Python:

def is_valid_move(x,y,board):
    return ((0 <= x <= 2) and (0 <= y <= 2)) and (board[x][y] == '_')

def check_win(board):
    if board[0][0] == board[0][1] == board[0][2] != '_':
        return True
    if board[1][0] == board[1][1] == board[1][2] != '_':
        return True
    if board[2][0] == board[2][1] == board[2][2] != '_':
        return True
    if board[0][0] == board[0][1] == board[0][2] != '_':
        return True
    if board[0][1] == board[1][1] == board[2][1] != '_':
        return True
    if board[0][2] == board[1][2] == board[2][2] != '_':
        return True
    if board[0][0] == board[1][1] == board[2][2] != '_':
        return True
    if board[2][0] == board[1][1] == board[0][2] != '_':
        return True
    return False

def get_input_from_user(message:str):
    coord = input(message)
    str_x, str_y = coord.split()
    return int(str_x), int(str_y)

def make_move(idx,board):
    if idx % 2 == 0:
        x, y = get_input_from_user("Player X, please enter a move:")
        while not is_valid_move(x, y,board):
            x,y = get_input_from_user("Invalid move, please try again:")
        board[x][y] = 'X'
    else:
        x, y = get_input_from_user("Player O, please enter a move:")
        while not is_valid_move(x, y,board):
            x, y = get_input_from_user("Invalid move, please try again:")
        board[x][y] = 'O'

def print_board(board):
    for i in range(3):
        print(board[i])

if __name__ == '__main__':
    idx = 0
    board = [['_','_','_'] for i in range(3)]
    condition = False
    while condition is not True or idx <= 8:
        make_move(idx,board)
        print_board(board)
        condition = check_win(board)
        if condition is True and idx % 2 == 0:
            print("Player X is the Winner!")
        elif condition is True:
            print("Player O is the Winner!")
        idx += 1
    if idx > 8 and condition is not True:
        print("Its a Draw!")

Here is a simple test run of this code:

Player X, please enter a move:0 2
['_', '_', 'X']
['_', '_', '_']
['_', '_', '_']
Player O, please enter a move:0 1
['_', 'O', 'X']
['_', '_', '_']
['_', '_', '_']
Player X, please enter a move:1 1
['_', 'O', 'X']
['_', 'X', '_']
['_', '_', '_']
Player O, please enter a move:0 0
['O', 'O', 'X']
['_', 'X', '_']
['_', '_', '_']
Player X, please enter a move:2 0
['O', 'O', 'X']
['_', 'X', '_']
['X', '_', '_']
Player X is the Winner!

Let me know your thoughts about my code.

I see a few areas where you can improve.

You don't need parenthesis around the expressions you and or return:

def is_valid_move(x, y, board):
    return 0 <= x <= 2 and 0 <= y <= 2 and board[x][y] == '_'

Sometimes you do need parenthesis, but only if the operator precedence is wrong otherwise. I.e A and B or C is different from A and (B or C).
Your check_win function is very hard to debug. How sure are you that you did not mess up any of the indices while copy&pasting, and how long would it take you to check that you didn't?

Instead divide the function into sub-responsibilities, which you can name and reason about individually:

def all_equal(it):
    it = iter(it)
    first = next(it)
    return all(x == first for x in it)

def check_rows(board):
    for row in board:
        if row[0] != "_" and all_equal(row):
            return True
    return False

def check_cols(board):
    for col in zip(*board):  # transpose the board
        if col[0] != "_" and all_equal(col):
            return True
    return False

def check_diagonals(board):
    if board[0][0] != "_" and all_equal(board[i][i] for i in range(len(board))):
        return True
    if board[0][2] != "_" and all_equal([board[0][2], board[1][1], board[2][0]]):
        return True
    return False

def check_win(board):
    return check_rows(board) or check_cols(board) or check_diagonals(board)

While this code is longer, it should also be more readable. Also, this way only the diagonal check is still complicated to check for correctness, but at least it is localized.
Your get_input_from_user function can be shortened a bit, at the cost of some readability (at least until you get used to functional programming):

def get_input_from_user(message: str):
    return tuple(map(int, input(message).split()))

Don't iterate over the indices, if what you really want to do is iterate over the elements:

def print_board(board):
    for row in board:
        print(row)

Your main loop and the make_move function. The make_move function has two almost identical branches, the only difference is the player mark. So why not pass that instead of the index? In your main loop you can also change that to just swap between the two players, which lets you use a for loop which is automatically restricted to n iterations:

def make_move(player, board):
    x, y = get_input_from_user(f"Player {player}, please enter a move:")
    while not is_valid_move(x, y, board):
        x,y = get_input_from_user("Invalid move, please try again:")
    board[x][y] = player

if __name__ == '__main__':
    players = "X", "O"
    board = [['_'] * 3 for _ in range(3)]
    for _ in range(9):
        make_move(players[0], board)
        print_board(board)
        if check_win(board):
            print(f"Player {players[0]} is the Winner!")
            break
        players = players[::-1]  # equivalent to players[0], players[1] = players[1], players[0]
    else:    # only runs if no `break` broke the loop
        print("Its a Draw!")

I also used some f-strings for formatting, multiplication of lists, and the else clause of loops to detect a draw.
Python has an official style-guide, PEP8. It recommends always puting a space after commas in parameter lists, etc.


Iteratively extending a list Is there a way to collapse multiple_get into as few lines as possible?

def single_get(target):
    return [some list of objects] # might be an empty list

def multiple_get(targets):
    result = []
    for target in targets:
        result.extend(single_get(target))
    return result

Look into the itertools library in general, for list-and-sequence-manipulating commands. You're looking for a way to "flatten" a list of lists; itertools calls this itertools.chain.

def multiple_get(targets):
    return list(itertools.chain.from_iterable(single_get(target) for target in targets))

However, Python can do it natively as a nested list comprehension:

def multiple_get(targets):
    return [r for target in targets for r in single_get(target)]


Extracting average time series I have this JSON code that I got from a get request with Azure API. Everything works how I want it but it doesn't look good. There must be an easier way to parse the data.
import json
#GET REQUEST code here, it works now the code below is grabbing the result and loading it.
formatted_response = {'cost': 0, 'timespan': '2020-07-07T03:00:00Z/2020-07-07T03:15:00Z', 'interval': 'TM', 'value': [{'id': '/subscriptions/hjhkjhjljkjknlkjjlkj/Groups/jhkjhjkhjs/providers/Micro/virtualMachines/jhjkhkjhjkhkhljkl/providers/MicInsights/metrics/Percentage CPU', 'type': 'Microsoft.Insights/metrics', 'name': {'value': 'Percentage CPU', 'localizedValue': 'Percentage CPU'}, 'displayDescription': 'The percentage of allocated compute units that are currently in use by the Virtual Machine(s)', 'unit': 'Percent', 'timeseries': [{'metadatavalues': [], 'data': [{'timeStamp': '2020-07-07T03:00:00Z', 'average': 2.4659375}, {'timeStamp': '2020-07-07T03:01:00Z', 'average': 2.974375}, {'timeStamp': '2020-07-07T03:02:00Z', 'average': 2.90265625}, {'timeStamp': '2020-07-07T03:03:00Z', 'average': 1.72484375}, {'timeStamp': '2020-07-07T03:04:00Z', 'average': 1.1275}, {'timeStamp': '2020-07-07T03:05:00Z', 'average': 0.05640625}, {'timeStamp': '2020-07-07T03:06:00Z', 'average': 0.05515625}, {'timeStamp': '2020-07-07T03:07:00Z', 'average': 0.055}, {'timeStamp': '2020-07-07T03:08:00Z', 'average': 0.28765625}, {'timeStamp': '2020-07-07T03:09:00Z', 'average': 0.0546875}, {'timeStamp': '2020-07-07T03:10:00Z', 'average': 0.054375}, {'timeStamp': '2020-07-07T03:11:00Z', 'average': 0.05734375}, {'timeStamp': '2020-07-07T03:12:00Z', 'average': 0.0553125}, {'timeStamp': '2020-07-07T03:13:00Z', 'average': 0.05609375}, {'timeStamp': '2020-07-07T03:14:00Z', 'average': 0.0528125}]}], 'errorCode': 'Success'}], 'namespace': 'Microsoft/virtualMachines', 'resourceregion': 'eastus8'}

p = formatted_response['value']

for i in p:
    for j in i:
        if j == 'timeseries':
            q = i[j]
for l in q:
    for u in l:
        if u =="data":
            g=l['data']

for r in g:
    for s in r:
        if s == "average":
            print(r[s])

$ python testapi.py
2.4659375
2.974375
2.90265625
1.72484375
1.1275
0.05640625
0.05515625
0.055
0.28765625
0.0546875
0.054375
0.05734375
0.0553125
0.05609375
0.0528125

Json should be put in a separate file.
myfile.json
{   "cost":0,
   "timespan":"2020-07-07T03:00:00Z/2020-07-07T03:15:00Z",
   "interval":"TM",
   "value":[      {         "id":"/subscriptions/hjhkjhjljkjknlkjjlkj/Groups/jhkjhjkhjs/providers/Micro/virtualMachines/jhjkhkjhjkhkhljkl/providers/MicInsights/metrics/Percentage CPU",
         "type":"Microsoft.Insights/metrics",
         "name":{
            "value":"Percentage CPU",
            "localizedValue":"Percentage CPU"

},
         "displayDescription":"The percentage of allocated compute units that are currently in use by the Virtual Machine(s)",
         "unit":"Percent",
         "timeseries":[            {               "metadatavalues":[

],
               "data":[                  {
                     "timeStamp":"2020-07-07T03:00:00Z",
                     "average":2.4659375

},
                  {
                     "timeStamp":"2020-07-07T03:01:00Z",
                     "average":2.974375

},
                  {
                     "timeStamp":"2020-07-07T03:02:00Z",
                     "average":2.90265625

},
                  {
                     "timeStamp":"2020-07-07T03:03:00Z",
                     "average":1.72484375

},
                  {
                     "timeStamp":"2020-07-07T03:04:00Z",
                     "average":1.1275

},
                  {
                     "timeStamp":"2020-07-07T03:05:00Z",
                     "average":0.05640625

},
                  {
                     "timeStamp":"2020-07-07T03:06:00Z",
                     "average":0.05515625

},
                  {
                     "timeStamp":"2020-07-07T03:07:00Z",
                     "average":0.055

},
                  {
                     "timeStamp":"2020-07-07T03:08:00Z",
                     "average":0.28765625

},
                  {
                     "timeStamp":"2020-07-07T03:09:00Z",
                     "average":0.0546875

},
                  {
                     "timeStamp":"2020-07-07T03:10:00Z",
                     "average":0.054375

},
                  {
                     "timeStamp":"2020-07-07T03:11:00Z",
                     "average":0.05734375

},
                  {
                     "timeStamp":"2020-07-07T03:12:00Z",
                     "average":0.0553125

},
                  {
                     "timeStamp":"2020-07-07T03:13:00Z",
                     "average":0.05609375

},
                  {
                     "timeStamp":"2020-07-07T03:14:00Z",
                     "average":0.0528125

}

]

}

],
         "errorCode":"Success"

}

],
   "namespace":"Microsoft/virtualMachines",
   "resourceregion":"eastus8"
}

myfile.py
with open("myfile.json") as file_obj:
    formatted_response = json.load(file_obj)

Use descriptive identifiers for variables.
formatted_response_value = formatted_response['value']

Unnecessary double for loop
formatted_response_value = formatted_response['value']
timeseries = formatted_response_value[0]["timeseries"]   #please name something descriptive at all places.
data = q[0]["data"]
average = list(map(lambda x:x["average"], g))[-1] #or [entry["average"] for entry in g][-1]


Sieve of Eratosthenes in Erlang I just started learning Erlang. Here is my crack at the Seive, based on (https://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf):

-module(seive).
-export([seive/1]).

seive(N) ->
    L = lists:seq(1,N),
    {Megass, Ss, Micros} = erlang:timestamp(),
    S = doseive(L, 2),
    {Megase, Se, Microe} = erlang:timestamp(),
    {Megase-Megass, Se-Ss, Microe-Micros, S}.

doseive(L, Index) ->
    Isq = Index*Index-1,
    if Isq > length(L) -> [X || X <- L, X /= -1]; %done crossing out
    true ->
        case  lists:nth(Index, L) == -1 of
        true -> doseive(L, Index + 1); %nothing to cross this pass
        false ->
            {L1, L2} = lists:split(Isq, L),
             L3 = lists:map(fun(X) -> if X == -1 orelse (X rem Index == 0 andalso X /= Index) -> -1; true  -> X  end end , L2),
             doseive(lists:append(L1, L3), Index + 1)
    end end.

This takes 52 seconds to generate the first two million primes:

6> seive:seive(2000000).
{0,19,53218,
 [1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,
  73,79,83,89|...]}

I was expecting it to be faster based on other solutions on the web.

Sticking to serial (I have not even attempted a parallel solution yet, so I'd like to try that on my own first), what are the problems with my code? I looked for "in place" versions of map so that I don't continuously copy lists into new lists, which I think is what is killing me, but the essence of functional is this immutable-ness.

If I was in an imperative language, I would iterate over a hashmap, but there is no "map-update" function for hashmaps. I guess I could try accessing values in a loop, but this solution better lends itself to imperative languages. Would be nice to have something like

mapupdate(F, V)
%updates all values for keys to V where F(key) is true

I also tried a solution with filter:

doseivev2(L, Index) ->
if Index > length(L) -> L;
true ->
    case Index > length(L) of
        true -> L;
        false ->
            %if you do filter, you dont know what index p^2 is anymore...
            doseivev2(lists:filter(fun(X) -> X =< Index orelse X rem Index /= 0 end, L), Index + 1)
end end.

but it is WAAAAY slower. Does not even finish for 1M.

You point it, this program copies and traverse the lists too many times. You should think to reduce the size of the list at each prime iteration, you can initialize the first list without all the multiples of 2,3,5 (it is quite easy), you should pass length(L) as a parameter (it needs to traverse the list at each iteration).

Since the sieve algorithm is based on the modification of a set of data, the list is not the best data structure to work with. I think you should have much better result with ets.

[edit] I have tested your version on my laptop using timer:tc/3 and found 24s (your measure is 19.5s, not 52s). a version using ets and the different optimizations I suggest takes 1.2s for the same job.

With 10000000 the times are 252s and 7s, which suggests that with your algorithm the execution time is increasing more than with ets (ration 10 and 6 for a data set 5 time bigger).

Last point, you are returning 1 as a prime which is not correct.


Implementation of GroupBy in .NET I've implemented the GroupBy extension method for IEnumerable<T> type as an excersise to deep a little more into LINQ.

What do you think about the source code?

Code:

static IEnumerable<IGrouping<TKey,TElement>> GroupBy<TKey,TElement>(this IEnumerable<TElement> source, Func<TElement,TKey> keySelector)
{
    //Grouping elements in the dictionary according to the criteria
    var dict = new Dictionary<TKey, List<TElement>>();

    //Filling the dictionary. It will contain: [Key -> List<Values>]
    foreach (var x in source)
    {
        var key = keySelector(x);
        if (dict.Keys.Contains(key))
        {
            dict[key].Add(x);
        }
        else
        {
            dict.Add(key, new List<TElement> { x });
        }
    }

    //For each group...
    foreach (var x in dict)
    {
        yield return new Grouping<TKey, TElement>(x.Key, x.Value);
    }
}

class Grouping<TKey, TElement> : IGrouping<TKey, TElement>
{
    private TKey _key;
    private IEnumerable<TElement> _elements;

    public Grouping(TKey key, IEnumerable<TElement> elements)
    {
        _key = key;
        _elements = elements;
    }

    public IEnumerator<TElement> GetEnumerator()
    {
        return _elements.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public TKey Key
    {
        get { return _key; }
    }
}

If you want to duplicate GroupBy semantics exactly, there are several things missing:

Eager error checking on parameters instead of deferred
The correct order of the groups (GroupBy guarantees that the groups are ordered by the relative order of the group's first element in the source)
Allowing keys that are null

You may be interested in Jon Skeet's recent blog postings.


Fantasy game inventory — Ch. 5 Automate the Boring Stuff Here is a practice exercise — Fantasy Game Inventory \$-\$

  You are creating a fantasy video game. The data structure to model the
  player’s inventory will be a dictionary where the keys are string
  values describing the item in the inventory and the value is an
  integer value detailing how many of that item the player has. For
  example, the dictionary value {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} means the player has 1 rope, 6 torches,
  42 gold coins, and so on.

  Write a function named display_inventory() that would take any
  possible “inventory” and display it like the following -

  Inventory:
12 arrows
42 gold coins
1 rope
6 torches
1 dagger
Total number of items: 62

  Hint - You can use a for loop to loop through all the keys in a
  dictionary.

I have written the following code. Any feedback is highly appreciated.

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

def display_inventory(inventory):
    total_items = 0
    print ("Inventory:")
    for item in inventory:
        print(str(inventory[item]) + ' ' + item)
        total_items += inventory[item]
    print("Total number of items: " + str(total_items))

if __name__ == '__main__':
    display_inventory(stuff)

I am suggesting to use fstrings and the dictionary items() method.

The

print(f'{value} {key}')

instead of

print(str(inventory[item]) + ' ' + item)

is more neatly:

def display_inventory(inventory):
    total_items = 0
    print ("Inventory:")

    for key, value in inventory.items():
        print(f'{value} {key}')
        total_items += value

    print(f'Total number of items: {total_items}')

Also, you can just calculate the total number in the needed place by the sum() function and the dictionary values() method. Then, you are not needing the total_items variable.

def display_inventory(inventory):
    print ("Inventory:")

    for key, value in inventory.items():
        print(f'{value} {key}')

    print(f'Total number of items: {sum(inventory.values())}')