Google Kickstart Round E 2020 Longest Arithmetic Runtime Error - python

I tried solving this challenge mentioned below but I got a Run Time error. I used Python
Problem
An arithmetic array is an array that contains at least two integers and the differences between consecutive integers are equal. For example, [9, 10], [3, 3, 3], and [9, 7, 5, 3] are arithmetic arrays, while [1, 3, 3, 7], [2, 1, 2], and [1, 2, 4] are not arithmetic arrays.
Sarasvati has an array of N non-negative integers. The i-th integer of the array is Ai. She wants to choose a contiguous arithmetic subarray from her array that has the maximum length. Please help her to determine the length of the longest contiguous arithmetic subarray.
Input:
The first line of the input gives the number of test cases, T. T test cases follow. Each test case begins with a line containing the integer N. The second line contains N integers. The i-th integer is Ai.
Output:
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the length of the longest contiguous arithmetic subarray.
Limits
Time limit: 20 seconds per test set.
Memory limit: 1GB.
1 ≤ T ≤ 100.
0 ≤ Ai ≤ 109.
Test Set 1
2 ≤ N ≤ 2000.
Test Set 2
2 ≤ N ≤ 2 × 105 for at most 10 test cases.
For the remaining cases, 2 ≤ N ≤ 2000.
Sample Input
4
7
10 7 4 6 8 10 11
4
9 7 5 3
9
5 5 4 5 5 5 4 5 6
10
5 4 3 2 1 2 3 4 5 6
Output
Case #1: 4
Case #2: 4
Case #3: 3
Case #4: 6
Here's my python3 solution which gives run time error
t = int(input())
for t_case in range(t):
n = int(input())
arr = list(map(int, input().split()))
x = []
for i in range(n - 1) :
x.append((arr[i] - arr[i + 1]))
ans, temp = 1, 1
j = len(x)
for i in range(1,j):
if x[i] == x[i - 1]:
temp = temp + 1
else:
ans = max(ans, temp)
temp = 1
ans = max(ans, temp)
print(f"Case #{t_case+1}: {ans+1}")
Could anyone please help me out.

As of now Kickstart is using Python 3.5 which does not support f-strings (they were added in py3.6). Try to replace them with str.format.

t=int(input())
for test in range(t):
n=int(input())
arr = list(map(int, input().split()))
x = []
for i in range(n - 1) :
x.append((arr[i] - arr[i + 1]))
ans, temp = 1, 1
j = len(x)
for i in range(1,j):
if x[i] == x[i - 1]:
temp = temp + 1
else:
ans = max(ans, temp)
temp = 1
ans = max(ans, temp)
print('Case #{0}: {1}'.format(test+1,ans+1))

Related

Finding number from list that respects conditions

I need to code a script that chooses a number from a user input (list) depending on two conditions:
Is a multiple of 3
Is the smallest of all numbers
Here is what I've done so far
if a % 3 == 0 and a < b:
print (a)
a = int(input())
r = list(map(int, input().split()))
result(a, r)
The problem is I need to create a loop that keeps verifying these conditions for the (x) number of inputs.
It looks like you want a to be values within r rather than its own input. Here's an example of iterating through r and checking which numbers are multiples of 3, and of finding the minimum of all the numbers (not necessarily only those which are multiples of 3):
r = list(map(int, input().split()))
for a in r:
if a % 3 == 0:
print(f"Multiple of 3: {a}")
print(f"Smallest of numbers: {min(r)}")
1 2 3 4 5 6 7 8 9 0
Multiple of 3: 3
Multiple of 3: 6
Multiple of 3: 9
Multiple of 3: 0
Smallest of numbers: 0
Doing this in one line – or through generators – can improve performance through optimizing memory allocation:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# The following is a generator
# Also: you need to decide if you want 0 to be included
all_threes = (x for x in my_list if x%3==0)
min_number = min(my_list)

Kickstart Round C 2020 Countdown Problem - finding number of contiguous subarray

Edit - The output didn't have a space before the colon. But after changing that, instead of wrong answer, it's saying runtime error. Even the sample input tests ran successfully. What could possible be wrong?
Problem
Avery has an array of N positive integers. The i-th integer of the array is Ai.
A contiguous subarray is an m-countdown if it is of length m and contains the integers m, m-1, m-2, ..., 2, 1 in that order. For example, [3, 2, 1] is a 3-countdown.
Can you help Avery count the number of K-countdowns in her array?
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each test case begins with a line containing the integers N and K. The second line contains N integers. The i-th integer is Ai.
Output
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the number of K-countdowns in her array.
Limits
Time limit: 20 seconds per test set.
Memory limit: 1GB.
1 ≤ T ≤ 100.
2 ≤ K ≤ N.
1 ≤ Ai ≤ 2 × 105, for all i.
Test set 1
2 ≤ N ≤ 1000.
Test set 2
2 ≤ N ≤ 2 × 105 for at most 10 test cases.
For the remaining cases, 2 ≤ N ≤ 1000.
Sample
Input
3
12 3
1 2 3 7 9 3 2 1 8 3 2 1
4 2
101 100 99 98
9 6
100 7 6 5 4 3 2 1 100
Output
Case #1: 2
Case #2: 0
Case #3: 1
T = int(input())
res = []
for i in range(T):
N, K = map(int, input().split(' '))
ai = list(map(int, input().split(' ')))
y=0
count=0
for m in range(len(ai)):
count=0
if(ai[m]==K):
if(len(ai)>=m+K-1):
for j in reversed(range(1, K)):
if(ai[m+K-j]==j):
count=count+1
if(count==K-1):
y=y+1
else:
break
else:
continue
res.append("Case #"+str(i+1)+" : "+str(y))
for g in range(len(res)):
print(res[g])
You can use a two-pointer approach like take two variables i and j and initialize both with 0
Keeping i fixed increment j if the required condition is met i.e.
while(a[k+1]-a[k]==1):
j++
k++
wherever condition fails, calculate j-i. If at all j-i==m then increment your counter say cnt and then put i=j and repeat until the end of array

How to find how many values are divisible in to certain value in 2d array in python

The following code generate random number of 2d arrays and I want to print how many values in each pair are divisible to 3. For example assume we have an array [[2, 10], [1, 6], [4, 8]].
So the first pair which is [2,10] has 3 ,6 and 9 which are totally 3 and second pair has 3 and 6 which are totally two and last pair[4,8] has just 1 divisible to 3 which is 6. Therefore, The final out put should print sum of total number of divisible values which is 3+2+1=6
a=random.randint(1, 10)
b = np.random.randint(1,10,(a,2))
b = [sorted(i) for i in b]
c = np.array(b)
counter = 0;
for i in range(len(c)):
d=(c[i,0],c[i,1])
if (i % 3 == 0):
counter = counter + 1
print(counter)
One way is to count how many integers in the interval are divisible by 3 by testing each one.
Another way, and this is much more efficient if your intervals are huge, is to use math.
Take the interval [2, 10].
2 / 3 = 0.66; ceil(2 / 3) = 1.
10 / 3 = 3.33; floor(10 / 3) = 3.
Now we need to count how many integers exist between 0.66 and 3.33, or count how many integers exist between 1 and 3. Hey, that sounds an awful lot like subtraction! (and then adding one)
Let's write this as a function
from math import floor, ceil
def numdiv(x, y, div):
return floor(y / div) - ceil(x / div) + 1
So given a list of intervals, we can call it like so:
count = 0
intervals = [[2, 10], [1, 6], [4, 8]]
for interval in intervals:
count += numdiv(interval[0], interval[1], 3)
print(count)
Or using a list comprehension and sum:
count = sum([numdiv(interval[0], interval[1], 3) for interval in intervals])
You can use sum() builtin for the task:
l = [[2, 10], [1, 6], [4, 8]]
print( sum(v % 3 == 0 for a, b in l for v in range(a, b+1)) )
Prints:
6
EDIT: To count number of perfect squares:
def is_square(n):
return (n**.5).is_integer()
print( sum(is_square(v) for a, b in l for v in range(a, b+1)) )
Prints:
5
EDIT 2: To print info about each interval, just combine the two examples above. For example:
def is_square(n):
return (n**.5).is_integer()
for a, b in l:
print('Pair {},{}:'.format(a, b))
print('Number of divisible 3: {}'.format(sum(v % 3 == 0 for v in range(a, b+1))))
print('Number squares: {}'.format(sum(is_square(v) for v in range(a, b+1))))
print()
Prints:
Pair 2,10:
Number of divisible 3: 3
Number squares: 2
Pair 1,6:
Number of divisible 3: 2
Number squares: 2
Pair 4,8:
Number of divisible 3: 1
Number squares: 1

how to use bitwise operator in python?

Description:
Input a list of numbers “num_list”.
All numbers in the list occur even times expect one number which occurs odd number of times. Find the number that occurs odd number of time in O(1) space complexity and O(n) time complexity.
Note: Use Bitwise operator.
Sample Input:
1 2 2 5 5 1 3 9 3 9 6 4 4
What I tried:
def getOddOccurrence(arr, arr_size):
for i in range(0, arr_size):
count = 0
for j in range(0, arr_size):
if arr[i] == arr[j]:
count += 1
if (count % 2 != 0):
return arr[i]
return -1# driver code
arr = [1, 2, 2, 5, 5, 1, 3, 9, 3, 9, 6, 4, 4]
n = len(arr)
print(getOddOccurrence(arr, n))
Bitwise operations consists of multiple operations like AND, OR, XOR... and so on. The one you are looking for is called XOR.
XOR of number with same number is 0. So if you XOR all elements in your array, all elements occurring even number of times cancel each other out. And you are left with with the number that occurred odd number of times.
Time Complexity: O(N)
Space Complexity: O(1)
def getOddOccurrence(arr, arr_size):
if len(arr) == 0:
return -1
xor = arr[0]
for i in range(1, arr_size):
xor = xor ^ arr[i]
return xor
arr = [1,2,2,5,5,1,3,9,3,9,6,4,4 ]
n = len(arr)
print(getOddOccurrence(arr, n))

finding the length of the longest subsequence

Here, in this piece of code, it prints the length of the largest subsequence of a sequence that's increasing then decreasing or vice versa.
for example:
Input: 1, 11, 2, 10, 4, 5, 2, 1
Output: 6 (A Longest Subsequence of length 6 is 1, 2, 10, 4, 2, 1)
but how can I make it work with three monotonic (increasing or decreasing) regions?
like increasing-decreasing-increasing OR decreasing-increasing-decreasing
example:
input: 7 16 1 6 20 17 7 18 25 1 25 21 11 5 29 11 3 3 26 19
output: 12
(largest subsequence: 7 1 6 17 18 25 25 21 11 5 3 3) as we see,
it can be split into three regions:
7,1 / 6,17,18,25,25 / 21,11,5,3,3
arr = list(map(int, input().split()))
def lbs(arr):
n = len(arr)
lis = [1 for i in range(n+1)]
for i in range(1 , n):
for j in range(0 , i):
if ((arr[i] > arr[j]) and (lis[i] < lis[j] +1)):
lis[i] = lis[j] + 1
lds = [1 for i in range(n+1)]
for i in reversed(range(n-1)):
for j in reversed(range(i-1 ,n)):
if(arr[i] > arr[j] and lds[i] < lds[j] + 1):
lds[i] = lds[j] + 1
maximum = lis[0] + lds[0] - 1
for i in range(1 , n):
maximum = max((lis[i] + lds[i]-1), maximum)
return maximum
print ("Length of LBS is",lbs(arr))
I've came up with a O(n^2 log n) idea.
You want to divide your whole segment into three parts: first one containing increasing subsequence, second one containing decreasing one and the last one containing again increasing one.
First of all, let's choose a sequence's prefix - the first part (O(n) possibilities). To minimize the amount of checked intervals, you can pick only prefixes which last element is in their longest increasing subsequence. (In other words, when choosing range [1, x], a_x should be in it's longest increasing subsequence)
Now you have similar problem to the one you've already solved - finding decreasing, then increasing subsequence (I'd use binary search instead of for loop you used, by the way). The only difference is that the decreasing subsequence must start from values smaller than the last element of chosen prefix (just ignore any larger or equal values) - you're able to do it in O(n log n).

Categories