python 3.x – Generate random string to match the goal string with minimum iteration and control statements

It took me a while to understand the code but I hope that I understood it properly.
Lets say you have the string “abcd”

   goal string      "abcd"
   1st iteration    "ftcP" -> you save the 3rd position as found
   2nd iteration    "aXlL" -> At this pint both 1st and 3rd positions have been found 
   3rd iteration    "...." -> Still 3rd and 1st 
   4th iteration    "UbDd" -> all positions have matched at least once. 
   Stop and return 4 as the result

If the previous example is what you want to achieve below is my code suggestion

from random import choice

pool = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !@#&()–({}):;‘,'?/*1234567890'''
GetNewChar = lambda x: choice(pool)

def GetRandomString(stringLen):
    characters = (GetNewChar() for i in range(stringLen))
    return ''.join(characters)

def IterationsToMatchString(goal_string):
    IsGoalAchieved = (False for i in goal_string)
    while not all(IsGoalAchieved): 
        iterations += 1
        test_string = GetRandomString(len(goal_string))
        Matches = (g==t for g,t in zip(goal_string,test_string))
        for i,t in enumerate(IsGoalAchieved):
            if t is False: 
                IsGoalAchieved(i) = Matches(i)
    return iterations

example = input()

regardless of which variable naming convention you use I suggest not using the same name for the function and the output unless you are writing a decorator function. In your “randomString” function you return a variable named “randomString” which makes the code difficult to understand and is likely to bug. I would suggest changing the name of the function to improve reading.

Also you abuse the global keyword. You can just pass arguments to the function. In this case your function randomString generates a random string of a fixed length. Therefore you can always call that function with the length as a parameter.

Also as you have seen I have substituted the usage of randrange by choice (but does the same). I prefer it because we are picking one item out of a certain sequence.I have used a lambda function to provide a more “readable” name that gives information about what is being done.

real analysis – Prove the existence of local minimum of a multi-variable absolute value function.

I have the following function
$$H(mathbf{x}) = a_{1}|x_{1}-A_{1}|+a_{2}|x_{2}-A_{2}|+cdots+a_{n}|x_{n}-A_{n}|

where all coefficients are positive.

For two dimensional case, I can plot $$H(x_{1},x_{2}) = a_{1}|x_{1}-A_{1}|+a_{2}|x_{2}-A_{2}|

and it indeed has only one minimum,

enter image description here

However, I cannot prove it in a more general case. Does anyone once had encountered such problems?

performance – Finding minimum steps required to traverse from source to terminal

Hello everyone this is my first post here so please do critique my post if there’s anything.

I have made a program intended to pass a programming challenge on, here.
It should do as title says, but with the conditions that each traversal follows the rules of a “Knight” from chess, that being plus/minus two columns/rows and plus/minus one column/row.

  1. _read method:
    I attempted to solve this making a Node class and passing coordinate and char data into each instance of a Node object for each coordinate.

  2. _adjacencify method:
    Thereafter, I found adjacencies (neighbours) of all Node objects, with the aforementioned condition of a chess Knight.

  3. _jump method:
    Lastly, I used a BFS implementation in order to find the shortest path from the source (root) to the terminal (here represented as ‘K’).

  4. find_path:
    Wraps everything up.

Here’s the code I ended up with:

class Nite
  #attr_accessor :char, :col, :row
  class Node
    attr_accessor :char, :col, :row, :disc, :parent
    attr_reader :adjies
    def initialize(char, col, row)
      @char = char
      @col = col
      @row = row
      @adjies = () # adjacencies
      @disc = false
      @parent = nil
    def add(value)
      @adjies << value

  def _read
    # assign each coord. to a Node-object
    n = gets.to_i
    nodes =
    n.times do |x|
      temp = gets.strip.to_s
      temp.size.times do |y|
        node =, x, y)
        nodes << node


  def _adjacencify(nodes)

    nodes.each do |x|
      nodes.each do |y|
        if y.col == x.col && y.row == x.row || y.char == '#'

        # logic

        if x.row == (y.row - 1) # y.row + 1

          if x.col == (y.col - 2) # y.col + 2
            x.add(y) # (col+2, row+1)
          elsif x.col == (y.col + 2) # y.col - 2
            x.add(y) # (col-2, row+1)
        elsif x.row == (y.row + 1) # y.row - 1

          if x.col == (y.col - 2) # y.col + 2
            x.add(y) # (col+2, row-1)
          elsif x.col == (y.col + 2) # y.col - 2)
            x.add(y) # (col-2, row-1)

        if x.row == (y.row - 2) # y.row + 2

          if x.col == (y.col - 1) # y.col + 1
            x.add(y) # (col+1, row+2)
          elsif x.col == (y.col + 1) # y.col - 1
            x.add(y) # (col-1, row+2)
        elsif x.row == (y.row + 2) # y.row - 2

          if x.col == (y.col - 1) # y.col + 1
            x.add(y) # (col+1, row-2)
          elsif x.col == (y.col + 1) # y.col - 1
            x.add(y) # (col-1, row-2)




  def _jump(nodes)

    nodes = _adjacencify(nodes)

    q =
    root = nodes(0)
    root.disc = true
    q << root

    while !q.empty? do
      v = q.pop
      if v.char == 'K'
        steps = 0
        until v.parent == nil do
          if !v.nil?
          steps += 1
          v.parent = v.parent.parent
        return steps
      v.adjies.each do |w|
        if w.disc == false
          w.parent = v
          w.disc = true
          q << w
    return -1


  def find_path


nite =
puts nite.find_path

I suspect of course that the _adjacencify method is super time consuming, and that some loops are way too time consuming.
I failed the <1.00s time requirement in order to pass the challenge.

I want all types of criticism on my code, and I want tips and also, if anyone wants, different implementations that perform better.
Especially Ruby convention is something I want critique on, considering I am coming from a Java and Python background and I’m fairly fresh in Ruby.

Please tell me if I should edit anything in this post to make anything clearer.

beginner – Greedy algorithms to find minimum number of coins (CS50)

I’m taking CS50, an Introduction to CS, and we’re asked to do the following task:

Suppose that a cashier owes a customer some change and in that cashier’s drawer are quarters (25¢), dimes (10¢), nickels (5¢), and pennies (1¢). The problem to be solved is to decide which coins and how many of each to hand to the customer. Think of a “greedy” cashier as one who wants to take the biggest bite out of this problem as possible with each coin they take out of the drawer. For instance, if some customer is owed 41¢, the biggest first (i.e., best immediate, or local) bite that can be taken is 25¢. (That bite is “best” inasmuch as it gets us closer to 0¢ faster than any other coin would.) Note that a bite of this size would whittle what was a 41¢ problem down to a 16¢ problem, since 41 – 25 = 16. That is, the remainder is a similar but smaller problem. Needless to say, another 25¢ bite would be too big (assuming the cashier prefers not to lose money), and so our greedy cashier would move on to a bite of size 10¢, leaving him or her with a 6¢ problem. At that point, greed calls for one 5¢ bite followed by one 1¢ bite, at which point the problem is solved. The customer receives one quarter, one dime, one nickel, and one penny: four coins in total

Here is my solution to the problem:

#include <stdio.h>
#include <cs50.h>
#include <math.h>

float cents, money;
int ask_money(void);
int dollars_to_cents(int dollars);
int get_max_coins(int _cents, int coin_type);
int min_coins_exchanged(int _money, int _coin_types(), int _arr_length);
int quarter = 25, dimes = 10, nickles = 5, pennies = 1;

int main(void)
    money = dollars_to_cents(ask_money());
    int arr_length = 4;
    int coin_types() = {quarter, dimes, nickles, pennies};
    printf("%in", min_coins_exchanged(money, coin_types, arr_length));

// Given some amount of money, this returns the maximum amount of coins of a certain type possible 
// such that the remaining money is less than the value of the coin type, then it subtracts our money by that amount 
int get_max_coins(int _cents, int coin_type)
    int max_coins = floor((float)((_cents) / coin_type));
    money -= max_coins * coin_type;
    return max_coins;

int ask_money(void)
        money = get_float("Change owed: ");
    while (money < 0);
    return money;

// Necessary to avoid problems with floating point imprecision
int dollars_to_cents(int dollars)
    return round(money * 100);

// Calculates the minimum amount of coins exchanged such that when these coins are added up they are equal to the change owed
int min_coins_exchanged(int _money, int _coin_types(), int _arr_length)
    int _min_coins_exchanged = 0;
    for(int i = 0; i < _arr_length; i++)
        _money = money;
        _min_coins_exchanged += get_max_coins(_money, _coin_types(i));
    return _min_coins_exchanged;

I’m looking for feedback on my code. How do I make my code better and cleaner? I.e in terms of readability, performance, comments, design principles, etc. There’s a lot of ways to approach this problem, and indeed when trying to solve it I’ve tried many different ways but this is my current favorite. What do you think about my solution? Perhaps there’s a better way to approach the problem?

Bounds on minimum solutions to empirical and theoretical objective functions

Let $P$ and $Q$ be two probability distributions and let

$$S_0 = min_{f,g} left( int f(x), dP(x) + int g(y), dQ(y) right)$$ such that $f(x)+g(y) geq langle{x,yrangle}$ where $f,g$ are strongly convex. This is a Wasserstein semi-dual except with the strongly convex restriction.

Now say I want to estimate the above but I only have points $x_1,ldots,x_n in hat{P}$ and $y_1,ldots,y_n in hat{Q}$ to work with.

Compute $$S^{*} =min_{hat{f_i},hat{g_i},nablahat{f_i},nablahat{g_i}} left( frac{1}{n}sum_{i=1}^n hat{f}_i + frac{1}{n}sum_{i=1}^n hat{g}_i right)$$ where

$hat{f_i}+hat{g_j} geq langle{x_i,y_jrangle}$,

$hat{f_i} geq hat{f_j} + langle{nablahat{f_j},x_i-x_jrangle} + frac{c}{2}left|x_j-x_iright|^2$,

and $hat{g_i} geq hat{g_j} + langle{nablahat{g_j},y_i-y_jrangle} + frac{c}{2}left|y_j-y_iright|^2$

for all $i,j$. So we can think of $hat{f_i},hat{g_i},nablahat{f_i},nablahat{g_i}$ as being updated repeatedly after starting off with some suitable values at initialization.

Is there anything one can say about $S_0-S^*$? I’m honestly lost and I don’t know how to proceed here. Are there any techniques I can use here?

minimum number of edges that should be added to an undirected graph to make it a tree

Your first guess is correct. Sometimes there is more than one way to write the same solution.

Clearly, if there are $k$ connected components you’ll need exactly $k-1$ edges to connect them (without forming any cycle).

On the other hand, a tree with $n$ nodes must have exactly $n-1$ edges, so if the graph is acyclic and already has $m$ edges, then it is missing $n-1-m$ edges.

Regarding the example: the given graph has $n=10$ vertices, $m=6$ edges, and $k=4$ connected components (not 3), so the answer is $3=k-1=n-m-1$. The sets of vertices in each connected component are ${1,2,8}, {3}, {4, 6, 10}$, and ${5, 7, 9}$.

algorithms – Find an minimum weight elementary path with a given constraint

I have a problem as below and I am really stuck with it as it run with more than the time I desired (about 1 second). I really want your help to build up a more efficient algorithms than mine

Given an undirected graph G = (V, E) with two parameter of weights w1 and w2 for each edges. This graph has N vertices and M edges. A K-Elementary path S is a sub-graph of G which must be an elementary graph and it does have exactly K edges.

Find a K-elementary path S with the sum of w1 of all edges as minimum value and the sum of w2 of all edges of S must be smaller than a given value Q. If it does not exist any path satisfied, print out the value -1


The first line with four values N, M, K, Q (2 <= N, K <= 50, 1 <= M <= 2*N, 1 <= Q <= 10^9)

The next M lines show the edges of the graph: V1 V2 W1 W2 (1 <= V1, V2 <= N, 1 <= W1 <= 10^4, 1 <= W2 <= 10^4)

Output: One integer to show the minimum weight of the k-elementary graph found. -1 if non-exists

Sample test case:


5 7 3 6
1 2 1 2
1 4 2 2
1 5 3 6
2 3 3 2
2 4 4 4
3 4 5 1
4 5 4 7



First of all, I want to quote the definition of an elementary path.

In short, for this problem, we need to find an k-elementary path S such that the weight to w1 is minimum, the sum of all edges to w2 is less than or equal to Q and it does have exactly K edges.

I do have a Backtracking approach, in which I tried to build up all the graph satisfying the second condition (w2) and then find the minimum of the first condition (w1) but, as you have known, the time complexity is quite high. However, I find it hard to convert it to dynamic programming or any other methods to reduce to time complexity. I do add some Branch-bound condition but it is still slow.

Below is my source code which you can refer but I do not think it is useful

#include <bits/stdc++.h>
using namespace std;
#define N 51
#define INF 1e9
int n, m, K, Q;
bool appear(N);
int W1(N)(N);
int W2(N)(N);
int currentSum1 = 0;
int currentSum2 = 0;
int source = 0;
int res = INF;
int Log(N);
int minElement = INF;
bool check(int k, int v)
    return !appear(v) && W1(Log(k - 1))(v) != 0 && W2(Log(k - 1))(v) != 0;
void solution()
    if(currentSum1 != 0 && currentSum1 < res)
        res = currentSum1;
        // for(int i = 0; i <= K; i++)
        //     cout << Log(i) << " ";
        // cout << endl;
void solve(int k)
    for(int v = 1; v <= n; v++)
        if(check(k, v) && currentSum2 + W2(source)(v) <= Q && currentSum1 + (K - k) * minElement <= res) //Branch-bound condition
            Log(k) = v;
            currentSum2 += W2(Log(k - 1))(v);
            currentSum1 += W1(Log(k - 1))(v);
            appear(v) = true;
            if(k == K)
                solve(k + 1);
            currentSum1 -= W1(Log(k - 1))(v);
            currentSum2 -= W2(Log(k - 1))(v);
            appear(v) = false;
int main()
    // freopen("data.txt", "r", stdin);
    cin >> n >> m >> K >> Q;
    for(int i = 0; i < m; i++)
        int x, y, w1, w2;
        cin >> x >> y >> w1 >> w2;
        minElement = min(minElement, w1);
        W1(x)(y) = w1;
        W1(y)(x) = w1;
        W2(x)(y) = w2;
        W2(y)(x) = w2;
    for(int v = 1; v <= n; v++)
        source = v;
        currentSum2 = 0;
        currentSum1 = 0;
        Log(0) = v;
        for(int i = 1; i <= n; i++)
            appear(i) = false;
        appear(source) = true;
    if(res != INF)
        cout << res << endl;
        cout << -1 << endl;

algorithm – Given a positive integer N, what is the minimum positive integer K such that K! Is a multiple of the square of N?

Pretty new to programming, been doing some pretty basic stuff but I came across a more complicated one now (C language), not sure how to start with it. I’m not understanding the definition of “K! is a multiple of the square of N” to be frank, so I can’t really tell what is expected from me here. If anyone could just explain the point to me, I would really appreciate it.


Given a positive integer N, what is the minimum positive integer K such that K! is a multiple of the square of N?

Note that a is a multiple of b if a=b*k for some integer k.
Moreover, note that for any positive integer M, M! is the product of all positive integers whose value is at most M.


The first line of input contains T, the number of test cases. The following lines describe the test cases.
Each test case consists of one line containing a single integer N.


For each test case, print a single integer which is the answer for that test case.

1 <= T <= 200000
1 <= N <= 200000

Sample Input:

Sample Output:

Thanks a lot in advance for any tips!

tag removed – Estimate the minimum distance between his starting point and the current position

A farmer owns a rectangular farm that has a road on all four sides. He starts from one corner of the field and walks north. After going 600 meters, he takes a right turn and walks another 400 meters. Again he takes a right and walks for 100 meters Estimate the minimum distance between his starting point and the current position.

a. 360 m
b. 500 m
c. 420 m
d. None of the above

My answer came (410000)^0.5 but the answer is A. 360m