Roman Numeral Conversion in Java I have designed this by using the stack data structure (similar to balanced parentheses problem) checking if the previous element is decreasing the number or not.

package test;

import main.algorithms.RomanConversion;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class RomanConversionTest {

    RomanConversion romanConversion;

    @Before
    public void setUp(){
        romanConversion = new RomanConversion();
    }

    @Test
    public void testRomanConversion(){
        Assert.assertEquals(154, romanConversion.convert("CLIV"));
        Assert.assertEquals(101, romanConversion.convert("CI"));
        Assert.assertEquals(43, romanConversion.convert("XLIII"));
    }

}

package main.algorithms;

import java.util.HashMap;
import java.util.Stack;

public class RomanConversion {

    public HashMap createMap(){
        HashMap<String, Integer> romanMap = new HashMap<>();
        romanMap.put("I" , 1);
        romanMap.put("IV",4);
        romanMap.put("V" ,5);
        romanMap.put("IX",9);
        romanMap.put("X" ,10);
        romanMap.put("XL",40);
        romanMap.put("L" ,50);
        romanMap.put("XC",90);
        romanMap.put("C" ,100);
        romanMap.put("CD",400);
        romanMap.put("D" ,500);
        romanMap.put("CM",900);
        romanMap.put("M" ,1000);

        return romanMap;
    }

    public int convert(String letter) {

        int result=0;
        HashMap<String, Integer> map = new HashMap<>();
        map = createMap();
        String str;
        char[] array = letter.toCharArray();
        Stack<Character> stack = new Stack<>();

        for(char c: array){
            if(stack.isEmpty()){
                result += map.get(String.valueOf(c));
                stack.push(c);
            }else{
                char lastElement= stack.peek();
                if(map.containsKey(lastElement+""+c)) {
                    result -= map.get(String.valueOf(lastElement));
                    result += map.get(String.valueOf(lastElement) + String.valueOf(c));
                    stack.push(c);
                }else{
                    result += map.get(String.valueOf(c));
                    stack.push(c);
                }
            }

        }
        return result;
    }
}

I think your code is - in general - good. Your algorithm is working correctly and I really like the idea of using a Hashmap to save the values of the roman numbers.

One thing I miss is the handling of edge cases. Especially you should think about the following edge cases:

letter == null
Empty String
Strings that aren't valid roman numbers (for example "IXI" or "MMMM" aren't valid)

The first two problems are pretty easy to solve:

if(letter == null || letter.equals("")) {
        return -1;
}

The third part is a bit more difficult to solve:

if(!letter.matches("M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$")) {
        return -1;
}

As you can see, you can use a regular expression to validate if the string letter contains a valid roman number (as explained for example here).

One thought about your testing-class: You are using JUnit, which is good, but I think you are testing much too little (remember the edge cases!).

I wrote a test myself with the following values:

String[] input = {null, "", "I", "V", "XXXIII", "DCCXLVII", "CMXXIX", "MCCXXXII", "MMMCMXCIX", "MMMMXI", "KMXI", "VX", "VL", "VC", "VD", "VM","LC", "LD", "LM", "DM", "IL", "IC", "ID", "IM", "XD", "XM", "CXLV", "MIXI", "IXI", "MXIII", "MMMM", "IIII"};

int[] expectedOutput = {-1, -1, 1, 5, 33, 747, 929, 1232, 3999, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 145, -1, -1, 1013, -1, -1};


Avoid iteration on complete list to find (fuzzy) matching string I have about 10k categories, represented by their name.
I need to find a match for a category input among this list of 10k categories.

This is done through an API, and by batches: the endpoint will receive about 500 categories to match.

The process is:

-> Receive request with all categories to match

-> For each word, run fuzzy matching algorithm with the 10k categories.

-> Return match

I'm using Fuzzy Wuzzy for the algorithm, and Django for the API.
Basically, this would look like this:

response = {}

for category in categories_received:
  for master_category in master_categories:
    if fuzz.ratio(category, master_category) > 95:
       response[category] = master_category

This is terribly inefficient, but I couldn't find another way to do it.
I control both sides: the way data is sent to the API, and of course the way it is compared to the existing categories.

Any idea/input on how to make this code more efficient would be much appreciated

Fuzzy-wuzzy is poorly optimized for that kind of use.

What you can do is use fuzzy-wuzzy functions to construct your own ratio function.

The biggest boost you will get if you will use any caching for master_category tokenization. If you are on python3 you can use functions.lru_cache and if memory allows you I would suggest making it the size of len(master_categories)+1.

This is a small change and it will increase memory usage a lot, but as a result speed of calculation will also be boosted a lot.

also since you need just 1 master_category per each category, just break your loop as soon as you find one.

for category in categories_received:
  for master_category in master_categories:
    if fuzz.ratio(category, master_category) > 95:
       response[category] = master_category
       break


Puzzle game - converting binary numbers to decimal I've been learning Python for a few weeks and I created a simple game where you convert binary numbers to decimal. It shows you n binary numbers and you are supposed to enter the numbers in decimal system in sequence as a password. After failing three times you lose. I'd like to implement it into a bigger game later.

Here's the code:

import random

# Conver decimal to binary.
def toBin(i):
    bin = "{0:b}".format(i)
    return bin

# Generate random password and it's binary version.
def generatePassword(n):
    password = []
    passwordBin = []
    for i in range(n):
        a = random.randint(0, 9)
        password.append(a)
        passwordBin.append(toBin(a))
    return password, passwordBin

# Prints the binary password and a frame.
def printPassword(password):
    print(12 * '#')
    for i in range(len(password[1]) + 4):
        if i <= 1:
            print(2 * '#' + 8 * ' ' + 2 * '#')
        elif i <= 5:
            print(2 * '#' + password[1][i - 2].rjust(4, '0').center(8) + 2 * '#')
        else:
            print(2 * '#' + 8 * ' ' + 2 * '#')
    print(12 * '#')

# The game loop.
def puzzle(n):
    password = generatePassword(n)
    win = False
    endLoop = False
    attempts = 3
    while endLoop is False:
        # Check remaining attempts.
        if attempts > 0:
            printPassword(password)
            print('Attempts remaining: ' + str(attempts) + '\n')
            # Looping through password numbers.
            for i in range(n):
                print('Number ' + str(i + 1), '\t\t', end='')
                # Input and check for ValueError.
                try:
                    inp = int(input())
                except ValueError:
                    print('You can only enter numbers.')
                    break
                # Is input correct?
                if inp == password[0][i]:
                    print('CORRECT')
                else:
                    attempts -= 1
                    print('WRONG\n')
                    break
            # End loop and win.
            else:
                endLoop = True
                win = True
        # End loop.
        else:
            endLoop = True
    # Check win condition.
    if win is True:
        print('ACCESS GRANTED')
    else:
        print('ACCESS DENIED')

# Run the game.
puzzle(4)

Are there any ways to improve my code, expecially the puzzle(n) function? The conditions and loops took me some time to get working and still kinda confuse me. I hope there aren't any bugs.

Style

Please follow PEP8 conventions on naming: function names should be lowercase_with_underscores

On documentation: information on functions should be put below their definition in the form of a docstring, in order to allow programmatic access via help(function).

generatePassword

List comprehension

The explicit loop in generate_password is unnecessary, it is too long making the reader forget about the logic behind such function.

def generate_password_and_binary(n):
    """ A "password" is a list of length `n` containing random digits. """
    password = [random.randint(0, 9) for _ in range(n)]
    return password, [to_bin(digit) for digit in password]

This version with list comprehension is shorter and more to the point.

I also incorporated the comment into the function name (self-documenting code is better than code + comments) and added a more detailed docstring.

printPassword

I think your printPassword has a serious bug:

>>> generatePassword(8)
([2, 1, 7, 6, 4, 5, 7, 3], ['10', '1', '111', '110', '100', '101', '111', '11'])
>>> printPassword(_)
############
##        ##
##        ##
##  0010  ##
##  0001  ##
##  0111  ##
##  0110  ##
##        ##
##        ##
##        ##
##        ##
##        ##
##        ##
############

Only the first four digits where printed and the rest ignored.
This bug is probably a result of over-complication caused by indexes and comparison, while a plain for iteration over the collection is sufficient, here is a simpler (and correct!) way to write this function:

def print_password(binary_version): # No need to pass all password if only binary part is shown
    wall = "#" * 12
    spaced = "{0}{1}{0}".format("##", " " * 8)
    print(wall, spaced, sep="\n")
    for binary_digit in binary_version:
        print("{0}{1}{2}{1}{0}".format("##", "  ", binary_digit.rjust(4, "0")))
    print(spaced, wall, sep="\n")

Now all of the password is printed:

>>> print_password(['10', '1', '111', '110', '100', '101', '111', '11'])
############
##        ##
##  0010  ##
##  0001  ##
##  0111  ##
##  0110  ##
##  0100  ##
##  0101  ##
##  0111  ##
##  0011  ##
##        ##
############


A clock and a fortune: a full screen clock with random quotes in Tcl/Tk I've written a small Tcl/Tk script for a friend that displays the current time, as well as a quote. He uses it in some project with a Raspberry Pi, and since I didn't want to cobble up something up in Qt, PyQt, or some kind of website, I tried to write something in Tcl/Tk.

Demo

Here is how it looks in the end:

Requirements

This script assumes that you have fortune available an in your $PATH.

Script

#!/usr/bin/env tclsh

proc every {ms body} {
    eval $body
    after $ms [info level 0]
}

label .time -bg black -fg white -font {Arial 150} -textvar ::time -pady 30
every 1000 { set ::time [clock format [clock sec] -format "%T"] }

label .fortune -bg black -fg white -font {Arial 15}  -textvar ::fortune
every 30000 { set ::fortune [exec fortune -s] }

pack .time -fill both
pack .fortune -fill both -expand 1

. configure -bg black

wm attributes . -fullscreen 1

bind . <q> exit

What to review

This is my first script in Tcl/Tk. Feel free to commend on anything, especially if there's some kind of common style I'm missing.

Nice code. I only see a couple of items

add package require Tk to be explicit you need tk
use uplevel #0 $body instead of eval


Solution to Codejam 2019's Pylons I'm trying to solve Pylons from the 2019's round 1A.

  Problem

  Our Battlestarcraft Algorithmica ship is being chased through space by
  persistent robots called Pylons! We have just teleported to a new
  galaxy to try to shake them off of our tail, and we want to stay here
  for as long as possible so we can buy time to plan our next move...
  but we do not want to get caught!

  This galaxy is a flat grid of R rows and C columns; the rows are
  numbered from 1 to R from top to bottom, and the columns are numbered
  from 1 to C from left to right. We can choose which cell to start in,
  and we must continue to jump between cells until we have visited each
  cell in the galaxy exactly once. That is, we can never revisit a cell,
  including our starting cell.

  We do not want to make it too easy for the Pylons to guess where we
  will go next. Each time we jump from our current cell, we must choose
  a destination cell that does not share a row, column, or diagonal with
  that current cell. Let (i, j) denote the cell in the i-th row and j-th
  column; then a jump from a current cell (r, c) to a destination cell
  (r', c') is invalid if and only if any of these is true:

r = r'
c = c'
r - c = r' - c'
r + c = r' + c'

  Can you help us find an order in which to visit each of the R × C
  cells, such that the move between any pair of consecutive cells in the
  sequence is valid? Or is it impossible for us to escape from the
  Pylons? Input

  The first line of the input gives the number of test cases, T. T test
  cases follow. Each consists of one line containing two integers R and
  C: the numbers of rows and columns in this galaxy. Output

  For each test case, output one line containing Case #x: y, where y is
  a string of uppercase letters: either POSSIBLE or IMPOSSIBLE,
  according to whether it is possible to fulfill the conditions in the
  problem statement. Then, if it is possible, output R × C more lines.
  The i-th of these lines represents the i-th cell you will visit
  (counting starting from 1), and should contain two integers ri and ci:
  the row and column of that cell. Note that the first of these lines
  represents your chosen starting cell. Limits

  Time limit: 20 seconds per test set. Memory limit: 1GB. Test set 1
  (Visible)

  T = 16. 2 ≤ R ≤ 5. 2 ≤ C ≤ 5. Test set 2 (Hidden)

  1 ≤ T ≤ 100. 2 ≤ R ≤ 20. 2 ≤ C ≤ 20.

The analysis suggests that a brute force approach should work. However, my Python 3 solution doesn't pass the 2nd test case. Can I make it faster without complicating the algorithm?

from itertools import product, repeat

def main():
    T = int(input())  # the number of test cases

    for case in range(1, T+1):
        R, C = map(int, input().split())  # the numbers of rows and columns

        stack = []

        for r, c in product(range(R), range(C)):
            grid = [[False]*C for _ in repeat(None, R)]
            grid[r][c] = True
            stack.append((((r, c),), grid))

        while stack:
            moves, grid = stack.pop()
            if len(moves) == R*C:
                print('Case #{}: POSSIBLE'.format(case))
                for r, c in moves:
                    print(r+1, c+1)
                break

            for r, c in product(range(R), range(C)):
                if (not grid[r][c] and r != moves[-1][0] and c != moves[-1][1]
                        and moves[-1][0] - moves[-1][1] != r - c
                        and moves[-1][0] + moves[-1][1] != r + c):
                    g = [r.copy() for r in grid]
                    g[r][c] = True
                    stack.append((moves+((r, c),), g))
        else:
            print('Case #{}: IMPOSSIBLE'.format(case))

main()

A simple randomized brute-force works for this problem. From the analysis:

  We can try these solutions anyway, or we can rely on our occasional
  friend, randomness! We can pick a random starting cell, repeatedly
  choose valid moves uniformly at random from the space of all allowed
  moves from our current cell, and, if we run out of available moves,
  give up and start over. For any case except for the impossible ones
  mentioned above, this approach finds a solution very quickly.

Python code:

from itertools import product, repeat
from random import choice

def main():
    T = int(input())  # the number of test cases

    for case in range(1, T+1):
        R, C = map(int, input().split())  # the numbers of rows and columns

        if R < 2 or C < 2 or R + C < 7:
            print('Case #{}: IMPOSSIBLE'.format(case))
        else:
            print('Case #{}: POSSIBLE'.format(case))

            while True:
                grid = [[False]*C for _ in repeat(None, R)]
                moves = []
                last = None
                for _ in repeat(None, R*C):
                    candidates = ([(r, c) for r, c in product(range(R), range(C)) if not grid[r][c]
                                   and r != last[0] and c != last[1] and last[0] - last[1] != r - c
                                   and last[0] + last[1] != r + c]
                                  if last is not None else list(product(range(R), range(C))))
                    if not candidates:
                        break
                    cell = choice(candidates)
                    moves.append(cell)
                    grid[cell[0]][cell[1]] = True
                    last = cell
                else:
                    for r, c in moves:
                        print(r+1, c+1)
                    break

main()


Read and display JSON results from Google Books API I’m working with the Google Books API and I’m not so sure about the way I’m going to get the search data and return it to the user. I will describe the path here and I would like to know if you would do something different.
First, I receive a search request from the user via a form inside index.html:
<form action='/lookup' method="post">
  <input type="text" name="search" placeholder="Search by title, author, publisher, release, ISBN ...">
  <button type="submit">Buscar</button>
  {% block search %}{% endblock %}
</form>

So in an app.py I get this request like this:
@app.route("/lookup", methods=["GET", "POST"])
@login_required
def search():
    """Get book search."""
    if request.method == "POST":
        result_check = is_provided("search")
        if result_check is not None:
            return result_check
        search = request.form.get("search").upper()
        search = lookup(search)
        if search is None:
            return "Invalid Search"
        return render_template("search.html", search={
            'totalItems': search['totalItems'],
            'title': search['title'],
            'authors': search['authors']
        })
    else:
        return render_template("/")

Next, I access a lookup function in helpers.py:
def lookup(search):
    """Look up search for books."""
    # Contact API
    try:
        url = f'https://www.googleapis.com/books/v1/volumes?q={search}&key=MYAPIKEY'
        response = requests.get(url)
        response.raise_for_status()
    except requests.RequestException:
        return None

    # Parse response
    try:
        search = response.json()
        return {
            "totalItems": int(search["totalItems"]),
            "items": search["items"]
        }
    except (KeyError, TypeError, ValueError):
        return None

To return the results to the user I have a search.html that is still under construction:
{% extends "index.html" %}

{% block search %}

Total Items: {{search['totalItems']}}

Título: {{search['items'][0]['volumeInfo']['title']}}

Autor(a): {{search['items'][0]['volumeInfo']['authors']}}

Título: {{search['items'][2]['volumeInfo']['title']}}

Autor(a): {{search['items'][2]['volumeInfo']['authors']}}

{% endblock %}

Finally, my question: is this path I am following to access the API and return the data to the user the most recommended? Would you do anything other than that?

Split search() up into two functions, each accepting only one method, and dispose of your if.
There's a little bit of religion around this, but HTML5 accepts both "naive HTML" and XHTML-compatible tag closure, so this:
<input type="text" name="search">

is also accepted as
<input type="text" name="search" />

and the latter is (1) more explicit on where the tag ends and (2) is more broadly compatible.
This:
request.form.get("search").upper()

does not benefit from get, because you don't provide a default. Either allow the crash on a missing parameter, i.e. request.form['search'], or provide a default to get, likely the empty string.
This:
search = lookup(search)

is ill-advised, because it swaps types on the same symbol. The input is a string and the output is a dictionary.
This:
url = f'https://www.googleapis.com/books/v1/volumes?q={search}&key=MYAPIKEY'

first should not hard-code your API key directly into the string, and second should not format any query parameters into the string. Instead, pass params={...} into get().
This:
except requests.RequestException:
    return None

is fairly catastrophic for the application's ability to tell maintainers and users what went wrong. You're going to want to log the exception, and translate it into an appropriate failure message returned to your own caller.
This:
requests.get(url)

should use the response in a with.
Your search.html template is deeply bizarre. Where I would expect to see a for, you've only shown the first and third items?
Ensure that you're telling the browser that your content is in Spanish.
This:
action='/lookup'

needs to use double quotes.


A switch case statement that returns a timespan I have a switch case statement containing enum values as cases. These enum values are time units. Now I want to generate a timespan by using an enum value and a long value so like this:

2 (long) Minutes (Enum value)
1 (long) Year (Enum value)

... and so on.
This is the switch-case statement:
private const double yearValue = 365.2425;

public TimeSpan ResetTimeSpan
            {
                get
                {
                    switch (ResetTimeUnitEnumValue)
                    {
                        case TimeUnit.Seconds:
                            return new TimeSpan(0,0,0, (int)ResetTime);
                        case TimeUnit.Minutes:
                            return new TimeSpan(0, 0, (int)ResetTime, 0);
                        case TimeUnit.Hours:
                            return new TimeSpan(0, (int)ResetTime, 0);
                        case TimeUnit.Days:
                            return new TimeSpan((int)ResetTime, 0, 0, 0);
                        case TimeUnit.Months:
                            return new TimeSpan((int)(ResetTime * (yearValue / 12)), 0, 0, 0);
                        case TimeUnit.Years:
                            return new TimeSpan((int)(ResetTime * yearValue), 0, 0, 0);
                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }
            }

But I don't like it and it feels very double. Could anyone review this and refactor it, since I'm not able to see it.

private const double yearMultiplier = 365.2425;

private Dictionary<TimeUnit, Func<double, TimeSpan>> timespanConverters = new Dictionary<TimeUnit, Func<double, TimeSpan>>
{
    { TimeUnit.Seconds, TimeSpan.FromSeconds },
    { TimeUnit.Minutes, TimeSpan.FromMinutes },
    { TimeUnit.Hours,   TimeSpan.FromHours },
    { TimeUnit.Days,    TimeSpan.FromDays },
    { TimeUnit.Months, t => TimeSpan.FromDays((int)t * (yearMultiplier / 12))) },
    { TimeUnit.Years,  t => TimeSpan.FromDays((int)t * yearMultiplier)) }
}

// ....

public TimeSpan ResetTimeSpan
{
    get
    {
        return timespanConverters[ResetTimeUnitEnumValue](ResetTime);
    }
}

Bit of a shame that System.TimeSpan doesn't have FromMonths or FromYears methods otherwise this would look really neat :)


Perform various actions on a list I am solving the following HackerRank problem:

Consider a list (list = []). You can perform the following commands:

insert i e: Insert integer e at position i.
print: Print the list.
remove e: Delete the first occurrence of integer e.
append e: Insert integer e at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.

Initialize your list and read in the value of followed by lines of
commands where each command will be of the types listed above. Iterate
through each command in order and perform the corresponding operation
on your list.

My solution was:
if __name__ == '__main__':
    N = int(input())

    my_list = []

    commands = dict(
            insert=lambda i,v: my_list.insert(i,v),
            print=lambda: print(my_list),
            remove=lambda e: my_list.remove(e),
            append=lambda v: my_list.append(v),
            sort=lambda: my_list.sort(),
            pop=lambda: my_list.pop(),
            reverse=lambda: my_list.reverse()
        )

    for _ in range(N):
        command, *args = input().split()
        commands[command](*list(map(int, args)))

I did find another solution (I didn't write it) that seems cleaner than mine:
n = input()
l = []
for _ in range(n):
    s = raw_input().split()
    cmd = s[0]
    args = s[1:]
    if cmd !="print":
        cmd += "("+ ",".join(args) +")"
        eval("l."+cmd)
    else:
        print l

Suggestions:

Most of your lambdas are unnecessary wrappers around perfectly fine functions, so I'd just use the latter instead.
The list in (*list(map(...))) is unnecessary, just unpack the iterable that map gets you.
There's nothing else in your code, so importing it doesn't give you anything, so you'd just run the script, so if __name__ == '__main__': is rather pointless.
I'd read the number of commands only when I need it, not early.
I find my_list unnecessarily verbose, a commonly used name is lst.
Indent the dict arguments by the standard four spaces instead of eight.
So, rewritten:

lst = []

commands = dict(
    insert=lst.insert,
    print=lambda: print(lst),
    remove=lst.remove,
    append=lst.append,
    sort=lst.sort,
    pop=lst.pop,
    reverse=lst.reverse
)

for _ in range(int(input())):
    command, *args = input().split()
    commands[command](*map(int, args))

As shown in some other solutions in the discussion, we can use getattr instead of building our own dict serving pretty much the same purpose. I didn't see anyone using its default parameter, though, which can neatly cover the print command:
lst = []
for _ in range(int(input())):
    command, *args = input().split()
    getattr(lst, command, lambda: print(lst))(*map(int, args))


Python address index +1 with list comprehension Task from CodingBat:

  Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.

My original answer to the problem:

def sum13(nums):
  sum = 0
  for idx,val in enumerate(nums):
    if val == 13 or (idx != 0 and nums[idx-1] == 13):
      pass
    else:
      sum = sum + val

  return sum

Doing this with list comprehension,  I came up with

return sum([x if x!=13 and nums[idx-1 if idx >0 else 0] !=13 else 0 for idx,x in enumerate(nums)])

Is there a way to make this cleaner?

EDIT: As pointed out by an anonymous user, my first version did not skip numbers that follow an even number of 13's.

Use an iterator. While you for loop over an iterator you can skip items with next.

def lucky_nums(nums):
    nums = iter(nums)
    for i in nums:
        if i == 13:
            while next(nums) == 13:
                pass
        else:
            yield i

print sum(lucky_nums([12,13,14,15]))


Letter case permutation The question can be found here https://leetcode.com/problems/letter-case-permutation

  Given a string S, we can transform every letter individually to be
  lowercase or uppercase to create another string.  Return a list of all
  possible strings we could create.

My question pertains mostly to the pattern that I am following. I find that with alot of these leetcode question that I want to use recursion for I find myself making two versions of a function. One which acts as the "interface" is this case
letterCasePermutation and one which acts as the worker (letterCasePermutationAux) where the only difference is the arguments (I would usually have something like a counter and a reference to a vector to hold my answers).

I choose this question as an example but really any recursive question could act as a stand in here.

class Solution(object):

    ans = []

    def letterCasePermutationAux(self, S, i=0):

        if i >= len(S):
            self.ans.append(S)
            return

        if S[i].isalpha():
            temp = list(S)
            temp[i] = S[i].upper() if S[i].islower() else S[i].lower()
            self.letterCasePermutationAux("".join(temp), i+1)

        self.letterCasePermutationAux(S,i+1)

    def letterCasePermutation(self, S):
        self.ans=[]
        self.letterCasePermutationAux(S)
        return self.ans

My question is, is there a nicer way I can go about accomplishing this task? One which can perform recursion only using one function?

It's fairly common to use an auxiliary parameter as an index or accumulator in recursive functions.  If you don't like having the extra function or method "cluttering" the namespace, you can nest it inside the driver like this:

class Solution:

    def letterCasePermutation(self, S):

        def aux(S, i):

            if i >= len(S) and len(S) > 0:
                self.ans.append(S)
                return

            if S[i].isalpha():
                temp = list(S)
                temp[i] = S[i].upper() if S[i].islower() else S[i].lower()
                self.letterCasePermutationAux("".join(temp), i+1)

            self.letterCasePermutationAux(S,i+1)

        self.ans=[]
        self.letterCasePermutationAux(S)

        return self.ans

A common way to recursively process a string, list, or other sequence is to define the base case as an empty sequence which returns a list with with the base case answer.  If the sequence isn't empty, take off the first element of the sequence and recursively call the function with the rest of the list.  Then process the list returned by the recursive call to add back in the first element.

class Solution:
    def letterCasePermutation(self, s):

        # base case the answer is a list with an empty string
        if s == '':
            return ['']

        else:
            ans = []

            if s[0].isalpha():
                # if s[0] is a letter, prepend it to all the answers in the list
                # returned by the recursive call.  First as a lowercase letter
                # and then as an uppercase letter
                for tail in self.letterCasePermutation(s[1:]):
                    ans.append(s[0].lower() + tail)
                    ans.append(s[0].upper() + tail)

            else:
                # if it's not a letter, just prepend it to all the answers in
                # the list returned by the recursive call.
                for tail in self.letterCasePermutation(s[1:]):
                    ans.append(s[0] + tail)

            return ans

Here's an elegant solution using generators to create the permutations lazily:

class Solution:

    def letterCasePermutation(self, s):
        def aux(s, acc):
            if s == '':
                yield acc

            else:
                yield from aux(s[1:], acc + s[0])

                if s[0].isalpha():
                    yield from aux(s[1:], acc + s[0].swapcase())

        yield from  aux(s, '')


Checking winning conditions in Tic-Tac-Toe This code checks winning conditions in Tic-Tac-Toe by checking if there is any row, column or diagonal with the same symbols.

The board is a 2-dimensional array of chars. The character ' ' means that a field is empty.

How can I refactor/simplify this code?

 public static bool SomeoneWins(char[][] board)
        {
            // Check columns
            for (var x = 0; x < board.Length; x++)
            {
                var firstField = board[x][0];
                if (firstField == ' ') continue;
                bool allFieldsTheSame = true;

                for (var y = 1; y < board[x].Length; y++)
                {
                    if (board[x][y] != firstField)
                    {
                        allFieldsTheSame = false;
                        break;
                    }
                }

                if (allFieldsTheSame) return true;
            }

            // Check rows
            for (var y = 0; y < board.Length; y++)
            {
                var firstField = board[0][y];
                if (firstField == ' ') continue;
                var allFieldsTheSame = true;

                for (var x = 1; y < board.Length; x++)
                {
                    if (board[x][y] != firstField)
                    {
                        allFieldsTheSame = false;
                        break;
                    }
                }

                if (allFieldsTheSame) return true;
            }

            // first diagonal
            if (board[0][0] != ' ')
            {
                var allFieldsTheSame = true;

                for (var d = 0; d < board.Length; d++)
                {
                    if (board[d][d] != board[0][0])
                    {
                        allFieldsTheSame = false;
                        break;
                    }
                }
                if (allFieldsTheSame) return true;
            }

            // second diagonal
            if ( board[board.Length - 1][0] != ' ')
            {
                var allFieldsTheSame = true;
                for (var d = 0; d < board.Length; d++)
                {
                    if (board[d][board.Length-d-1] !=  board[board.Length - 1][0])
                    {
                        allFieldsTheSame = false;
                        break;
                    }
                }
                if (allFieldsTheSame) return true;
            }

            return false;
        }

What does all winning conditions in Tic Tac Toe have in common? They are all straight lines!

The idea of having one method that can be called multiple times is a good one, to do that we need to input the starting position, and how much we should change x and y with every time.

We also need a way to stop the loop, we can either stop when we notice that we will go out of bounds, or we can stop after a specific number of checks. In this implementation, I chose to hard-code 3 as the limit for how many tiles to check.

public static bool AllFieldsTheSame(int startX, int startY, char[][] board, int dx, int dy)
{
    char firstField = board[startY][startX]
    if (firstField == ' ')
    {
        return false;
    }

    for (var i = 0; i < 3; i++)
    {
        int y = startY + dy * i;
        int x = startX + dx * i;
        if (board[y][x] != firstField)
        {
            return false;
        }
    }

    return true;
}

Then this method can be called repeatedly as follows:

public static bool SomeoneWins(char[][] board)
{
    // Check columns
    for (var x = 0; x < board.Length; x++)
    {
        if (AllFieldsTheSame(x, 0, board, 0, 1))
            return true;
    }

    // Check rows
    for (var y = 0; y < board.Length; y++)
        if (AllFieldsTheSame(0, y, board, 1, 0))
            return true;

    // Check diagonals
    if (AllFieldsTheSame(0, 0, board, 1, 1))
        return true;

    if (AllFieldsTheSame(2, 0, board, -1, 1))
        return true;
}

However, I suspect you are also interested in who wins, in which case you could have both AllFieldsTheSame and SomeoneWins return a char instead of a bool.

And by the way, I'd prefer to use an enum for the possible values of each tile. A char can have the value of Q, but I don't believe you want to place a Q tile in your game. Using an enum reduces the eliminates any possible risk of invalid characters.


Python vocabulary trainer for terminal To train my Python skills I have made a vocabulary trainer which runs on a terminal:

import random
import os
import sys

FILE_PATH = "./words.txt"

class Entry:
    def __init__(self, french, english):
        self.french = french
        self.english = english

entries = []

if os.path.isfile(FILE_PATH):
    words = open(FILE_PATH, "r")

    for line in words:
        words = line.split(",")
        entries.append(Entry(words[0].strip(), words[1].strip()))

def insert():
    while True:
        french = raw_input("French word: ")

        if french == "#":
            return

        english = raw_input("English word: ")

        if english == "#":
            return

        entries.append(Entry(french, english))
        backup_wordpairs()

def query():
    total = 0
    right = 0
    wrong = 0

    while True:
        i = random.randint(0, len(entries) - 1)
        french = raw_input("French translation of " + entries[i].english + ": ")

        # TODO: Add a statistics which is displayed before leaving (x of y correct. Equal z percent).
        if french == "#":
            percentage = (right  * 100) / total
            print("You answered " + str(right) + " question out of " + str(total) + " correct.")
            print("Percentage: " + str(percentage) + " %")
            return

        total = total + 1

        if french.strip() == entries[i].french.strip():
            print("Correct.")
            right = right + 1
        else:
            print("Wrong!")
            wrong = wrong + 1

def printall():
    if len(entries) == 0:
        print("No words stored.")
        return

    for i in range(len(entries)):
        print(entries[i].french + " : " + entries[i].english)

def backup_wordpairs():
    woerter = open(FILE_PATH, 'w')

    for wort_paar in entries:
        woerter.write(wort_paar.french + "," + wort_paar.english + "\n")

    woerter.close()

def reset_list():
    global entries

    entries = []

    if os.path.isfile(FILE_PATH):
        os.remove(FILE_PATH)

while True:
    command = raw_input("Please enter a command: ")

    if command == "add":
        insert()
    elif command == "test":
        query()
    elif command == "list":
        printall()
    elif command == "end":
        break
    elif command == "reset":
        reset_list()
    else:
        print("No known command.")

print(" ------- Vocabulary becomes terminated. ----------  ")
sys.exit()

My GitHub repository (including a README-file with user-instructions and a screenshot).

The application runs fine but I would appreciate feedback from more experienced Python-developers. What would you have done differently and why?

Currently your code is all over the place. You have global variables (which should be named in ALL_CAPS according to Python's official style-guide, PEP8), functions which modify these globals, then some actual code in between the functions and at the end some code that actually executes the code, also in the global namespace (preventing you from importing any of the functions defined here in another script).

In addition I would also change:

Use random.choice(entries) instead of random.randint(0, len(entries)).
Make Entry a collections.namedtuple (which allows using tuple unpacking).
Since you say you are using Python 3.x, use the new f-strings introduced in Python 3.6.
Where this is not possible, use str.format instead of building the strings using addition and manual calls to str.
Make main take the file path (defaulting to the global constant) so it is more extendable.
Making sure to close all opened files again using with ... as.
Use if __name__ = "__main__" guard to allow importing.
Call strip on the manually entered words, removing the need to do that every time you compare them later.
Remove the wrong variable, it is unused (and can be easily calculated as total - right).
raw_input is not called that anymore in Python 3. It is now called input (and the input from Python 2 is gone).

import random
import os
import sys
from collections import namedtuple

FILE_PATH = "./words.txt"
Entry = namedtuple("Entry", ["french", "english"])

def insert(entries):
    while True:
        french = input("French word: ").strip()
        if french == "#":
            return
        english = input("English word: ").strip()
        if english == "#":
            return
        entries.append(Entry(french, english))

def query(entries):
    total, right = 0, 0
    while True:
        word_pair = random.choice(entries)
        french = input(f"French translation of {word_pair.english}:")

        if french == "#":
            percentage = (right * 100) / total
            print(f"You answered {right} question out of {total} correct.")
            print(f"Percentage: {percentage} %")
            return
        total += 1
        if french.strip() == word_pair.french:
            print("Correct.")
            right += 1
        else:
            print("Wrong!")

def printall(entries):
    if len(entries) == 0:
        print("No words stored.")
        return
    for word_pair in entries:
        print("{} : {}".format(*word_pair))

def backup_wordpairs(entries, file_path):
    with open(file_path, 'w') as words:
        for word_pair in entries:
            words.write("{},{}\n".format(*word_pair))

def main(file_path=FILE_PATH):
    if os.path.isfile(file_path):
        with open(file_path) as words:
            entries = [Entry(*map(str.strip, line.split(",")))
                       for line in words]
    else:
        print("File does not exist")
        sys.exit()

    while True:
        command = input("Please enter a command: ")

        if command == "add":
            insert(entries)
            backup_wordpairs(entries, file_path)
        elif command == "test":
            query(entries)
        elif command == "list":
            printall(entries)
        elif command == "end":
            break
        elif command == "reset":
            entries.clear()
            if os.path.isfile(file_path):
                os.remove(file_path)
        else:
            print("No known command.")

    print(" ------- Vocabulary becomes terminated. ----------  ")
    sys.exit()

if __name_ == "__main__":
    main()

As you can see now, almost all functions take entries as the first argument and modify it somehow. This should tell you that you could easily make this a class.


Calling a function every 40 second inside a while loop This code invokes a function for every 40 seconds inside a loop. I am doubtful about this condition:

if ((time_left <= 0 || time_left > interval))

Is only checking (time_left <= 0) fine? I referred to some websites and they have also added a check for time_left > interval. Is this check required?

int print_timed_op()
{
    time_t        time_now;
    time_t        time_left;
    time_t        time_next_interval;
    int           interval = 40, hit_count =10; //40 second interval, 10 times
    time_next_interval = time(0) + interval;

   //tight loop
   while (1) {
         sleep(1);
         time_now = time(0);
         time_left = time_next_interval - time_now;
         /* here time_left > interval check required ? */
         if ((time_left <= 0 || time_left > interval)) {
              call_my_fuc();
              time_next_interval = time(0) + interval;
              time_left = interval;
              hit_count--;
         }

         if(hit_count< 0)
            break;
  }
  return 0;
}

Note: I don't want to use a Linux timer system call or any other method to invoke the function periodically.

This seems like a fairly straightforward implementation with reasonable naming. It seems very maintainable, so good work there. Here are a few suggestions:

Useless variables

The time_now variable doesn't seem to serve much of a purpose. You calculate it, then immediately use it. However, you could just call time(0) directly like this:

time_left = time_next_interval - time(0);

It's fewer characters, and since you're calling time(0) directly in several other places, any reader of the code will already have to know what it means.

Don't Repeat Yourself

Usually the "Don't Repeat Yourself" suggestion has to do with code being copied several times. You haven't done that, but you are running your loop far more frequently than you have to. Instead of sleeping for 1 second and then checking if you've reached your desired time, why not sleep for the desired amount of time? Something like this:

time_t remainder = interval;
while(1)
{
    sleep(remainder);
    start_time = time(0);
    call_my_func();
    hit_count--;

    if(hit_count< 0)
        break;
    remainder = (start_time + interval) - time(0);
}

Use Your Loop Counter as a Loop Counter

You have a loop control variable, but you aren't directly using it as such. Instead you've written an infinite loop and then a conditional which checks the loop counter and breaks out of the infinite loop. This isn't the 1970s! We have proper control flow structures now. Just do:

while (hit_count >= 0)
{
    //... etc.
    hit_count--;
}


Quick linked-list implementation I need a simple singly-linked list to help implement some memory management functionality. I just finished writing it up and would really like a code review since I haven't written this particular data structure in a long time.

struct pid_node {

  int PID;
  struct pid_node* next;

};

 struct pid_node* pid_node_create(int PID) {
   struct pid_node* new;
   new = kmalloc(sizeof(struct pid_node));
   if (new == NULL) return NULL;
   new->PID = PID;
   new->next = NULL;
   return new;
 }

 void add_pid_node(struct pid_node* head, struct pid_node* new) {
   struct pid_node* temp;
   temp = head;
   while(temp->next != NULL) temp = temp->next;
   temp->next = new;
 }

 void remove_pid_node(struct pid_node* head, struct pid_node* dead) {
   struct pid_node* temp, other_part_of_list, delete_node;
   temp = head;
   while(temp->next != NULL) {
     if (temp->next == dead) {
       delete_node = temp->next;
       other_part_of_list = temp->next->next;
       temp->next = other_part_of_list;
       kfree(delete_node); //don't leak memory
       return;
     }
     temp = temp->next;
   }
   kprintf("Got to end of PID list, didn't remove 'dead'!\n");
 }

 //returns true or false (1 or 0) if a particular PID is within my list
 int query_pid(int PID, struct pid_node* head) {
   struct pid_node* temp;
   temp = head;
   while(temp->next != NULL) {
     if (temp->PID == PID) return 1;
     temp = temp->next;
   }
   return 0; //didn't find it
  }

It doesn't have to be super fancy or anything. It just has to properly carry out the four functions.

A couple of conceptual errors:

Pass by value

You can remove the temporary copy of head in your functions. In C, all arguments are passed by value. This means you can operate directly on the head parameter exposed to your function without worrying about the argument in the calling code. Although both point to the same location, each is a different pointer variable with its own address.

Pointer declarations

struct pid_node* temp, other_part_of_list, delete_node;

Remember that the * is not part of the type, but part of the declarator. A clearer way to write declarations involving pointers is to move the * directly in front of the identifier. This follows the C convention that "declaration mimics use." So, the line changes to

struct pid_node *temp, other_part_of_list, delete_node;

Now the error (and fix) is obvious. If there is no * before a variable, its a variable of the type instead of a pointer to the type.

struct pid_node *temp, *other_part_of_list, *delete_node;

Edit: remove head special case

In order to modify the head argument itself, which is a pointer-to-struct, you need to pass a pointer-to-pointer-to-struct or return the new head. For example (pointer-to-pointer-to-struct):

void remove_pid_node(struct pid_node **head, struct pid_node *dead) {
...
    if (*head == dead) {
         temp = *head;
         *head = temp->next;
         kfree(temp);
         return;
    }

Then you would call the code like this:

remove_pid_node(&head, head);

Note: don't forget to check for NULL arguments.


View for displaying nounal and verbal pages I've got this code in my View that just list two type of links.

Here's an example output:

Nounal Pages

cleaners/house-cleaners

Verbal Pages

cleaning/house-cleaning

Here's the view code. How could this be refactored to remove duplicate and push logic and loops out of the view?

  %h3 Nounal Pages
  %ul.row-fluid
  - categories.each do |category|
    - subcategories.each do |subcategory|
      %ul
        %li= link_to "#{category.pluralised_nounal_slug}/#{subcategory.pluralised_nounal_slug}", main_app.new_pluralised_nounal_subcategory_path(category: category.pluralised_nounal_slug, subcategory: subcategory.pluralised_nounal_slug), target: '_blank'

  %h3 Verbal Pages
  %ul
  - categories.each do |category|
    - subcategories.each do |subcategory|
      - if category.verbal_slug.present? && subcategory.verbal_slug.present?
        %ul
          %li= link_to "#{category.verbal_slug}/#{subcategory.verbal_slug}", main_app.new_verbal_subcategory_path(category: category.verbal_slug, subcategory: subcategory.verbal_slug, aspect: 'verbal'), target: '_blank'

You might consider having the controller (or some other thing that is not the view) set up all of the data, such that the view can merely do this:

- @nounals.each do |text, uri|
  %ul
    %li= link_to text, uri, target: '_blank'

and

- @verbals.each do |text, uri|
  %ul
    %li= link_to text, uri, target: '_blank'

Once the two loops are the same other than the variable, you can use a partial template to render each of them.


Generating string expression from data for filter I have a set of parameters, and I need to get the expression:

So I got this parameters:

filters = {
  "type": 'human',
  "age": [{'min': 4, 'max': 8}, {'min': 15, 'max': 30}],
  "size": [{'min': 60}],
}

And my goal is to obtain this string from it:

type == 'human' and ((age >= 4 and age <= 8) or (age >= 15 and age <= 30)) and size >= 60

But when I am writing my script to do so, I keep having small details that bother me like the position of the 'or' or 'and' or the parenthesis.
And i think it really hit the readability here.
So I thought maybe there was a better way, but searching Google only shows me the inverse of what I want, that is transforming expression to expression tree.

I am trying to generate a string expression from a set of data (for a filter).

So if someone have a better idea, (or algo, or ...)

Here is my script:

#!/usr/bin/python3

# goal : type == 'human' and ((age >= 4 and age <= 8) or (age >= 15 and age <= 30)) and size >= 60
filters = {
  "type": 'human',
  "age": [{'min': 4, 'max': 8}, {'min': 15, 'max': 30}],
  "size": [{'min': 60}],
}

s = ''
type_first = True
for key, value in filters.items():
  if type_first:
    type_first = False
    s += "("
  else:
    s += " and ("
  value_first = True
  if(isinstance(value, str)):
    s += "%s == %s" % (key, value)
  elif(isinstance(value, list)):
    if value_first:
      value_first = False
    else:
      s += " and"
    dict_first = True
    for dict_ in value:
      if dict_first:
        dict_first = False
        s += "("
      else:
        s += " or ("
      if dict_.get('min', 0):
        s += "%s >= %s" % (key, dict_['min'])
        if dict_.get('max', 0):
          s += " and "
      if dict_.get('max', 0):
        s += "%s <= %s" % (key, dict_['max'])
      s += ")"
  s += ")"

print(s)

Please note that I am not actually reviewing your code, but guiding you towards hopefully better design, so that you can fix the issues yourself
In that same vein, the code snippets I am including do not contain a full solution, but only the hints towards it.

These kinds of transformations are very easy if you start to decompose them.

For example, you have two different rules for dealing with string data type and list data type, so let's create two different entities to deal with them.

(Here I chose functions as top-level entities, you can create classes too)

def convert_string(key, value):
    return f"{key} == '{value}'"   # I am assuming you want value in quotes

Similarly, define one for lists. (Hint: You should define one entity for dict and list function should only call and compose dict function)

How do you choose which entity to call? Simple, call another entity.

def choose_function(key, value):
    # Your logic here
    # returns func

And finally, a composing function, which is also your main function.

def convert(params):
    str_list = []
    for key, value in params.items():
        str_list.append(choose_func(key, value)(key, value))
    return ' and '.join(str_list)}

Why it would be better than your solution?

It is much easier to test. Your problem statement is pretty much easy, but these kinds of problems could become very big with lots of complex rules in the long run, where unit testability gives you the confidence to make changes
You divide the problem statement into individual sub-pieces and another sub-problem deal with how to merge those solutions. That would eliminate lots of your _first variables. It also makes it easier in the long run.
Code readability


Make extensions for kotlin arrays I wanted to make a library thing which provides specific extensions for collections/collection-like containers in kotlin:

fun <T> Collection<T>.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }

fun String.extendEntries(length: Int) = this.toList().extendEntries(length)
fun <T> Array<T>.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun CharArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun BooleanArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun DoubleArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun IntArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun LongArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun FloatArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun ByteArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }
fun ShortArray.extendEntries(length: Int) = this.flatMap { x -> List(length) { x } }

Is the above a good way to do it if I want to cover arrays?

Exampe usage:

val a = intArrayOf(1, 2, 3)
println(a.extendEntries(5))

Outputs:

[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]

Sadly, yes. If you want users of your library to write intArrayOf(1, 2, 3).extendEntries(5) then this is how it is done in Kotlin.

In fact, the Kotlin source code contains methods similar to it, with a specific function for each type of array: (kotlin.collections._Arrays.kt)

/**
 * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original array.
 */
public inline fun <R> ShortArray.flatMap(transform: (Short) -> Iterable<R>): List<R> {
    return flatMapTo(ArrayList<R>(), transform)
}

/**
 * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original array.
 */
public inline fun <R> IntArray.flatMap(transform: (Int) -> Iterable<R>): List<R> {
    return flatMapTo(ArrayList<R>(), transform)
}

/**
 * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original array.
 */
public inline fun <R> LongArray.flatMap(transform: (Long) -> Iterable<R>): List<R> {
    return flatMapTo(ArrayList<R>(), transform)
}

However, Kotlin uses a generator to generate such files, see the README at https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib

In your case, you might consider just implementing Iterable<T>.extendEntries as all of these specific types of arrays can be transformed to an Iterable<T> using the Kotlin stdlib .asIterable function.


Web page based on a sample from a book I've created a web page based on a sample from a book. It works fine, but seems to have become too complicated.

'use strict';
function toggle (triggers, elements, per_trigger, events) {
    function toggle(index, per, elem, func) {
        for (var i = 0; i < per; i++)
            func(elem[index+i]);
    }

    if ((elements.length % triggers.length != 0 && elements.length != triggers.length * per_trigger)
        || (elements.length == 0 || triggers.length == 0)
        || (events[0].func == undefined || events[0].ev == undefined)) {
        console.error('toggle: number of elements must be divisible by' +
        'number of triggers, because one trigger can toggle more than one element\n' +
        'for example: if you want a trigger to toggle two elements, then the per_trigger' +
        ' argument will be 2 and the number of elements must be equal to the number of triggers * 2');
        return false;
    }
    for (var i = 0; i < triggers.length; i++) {
        for (var f = 0; f < events.length; ++f) {
            (function(_i, _f) {
                $(triggers[_i]).on(events[_f].ev, function() {
                    toggle(_i*per_trigger, per_trigger, elements, events[_f].func);
                })
            })(i, f);
        }
    }
    return true;
}

var hidden, trigger, PER_TRIGGER = 1, onclick;
function defineTriggers(hide) {
    hidden = document.getElementsByTagName('div');
    trigger = document.getElementsByTagName('h2');

    if (hide) {
        // hiding elements ..
        for (var r=0; r<hidden.length; ++r) {
            if (hidden[r].displayinfo == undefined)
                hidden[r].displayinfo = hidden[r].style.display;
            hidden[r].style.display = 'none';
            hidden[r].shown = false;
        }
        toggle(trigger, hidden, PER_TRIGGER, [{'ev': 'click', 'func': onclick}]); // defined externally ..
    }
}

function addDiv(date, info) {
    var d = document.createElement('div'),
        s = document.createElement('h2'),
        p = document.createElement('p');
    p.textContent = info;
    s.textContent = date;
    document.body.appendChild(s);
    document.body.appendChild(d);
    d.appendChild(p);
    d.style.display = 'none';
    d.shown = false;
    d.displayinfo = 'block';
    hidden[hidden.length] = d;
    trigger[trigger.length] = s;
    toggle([s], [d], PER_TRIGGER, [{'ev': 'click', 'func' : onclick}]);
}

    alert('running')
    onclick = function(e) {
        e.style.display = e.shown ? 'none' : e.displayinfo;
        e.shown = !e.shown;
    };
    defineTriggers(true);

    // adding btn
    var b = document.createElement('button'),
        f = document.getElementsByTagName('footer')[0];

    f.appendChild(b);
    b.textContent = 'Add a Date'

    b.onclick = function() {
        var day, info, day_regex = /[A-Z][a-z]{1,7} [1-9][0-9]?, 2[0-9]{3}/;
        do {
            day = prompt('Day');
            if (!day_regex.test(day)) alert('Day not correct .. !');
        } while(!day_regex.test(day))
        info = prompt('Info');
        addDiv(day, info);
    }

Is it possible to improve the clarity of this code, without affecting its functionality?

I wrote this up using a lot more jQuery as an example. Confirmed working JSFiddle here.

You can see there's a considerably less lines of code, there's less boilerplate on each line (things like document.getElementsByTagName), and at least in my opinion it's a lot more expressive.

Additionally, it becomes much easier to do other things that jQuery does well. For example, to animate these toggles. Just change $hidden.toggle() to $hidden.slideToggle()

Full code:

'use strict';

function enterData(){
    var day, info, day_regex = /[A-Z][a-z]{1,7} [1-9][0-9]?, 2[0-9]{3}/;
    do {
        day = prompt('Day');
        if (!day_regex.test(day)) alert('Day not correct .. !');
    } while(!day_regex.test(day))
    info = prompt('Info');
    addDiv(day, info);
}

function bindEventsToEl( $trigger, $hidden, events ){

    //This lets you pass in a different hash of events to bind, if you wanted to
    var eventsHash = events || {
        click: function(){
            $hidden.toggle();
        }
    };

    for ( var event_type in eventsHash ){
        $trigger.on( event_type, eventsHash[event_type] );
    }
}

function defineTriggers(hide) {
    var $hidden = $("div"),
        $triggers = $("h2");

    if (hide) {
        $hidden.hide();

        $triggers.each(function(i,el){
            bindEventsToEl( $(el), $( $hidden[i] ) );
        });
    }
}

function addDiv(date, info) {
    //Creating your empty elements and inserting content
    var $header = $("<h2>").text(date),
        $p = $("<p>").text(info),
        $div = $("<div>").append($p).hide();

    //You can chain appends to the root selector
    $("body").append($header).append($div);

    bindEventsToEl( $header, $div );
}

alert('running')

// bind all of our initial header/div combos
defineTriggers(true);

// create the button to add new sections
var $button = $("<button>").text("Add a Date").appendTo("footer").on( "click", enterData );

I removed your PER_TRIGGER, per_trigger variables and the if check around binding event listeners based on their count. It didn't seem to apply in your current JSfiddle anyway, and the reasoning behind it seemed a little shaky.

However, I think this problem might be solved just by using jQuery. Check out the bindEventsToEl function. Because $trigger and $hidden are jQuery selectors, you can have any number of elements in them.

For example, we can call this:

bindEventsToEl( $("h2, div"), $("div") );

This causes ALL divs to toggle whenever ANY h2 or div is clicked. Not exactly useful, but I think it shows you how powerful and expressive jQuery can be when selecting and binding events.

You can pass in a different event hash to the bindEventsToEl as well:

bindEventsToEl( $("h2"), $("div") , {
    click: function(){ console.log("bonus click"); },
    mouseover: function(){ console.log("mouseover"); }
});

If you're still not convinced that jQuery is the route you want to go, some recommendations for your prior code:

Focus on simplifying your toggle function so that it's much more clear what it's doing.
Try not to have as much nesting inside functions, break them out into their component parts.
Definitely don't have another function named 'toggle' inside a function named 'toggle'. It makes it look like it's calling itself recursively.
Give the rest of your variables slightly clearer names as well.


O Levels 2210 Computer Science Pre-Release: Senior Citizens Trip Organizer Can anyone go over the code and suggest any edits and/or efficient solutions?

Attached below are the provided tasks and their solutions. The task is copyright of Cambridge International Examinations.

#©Nosher Zapoo 2017.
#Task 1 starts here.

number_of_citizens = int(input('Please Enter the number of citizens on the trip: '))

#Validation Check:

if number_of_citizens > 2 and number_of_citizens < 37:
    if number_of_citizens > 24 :
        carer = 3
    else:
        carer = 2
else:
    print('Sorry the range of people is 10 - 36. Please Try again.')
    exit()

#Calculating the cost using economies of scale.

total_people = number_of_citizens + carer
if total_people < 17:
    hire = 150
    cost_meal = 14*total_people
    cost_ticket = 21*total_people
elif total_people < 27:
    hire = 190
    cost_meal = 13.5*total_people
    cost_ticket = 20*total_people

elif total_people < 40:
    hire = 225
    cost_meal = 13*total_people
    cost_ticket = 19*total_people
else:
    exit()

#Working out the total cost
total_cost= hire + cost_meal + cost_ticket
avg_cost= total_cost / number_of_citizens
print('Number of Citizens = ',number_of_citizens)
print ('Total Cost = $', total_cost)
print ('Cost per Person = $', avg_cost)

#Task2 Starts!!!

#Creating Empty Lists to append as arrays.
names = []
amounts = []
total_amount  = 0

#Using an undefined loop
for x in range (0, total_people ):
    name = input('Name: ')
    amount = input ('Amount: ')
    names.append (name)
    amounts.append (amount)
    total_amount = total_amount + int(amount)

#Adding Spare people and their costs
if total_people < 17:
    extra_people = 16 - total_people
elif total_people < 27:
    extra_people = 26 - total_people
elif total_people < 40:
    extra_people = 39 - total_people

extra_cost = extra_people*avg_cost
total_cost = total_cost + extra_cost

if extra_people > 0:
    print ('There are', extra_people, 'seats available. Please enter the name & amount of people joining on extra seats')
    updated_people = total_people + extra_people
    for x in range (total_people, updated_people):
        name = input('Name: ')
        amount = input ('Amount: ')
        names.append (name)
        amounts.append (amount)
        total_amount = total_amount + int(amount)

for x in range (0, updated_people):
    print (names[x])

#Task 3 Starts here.

profit = total_amount - total_cost
if profit > 0:
    print ('Profit gained $', profit)
elif profit == 0:
    break_even_value = total_cost
    print ('The Outing has broken even as the Total Cost is equal to the Total Amount.')
else:
    print ('The Outing is in loss of $', profit)

There are a few things to improve:

Task 1

the initial validation check is not correct. You are checking for a minimum number of people to be more than 2, while the error message says the minimum is 10:

  Sorry the range of people is 10 - 36. Please Try again.

I would use an inclusive ranges for readability. Also, you can use the chained comparison:

if 10 <= number_of_citizens <= 36

you can use a short if/else form when defining carer:

carer = 3 if number_of_citizens > 24 else 2

to avoid over-nesting things, I would handle the "negative case" first:

if not(10 <= number_of_citizens <= 36):
    print('Sorry the range of people is 10 - 36. Please Try again.')
    exit()

carer = 3 if number_of_citizens > 24 else 2

don't hardcode the coefficient values for costs and hires, define them as constants, or better in a separate configuration file or module

Task 2

Some of the things from the "Task 1" can also be applied here as well.

when you have a throwaway (not used, but syntactically needed) variable, it is agreed to use _ (underscore) variable name
looks like you don't have to keep the amounts in a list and can simply calculate the total amount, while only collecting names into a list
the range() starts at 0 by default, you can avoid specifying 0:

for _ in range(total_people):
     # ...

The definition step then might look like this:

names = []
total_amount  = 0

for _ in range(total_people):
    names.append(input('Name: '))
    total_amount += int(input('Amount: '))

when you print out the names, you can loop over the names in a list directly instead of looping over indexes:

for name in names:
    print(name)

Task 3

the break_even_value variable is set but never used

There were also some PEP8 violations in terms of code style, like missing spaces around operators or extra spaces after the function calls. Install a linter like flake8 or pylint to catch this kind of common violations.


Longest common substring I wrote a program to find the longest common subsequence among several strings. I used a naive algorithm and implementation.

The motivation was solving the Rosalind problem at http://rosalind.info/problems/lcs/ . You can find sample input there as well. The Rosalind problem concerns strings as DNA, but I think my code can be treated as a general string operation.

The problem asks for any of the common substrings if there is more than one, but I find all of them.

How can this code be improved? What obvious problems are there?

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace Finding_a_Shared_Motif
{
    class Program
    {
        private static void Main()
        {
            var input = File.ReadAllLines("rosalind_lcs.txt").ToList();

            var t = new Stopwatch();
            t.Restart();
            var lcs = LongestCommonSubstring(input);
            t.Stop();

            File.WriteAllLines("output.txt", lcs);
            Console.WriteLine("Finished in {0} msec.", t.ElapsedMilliseconds);
            Console.ReadLine();
        }

        public static IEnumerable<string> LongestCommonSubstring(List<string> strings)
        {
            var lcs = LongestCommonSubstring(strings[0], strings[1]);

            for (var i = 2; i < strings.Count(); i++)
            {
                var new_lcs = new BestStrings();

                foreach (var s in lcs) new_lcs.Add(LongestCommonSubstring(s, strings[i]));

                lcs = new_lcs;
            }

            return lcs;
        }

        private static BestStrings LongestCommonSubstring(string s1, string s2)
        {
            var lcs = new BestStrings();

            for (var i = 1 - s2.Length; i < s1.Length; i++)
            {
                var substrings = BestSubstringWithAlignment(s1, s2, i);

                if (substrings.Length == 0) continue;

                lcs.Add(substrings);
            }

            return lcs;
        }

        private static BestStrings BestSubstringWithAlignment(string s1, string s2, int offset)
        {
            var substrings = new BestStrings();

            var substring = "";
            for (var i = Math.Max(0, offset); i < s1.Length && i < s2.Length + offset; i++)
            {
                var c1 = s1[i];

                var c2 = s2[i - offset];

                if (c1 == c2)
                {
                    substring = substring + c1;
                }
                else
                {
                    substrings.Add(substring);
                    substring = "";
                }
            }
            substrings.Add(substring);

            return substrings;
        }

        sealed class BestStrings : Collection<string>
        {
            public int Length
            {
                get { return base[0].Length; }
            }

            public BestStrings()
            {
                base.Add("");
            }

            public new void Add(string s)
            {
                if (s.Length == 0 || s.Length < Length || Contains(s)) return;

                if (s.Length > Length) Clear();
                base.Add(s);
            }

            public void Add(IEnumerable<string> collection)
            {
                foreach (var s in collection) Add(s);
            }
        }
    }
}

Firstly some style.

Short named variables don't help readability at all. c1, c2, s1, s2 are a bad idea. I know this is just a challenge and not production code but keeping a consistent style is a good habit.

Secondly I would start by using the string.Contains() method. It will find if a specified substring exists and should help clean up some of the code.

In this train of thought I decided to start with all the possible substrings in the first string and then search the list of all strings.

public static IEnumerable<string> LongestCommonSubstrings(List<string> strings)
{
    var firstString = strings.FirstOrDefault();

    var allSubstrings = new List<string>();
    for(int substringLength = firstString.Length -1; substringLength >0; substringLength--)
    {
        for(int offset = 0; (substringLength + offset) < firstString.Length; offset++)
        {
            string currentSubstring = firstString.Substring(offset,substringLength);
            if (!System.String.IsNullOrWhiteSpace(currentSubstring) && !allSubstrings.Contains(currentSubstring))
            {
                allSubstrings.Add(currentSubstring);
            }
        }
    }

    return allSubstrings.OrderBy(subStr => subStr).ThenByDescending(subStr => subStr.Length).Where(subStr => strings.All(currentString => currentString.Contains(subStr)));
}

This will also allow us to do a .FirstOrDefault() on the linq and get the largest ( due to the orderby() calls.

(To test I used a static list of strings instead of a file:)

public static void Run()
{
    var input = new List<string>{
        "GATTACA",
        "TAGACCA",
        "ATACA",
    };

    var t = new Stopwatch();
    t.Restart();
    var lcs = LongestCommonSubstrings(input);
    t.Stop();

    Console.WriteLine("All Common substrings: \r\n{0}", string.Join("\r\n", lcs));
    Console.WriteLine("Finished in {0} msec.", t.ElapsedMilliseconds);
    Console.ReadLine();
}

DISCLAIMER: Haven't fully tested the above code. May harm your brain/computer.


TypeScript, checking for keys and subkeys and its variants How to reduce code size?

  getAlreadySaved(goal: GoalModel): number {

        if (goal.status && goal.status.investedAmount && !goal.status.pendingIncoming && !goal.status.pendingOutgoing) {
            return goal.status.investedAmount;

        } else if (goal.status && goal.status.investedAmount && goal.status.pendingIncoming && !goal.status.pendingOutgoing) {
            return goal.status.investedAmount + goal.status.pendingIncoming;

        } else if (goal.status && goal.status.investedAmount && !goal.status.pendingIncoming && goal.status.pendingOutgoing) {
            return goal.status.investedAmount - goal.status.pendingOutgoing;

        } else if (goal.status && goal.status.investedAmount && goal.status.pendingIncoming && goal.status.pendingOutgoing) {
            return goal.status.investedAmount + goal.status.pendingIncoming - goal.status.pendingOutgoing;

        } else {
            return 0;
        }

    }

Find invalid cases first then return early. In this case, it looks like the initial goal.status check is primarily for presence check. You can remove that from the entire logic and put it up front, returning 0 early.

Now the whole point of TypeScript is to provide types to your data so you won't be doing unnecessary type checks in code. In the case of pendingIncoming, pendingOutgoing and investedAmount, they're numbers. The type for status should at least define them as number. Without a value, they should at least be initialized to 0. That should remove the unnecessary conditions.

With that, your code is essentially just:

getAlreadySaved(goal: GoalModel): number {
  const status:Status = goal.status;

  if(!status) return 0;

  // If we can assume they're numbers, we can safely say we can do math.
  return status.investedAmount + status.pendingIncoming - status.pendingOutgoing;
}


Bridge Crossing - Classic Puzzle Problem - The classic puzzle of finding the minimum amount of time required to cross a bridge given that only two people can cross the bridge at any one time.
Since they have only one flashlight (it's dark and they need the flashlight), the two people move at the speed of the slower one.

Constraints - Upto 6 people (although it should work for a higher number of people)

Input - Number of people (up to 6 tested) & Sorted vector of time required by each person to cross the bridge.

Output - Minimum time possible

int main()
{
  vector<int> v; int n; int time;
  int items;
  int k = 2;
  cin>>items;
  for (int i = 0; i < items; i++)
  {
    cin >> n;
    v.push_back(n);
   }

  if (v.size() == 1)
  {
    cout << v[0];
    return 0;
  }
  int last = v.size() - 1;
  time = v[0] + v[1] + v[last] + v[1];

  while (last-k >= 2)
  {
    time += v[0] + v[last - k];
    k++;
  }
  time = time + v[1];

  cout << time;
  return 0;
}

Note : Code will not work for 2 people, missed a special case.

The overwhelming first impression I get from your code is that without the text description above, I wouldn't have a clue what it is you're trying to do.  A lot of these types of problems have some kind of prompting which helps, however your code doesn't have that, its only output is time after it's finished.

The two main improvements I'd suggest are:

Put your code in a function that defines an interface.
Use variable names that have some kind of meaning.

Implementing these two basics would go a long way to making your code easier to follow.

For example, your vector v might be people?!?

You could have a method calculate_minimum_time_to_cross_bridge, which took in a list of people and returned the time.

Whilst your variable names might have meaning to you, they have no meaning a new reader without context.

One final point is that whilst you can do this:

vector<int> v; int n; int time;

It's generally considered bad form.  One declaration per line means the declarations are less likely to get lost.


Java Save/Load Optimization I have recently gotten into Java in a Computer Science class at my high school and I am trying to learn more than just the basics I have learned in school. Yesterday, I designed a very simple text editor I named Aqua that is written with Swing. For some reason, my computer drags a little bit when I run these methods. Is it because I have a crappy computer or did I write something wrong? Thanks!

private void save(String content, String name) throws IOException{
    System.out.println(dir.toString());
    if(firstRun<1){
        dirCreation();
        firstRun++;
    }
    try{
            String savedText = content;
            System.out.println(savedText);
            File newTextFile = new File(newDir.toString() + File + name + ".aqua");
            System.out.println(newDir.toString() + File.seperator + name + ".aqua");
            if (!newTextFile.exists()) {
                System.out.println("Created new File");
                newTextFile.createNewFile();
            }
        try (FileWriter fw = new FileWriter(newTextFile)) {
            fw.write(savedText);
        }

    }
    catch(IOException x){
                System.err.format("IOException: %s%n", x);
    }
}
private void load(String name) throws FileNotFoundException, IOException{
    if(firstRun<1){
        dirCreation();
        i++;
    }

    File loadingFile = new File(newDir + "\\" + name + ".aqua");
    Scanner scan = new Scanner(loadingFile);
    StringBuilder loadedText = new StringBuilder("");
    while (scan.hasNextLine()) {
            loadedText.append(scan.nextLine() + "\n");
            //Is this correct usage of StringBuilder?
    }
    jTextArea1.setText(out);
    }

There are formatting and whitespace issues in your code, fix them! You're also switching between declaring variables and initializing them in the next line and initializing them in the same line, be consistent!

if(i<1){

That hurts! What is i? Where does it come from? Why do you check against less then one? Keep your variable names always clear, f.e. numberOfLinesInFile is way better then i in my opinion.

new File(newDir.toString() + "\\" + name + ".aqua");

This assumes that it is run on a Windows machine (or anything else that uses a backslash as path separator...which I hope no one else does). That will lead lead to problems on *nix machines, but I know that / works on any platform, you could also go full length and use File.separator.

Or you use the constructor-overload that is provided for exactly these means:

new File(newDir.toString(), name + ".aqua"):

String out = "";

That's not a great name for that variable, text or content would be better suited.

out+=line + "\n";

This has one problem, concatenating strings with the + is slow like whatever-place-of-ternal-pain-you-believe-in-if-any. Use a StringBuilder, that will speed things up considerable.

jTextArea1.setText(out);

Again, not a good name.


while found_last_factor == False:

Style is subjective, but I know I'm not the only develop who considers comparisons to Boolean literals to be bad style. while not found_last_factor: is an alternative which I consider preferable.

There are various inefficiencies in this code:

    while found_last_factor == False:
        for f in range(2, int(n/2+1)):
            if n % f == 0 and is_prime(f):
                n /= f
                factors.append(f)
                if is_prime(n):
                    factors.append(n)
                    found_last_factor = True
                    break
    return sorted(factors)

If it were modified to handle repeated prime factors in an inner loop rather than in the outmost loop then

The test is_prime(f) would be unnecessary, because n % f == 0 would already imply the primality of f.
Primes would be discovered in order, removing the need to call sorted.
A lot of unnecessary iterations of f would be saved. You rebutted AJNeufeld's observation on this subject, so consider an alternative perspective: add a line print(f) at the top of the for f loop, and then call prime_factors(1024).

The call to is_prime(n) tests primality by trial division, and is called from a loop which is factoring n by trial division. That's duplication of both code and run time.

/= does floating point division. Use //= for integer division. Similarly int(n/2+1) could be n//2 + 1.


Checking if a user can withdraw money This is purely testing my skills; I am not actually coding for a bank.  This is part of a bank account class.

public void withDraw(double amount)
    {
        if(balance - amount >= odLimit)
        {
            balance -= amount;
        }
        else
        {
            Console.WriteLine("Error.  Withdrawing will take you below overdraft limit.  Enter a new amount: ");
            double amount2;
            while (!double.TryParse(Console.ReadLine(), out amount2) || (balance - amount2 < odLimit))
            {
                Console.WriteLine("Enter a valid number: ");
            }

            balance -= amount2;
        }
    }

odLimit is the overdraft limit.  The code checks if the balance - amount is greater than or equal to the odLimit (say -900), and if so, it simply takes that money from the account.  If that's not the case then it keeps asking the user to enter an amount they wish to withdraw, and when they enter a value that won't take the account below the overdraft limit and is a double.

Just checking that this is the most efficient way to do this.  I prefer minimum lines of code.

Also in the main program class.  Would you find it more efficient to create a menu function and call the withDraw function from the menu using a switch statement within the menu, or call a method in the program class from the switch statement that asks the user for their value, and then calls the withDraw function in the bank account class?

For proper encapsulation, you want the interface logic to be completely separate from your atomic behaviours like withdrawing funds.

Something to consider: Where are the funds going? In a traditional banking system all operations are done in pairs as an atom. You withdraw from one account and deposit to another account, or into the cash withdrawal ledger, et al.

Your Withdraw method should return a result containing enough information that the caller can determine how to act. This would include whether the operation was successful (and if not, why not). For a simple case, you could probably do this with an enum. The method should take a decimal in (always use decimal for money, since you're concerned with precision and double is an approximate). Your calling routine should handle the validation and conversion, and if necessary the prompt back to the user to enter a valid number.

public enum OpResult = { Complete, Failed_Insufficient_Funds, Failed_Account_Frozen, Failed_Invalid_Amount };

    ...

public OpResult Withdraw(decimal amount)
{
   if (amount <= 0)
   {
       return OpResult.Failed_Invalid_Amount;
   }
   else if (balance - amount < odLimit)
   {
       return OpResult.Failed_Insufficient_Funds;
   }
   ...
   else
   {
       balance -= amount;
       return OpResult.Complete;
   }
}


File encoder/decoder in Nim I wrote a simple program to encode a local text file with password and decode it back. There is one text file and it is either encoded with a password or is in plain text.

I had a version in Python for this, but nim compiles to an executable, so I gave it a try.

I'm not perfectly happy with command line argument handling, as well as with some repeated code in case statement, but maybe there are other things to improve too.

import os
import system
import strutils
import terminal

import xxtea

const FILENAME = "passwords.txt"
const USAGE = """Encrypt and decrypt a file using a password.

Usage:
    vault open [file]
    vault close [file]

Default file:
    passwords.txt

WARNING: this program may overwrite or delete file content without
a possibilty of recovery. Passwords cannot be recovered. Information
can be destroyed by repeated attempts of encryption/decryption. Use
at you own risk.
"""

proc getpass(message: string = "Password: "): string =
   return terminal.readPasswordFromStdin(message)

proc getpass2(): string =
    let key = getpass()
    let key2 = getpass("Repeat password: ")
    if key == key2:
        return key
    else:
        quitWithMessage("Passwords do not match")

proc write(content: string): void =
    writeFile(filepath(), content)

proc notify(message: string): void =
    echo message, " ", filepath()

# cli args helpers

proc filepath(): string =
    try:
       return paramStr(2)
    except IndexError:
       return FILENAME

proc command(): string =
    try:
       return paramStr(1).toLowerAscii()
    except IndexError:
       quitWithMessage(USAGE)

# flow control

proc quitWithMessage(message: string): void =
    echo message
    quit(1)

# main

if command() notin ["open", "close", "help"]:
    quitWithMessage(USAGE)

let existingContent = readFile(filepath())

case command()
    of "open":
        let key = getpass()
        let newContent = xxtea.decrypt(existingContent, key)
        write(newContent)
        notify("Decoded")
    of "close":
        let key = getpass2()
        let newContent = xxtea.encrypt(existingContent, key)
        write(newContent)
        notify("Encoded")
    of "help":
        quitWithMessage(USAGE)

As long as the encoding and decoding are so similar you could use a template

template doCmd(gp: untyped, encdec: untyped, msg: string): void =
    let key = gp()
    let newContent = encdec(existingContent, key)
    write(newContent)
    notify(msg)

and then:

of "open":
    doCmd getpass, xxtea.decrypt, "Decoded"
of "close":
    doCmd getpass2, xxtea.encrypt, "Encoded"

You can also use a proc that accepts proc as arguments, more safe for checking the types of arguments passed, but at that point either getpass and getpass2 are declared with the same arguments or you have to pass an argument for each variant.

To pass a function as an argument just use proc and{.closure}

proc doCmd(gp: proc(m: string = "Password: "): string {.closure}, encdec: proc(b: string, k: string): string {.closure}, msg: string): void =
    let key = gp()


Project Euler #2: Even Fibonacci numbers Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  \$1, 2, 3, 5, 8, 13, 21, 34, 55, 89...\$

  By considering the terms in the Fibonacci sequence whose values do not
  exceed \$N\$, find the sum of the even-valued terms.

  Input Format:

  First line contains \$T\$ that denotes the number of test
  cases. This is followed by \$T\$ lines, each containing an integer, \$N\$.

  Output Format:

  Print the required answer for each test case.

  Constraints:

  \$1 \le T \le 10^{5}\$
  \$10 \le N \le 4 \times 10^{16}\$

#include <iostream>

int main () {
    int nCases;
    std::cin >> nCases;
    for (int i = 0; i < nCases; i++) {
        unsigned long back = 1;
        unsigned long front = 2;
        unsigned long total = front;
        unsigned long maxNumber;
        std::cin >> maxNumber;
        while (true) {
            unsigned long frontPrime = front;
            front = (3 * front) + (2 * back);
            back = (2 * frontPrime) + back;
            if (front > maxNumber) {
                break;
            } else {
                total += front;
            }
        }
        std::cout << total << '\n';
    }
    return 0;
}

Commented and formatted:

#include <iostream>

int main () {
    int nCases;
    std::cin >> nCases;

    for (int i = 0; i < nCases; i++) {
        unsigned long back  = 1; // First number of the sequence
        unsigned long front = 2; // Second number of the sequence
        unsigned long total = front; // Since out of the 2, only front is even

        unsigned long maxNumber;
        std::cin >> maxNumber;

        // Keep on getting the even numbers until the number becomes
        // greater than the max
        while (true) {
            unsigned long frontPrime = front; // Need to store its original value for use later

            // We know that every 3rd number is even:
            // 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...
            // o, o, e, o, o, e,  o,  o,  e,  o,  o,   e...
            // Since an odd plus an odd has to equal an even,
            // but an even and an odd is always odd.
            //
            // So using f(n+2) = f(n+1)        + f(n)
            //                 = f(n) + f(n-1) + f(n)
            //                 = 2f(n) + f(n-1)
            //
            // and      f(n+3) = f(n+2)               + f(n+1)
            //                 = f(n+1)        + f(n) + f(n) + f(n-1)
            //                 = f(n) + f(n-1) + f(n) + f(n) + f(n-1)
            //                 = 3f(n) + 2f(n-1)
            //
            // Where n = front, and n-1 = back,
            // we can save from iterating more than once.
            // n+2 is 3 spaces ahead of n-1, and n+3 is 3 spaces ahead of n,
            // thus we go to each even only and save a modulo check.

            front = (3 * front) + (2 * back);
            back  = (2 * frontPrime) + back;

            if (front > maxNumber) {
                break;
            } else {
                total += front;
            }
        }

        std::cout << total << '\n';
    }

    return 0;
}

I was wondering if there is anything I could do to improve the efficiency, both processor- and memory-wise, size (of the code itself not the comments), or general style.

I am also curious as to whether or not there would be a better way to do my algorithm so as not to store frontPrime.

I see a number of things that may help you improve your code.

Make it clear when loops end

The code currently uses while (true) but it doesn't really loop infinitely.  It's better, generally, to have the loop exit condition explicitly stated.  For example we could rewrite your main loop as:

unsigned long total = 0;
while (front <= maxNumber) {
    total += front;
    unsigned long frontPrime = front;
    front = (3 * front) + (2 * back);
    back = (2 * frontPrime) + back;
}

Analyze the mathematics

Your mathematical analysis is correct as far as it goes, but there's a bit easier way to do it.  A bit more algebra will convince you that the series looks like this:

$$a_0 = 0$$
$$a_1 = 2$$
$$a_n = 4a_{n-1} + a_{n-2}$$

Derivation of this sequence

The Fibonacci numbers are defined as:
$$F_0 = 0$$
$$F_1 = 1$$
$$F_n = F_{n-1} + F_{n-2}$$
As you've already noted, the sum of two odd number is even, and the sum of an odd and even number is odd. For the Fibonacci sequence, this means that the sequence of \$O\$ (odd) and \$E\$ (even) looks like this:

$$E, O, O, E, O, O, E, ...$$
In other words, every third term is even.  This gets us to the fact that \$a_n = F_{3n}\$. From this observation, we have this:

$$a_n = F_{3n}$$
$$a_{n-1} = F_{3(n-1)} = F_{3n-3}$$
$$a_{n-2} = F_{3(n-2)} = F_{3n-6}$$
$$a_n = F_{3n-1} + F_{3n-2}$$
Using the definition of the Fibonacci sequence, and expanding the terms on the right, this becomes:
$$a_n = F_{3n-2} + F_{3n-3} + F_{3n-3} + F_{3n-4}$$
Substituting \$a\$ terms for \$F\$ terms, we have:
$$a_n = F_{3n-2} + 2a_{n-1} + F_{3n-4}$$
Expanding the \$F\$ terms on the right again using the definition of the Fibonacci sequence yields:
$$a_n = F_{3n-3} + F_{3n-4} + 2a_{n-1} + F_{3n-5} + F_{3n-6}$$
Again, substitute \$a\$ terms for \$F\$ terms:
$$a_n = a_{n-1} + F_{3n-4} + 2a_{n-1} + F_{3n-5} + a_{n-2}$$
Doing one last substitution and rearranging terms, we get:
$$a_n = 4a_{n-1} + a_{n-2}$$

Code implementation

That means that the outer loop could instead be written like this:

unsigned long back = 0;
unsigned long front = 2;
unsigned long current=0;
unsigned long total = front;
unsigned long maxNumber;
std::cin >> maxNumber;
while (front <= maxNumber) {
    total += current;
    current = 4*front + back;
    back = front;
    front = current;
}
std::cout << total << '\n';

In this scheme \$a_{n-2}\$ is named back and \$a_{n-1}\$ is named front.  Naturally, \$a_n\$ is named current.

Don't recompute values

The sequence is the same every time, so it really doesn't make much sense to recompute values every time.  Better would be to compute them once and save them in a std::vector or std::array. Even better is to compute the values once at compile time.  Given the input range, there are less than 30 terms, which is a very modest storage requirement.

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.