how can I decrease execution time needed for python code? - python

#https://www.codechef.com/problems/GRIDGM
from sys import setrecursionlimit
setrecursionlimit(10**6)
def sol(l,lst):
sum=0
for i in range(l[0],l[2]+1):
for j in range(l[1],l[3]+1):
#print(lst[i-1][j-1],end="")
sum += lst[i-1][j-1]
#print('---')
#print("sol below")
return sum
for _ in range(int(input())):
n,m=map(int, input("enter values of n and m").split())
lst=[]
for _ in range(n):
lst.append(list(map(int,input("enter a row").split())))
#print(lst)
#q=int(input())
#dj=[] #it saves x y and a b
for _ in range(int(input("enter no of queries"))):
#v=list(map(int,input().split()))
#print(v)
#print('sol below')
print(sol(list(map(int,input("enter cordinates").split())),lst))
sample input
1
4 4
9 13 5 2
1 11 7 6
3 7 4 1
6 0 7 10
2
2 1 4 2
2 2 4 4
output
28
53
above code took 5.1 sec to execute.
in this question, I have to find sum of elements within given coordinates a,b and x,y
more information about this problem can be found in the link below.
https://www.codechef.com/problems/GRIDGM

Related

sum of Fibbonaci Sequences?

Trying to add the sum of Fibonacci, using definite loops. It's meant to calculate the summation of Fibonacci number with each number too. Below is the sample for the Fibonacci sequence and its summation, how do i add the sum of the fibonacci eg 1,1,2,3,5,8
Fibonacci Summation
0 0
1 1
1 2
2 4
3 7
5 12
8 20
n = int(input("enter"))
def fibonacciSeries():
a=0
b=1
for i in range (n-2):
x = a+b
a=b
b=x
int(x)
x[i]= x+x[i-1]
#should add the previous sequences
print(x)
fibonacciSeries()
You don't need to keep track of the whole sequence. Plus your Fibonacci implementation doesn't start with 1, 1 but rather 1, 2 so I fixed that.
def fibonacciSeries(n):
a=0
b=1
x=1
series_sum = 0
for i in range (n-2):
series_sum += x
print(f'{x} {series_sum}')
x = a+b
a=b
b=x
n = 10
fibonacciSeries(n)
Output:
1 1
1 2
2 4
3 7
5 12
8 20
13 33
21 54
def fibonacciSeries(n):
sum = 0
a = 0
b = 1
x = 1
sum = 0
for i in range(0,n - 2):
sum += x
print(x,sum)
x = a + b
a = b
b = x
n = int(input("enter : ")) # n = 8
fibonacciSeries(n)
Output:
enter : 8
1 1
1 2
2 4
3 7
5 12
8 20

Matrix Rotation in Python

In this Program I need to rotate the matrix by one element in clockwise direction.I had done with the code but I have a problem with removing the newlione in the the last row in the given Matrix. In this Program the user has to give the input. The code is
def rotate(m):
if not len(m):
return
top=0
bottom=len(m)-1
left=0
right=len(m[0])-1
while(left<right and top < bottom):
prev=m[top+1][left]
for i in range(left,right+1):
curr=m[top][i]
m[top][i]=prev
prev=curr
top+=1
for i in range(top,bottom+1):
curr=m[i][right]
m[i][right]=prev
prev=curr
right-=1
for i in range(right,left-1,-1):
curr=m[bottom][i]
m[bottom][i]=prev
prev=curr
bottom-=1
for i in range(bottom,top-1,-1):
curr=m[i][left]
m[i][left]=prev
prev=curr
left+=1
return m
def printMatrix(m):
for row in m:
print(' '.join(str(n) for n in row))
n = int(input())
m = []
for i in range(1,n+1):
l = list(map(int, input ().split ()))
m.append(l)
marix=rotate(m)
printMatrix(m)
The Test Case is given Below
Input
4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Expected Output:
5 1 2 3\n
9 10 6 4\n
13 11 7 8\n
14 15 16 12
Actual Output Which i get:
5 1 2 3\n
9 10 6 4\n
13 11 7 8\n
14 15 16 12\n
This is just an issue with your printMatrix() function, print() by defaults adds a newline. You could replace it with below to eliminate the last newline (though I'm not sure why this is so critical):
def printMatrix(m):
print('\n'.join(' '.join(str(n) for n in row) for row in m), end='')

Print a number table in a simple format

I am stuck trying to print out a table in Python which would look like this (first number stands for amount of numbers, second for amount of columns):
>>> print_table(13,4)
0 1 2 3
4 5 6 7
8 9 10 11
12 13
Does anyone know a way to achieve this?
This is slightly more difficult than it sounds initially.
def numbers(n, r):
print('\n'.join(' '.join(map(str, range(r*i, min(r*(i + 1), n + 1)))) for i in range(n//r + 1)))
numbers(13, 4)
#>>> 0 1 2 3
4 5 6 7
8 9 10 11
12 13
def numbers(a,b):
i=0;
c=0;
while i<=a:
print(i,end="") #prevents printing a new line
c+=1
if c>=b:
print("\n") #prints a new line when the number of columns is reached and then reset the current column number
c=0;
I think it should work
def num2(n=10, r=3):
print('\n'.join(' '.join(tuple(map(str, range(n+1)))[i:i+r]) for i in range(0, n+1, r)))
<<<
0 1 2
3 4 5
6 7 8
9 10

write a program that prints a nested loop in Python

I'm trying to print a nested loops that looks like this:
1 2 3 4
5 6 7 8
9 10 11 12
This is what I have so far:
def main11():
for n in range(1,13)
print(n, end=' ')
however, this prints the numbers in one line: 1 2 3 4 5 6 7 8 9 10 11 12
You can do that using string formatting:
for i in range(1,13):
print '{:2}'.format(i),
if i%4==0: print
[OUTPUT]
1 2 3 4
5 6 7 8
9 10 11 12
Modulus Operator (%)
for n in range(1,13):
print(n, end=' ')
if n%4 == 0:
print
for offset in range(3):
for i in range(1,5):
n = offset*4 + i
print(n, end=' ')
print()
Output:
1 2 3 4
5 6 7 8
9 10 11 12
Or if you want it nicely formatted the way you have in your post:
for offset in range(3):
for i in range(1,5):
n = offset*4 + i
print("% 2s"%n, end=' ')
print()
Output:
1 2 3 4
5 6 7 8
9 10 11 12
Most of the time when you write a for loop, you should check if this is the right implementation.
From the requirements you have, I would write something like this:
NB_NB_INLINE = 4
MAX_NB = 12
start = 1
while start < MAX_NB:
print( ("{: 3d}" * NB_NB_INLINE).format(*tuple( j+start for j in range(NB_NB_INLINE))) )
start += NB_NB_INLINE

Grouping list of integers in a range into chunks

Given a set or a list (assume its ordered)
myset = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
I want to find out how many numbers appear in a range.
say my range is 10. Then given the list above, I have two sets of 10.
I want the function to return [10,10]
if my range was 15. Then I should get [15,5]
The range will change. Here is what I came up with
myRange = 10
start = 1
current = start
next = current + myRange
count = 0
setTotal = []
for i in myset:
if i >= current and i < next :
count = count + 1
print str(i)+" in "+str(len(setTotal)+1)
else:
current = current + myRange
next = myRange + current
if next >= myset[-1]:
next = myset[-1]
setTotal.append(count)
count = 0
print setTotal
Output
1 in 1
2 in 1
3 in 1
4 in 1
5 in 1
6 in 1
7 in 1
8 in 1
9 in 1
10 in 1
12 in 2
13 in 2
14 in 2
15 in 2
16 in 2
17 in 2
18 in 2
19 in 2
[10, 8]
notice 11 and 20 where skipped. I also played around with the condition and got wired results.
EDIT: Range defines a range that every value in the range should be counted into one chuck.
think of a range as from current value to currentvalue+range as one chunk.
EDIT:
Wanted output:
1 in 1
2 in 1
3 in 1
4 in 1
5 in 1
6 in 1
7 in 1
8 in 1
9 in 1
10 in 1
11 in 2
12 in 2
13 in 2
14 in 2
15 in 2
16 in 2
17 in 2
18 in 2
19 in 2
[10, 10]
With the right key function, thegroupbymethod in the itertoolsmodule makes doing this fairly simple:
from itertools import groupby
def ranger(values, range_size):
def keyfunc(n):
key = n/(range_size+1) + 1
print '{} in {}'.format(n, key)
return key
return [len(list(g)) for k, g in groupby(values, key=keyfunc)]
myset = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print ranger(myset, 10)
print ranger(myset, 15)
You want to use simple division and the remainder; the divmod() function gives you both:
def chunks(lst, size):
count, remainder = divmod(len(lst), size)
return [size] * count + ([remainder] if remainder else [])
To create your desired output, then use the output of chunks():
lst = range(1, 21)
size = 10
start = 0
for count, chunk in enumerate(chunks(lst, size), 1):
for i in lst[start:start + chunk]:
print '{} in {}'.format(i, count)
start += chunk
count is the number of the current chunk (starting at 1; python uses 0-based indexing normally).
This prints:
1 in 1
2 in 1
3 in 1
4 in 1
5 in 1
6 in 1
7 in 1
8 in 1
9 in 1
10 in 1
11 in 2
12 in 2
13 in 2
14 in 2
15 in 2
16 in 2
17 in 2
18 in 2
19 in 2
20 in 2
If you don't care about what numbers are in a given chunk, you can calculate the size easily:
def chunk_sizes(lst, size):
complete = len(lst) // size # Number of `size`-sized chunks
partial = len(lst) % size # Last chunk
if partial: # Sometimes the last chunk is empty
return [size] * complete + [partial]
else:
return [size] * complete

Categories

Resources