Roy and Profile Picture - python-3.x

I need help with my code, i'm doing the code of Roy and Profile Picture in the hackearth, and when i going to run, this error appears:
'ValueError: invalid literal for int() with base 10:'
This is my code:
l = int(input())
n = int(input())
i = 0
while i < n:
wh = str(input().split(' '))
w,h = int(wh[0]),int(wh[1])
if w == l and h == l:
print('ACCEPTED')
else:
if w > l and h > l:
print('CROP IT')
else:
print('UPLOAD ANOTHER')
i+=1
sorry for my mistakes with the english, i'm learning. Is this in python 3.x

Correct Program is below:
l = int(input())
n = int(input())
i = 0
while i < n:
wh = (input().split())
w = int(wh[0])
h = int(wh[1])
if w < l or h < l:
print('UPLOAD ANOTHER')
else:
if w == h and (w >= l and h >= l) :
print('ACCEPTED')
else:
print('CROP IT')
i+=1

Scanner s = new Scanner(System.in);
int L = Integer.parseInt(s.nextLine());
int N = Integer.parseInt(s.nextLine());
int i = 0;
while(i++ < N) {
String[] arr = s.nextLine().split(" ");
int W = Integer.parseInt(arr[0]);
int H = Integer.parseInt(arr[1]);
if(W < L || H < L) {
System.out.println("UPLOAD ANOTHER");
} else if (W >= L && H >= L) {
if(W == H) {
System.out.println("ACCEPTED");
} else {
System.out.println("CROP IT");
}
}
}

Related

python replace '?' with not successive or preceding character

I am trying to solve a riddle, the challenge is to replace the question mark in a string by not using the previous or the following character in that string
For example:-
riddle = 'abcd?ef?'
expected_out = 'abcdiefa'
riddle = '???'
expected_out = 'aea'
This is the solution that I have tried but for some reason it isn't working
successor_element = ''
predecessor_element = ''
my_pre_succ_elements = []
riddle = "ab?ac?"
required_list = []
def solution(riddle):
my_replacers = ['a','e','i']
j = len(riddle)
print(j)
for e in range(0,j):
req_element = riddle[e]
print(e)
print(req_element)
if req_element == '?':
if e == 0:
successor_element = riddle[e+1]
if e == j-1:
predecessor_element = riddle[e-1]
if (e!= 0) and (e != j-1):
successor_element = riddle[e+1]
predecessor_element = riddle [e-1]
my_pre_succ_elements.extend(successor_element)
my_pre_succ_elements.extend(predecessor_element)
required_list = list(set(my_pre_succ_elements)^set(my_replacers))
substitutor = required_list[0]
riddle = str(riddle[0:e]) + str(substitutor) + str(riddle[e + 1:])
print(riddle)
pass
You were pretty close. This should work:
if req_element == '?':
possibles = ['a','e','i']
if e > 0 and riddle[e-1] in possibles:
possibles.remove(riddle[e-1])
if e < j-1 and riddle[e+1] in possibles:
possibles.remove(riddle[e+1])
substitutor = possibles[0]
riddle = riddle[:e] + substitutor + riddle[e+1:]

python: copy values of big array in smaller arrays

I have a problem,
where I would like to copy values of X a ( n x n ) array into smaller array A, B , C, D
here is my current code.
X = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
n = len(X)
n_by_2 = n // 2
A = [[]]
B = [[]]
C = [[]]
D = [[]]
"""
X = [
A<-- B<--
[1,2, | 3,4],
[5,6, | 7,8],
-------|-------
D<-- | C<--
[9,10, | 11,12],
[13,14,| 15,16]
]
"""
for i in range(len(X)):
for j in range(len(X[i])):
if (i >= 0 and i < n_by_2) and (j >= 0 and j < n_by_2):
#copy 1st quadrent values to A
#A[i][j] = X[i][j]
if (i >= 0 and i < n_by_2) and (j >= n_by_2 and j < n):
#copy 2nd quadrent values to B
#B[i][j] = X[i][j]
if (i >= n_by_2 and i < n) and (j >= 0 and j < n_by_2):
#copy 3rd quadrent values to C
#C[i][j] = X[i][j]
if (i >= n_by_2 and i < n) and (j >= n_by_2 and j < n):
#copy 4th quadrent values to D
#D[i][j] = X[i][j]
Be careful that you cannot add a new item x to an empty list l by doing.
l[0] = x. This only works if the list already has a length greater than 0. In that situation, you can use the append method instead.
For your problem, this code will do the job:
X = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
n = len(X)
n_by_2 = n // 2
A = []
B = []
C = []
D = []
for i in range(n_by_2):
A.append(X[i][:n_by_2])
B.append(X[i][n_by_2-1:-1])
for i in range(n_by_2):
C.append(X[i + n_by_2][:n_by_2])
D.append(X[i + n_by_2][n_by_2-1:-1])
print(A)
print(B)
print(C)
print(D)

Why doesn't assigning new values to a numpy array work?

I have the following code. The beggining is quite long, but only serves to generate data. The problem happens with a few lines at the end.
##### Import packages
import numpy as np
import scipy.linalg as la
##### Initial conditions
N = 5
lamda = 7
mu = 2
a = 0.5
r = - np.log(a).copy()
St_Sp = np.arange(- N, N + 1)
Card = St_Sp.shape[0]
##### Define infintesimal generator
def LL(x, y):
if x == N or x == - N: re = 0
elif x - y == - 1: re = lamda
elif x - y == 1: re = mu
elif x - y == 0: re = - (mu + lamda)
else: re = 0
return re
def L(x):
return - LL(x, x)
##### Define function Phi
def Phi(x): return max(x, 0)
Phi = np.vectorize(Phi)
##### Define vector b
b = Phi(St_Sp).copy()
##### Define function Psi
def Psi(x): return L(x) / (L(x) + r)
Psi = np.vectorize(Psi)
##### Generate a Boolean vector whose all elements are False
d = np.array([0] * Card).astype(bool)
##### Define matrix A
A = np.zeros((Card, Card))
for i in range(Card):
for j in range(Card):
if (i != j) & (L(St_Sp[i]) != 0):
A[i, j] = LL(St_Sp[i], St_Sp[j]) / L(St_Sp[i])
elif (i != j) & (L(St_Sp[i]) == 0):
A[i, j] = 0
elif (i == j) & (Psi(St_Sp[i]) != 0):
A[i, j] = - 1 / Psi(St_Sp[i])
else: A[i, j] = 1
##### Row names of A
rows = np.arange(0, Card)
##### Define matrix B
B = np.zeros((Card, Card))
for i in range(Card):
for j in range(Card):
if i != j:
B[i, j] = LL(St_Sp[i], St_Sp[j])
else: B[i, j] = LL(St_Sp[i], St_Sp[j]) - r
##### Generate I_0
I = [np.array([1] * Card).astype(bool), d.copy()]
Z = b.copy()
index0 = np.matmul(B, Z) <= 0
index1 = ~ index0
##### Generate I_1
I = [index0, index1]
Z = b.copy()
if np.sum(I[1]) > 0:
order = np.concatenate((rows[I[1]], rows[~ I[1]]))
A1 = A[np.ix_(rows[I[1]], order)]
A2 = la.lu(A1)[2]
p = np.atleast_2d(A1).shape[0]
B1 = A2[:, range(p)]
B2 = - np.matmul(A2[:, p:], Z[I[0]])
print('Before being assigned new values, Z is \n', Z)
print('\n The index I[1] of elements of Z to be change \n', I[1])
M = la.solve_triangular(B1, B2, lower = False)
print('\n The values to be assigned to Z[I[1]] is \n', M)
Z[I[1]] = M
print('\n After being assigned new values, Z is \n', Z)
with result
Before being assigned new values, Z is
[0 0 0 0 0 0 1 2 3 4 5]
The index I[1] of elements of Z to be change
[False False False False False True True True True True False]
The values to be assigned to Z[I[1]] is
[2.08686055 2.88974949 3.40529229 3.88978577 4.41338306]
After being assigned new values, Z is
[0 0 0 0 0 2 2 3 3 4 5]
It's very weird to me that the command Z[I[1]] = M does not assign new values from M to the postion of Z indexed by I[1]. Could you please elaborate on why this problem arises and how to resolve it?
The datatype of your array Z is int, to the values are typecasted by python automatically, resulting in the interger values of int([2.08686055 2.88974949 3.40529229 3.88978577 4.41338306]) = [2 2 3 3 4 5].
If you want to change that behavour, you just need to add a line to change the type of your original array:
Z = Z.astype(float)

How to fix with KeyError: q[minKey]? Run time error on python

I'm currently doing my school assignment which needs to be submitted to Automarker to test the code.
The question I'm stuck has to pass 5 different tasks and each task contains different input which is not given.
The only input is given is the sample input which shows below.
I keep getting the result of "KeyError: del q[min_Key]" and the status show "RunTimeError".
I don't understand how does it occurs?
And how to fix this error correctly?
from math import sqrt
import math
def getP(numV, ver, e):
d = -1
q = {0:0.0}
while bool(q):
minNum = 9999.0
min_Key = len(q) - 1
for k in q.keys():
if minNum > q[k]:
minNum = q[k]
min_Key = k
if numV-1 == min_Key:
d = minNum
break
del q[min_Key]
for v in e[min_Key].keys():
if v not in q:
q[v] = minNum+e[min_Key][v]
else:
if q[v] > minNum+e[min_Key][v]:
q[v] = minNum+e[min_Key][v]
return (d)
while True:
try:
user_input = input().split(',')
size = len(user_input)
n = user_input[0]
ver = {}
numV = 0
for i in range(1, size):
if i % 2 == 1:
ver[numV] = (float(user_input[i]), float(user_input[i+1]))
numV = numV + 1
e = {}
for u in ver.keys():
e[u] = {}
for v in ver.keys():
if u != v:
dist1 = (ver[u][1] - ver[v][1])*(ver[u][1] - ver[v][1])
dist2 = (ver[u][0] - ver[v][0])*(ver[u][0] - ver[v][0])
dist = dist1 + dist2
if dist <= 10000.0:
dist = sqrt(dist)
e[u][v] = dist
d = getP(numV, ver, e)
if d == -1:
print(d)
else:
print('{0:.2f}'.format(d))
except EOFError:
break
Sample Input: 100,0,0,0,100,100,100
Sample Output: 200.00
TIA!

Python: Compute a Huge Fibonacci Number Modulo m

# Uses python3
# Given two integers n and m, output Fn mod m (that is, the remainder of Fn when divided by m
def Huge_Fib(n,m):
if n == 0 : return 0
elif n == 1: return 1
else:
a,b = 0,1
for i in range(1,n):
a, b = b, (a+b) % m
print(b);
n,m = map(int, input().split());
Huge_Fib(n,m);
The code works very well. However, when I run a case as n = 99999999999999999, m = 2, it takes me much time. Do you have any better solutions?
Here is my solution, you don't have to go through 99999999999999999 iterations if you find the pisano period.
I also recommend that you watch this video: https://www.youtube.com/watch?v=Nu-lW-Ifyec
# Uses python3
import sys
def get_fibonacci_huge(n, m):
if n <= 1:
return n
arr = [0, 1]
previousMod = 0
currentMod = 1
for i in range(n - 1):
tempMod = previousMod
previousMod = currentMod % m
currentMod = (tempMod + currentMod) % m
arr.append(currentMod)
if currentMod == 1 and previousMod == 0:
index = (n % (i + 1))
return arr[index]
return currentMod
if __name__ == '__main__':
input = sys.stdin.read();
n, m = map(int, input.split())
print(get_fibonacci_huge(n,m))
# Uses python3
# Given two integers n and m, output Fn mod m (that is, the remainder of Fn when divided by m
def Huge_Fib(n,m):
# Initialize a matrix [[1,1],[1,0]]
v1, v2, v3 = 1, 1, 0
# Perform fast exponentiation of the matrix (quickly raise it to the nth power)
for rec in bin(n)[3:]:
calc = (v2*v2) % m
v1, v2, v3 = (v1*v1+calc) % m, ((v1+v3)*v2) % m, (calc+v3*v3) % m
if rec == '1': v1, v2, v3 = (v1+v2) % m, v1, v2
print(v2);
n,m = map(int, input().split());
Huge_Fib(n,m);
This is a superfast solution refer to https://stackoverflow.com/a/23462371/3700852
I solved it in Python 3. This the fastest algorithm to compute a huge Fibonacci number modulo m.For example for n =2816213588, m = 239, it took Max time used: 0.01/5.00, max memory used: 9424896/536870912.)
def pisanoPeriod(m):
previous, current = 0, 1
for i in range(0, m * m):
previous, current = current, (previous + current) % m
# A Pisano Period starts with 01
if (previous == 0 and current == 1):
return i + 1
def calc_fib(n,m):
p = pisanoPeriod(m)
n = n % p
if (n <= 1):
return n
else:
previous,current = 0,1
for i in range(2,n+1):
previous,current = current,(previous+current)
return current%m
n,m =map(int,input().split(" "))
print(calc_fib(n,m))
In the below code we are using two concepts of Fibonacci series:
Pisano periods follows a Fibonacci sequence and hence each repetition(pattern) begins with 0 and 1 appearing consecutively one after the other.
fib(n) divides fib(m) only when n divides m which means if fib(4)%3==0,then fib(4+4)%3==0,fib(4+4+4)%3==0 and so on.This helps us in finding the Pisano period.
To know about Pisano periods,I recommend that you watch this video: https://www.youtube.com/watch?v=Nu-lW-Ifyec
#python3
def pisano_length(m):
i=2
while(fib(i)%m!=0):
i+=1
if(fib(i+1)%m!=1):
while(fib(i+1)%m!=1):
i+=i
print("The pisano length for mod {} is: {}".format(m,i))
return(i)
def fib(n):
a,b=0,1
if(n==0 or n==1):
return n
else:
for i in range(2,n+1):
b,a=a+b,b
return(b)
#we want to calculate fib(n)%m for big numbers
n,m=map(int,input().split())
remainder=n%pisano_length(m)
print(fib(remainder)%m)
You should look up Pisano periods.
https://en.wikipedia.org/wiki/Pisano_period and
http://webspace.ship.edu/msrenault/fibonacci/fibfactory.htm should give you a good understanding of what they are.
edit: Just googling "fibonacci modulo" gives you those two as the top two results.
For any integer m>=2, the sequence fn modulo m is periodic - Pisano Period.
So no need to store and find fn. Instead, find a repeating pattern for given m.
This is how i have done by calculating the pisano period.(Java)
public static long get_pisano_period(long m) {
long a = 0, b = 1;
long c;
for (int i = 0; i < m * m; i++) {
c = (a + b) % m;
a = b;
b = c;
if (a == 0 && b == 1)
return i + 1;
}
return 0;
}
public static BigInteger get_fibonacci_huge(long n,long m) {
long remainder = n % get_pisano_period(m);
BigInteger first = BigInteger.valueOf(0);
BigInteger second=BigInteger.valueOf(1);
BigInteger m1=BigInteger.valueOf(m);
BigInteger res = BigInteger.valueOf(remainder);
for (long i = 1; i < remainder; i++) {
res = (first.add(second)).mod(m1);
first = second;
second = res;
}
return res.mod(m1);
}

Resources