I need help with returning the value of expression(expression being the parameter of the function).
This is what i have tried so far. It's just an example with a random equation, my plan would be to understand how to solve it correctly so i could later on tranform it into a function
sum = 0
eq = '2+4-5'
string = ""
for x in eq:
if x in ('+', '-'):
if x == '+':
sum += int(string)
elif x == "-":
sum -= int(string)
string = ""
else:
string += x
sum += int(string)
print(sum)
"1+2" => 3 # input = "1+2" and the output of the function would be 3
"-1+21" => 20
"+1-1" => 0
Look up the eval() function:
>> eq = "2+4-5"
>> eval(eq)
1
As said in the comments eval() evaluate the string passed as Python code which is potentially dangerous.
Try This one:
import re
eq = '+1-1'
ls = [int(i) for i in re.findall('[-+]?[0-9]+', eq)]
res = sum(ls)
print(res)
Related
I need code that have exact function like oct() in Python but without using any other methods and functions.
I wrote this, but I think it's so large and also I don't want use range and len:
def get_oct(x):
next_step = [x]
r_mod = []
while True:
x /= 8
i = int(x)
next_step.append(i)
if int(x / 8) == 0:
break
for m in range(len(next_step)):
next_step[m] %= 8
j = int(next_step[m])
r_mod.append(j)
t_mod = r_mod[::-1]
return "0o" + "".join(str(e) for e in t_mod)
entry = int(input("Enter a number: "))
print(get_oct(entry))
If you want this to work like the built-in oct(), you need to account for zero and negative numbers. A nicer way to deal with this is to use the function divmod() the returns the result of integer division and the remainder. Just keep doing that until the value is zero:
def get_oct(x):
if x == 0: return '0o0'
prefix = '-0o' if x < 0 else '0o'
x = abs(x)
res = ''
while x:
x, rem = divmod(x, 8)
res = str(rem) + res
return (prefix + res)
assert(get_oct(80) == oct(80))
assert(get_oct(1) == oct(1))
assert(get_oct(0) == oct(0))
assert(get_oct(-2) == oct(-2))
assert(get_oct(-201920) == oct(-201920))
assert(get_oct(12345678910) == oct(12345678910))
If all that is needed is to print in octal without oct() function,string formatting could be the easiest option.
num = int(input("Enter a number: "))
print("{:o}".format(num))
Output:
Enter a number: 10
12
This is also possible with string variable
num = int(input("Enter a number: "))
s = "{:o}".format(num)
print(s)
Output:
Enter a number: 10
12
I have string with only + and -, plus increases some variable, minus respectively decreases it. I should check if variable will be less than 0 or greater than N during processing any symbol of input string.
For example I have input:
N = 10
string = "+++++++++---+-+-+"
Output:
True
Input:
N = 3
string = "+-+-+-++-+++--"
Output:
False
Python solution is:
def check(string, N):
accumulator = 0
for ch in string:
if ch == '+':
accumulator += 1
elif ch == '-':
accumulator -= 1
if accumulator < 0 or accumulator > N:
return False
return True
But I need to implement this using ONLY regular expressions, like this:
def check(string, N):
regex = r'^$' # <-- regex is here
return bool(re.match(regex, string))
Any ideas?
value = input("Enter the binary value to convert to a decimal number.")
prod = 0
power = 0
ans = 0
for i in range (int(value)):
prod = ((int(value[*right most digit here*])) * ((2**power)))
ans = prod + ans
prod = 0
power + 1
else:
print (ans)
I am trying to create a binary calculator.
I believe I have the power part of the equation working as it begins with 2 ^ 0, then 2 ^ 1 for the next digit and so on. But I am having trouble getting the first part of the equation, the right most digit of the value inputted.
So let's say, 0101 was inputted. I want 1 * ( 2 ^ 0 ) in the first loop, 0 * ( 2 ^ 1) in the second loop, and so on; right to left. So with how indexing works in Python, how can I reverse index it so [4] is in the first loop, then [3] in the second loop, and so on.
Thanks for help.
However there are better options available, i am assuming you are clearing your basics. Following can be the options:
Note : You should use len(value) instead of int(value) in the loop.
# 1. When starting the loop from 0 (i.e. i=0). you can use ( len(value) - i )th index.'
for i in range (len(value)):
prod = ((int(value[len(value) - i - 1])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
# 2. Python also supports negative indexing, So you may run a loop from -1 to -len(value).
for i in range (-1,-len(value) - 1,-1):
prod = ((int(value[i])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
# 3. You can reverse the whole string in your first step and then loop from 0 to len(value)-1.
value = reversed(value)
for i in range (len(value)):
prod = ((int(value[i])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
But there are some bugs in the code (or may be lack on information). This code works only for unsigned integers. If you want it to work on signed numbers as well, you have to take 2's complement into consideration.
Below is a very simple code that works with signed numbers too (in case needed):
#convert binary string into decimal value. Works on 2's complement.
def binToDecimal(s):
neg = False
if s[0] == '1':
s = twosComp(s)
neg = True
#compute the decimal value
val = reduce(lambda x,y : int(x)*2+1 if y=='1' else int(x)*2,'0'+s)
#negate the value if the first bit is 1
return -val if neg else val
#return the 2's complement string
def twosComp(s):
s = list(s[::-1])
#take 1's complement
s = ['1' if i=='0' else '0' for i in s]
#take 2's complement
for i in range(len(s)):
if s[i] == '0':
#no carry will be generated in this case, so we break it.
s[i] = '1'
break
else:
s[i]='0'
# return 2's complement string
return ''.join(map(str,s))[::-1]
value = input("Enter the binary value to convert to a decimal number.")
power = 0
ans = 0
for i in reversed(value):
prod = int(i) * (2**power)
ans = prod + ans
power += 1
else:
print(ans)
Improved your code while keeping it as close to your code as possible. Your for loop was creating a list of 1 to whatever the value we input, that's not what you should be doing. One way of doing is, treating your input as a string (which basically is a list that can be iterated through) reverse it so you go from right to left, then do your operation on it on each value. You were trying to get the index of the location of the value input right? Why? Python is beautiful where you most likely don't need to directly tell the index of something.
value = input("Enter the binary value to convert to a decimal number.")
prod = 0
power = 0
ans = 0
for i in range(int(len(value))-1):
prod = ((int(value[-1])) * ((2**power)))
ans = prod + ans
prod = 0
power + 1
else:
print (ans)
You were doing the range of the value and not the input len so we use len() to get the length of the string that was inputted. -1 is there because the length of a string can be 3 for input 001 but if indexing 3 would be out of bounds because indexing starts at 0 not 1
Note that in Python a negative index value is accepted. Negative index means starts from the end of the list and count backwards, so I think that was the answer you were looking for.
For example if we have the list my_list=['a','b','c'] and we call my_list[-2] it will return 'b'
You have some mistakes in your code, so replace it with this:
value = input("Enter the binary value to convert to a decimal number: ")
value = int(value) # conversion from string to number
power = 0
ans = 0
while(value > 0):
lastDigit = value % 10 # last digit
value = value // 10 # cutting off last digit (for next iteration)
prod = lastDigit * (2 ** power)
ans = prod + ans
power = power + 1
print (ans)
Last digit is calculated as the remainder after division by 10 (value % 10)
and is cutting of by integer division by 10 (value // 10) - as in first grades of basic school: 27 % 10 = 7 27 // 10 = 2
Simpler way to achieve this with be to mention base as 2 with int(). For example:
>>> num = '110'
>>> int(num, 2)
6
In case you are looking for custom solution, you may create a function as:
def binary_string_to_int(binary_string):
int_num = 0
for i in binary_string:
int_num += int(i)
int_num *= 2
return int_num / 2
Sample run:
>>> binary_string_to_int('111')
7
>>> binary_string_to_int('101')
5
I am trying to make a decimal number ternary in a python function. My idea was to keep dividing until the quotient and remainder were equal, but I can't seem to get that to work. Here's my code:
l = 1
#problem code
def ternary(n):
e = n/3
q = n%3
e= n/3
q= e%3
print q
r = input("What number should I convert?: ")
k = bin(r)
v = hex(r)
i = oct(r)
print k+"(Binary)"
print v+"(Hex)"
print i+"(Octals)"
ternary(r)
l+=1
# Variables:
#l,r,k,v,i
#n,q,e
My idea was to keep dividing until the quotient and remainder were equal, but I can't seem to get that to work.
Yeah, something like that. Essentially, you want to keep dividing by 3, and collect the remainders. The remainders then make up the final number. In Python, you can use divmod to divide and collect the remainder.
def ternary (n):
if n == 0:
return '0'
nums = []
while n:
n, r = divmod(n, 3)
nums.append(str(r))
return ''.join(reversed(nums))
Examples:
>>> ternary(0)
'0'
>>> ternary(1)
'1'
>>> ternary(2)
'2'
>>> ternary(3)
'10'
>>> ternary(12)
'110'
>>> ternary(22)
'211'
You can also use the implementation of NumPy:
https://numpy.org/doc/stable/reference/generated/numpy.base_repr.html?highlight=base_repr#numpy.base_repr
Though, I agree that a function for ternary exclusively is faster.
import numpy as np
number=100 # decimal
ternary=np.base_repr(number,base=3)
print(ternary)
#10201
This can also be done with recursion.
def ternary(n):
e = n//3
q = n%3
if n == 0:
return '0'
elif e == 0:
return str(q)
else:
return ternary(e) + str(q)
More generally, you can convert to any base b (where 2<=b<=10) with the following recursive function.
def baseb(n, b):
e = n//b
q = n%b
if n == 0:
return '0'
elif e == 0:
return str(q)
else:
return baseb(e, b) + str(q)
We can implement decimal to binary conversion for positive integers in Python by using the following algorithm that takes an integer n as input and returns a string of 1's and 0's holding the binary representation of n .
Write a function int_to_bin_string(n) (in int_to_bin_string.py) which takes a non-negative integer n and returns the a string of 1's and 0's.
We are not allowed to use any built in python functions that converts numbers to strings or vice versa.
def int_to_bin_string(n):
if n == 0:
return "0"
s = ''
while n > 0:
if n % 2 == 0:
ch = "0"
else:
ch = "1"
s = s + ch
n = n/2
return s
That's what I have tried. When I try int_to_bin_string(255) I get '1', instead of '11111111'
It works now!
for the second to last line, you need to have
n = n/2
You have a premature return in return s. It needs to be outside your while loop, which is why you are getting only one character. Also it should be n = n/2.
Additionally, look at your first return statement, it returns an integer instead of a string.
You could use a key function of python
bin( value ) # returns a string like '0b110110'
simply get a slice if you only want the numbers...
bin( value )[2:]
This could be an alternative for you... it's almost the same though
def int_to_bin_string(n):
s = ''
while n:
s = ((n & 1) and "1" or "0") + s
n >>= 1
return s or "0"
I hope this does help ;)
I'll bet a nickel, from the symptoms, that this is a Python 3 vs. Python 2 issue. Your code as modified works fine on Python 2.
You can make this code bilingual with a simple modification. Replace the division by 2 with a shift. In place of n = n/2, use n = n>>1. That works on both P2 and P3.
def int_to_bin_string(num):
n = int(num) # added to force int type on entry
if n == 0:
return "0"
s = ''
while n > 0:
if n % 2 == 0:
ch = "0"
else:
ch = "1"
s = s + ch
n = n >> 1 # was n/2
return s
I also added a small filter to coerce the argument to int on entry, with a rename to avoid losing the original argument value. When debugging, I like see the original value--hence the rename. I just do that as reflex; it's not related to your question.