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.
Related
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.
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
[Working with Python 3.x]
I'm trying to display 2D line equations. I'm assuming the coefficents or constants to be float because it's possible they can be float. However, if they are integers, I'd like to show them as integers.
That is, instead of
x + 3.0y = 13.0
I want to display
x + 3y = 13
However,
x + 3.5y = 13.5
should stay as is.
How do I do this kind of conditional formatting?
Assumming the function for that will only be passed an exact multiplier (without unknown variable), input and output are strings:
def simplifyFloat(str):
f = float(str)
if f % 1 == 0: #if f has some floating point this is going to be false
f = int(f)
return str(f)
And usage:
equation = '2.0x + 3.5y + 2'
x_part, o, y_part, o, const_part = equation.split(' ') # o variables for dumping operators
# [:-1] before string means you get rid of the last letter, which is 'x' and 'y'
print(simplifyFloat(x_part[:-1])) # output '2'
print(simplifyFloat(y_part)[:-1]) # output '3.5'
There might be more efficient ways to do that, but branching with ceil value works correctly:
import math
number1 = 3.0
number2 = 3.5
def integral_formatting(n):
return n if n != math.ceil(n) else math.ceil(n)
>>> integral_formatting(number1)
3
>>> integral_formatting(number2)
3.5
An efficient way I can come up with, is to make a function that returns integer or float, depending on the case. The function can be like
def check(x):
if int(x) == x:
return int(x)
else:
return float(x)
Now, any number can be put in equation as check(1.0) * x + check(13) * y = check(13.5). This will result in 1x + 13y = 13.5. Hope this helps!
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
x = 5
def SsolGom():
k = 1
for i in range( 1 , x+1 ):
k = k * i
print(SsolGom)
=function SsolGom at 0x00F1B660
120 must come out but strange value came out...
SsolGom is a function, SsolGom() is the value returned by this function. It's similar in math: sin is a function, sin(0) is a number.
x = 5
def SsolGom():
k = 1
for i in range( 1 , x+1 ):
k = k * i
return k
print(SsolGom())
# 120
You need to have a correct indentation inside your function, and you need to return a value. SsolGom() would be None otherwise.
Note that x probably shouldn't be a global variable. Otherwise, your function could be replaced by return 120:
def factorial(x):
k = 1
for i in range(x):
k = k * (i + 1)
return k
print(factorial(5))
Finally, here's the easiest way to get factorial in Python:
>>> from math import factorial
>>> factorial(5)
120
You're missing the brackets. It should be:
print(SsolGom())
You are printing the function without the parenthesis. Calling a function with and without parenthesis gives different results in Python. If you do not provide a parenthesis, Python considers it as properties and not a method/function. Hence you got that result
provide a return statement in the function.
Updated Code:
x=5
def SsolGom():
k=1
for i in range( 1 , x+1 ):
k=k*i
return k
print(SsolGom())