I was trying to make a progam that reads "raiz"(means square root) and writes ""(1/2)**"
Just wanted to have 24 as result, but occurs an error saying that i can't convert "(1/2)**576" into a float/int.
def main(args):
a = input("Qual expressão quer simplificar? \n")
i = 0
x = ""
while i < len(a):
c = a[i]
r = a[i: i + 5]
b = a[i: i + 4]
g = a[i: i + 8]
h = a[i: i + 7]
if g == "raiz de ":
c = "(1/2)**"
i += 7
elif h == "raiz de":
c = "(1/2)**"
i += 6
elif b == "raiz":
c = "(1/2)**"
i += 3
if r == "vezes":
c= "*"
i += 4
i += 1
x += c
z = float(x)
print(z)
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
enter code here
If the question is why are you receiving this error, it is because of the line z = float(x). You are passing in x, which is a string with non-decimal characters. In one case you are trying to convert "(1/2)**" into a float.
float() takes a number or a string, but the string must be digits.
float('(1/2)**')
# ValueError: could not convert string to float: (1/2)**
float('2.5')
# 2.5
float(4/2)
# 2.0
Related
I'm trying to run a for loop within a string, and I get that error.
Here's my code and the error I get:
code:
from cmath import inf
from tkinter import Y
from typing import Counter
def function(x, y):
x = 0
y = 0
s = "LRLRLRGLRGRLGRRRGRGLRG"
n = range(-100,100)
n_R = s.count("R", 0, 10)
n_L = s.count("L", 0, 10)
print(n_R)
print(n_L)
for c in s:
if n_R - n_L == 4 + 4*n:
return y += 1
elif n_R - n_L == 3 + 4*n:
return x -= 1
elif n_R - n_L == 2 + 4*n:
return y -= 1
else n_R - n_L == 1 + 4*n:
return x += 1
return x
return y
Error:
return y += 1
^
SyntaxError: invalid syntax
I have tried y = y + 1, and I get the same error.
Any ideas?
There are a number of errors in the code, but focusing on the error specifically referred to, this would resolve:
for c in s:
if n_R - n_L == 4 + 4*n:
y += 1
return y
The reason why this is the case is because y += 1 is actually a statement. Whereas, the OP needs to increment y before it is returned as a value.
For context, I am trying to find all viable solutions to this question:
here's the code I have so far, but I am having trouble with the part that is supposed to iterate through every possible combination.
x = 1
y = 1
z = 10
a = 10
while x < 10 and y < 10 and z < 100 and a < 100: #iterates through every possible combination
x = x + 1
y = y + 1
z = z + 1
a = a + 1
if x != y: #checks if x and are the same
if a/x == z/y or z/x == a/y: #checks if x and y are proportional to a and z
a = str(a) #converting each int to string
z = str(z)
x = str(x)
y = str(y)
if a.count(x) < 1 and a.count(y) < 1 and z.count(y) <1 and z.count(x) < 1: #checks if any number reapeats
print(x, y, z, a) #prints viable solution```
You have six boxes to fill. Just run through all permutations of 6 members and check the conditions:
import itertools
for a,b,c,d,e,f in itertools.permutations([0,1,2,3,4,5,6,7,8,9],6):
if a == 0 or b == 0 or c == 0 or e == 0:
continue
if (10*c + d) / a == (10*e + f) / b:
print( a, b, c*10+d, e*10+f )
It looks like there are 57 solutions.
I must write a function that computes the logarithm of a number x relative to a base b (rounded down if the answer is not an integer). I wrote this function but it's not working
def myLog(x, b):
result = 1
if b > x :
result -= 1
return result
elif x == b :
return result
else :
result += 1
b *= result
return myLog(x,b)
Why are you multiplying the base by result and changing the base? When you determine that the base fits into the input number, you should be dividing the number by the base. Since the division means the final number is 1 more, you add 1 to the result of the recursive call.
def myLog(x, b):
result = 1
if b > x:
result -= 1
return result
elif x == b:
return result
else:
x /= b
return 1 + myLog(x, b)
Example: myLog(32, 2):
32/2 = 16, add 1 to answer
16/2 = 8, add 1 to answer
...
answer = 5
Some of the code is unnecessary though, and I would further edit it to be this:
def myLog(x, b):
if b > x:
return 0
elif x == b:
return 1
else:
x /= b
return 1 + myLog(x, b)
I am learning python and I meet some troubles.
I want to write the script to reverse a negative integer " -1234 to 4321- " and non-integer " 1.234 to 432.1". please help me.
P.S. cannot use "str()" function
I just only can write the script to reverse positive integer 1234 to 4321
def reverse_int(n):
x = 0
while n > 0:
x *= 10
x += n % 10
n /= 10
return x
print reverse_int(1234)
def reve(x):
x=str(x)
if x[0]=='-':
a=x[::-1]
return f"{x[0]}{a[:-1]}"
else:
return x[::-1]
print(reve("abc"))
print(reve(123))
print(reve(-123))
#output
cba
321
-321
how about using your code, but just concatenate a - when n is negative?
rev_int.py:
def reverse_int(m):
x = 0
n = m
if m < 0 :
n *= -1
while n > 0 :
x *= 10
x += n % 10
n /= 10
if m < 0:
#concatenate a - sign at the end
return `x` + "-"
return x
print reverse_int(1234)
print reverse_int(-1234)
This produces:
$ python rev_int.py
4321
4321-
Using SLICING EASILY DONE IT
def uuu(num):
if num >= 0:
return int(str(num)[::-1])
else:
return int('-{val}'.format(val = str(num)[1:][::-1]))
Below code runs fine on Python-3 and handles positive and negative integer case. Below code takes STDIN and prints the output on STDOUT.
Note: below code handles only the integer case and doesn't handles the
non-integer case.
def reverseNumber(number):
x = 0
#Taking absolute of number for reversion logic
n = abs(number)
rev = 0
#Below logic is to reverse the integer
while(n > 0):
a = n % 10
rev = rev * 10 + a
n = n // 10
#Below case handles negative integer case
if(number < 0):
return (str(rev) + "-")
return (rev)
#Takes STDIN input from the user
number=int(input())
#Calls the reverseNumber function and prints the output to STDOUT
print(reverseNumber(number))
Using str convert method.
num = 123
print(str(num)[::-1])
Use this as a guide and make it work for floating point values as well:
import math
def reverse_int(n):
if abs(n) < 10:
v = chr(abs(n) + ord('0'))
if n < 0: v += '-'
return v
else:
x = abs(n) % 10
if n < 0: return chr(x + ord('0')) + reverse_int(math.ceil(n / 10))
else: return chr(x + ord('0')) + reverse_int(math.floor(n / 10))
print reverse_int(1234)
Why not just do the following?:
def reverse(num):
revNum = ''
for i in `num`:
revNum = i + revNum
return revNum
print reverse(1.12345)
print reverse(-12345)
These would print 54321.1 and 54321-.
I am trying to run a test if the number ends in .0
I am running a program with numbers orders of magnitude apart so I can't estimate to a certain amount of digits. using % doesn't work either because then certain numbers are excluded. All the numbers in this program are floating point numbers so I need a way to check if it ends with .0, not with .00000000000001232 or something it has to end exactly in .0
The problem with the round function is that I am dealing with numbers of several orders of magnitude. I need something that checks if it has only 1 decimal after the . or something that checks if the that decimal is a 0.
code:
from myro import *
from math import *
def main():
z = 3
a = 2
b = 2
x = 3
y = 2 #starts at y = 3
lim = 25
c = (a**x + b**y)**(1.0/z)
resultnum = 0
while z <= lim:
while a <= lim:
while b <= lim:
while x <= lim:
while y <= lim:
y = y + 1
c = (a**x + b**y)**(1.0/z)
if float(int(c) + 1) != round(c, 6):
pass
else:
print str(a) + "^" + str(x) + " + " + str(b) + "^" + str(y) + " = " + str(int(c)+1) + "^" + str(z)
resultnum = resultnum + 1
print c
y = 3
x = x + 1
x = 3
b = b + 1
b = 3
a = a + 1
a = 3
z = z + 1
print z
print "code cycle complete"
print str(resultnum) + " results"
main()
>>> n1 = 2.0
>>> int(n1) == n1 and isinstance(n1, float)
True
>>> n1 = 2
>>> int(n1) == n1 and isinstance(n1, float)
False
>>> n1 = 2.01
>>> int(n1) == n1 and isinstance(n1, float)
False
>>> n1 = 1E1 #works for scientific notation as well
>>> int(n1) == n1 and isinstance(n1, float)
True
Python does this already. Going with what Python gives as a string might be what you want:
In [577]: def dot_zero(number):
.....: return str(number).endswith('.0')
.....:
In [578]: dot_zero(2.0)
Out[578]: True
In [579]: dot_zero(2)
Out[579]: False
In [580]: dot_zero(2.01)
Out[580]: False
EDIT
As pointed out by #jamylak this does not work for large numbers since the scientific notation used by str. Keeping the basic idea of conversion into a string, but also catering for large numbers, we end up with more verbose and admittedly rather ugly solution:
def dot_zero_string(number):
# tested and works with Python 3.3
split = str(number).split('e')
return len(split) == 2 or split[0].endswith('.0')
This is the solution in the answer from #AshwiniChaudhary
def dot_zero_inst(number):
return int(number) == number and isinstance(number, float)
Comparing different cases gives the same result:
numbers = [1, 1.0, 1000, 1000.0, 3e38, 1.5555555555555555555555e12,
1.5555555555555555555555e17, 0, 0.0]
numbers = numbers + [-number for number in numbers]
for number in numbers:
assert dot_zero_inst(number) == dot_zero_string(number)
Just to show another method, you can always split by the '.':
>>> num = 12.023
>>> str(num).split('.')[1] == '0'
False
>>> num = 12.0
>>> str(num).split('.')[1] == '0'
True
Note that this works because you said that all were floating points. This will provide an error num is an int
x = 26.5
b % math.floor(b) == 0
>>> False
x = 26.0
b % math.floor(b) == 0
>>> True
should also do it.