Trouble with variables (Python) - python-3.x

I'm a newbie with programming and I'm in trouble with this code:
def supercalcx(a, b):
n = a
while a <= b:
n = n * a
a = a + 1
print(n)
The IDE give me the error: "TypeError: can't multiply sequence by non-int of type 'str'", but I'm sure the inputs are ints or floats, can anyone explain me the problem. Thanks !

This function works:
>>> def supercalcx(a, b):
... n = a
... while a <= b:
... n = n * a
... a = a + 1
... print(n)
...
>>> supercalcx(2, 4)
48

Your function does not convert between data types. A very crude method of this is to do the following below:
def supercalcx(a,b):
n = int(a)
a = int(a)
b = int(b)
while a <= b:
n = n * a
a = a + 1
print(n)
A couple of suggestions to improve your code:
A function should rarely have the print() function inside of it; instead, use the return keyword. You can change a = a + 1 to a += 1 and n = n * a to n *= a. You can also introduce try and except which will attempt to perform whatever is tabbed under try and if something throws an error specified by the except block, it will then perform whatever is tabbed under except. A somewhat improved version is below:
def supercalcx(a, b):
try:
n = int(a)
a = int(a)
b = int(b)
except ValueError:
return "Unable to convert to integers!"
while a <= b:
n *= a
a += 1
return n
print(supercalcx("1", 2))
print(supercalcx(1, 2))

Related

I want to return the sum of all indexes in n via recursion. How do I do this?

def final_sum(n):
n = str(n)
if int(n) == 0:
return 0
else:
x = int(n[0])
return x + int(final_sum(n[1:]))
print(final_sum(123))
For example, if my n is 123, I should be getting 6. But I am having an error in this code. Can anyone help? I have to use recursive function. So tell me what's wrong with the code.
in return x + int(final_sum(n[1:])), n[1:] is str type
in the beginning of the function, with n = str(n), you assume the input is an int
Besides, you did not consider the case that n[1:] can be empty in return x + int(final_sum(n[1:])).
Here is an anwser based on your code
def final_sum(n):
if n == 0:
return 0
n = str(n)
x = int(n[0])
if len(n)==1:
return x
else:
return x + final_sum(int(n[1:]))
Here is another version using % operation
def final_sum(n):
if n < 10:
return n
return n % 10 + final_sum(n // 10)
First of all, at the beggining I would do this instead of casting back and forth:
def final_sum(n):
if n<10:
return n
You see, the problem is, in the last recursive iteration, you are passing this to the function:
final_sum("")
When you should be passing an int. I think this is happening because your last cast is backwards and you never check how many digits the number has. So the code should look like this:
def final_sum(n):
if n<10:
return n
n = str(n)
x = int(n[0])
return x + final_sum(int(n[1:]))
print(final_sum(123))

How to check if this input is a negative number

I'm new to python and want to make a program that generates Pi with the given decimal numbers. Problem is that I don't know how to check if the user has inputted a positive number.
This is the function that generates Pi (I don't know for sure how it works)
def PiBerekening(limiet):
q = 1
r = 0
t = 1
k = 1
n = 3
l = 3
decimaal = limiet
teller = 0
while teller != decimaal + 1:
if 4 * q + r - t < n * t:
# yield digit
yield n
# insert period after first digit
if teller == 0:
yield '.'
# end
if decimaal == teller:
print('')
break
teller += 1
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
And this is how I ask the user how many decimals he wants to see
while not verlaatloop:
try:
pi_cijfers = PiBerekening(int(input("With how many decimals would you like to calculate Pi?")))
assert pi_cijfer > 0 # This is one of the things I've tried but I get the "NameError: name 'pi_cijfer' is not defined" error and I don't know what to do to check if the inputted number is negative
except ValueError:
print("This isn't a valid number, try again")
except AssertionError:
print("This number is negative, try again")
else:
verlaatloop = True
This is how I show the calculated Pi
for pi_cijfer in pi_cijfers:
print(pi_cijfer, end='')
You can first validate the input and then pass it to the PiBerekening function. Something like this:
while not verlaatloop:
try:
no_decimals = int(input("With how many decimals would you like to calculate Pi?"))
if no_decimals > 0:
pi_cijfers = PiBerekening(no_decimals)
#assert pi_cijfer > 0 # This is one of the things I've tried but I get the "NameError: name 'pi_cijfer' is not defined" error and I don't know what to do to check if the inputted number is negative
except ValueError:
print("This isn't a valid number, try again")
except AssertionError:
print("This number is negative, try again")
else:
verlaatloop = True

How to write a function using for and if

I'm trying to write a code for calculating the number of factors for an arbitrary integer number but unfortunately when I run that I receive a false answer
I have tried for loop without defining function in this case and I got the result.Contrary to that, when I define a function I can't see the proper result
r = 0
def factor(a):
global r
for i in range(1, a + 1):
if a % i == 0:
r += 1
return r
a = int(input())
factor(a)
for example 18 has 6 factors but I receive just 1.
Use print to check your code. Indentation in Python matters. Also, global is not needed.
def factor(a):
r = 0
for i in range(1, a + 1):
if a % i == 0:
print('i', i)
r += 1
return r
a = int(input())
print(factor(a))
It was an indentation problem: the function should only return after the loop has finished iterating.
r = 0
def factor(a):
global r
for i in range(1, a + 1):
if a % i == 0:
r += 1
return r
a = 18 # int(input())
factor(a)
output:
6

Working out the binomial coefficient in python using memoization

I'm trying to teach myself dynamic programming and was practicing a question from http://www.geeksforgeeks.org/dynamic-programming-set-9-binomial-coefficient/. I first attempted the question in Java and my code gives the correct results. Java code:
static int calculate(int n, int k){
if(k == 0 || k == n)
return 1;
if(dp[n][k] != Integer.MAX_VALUE)
return dp[n][k];
else
dp[n][k] = calculate(n - 1, k -1) + calculate(n-1, k );
return dp[n][k];
}
However, when I tried to implement the same thing in Python, I could not and am getting strange results, e.g. when n is 5 and k is 2 I get 13, not 10. I'm quite new to Python so may be missing something obvious but if anyone could help that would be greatly appreciated. Python code:
dp = [[-1] * 3] * 6
def calculate(n, k):
if n == k or k == 0:
return 1
if dp[n][k] > 0:
return dp[n][k]
else:
dp[n][k] = calculate(n-1, k-1) + calculate(n-1, k)
return dp[n][k]
I think there is no need of this condition if dp[n][k] > 0:.
Try it :
dp = [[-1] * 3] * 6
def calculate(n, k):
if n == k or k == 0:
return 1
dp[n][k] = calculate(n-1, k-1) + calculate(n-1, k)
return dp[n][k]
Link : Working code
Everything in your code is correct except the initialization. This might have happened because you might not be completely aware how lists work.
Look at this statement and lets understand what it does:
dp = [[-1] * 3] * 6
Operator * just replicates copies of whatever provided as list. So all the lists are essentially same and referencing to one list.
To avoid this you must initialize it individually. Something like this:
dp = [[-1 for j in range(100)] for i in range(100)]
So the modified code would become something like this.(Just has change in initialization method.)
dp = [[-1 for j in range(100)] for i in range(100)]
def calculate(n, k):
if n == k or k == 0:
return 1
if dp[n][k] > 0:
return dp[n][k]
else:
dp[n][k] = calculate(n-1, k-1) + calculate(n-1, k)
return dp[n][k]
print(calculate(5,2))
As an advice, normally lists are not used for implementing memoization in python instead other methods are used which you might want to look on your own.

Creating a Fibonacci sequence function in Python 3

I am trying to create a function that prints a list of the first 4 numbers in the Fibonacci sequence, the first 10 numbers in the Fibonacci sequence, and then "the first -4" numbers in the Fibonacci sequence. The "-4" numbers in the Fibonacci sequence should return an empty list because there is no "-4" numbers in the sequence. I need the function to print the 3 lists as an end result in the main() function. Here is my code so far, I'm new to functions so any help would be appreciated.
fn = []
def F(n):
i = 0
a = 0
b = 1
for i in range(0,n):
temp = a
a = b
b = temp + b
fn.append(b)
i = i + 1
return fn
main():
print F(4)
print F(10)
print F(-4)
Your function for generating Fibonacci numbers is correct except the global variable fn = [] should be declared within the function body. Also, as suggested in the comment by #alfasin, a, b = b, a + b is more Pythonic.
def fib_list(n):
a = 0; b = 1; fib_list = []
if n <= 0:
return
for i in range(0, n):
a, b = b, a + b
fib_list.append(b)
return fib_list
The other problems I could find with your code:
* print is not a statement in Python 3.x.x, it is a function instead, i.e. print F(4) should be print(F(4))
* main(): should be changed to if __name__ == '__main__':

Resources