how to resolve this "inf" problem with python code - python

i have a problem with this python code for inverting a Number
like Nb = 358 ---> inv = 853
but in the end i got 'inf' msg from the prog , and its runs normally in C language
def envers(Nb):
inv = 0
cond = True
while cond:
s = Nb % 10
inv = (inv*10)+ s
Nb = Nb/10
if Nb == 0:
cond = False
return inv
data = int(input("give num"))
res = envers(data)
print(res)

This is likely much easier to do via string manipulation, which has a friendly and simple syntax (which are a major reason to choose to use Python)
>>> int(input("enter a number to reverse: ")[::-1])
enter a number to reverse: 1234
4321
How this works
input() returns a string
strings are iterable and [::-1] is used to reverse it
finally convert to an int
Add error checking to taste (for example to to ensure you really received a number)

Here is a simple implementation for a numerical approach:
def envers(Nb):
out = 0
while Nb>0:
Nb, r = divmod(Nb, 10)
out = 10*out + r
return out
envers(1234)
# 4321
envers(358)
# 853
envers(1020)
# 201
Without divmod:
def envers(Nb):
out = 0
while Nb>0:
r = Nb % 10
Nb //= 10
out = 10*out + r
return out

When you set
Nb = Nb / 10
Nb becomes a float (say 1 -> 0.1) and will be able to keep being divided until it reaches a certain limit.
By that point, your inv value will reach python's limits and become 'inf'.
Replacing this line with
Nb = Nb // 10
using Python's builtin integer division will fix the issue.

Related

Function returns the same value many times I Python

I need to write a function that will convert the number A to base N. In this case, the number 19 is binary. All I have to do is rewrite the resulting number backwards and return from the function.
I looked into debug mode and didn't understood a thing honestly, it's just looping over line 15 because of... reasons I guess.
def translate(a, n=2):
r1 = []
r2 = ()
r3 = ()
b = int(a/n)
c = a%n
if b >= 1:
r1.append(str(c))
r1.append(str(translate(b,n)))
else:
r1.append(str(c))
return r1
print(translate(19,2))
I didn’t manage to come up with much, after all, I’m not a programmer at all, but I need to do this so that I don’t get expelled.
You don't really need a recursive approach for this. Here's a technique that will work for where 2 <= base <= 10 and a >= 0
def translate(a, base=2):
r = ''
while a > 0:
r += str(a % base)
a //= base
return r[::-1] if r else '0'
The problem was that every time you call the function, it would append to the list and also, the list would be initialized every time it was called. Hence using a global variable and instead of appending the returned value in the if block just running the function again worked. Code:
r1 = []
def translate(a, n=2):
global r1
r2 = ()
r3 = ()
b = int(a/n)
c = a%n
if b >= 1:
r1.append(str(c))
# print(r1)
translate(b,n)
# print(r1)
else:
r1.append(str(c))
# return r1
translate(2,2)
print(''.join(r1)[::-1])# Join and reverse

Fibonacci sequence calculator seems correct but can't find similar code online. Is there something wrong?

I made a simple Fibonacci sequence calculator for the first 22 terms:
i=1
n=0
while i<=20000:
i = i + n
n = i - n
print(i)
Looks like the result is correct
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
but I can't seem to find similar code anywhere online. I think that's a big red flag. Can someone tell me what is wrong here? Is this inefficient code?
No, that code is fine. The probable reason you can't find similar code online is that it's unusual to use the subtraction operator in Fibonacci, which is a purely additive function, tn = tn-2 + tn-1.
It works, of course, since addition/subtraction is both commutative and associative, meaning that order and grouping of terms is unimportant:
i = i + n # iNew = iOld + nOld
n = i - n # nNew = (iNew) - nOld
# = (iOld + nOld) - nOld
# = iOld + (nOld - nOld)
# = iOld + (0)
# = iOld
Use of subtraction allows you to bypass needing a third variable, which would be something like this in a lesser language than Python:
nextN = i + n
i = n
n = nextN
In Python, you don't actually need that since you can use tuple assignment such as:
(n, i) = (i, n + i)
With that, everything on the right of the = is evaluated before any assignments to the left.
It's an unusual way to do it, but it's correct. Your lines:
i = i + n
n = i - n
are the same as doing:
new_i = i + n
n = i
i = new_i
or,
i, n = i + n, i
which would be the usual way in Python.

Need to reduce run time on creating a list of numbers based on a formula and a number n

Need a better way to create a list of numbers, so that the run time is less. Or probably figure out a better approach to my problem.
I'm running a code to create a series of numbers based on 2 formulas. Starting from 1, the formulas create the following numbers. The idea is to return the number n from the list that is created at the end. Even tough the formulas create the same number in some cases, only unique values remain, and the list is sorted to match. I use a while loop to create the list, and I believe that reducing the number of repetitions can help with my problem, but I can't figure out a way to effectively reduce it, without ruining the purpose of my code.
def dbl_linear(n):
x = 1
y = 0
z = 0
i = 0
u = []
u.append(x)
while i <= n:
x = (u)[i]
y = 2 * x + 1
u.append(y)
z = 3 * x + 1
u.append(z)
i = i + 1
u.sort()
uFix = set(u)
uFix = list(uFix)
uFix.sort()
return uFix[n]
print(dbl_linear(50))
These are the expected results. Which I get, but it takes too long.
dbl_linear(10), 22)
dbl_linear(20), 57)
dbl_linear(30), 91)
dbl_linear(50), 175)
Your function can be considerably simplified to:
Code:
def dbl_linear(n):
u = [1]
for i in range(n):
x = u[i]
u.extend((2 * x + 1, 3 * x + 1))
return sorted(set(u))[n]
Test Code:
assert dbl_linear(10) == 22
assert dbl_linear(20) == 57
assert dbl_linear(30) == 91
assert dbl_linear(50) == 175

Sympy won't simplify or expand exponential with decimals

i'm trying to simplify a huge expression of powers of n , and one of the results of sympy throws a (n+1)^1.0 , i noticed that
f=n*((n+1)**1.0)
sympy.expand(f)
doesn't work it stays the same instead of giving n^2+n, so i was wondering if there's any way to perform something like this
Sympy will expand your expression as expected when the power is an integer number. If the power is stored as a rational or a float, it won't work. Your options are either to rewrite your expression using integers, or write some code that will automatically check if a float stores an integer number (up to numerical precision error) and act accordingly.
Here's a starting point for that:
def rewrite_polynomial(p):
args_list = []
if not p.is_Mul:
return None
for m in p.args:
if not m.is_Pow:
args_list.append(m)
else:
pow_val = m.args[1]
if pow_val.is_Float:
pow_val_int = int(pow_val)
if pow_val.epsilon_eq(pow_val_int):
args_list.append(Pow(m.args[0],Integer(pow_val_int)))
else:
args_list.append(m)
else:
args_list.append(m)
return Mul(*args_list)
n = Symbol('n')
f= n*((n+1)**1.0)
g = rewrite_polynomial(f)
print(g)
Based on Yakovs answer, I made a rewrite rule that makes a DFS traversal of the expression tree and replaces powers to integers in float type.
The code is probably not very efficient, but it worked for my use cases.
Since I'm not a sympy expert, I guess there are some edge cases where this code will break.
Anyways, here you go!
import sympy as s
def recurse_replace(expr,pred,func):
if len(expr.args) == 0:
return expr
else:
new_args = tuple(recurse_replace(a,pred,func) for a in expr.args)
if pred(expr):
return func(expr,new_args)
else:
return type(expr)(*new_args)
def rewrite(expr,new_args):
new_args = list(new_args)
pow_val = new_args[1]
pow_val_int = int(new_args[1])
if pow_val.epsilon_eq(pow_val_int):
new_args[1] = s.Integer(pow_val_int)
new_node = type(expr)(*new_args)
return new_node
def isfloatpow(expr):
out = expr.is_Pow and expr.args[1].is_Float
return out
def clean_exponents(expr):
return recurse_replace(expr,isfloatpow,rewrite)
x=s.symbols('x')
expr = (1+x) ** 1.0
s.pprint(expr)
expr2 = recurse_replace(expr,isfloatpow,rewrite)
s.pprint(expr2)
With output
1.0
(x + 1)
x + 1

Function in Python keeps returning unnecessary floats

I have the following code, which keeps producing errors:
import math
def pen_checker(number):
print(number)
for x in range(1, number):
y = x*(3*x-1)/2
if(number == y):
return True
return False
def pen_calculator(n):
x = n*(3*n-1)/2
return x
def main():
pen1 = 1
pen2 = 1
pen1_val = 0
pen2_val = 0
crt_sum = 0
crt_dif = 0
MAX_CAP = 1000
for pen1 in range(1, MAX_CAP):
pen1_val = pen_calculator(pen1)
for pen2 in range(1, MAX_CAP):
pen2_val = pen_calculator(pen2)
z = pen1_val + pen2_val
if(pen_checker(z)== True and pen_checker(fabs(pen1_val-pen2_val))== True):
print(fabs((pen1_val-pen2_val)))
main()
For some reason, the function pen_calculator() seems to return floats. I know that technically, there are no variable types in Python, but before I call the function, everything is printed as:
1
1
2
And afterwards:
1.0
1.0
2.0
(That was just me trying to find out what's wrong, it is not written in the code)
Normally, this would be no problem, but a for-loop in the function pen_checker requires the "stop" to be an integer, so the code won't work. How do I solve this?
In Python3, if you divide numbers with / it will always give you a float. If you want to divide integers and get an integer, you can use the // operator.

Categories

Resources