Getting index error in the code in python - python

def fact(n):
fac = 1
while (n>1):
fac = fac*n
n -= 1
return fac
z = 0
t = int(raw_input())
nz = []
for i in range(0,t):
c = 0
n = int(raw_input())
z = fact(n)
z = list(str(z))
for j in range(len(z)-1,1,-1):
if z[j] != '0':
break
else:
c +=1
nz[i].append(c)
for k in range(0,t):
print nz[k]
Hello I am getting
Indexerror : index out of range at " nz[i].append(c)
This program should calculate trailing zeros in the factorial of N.
Can you also please help me optimize my code, so it can run also for large values of N?

nz is empty list. It doesn't have any elements, so nz[i] would always raise IndexError. Perhaps you meant nz.append(c) ie. add c at the end of nz.

This is how does append() work:
list.append(x)
Add an item to the end of the list; equivalent to a[len(a):] = [x].
so you may want to change nz[i].append(c) to nz.append(c), since your i index is already handled by the append function. You're actually assuming you have an i element in your list, which is false, since you are using an empty list
About optimizing, your problem is probably due to your recursion limit. Try import sys; sys.getrecursionlimit() in your python shell, you should see something like 1000 as result.
Swapping for an iterative version of the factorial function could be a start
def fact(n):
r = 1
for x in range (n):
r = r * (x+1)
return r

Related

When I run my code, I keep getting an error saying perhaps I forgot a comma. Where would this be an issue within the code?

n= int(input())
a= list(range(1,"x",n+1)
print(a)
b=1:
for b in a
if num % 2 != 0:
b= b*num
print(b)
This is for my into to python class and this is the question for context.
"Taking an integer value n from the user with input(). Your program will calculate the
product of all odd numbers from 1 through the given n. For example: the user gave
n=20. You python code will calculate the following value:
1 x 3 x 5 x 7 x 9 x 11 x 13 x 15 x 17 x 19
Your program will print out 654729075.0 back to the user.
Please calculate the value for n=23 using your program?"
When I run my code, I keep getting an error saying perhaps I forgot a comma. Where would this be an issue within the code? The r in range keeps getting highlighted.
Noticed a few issues here. First, you don’t need list() in your definition of a. You also don’t need a var named a at all.
Also, the syntax for range is range(start, stop, step). You want to start at 1, stop at n+1 (because range is exclusive), and move forward 2 each time. Therefore, it’s range(1, n+1, 2). The code will look like this:
n = int(input())
b = 1
for num in range(1, n+1, 2):
b *= num
print(b)
try this: You are adding unnecessary "x" in code range should (start, end, [Step])
n= int(input())
a= list( range(1,n+1) )
print(a)
ans=1
for i in range(len(a)):
if a[i] % 2 != 0:
ans*=a[i]
else:
continue
print(float(ans)
Read:
Try to go through built in functions
https://docs.python.org/3/library/functions.html
Range- https://docs.python.org/3/library/functions.html#func-range
List - https://docs.python.org/3/library/functions.html#func-list
The code has several flaws. The expert comments are already indicating that. here is one possible version of executable code that can do what you want.
n= int(input())
a=list(range(1,n+1,2))
print(a)
b = 1
for num in a:
b *= num
print(b)

Euler method for two dimension system

I am absolutely a beginner in programming. and trying to write an algorithm of the Euler method for interaction two systems. When I run the code I got this Error message. I will appreciate it if you help me. Thank you.
IndexError: list assignment index out of range
def NmDef(U1, V1, U2, V2):
Nm = math.sqrt((U1-V1)**2+(U2-V2)**2) #sqrt
return Nm
NmDef_value = []
for i in range(n):
i +=1
L = NmDef(U[i], V[i], U[i-1], V[i-1])
print(i, L)
NmDef_value.append(L)
I can see that you have many errors in the for loops.
First in this for loop you have:
NmDef_value = []
for i in range(n):
i +=1
L = NmDef(U[i], V[i], U[i-1], V[i-1])
print(i, L)
NmDef_value.append(L)
In this code the foor loop is incrementing the i value by 1 on each step. In you case it is incrementing it by 1 and you are also incrementing it by 1 so on each iteration you are incrementing i by 2. When you will arrive at the last element of the list you will have i = n and you can only take the element of a list with the value n-1 or else you will get index out of range. You can fix it like that:
NmDef_value = []
for i in range(1,n):
L = NmDef(U[i], V[i], U[i-1], V[i-1])
print(i, L)
NmDef_value.append(L)
For the second for loop:
for i in range (n):
U[i]=U[i-1]+dt*(Fa[i]+Fr[i])
V[i]=V[i-1]-dt*(Fa[i]+Fr[i])
for i in range (n):
print(U[i], V[i])
In this one for i = 0 you are trying to access U[i-1] so it is U[-1] and it will be out of range too. You can add a can start the for loop with 1 like that: for i in range(1,n)

Python code for multiplying adjacent digits of a big number and finding maximum possible product, not giving desired result

Here is a Python code for finding maximum product we can get from 13 adjacent digits of a number. There is no error message, but this program is not giving the desired output. I am getting(in repl.it) 1 everytime, though it is clear that the answer is not 1. I am new to programming.
My attempt
I have converted the number into an string and stored it into a array to get element by element. The outer for loop traversing over all the numbers(last time when i have value len(n)-12, i+j will reach the last entry of the array. (Though the array stores the number in a reverse order, I haven't reversed it because, we don't need to).
n = "123899778978978787888787778788767677667"
arr = []
for i in range(len(n)):
arr.append(int(n)%10)
n = str(int(n)//10)
mul = 1
max_mult = 1
for i in range(len(n)-12):
for j in range(13):
mul = mul * int(arr[i+j])
if(max_mult<mul):
max_mult = mul
print(max_mult)
Can anyone tell me where I am going wrong? Any help will be appreciated.
Your logic can be simplified somewhat using zip:
n_list = list(map(int, list(n)))
res = max(i * j for i, j in zip(n_list, n_list[1:])) # 81
If you insist on using a for loop:
n_list = list(map(int, list(n)))
max_mult = 0
for i, j in zip(n_list, n_list[1:]):
mult = i * j
if mult > max_mult:
max_mult = mult
print(max_mult) # 81
Note you can modify your existing range-based iteration, but this is not considered Pythonic:
for i in range(len(n_list) - 1):
mult = n_list[i] * n_list[i+1]
if mult > max_mult:
max_mult = mult

Python: Editing list while iterating over it

There are some related questions on Stack but I wanted to be as clear as possible. I am using Python 3
If I have a list, N, and I use the following code:
N = [1,2,3,4,6,7,8]
for x in N:
N[x] = N[x] * -1
return N
I am getting a Index out of range error. I understand you shouldn't be adding and deleting elements while iterating over a list, but I wanted a clear definition of why the above example won't work.To me, it seems like there shouldn't be a problem. In the first iteration, x should evaluate to 1. So if I want to edit N[1], I don't see why I wouldn't be able to.
As a side note, I know enumerate() is the proper way to do it.
Use enumerate
Ex:
N = [1,2,3,4,6,7,8]
for x, value in enumerate(N):
N[x] = value * -1
print(N)
or a list comprehension.
Ex:
N = [x * -1 for x in N]
In for x in N:, x takes on each value in N, then you use it like an index. Lists in Python are 0-indexed, so you get an Index out of range error when you reach the end of the list and try to access N[8], which doesn't exist. You can use for x in range(len(N)): instead.
The problem here is actually a little different: you're treating members of the list as if they were indices of the list. Since N[8] doesn't exist, that's where your error is coming from. I think what you meant to do was:
N = [1,2,3,4,6,7,8]
for x in range(len(N)):
N[x] = N[x] * -1
return N
In the first iteration, x=1 which means N[1] equals 2 and so your new N[1] becomes 2 * -1 = -2. Now when x is 8 since you are using for x in N, your code tries to access N[8] but since the length of N is 8, the indexing starts from 0 and goes up to 7. Hence there is no index 8 and hence you get an error Index out of range error
Use good ol' lambda's or a specific callable in list comprehension:
lambda:
N = [1,2,3,4,6,7,8]
M = [(lambda x:-x)(element) for element in N]
print(M)
callable/function:
def negate(x):
return -x
N = [1,2,3,4,6,7,8]
M = [negate(element) for element in N]
print(M)
In your code here -
N = [1,2,3,4,6,7,8]
for x in N:
# x will be 1, 2, 3, 4
And the way you are accessing is -
N[x]
But indices run from 0 to n-1, where n-1 is the last element. Also, in your list, you are missing a 5 so indices will change badly. If you had
N = [1,2,3,4,5,6,7,8]
your code would have worked fine. But since that's not the case, you'd have to use range like -
for i in range(len(N)):
N[i] = N[i] * -1
You are enumerating in a wrong way
N = [1,2,3,4,6,7,8]
for i, x in enumerate(N):
N[i] = N[i] * -1
return N

How to convert a collection of numbers into other base

Again firstly I am sorry because keep asking the same question.I am new to python programming. I am now trying to build a program which convert every element in a list of numbers of base 10 into its base 4. For example here, say i have numbers from 0 to 20 or more, I want to convert every number starting from 0 to numbers of base 4. The result should be like this
[[0,0],[0,1],...[1,1,0]
for numbers starting from 0 to 20. For the code,here is what I wrote so far
for n in range(21):
def base(n,b):
result = []
while n > 0:
result.insert(0, n % b)
n = n // b
return result
print(base(n, 4))
For the result I got only for number 20 which is
[1,1,0]
Did I missed something here or there is another option to make it work?
Thank you for the answer
The issue is that you are defining the function inside the loop body, and only call it once. The structure you actually need is
<define the function>
for n in range(21):
print(base(n, 4))
The results will print out, but each one on a separate line. To create a list of the results you should replace the two lines of the loop with a single line that prints a list of all results, like
print([base(n, 4) for n in range(21)])
The problem is that you're defining the function inside the loop. What you want to do is define the function first, then construct your desired list:
def base(n,b):
result = []
while n > 0:
result.insert(0, n % b)
n = n // b
return result
print [base(n, 4) for n in range(21)]
(See this article if you're new to list comprehensions.)
If you want all the numbers, then indent your print statement, so that it's part of the loop.
If you want these as strings, then convert the digits to characters and concatenate them.
I've done both here:
def base(n, b):
result = []
while n > 0:
result.insert(0, n % b)
n = n / b
return result
for decimal in range(21):
print(''.join(str(digit) for digit in base(decimal, 4)))
You can manually compute the base of a number by doing something like this:
from math import log
from math import floor
def n_to_base(n, b):
num = n
lead_idx = floor(log(num, b))
b_rep = int(10**lead_idx)
b_rep = str(b_rep)
rep = 0
for i in range(len(b_rep)-1, -1, -1):
coeff = floor(num/(b**i))
rep += int(coeff*(10**i))
num -= int(coeff*(b**i))
return rep

Categories

Resources