By using this equation:
second order Central finite difference coefficients equation
I need to find the coefficients given it for a second order differential. Without using a library that will just do it for me.
Central finite difference coefficients table
I tried using nested for loops to get each number but for some reason it never went to one of my elif sections.I have print values there to check when it does go there and what values the variables are.
I am not getting any error just the incorrect numbers.
"""
Filter for 2nd derivative
"""
n = 2
k = n/2
#k = range(-k,k+1)
#k = list(k)
h = 0.01
for j in range(0, n+1):
Isum = 0
for i in range(0, n+1):
Msum = 0
if i == j:
continue
else:
for m in range(0, n+1):
product = 1
if m == j or m == i:
continue
else:
for l in range(0, n+1):
if l == j or l == i or l == m:
continue
print("j is equal to:", + j)
print("i is equal to:", + l)
print("j - i is equal to:", + j - l)
product = product * ((k-l)/j-l)
product = product * (1/(j - m))
Msum += product
Msum = Msum * (1/(j-i))
Isum += Msum
print(Isum)
Write a function that accepts a number n as an input, and it returns n rows that look like the following pattern. Run your function for n = 19 (the output below is for n=19).
n = int(input("enter number of rows:"))
for i in range(1, n+1):
for j in range(1, n-i+1):
print(end=' ')
for j in range(i,0, -1):
print(''+str(j),end='')
for j in range(2,i+1):
print(str(j)+'_',end='')
print()
Ouput
1
212_
3212_3_
43212_3_4_
543212_3_4_5_
6543212_3_4_5_6_
76543212_3_4_5_6_7_
876543212_3_4_5_6_7_8_
9876543212_3_4_5_6_7_8_9_
109876543212_3_4_5_6_7_8_9_10_
11109876543212_3_4_5_6_7_8_9_10_11_
1211109876543212_3_4_5_6_7_8_9_10_11_12_
131211109876543212_3_4_5_6_7_8_9_10_11_12_13_
14131211109876543212_3_4_5_6_7_8_9_10_11_12_13_14_
1514131211109876543212_3_4_5_6_7_8_9_10_11_12_13_14_15_
161514131211109876543212_3_4_5_6_7_8_9_10_11_12_13_14_15_16_
17161514131211109876543212_3_4_5_6_7_8_9_10_11_12_13_14_15_16_17_
1817161514131211109876543212_3_4_5_6_7_8_9_10_11_12_13_14_15_16_17_18_
191817161514131211109876543212_3_4_5_6_7_8_9_10_11_12_13_14_15_16_17_18_19_
Here's a solution that works well. Since this looks like homework, I'll just give the algorithm.
For each row create a list of row * 2 + 1 size and fill with underscores
Ex: row 0 -> [_], row 1 -> [___], row 2 -> [_____], etc
Find the middle of row and put 1 at the index
Then put 2 and indexes middle-2 and middle + 2
Put 3 and indexes middle-4 and middle+4
Repeat to finish row
Ex: [_________] ->
[____1____] ->
[__2_1_2__] ->
[3_2_1_2_3]
Print spaces - 1st row gets n spaces. 2nd row gets n-1 spaces, etc
Print the list
Repeat for next row
A slight improvement to this would be to just build the last line and then print slices of the last line in a loop. Starting from the middle and widening out.
I see you have accepted the other answer, so I assume you're have your assignment done so I can post my code.
n = 19
last_line = ['_'] * (n * 2 - 1)
middle = len(last_line) // 2
for j in range(0, n, 2):
last_line[middle + j] = str(j // 2 + 1)
last_line[middle - j] = str(j // 2 + 1)
for row in range(n):
print(f"{' ' * (n - row)}{''.join(last_line[middle - row:middle + row + 1])}")
The first 6 lines of the code build the last line of the pyramid. And the last 2 lines prints slices of that.
This will work and will give you a good answer on your assignment.
n = int(input("enter number of rows:"))
r = 0
for i in range(1, int((n+1)/2+1)):
r += 1
for j in range(1, n-i+1):
print(end=' ')
for kk in range(i,0, -1):
if i==1:
print(' '+str(i))
else:
if kk==i:
print(end= ' ')
if kk==1:
print(str(kk), end='')
else:
print(str(kk)+'_', end='')
for ll in range(2,i+1):
if i>1:
print('_'+str(ll), end='')
if i>1:
print()
r += 1
if r > n:
break
for jj in range(1, n-i+1):
print(end=' ')
for k in range(i,0, -1):
if i==1:
print('_'+str(i)+'_', end='')
else:
print('_'+str(k), end='')
for l in range(2,i+1):
if l==2:
print('_'+str(l)+'_',end='')
else:
print(str(l)+'_',end='')
print()
Result:
1
_1_
2_1_2
_2_1_2_
3_2_1_2_3
_3_2_1_2_3_
4_3_2_1_2_3_4
_4_3_2_1_2_3_4_
5_4_3_2_1_2_3_4_5
_5_4_3_2_1_2_3_4_5_
6_5_4_3_2_1_2_3_4_5_6
_6_5_4_3_2_1_2_3_4_5_6_
7_6_5_4_3_2_1_2_3_4_5_6_7
_7_6_5_4_3_2_1_2_3_4_5_6_7_
8_7_6_5_4_3_2_1_2_3_4_5_6_7_8
_8_7_6_5_4_3_2_1_2_3_4_5_6_7_8_
9_8_7_6_5_4_3_2_1_2_3_4_5_6_7_8_9
_9_8_7_6_5_4_3_2_1_2_3_4_5_6_7_8_9_
10_9_8_7_6_5_4_3_2_1_2_3_4_5_6_7_8_9_10
I have the code:
n = int(input())
l = []
for i in range(n):
l.append([])
for j in range(n):
if i==j:
l[i].append("*")
elif i+j==n-1:
l[i].append("*")
else:
l[i].append("")
# if i+j==n-1:
# l[i].append("*")
# else:
# l[i].append("")
for i in l:
print(*i)
Which gives me , diagonals.
As j1-lee said, it's enough to add n = 2 * n - 1 after reading it.
But wanted to show alternative approach if you want to just print result:
string = "{0: >{width_1}}{1: >{width_2}}"
n = int(input())
for i in range(1, n):
print(string.format("*", "*", width_1=i, width_2=2 * n - 2 * i))
print("{0: >{width}}".format("*", width=n))
for i in range(n - 1, 0, -1):
print(string.format("*", "*", width_1=i, width_2=2 * n - 2 * i))
{0: >5}.format("abc") syntax means reserve 5 cells to variable and put there "abc". So to achieve that we increase width_1 and deacrese width_2 in loop, then print middle star and then deacrese width_1 and increase width_2 in loop again.
I'm working on a code challenge in which I have to reduce the execution time as much as possible, the only thing I able to find where I can make an improvement is a nested if-else statement inside a nested for-loop but I'm not sure how it can be improvided.
Here's my code:
mat = [[0] * n] * n
count = 0
for i in range(n,0,-1):
count += 1
for j in range(i,n+1,1):
if i == j:
pass
else:
if getEnemyStatus(mat, i, j):
break
else:
if isEnemy(enemyDict, i, j):
setStatus(mat, i, j)
break
else:
count += 1
value of n can be from 1 to 10^5
You can skip the first if condition by starting with i+1 in range
for j in range(i+1, n+1, 1):
# code here
Second, nested if else condition should be avoided with elif for reading purpose.
Update code should be like:
mat = [[0] * n] * n
count = 0
for i in range(n,0,-1):
count += 1
for j in range(i + 1, n + 1, 1):
if getEnemyStatus(mat, i, j):
break
elif isEnemy(enemyDict, i, j):
setStatus(mat, i, j)
break
else:
count += 1
NOTE: Also if you can set the status setStatus in your isEnemy function then you can get more cleaner code:
mat = [[0] * n] * n
count = 0
for i in range(n,0,-1):
count += 1
for j in range(i + 1, n + 1, 1):
if getEnemyStatus(mat, i, j) or isEnemy(enemyDict, i, j):
break
count += 1
I was solving the Find the min problem on facebook hackercup using python, my code works fine for sample inputs but for large inputs(10^9) it is taking hours to complete.
So, is it possible that the solution of that problem can't be computed within 6 minutes using python? Or may be my approaches are too bad?
Problem statement:
After sending smileys, John decided to play with arrays. Did you know that hackers enjoy playing with arrays? John has a zero-based index array, m, which contains n non-negative integers. However, only the first k values of the array are known to him, and he wants to figure out the rest.
John knows the following: for each index i, where k <= i < n, m[i] is the minimum non-negative integer which is not contained in the previous *k* values of m.
For example, if k = 3, n = 4 and the known values of m are [2, 3, 0], he can figure out that m[3] = 1.
John is very busy making the world more open and connected, as such, he doesn't have time to figure out the rest of the array. It is your task to help him.
Given the first k values of m, calculate the nth value of this array. (i.e. m[n - 1]).
Because the values of n and k can be very large, we use a pseudo-random number generator to calculate the first k values of m. Given positive integers a, b, c and r, the known values of m can be calculated as follows:
m[0] = a
m[i] = (b * m[i - 1] + c) % r, 0 < i < k
Input
The first line contains an integer T (T <= 20), the number of test
cases.
This is followed by T test cases, consisting of 2 lines each.
The first line of each test case contains 2 space separated integers,
n, k (1 <= k <= 10^5, k < n <= 10^9).
The second line of each test case contains 4 space separated integers
a, b, c, r (0 <= a, b, c <= 10^9, 1 <= r <= 10^9).
I tried two approaches but both failed to return results in 6 minutes, Here's my two approaches:
first:
import sys
cases=sys.stdin.readlines()
def func(line1,line2):
n,k=map(int,line1.split())
a,b,c,r =map(int,line2.split())
m=[None]*n #initialize the list
m[0]=a
for i in xrange(1,k): #set the first k values using the formula
m[i]= (b * m[i - 1] + c) % r
#print m
for j in range(0,n-k): #now set the value of m[k], m[k+1],.. upto m[n-1]
temp=set(m[j:k+j]) # create a set from the K values relative to current index
i=-1 #start at 0, lowest +ve integer
while True:
i+=1
if i not in temp: #if that +ve integer is not present in temp
m[k+j]=i
break
return m[-1]
for ind,case in enumerate(xrange(1,len(cases),2)):
ans=func(cases[case],cases[case+1])
print "Case #{0}: {1}".format(ind+1,ans)
Second:
import sys
cases=sys.stdin.readlines()
def func(line1,line2):
n,k=map(int,line1.split())
a,b,c,r =map(int,line2.split())
m=[None]*n #initialize
m[0]=a
for i in xrange(1,k): #same as above
m[i]= (b * m[i - 1] + c) % r
#instead of generating a set in each iteration , I used a
# dictionary this time.
#Now, if the count of an item is 0 then it
#means the item is not present in the previous K items
#and can be added as the min value
temp={}
for x in m[0:k]:
temp[x]=temp.get(x,0)+1
i=-1
while True:
i+=1
if i not in temp:
m[k]=i #set the value of m[k]
break
for j in range(1,n-k): #now set the values of m[k+1] to m[n-1]
i=-1
temp[m[j-1]] -= 1 #decrement it's value, as it is now out of K items
temp[m[k+j-1]]=temp.get(m[k+j-1],0)+1 # new item added to the current K-1 items
while True:
i+=1
if i not in temp or temp[i]==0: #if i not found in dict or it's val is 0
m[k+j]=i
break
return m[-1]
for ind,case in enumerate(xrange(1,len(cases),2)):
ans=func(cases[case],cases[case+1])
print "Case #{0}: {1}".format(ind+1,ans)
The last for-loop in second approach can also be written as :
for j in range(1,n-k):
i=-1
temp[m[j-1]] -= 1
if temp[m[j-1]]==0:
temp.pop(m[j-1]) #same as above but pop the key this time
temp[m[k+j-1]]=temp.get(m[k+j-1],0)+1
while True:
i+=1
if i not in temp:
m[k+j]=i
break
sample input :
5
97 39
34 37 656 97
186 75
68 16 539 186
137 49
48 17 461 137
98 59
6 30 524 98
46 18
7 11 9 46
output:
Case #1: 8
Case #2: 38
Case #3: 41
Case #4: 40
Case #5: 12
I already tried codereview, but no one replied there yet.
After at most k+1 steps, the last k+1 numbers in the array will be 0...k (in some order). Subsequently, the sequence is predictable: m[i] = m[i-k-1]. So the way to solve this problem is run your naive implementation for k+1 steps. Then you've got an array with 2k+1 elements (the first k were generated from the random sequence, and the other k+1 from iterating).
Now, the last k+1 elements are going to repeat infinitely. So you can just return the result for m[n] immediately: it's m[k + (n-k-1) % (k+1)].
Here's some code that implements it.
import collections
def initial_seq(k, a, b, c, r):
v = a
for _ in xrange(k):
yield v
v = (b * v + c) % r
def find_min(n, k, a, b, c, r):
m = [0] * (2 * k + 1)
for i, v in enumerate(initial_seq(k, a, b, c, r)):
m[i] = v
ks = range(k+1)
s = collections.Counter(m[:k])
for i in xrange(k, len(m)):
m[i] = next(j for j in ks if not s[j])
ks.remove(m[i])
s[m[i-k]] -= 1
return m[k + (n - k - 1) % (k + 1)]
print find_min(97, 39, 34, 37, 656, 97)
print find_min(186, 75, 68, 16, 539, 186)
print find_min(137, 49, 48, 17, 461, 137)
print find_min(1000000000, 100000, 48, 17, 461, 137)
The four cases run in 4 seconds on my machine, and the last case has the largest possible n.
Here is my O(k) solution, which is based on the same idea as above, but runs much faster.
import os, sys
f = open(sys.argv[1], 'r')
T = int(f.readline())
def next(ary, start):
j = start
l = len(ary)
ret = start - 1
while j < l and ary[j]:
ret = j
j += 1
return ret
for t in range(T):
n, k = map(int, f.readline().strip().split(' '))
a, b, c, r = map(int, f.readline().strip().split(' '))
m = [0] * (4 * k)
s = [0] * (k+1)
m[0] = a
if m[0] <= k:
s[m[0]] = 1
for i in xrange(1, k):
m[i] = (b * m[i-1] + c) % r
if m[i] < k+1:
s[m[i]] += 1
p = next(s, 0)
m[k] = p + 1
p = next(s, p+2)
for i in xrange(k+1, n):
if m[i-k-1] > p or s[m[i-k-1]] > 1:
m[i] = p + 1
if m[i-k-1] <= k:
s[m[i-k-1]] -= 1
s[m[i]] += 1
p = next(s, p+2)
else:
m[i] = m[i-k-1]
if p == k:
break
if p != k:
print 'Case #%d: %d' % (t+1, m[n-1])
else:
print 'Case #%d: %d' % (t+1, m[i-k + (n-i+k+k) % (k+1)])
The key point here is, m[i] will never exceeds k, and if we remember the consecutive numbers we can find in previous k numbers from 0 to p, then p will never reduce.
If number m[i-k-1] is larger than p, then it's obviously we should set m[i] to p+1, and p will increase at least 1.
If number m[i-k-1] is smaller or equal to p, then we should consider whether the same number exists in m[i-k:i], if not, m[i] should set equal to m[i-k-1], if yes, we should set m[i] to p+1 just as the "m[i-k-1]-larger-than-p" case.
Whenever p is equal to k, the loop begin, and the loop size is (k+1), so we can jump out of the calculation and print out the answer now.
I enhanced the performance through adding map.
import sys, os
import collections
def min(str1, str2):
para1 = str1.split()
para2 = str2.split()
n = int(para1[0])
k = int(para1[1])
a = int(para2[0])
b = int(para2[1])
c = int(para2[2])
r = int(para2[3])
m = [0] * (2*k+1)
m[0] = a
s = collections.Counter()
s[a] += 1
rs = {}
for i in range(k+1):
rs[i] = 1
for i in xrange(1,k):
v = (b * m[i - 1] + c) % r
m[i] = v
s[v] += 1
if v < k:
if v in rs:
rs[v] -= 1
if rs[v] == 0:
del rs[v]
for j in xrange(0,k+1):
for t in rs:
if not s[t]:
m[k+j] = t
if m[j] < k:
if m[j] in rs:
rs[m[j]] += 1
else:
rs[m[j]] = 0
rs[t] -= 1
if rs[t] == 0:
del rs[t]
s[t] = 1
break
s[m[j]] -= 1
return m[k + ((n-k-1)%(k+1))]
if __name__=='__main__':
lines = []
user_input = raw_input()
num = int(user_input)
for i in xrange(num):
input1 = raw_input()
input2 = raw_input()
print "Case #%s: %s"%(i+1, min(input1, input2))