programming languages – Knight tracking

def get_possibilities(x,y):
    m=5
    n=6
    possible = ()
    moves = ((2,1) , (1,2),(2,-1),(-1,2),(-2,1),(1,-2),(-2,-1),(-1,-2))
    for i in range(m):
        for j in range (n):
            for (dx,dy) in moves:
                if 0 < x+dx <= m and 0<y+dy<=n and (x+dx,y+dy) not in possible :
                    possible.append((x+dx,y+dy))
    return possible
    
def solv(m,n,x,y):
    for i in range (m):
        for j in range (n):
            pos = get_possibilities(x,y)
            mini = pos(0)
            for p in pos:
                    if len(get_possibilities(p(0), p(1))) <= len(get_possibilities(mini(0), mini(1))):
                        mini = p 
            (x,y) = (mini(0),mini(1))

I am trying to implement knight tour using Warnsdroff alogorithm , this is what I have tried to implement. I want to track knight position on chess board starting from Iniitial place like ((1,1),(2,3),…..) like this. But when I run my code it gives me weired output , please help me out. How can I incorportae backtracking in this ?

dynamic programming – Why longest common substring path reconstruction is wrong!

I’ve implemented longest common substring in python. I know the usual way to reconstruct the path. But, I am reading my algorithm many times, I don’t understand why it doesn’t work for some test-cases. I am trying to construct the solution while the longest path is being made through dynamic programming.

def lcs(s1, s2):
    n = len(s1)
    m = len(s2)
    
    trow = (0) * (m+1)
    table = (trow) * (n+1)
    
    srow = ("") * (m+1)
    solution = (srow) * (n+1)
    
    for i in range(1, n+1):
        for j in range(1, m+1):
            if s1(i-1) == s2(j-1):                
                table(i)(j) = table(i-1)(j-1) + 1
                
                # Adding this character to the solution
                solution(i)(j) = solution(i-1)(j-1) + s1(i-1)
            
            elif table(i)(j-1) > table(i-1)(j):
                table(i)(j) = table(i)(j-1)
                
                # Choosing the solution related to the longer path
                solution(i)(j) = solution(i)(j-1) 
                
            else:
                table(i)(j) = table(i-1)(j)
                
                # Choosing the solution related to the longer path
                solution(i)(j) = solution(i-1)(j) 
    
    return solution(n-1)(m-1)
lcs('amin', 'kahmjiknln')
# Returns 'amin'

lcs('amin', 'aaaakahmjiknln')
# Returns 'aaaaamin'

programming languages – Find the most frequent alphabet appearing in the given string. In case letter with same frequency, choose the one which comes first alphabetically

Thanks for contributing an answer to Computer Science Stack Exchange!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.

To learn more, see our tips on writing great answers.

mathematical programming – Numerical computing Question

Thanks for contributing an answer to Computer Science Stack Exchange!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.

To learn more, see our tips on writing great answers.

New to programming advice and input on my first “real” Python project. What can I do to get better? best practices?

So this is a project I have been working on for the last few weeks. Just started learning Python. Started out with bash scripting and got the itch to learn more. Anyway code fetches covid-19 data from the internet, assembles data the way I need it to, plots it on graphs that are saved as .png files, writes all the data and graphs to a ‘README.md’ file and pushes it to github. As I am self taught I am posting this for feedback so I dont develop bad habits and can learn the best practices. Any advice or criticism would be appreciated. Thank you.

#!/usr/bin/env python3
import requests
import pandas as pd
import io
import numpy as np
import matplotlib.pyplot as plt
import os

# **** Build data ****

# Fetch data
url = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us.csv'
download = requests.get(url).content
df = pd.read_csv(io.StringIO(download.decode('utf-8')))

# Extract each column individually
date = df('date')
cases = df('cases')
deaths = df('deaths')

# Calculate new cases
total_cases = np.array(cases)
new_cases = np.diff(total_cases)
new_cases = np.insert(new_cases, 0, 1)

# Calculate new deaths
total_deaths = np.array(deaths)
new_deaths = np.diff(total_deaths)
new_deaths = np.insert(new_deaths, 0, 0)

# Create csv for total cases and deaths
df = pd.DataFrame({'date': date, 'total cases': total_cases,
    'total deaths': total_deaths})
df.to_csv('data/us_covid-19_total.csv', index=False)

# Create csv for new cases and deaths
df = pd.DataFrame({'date': date, 'new cases': new_cases, 
    'new deaths': new_deaths})
df.to_csv('data/us_covid-19_new.csv', index=False)

# Create csv for all aggregated data
df = pd.DataFrame({'date': date, 'total cases': total_cases, 
    'total deaths': total_deaths, 'new cases': new_cases, 'new deaths': new_deaths})
df.to_csv('data/us_covid-19_data.csv', index=False)

# **** Plot data ****

# x axis for all plots
x = np.array(date, dtype='datetime64')

# Plot Total Cases
y = total_cases / 1000000
plt.figure('US Total COVID-19 Cases', figsize=(15, 8))
plt.title('US Total COVID-19 Cases')
plt.ylabel('Cases (in millions)')
plt.grid(True, ls='-.')
plt.yticks(np.arange(min(y), max(y) + 10))
plt.plot(x, y, color='b')
plt.savefig('plots/US_Total_COVID-19_Cases.png')

# Plot Total Deaths
y = total_deaths / 1000
plt.figure('US Total COVID-19 Deaths', figsize=(15, 8))
plt.title('US Total COVID-19 Deaths')
plt.ylabel('Deaths (in thousands)')
plt.grid(True, ls='-.')
plt.yticks(np.arange(min(y), max(y) + 100, 50))
plt.plot(x, y, color='b')
plt.savefig('plots/US_Total_COVID-19_Deaths.png')

# Plot New Cases
y = new_cases / 1000
plt.figure('US New COVID-19 Cases', figsize=(15, 8))
plt.title('US New COVID-19 Cases')
plt.ylabel('Cases (in thousands)')
plt.grid(True, ls='-.')
plt.yticks(np.arange(min(y), max(y) + 100, 50))
plt.plot(x, y, color='b')
plt.savefig('plots/US_New_COVID-19_Cases.png')

# Plot New Deaths
y = new_deaths
plt.figure('US New COVID-19 Deaths', figsize=(15, 8))
plt.title('US New COVID-19 Deaths')
plt.ylabel('Deaths')
plt.grid(True, ls='-.')
plt.yticks(np.arange(min(y), max(y) + 1000, 500))
plt.plot(x, y, color='b')
plt.savefig('plots/US_New_COVID-19_Deaths.png')

# **** Write to README.md ****

# New cases and deaths in the last 24 hours
cases = new_cases(-1)
deaths = new_deaths(-1)

# 7-day mean for new cases and deaths
cmean = np.mean(new_cases(-7:))
dmean = np.mean(new_deaths(-7:))

# Date
date = np.array(date, dtype='datetime64')
date = date(-1)

# DataFrame for new cases and deaths in the last 24 hours 
df_24 = pd.DataFrame({'New cases': (f'{cases:,d}'), 'New deaths': (f'{deaths:,d}')})
df_24 = df_24.to_markdown(index=False, disable_numparse=True)

# DataFrame for 7-day average
df_avg = pd.DataFrame({'Cases': (f'{int(cmean):,d}'), 'Deaths': (f'{int(dmean):,d}')})
df_avg = df_avg.to_markdown(index=False, disable_numparse=True)

# Write to 'README.md'
f = open('README.md', 'w')
f.write(f'''# US COVID-19 (Data)(https://github.com/drebrb/covid-19-data/blob/master/data/us_covid-19_data.csv)
###### Reported numbers for {str(date)} 
{df_24}
###### 7-day average 
{df_avg}
## (Total Cases and Deaths)(https://github.com/drebrb/covid-19-data/blob/master/data/us_covid-19_total.csv)
### Cases
!(Plot)(https://github.com/drebrb/covid-19-data/blob/master/plots/US_Total_COVID-19_Cases.png)
### Deaths
!(Plot)(https://github.com/drebrb/covid-19-data/blob/master/plots/US_Total_COVID-19_Deaths.png)
## (New Cases and Deaths)(https://github.com/drebrb/covid-19-data/blob/master/data/us_covid-19_new.csv) 
### Cases
!(Plot)(https://github.com/drebrb/covid-19-data/blob/master/plots/US_New_COVID-19_Cases.png)
### Deaths
!(Plot)(https://github.com/drebrb/covid-19-data/blob/master/plots/US_New_COVID-19_Deaths.png)''')
f.close()

# **** push to github ****

os.system('git add . && git commit -m "Updating data." && git push')
```

linear programming – When LP solution is ILP solution?

For many discrete problems, it’s natural to consider their continuous relaxations. A common case is when instead of $x_i in {0, 1}$ we allow $x_i in (0, 1)$. In certain cases, the original problem is an integer linear programming (ILP) problem, and its relaxed version becomes a linear programming (LP) problem, which we can efficiently solve.

Questions: Are there common techniques which show that, for a particular problem:

  1. An LP solution will always be an ILP solution?
  2. There exists an LP solution that is also an ILP solution?
  3. A particular LP algorithm (e.g. simplex method) finds an ILP solution.

By “solution”, I, of course, mean a vector on which the objective reaches its optimum.

programming practices – Unit testing a chain of network requests – how many tests?

I have some fairly complex code, that is a chain of API calls. The result of one call is the input of the next.

class PaymentService {
   func pay(userId: String) async {
      let paymentSource = await thirdPartyService.createPaymentSource() // A
      let order = await orderService.createOrder(paymentSource: paymentSource) // B
      let result = await paymentService.chargeUser(userId: userId, order: order) // C
   }

I would like to test that:

  • The methods are called
  • The correct parameters are passed into each step

How many tests would you write for something like this?

  • On one hand, most TDD material suggests that tests should test a single thing, and if the test fails, there should be a single reason why this happened.
  • On the other hand, I feel like there is a lot of duplicated setup code, and a single test might be easier to understand.

Multiple tests:

// Tests line A
func test_pay_callsThirdPartyService() {
    // Given
    mockThirdPartyService.createPaymentSource_returnValue = mockPaymentSource
    
    // When
    sut.buy(userId: "123")

    // Then
    assert(mockThirdPartyService.createPaymentSource_called) == true
}

// Tests line B
func test_pay_callsCreateOrder_withPaymentSource() {
    // Given
    let paymentSource = mockPaymentSource
    mockThirdPartyService.createPaymentSource_returnValue = paymentSource
    mockOrderService.createOrder_returnValue = mockOrder
    
    // When
    sut.buy(userId: "123")

    // Then
    assert(mockOrderService.createOrder_called) == true
    assert(mockOrderService.createOrder_paymentSource) == paymentSource
}

// Tests line C
func test_pay_callsChargeUser_withCreatedOrder() {
    // Given
    let order = mockOrder
    let userId = "123"

    mockThirdPartyService.createPaymentSource_returnValue = paymentSource
    mockOrderService.createOrder_returnValue = order
    mockPaymentService.chargeUser_returnValue = mockResult
    
    // When
    sut.buy(userId: userId)

    // Then
    assert(mockOrderService.chargeUser_called) == true
    assert(mockOrderService.createOrder_userId) == userId
    assert(mockOrderService.createOrder_order) == order
}

Single test

func test_pay_callsPaymentChainCorrectly() {
    // Given
    let paymentSource = mockPaymentSource
    let order = mockOrder
    let userId = "123"

    mockThirdPartyService.createPaymentSource_returnValue = paymentSource
    mockOrderService.createOrder_returnValue = order
    mockPaymentService.chargeUser_returnValue = mockResult
    
    // When
    sut.buy(userId: userId)

    // Then
    // Tests line A
    assert(mockThirdPartyService.createPaymentSource_called) == true

    // Tests line B
    assert(mockOrderService.createOrder_called) == true
    assert(mockOrderService.createOrder_paymentSource) == paymentSource

    // Tests line C
    assert(mockOrderService.chargeUser_called) == true
    assert(mockOrderService.createOrder_userId) == userId
    assert(mockOrderService.createOrder_order) == order
}

python – Vigenère Cipher problem in competitive programming

I’ve just started doing programming problems.

https://icpcarchive.ecs.baylor.edu/external/58/p5880.pdf

The code below works fine, but my run time is 2.715 seconds and the time limit is 3 seconds.

How can I improve speed of this code?

I’ve already started to use sys.stdin instead of input().

import string
import sys


while True:
    key = sys.stdin.readline().strip()
    key = int(key) if key.isdigit() else key
    if key == 0: break

    decrypted_msg = sys.stdin.readline().strip()
    decrypted_msg = int(decrypted_msg) if decrypted_msg.isdigit() else decrypted_msg
    if decrypted_msg == 0: break

    key = (len(decrypted_msg)//len(key) + 1) * key
    key = key(0:len(decrypted_msg))

    encrypted_msg = ""

    for i in range(len(decrypted_msg)):
        key_idx = string.ascii_uppercase.index(key(i))
        deciphered_idx = string.ascii_uppercase.index(decrypted_msg(i))

        enciphered_idx = (deciphered_idx + key_idx + 1) % len(string.ascii_uppercase)
        encrypted_msg += string.ascii_uppercase(enciphered_idx)

    print(encrypted_msg)

Do any programming languages use types as values? Would there be any point?

You say:

One thing I haven’t seen (…) is using a type as a value that can be passed around, allowing it to instantiate new objects, call static functions etc, while still providing all the benefits of strong type checking

Emphasis mine.

For example, I have 2 classes, J and K, both of which implement interface I and in some circumstances may be used in the same place.

And:

if the type itself can be passed I could have a function that takes a type implementing I and call whichever version of a static member function, based on the passed object

Emphasis mine.

Something that gets close is runtime interrogations. For example with simple C# pattern matching:

public static void Test<T>(T obj)
    where T: I
{
    if (obj is J objAsJ)
    {
        // use J, including static methods on J
    }

    if (obj is K objAsK)
    {
        // use K, including static methods on K
    }
}

This provides “all the benefits of strong type checking”. However, of course, has the drawback of forcing you to enumerate the possible types.

If the type is to be passed at runtime – for example, in a variable, as the question suggests – it means it is not known at compile time, so we lose that strong type checking. To pass a type at runtime but have some type information in compile time, we have generic type arguments and constraints, of course. Yet, that won’t give you access to static members.

I only see two paths to keep such strong type checking: We interrogate the object, as shown above. Or stronger generic constraints…


Another thing that gets close is static interface methods. If we can make a generic constraint to such interface, we could be able to use those static members.

Java has interfaces with static methods, but you can’t override those. So we need a language with has something like interfaces with static members that we can override. Rust is such language.

For example, I have 2 classes, J and K, both of which implement interface I and in some circumstances may be used in the same place.

I’ll have two types Dog and Sheep, and a trait Animal implemented for both.

if the type itself can be passed I could have a function that takes a type implementing I and call whichever version of a static member function, based on the passed object

Traits in Rust can have static functions, which we get to implement for each type.

I’ll show how to call both static and instance functions defined in a trait, getting a different result depending on the actual type. So it calls “whichever version of a static member function, based on the passed object”.

The reason I’m saying it gets very close is because I’ll never have a variable storing the type, which is what the title of the question suggests (“Do any programming languages use types as values?”).

To be fair, Rust has TypeID, which is just a number. It can be used to identify and compare types, but that’s about it.

Instead everything is type checked at compile time (which, according to comments, seems to be what you care about). Rust does not have runtime reflection.

Note: I’ll be using String (which is a heap allocated string), and i’ll be cloning it. Not efficient, but I don’t bother with lifetimes.


I’ll have two types Dog and Sheep:

struct Dog { name: String }
struct Sheep { wool: bool, name: String }

An Animal trait:

trait Animal {
    fn new(name: String) -> Self; // Self is the type that implements the trait
    
    fn name(&self) -> String;
    
    fn noise(&self) -> String;
    
    fn talk(&self) {
        println!("{} says {}", self.name(), self.noise()); // This is default impl.
    }
    
    fn specie() -> String;
}

And we implement the trait for both types. This is Animal for Dog:

impl Animal for Dog {
    fn new(name: String) -> Dog {
        Dog { name: name }
    }

    fn name(&self) -> String {
        self.name.clone()
    }

    fn noise(&self) -> String {
        "bark!".to_string()
    }
    
    fn specie() -> String
    {
        "Canine".to_string()
    }
}

This is Animal for Sheep.

impl Animal for Sheep {
    fn new(name: String) -> Sheep {
        Sheep { name: name, wool: true }
    }

    fn name(&self) -> String {
        self.name.clone()
    }

    fn noise(&self) -> String {
        if self.wool {
            "baaaaah!".to_string()
        } else {
            "baaaaah?".to_string()
        }
    }
    
    fn talk(&self) {
        println!("{} pauses briefly... {}", self.name, self.noise());
    }
    
    fn specie() -> String
    {
        "Ovine".to_string()
    }
}

Let us use them:

fn test<T: Animal>(animal: &T) {
    println!("{}", T::specie());
    animal.talk();
    let clone = T::new("Clone of ".to_owned() + &animal.name());
    clone.talk();
}

fn main() {
    let my_dog: Dog = Animal::new("Snuppy".to_string());
    let mut my_sheep: Sheep = Animal::new("Dolly".to_string());
    test(&my_dog);
    test(&my_sheep);
}

As you can see the test function is generic. It has a type argument T that must have an implementation of Animal. And it borrows an argument of that type.

We are able to call static functions defined in the trait:

println!("{}", T::specie());

Which outputs "Canine" for Dog and "Ovine" for Sheep.

We are able to call instance functions defined in the trait:

animal.talk();

We are able to create new instances of the same type we are given (this is just another static function):

let clone = T::new("Clone of ".to_owned() + &animal.name());

And use those those instances:

clone.talk();

Everything is type checked at compile time.

This is the output of the program:

Canine
Snuppy says bark!
Clone of Snuppy says bark!
Ovine
Dolly pauses briefly... baaaaah!
Clone of Dolly pauses briefly... baaaaah!

What is Confinement and Bounds in programming?

I don’t understand deference between confinement and bound in programming? I always understand these two as same definition..

Could you please explain me someone,

  • what is bound and confinement?
  • What is deference between these two?