Sorry for the formatting. New at posting questions
I was practicing this problem asked in the last round of Google Kick Start 2020. The problem is called Record Breaker and is as follows:
Isyana is given the number of visitors at her local theme park on N consecutive days. The number of visitors on the i-th day is Vi. A day is record breaking if it satisfies both of the following conditions: The number of visitors on the day is strictly larger than the number of visitors on each of the previous days. Either it is the last day, or the number of visitors on the day is strictly larger than the number of visitors on the following day. Note that the very first day could be a record breaking day!
Please help Isyana find out the number of record breaking days.
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 Vi.
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 record breaking days.
Limits Time limit: 20 seconds per test set. Memory limit: 1GB. 1 ≤ T ≤ 100. 0 ≤ Vi ≤ 2 × 105.
Test set 1
1 ≤ N ≤ 1000.
Test set 2
1 ≤ N ≤ 2 × 105 for at most 10 test cases. For the remaining cases, 1 ≤ N ≤ 1000.
Sample
Input
4
8
1 2 0 7 2 0 2 0
6
4 8 15 16 23 42
9
3 1 4 1 5 9 2 6 5
6
9 9 9 9 9 9
Output
Case #1: 2
Case #2: 1
Case #3: 3
Case #4: 0
In Sample Case #1, the bold and underlined numbers in the following represent the record breaking days: 1 2 0 7 2 0 2 0.
In Sample Case #2, only the last day is a record breaking day.
In Sample Case #3, the first, the third, and the sixth days are record breaking days.
In Sample Case #4, there is no record breaking day.
This is the solution I created. It gives a Wrong Answer in the first Test Case but I can't think of any specific case that I have missed.
def sol(testcase):
days = int(input())
record_breaking = 0
greatest = 0
visitors = [0] + list(map(int, input().split())) + [0]
for x in range(days+1):
if x == 0:
continue
if visitors[x] > greatest:
greatest = visitors[x]
if (visitors[x] > visitors[x-1]) and (visitors[x] > visitors[x+1]):
record_breaking += 1
print(f"Case #{testcase}: {record_breaking}")
testcases = int(input())
for x in range(testcases):
sol(x+1)
// Here Is Your Answer Cleared All Test Cases
T = int(input())
for i in range(T):
N = int(input())
Vs = [int(v) for v in input().split(" ")]
max_number = -1
record_breaks = 0
for j in range(N):
first_condition = Vs[j] > max_number
if j+1 < N:
second_condition = Vs[j] > Vs[j+1]
else:
second_condition = True
if first_condition and second_condition:
record_breaks +=1
if first_condition:
max_number = Vs[j]
print("Case #{}: {}".format(str(i+1), str(record_breaks)))
Related
I am trying to create a variable that display how many days a bulb were functional, from different variables (Score_day_0).
The dataset I am using is like this one bellow, where score at different days are: 1--> Working very well and 10-->stop working.
What I want is to understand / know how to create the variable Days, where it will display the number of days the bulbs were working, ie. for sample 2, the score at day 10 is 8 and day_20 is 10 (stop working) and therefore the number of days that the bulb was working is 20.
Any suggestion?
Thank you so much for your help, hope you have a terrific day!!
sample
Score_Day_0
Score_Day_10
Score_Day_20
Score_Day_30
Score_Day_40
Days
sample 1
1
3
5
8
10
40
sample 2
3
8
10
10
10
20
I've tried to solve by myself generating a conditional loop, but the number of observations in Days are much higher than the number of observation from the original df.
Here is the code I used:
cols = df[['Score_Day_0', 'Score_Day_10....,'Score_Day_40']]
Days = []
for j in cols['Score_Day_0']:
if j = 10:
Days.append(0)
for k in cols['Score_Day_10']:
if k = 10:
Days.append('10')
for l in cols['Score_Day_20']:
if l = 10:
Days.append('20')
for n in cols['Score_Day_30']:
if n = 105:
Days.append('30')
for n in cols['Score_Day_40']:
if m = 10:
Days.append('40')
Your looking for the first column label (left to right) at which the value is maximal in each row.
You can apply a given function on each row using pandas.DataFrame.apply with axis=1:
df.apply(function, axis=1)
The passed function will get the row as Series object. To find the first occurrence of a value in a series we use a simple locator with our condition and retrieve the first value of the index containing - what we were looking for - the label of the column where the row first reaches its maximal values.
lambda x: x[x == x.max()].index[0]
Example:
df = pd.DataFrame(dict(d0=[1,1,1],d10=[1,5,10],d20=[5,10,10],d30=[8,10,10]))
# d0 d10 d20 d30
# 0 1 1 5 8
# 1 1 5 10 10
# 2 1 10 10 10
df['days'] = df.apply(lambda x: x[x == x.max()].index[0], axis=1)
df
# d0 d10 d20 d30 days
# 0 1 1 5 8 d30
# 1 1 5 10 10 d20
# 2 1 10 10 10 d10
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
I am researching how python implements dictionaries. One of the equations in the python dictionary implementation relates the pseudo random probing for an empty dictionary slot using the equation
j = ((j*5) + 1) % 2**i
which is explained here.
I have read this question, How are Python's Built In Dictionaries Implemented?, and basically understand how dictionaries are implemented.
What I don't understand is why/how the equation:
j = ((j*5) + 1) % 2**i
cycles through all the remainders of 2**i. For instance, if i = 3 for a total starting size of 8. j goes through the cycle:
0
1
6
7
4
5
2
3
0
if the starting size is 16, it would go through the cycle:
0 1 6 15 12 13 2 11 8 9 14 7 4 5 10 3 0
This is very useful for probing all the slots in the dictionary. But why does it work ? Why does j = ((j*5)+1) work but not j = ((j*6)+1) or j = ((j*3)+1) both of which get stuck in smaller cycles.
I am hoping to get a more intuitive understanding of this than the equation just works and that's why they used it.
This is the same principle that pseudo-random number generators use, as Jasper hinted at, namely linear congruential generators. A linear congruential generator is a sequence that follows the relationship X_(n+1) = (a * X_n + c) mod m. From the wiki page,
The period of a general LCG is at most m, and for some choices of factor a much less than that. The LCG will have a full period for all seed values if and only if:
m and c are relatively prime.
a - 1 is divisible by all prime factors of m.
a - 1 is divisible by 4 if m is divisible by 4.
It's clear to see that 5 is the smallest a to satisfy these requirements, namely
2^i and 1 are relatively prime.
4 is divisible by 2.
4 is divisible by 4.
Also interestingly, 5 is not the only number that satisfies these conditions. 9 will also work. Taking m to be 16, using j=(9*j+1)%16 yields
0 1 10 11 4 5 14 15 8 9 2 3 12 13 6 7
The proof for these three conditions can be found in the original Hull-Dobell paper on page 5, along with a bunch of other PRNG-related theorems that also may be of interest.
I have to do these for school and I don't know how to.
Write a function print_triangular_numbers(n) that prints out the first n triangular numbers (n is an input). A call to print_triangular_numbers(5) would produce the following output:
n result
1 1
2 3
3 6
4 10
5 15
A triangular number can be expressed as
n(n+1)/2
Thus, you need to build a simple loop, starting at 1 and going through your passed parameter:
def print_triangular_numbers(n):
for x in range(1,n+1):
print x, x * (x + 1) / 2
The for loop starts at 1 and goes through n+1 because range is not inclusive of the end point.
This outputs:
1 1
2 3
3 6
4 10
5 15
I want to make a program that counts down from 10 by using the operator while.
This is what I have so far but it would not do what I want.
i = 10
while i < 10:
print(i)
i = i-1
This doesn't work and I'd like to know why!
You exit the loop as soon as i is less than 10. 9 is less than 10 so you leave the loop in the first run. What you need is:
i = 10
while i > 0:
print(i)
i = i-1
In this case you stay in the loop as long as i is greater than zero.
i < 10 means "i is less than 10"
i > 10 means "i is greater than 10"
The symbol is a bit like an arrow. It always points towards the smaller item. This is slightly different if you are checking for a condition.
if i < 10 is saying "if i is less than 10"
while i > 10 is saying, "while i is greater than 10"
So this is what you need:
i = 10
while i > 0: # while i is greater than zero
print(i)
i = i - 1 # i will eventually be less than zero, meaning the
# condition for the loop will return false and stop the loop
This will print i from 10 to 0
Others have shown you the way how to do it with while. My question is why do you want to do it by using while. If there are no constrains, I would suggest you to look for range:
https://docs.python.org/3.5/library/functions.html#func-range
You could implement your counting like this:
for i in range(11):
print(i)
#output
0
1
2
3
4
5
6
7
8
9
10
To count down just reverse the range function:
for i in reversed(range(11)):
print(i)
#output
10
9
8
7
6
5
4
3
2
1
0
I hope this alternative can help you.