This question already has an answer here:
Competitive Programming Python: Repeated sum of digits Error
(1 answer)
Closed 5 years ago.
I would like to find the sum of the digits using python. when i enter a birth year 1982 the result should be 1+9+8+2 = 20 final total result is 2+0 = 2.
The reason that i am posting this question is i didn't find any simple python solution for this.
This is my code
num = int(input("Enter your birth year: "))
x = num //1000
x1 = (num - x*1000)//100
x2 = (num - x*1000 - x1*100)//10
x3 = num - x*1000 - x1*100 - x2*10
x4 = x+x1+x2+x3
num2 = int(x4)
x6 = num2 //10
x7 = (num2 -x6)//10
print("your birth number is" ,x6+x7)
but i am not getting the correct sum value.
Sum the digits of an integer until the result is a one-digit integer:
def sum_digits(num):
num = str(num)
if len(num) < 2:
return int(num)
else:
return sum_digits(sum([int(dig) for dig in str(num)]))
>> sum_digits(1982)
2
Or a simpler version for the case your number is a year:
def sum_digits(num):
return sum([int(dig) for dig in str(num)])
Just call the function twice
>> sum_digits(sum_digits(1982))
2
Try adding some debug statements to inspect values as your program runs.
num = int(input("Enter your birth year: "))
x = num //1000
x1 = (num - x*1000)//100
x2 = (num - x*1000 - x1*100)//10
x3 = num - x*1000 - x1*100 - x2*10
print (x, x1, x2, x3)
x4 = x+x1+x2+x3
print (x4)
num2 = int(x4)
x6 = num2 //10
x7 = (num2 -x6)//10
print (x6, x7)
print("your birth number is" ,x6+x7)
You'll quickly find your problem.
Related
I'm building a optimization tool using Pulp.
It's purpose is to define which SKU to take and which SKU to leave from each warehouse.
I'm having trouble with the following constraint:
"The maximum of different SKUs selected should not exceed 500"
That is to say, that no matter how many units you take, as long as they do not exceed 500 varieties (different SKUs), its all good.
This is what I've got so far
#simplex
df=pd.read_excel(ruta+"actual/202109.xlsx", nrows=20) #leemos la nueva base del mes
# Create variables and model
x = pulp.LpVariable.dicts("x", df.index, lowBound=0)
mod = pulp.LpProblem("Budget", pulp.LpMaximize)
# Objective function
objvals = {idx: (1.0)*(df['costo_unitario'][idx]) for idx in df.index}
mod += sum([x[idx]*objvals[idx] for idx in df.index])
# Lower and upper bounds:
for idx in df.index:
mod += x[idx] <= df['unidades_sobrestock'][idx]
# Budget sum
mod += sum([x[idx] for idx in df.index]) <= max_uni
# Solve model
mod.solve()
# Output solution
for idx in df.index:
print (str(idx) + " " + str(x[idx].value()))
print ('Objective' + " " + str(pulp.value(mod.objective)))
In the same dataframe, I have a column with the SKU of each particular row df['SKU']
I'm imagining that the constraint should look something like:
for idx in df.index:
mod += df['SKU'].count(distinct) <= 500
but that doesn't seem to work.
Thanks!
You will need a binary variable y[i] to indicate if a SKU is used. In math-like notation:
x[i] ≤ maxx[i]*y[i] (y[i] = 0 ==> x[i] = 0)
sum(i, y[i]) ≤ maxy (limit number of different SKUs)
y[i] ∈ {0,1} (binary variable)
where
maxx[i] = upperbound on x[i]
maxy = limit on number of different SKUs
I am trying to compute a series, and I am running into an issue that I don't know why is occurring.
"RuntimeWarning: divide by zero encountered in double_scalars"
When I checked the code, it didn't seem to have any singularities, so I am confused. Here is the code currently(log stands for natural logarithm)(edit: extending code if that helps):
from numpy import pi, log
#Create functions to calculate the sums
def phi(z: int):
k = 0
phi = 0
#Loop through 1000 times to try to approximate the series value as if it went to infinity
while k <= 100:
phi += ((1/(k+1)) - (1/(k+(2*z))))
k += 1
return phi
def psi(z: int):
psi = 0
k = 1
while k <= 101:
psi += ((log(k))/( k**(2*z)))
k += 1
return psi
def sig(z: int):
sig = 0
k = 1
while k <= 101:
sig += ((log(k))**2)/(k^(2*z))
k += 1
return sig
def beta(z: int):
beta = 0
k = 1
while k <= 101:
beta += (1/(((2*z)+k)^2))
k += 1
return beta
#Create the formula to approximate the value. For higher accuracy, either calculate more derivatives of Bernoulli numbers or increase the boundry of k.
def Bern(z :int):
#Define Euler–Mascheroni constant
c = 0.577215664901532860606512
#Begin computations (only approximation)
B = (pi/6) * (phi(1) - c - 2 * log(2 * pi) - 1) - z * ((pi/6) * ((phi(1)- c - (2 * log(2 * pi)) - 1) * (phi(1) - c) + beta(1) - 2 * psi(1)) - 2 * (psi(1) * (phi(1) - c) + sig(1) + 2 * psi(1) * log(2 * pi)))
#output
return B
A = int(input("Choose any value: "))
print("The answer is", Bern(A + 1))
Any help would be much appreciated.
are you sure you need a ^ bitwise exclusive or operator instead of **? I've tried to run your code with input parameter z = 1. And on a second iteration the result of k^(2*z) was equal to 0, so where is from zero division error come from (2^2*1 = 0).
I can generate a binary variable y as follows:
clear
set more off
gen y =.
replace y = rbinomial(1, .5)
How can I generate n variables y_1, y_2, ..., y_n with a correlation of rho?
This is #pjs's solution in Stata for generating pairs of variables:
clear
set obs 100
set seed 12345
generate x = rbinomial(1, 0.7)
generate y = rbinomial(1, 0.7 + 0.2 * (1 - 0.7)) if x == 1
replace y = rbinomial(1, 0.7 * (1 - 0.2)) if x != 1
summarize x y
Variable | Obs Mean Std. Dev. Min Max
-------------+---------------------------------------------------------
x | 100 .72 .4512609 0 1
y | 100 .67 .4725816 0 1
correlate x y
(obs=100)
| x y
-------------+------------------
x | 1.0000
y | 0.1781 1.0000
And a simulation:
set seed 12345
tempname sim1
tempfile mcresults
postfile `sim1' mu_x mu_y rho using `mcresults', replace
forvalues i = 1 / 100000 {
quietly {
clear
set obs 100
generate x = rbinomial(1, 0.7)
generate y = rbinomial(1, 0.7 + 0.2 * (1 - 0.7)) if x == 1
replace y = rbinomial(1, 0.7 * (1 - 0.2)) if x != 1
summarize x, meanonly
scalar mean_x = r(mean)
summarize y, meanonly
scalar mean_y = r(mean)
corr x y
scalar rho = r(rho)
post `sim1' (mean_x) (mean_y) (rho)
}
}
postclose `sim1'
use `mcresults', clear
summarize *
Variable | Obs Mean Std. Dev. Min Max
-------------+---------------------------------------------------------
mu_x | 100,000 .7000379 .0459078 .47 .89
mu_y | 100,000 .6999094 .0456385 .49 .88
rho | 100,000 .1993097 .1042207 -.2578483 .6294388
Note that in this example I use p = 0.7 and rho = 0.2 instead.
This is #pjs's solution in Stata for generating a time-series:
clear
set seed 12345
set obs 1
local p = 0.7
local rho = 0.5
generate y = runiform()
if y <= `p' replace y = 1
else replace y = 0
forvalues i = 1 / 99999 {
set obs `= _N + 1'
local rnd = runiform()
if y[`i'] == 1 {
if `rnd' <= `p' + `rho' * (1 - `p') replace y = 1 in `= `i' + 1'
else replace y = 0 in `= `i' + 1'
}
else {
if `rnd' <= `p' * (1 - `rho') replace y = 1 in `= `i' + 1'
else replace y = 0 in `= `i' + 1'
}
}
Results:
summarize y
Variable | Obs Mean Std. Dev. Min Max
-------------+---------------------------------------------------------
y | 100,000 .70078 .4579186 0 1
generate id = _n
tsset id
corrgram y, lags(5)
-1 0 1 -1 0 1
LAG AC PAC Q Prob>Q [Autocorrelation] [Partial Autocor]
-------------------------------------------------------------------------------
1 0.5036 0.5036 25366 0.0000 |---- |----
2 0.2567 0.0041 31955 0.0000 |-- |
3 0.1273 -0.0047 33576 0.0000 |- |
4 0.0572 -0.0080 33903 0.0000 | |
5 0.0277 0.0032 33980 0.0000 | |
Correlation is a pairwise measure, so I'm assuming that when you talk about binary (Bernoulli) values Y1,...,Yn having a correlation of rho you're viewing them as a time series Yi: i = 1,...,n, of Bernoulli values having a common mean p, variance p*(1-p), and a lag 1 correlation of rho.
I was able to work it out using the definition of correlation and conditional probability. Given it was a bunch of tedious algebra and stackoverflow doesn't do math gracefully, I'm jumping straight to the result, expressed in pseudocode:
if Y[i] == 1:
generate Y[i+1] as Bernoulli(p + rho * (1 - p))
else:
generate Y[i+1] as Bernoulli(p * (1 - rho))
As a sanity check you can see that if rho = 0 it just generates Bernoulli(p)'s, regardless of the prior value. As you already noted in your question, Bernoulli RVs are binomials with n = 1.
This works for all 0 <= rho, p <= 1. For negative correlations, there are constraints on the relative magnitudes of p and rho so that the parameters of the Bernoullis are always between 0 and 1.
You can analytically check the conditional probabilities to confirm correctness. I don't use Stata, but I tested this pretty thoroughly in the JMP statistical software and it works like a charm.
IMPLEMENTATION (Python)
import random
def Bernoulli(p):
return 1 if random.random() <= p else 0 # yields 1 w/ prob p, 0 otherwise
N = 100000
p = 0.7
rho = 0.5
last_y = Bernoulli(p)
for _ in range(N):
if last_y == 1:
last_y = Bernoulli(p + rho * (1 - p))
else:
last_y = Bernoulli(p * (1 - rho))
print(last_y)
I ran this and redirected the results to a file, then imported the file into JMP. Analyzing it as a time series produced:
The sample mean was 0.69834, with a standard deviation of 0.4589785 [upper right of the figure]. The lag-1 estimates for autocorrelation and partial correlation are 0.5011 [bottom left and right, respectively]. These estimated values are all excellent matches to a Bernoulli(0.7) with rho = 0.5, as specified in the demo program.
If the goal is instead to produce (X,Y) pairs with the specified correlation, revise the loop to:
for _ in range(N):
x = Bernoulli(p)
if x == 1:
y = Bernoulli(p + rho * (1 - p))
else:
y = Bernoulli(p * (1 - rho))
print(x, y)
I am stuck with a problem in Integer Programming constraint using PULP in python. I have 2 variables x1, x2 and a constant y. How do i write a constraint on x1 = min(x2 ,y1).
I have written below two condition:
x1 < y1;
x1 < x2
But it is giving me x1 = 0 for my problem.
It should take one of the values from x2 and y1
Thanks in advance. Will really appreciate your help.
Code used:
*import pandas as pd
from pulp import *
data = pd.read_csv("Test.csv")
limit = LpVariable("limit",0, 1000, cat='Integer')
sales = LpVariable.dicts("Sales", (i for i in data.index), lowBound=0, cat="Integer")
####### Defining the Problem
prob = pulp.LpProblem("Profit", pulp.LpMaximize)
prob += pulp.lpSum((1-data.loc[i,'Prize']) * sales[i] for i in data.index)
####### Constraints
for idx in data.index:
max_sales = data.loc[idx, 'Sales'] + data.loc[idx, 'Rejec']
prob += sales[idx] <= max_sales
prob += sales[idx] <= limit
###### Getting the output
prob.solve()
for v in prob.variables():
print v.name,v.varValue
print value(prob.objective)
Data Used (try.csv)
enter image description here
I have the following simple problem that I want to solve with NLopt:
using JuMP
using NLopt
"""
min_x = x1 * x4* (x1 + x2 + x3) + x3
s.t.
x1 * x2 * x3 * x4 >= 25
x_1^2 + x_2^2 + x_3^2 + x_4^2 = 40
1 <= x1,x2,x3,x4 <= 5
starting values: vec(x) = (x1 = 1, x2 = 5, x3 = 5, x4 = 1)
"""
tic()
m = Model(solver=NLoptSolver(algorithm=:LD_MMA))
#defVar(m, 1 <= x1 <= 5)
#defVar(m, 1 <= x2 <= 5)
#defVar(m, 1 <= x3 <= 5)
#defVar(m, 1 <= x4 <= 5)
#setNLObjective(m, Min, x1 * x4 * (x1 + x2 + x3) + x3)
#addNLConstraint(m, x1^2 + x2^2 + x3^2 + x4^2 == 40)
#addNLConstraint(m, x1 * x2 * x3 * x4 >= 25)
setValue(x1, 1)
setValue(x2, 5)
setValue(x3, 5)
setValue(x4, 1)
status = solve(m)
println("got ", getObjectiveValue(m), " at ", [getValue(x1),getValue(x2), getValue(x3), getValue(x4)])
toc()
However I get an argument error. Is there any way to make this work with NLopt and if not how this code can change so as to use it with the other free optimizers that can be installed in Julia (maybe Ipopt but not Gurobi)?
Well, I was unable to solve the problem using NLopt, but instead I managed to solve it with Ipopt.
The solution is simple for using Ipopt. Firstly you have to download Ipopt (I used the Windows version for now and I will also try in Linux) from this site and put it in the path (if you put it in the path and go to the command line and type ipopt it must show no error-it will actually show ipopt options). Just go at the very end to find the newest version.
Then I sliglty modified the code that I provided before to account for Ipopt in this way:
using JuMP
using Ipopt
"""
The problem that I want to solve has 4 variables and 6 constraints.
It is the following:
min_x = x1x4(x1+x2+x3) + x3
s.t.
x1*x2*x3*x4 >= 25
x_1^2 + x_2^2 + x_3^2 + x_4^2 = 40
1 <= x1,x2,x3,x4 <= 5
starting values: x0 = (x1 = 1, x2 = 5, x3 = 5, x4 = 1)
"""
tic()
m = Model(solver=IpoptSolver())
#defVar(m, 1 <= x1 <= 5)
#defVar(m, 1 <= x2 <= 5)
#defVar(m, 1 <= x3 <= 5)
#defVar(m, 1 <= x4 <= 5)
#setNLObjective(m, Min, x1 * x4 * (x1 + x2 + x3) + x3)
#addNLConstraint(m, x1^2 + x2^2 + x3^2 + x4^2 == 40)
#addNLConstraint(m, x1 * x2 * x3 * x4 >= 25)
setValue(x1, 1)
setValue(x2, 5)
setValue(x3, 5)
setValue(x4, 1)
status = solve(m)
println("got ", getObjectiveValue(m), " at ", [getValue(x1),getValue(x2),
getValue(x3), getValue(x4)])
toc()
More information about the right name of the solvers etc. can be found here: https://jump.readthedocs.org/en/latest/installation.html#getting-solvers