Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
For example
(x + y)^4 = x^4 +(4x^3)y + (6x^2)y^2 + + 4xy^3 + y^4
I'm using python 3.3.2 and I don't know where to start, I need a little guidance. I'm not asking for the answer to it, just the general steps to make this program work. I've done a few other programs before, and this is probably pushing the limit on what I can do.
SymPy already do that for you:
>>> import sympy
>>> x, y = sympy.symbols("x y")
>>> formula = (x + y) ** 4
>>> formula
(x + y)**4
>>> formula.expand()
x**4 + 4*x**3*y + 6*x**2*y**2 + 4*x*y**3 + y**4
If you need a visualization as a string with "^", you can do:
>>> str(formula.expand()).replace("**", "^")
'x^4 + 4*x^3*y + 6*x^2*y^2 + 4*x*y^3 + y^4'
The code below can be found on this site.
Usage
python binomialexpansion.py 3
Output
x^3 + 3x^2y + 3xy^2 + y^3
Code
import sys
power = int(eval(sys.argv[1]))
strpower = str(power)
coeffs = []
if power == 0:
print 1
exit()
if (power+1) % 2 == 0:
turningp = (power+1)/2
counter = 1
else:
turningp = (power+2)/2
counter = 2
for i in range(1, power+2):
if i == 1:
sys.stdout.write("x^"+strpower+" + ")
coeffs.append(1)
continue
if i == power+1:
print "y^"+strpower,
coeffs.append(1)
break
if i > turningp:
co = coeffs[turningp-counter]
counter = counter+1
else:
co = ((power-(i-2))*coeffs[i-2])/(i-1)
coeffs.append(co)
sys.stdout.write(str(co))
if power-(i-1) == 1:
sys.stdout.write("x")
else:
sys.stdout.write("x^"+str(power-(i-1)))
if i-1 == 1:
sys.stdout.write("y ")
else:
sys.stdout.write("y^"+str(i-1)+" ")
sys.stdout.write("+ ")
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
def HydrogenCount(Compound):
HydrogenNo = 0
for i in range(0, len(Compound)):
Compound[i] == "H":
print(Compound[i+1])
Temp = Compound[i+1]
Temp = int(Temp)
HydrogenNo = HydrogenNo + Temp
return HydrogenNo
HydrogenNo = HydrogenCount(Compound)
print ("HydrogenCount = ", HydrogenNo)
for an input like CH3CH2CH3 it should output hydrogen count = 8
but instead it outputs hydrogen count = 3 as it stops at the first h
Unindent the return statement. It's currently inside of the for loop and needs to be executed after. Otherwise it will only count the first.
def HydrogenCount(Compound):
HydrogenNo = 0
for i in range(0, len(Compound)):
Compound[i] == "H":
print(Compound[i+1])
Temp = Compound[i+1]
Temp = int(Temp)
HydrogenNo += Temp
return HydrogenNo
What if the H in the molecule has more than 9 atoms, say sugar compound C12H22O11 or glucose C6H12O6?
May I suggest you revamp the code this way:
import re
regex = re.compile('H([0-9]*)')
def HydrogenCount(Compound):
try:
return sum([int(i) for i in regex.findall(Compound)])
except:
return(0)
You may run this as:
print(HydrogenCount("CH3CH2CH3"))
print(HydrogenCount("C6H12O6"))
I still see one more flaw in the question and therefore all answers, which is how about molecules like CH3COOH, where H followed by no number implies 1 atom. So, this is the revised code to handle that too:
import re
regex = re.compile('H([0-9]*)')
def HydrogenCount_v2(Compound):
try:
res = [i if i != '' else '1' for i in regex.findall(Compound)]
return sum([int(i) for i in res])
except:
return(0)
print(HydrogenCount_v2("CH3CH2CH3"))
print(HydrogenCount_v2("C6H12O6"))
print(HydrogenCount_v2("CH3COOH"))
You can refactor your code like this:
def calculate_hydrogen_count(compound):
hydrogen_count = 0
for i in range(0, len(compound) - 1):
if compound[i] == "H":
hydrogen_count += int(compound[i + 1])
return hydrogen_count
compound = "CH3CH2CH3"
hydrogen_count = calculate_hydrogen_count(compound)
print ("HydrogenCount = ", hydrogen_count)
Outputting
8
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I tried running this program that I made but it kept having the message "SyntaxError, EOL while scanning string literal
import random
import math
def RoTMG_HP_Function () :
initial = 0
for x in range (19) :
initial += (random.randint(-5, 5))
return initial
'''print(RoTMG_HP_Function())'''
def Roll_Simulator(x):
x = int(input("enter number of simulations."))
RollsList = []
for i in range (x):
RollsList.append(str(RoTMG_HP_Function()))
'''#Miscellaneous code, just test case, not relevant
for i in range (-95,96):
Listcount = 0
for j in range (200):
if int(Rollslist[j]) == i:
Listcount +=1
if Listcount > 0:
print('The roll of ' + str(i) + ' appears ' + str(Listcount) + ' times. ')''''
LifepotExpenditure = 0
for i in range (-19,20):
Listcount = 0
RollsLower = 0
for j in range (x):
if math.floor(int(RollsList[j]) // 5) == i:
Listcount +=1
elif math.floor(int(RollsList[j]) // 5) < i:
RollsLower += 1
if Listcount > 0:
print('Differential of ' + str(i) + ': ' + str(Listcount) + '. The probability of this is ' + str(float(100*Listcount / x)) + '%. The probability of a worse roll is ' + str(float(100*RollsLower / x)) + '%.')
LifepotExpenditure += i*(Listcount)
AverageLifepotExpenditure = float(19.0) - float(LifepotExpenditure / x)
print('\n' + 'On average, you will spend ' + str(AverageLifepotExpenditure) + ' lifepots to max life.')
print(Roll_Simulator(21))
This line
print('The roll of ' + str(i) + ' appears ' + str(Listcount) + ' times. ')''''
Has one extra comma in the end, just remove it
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Today, i have trying to resolve a small star pyramid :
Input:
5 1
Output:
*
**
***
****
Code:
x = 1
y = 0
m, e = map(int, raw_input().split())
while x < m:
print "\n" * y, "*" * e
m -= 1
e += 1
I did that but there is a better solution?? Thanks =)
I think this can be solved more easily:
stop, first = map(int, raw_input().split())
for i in range(stop - 1):
print '*' * (i + first)
just for fun >:)
class c:
def __init__(s,m,e):
s.e , s.m = sorted([e, m])
s.r = 42
def __iter__(s):
return s
def next(s):
if s.m < s.e:
t = "".join(chr(s.r) for _ in range(s.m))
s.m += 1
return t
else:
raise StopIteration
print "\n".join(c(*map(int,raw_input().split())))
n = int(raw_input())
for i in range(n): print "*"*i
This appears to do what your program intends to do, however I can't quite tell because of the issues I raised in my comment above.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Can anyone tell me why this has a syntax error? I've run this exact code before and it worked perfectly. The line in strong text is where Python tells me the syntax error is. Thanks, everyone!
import random
count = 0
while count < 10:
attackerLV = 20
attackerST = 20
attackerSK = 20
baseAtkPwr = 20
attackPWR = ((random.randint(85,100) * (baseAtkPwr + attackerLV + attackerST + attackerSK)) // 100
**defenderLV = 20**
defenderCON = 20
defenderSKa = 20
baseDefPwr = 20
defensePWR = (((random.randint(85,100)) * (baseDefPwr + defenderLV + defenderCON + defenderSKa)) // 4) // 100
damage = attackPWR - defensePWR
if damage <= 1:
damage = 1
print(str(attackPWR))
print(str(defensePWR))
print(str(damage))
print()
count = count + 1
You missed a parenthesis here:
attackPWR = ((random.randint(85,100) * (baseAtkPwr + attackerLV + attackerST + attackerSK)) // 100
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
How can I print the full float result of a simple operation in python? My code does:
if( int(array_Y[counter2]) == int(round(float(elem[0])))):
if(int(round(float(elem[0]))) == 0):
negatiu_verdader += 1
if(int(round(float(elem[0]))) == 1):
positiu_verdader += 1
counter = counter + 1
counter2 = counter2 + 1
error = float(1.0000- (1.0000 * counter / counter2))
print " ERROR!!!!!!!!!!!!!!!!!!!!!!!! :" + ("{0:.15f}".format(round(error,2)))
But the error is always: 0.420000000000000 or 0.230000000000000 but I would like the error to be: 0.43233213213232.
You are rounding your error down to two decimal places by calling round(error, 2):
>>> round(0.43233213213232, 2)
0.43
Don't do that if you want to show more precision:
>>> format(round(0.43233213213232, 2), '.15f')
'0.430000000000000'
>>> format(0.43233213213232, '.15f')
'0.432332132132320'
You do a lot of redundant work in your code, simplify it down a little:
elem_rounded = int(round(float(elem[0])))
if int(array_Y[counter2]) == elem_rounded:
if not elem_rounded:
negatiu_verdader += 1
elif elem_rounded == 1:
positiu_verdader += 1
counter += 1
counter2 += 1
error = 1.0 - (1.0 * counter / counter2)
print " ERROR!!!!!!!!!!!!!!!!!!!!!!!! :{0:.15f}".format(error)