Python programming: – Code Review Stack Exchange

#Answer the following question without running the code. The procedure isMyNumber is used to hide a secret number (integer). It takes an integer x as a parameter and compares it to the secret number. It returns: -1 if the parameter x is less than the secret number 0 if the parameter x is correct 1.

def jumpAndBackpedal(isMyNumber):
isMyNumber: Procedure that hides a secret number.
It takes as a parameter one number and returns:
* -1 if the number is less than the secret number
* 0 if the number is equal to the secret number
* 1 if the number is greater than the secret number

returns: integer, the secret number
guess = 1
if isMyNumber(guess) == 1:
    return guess
foundNumber = False
while not foundNumber:
    sign = isMyNumber(guess)
    if sign == -1:
        guess *= 2
        guess -= 1
return guess

#Unfortunately, the implementation given does not correctly return the secret number. Please fix the errors in the code such that jumpAndBackpedal correctly returns the secret number.

I wanted to get hints how to think about this problem

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.

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 ‘’ 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 = ''
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')

# 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')

# 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')

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

# **** Write to ****

# 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 ''
f = open('', 'w')
f.write(f'''# US COVID-19 (Data)(
###### Reported numbers for {str(date)} 
###### 7-day average 
## (Total Cases and Deaths)(
### Cases
### Deaths
## (New Cases and Deaths)( 
### Cases
### Deaths

# **** 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.

python – Vigenère Cipher problem in competitive programming

I’ve just started doing programming problems.

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)


Fine-grained versioning of entities in programming languages

I have a question related to design, implementation of programming languages. I hope it fits here and apologize if it doesn’t.

All or most programming languages version modules (aka packages, libraries, crates). All the entities in a module (types, functions, variables and other information) share the same version with the module. However usually only some parts of a module change between a version and the next.

When two different modules use different versions of the same third module, this creates an incompatibility.

  • Some programming languages (for instance C and C++) ignore the problem altogether. They don’t care about the version but only about the name and signature of entities. They accept programs that may crash or misbehave when executed, if different pieces of such programs expected different versions of a same entity that changed.

  • Other programming languages (for instance Rust or Node.js) trait different versions of the same entity as two completely different entities. This avoid crashes, but introduces unnecessary incompatibilities between entities that did not change.

This can be a big problem for modules that define many different entities and that lots of other modules depend on, for instance the standard library of a programming language. Most programming languages use special tricks for their standard libraries: for instance they tie the standard library’s version to the compiler version and require to recompile everything when the compiler version changes.

A better solution to this problem could be versioning every entity independently instead of whole modules. The GNU implementation of the standard library of C and C++ do this. I have seen some Rust crates do this too by importing their previous version and re-exposing all the symbols that didn’t change. But these processes are very tedious and easy to get wrong, hence very few pieces of software adopt similar practices.

Do we know of any good way to version entities in a fine-grained way?

Has there been any research on this problem?

A practical example

If the problem I described isn’t clear, let me explain it with a practical example.

A module “time 1.0.0” defines loads of entities related to time. Among many others, it defines these two types:

type UnixTime   = uint32_t; # seconds from 1970 Jan 1
type UnixTimeNS = uint32_t; # nanoseconds from 1970 Jan 1

After “time 1.0.0” is out, we realize that UnixTimeNS is too small: it needs to be an uint64_t. We change that type and release “time 2.0.0” since we did an incompatible API change. Nothing else changed in the whole “time” module besides that UnixTimeNS type.

Two other modules “logger” and “totp” depend on “time”. The former was developed on “time 1.0.0”, while the latter uses “time 2.0.0”. They both only use time::UnixTime and nothing else. This type did not change between the two version. But the compiler can’t know that and treats time_1.0.0::UnixTime and time_2.0.0::UnixTime as different, incompatible types. It’s now very hard to use both “logger” and “totp”.

Imagine if they make a similar change to the standard library of any existing language: it could result in a tremendous split between new and existing modules, something as catastrophic as the switch from Python 2 to Python 3. All for a very minor change that affects 0.1% of the existing code.

I developed a rust crate ( and a Node.js package ( to show this problem in action. The names used in these projects differ from the ones in the example described here, but the meaning is the same.

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.


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.noise()); // This is default impl.
    fn species() -> 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 {

    fn noise(&self) -> String {
    fn species() -> String

This is Animal for Sheep.

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

    fn name(&self) -> String {

    fn noise(&self) -> String {
        if self.wool {
        } else {
    fn talk(&self) {
        println!("{} pauses briefly... {}",, self.noise());
    fn species() -> String

Let us use them:

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

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

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::species());

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

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

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() + &;

And use those those instances:;

Everything is type checked at compile time.

This is the output of the program:

Snuppy says bark!
Clone of Snuppy says bark!
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?

When or why would someone use a programming language (Swift, Java, C++, Rust etc…) over an engine like Unity?

Everytime I’ve read about people asking whether they should write their game in C++ or Unity, Unity is usually the default answer, unless they want to go through the hassle of creating an engine by themselves when Unity already does everything for you. If that’s the case is there ever a case where writing a game in C++, Java, Rust etc… is better than using Unity? If so what are these cases?

functional programming – Passing Multiple Arguments Including A List To A Function In Haskell

Your use of mutliplesOfKLessThanN is not correct

mutliplesOfKLessThanN((3,5) 1000)

Is not interpreted by Haskell as

Apply mutliplesOfKLessThanN with (3,5) and 1000.

but instead it is interpteted as

Apply (3,5) to 1000 and apply multiplesOfKLessThanN to the result.

I think your misconception is in how function application occurs. In many languages function application requires parentheses e.g. f(x). For Haskell parentheses, only ever mean do this operation first, and function application is achieved by putting things next to each other. So f(x) works in Haskell because it is the same as f x, but f(x y) is the same as f(x(y)) and tells Haskell to evaluate x y first and then give it to f.

With your code Haskell can’t apply (3,5) as a function, which is what Haskell is telling you, it expected a function (in fact a specific type of function).

The proper way to write this would be

multiplesOfKLessThanN (3,5) 1000

This should handle that main error you are getting.