I am not so proficient in python. I had this code in a practice coding. Since it is a golf code problem, i thought of trying python as i have some knowledge about it.
This is my program
Hack sequence of IndiaHacks-2014 if given as below
Hi = 2014*Hi-1 + 69*Hi-2 for (i>2)
Hi = 1 for (i<=2)
Given n, you need to find nth term of Hack sequence
I have used the following code
T = input()
for i in range(T):
N = int(input())
if N <= 2:
print 1
else :
a = [1,1]
j=2
while j < N :
a.append((2014 * a[j-1]) + (69 * a[j-2]))
j++
print a[N-1]
But i get the following error
SyntaxError:
invalid syntax
11, 7, \t\t\tj++\n
Can anyone please tell me what is wrong with this code and why am I getting this error?
Use j += 1 instead of j++. There is no ++ operator in python.
OR in this case simply don't use manually incremented loop variable:
T = input()
# I'm not sure about this part of your code:
# (indentation and the expected value of T)
for i in range(T):
N = int(input())
# To solve this problem you don't have to populate an array,
# you always need only the last two items:
prev2, prev1 = 1, 1
# We could omit this "if" check because the range(N-2) expression
# generates nothing when the input parameter is zero or less,
# that is: when N <= 2.
if N > 2:
# Note: in case of python3 use range(), in case of python2 use xrange()
for _ in range(N-2):
new = (2014 * prev1) + (69 * prev2)
prev2, prev1 = prev1, new
print prev1
To solve this problem you don't need an array but even if you needed an array you could run the j loop variable from 2 to N-1 with for j in range(2, N):. Note that in python you could simply use array[-1] and array[-2] to address the last two items of the array instead of calculating the absolute index (like array[N-1]). Python arrays can be indexed with a negative number relative to the end of the array.
There is no j++ in python. Use j += 1.
Related
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)
I am new to python and I was trying out bubble sort. Not able to find the error.
Little help here.
def bubble(n, list):
for i in range(0, n):
for j in range(0, n - i - 1):
if list[j] > list[j + 1]:
list[j],list[j+1] = list[j + 1],list[j]
def main():
n = input('size')
n = int(n)
list = []
for i in range(0, n):
no = input('no')
list + [no]
bubble(n, list)
print(list)
main()
During execution, it's showing:
line 4, in bubble
if (list[j] > list[j + 1]):
IndexError: list index out of range
But I couldn't find out how. The index always will be
The first problem is that you don't convert the input('no') to int. It is not the cause of the current problem, but would cause problems later.
The second problem is that you use list as a variable name. list is a predefined Python class and you will overwrite it. Choose a different name.
The third problem is that you use list + [no]. That will not add no to list. It would just store the output temporarily and delete it automatically. There are 2 solutions:
1. Using +=
a += b is equal to a = a + b. This is also the case for many arithmetical operators. Just replace + with +=.
2. Using append
append is faster. Use it like somelist.append(somevalue).
This is been killing me. When using the following code to print the Fib number, it gives the right output:
a = 0
n = 1
while n < 55:
print(n)
a,n = n,a+n
but when I change to this:
a = 0
n = 1
while n < 55:
print(n)
a = n
n = a+n
The output is totally different.
I've even run it thru pythontutor.com to watch stepping.
What are I missing.
There is a difference in the way variable values are interpreted and assigned between the two code snippets.
In case of the first snippet, while assigning the value to "n", the new value of a is not used, rather the value of a from the previous iteration is used.
But, in case of the second snippet, the value of "a" is first updated and then used for the second statement.
Let's take an example:
For the first iteration where n is 1,
First Code Snippet: At the end of the iteration, the value of a will be 1 and value of n also will be 1. (For n = a+n, value of a is considered 0)
Second Code Snippet: At the end of the iteration, the value of a will be 1 and value of n will be 2. (For n = a+n, value of a is considered 1)
The key point to be noted about the Python Comma Operator is that, all the expressions to the right of the assignment operator are evaluated first before the assignments are actually made and this causes the difference in output between the two.
Well, the initial assignment
a,n = n,a+n
means
old_a = a
a = n
n = old_a + n # saved a value (old_a) used
Please, notice that n = old_a + n, not a + n == 2 * n
Let's call a_i and n_i the values of a and n at the i-th iteration.
In the first code you are assigning to n_i+1 the value a_i + n_i, instead in the second code you are assignign to n_i+1 the value a_i+n_i+n_i.
This happen because you are assigning a before n in the second code, while this happen simultaneously in the first one. To solve this issue save in a temporary variable the old value of n or a.
Alternatively, with just a bit of math, you can do the following without saving any temporary variable:
a = 0
n = 1
while n < 55:
print(n)
n = a+n
a = n-a
which is equivalent to: a_i+1 = n_i+1 - a_i = a_i + n_i - a_i = n_i.
I couldn't find an answer by searching and I've been working on this for two days and am stumped. I think I am just confused on the math. I am trying to write a function that finds the first n triangular numbers.
def formula(n):
i = 1
while i <= n:
print i, '\t', n * (n + 1)/ 2
i += 1
print
So for example if I type in formula(5) it would look like this:
1 1
2 3
3 6
4 10
5 15
I got how to make a table going from 1 through whatever number I choose n.. but I can't figure out how to make the second part equal the formula I typed in which would be n*(n+1)/2. What is the logic going through this? Everytime I type in formula(5) for example the loop goes from 1-5 but returns the same exact answer in the right hand column all the way down which would be 15. I can't make it to where it would start at 1, 3, 6 etc on the right hand side.
The comment that observed that you are computing n * (n + 1) / 2 instead of i * (i + 1) / 2 is correct. You can also get rid of having to do a multiplication and division at each step by observing that the i-th triangle number is simply the sum of the integers from 1 to i, so at each step you just have to add i to the previous triangle number. Code below:
def formula(n):
ith_sum = 0
for i in xrange(1, n+1):
ith_sum += i
print i, '\t', ith_sum
I had completely forgotten about triangular numbers, thank you for the question! I am glad you now know the correct solution. I was curious if it could be done a different way:
def triangular(number):
return number + triangular(number-1) if number else 0
print triangular(5)
If you fancy a challenge, you could try and work this out. A print statement here and there would help you spot what is happening.
This is a simple solution that worked for me
def print_triangular_numbers(n):
for i in range(n+1):
print(i, int(i * (i + 1)/ 2))
print_triangular_numbers(5)
This is not the answer to this question. So delete it as soon as you read it.
It is the answer for printing
#
##
###
####
#####
######
on the console.
Follwing is the code for it :
var strng="";
for (var i=1; i<7; i++)
{
for (var j=1; j<=i; j++)
{
strng=strng+"#";
}
strng=strng+"\n";
}
console.log(strng);
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