Converting nested for loop to while loop in Python - python

I am a beginner in python and I have used what I know from eclipse to write 4 nested for loops. I would like to condense my loops into a while loop but I am unsure how to do so. Could someone please help me? Here's my code:
import sys
n = int(sys.argv[1])
# step 1 four nested loops
for a in range(1, n + 1):
a3 = a*a*a
if a3 > n:
break
for b in range(a + 1, n + 1):
b3 = b*b*b
if a3 + b3 > n:
break
for c in range(a + 1, n + 1):
c3 = c*c*c
if c3 > a3 + b3:
break
for d in range(c + 1, n + 1):
d3 = d*d*d
if c3 + d3 > a3 + b3:
break
if a3 + b3 == c3 + d3:
print str(a3 + b3), " = ", a, "^3", " + ", b, "^3", " = ", c, "^3", " + ", d, "^3"

Related

Use numerical methods to find the value of 6 variables using 5 equations

There is one combination of b1, b2, b3, r1, r2, r3 which meets the following equations:
b1 = 4 * r1
b2 = 4 * r2
b3 = 4 * r3
b1 = b2 + b3
r1 = r2 + r3
I have been trying to write a piece of python code to find that combination (or maybe there is more than one). The piece of code has to go through various permutations to find the right combination. I was struggling to write the code so hopefully someone can help me out. This is what i started off with:
for b1 in range(9,50):
for b2 in range(9,50):
for b3 in range(5,20):
for r1 in range(5,20):
for r2 in range(5,20):
for r3 in range(5,20):
if b1 == 4 * r1 & b2 == 4 * r2 & b3 == 4 * r3 & b1 == b2 + b3 & r1 == r2 + r3:
print(b1, b2, b3, r1, r2, r3)
Unless I've completely missed what the desired outcome is supposed to be from the equations above, there are countless permutations that produce a true comparison of values for "r1", "r2", "r3", "b1", "b2", and "b3". That is because the equation:
b1 = b2 + b3
is equivalent to:
4 * r1 = 4 * (r2 + r3)
So once you determine what value of "r1" is equal to "r2 + r3", the "b1" equation is going to follow suit.
I built the following proof of principle program to test that out using just eighty-one combinations of values for "r2" and "r3" and solving for "r1" with a check of "b1".
r1 = 0
r2 = 0
r3 = 0
b1 = 0
b2 = 0
b3 = 0
print("Valid combinations of r1/r2/r3")
print("______________________________________________________________")
for r2 in range (1, 10):
for r3 in range (1, 10):
r1 = r2 + r3
b1 = 4 * r1
b2 = 4 * r2
b3 = 4 * r3
if (b1 == (4 * (r2 + r3))):
print("r1:", r1, "r2:", r2, "r3:", r3)
print("r1 = r2 + r3, which is", r1, "=", r2, "+", r3)
print("b1 =", b1, "b2 =", b2, "b3 =", b3)
print("b1 = b2 + b3, which is", b1, "=", b2, "+", b3)
print("- - - - - - - - - - - - -")
That yielded eighty-one instances where all of the parameters are met.
r1: 17 r2: 9 r3: 8
r1 = r2 + r3, which is 17 = 9 + 8
b1 = 68 b2 = 36 b3 = 32
b1 = b2 + b3, which is 68 = 36 + 32
- - - - - - - - - - - - -
r1: 18 r2: 9 r3: 9
r1 = r2 + r3, which is 18 = 9 + 9
b1 = 72 b2 = 36 b3 = 36
b1 = b2 + b3, which is 72 = 36 + 36
- - - - - - - - - - - - -
The exercise almost seems more of a proof that if the first four equations are true, the fifth equation is true.
Hi thank you for your time. I just realized I needed a different set of equations. The problem is about blue and red tiles. A child has a huge amount of blue tiles and red tiles, the number is unknown. He uses all the blue tiles to form a rectangle and the red tiles to form a border around the rectangle of 1 tile thickness, he has 4 times as many blues tiles as red tiles. He then messes us the rectangle and forms 2 smaller (unidentical) rectangles using all of the tiles. Each rectangle follows the same convention of blue rectangle and red border consisting of 1 tile thickness. The question asks to find the number of blue and red tiles for each rectangle (big/medium/small). Algebraically I only see 5 equations which can be formed but 6 unknowns so I have no idea how to solve it algebraically but I realized I can use brute force to get the answer using python. In the end, I slept on it for a few days and tried again just now and got the answer.
This was a question my 14yr cousin got as his math homework, haha. I still couldn't work it out algebraically, I guess his teacher will find the solution. Thank you again for your time and apologies I only later realized the equations needed to be amended.
The below solves the answer.
for w1 in range(10, 100):
for w2 in range(10, 50):
for w3 in range(10, 25):
for l1 in range(5, 15):
for l2 in range(5, 15):
for l3 in range(5, 15):
if (w1 * l1 == (w2 * l2) + (w3 * l3)) and \
(((w1 * l1) / 4) == ((w2 * l2) / 4) + ((w3 * l3) / 4)) and \
(w1 * l1 == (8 * w1) + (8 * l1) + 16) and \
(w2 * l2 == (8 * w2) + (8 * l2) + 16) and \
(w3 * l3 == (8 * w3) + (8 * l3) + 16):
print("blue tiles for big rectangle is", int(w1 * l1))
print("red tiles for big rectangle is", int((w1 * l1) /4))
print("blue tiles for medium rectangle is", int(w2 * l2))
print("red tiles for medium rectangle is", int((w2 * l2) /4))
print("blue tiles for small rectangle is", int(w3 * l3))
print("red tiles for small rectangle is", int((w3 * l3) /4))
else:
None

How to insert an integer at specific index in a file using Jupyter-Notebook/python?

[]
The Image is the perfect display of my problem.
I have a .txt file. containing the alphabet: a b c d e f g h i ...
I want to insert a number with each letter, so the updated file look like this:
a1 b2 c3 d4 e5 f6 and so on.
How can I do this in Python?
Note: Also, how to do the same when the letters are in a column, not a row?
this is another solution based on your modified question.
you can write the output on the file
with open('s.txt') as s:
alphabet = s.readlines()
i = 1
for l in alphabet:
res = l.split()
print(res[0], " ", (res[1] + str(i)))
i = i+1
Output on the console
A a1
B b2
C c3
D d4
E e5
F f6
G g7
H h8
I i9
J j10
Try this:
with open('s.txt') as s:
alphabet = s.read()
lst = alphabet.split()
for x in range( len(lst)):
print(lst[x]+str(x+1)," ", end='')
output:
a1 b2 c3 d4 e5 f6

Python triplet of numbers

I would like to write a program for Pythagorean Triplet. Program for numbers a, b, c return Pythagorean three natural numbers a1, b1, c1 such that a1 >= a, b1 >= b, c1 >= c.
def Triplet(a, b, c):
a1 = a
b1 = b
n = 5
m = 0
while True:
m += 1
while b1 <= (b + n * m):
a1 = a
while a1 <= b1:
#while c1 > c:
c1 = (a1 * a1 + b1 * b1) ** .5
if c1 % 1 == 0:
return a1, b1, int(c1)
a1 += 1
b1 += 1
print(Triplet(3,4,6))
For input: (3, 4, 6), output should be: (6, 8, 10). Where is the error?
The issue is that you've commented out your incorrect check for c1 > c, but not replaced it with anything.
If you just add that condition back before the return, it works:
def Triplet(a,b,c):
a1=a
b1=b
n=5
m=0
while True:
m+=1
while b1<=(b+n*m):
a1=a
while a1<=b1:
c1=(a1*a1+b1*b1)**.5
if c1>=c and c1%1==0:
return a1,b1,int(c1)
a1+=1
b1+=1
print(Triplet(3,4,6))
If you change the condition to if c1%1==0 and c1>=c: then the issue will get fixed.
I ran it locally and i got (6, 8, 10)

Dtype error in function using norm pdf over a pandas dataframe

I am having issues calculating a function, while the function itself is pretty straightforward.
I have the following dataframe:
import pandas as pd
import numpy as np
import math as m
from scipy.stats import norm
dff = pd.DataFrame({'SKU': ['001', '002', '003','004','005'],
'revenue_contribution_in_percentage': [0.2, 0.2, 0.3,0.1,0.2],
'BuyPrice' : [7.78,9.96,38.87,6.91,14.04],
'SellPrice' : [7.9725,12.25,43,7.1,19.6],
'margin' : [0.9725,2.2908,5.8305,0.2764,5.1948],
'Avg_per_week' : [71.95,75.65,105.7,85.95,66.1],
'StockOnHand' : [260,180,260,205,180],
'StockOnOrder': [0,0,0,0,0],
'Supplier' : ['ABC', 'ABC', 'ABC','ABC','ABC'],
'SupplierLeadTime': [12,12,12,12,12],
'cumul_value':[0.20,0.4,0.6,0.8,1],
'class_mention':['A','A','B','D','C'],
'std_week':[21.585,26.4775,21.14,31.802, 26.44],
'review_time' : [5,5,5,5,5],
'holding_cost': [0.35, 0.35, 0.35,0.35,0.35],
'aggregate_order_placement_cost': [1000, 1000,1000,1000,1000],
'periods' : [7,7,7,7,7]})
dff['holding_cost'] = 0.35
dff1 = dff.sort_values(['Supplier'])
df2 = pd.DataFrame(dff1)
df2['forecast_dts'] = 5
df2['sigma_rtlt'] = 0.5
i need passing some of this parameters into the function:
#
a0 = -5.3925569
a1 = 5.6211054
a2 = -3.883683
a3 = 1.0897299
b0 = 1
b1 = -0.72496485
b2 = 0.507326622
b3 = 0.0669136868
b4 = -0.00329129114
z = np.sqrt(np.log(25
/
(norm.pdf((df2['forecast_dts'])*(1-0.98)/df2['sigma_rtlt']) -
((df2['forecast_dts']*(1-0.98)/df2['sigma_rtlt']))* (1-norm.cdf(df2['forecast_dts']*(1-0.98)/df2['sigma_rtlt']))) ^ 2))
num = (a0 + a1 * z + a2 * z ^ 2 + a3 * z ^ 3)
den = (b0 + b1 * z + b2 * z ^ 2 + b3 * z ^ 3 + b4 * z ^ 4)
k = num / den
return k
but then calculating
calc = calc_invUnitNormalLossApprox()*df2['sigma_rtlt']
returns the error:
File "/usr/local/lib/python3.7/site-packages/pandas/core/ops/__init__.py", line 1280, in na_op
dtype=x.dtype, typ=type(y).__name__
TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]
At this point I am not sure what is going on there, especially because i know the formula itself is correct, I am assuming there is something wrong with my use of norm pdf and cdf but I couldnt figure it out.
Any help would be really appreciated.
I think with the ^ operator you are trying to do a bitwise XOR
I think you need to use the ** operator.
This code works
def calc():
a0 = -5.3925569
a1 = 5.6211054
a2 = -3.883683
a3 = 1.0897299
b0 = 1
b1 = -0.72496485
b2 = 0.507326622
b3 = 0.0669136868
b4 = -0.00329129114
z = np.sqrt(np.log(25
/
(norm.pdf((df2['forecast_dts'])*(1-0.98)/df2['sigma_rtlt']) -
((df2['forecast_dts']*(1-0.98)/df2['sigma_rtlt']))* (1-norm.cdf(df2['forecast_dts']*(1-0.98)/df2['sigma_rtlt']))) ** 2))
num = (a0 + a1 * z + a2 * z ** 2 + a3 * z ** 3)
den = (b0 + b1 * z + b2 * z ** 2 + b3 * z ** 3 + b4 * z ** 4)
k = num / den
return k
Not : I have change the ^ operator to **

EOF error python 3?

I keep getting an EOF error in python 3. Here is my code
num = float(input()) #servings
p = float(input()) #people
a2 = float(input())
b2 = float(input())
c2 = float(input())
d2 = float(input())
e2 = float(input())
f2 = float(input())
g2 = float(input())
h2 = float(input())
i2 = float(input())
a1 = a2 / num
b1 = b2 / num
c1 = c2 / num
d1 = d2 / num
e1 = e2 / num
f1 = f2 / num
g1 = g2 / num
h1 = h2 / num
i1 = i2 / num
a = a1 * p
b = b1 * p
c = c1 * p
d = d1 * p
e = e1 * p
f = f1 * p
g = g1 * p
h = h1 * p
i = i1 * p
lis = str(a)+ str(b)+ str(c)+ str(d)+ str(e)+ str(f)+ str(g)+ str(h)+ str(i)
print (lis) #8 14 1 1 6 2 1 2 .5 2
and the error is on line 11. If I delete line 11 and all code that goes with it, it gives me the error on line 10, then 9, then 8, etc.
The code works fine until you give 11 input values since there are 11 input statements. The EOF error occurs when you don't provide sufficient inputs. I assume the comment on the last line is your input and it has only 10 values. I think that's the reason for the EOF error.

Categories