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)
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 1 year ago.
Improve this question
Define a function named print_pyramid(number_of_rows) which takes an integer as a parameter and prints a specific pyramid pattern using numbers. Note: you may assume that the number of rows will always be > 1 and < 10 and you must use a nested for loop.
For example:
Pyramid I'm meant to get
Above is my question and what I need to get, but I am unsure on how to complete it below is my code attempt and my result.
This is my code:
def print_pyramid(number_of_rows):
for row in range(number_of_rows):
for column in range(row, number_of_rows):
print("", end="")
for column in range(row+1):
print(row+1, end="")
for column in range(row, number_of_rows-1):
print(" ", end= "")
for column in range(row+1):
print(row+1, end="")
print()
But my code gives me this:
My result/output
Jared's answer is correct and definitely more elegant, but here's another solution anyway. More beginner friendly hopefully easier to understand at a glance.
def pyramid(number_of_rows):
for i in range(1, number_of_rows + 1):
indent = ' ' * (number_of_rows - i)
row = str(i) * (i * 2 - 1)
print(indent + row)
here is a list comprehension that uses a for loop to generate the pyramid pattern
print_pyramid = lambda x : print("\n".join([(" "*(x-i))+(str(i)*(i*2-1))+(" "*(x-i)) for i in range(1,x+1)]))
print_pyramid(9) gives:
1
222
33333
4444444
555555555
66666666666
7777777777777
888888888888888
99999999999999999
You can define a function to print your pyramid in this way
def pyramid(rows: int) -> str:
if rows < 1 or rows > 9:
raise ValueError
pyramid_string = ""
for i in range(1, rows + 1):
pyramid_string += f" " * (rows - i) + f"{i}" * (i * 2 - 1) + "\n"
return pyramid_string
then call the function
print(pyramid(rows=5))
or you can use a variable to store the result of the function
five_rows_pyramid = pyramid(rows=5)
print(five_rows_pyramid)
output
1
222
33333
4444444
555555555
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 7 years ago.
Improve this question
I am trying to extract what's between parenthesis (including parenthesis) recursively.
This is my solution:
def paren(txt):
if txt[1] == ")":
return ''
if txt[0] == "(":
if len(txt) > 2:
return txt[1] + paren(txt[:1] + txt[2:])
return txt[1]
if len(txt) > 2:
return paren(txt[1:])
return ""
But it doesn't include any parenthesis. How can I fix it?
Example:
print paren("h(ello)o")
Output: (ello)
print paren("(hello)")
Output: (hello)
If you have a single pair of parenthesis, I would recommend to go with Halcyon Abraham Ramirez's answer. Otherwise, try this method:
def paren(text):
pstack = 0
start = 0
end = len(text)
for i, c in enumerate(text):
if c == '(':
if pstack == 0:
start = i
pstack += 1
elif c == ')':
pstack -= 1
if pstack == 0:
end = i
break
return text[start:end]
And here is an example:
>>> paren("h(ello)")
'(ello)'
If you do not need the root parenthesis, you can modify the return statement like this:
return text[start+1:end-1]
And again:
>>> paren("h(ello)")
'ello'
use index
word = "hehlllllllll(ooooo)jejejeje"
def extract(word):
return word[word.index("("):word.index(")") + 1]
output:
(ooooo)
taking it further.
if there are multiple parenthesis:
a = "h((el(l))o"
def extract_multiple_parenthesis(word):
closing_parenthesis = word[::-1].index(")")
last_parenthesis_index = (len(word) - closing_parenthesis)
return word[word.index("("):last_parenthesis_index]
output:
((el(l))
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 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("+ ")