Solve in Python:
A variation of determining leap years, assuming only integers are used and years can be negative and positive.

Write a function which will return the days in the year and the year entered in a string.  For example 2000, entered as an integer, will return as a string 2000 has 366 days

There are a few assumptions we will accept the year 0, even though there is no year 0 in the Gregorian Calendar.

Also the basic rule for validating a leap year are as follows

Most years that can be divided evenly by 4 are leap years.

Exception: Century years are NOT leap years UNLESS they can be evenly divided by 400.

So the years 0, -64 and 2016 will return 366 days.
Whilst 1974, -10 and 666 will return 365 days.

def year_days(year):

    if year % 100 == 0 and year % 400 ==0:
        return f'{year} has 366 days'
    elif year % 4 == 0 and year % 100 !=0:
        return f'{year} has 366 days'
    else:
        return f'{year} has 365 days'


Solve in Python:
A very easy task for you!

You have to create a method, that corrects a given date string.
There was a problem in addition, so many of the date strings are broken.
Date-Format is european. That means "DD.MM.YYYY".

Some examples:

"30.02.2016" -> "01.03.2016"
"40.06.2015" -> "10.07.2015"
"11.13.2014" -> "11.01.2015"
"99.11.2010" -> "07.02.2011"

If the input-string is null or empty return exactly this value!
If the date-string-format is invalid, return null.

Hint: Correct first the month and then the day!

Have fun coding it and please don't forget to vote and rank this kata! :-)

I have created other katas. Have a look if you like coding and challenges.

import datetime as dt
import re

def date_correct(date):
    if isinstance(date,str) and re.fullmatch(r'\d\d\.\d\d\.\d{4}', date):
        d,m,y = map(int,date.split('.'))
        nM,m  = divmod(m-1,12) ; y+=nM ; m+=1
        d     = dt.date(y,m,1) + dt.timedelta(days=d-1)
        return f'{d.day:02}.{d.month:02}.{d.year:02}'
    if date=='': return ""


Solve in Python:
A very passive-aggressive co-worker of yours was just fired. While he was gathering his things, he quickly inserted a bug into your system which renamed everything to what looks like jibberish. He left two notes on his desk, one reads: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" while the other reads: "Uif usjdl up uijt lbub jt tjnqmf kvtu sfqmbdf fwfsz mfuufs xjui uif mfuufs uibu dpnft cfgpsf ju".

Rather than spending hours trying to find the bug itself, you decide to try and decode it.

If the input is not a string, your function must return "Input is not a string". Your function must be able to handle capital and lower case letters. You will not need to worry about punctuation.

def one_down(txt):
    #your code here
    if isinstance(txt, list) or isinstance(txt,int):
        return "Input is not a string"
    Decode  = list(map((ord),txt))
    txt= ''
    for x in Decode:
        if x < 65 or x > 122:
            txt +=chr(x)
        elif x == 65 or x == 97:
            txt +=chr(x+25)
        else:
            txt +=chr(x-1)
    return(txt)


Solve in Python:
A wildlife study involving ducks is taking place in North America. Researchers are visiting some wetlands in a certain area taking a survey of what they see. The researchers will submit reports that need to be processed by your function.

## Input

The input for your function will be an array with a list of common duck names along with the counts made by the researchers. The names and counts are separated by spaces in one array element. The number of spaces between the name and the count could vary; but, there will always be at least one. A name may be repeated because a report may be a combination of surveys from different locations.

An example of an input array would be:
```
["Redhead 3", "Gadwall 1", "Smew 4", "Greater Scaup 10", "Redhead 3", "Gadwall 9", "Greater Scaup 15", "Common Eider 6"]
```

## Processing

Your function should change the names of the ducks to a six-letter code according to given rules (see below). The six-letter code should be in upper case. The counts should be summed for a species if it is repeated.

## Output

The final data to be returned from your function should be an array sorted by the species codes and the total counts as integers. The codes and the counts should be individual elements.

An example of an array to be returned (based on the example input array above) would be:
```
["COMEID", 6, "GADWAL", 10, "GRESCA", 25, "REDHEA", 6, "SMEW", 4]
```
The codes are strings in upper case and the totaled counts are integers.

### Special Note

If someone has `"Labrador Duck"` in their list, the whole list should be thrown out as this species has been determined to be extinct. The person who submitted the list is obviously unreliable. Their lists will not be included in the final data. In such cases, return an array with a single string element in it: `"Disqualified data"`

Rules for converting a common name to a six-letter code:

* Hyphens should be considered as spaces.
* If a name has only one word, use the first six letters of the name. If that name has less than six...

def create_report(names):
    result = {}

    for name in names:
        if name.startswith("Labrador Duck"):
            return ["Disqualified data"]

        name = name.upper().replace("-", " ").split()
        count = int(name.pop())

        if   len(name) == 1:  code = name[0][:6]
        elif len(name) == 2:  code = name[0][:3] + name[1][:3]
        elif len(name) == 3:  code = name[0][:2] + name[1][:2] + name[2][:2]
        elif len(name) == 4:  code = name[0][0] + name[1][0] + name[2][:2] + name[3][:2]

        if code in result:    result[code] += count
        else:                 result[code] = count

    return sum([[name, result[name]] for name in sorted(result)] , [] )


Solve in Python:
A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below.

Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S.

Example 1:

Input: A = [5,4,0,3,1,6,2]
Output: 4
Explanation:
A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.

One of the longest S[K]:
S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}

Note:

N is an integer within the range [1, 20,000].
The elements of A are all distinct.
Each element of A is an integer within the range [0, N-1].

class Solution:
     def arrayNesting(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """

         dic = set()
         ma = 0
         for i in nums:
             if i not in dic: # not considered
                 set_ = set()
                 while i  not in set_:
                     set_.add(i)
                     i = nums[i]
                 ma = max(ma,len(set_))
                 dic.update(set_)
         return ma


Solve in Python:
A zero-indexed array ```arr``` consisting of n integers is given. The dominator of array ```arr``` is the value that occurs in more than half of the elements of ```arr```.
For example, consider array ```arr``` such that ```arr = [3,4,3,2,3,1,3,3]``` The dominator of ```arr``` is 3 because it occurs in 5 out of 8 elements of ```arr``` and 5 is more than a half of 8.
Write a function ```dominator(arr)``` that, given a zero-indexed array ```arr``` consisting of n integers, returns the dominator of ```arr```. The function should return −1 if array does not have a dominator. All values in ```arr``` will be >=0.

def dominator(arr):
    for x in set(arr):
        if arr.count(x) > len(arr)/2.0:
            return x
    return -1


Solve in Python:
AND gates and OR gates are basic components used in building digital circuits. Both gates have two input lines and one output line. The output of an AND gate is 1 if both inputs are 1, otherwise the output is 0. The output of an OR gate is 1 if at least one input is 1, otherwise the output is 0.

You are given a digital circuit composed of only AND and OR gates where one node (gate or input) is specially designated as the output. Furthermore, for any gate G and any input node I, at most one of the inputs to G depends on the value of node I.

Now consider the following random experiment. Fix some probability p in [0,1] and set each input bit to 1 independently at random with probability p (and to 0 with probability 1-p). The output is then 1 with some probability that depends on p. You wonder what value of p causes the circuit to output a 1 with probability 1/2.

-----Input-----

The first line indicates the number of test cases to follow (about 100).

Each test case begins with a single line containing a single integer n with 1 ≤ n ≤ 100 indicating the number of nodes (inputs and gates) in the circuit. Following this, n lines follow where the i'th line describes the i'th node. If the node is an input, the line simply consists of the integer 0. Otherwise, if the node is an OR gate then the line begins with a 1 and if the node is an AND gate then the line begins with a 2. In either case, two more integers a,b follow, both less than i, which indicate that the outputs from both a and b are used as the two input to gate i.

As stated before, the circuit will be such that no gate has both of its inputs depending on the value of a common input node.

Test cases are separated by a blank line including a blank line preceding the first test case.

-----Output-----

For each test case you are to output a single line containing the value p for which the output of node n is 1 with probability exactly 1/2 if the inputs are independently and randomly set to value 1 with probability p. The value p should be printed with...

class node:
	def __init__(self,a,b=0,c=0):
		self.val=a
		self.a=b
		self.b=c

arr=[]

def finder(node,val):
	if(arr[node].val==0):
		return val
	else:
		a=finder(arr[node].a,val)
		b=finder(arr[node].b,val)
		if(arr[node].val==1):
			return a+b-a*b
		else:
			return a*b

t=int(input())
while(t>0):
	x=input()
	n=int(input())
	arr.append(node(0))
	for i in range(0,n):
		vals=input().split()
		sz=len(vals)
		for i in range(0,sz):
			vals[i]=int(vals[i])
		if(vals[0]==0):
			next=node(0)
			arr.append(next)
		else:
			next=node(vals[0],vals[1],vals[2])
			arr.append(next)
	lower=0.0
	higher=1.0
	eps=1e-9
	while((higher-lower)>eps):
		mid=(higher+lower)/2.0
		if(finder(n,mid)>0.5):
			higher=mid
		else:
			lower=mid
	print("%.5f" %(higher))
	arr=[]
	# print(higher)
	t-=1


Solve in Python:
ASC Week 1 Challenge 4 (Medium #1)

Write a function that converts any sentence into a V  A  P  O  R  W  A  V  E sentence. a V  A  P  O  R  W  A  V  E sentence converts all the letters into uppercase, and adds 2 spaces between each letter (or special character) to create this V  A  P  O  R  W  A  V  E effect.

Examples:
```javascript
  vaporcode("Lets go to the movies") // output => "L  E  T  S  G  O  T  O  T  H  E  M  O  V  I  E  S"
  vaporcode("Why isn't my code working?") // output => "W  H  Y  I  S  N  '  T  M  Y  C  O  D  E  W  O  R  K  I  N  G  ?"
```
```ruby
  vaporcode("Lets go to the movies") # output => "L  E  T  S  G  O  T  O  T  H  E  M  O  V  I  E  S"
  vaporcode("Why isn't my code working?") # output => "W  H  Y  I  S  N  '  T  M  Y  C  O  D  E  W  O  R  K  I  N  G  ?"
```
```python
  vaporcode("Lets go to the movies") # output => "L  E  T  S  G  O  T  O  T  H  E  M  O  V  I  E  S"
  vaporcode("Why isn't my code working?") # output => "W  H  Y  I  S  N  '  T  M  Y  C  O  D  E  W  O  R  K  I  N  G  ?"
```
```crystal
  vaporcode("Lets go to the movies") # output => "L  E  T  S  G  O  T  O  T  H  E  M  O  V  I  E  S"
  vaporcode("Why isn't my code working?") # output => "W  H  Y  I  S  N  '  T  M  Y  C  O  D  E  W  O  R  K  I  N  G  ?"
```
```cpp
  vaporcode("Lets go to the movies") // output => "L  E  T  S  G  O  T  O  T  H  E  M  O  V  I  E  S"
  vaporcode("Why isn't my code working?") // output => "W  H  Y  I  S  N  '  T  M  Y  C  O  D  E  W  O  R  K  I  N  G  ?"
```
```haskell
  vaporcode "Lets go to the movies"
  -- output => "L  E  T  S  G  O  T  O  T  H  E  M  O  V  I  E  S"
  vaporcode "Why isn't my code working?"
  -- output => "W  H  Y  I  S  N  '  T  M  Y  C  O  D  E  W  O  R  K  I  N  G  ?"
```

def vaporcode(s):
    return "  ".join(s.replace(" ", "").upper())


Solve in Python:
ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but **exactly** 4 digits or exactly 6 digits.

If the function is passed a valid PIN string, return `true`, else return `false`.

## Examples
```
"1234"   -->  true
"12345"  -->  false
"a234"   -->  false
```

def validate_pin(pin):
    return pin.isdecimal() and len(pin) in (4,6)


Solve in Python:
Abhi Ram analyses london stock exchange and invests in a software company C-.gate . He wants to sell his shares after 5 weeks.

Given the investment  m, increase or decrease of share prices of 5 weeks(+/- pi) , help him to calculate his net profit or loss percentage(n%) of his investment to establish his own company KMC.

-----Input:-----

- The first line contains an integer T which denotes the number of test cases.
- Each test case comprises of two lines: the first line contains the integer m which denotes the amount invested.

The second line consists of five space separated integers(p1, p2, p3, p4, p5) each preceeded by + (increase) or - (decrease) which give the percentage of change in share prices over 5 weeks.
.

-----Output:-----
The output contains a single number n which gives the percentage of profit or loss preceeded by + (profit) or - (loss).

-----Constraints:-----
- 1 ≤ T ≤ 100
- 1 ≤ m ≤ 105
- -100 ≤ pi ≤ 100

-----Example:-----
Input:
2
10000
+5 -3 -2 +10 +15
6256250
-24 +22 +4 -16 +20

Output:
+26.2634
-2.79977

for i in range(int(input())):
	 n = int(input())
	 P = list(map(float, input().split()))
	 pr = 1
	 for p in P:
		  a = 100+p
		  pr = (pr*a)/100
	 pr = (pr-1)*100
	 x = 6-len(str(int(abs(pr))))
   	 if (x==1):
   	 	 if (pr==0):
   	 	 	print(0)
		 elif (pr>0):
		 	print("+"+str("%.1f" % round(pr,x)))
		 else:
		 	print(str("%.1f" % round(pr,x)))
	 elif (x==2):
   	 	 if (pr==0):
   	 	 	print(0)
		 elif (pr>0):
		 	print("+"+str("%.2f" % round(pr,x)))
		 else:
		 	print(str("%.2f" % round(pr,x)))
	 elif (x==3):
   	 	 if (pr==0):
   	 	 	print(0)
		 elif (pr>0):
		 	print("+"+str("%.3f" % round(pr,x)))
		 else:
		 	print(str("%.3f" % round(pr,x)))
	 elif (x==4):
   	 	 if (pr==0):
   	 	 	print(0)
		 elif (pr>0):
		 	print("+"+str("%.4f" % round(pr,x)))
		 else:
		 	print(str("%.4f" % round(pr,x)))
	 elif (x==5):
   	 	 if (pr==0):
   	 	 	print(0)
		 elif (pr>0):
		 	print("+"+str("%.5f" % round(pr,x)))
		 else:
		 	print(str("%.5f" % round(pr,x)))
	 elif (x==6):
   	 	 if (pr==0):
   	 	 	print(0)
		 elif (pr>0):
		 	print("+"+str("%.6f" % round(pr,x)))
		 else:
		 	print(str("%.6f" % round(pr,x)))


Solve in Python:
Abhi and his friends (Shanky,Anku and Pandey) love to play with strings. Abhi invented a simple game. He will give a string S to his friends. Shanky and Anku will play the game while Pandey is just a spectator. Shanky will traverse the string from beginning (left to right) while Anku will traverse from last (right to left). Both have to find the first character they encounter during their traversal,that appears only once in the entire string. Winner will be one whose character is alphabetically more superior(has higher ASCII value). When it is not possible to decide the winner by comparing their characters, Pandey will be the winner.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.

Each test case contains a string S having only lowercase alphabets ( a..z ).

-----Output-----
For each test case, output a single line containing "SHANKY" if Shanky is the winner or "ANKU" if Anku is the winner or "PANDEY" if the winner is Pandey. Output your answer without quotes.

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 < |S| ≤ 10^5

-----Example-----
Input:
3
google
breakraekb
aman

Output:
SHANKY
PANDEY
ANKU

-----Explanation-----
Example case 2. Both Shanky and Anku can not find any such character. Hence it is not possible to decide the winner between these two. So Pandey is the winner.

for _ in range(int(input())):
 a = [0]*26
 s = input()
 t = s[::-1]
 for c in s:
  a[ord(c)-ord('a')]+=1
 l = []
 for i in range(26):
  if (a[i]==1):
   l.append(chr(ord('a')+i))
 if (len(l)<=1):
  print("PANDEY")
 else:
  shan = ""
  for c in s:
   if (c in l):
    shan = c
    break
  anku = ""
  for c in t:
   if (c in l):
    anku = c
    break
  if (shan>anku):
   print("SHANKY")
  else:
   print("ANKU")


Solve in Python:
Abhiram needs to search for an antidote. He comes to know that clue for finding the antidote is carefully hidden by KrishnaMurthy in the form of a puzzle.

The puzzle consists of a string S and a keywordK. Abhiram needs to find the string of position of anagrams R of the keyword in the string which is the clue.
The antidote is found in the box numbered R. Help him find his clue R.
Anagram: A word or phrase that is made by arranging the letters of another word or phrase in a different order. Eg: 'elvis' and 'lives' are both anagrams of each other.
Note: Consider, Tac and act are not anagrams(case sensitive).

-----Input:-----
The first line contains a string S of length land the second line contains a keyword K.

-----Output:-----

Output contains a line"The antidote is found in R." Where R= string of positions of anagrams.(the position of the first word in the string is 1).

-----Constraints:-----
1<=l<=500

1<=k<=50

-----Example:-----
Input:
cat is the act of tac
cat

Output:
The antidote is found in 46.

s = input()
k = input()
wrds = s.split(' ')
kl = len(k)
comp = sorted(k)

def ana(an):
 if an == k:
  return False
 return comp == sorted(an)

ans = ''
for x in range(0, len(wrds)):
 word = wrds[x]
 if len(word) == kl and ana(word):
  ans += str(x+1)

print('The antidote is found in %s.' %ans)


Solve in Python:
Abhishek is fond of playing cricket very much. One morning, he is playing cricket with his friends. Abhishek  is a right-hand batsman

.He has to face  all types of balls either good or  bad. There are total 26 balls in the game and each ball is represented

by one of the following two ways:-
1. "g" denotes a good ball.
2. "b" denotes a bad  ball.
All 26 balls are represented by lower case letters (a,b,.....z).
Balls faced by Abhishek are represented as a string s, all the characters of which are lower case  i.e, within  26 above mentioned balls.
A substring s[l...r] (1≤l≤r≤|s|) of string s=s1s2...s|s| (where |s| is the length of string s) is string slsl+1...sr.
The substring s[l...r] is good, if among the letters slsl+1...sr, there are at most k bad ones (refer sample explanation ).
Your task is to find out the number of distinct good substrings for the given string s. Two substrings s[x...y] and s[p...q] are considered distinct if their contents are different, i.e. s[x...y]≠s[p...q].

-----Input Format-----
First Line contains an integer T, number of test cases. For each test case, first line contains a string - a sequence of balls faced by Abhishek.

And, next line contains a string of characters "g" and "b" of length 26 characters. If the ith character of this string equals "1", then the i-th English letter is good, otherwise it's bad. That is, the first character of this string corresponds to letter "a", the second one corresponds to letter "b" and so on.

And, the third line of the test case consists of a single integer k (0≤k≤|s|) — the maximum acceptable number of bad characters in a good substring.

-----Output Format -----
For each test case, print a single integer — the number of distinct good substrings of string s.

-----Constraints-----
- 1<=T<=1000
- 1<=|s|<=2000
- 0<=k<=|s|

-----Subtasks-----
Subtask 1 : 20 Points
- 1<=T<=10
- 1<=|s|<=20
- 0<=k<=|s|
Subtask 2 : 80 Points
Original Constraints
Sample Input
2
ababab
bgbbbbbbbbbbbbbbbbbbbbbbbb
1
acbacbacaa
bbbbbbbbbbbbbbbbbbbbbbbbbb
2
Sample...

import sys
for _ in range(0,eval(input())):
    d,c,inp,mp,n=[],0,sys.stdin.readline().strip(),sys.stdin.readline().strip(),eval(input())
    for i in range(0,len(inp)):
        nn,h=n,0
        for j in range(i,len(inp)):
                if ( (mp[ord(inp[j])-ord('a')]=='g') or  nn>0 ):
                    if((mp[ord(inp[j])-ord('a')]=='g') == False ):
                        nn=nn-1
                    h=(h*256)^ord(inp[j])
                    d+=[h]
                else:
                    break
    print(len(set(d)))


Solve in Python:
Above: An overhead view of the house in one of the tests. The green outline indicates the path taken by K
A mouse named K has found a new home on Ash Tree Lane. K wants to know the size of the interior of the house (which consists of just one room). K is able to measure precise distances in any direction he runs. But K is wary of open spaces and will only run alongside walls, as mice tend to do. In this house the walls always connect at right angles.
K's plan is to run alongside the walls, traversing the entire perimeter of the room, starting and ending at K's mousehole. K memorizes the path as an alternating sequence of distance traveled and directional turn. Your task is to write a function that will find the area of the house interior when given K's path.
Input

Your function will receive a string as an argument. The string will consist of turns (`L` or `R`, for `left` and `right`, respectively) and positive integers, in an alternating sequence. `L`/`R` represents the turn direction made by K, and the integers mark the number of distance units to move forward.

Output

Your function should return an integer representing the area of the house, based on K's path. If K's path is not a valid path, return `null` or `None`.

Invalid Paths

A path is invalid if it meets any of the following criteria:
- the path intersects/overlaps itself (with the exception of the mousehole when completing the loop); see examples of path fragments below
- the path doesn't complete the loop back to the mousehole
- the mousehole is located along the straight path of a wall (K's mousehole must be located at a convex/concave corner position to be valid)

Invalidating overlap path fragment examples

- Example A: Perpendicular intersection `...5L2L3L4...`
- Example B: Point of overlap `...2L2R3R2R3L2...`
- Example C: Parallel overlap `...4L2R2R3R4R1L2...`

Test Example

The circled K and green arrow indicate the starting position and direction as given in the example test below

```python
mouse_path('4R2L1R5R9R4R4L3') #...

import re
O = lambda Q,W,E : W <= Q <= E if W < E else E <= Q <= W
def mouse_path(Q) :
  M,U,D,R,C = [],0,0,0,0
  for Q in re.findall('.\d+','R' + Q) :
    D,Q = D + ('O' < Q or 3),int(Q[1:])
    r,c = [-Q,0,Q,0][D % 4] + R,[0,Q,0,-Q][D % 4] + C
    U += R * c - r * C
    for H,W,h,w in M[:-1] :
      if (R == r) ^ (H == h) :
        if O(R,H,h) and O(W,C,c) if H - h else O(H,R,r) and O(C,W,w) and not 0 == r == c == H == W : return
      elif R == r == H and (O(C,W,w) or O(c,W,w) or O(W,C,c)) or C == c == W and (O(R,H,h) or O(r,H,h) or O(H,R,r)) : return
    M.append((R,C,r,c))
    R,C = r,c
  if 0 == R == C : return abs(U + R - C) / 2


Solve in Python:
Acacius is studying strings theory. Today he came with the following problem.

You are given a string $s$ of length $n$ consisting of lowercase English letters and question marks. It is possible to replace question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulting string exactly once?

Each question mark should be replaced with exactly one lowercase English letter. For example, string "a?b?c" can be transformed into strings "aabbc" and "azbzc", but can't be transformed into strings "aabc", "a?bbc" and "babbc".

Occurrence of a string $t$ of length $m$ in the string $s$ of length $n$ as a substring is a index $i$ ($1 \leq i \leq n - m + 1$) such that string $s[i..i+m-1]$ consisting of $m$ consecutive symbols of $s$ starting from $i$-th equals to string $t$. For example string "ababa" has two occurrences of a string "aba" as a substring with $i = 1$ and $i = 3$, but there are no occurrences of a string "aba" in the string "acba" as a substring.

Please help Acacius to check if it is possible to replace all question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulting string exactly once.

-----Input-----

First line of input contains an integer $T$ ($1 \leq T \leq 5000$), number of test cases. $T$ pairs of lines with test case descriptions follow.

The first line of a test case description contains a single integer $n$ ($7 \leq n \leq 50$), length of a string $s$.

The second line of a test case description contains string $s$ of length $n$ consisting of lowercase English letters and question marks.

-----Output-----

For each test case output an answer for it.

In case if there is no way to replace question marks in string $s$ with a lowercase English letters in such a way that there is exactly one occurrence of a string "abacaba" in the resulting string as a substring output "No".

Otherwise output "Yes" and in the next line output a resulting string consisting of $n$ lowercase English...

check="abacaba"

def compare(s,t):
    res=True
    for i in range(len(s)):
        res&=(s[i]==t[i] or s[i]=="?" or t[i]=="?")
    return res

for _ in range(int(input())):
    n=int(input())
    s=input()
    ans="No"
    res=""
    for i in range(n-6):
        t=s
        test=t[i:i+7]
        if compare(test,check):
            t=s[:i]+check+s[i+7:]
            t=t.replace("?","z")
            count=0
            for j in range(n-6):
                if t[j:j+7]==check:
                    count+=1
            if count==1:
                ans="Yes"
                res=t
    print(ans)
    if ans=="Yes":
        print(res)


Solve in Python:
Accepts a string from the user and print the reverse string as the output without using any built-in function.

-----Input:-----
Each testcase contains of a single line of input, a string.

-----Output:-----
For each testcase, output in a single line answer, the reverse string.

-----Sample Input:-----
1
Tracy

-----Sample Output:-----
ycarT

# cook your dish here
count = input()
for i in range(int(count)):
    stringToConvert = input()
    for i in reversed(range(len(stringToConvert))):
        print(stringToConvert[i],end='')
    print('\n')


Solve in Python:
According to Gary Chapman, marriage counselor and the author of ["The Five Love Languages"](https://en.wikipedia.org/wiki/The_Five_Love_Languages) books, there are five major ways to express our love towards someone: *words of affirmation, quality time, gifts, acts of service,* and *physical touch*. These are called the love languages. Usually, everyone has a main language: the one that he/she "speaks" and understands best. In a relationship, it's import to find your partner's main love language, so that you get along better with each other.

## Your task

Unfortunately, your relationship got worse lately... After a long discussion with your partner, you agreed to give yourself a few weeks to improve it, otherwise you split up...

You will be given a `partner` instance, and `n` weeks. The `partner`  has a `.response` method, and the responses may be: `"positive"` or `"neutral"`. You can try to get a response once a day, thus you have `n * 7` tries in total to find the main love language of your partner!

```if-not:haskell
The love languages are: `"words", "acts", "gifts", "time", "touch"` (available predefined as `LOVE_LANGUAGES`)
```
```if:haskell
The love languages are: `Words, Acts, Gifts, Time, Touch` ( available `Preloaded` as `LoveLanguage` )
```

Note: your partner may (and will) sometimes give a positive response to any love language ("false positive"), but the main one has a much higher possibility. On the other hand, you may get a neutral response even for the main language, but with a low possibility ("false negative").

There will be 50 tests. Although it's difficult to fail, in case you get unlucky, just run the tests again. After all, a few weeks may not be enough...

## Examples

```python
main love language: "words"

partner.response("words") ==> "positive"
partner.response("acts")  ==> "neutral"
partner.response("words") ==> "positive"
partner.response("time")  ==> "neutral"
partner.response("acts")  ==> "positive"    # false positive
partner.response("gifts") ==>...

def love_language(p, w):
    return max(LOVE_LANGUAGES, key=lambda x: sorted(map(p.response, w * [x])))


Solve in Python:
According to ISO 8601, the first calendar week (1) starts with the week containing the first thursday in january.
Every year contains of 52 (53 for leap years) calendar weeks.

**Your task is** to calculate the calendar week (1-53) from a given date.
For example, the calendar week for the date `2019-01-01` (string) should be 1 (int).

Good luck 👍

See also [ISO week date](https://en.wikipedia.org/wiki/ISO_week_date) and [Week Number](https://en.wikipedia.org/wiki/Week#Week_numbering) on Wikipedia for further information about calendar weeks.

On [whatweekisit.org](http://whatweekisit.org/) you may click through the calender and study calendar weeks in more depth.

*heads-up:* `require(xxx)` has been disabled

Thanks to @ZED.CWT, @Unnamed and @proxya for their feedback.


Solve in Python:
Ada is playing pawn chess with Suzumo.
Pawn chess is played on a long board with N$N$ squares in one row. Initially, some of the squares contain pawns.
Note that the colours of the squares and pawns do not matter in this game, but otherwise, the standard chess rules apply:
- no two pawns can occupy the same square at the same time
- a pawn cannot jump over another pawn (they are no knights!), i.e. if there is a pawn at square i$i$, then it can only be moved to square i−2$i-2$ if squares i−1$i-1$ and i−2$i-2$ are empty
- pawns cannot move outside of the board (outs are forbidden)
The players alternate turns; as usual, Ada plays first. In each turn, the current player must choose a pawn and move it either one or two squares to the left of its current position. The player that cannot make a move loses.
Can Ada always beat Suzumo? Remember that Ada is a chess grandmaster, so she always plays optimally.

-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first and only line of each test case contains a single string S$S$ with length N$N$ describing the initial board from left to right. An empty square and a square containing a pawn are denoted by the characters '.' and 'P' respectively.

-----Output-----
For each test case, print a single line containing the string "Yes" if Ada wins the game or "No" otherwise (without quotes).

-----Constraints-----
- 1≤T≤500$1 \le T \le 500$
- 2≤N≤128$2 \le N \le 128$
- S$S$ contains only characters '.' and 'P'

-----Example Input-----
1
..P.P

-----Example Output-----
Yes

-----Explanation-----
Example case 1: Ada can move the first pawn two squares to the left; the board after this move looks like
P...P

and now, Suzumo can only move the second pawn. If he moves it one square to the left, Ada will move it two squares to the left on her next move, and if he moves it two squares to the left, Ada will move it one square to the left, so the board after Ada's next move will...

for _ in range(int(input())):
    s = input().strip()
    a = []
    last = 0
    for i in range(len(s)):
     if s[i] == 'P':
      a.append(i - last)
      last = i + 1
    x = 0
    a = a[::-1]
    for v in a[::2]:
     x ^= v % 3
    print('Yes' if x else 'No')


Solve in Python:
Ada's classroom contains $N \cdot M$ tables distributed in a grid with $N$ rows and $M$ columns. Each table is occupied by exactly one student.
Before starting the class, the teacher decided to shuffle the students a bit. After the shuffling, each table should be occupied by exactly one student again. In addition, each student should occupy a table that is adjacent to that student's original table, i.e. immediately to the left, right, top or bottom of that table.
Is it possible for the students to shuffle while satisfying all conditions of the teacher?

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains two space-separated integers $N$ and $M$.

-----Output-----
For each test case, print a single line containing the string "YES" if it is possible to satisfy the conditions of the teacher or "NO" otherwise (without quotes).

-----Constraints-----
- $1 \le T \le 5,000$
- $2 \le N, M \le 50$

-----Example Input-----
2
3 3
4 4

-----Example Output-----
NO
YES

-----Explanation-----
Example case 2: The arrows in the following image depict how the students moved.

# cook your dish herefor _ in range(int(input())):
for _ in range(int(input())):
 x,y=list(map(int,input().split()))
 print("NO" if x*y%2 else "YES")


Solve in Python:
Adapted from here, with less terrible instructions and a couple tweaks.

Two kangaroos are jumping on a line. They start out at different points on the line, and jump in the same direction at different speeds. Your task is to determine whether or not they'll ever land in the same spot at the same time (you'll just have to suspend disbelief for a moment and accept that two kangaroos, for the purpose of this kata, can occupy the same space at the same time :)

Your function is given four arguments `(kanga1, rate1, kanga2, rate2)`; the first kangaroo's starting point, the first kangaroo's speed, the second kangaroo's starting point, and the second kangaroo's speed.

Return `true` if the above conditions are met, else `false`. Starting location and speed may vary wildly. The first kangaroo will _usually_ start behind the second one and travel faster, but not always. Starting locations may be negative, but speeds will always be > 0.

**Example:**
![kangaroo](https://i.imgur.com/hXRgSVg.jpg)

**Other examples:**

Brute force solutions are possible (and not discouraged), but you'll save yourself a lot of waiting time if you don't go that route :)

Good luck!

def kangaroo(kanga1, rate1, kanga2, rate2):
    if rate1 == rate2: return kanga1 == kanga2
    time_ = (kanga2 - kanga1) / (rate1 - rate2)
    return time_ > 0 and time_.is_integer()


Solve in Python:
Adding tip to a restaurant bill in a graceful way can be tricky, thats why you need make a function for it.

The function will receive the restaurant bill (always a positive number) as an argument. You need to 1) **add at least 15%** in tip, 2) round that number up to an *elegant* value and 3) return it.

What is an *elegant* number? It depends on the magnitude of the number to be rounded. Numbers below 10 should simply be rounded to whole numbers. Numbers 10 and above should be rounded like this:

10 - 99.99... ---> Round to number divisible by 5

100 - 999.99... ---> Round to number divisible by 50

1000 - 9999.99... ---> Round to number divisible by 500

And so on...

Good luck!

## Examples
```
 1  -->    2
 7  -->    9
12  -->   15
86  -->  100
```

from math import ceil

def graceful_tipping(bill):
    total = bill * 1.15
    if total < 10:
        return ceil(total)
    total /= 5
    d = 0
    while total >= 20:
        d += 1
        total /= 10
    return ceil(total) * 5 * 10**d


Solve in Python:
After Misha's birthday he had many large numbers left, scattered across the room. Now it's time to clean up and Misha needs to put them in a basket. He ordered this task to his pet robot that agreed to complete the task at certain conditions. Before the robot puts a number x to the basket, Misha should answer the question: is it possible to choose one or multiple numbers that already are in the basket, such that their XOR sum equals x?

If the answer is positive, you also need to give the indexes of these numbers. If there are multiple options of choosing numbers, you are allowed to choose any correct option. After Misha's answer the robot puts the number to the basket.

Initially the basket is empty. Each integer you put in the basket takes some number. The first integer you put into the basket take number 0, the second integer takes number 1 and so on.

Misha needs to clean up the place as soon as possible but unfortunately, he isn't that good at mathematics. He asks you to help him.

-----Input-----

The first line contains number m (1 ≤ m ≤ 2000), showing how many numbers are scattered around the room.

The next m lines contain the numbers in the order in which the robot puts them in the basket. Each number is a positive integer strictly less than 10^600 that doesn't contain leading zeroes.

-----Output-----

For each number either print a 0 on the corresponding line, if the number cannot be represented as a XOR sum of numbers that are in the basket, or print integer k showing how many numbers are in the representation and the indexes of these numbers. Separate the numbers by spaces. Each number can occur in the representation at most once.

-----Examples-----
Input
7
7
6
5
4
3
2
1

Output
0
0
0
3 0 1 2
2 1 2
2 0 2
2 0 1

Input
2
5
5

Output
0
1 0

-----Note-----

The XOR sum of numbers is the result of bitwise sum of numbers modulo 2.

n = int(input())
b = []
bb =[]
for i in range(n):
    x=int(input())
    idx = 0
    for j in range(len(b)):
        nxt = b[j] ^ x
        if nxt < x :
            x = nxt
            idx ^= bb[j]
    if x == 0:
        cnt = 0
        v = []
        for k in range(2000):
            if idx & (1 << k) :
                v.append(k)
        print(len(v),end=' ')
        for e in v:
            print(e,end=' ')
        print()
    else :
        print(0)
        idx ^= 1 << i
        b.append(x)
        bb.append(idx)


Solve in Python:
After a hard quarter in the office you decide to get some rest on a vacation. So you will book a flight for you and your girlfriend and try to leave all the mess behind you.

You will need a rental car in order for you to get around in your vacation. The manager of the car rental makes you some good offers.

Every day you rent the car costs $40. If you rent the car for 7 or more days, you get $50 off your total. Alternatively, if you rent the car for 3 or more days, you get $20 off your total.

Write a code that gives out the total amount for different days(d).

def rental_car_cost(d):
    total = d * 40
    if 3 <= d < 7: total -= 20
    if 7 <= d: total -= 50
    return total


Solve in Python:
After a long and successful day of preparing food for the banquet, it is time to clean up. There is a list of n jobs to do before the kitchen can be closed for the night. These jobs are indexed from 1 to n.

Most of the cooks have already left and only the Chef and his assistant are left to clean up. Thankfully, some of the cooks took care of some of the jobs before they left so only a subset of the n jobs remain. The Chef and his assistant divide up the remaining jobs in the following manner. The Chef takes the unfinished job with least index, the assistant takes the unfinished job with the second least index, the Chef takes the unfinished job with the third least index, etc. That is, if the unfinished jobs were listed in increasing order of their index then the Chef would take every other one starting with the first job in the list and the assistant would take every other one starting with the second job on in the list.

The cooks logged which jobs they finished before they left. Unfortunately, these jobs were not recorded in any particular order. Given an unsorted list
of finished jobs, you are to determine which jobs the Chef must complete and which jobs his assitant must complete before closing the kitchen for the
evening.

-----Input-----

The first line contains a single integer T ≤ 50 indicating the number of test cases to follow. Each test case consists of two lines. The first line contains two numbers n,m satisfying 0 ≤ m ≤ n ≤ 1000. Here, n is the total number of jobs that must be completed before closing and m is the number of jobs that have already been completed. The second line contains a list of m distinct integers between 1 and n. These are the indices of the jobs that have already been completed. Consecutive integers are separated by a single space.

-----Output-----

The output for each test case consists of two lines. The first line is a list of the indices of the jobs assigned to the Chef. The second line is a list of the indices of the jobs assigned to his assistant. Both lists must...

# cook your dish here
for _ in range(int(input())):
 n,m=map(int,input().split())
 lm=[int(item) for item in input().split()]
 l=[item for item in range(1,n+1)]
 for i in lm:
  l.remove(i)
 l.sort()
 list_chef=list()
 list_assistant=list()
 for i in range(0,len(l),2):
  list_chef.append(l[i])
 for i in range(1,len(l),2):
  list_assistant.append(l[i])
 print(*list_chef)
 print(*list_assistant)


Solve in Python:
After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are $n$ crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.

The crossroads are represented as a string $s$ of length $n$, where $s_i = \texttt{A}$, if there is a bus station at $i$-th crossroad, and $s_i = \texttt{B}$, if there is a tram station at $i$-th crossroad. Currently Petya is at the first crossroad (which corresponds to $s_1$) and his goal is to get to the last crossroad (which corresponds to $s_n$).

If for two crossroads $i$ and $j$ for all crossroads $i, i+1, \ldots, j-1$ there is a bus station, one can pay $a$ roubles for the bus ticket, and go from $i$-th crossroad to the $j$-th crossroad by the bus (it is not necessary to have a bus station at the $j$-th crossroad). Formally, paying $a$ roubles Petya can go from $i$ to $j$ if $s_t = \texttt{A}$ for all $i \le t < j$.

If for two crossroads $i$ and $j$ for all crossroads $i, i+1, \ldots, j-1$ there is a tram station, one can pay $b$ roubles for the tram ticket, and go from $i$-th crossroad to the $j$-th crossroad by the tram (it is not necessary to have a tram station at the $j$-th crossroad). Formally, paying $b$ roubles Petya can go from $i$ to $j$ if $s_t = \texttt{B}$ for all $i \le t < j$.

For example, if $s$="AABBBAB", $a=4$ and $b=3$ then Petya needs:[Image]  buy one bus ticket to get from $1$ to $3$,  buy one tram ticket to get from $3$ to $6$,  buy one bus ticket to get from $6$ to $7$.

Thus, in total he needs to spend $4+3+4=11$ roubles. Please note that the type of the stop at the last crossroad (i.e. the character $s_n$) does not affect the final expense.

Now Petya is at the first crossroad, and he wants to get to the $n$-th crossroad. After the party he has left with $p$ roubles. He's decided to go to some station on foot, and then go to home using only public transport.

Help him to choose the closest crossroad $i$ to go on foot the first, so he has...

for _ in range(int(input())):
    a, b, p = map(int, input().split())
    s = input()

    d = {'A': a, 'B': b}

    c = '0'
    inv = []
    start = 0
    for i in range(1, len(s)):
        if s[i] != s[i-1]:
            inv.append((start, i, s[i-1]))
            start = i
        elif i == len(s) - 1:
            inv.append((start, i, s[i]))

    ans, cost = len(s) - 1, 0
    for q in inv[::-1]:
        cost += d[q[2]]
        if cost > p:
            break
        else:
            ans = q[0]

    print(ans + 1)


Solve in Python:
After a wonderful evening in the restaurant the time to go home came. Leha as a true gentlemen suggested Noora to give her a lift. Certainly the girl agreed with pleasure. Suddenly one problem appeared: Leha cannot find his car on a huge parking near the restaurant. So he decided to turn to the watchman for help.

Formally the parking can be represented as a matrix 10^9 × 10^9. There is exactly one car in every cell of the matrix. All cars have their own machine numbers represented as a positive integer. Let's index the columns of the matrix by integers from 1 to 10^9 from left to right and the rows by integers from 1 to 10^9 from top to bottom. By coincidence it turned out, that for every cell (x, y) the number of the car, which stands in this cell, is equal to the minimum positive integer, which can't be found in the cells (i, y) and (x, j), 1 ≤ i < x, 1 ≤ j < y. $\left. \begin{array}{|l|l|l|l|l|} \hline 1 & {2} & {3} & {4} & {5} \\ \hline 2 & {1} & {4} & {3} & {6} \\ \hline 3 & {4} & {1} & {2} & {7} \\ \hline 4 & {3} & {2} & {1} & {8} \\ \hline 5 & {6} & {7} & {8} & {1} \\ \hline \end{array} \right.$ The upper left fragment 5 × 5 of the parking

Leha wants to ask the watchman q requests, which can help him to find his car. Every request is represented as five integers x_1, y_1, x_2, y_2, k. The watchman have to consider all cells (x, y) of the matrix, such that x_1 ≤ x ≤ x_2 and y_1 ≤ y ≤ y_2, and if the number of the car in cell (x, y) does not exceed k, increase the answer to the request by the number of the car in cell (x, y). For each request Leha asks the watchman to tell him the resulting sum. Due to the fact that the sum can turn out to be quite large, hacker asks to calculate it modulo 10^9 + 7.

However the requests seem to be impracticable for the watchman. Help the watchman to answer all Leha's requests.

-----Input-----

The first line contains one integer q (1 ≤ q ≤ 10^4) — the number of Leha's requests.

The next q lines contain five integers x_1, y_1, x_2, y_2, k (1 ≤ x_1 ≤ x_2 ≤ 10^9, 1 ≤...

mod = 1000000007
def sum(x,y,k,add) :
    if k<add:return 0
    up=x+add
    if up>k:up=k
    add=add+1
    return y*(((add+up)*(up-add+1)//2)%mod)%mod
def solve(x,y,k,add=0) :
    if x==0 or y==0:return 0
    if x>y:x,y=y,x
    pw = 1
    while (pw<<1)<=y:pw<<=1
    if pw<=x:return (sum(pw,pw,k,add)+sum(pw,x+y-pw-pw,k,add+pw)+solve(x-pw,y-pw,k,add))%mod
    else:return (sum(pw,x,k,add)+solve(x,y-pw,k,add+pw))%mod
q=int(input())
for i in range(0,q):
    x1,y1,x2,y2,k=list(map(int,input().split()))
    ans=(solve(x2, y2, k)-solve(x1 - 1, y2, k)-solve(x2, y1 - 1, k)+solve(x1-1,y1-1,k))%mod
    if ans<0:ans+=mod
    print(ans)


Solve in Python:
After acquiring an extraordinary amount of knowledge through programming contests, Malvika decided to harness her expertise to train the next generation of Indian programmers. So, she decided to hold a programming camp. In the camp, she held a discussion session for n members (n-1 students, and herself). They are sitting in a line from left to right numbered through 1 to n.

Malvika is sitting in the nth spot. She wants to teach m topics of competitive programming to the students. As the people taking part in the camp are all newbies, they know none of the topics being taught, i.e., initially, the first n - 1 people in the line know none of the topics, while the nth knows all of them.

It takes one hour for a person to learn a topic from his neighbour. Obviously, one person cannot both teach a topic as well as learn one during the same hour. That is, in any particular hour, a person can either teach a topic that he knows to one of his neighbors, or he can learn a topic from one of his neighbors, or he can sit idly. It is also obvious that if person x is learning from person y at a particular hour, then person y must be teaching person x at that hour.

Also, note that people can work parallely too, i.e., in the same hour when the 4th person is teaching the 3rd person, the 1st person can also teach the 2nd or learn from 2nd.

Find out the minimum number of hours needed so that each person learns all the m topics.

-----Input-----
- The first line of input contains a single integer T denoting number of test cases.
- The only line of each test case contains two space separated integers n, m as defined in the statement.

-----Output-----
- For each test case, output a single integer in a line corresponding to the answer of the problem.

-----Constraints-----
- 1 ≤ T, n, m ≤ 100

-----Example-----
Input:
2
2 1
3 2

Output:
1
4

-----Explanation-----
In the first example, there are two people. Second person is Malvika and she has to teach only one topic to the first person. It will take only one hour to do so.

In...

for i in range(int(input())):
 n,m=list(map(int,input().split()))
 if(n==1):
  print(0)
  continue
 if(n==2):
  print(m)
  continue
 ans=(n-1)+2*(m-1)
 print(ans)


Solve in Python:
After completing some serious investigation, Watson and Holmes are now chilling themselves in the Shimla hills. Very soon Holmes became bored. Holmes lived entirely for his profession. We know he is a workaholic. So Holmes wants to stop his vacation and get back to work. But after a tiresome season, Watson is in no mood to return soon. So to keep Holmes engaged, he decided to give Holmes one math problem. And Holmes agreed to solve the problem and said as soon as he solves the problem, they should return back to work. Watson too agreed.
The problem was as follows. Watson knows Holmes’ favorite numbers are 6 and 5. So he decided to give Holmes N  single digit numbers. Watson asked Holmes to form a new number with the given N numbers in such a way that the newly formed number should be completely divisible by 5 and 6. Watson told Holmes that he should also form the number from these digits in such a way that the formed number is maximum. He may or may not use all the given numbers. But he is not allowed to use leading zeros. Though he is allowed to leave out some of the numbers, he is not allowed to add any extra numbers, which means the maximum count of each digit in the newly formed number, is the same as the number of times that number is present in those given N digits.

-----Input-----
The first line of input contains one integers T denoting the number of test cases.
Each test case consists of one integer N, number of numbers.
Next line contains contains N single digit integers

-----Output-----
For each test case output a single number, where the above said conditions are satisfied. If it is not possible to create such a number with the given constraints print -1.If there exists a solution, the maximised number should be greater than or equal to 0.

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 10000
- 0 ≤ Each digit ≤ 9

-----Subtasks-----
Subtask #1 : (90 points)
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 10000

Subtask 2 : (10 points)

- 1 ≤ T ≤ 10
- 1 ≤ N≤ 10

-----Example-----
Input:
2
12
3 1 2 3 2 0 2 2 2 0 2...

def qsort(inlist):
 if inlist == []:
  return []
 else:
  pivot = inlist[0]
  lesser = qsort([x for x in inlist[1:] if x < pivot])
  greater = qsort([x for x in inlist[1:] if x >= pivot])
  return lesser + [pivot] + greater
def mul3(ip):
 q0=[]
 q1=[]
 q2=[]
 qsort(ip)
 sums=sum(ip)
 for i in ip:
  if (i % 3) == 0:
   q0.insert(0,i)
  if (i % 3) == 1:
   q1.insert(0,i)
  if (i % 3) == 2:
   q2.insert(0,i)
 if(sums%3==1):
  if(len(q1)):
   q1.pop()
  elif(len(q2)>=2):
   q2.pop()
   q2.pop()
  else:
   return -1
 elif(sums%3==2):
  if(len(q2)):
   q2.pop()
  elif(len(q1)>=2):
   q1.pop()
   q1.pop()
  else:
   return -1

 q0.extend(q1)
 q0.extend(q2)
 if(len(q0)<=0):
  return -1
 q0.sort()
 q0.reverse()
 return q0

t = int(input())
for z in range(t):
 n = int(input())
 a = list(map(int, input().split()))
 if 0 not in a or mul3(a)==-1:
  print(-1)
 else:
  out=''
  temp = mul3(a)
  for p in temp:
   out+=str(p)
  print(out)


Solve in Python:
After failing to clear his school mathematics examination, infinitepro decided to prepare very hard for his upcoming re-exam, starting with the topic he is weakest at ― computational geometry.
Being an artist, infinitepro has C$C$ pencils (numbered 1$1$ through C$C$); each of them draws with one of C$C$ distinct colours. He draws N$N$ lines (numbered 1$1$ through N$N$) in a 2D Cartesian coordinate system; for each valid i$i$, the i$i$-th line is drawn with the ci$c_i$-th pencil and it is described by the equation y=ai⋅x+bi$y = a_i \cdot x + b_i$.
Now, infinitepro calls a triangle truly-geometric if each of its sides is part of some line he drew and all three sides have the same colour. He wants to count these triangles, but there are too many of them! After a lot of consideration, he decided to erase a subset of the N$N$ lines he drew. He wants to do it with his eraser, which has length K$K$.
Whenever erasing a line with a colour i$i$, the length of the eraser decreases by Vi$V_i$. In other words, when the eraser has length k$k$ and we use it to erase a line with a colour i$i$, the length of the eraser decreases to k−Vi$k-V_i$; if k<Vi$k < V_i$, it is impossible to erase such a line.
Since infinitepro has to study for the re-exam, he wants to minimise the number of truly-geometric triangles. Can you help him find the minimum possible number of truly-geometric triangles which can be obtained by erasing a subset of the N$N$ lines in an optimal way? He promised a grand treat for you if he passes the examination!

-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of the input contains three space-separated integers N$N$, C$C$ and K$K$.
- N$N$ lines follow. For each i$i$ (1≤i≤N$1 \le i \le N$), the i$i$-th of these lines contains three space-separated integers ai$a_i$, bi$b_i$ and ci$c_i$.
- The last line contains C$C$ space-separated integers V1,V2,…,VC$V_1, V_2, \ldots,...

for x in range(int(input())):
  if(x == 6):
    n,c,kost = map(int, input().split())
    parallel = [{} for _ in range(c)]
    for _ in range(n):
        a,b,d = map(int, input().split())
        if(a in parallel[d-1]):
            parallel[d-1][a] += 1
        else:
            parallel[d-1][a] = 1

    v = list(map(int, input().split()))

    newparalle = [list(parallel[i].values()) for i in range(c)]
    pc = []
    for i in range(c):
        pc.append(len(parallel[i]))
        newparalle[i].sort()
    sumlekerakho = [sum(newparalle[i]) for i in range(c)]

    merasum = 0
    for i in range(c):
        vaah = sumlekerakho[i]
        ape = vaah * (vaah-1) * (vaah-2) // 6
        for ke in range(pc[i]):
            ape -= (newparalle[i][ke]) * (newparalle[i][ke]-1) * (vaah-newparalle[i][ke]) // 2
            if(newparalle[i][ke]>=3):
                ape -= newparalle[i][ke] * (newparalle[i][ke]-1) * (newparalle[i][ke]-2) // 6
        merasum += ape

    dp = [0 for _ in range(kost+1)]

    superlist = [[] for _ in range(c)]
    for i in range(c):
        sumsum = sumlekerakho[i]
        for k in range(sumsum):
            if(max(newparalle[i]) < (sumsum-k)/2):
                maxindex = newparalle[i].index(min(newparalle[i]))
            else:
                prod = (k-sumsum)*(sumsum-k) // 4 - 1
                for ke,item in enumerate(newparalle[i]):
                    if(prod < (item)*(item-sumsum+k) and item!=0):
                        prod = (item)*(item-sumsum+k)
                        maxindex = ke
            ape = (sumsum-k-newparalle[i][maxindex])*(sumsum-k-newparalle[i][maxindex]-1) // 2
            for ke,item in enumerate(newparalle[i]):
                ape -= (item)*(item-1)//2
            ape += newparalle[i][maxindex] * (newparalle[i][maxindex]-1) // 2
            superlist[i].append(ape)
            newparalle[i][maxindex] -= 1
            if(newparalle[i][maxindex]<=0):
               ...


Solve in Python:
After fixing the mercury leak, Kim has arrived in the planning room, where he finds a square map of a field, with $N$ rows and $N$ columns. Each cell in the field is either empty, or has a lookout tower on it. Using his notes, he immediately realises that this field is where the JSA will build their new base!
Kim knows that Soum is a fan of symmetric base design, and will only approve of a base to be built if it is square. Furthermore, Soum also requires that all the rows in the base, and all the columns in the base have exactly one tower square in them.
This means that a base plan is valid if and only if:
- It is square in shape
- Every row in the base has exactly one lookout tower in it.
- Every column in the base has exactly one lookout tower in it.
Kim notices that all the rows and all the columns in the field have exactly one tower square in them, but he knows that some of them could have been built to throw him off! Can you help Kim find how many valid base plans are possible in this field? Two base plans are considered different if one contains a cell in the grid that the other does not.
Please refer to the samples for more details.

-----Input:-----
- The first line of input contains $T$, the number of testcases.
- The first line of each testcase contains a single integer, $N$, representing the side length of the field.
- The next $N$ lines of each testcase contain a string of length $N$, consisting of only 0 and 1. If position $j$ in string $i$ is 0, it means that this the field has no tower at $[i][j]$, and if it is 1, then this cell does have a tower at $[i][j]$.
It is guaranteed that every row in the input will have exactly one tower, and every column in the input will also have exactly one tower.

-----Output:-----
For each testcase, output a single integer $K$, representing the number of different base plans possible.

-----Subtasks-----
- For all subtasks, $N \leq 2500$ and $T \leq 10$.
- In addition, the sum of $N$ in any testfile is at most $2500$.
Subtask 1 [28 points] : All the towers...

T=int(input())
for i in range(0,T):
    lst2=[]
    N=int(input())
    for j in range(0,N):
        lst=input()
        lst2.append(lst)
    print(int(N*(N+1)/2))


Solve in Python:
After learning a lot about space exploration, a little girl named Ana wants to change the subject.

Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:

You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").

Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $(i,j)$ is considered the same as the pair $(j,i)$.

-----Input-----

The first line contains a positive integer $N$ ($1 \le N \le 100\,000$), representing the length of the input array.

Eacg of the next $N$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array.

The total number of characters in the input array will be less than $1\,000\,000$.

-----Output-----

Output one number, representing how many palindrome pairs there are in the array.

-----Examples-----
Input
3
aa
bb
cd

Output
1

Input
6
aab
abcac
dffe
ed
aa
aade

Output
6

-----Note-----

The first example:  aa $+$ bb $\to$ abba.

The second example:  aab $+$ abcac $=$ aababcac $\to$ aabccbaa aab $+$ aa $=$ aabaa abcac $+$ aa $=$ abcacaa $\to$ aacbcaa dffe $+$ ed $=$ dffeed $\to$ fdeedf dffe $+$ aade $=$ dffeaade $\to$ adfaafde ed $+$ aade $=$ edaade $\to$ aeddea

def main():
    n = int(input())
    ans = 0
    d = {}
    for i in range(n):
        s = input()
        cur = 0
        for c in s:
            cur ^= (1 << (ord(c) - ord('a')))
        ans += d.get(cur, 0)
        for j in range(26):
            ans += d.get(cur ^ (1 << j), 0)
        t = d.get(cur, 0) + 1
        d[cur] = t
    print(ans)
    return

def __starting_point():
    main()
__starting_point()


Solve in Python:
After six days, professor GukiZ decided to give more candies to his students. Like last time, he has $N$ students, numbered $1$ through $N$. Let's denote the number of candies GukiZ gave to the $i$-th student by $p_i$. As GukiZ has a lot of students, he does not remember all the exact numbers of candies he gave to the students. He only remembers the following properties of the sequence $p$:
- The numbers of candies given to each of the first $K$ students ($p_1, p_2, \dots, p_K$) are known exactly.
- All elements of the sequence $p$ are distinct and positive.
- GukiZ didn't give more than $x$ candies to any student (the maximum value in the sequence $p$ is not greater than $x$).
- For each student $i$, there is at least one other student $j$ such that $|p_i - p_j| \le D$.
- The professor gave out the biggest possible total number of candies, i.e. $S = p_1 + p_2 + p_3 + \ldots + p_N$ is maximum possible.
GukiZ would like to know the total number of candies $S$ he had at the beginning. However, times change and after six days, the professor is really tired, so it is possible that there is no sequence $p$ which satisfies the constraints. Can you help GukiZ find the number of candies he gave out, or tell him that he must have made a mistake?

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains four space-separated integers $N$, $K$, $x$, $D$.
- The second line contains $K$ distinct space-separated integers $p_1, p_2, \dots, p_K$.

-----Output-----
For each test case, print a single line containing one integer — the number of candies GukiZ had, or $-1$ if there is no valid sequence $p$.

-----Constraints-----
- $1 \le T \le 50$
- $3 \le N \le 10^9$
- $1 \le K \le \mathrm{min}(N, 2 \cdot 10^4)$
- $1 \le x \le 2 \cdot 10^9$
- $1 \le D \le 10^9$
- $1 \le p_i \le x$ for each valid $i$
- All values $p_i$ from input are distinct

-----Subtasks-----
Subtask #1 (15 points): $1...

try:
# https://www.codechef.com/LTIME63B/problems/GHMC
# Finally.... I properly understood what needs to be done.

    def ctlt(arr, val):
        # find number of values in sorted arr < val
        if arr[0] >= val: return 0
        lo = 0
        hi = len(arr)
        while hi-lo > 1:
            md = (hi+lo)//2
            if arr[md]<val:
                lo = md
            else:
                hi = md

        return hi

    for _ in range(int(input())):
        n,k,x,d = map(int, input().split())
        z = input().strip().split()
        if k > 0:
            ps = list(map(int,z[:k]))
        else:
            ps = [x]

        ps.sort()

        if x<n or x<ps[-1] or n<k:
            print(-1)
            continue

        valchecked = 0
        fillval = 0
        valsdone = False
        isolbelow = True
        lastp = ps[0]

        while not valsdone and n>=k:
            if n == k:
                lo = x+d+1 # put out of range
            else:
            # find best maxfill (before val support)
                lo = 1
                hi = x+1
                while hi-lo>1:
                    md = (hi+lo)//2
                    v = (x-md+1) + ctlt(ps,md)
                    if v<n:
                        hi = md
                    else:
                        lo = md

            valsdone = True
            checkto = ctlt(ps,lo)-1
            if checkto >= valchecked:
            # support all vals
                for p in ps[valchecked+1:checkto+1]:
                    if lastp+d >= p:
                        isolbelow = False
                    elif isolbelow:
                        valsdone = False
                        fillval += lastp+d
                        n -= 1
                        isolbelow = (p > lastp + 2*d )
                    else:
                        isolbelow = True
                    lastp = p
                valchecked = checkto
                if valsdone and isolbelow:
                # check gap to maxfill
                    if lastp...


Solve in Python:
After the death of their mother, Alphonse and Edward now live with Pinako and Winry.

Pinako is worried about their obsession with Alchemy, and that they don't give attention to their studies.
So to improve their mathematical solving ability, every day she gives a mathematical problem to solve. They can go out to practice Alchemy only after they have solved the problem.
Help them by solving the given problem, so that they can go early today for their Alchemy practice.
Given an array A$A$ of N$N$ non-negative integers and two integers K$K$ and M$M$. Find the number of subsequences of array A$A$ of length K$K$ which satisfies the following property:

Suppose the subsequence is S=S1S2…SK$S = S_1S_2 \ldots S_K$, then for all i$i$ such that 1≤i≤K$1 \leq i \leq K$,
Si%M=i%M S_i \% M = i \% M
should hold true, where Si$S_i$ denotes the i$i$-th element of the subsequence, using 1-based indexing.
As the number of subsequences may be very large, output the answer modulo 1000000007$1000000007$.
PS: We also proposed the idea of making a look-alike clone through alchemy and keeping it in front of the study table. But it seems impossible to convince Edward to make a clone of his exact same height, and not taller than him. So solving the problem for him was a better choice.

-----Input:-----
- The first line contains T$T$, the number of test cases. Then the test cases follow.
- For every test case, the first line contains N$N$, K$K$ and M$M$.
- For every test case, the second line contains N$N$ integers Ai$A_{i}$ ( 1≤i≤N$1 \leq i \leq N$).

-----Output:-----
For every test case, output in a single line an integer denoting the number of valid subsequences modulo 109+7$10^9+7$

-----Constraints-----
- 1≤T≤100$1 \leq T \leq 100$
- 1≤N≤104$1 \leq N \leq 10^{4}$
- 1≤K≤N$1 \leq K \leq N$
- ⌈K100⌉≤M≤100×K$\lceil \frac{K}{100}\rceil \leq M \leq  100\times K$
- 0≤Ai≤109$0 \leq A_{i} \leq 10^{9}$

-----Sample Input:-----
1
12 4 3
4 5 6 7 1 4 6 9 0 0 10 2

-----Sample Output:-----
8

-----Explanation:-----
The...

def modinv(v,m):
    v %= m
    pv = m
    pc = 0
    c = 1
    while v > 0:
     q, a = divmod(pv, v)
     pc, c = c, pc-q*c
     pv, v = v, a
    return pc % m

def binmod(n,r,m):
    if 2*r > n: r = n - r
    if r < 0: return 0
    if r == 0: return 1
    tp = 1
    bm = 1
    for t in range(1, r+1):
     bm = bm*t%m
     tp = tp*(n+1-t)%m
    return (tp*modinv(bm,m))%m

MVAL = 1000000007
for ti in range(int(input())):
    n,k,m = map(int,input().split())
    ays = list(map(int,input().split()))


Solve in Python:
After the hundred years of war started by the Fire Nation, its time for the Water Tribes to bring it to an end. Avatar asked Sokka to go to the Southern WarZone from The Northern WarZone and gave him some money in a bag for his journey. Sokka has the World Map to guide him during his journey . The World Map is described as a $N$x$N$ grid where the Northern WarZone is denoted by $(0,0)$ and the Southern WarZone is denoted by $(N-1,N-1)$. Each location on the world map is denoted in a similar way by two integers r and c. For each location having:
- $r = c$ denotes neutral land ( $(0,0)$ and $(N-1,N-1)$ also come under this category)
- $r < c$ denotes the land under the rule of Water Tribes
- $r > c$ denotes the land under the rule of Fire Kingdom
Being wise Sokka travels only from one location to any other valid location (by valid location we mean a location which exists on the world map grid i.e. for that location $0 \leq r < N$ and $0 \leq c < N$ ) just to the right $(r,c+1)$ or below $(r+1,c)$ the current location randomly. Due to the times of war , Sokka has to pay one coin  each time he transitions from one nation to another. Here a transition is counted when Sokka is in Water Tribe land and moves to Fire Nation Land crossing the neutral land or vice versa .The first move is obviously never counted as a transition. Moreover , the coin is to be payed exactly once for one such transition (eg. if he makes this transition k times he has to pay k coins).
The initial number of coins Sokka has is $2*N$. The probability that the coins he has when he reaches his destination is lesser than the number of coins he started his journey with can be expressed as a fraction $P/Q$, where P and Q are integers $(P \geq 0, Q > 0)$  and Q is co-prime with $(10^9)+7$. You should compute $P/Q$ modulo $(10^9)+7$ for $T$ values of $N$.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, one integer $N$, the size of...

m=1000000007
def gcd(a, b):
    if (a == 0):
        return b
    return gcd(b % a, a)
def modexp(x, n):
    if (n == 0) :
        return 1
    elif (n % 2 == 0) :
        return modexp((x * x) % m, n // 2)
    else :
        return (x * modexp((x * x) % m,
                           (n - 1) / 2) % m)
def getFractionModulo(a, b):
    c = gcd(a, b)
    a = a // c
    b = b // c
    d = modexp(b, m - 2)
    ans = ((a % m) * (d % m)) % m
    return ans
t=int(input())
for i in range(t):
    n=int(input())
    n=n-1
    print(getFractionModulo(n-1,n+1))


Solve in Python:
Ahmed Gafer failed to pass the test, but he got the job because of his friendship with Said and Shahhoud. After working in the kitchen for a while, he blew it. The customers didn't like the food anymore and one day he even burned the kitchen. Now the master Chef is very upset.
Ahmed isn't useful anymore at being a co-Chef, so S&S decided to give him a last chance. They decided to give Ahmed a new job, and make him work as the cashier of the restaurant. Nevertheless, in order not to repeat their previous mistake, they decided to give him a little test to check if his counting skills are good enough for the job. The problem is as follows:
Given a string A of lowercase English letters, Ahmad was asked to find the number of good substrings.
A substring A[L, R] is good if:

-  The length of the substring is exactly 2 and AL = AR, OR
- The length of the substring is greater than 2,AL = AR and the substring A[L + 1, R - 1] has only one distinct letter.

Anyways, Ahmed struggled trying to find a solution for the problem. Since his mathematical skills are very poor as it turned out, he decided to cheat and contacted you asking for your help. Can you help him in this challenge?

-----Input-----
The first line of the input contains the integer T, indicating the number of test cases.
Each of the following T lines, contains a string A.

-----Output-----
For each test case, output a single line containing a single number, indicating the number of good substrings.

-----Constraints-----

- 1 ≤ T ≤ 100
- 1 ≤  |A|  ≤ 105
-  It's guaranteed that the sum of  |A|  over all test cases doesn't exceed 5x105.

-----Example-----
Input:
2
a
abba

Output:
0
2

-----Explanation-----
Example case 2. The good substrings of abba are: { bb } and { abba }.

# cook your dish here
for _ in range(int(input())):
 s=input()
 count=0
 i=0
 while i<len(s)-1:
  ch=s[i]
  j=i+1
  while j<len(s) and s[j]==ch:
   j+=1
  l=j-i
  if i!=0 and j!=len(s) and s[i-1]==s[j] :
   count+=1
  count+=l*(l-1)//2
  #print(s[i:j],count)
  i=j
 print(count)


Solve in Python:
Ahoy Matey!

Welcome to the seven seas.

You are the captain of a pirate ship.

You are in battle against the royal navy.

You have cannons at the ready.... or are they?

Your task is to check if the gunners are loaded and ready, if they are: ```Fire!```

If they aren't ready: ```Shiver me timbers!```

Your gunners for each test case are 4 or less.

When you check if they are ready their answers are in a dictionary and will either be: ```aye``` or ```nay```

Firing with less than all gunners ready is non-optimum (this is not fire at will, this is fire by the captain's orders or walk the plank, dirty sea-dog!)

If all answers are 'aye' then Fire!
if one or more are 'nay' then Shiver me timbers!

Also, check out the new Pirates!! Kata:
https://www.codewars.com/kata/57e2d5f473aa6a476b0000fe

def cannons_ready(gunners):
    fire = {v: k for k, v in gunners.items()}
    z = fire.get('nay')
    return 'Fire!'if not z else 'Shiver me timbers!'


Solve in Python:
Akshay is interested in mathematics, one day he came across a problem of modulus operator.He has  a list of M integers say arr[M] and has to find all integers K such that :
- K > 1
- arr[1]%K = arr[2]%K = arr[3]%K = … = arr[M]%K where '%' is a modulus operator.
Help Akshay to find all such K's.

-----Input:-----
- First line of input contains an integer M. Then M lines follow each containing one integer of the list. Input data is such that at least one integer K will always exist.

-----Output:-----
- Output all possible integers K separated by space in increasing order.

-----Constraints-----
- 2<= M <=100
- 1< value of each integer <109
- All integers will be distinct

-----Sample Input:-----
3
38
6
34

-----Sample Output:-----
2 4

m = int(input())
a = []
for i in range(m):
	a.append(int(input()))
ma = max(a)
x = a.index(ma)
k = max(a[:x]+a[x+1:])
for i in range(2,k):
	flag = 1
	for j in range(m-1):
		if (a[j]%i != a[j+1]%i):
			flag = 0
			break
	if (flag == 1):
		print(i,end = " ")


Solve in Python:
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift $X[i]$ grams on day $i$. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by $A$ grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts $C[i]$ because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of $K$ grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output $-1$.

-----Input-----

The first one contains two integer numbers, integers $N$ $(1 \leq N \leq 10^5)$ and $K$ $(1 \leq K \leq 10^5)$ – representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains $N$ integer numbers $X[i]$ $(1 \leq X[i] \leq 10^9)$ separated by a single space representing how many grams Alan wants to lift on day $i$. The third line contains one integer number $A$ $(1 \leq A \leq 10^9)$ representing permanent performance gains from a single drink. The last line contains $N$ integer numbers $C[i]$ $(1 \leq C[i] \leq 10^9)$ , representing cost of performance booster drink in the gym he visits on day $i$.

-----Output-----

One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.

-----Examples-----
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6

Output
5

Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6

Output
-1

-----Note-----

First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.

from sys import stdin
from heapq import heappop,heappush
def main():
	n,k = map(int,stdin.readline().split())
	X = list(map(int,stdin.readline().split()))
	A = int(stdin.readline().strip())
	C = list(map(int,stdin.readline().split()))
	l  = list()
	i = 0;g = k;ans = 0;flag = True
	while i < n and flag:
		heappush(l,C[i])
		if X[i] > g:
			while len(l)!= 0 and X[i] > g:
				ans+= heappop(l)
				g+= A
			if len(l) == 0 and X[i] > g:
				flag = False
		i+=1
	if flag:
		print(ans)
	else:
		print(-1)
main()


Solve in Python:
Alan's child can be annoying at times.

When Alan comes home and tells his kid what he has accomplished today, his kid never believes him.

Be that kid.

Your function 'AlanAnnoyingKid' takes as input a sentence spoken by Alan (a string). The sentence contains the following structure:

    "Today I " + [action_verb] + [object] + "."

    (e.g.: "Today I played football.")

Your function will return Alan's kid response, which is another sentence with the following structure:

    "I don't think you " + [action_performed_by_alan] + " today, I think you " + ["did" OR "didn't"] + [verb_of _action_in_present_tense] + [" it!" OR " at all!"]

    (e.g.:"I don't think you played football today, I think you didn't play at all!")

Note the different structure depending on the presence of a negation in Alan's first sentence (e.g., whether Alan says "I dind't play football", or "I played football").

! Also note: Alan's kid is young and only uses simple, regular verbs that use a simple "ed" to make past tense.
There are random test cases.

Some more examples:

    input  = "Today I played football."
    output = "I don't think you played football today, I think you didn't play at all!"

    input  = "Today I didn't attempt to hardcode this Kata."
    output = "I don't think you didn't attempt to hardcode this Kata today, I think you did attempt it!"

    input  = "Today I didn't play football."
    output = "I don't think you didn't play football today, I think you did play it!"

    input  = "Today I cleaned the kitchen."
    output = "I don't think you cleaned the kitchen today, I think you didn't clean at all!"

def alan_annoying_kid(stg):
    response = "I don't think you {0} today, I think you {1} {2} {3}!".format
    what = stg.replace("Today I ", "")[:-1]
    made = what.replace("didn't ", "").split()[0]
    filler = (what, "did", made, "it") if "didn't" in what else (what, "didn't", made[:-2], "at all")
    return response(*filler)


Solve in Python:
Alex and Lee play a game with piles of stones.  There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].
The objective of the game is to end with the most stones.  The total number of stones is odd, so there are no ties.
Alex and Lee take turns, with Alex starting first.  Each turn, a player takes the entire pile of stones from either the beginning or the end of the row.  This continues until there are no more piles left, at which point the person with the most stones wins.
Assuming Alex and Lee play optimally, return True if and only if Alex wins the game.

Example 1:
Input: piles = [5,3,4,5]
Output: true
Explanation:
Alex starts first, and can only take the first 5 or the last 5.
Say he takes the first 5, so that the row becomes [3, 4, 5].
If Lee takes 3, then the board is [4, 5], and Alex takes 5 to win with 10 points.
If Lee takes the last 5, then the board is [3, 4], and Alex takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alex, so we return true.

Constraints:

2 <= piles.length <= 500
piles.length is even.
1 <= piles[i] <= 500
sum(piles) is odd.

class Solution:
    memo = []

    def stoneGame(self, piles: List[int]) -> bool:
        length = len(piles)
        self.memo = [[[-1] * (length + 1) for _ in range(length + 1)] for i in range(2)]
        return (self.helper(0, length-1, piles, 1)) >= 0

    def helper(self, l, r, piles, ID):
        if l > r:
            return 0
        if self.memo[ID][l][r] != -1:
            return self.memo[ID][l][r]

        next = abs(ID - 1)
        if ID == 1:
            self.memo[ID][l][r] = max(piles[l] + self.helper(l + 1, r, piles, next),
                                      piles[r] + self.helper(l, r - 1, piles, next))
        else:
            self.memo[ID][l][r] = min(-piles[l] + self.helper(l + 1, r, piles, next),
                                      -piles[r] + self.helper(l, r - 1, piles, next))
        return self.memo[ID][l][r]


Solve in Python:
Alex decided to go on a touristic trip over the country.

For simplicity let's assume that the country has $n$ cities and $m$ bidirectional roads connecting them. Alex lives in city $s$ and initially located in it. To compare different cities Alex assigned each city a score $w_i$ which is as high as interesting city seems to Alex.

Alex believes that his trip will be interesting only if he will not use any road twice in a row. That is if Alex came to city $v$ from city $u$, he may choose as the next city in the trip any city connected with $v$ by the road, except for the city $u$.

Your task is to help Alex plan his city in a way that maximizes total score over all cities he visited. Note that for each city its score is counted at most once, even if Alex been there several times during his trip.

-----Input-----

First line of input contains two integers $n$ and $m$, ($1 \le n \le 2 \cdot 10^5$, $0 \le m \le 2 \cdot 10^5$) which are numbers of cities and roads in the country.

Second line contains $n$ integers $w_1, w_2, \ldots, w_n$ ($0 \le w_i \le 10^9$) which are scores of all cities.

The following $m$ lines contain description of the roads. Each of these $m$ lines contains two integers $u$ and $v$ ($1 \le u, v \le n$) which are cities connected by this road.

It is guaranteed that there is at most one direct road between any two cities, no city is connected to itself by the road and, finally, it is possible to go from any city to any other one using only roads.

The last line contains single integer $s$ ($1 \le s \le n$), which is the number of the initial city.

-----Output-----

Output single integer which is the maximum possible sum of scores of visited cities.

-----Examples-----
Input
5 7
2 2 8 6 9
1 2
1 3
2 4
3 2
4 5
2 5
1 5
2

Output
27

Input
10 12
1 7 1 9 3 3 6 30 1 10
1 2
1 3
3 5
5 7
2 3
5 4
6 9
4 6
3 7
6 8
9 4
9 10
6

Output
61

import sys
input = sys.stdin.readline

n,m=list(map(int,input().split()))
W=[0]+list(map(int,input().split()))
E=[tuple(map(int,input().split())) for i in range(m)]
S=int(input())

ELIST=[[] for i in range(n+1)]
EW=[0]*(n+1)

for x,y in E:
    ELIST[x].append(y)
    ELIST[y].append(x)

    EW[x]+=1
    EW[y]+=1

from collections import deque
Q=deque()
USED=[0]*(n+1)

for i in range(1,n+1):
    if EW[i]==1 and i!=S:
        USED[i]=1
        Q.append(i)

EW[S]+=1<<50
USED[S]=1

while Q:
    x=Q.pop()
    EW[x]-=1

    for to in ELIST[x]:
        if USED[to]==1:
            continue
        EW[to]-=1

        if EW[to]==1 and USED[to]==0:
            Q.append(to)
            USED[to]=1

#print(EW)
LOOP=[]

ANS=0
for i in range(1,n+1):
    if EW[i]!=0:
        ANS+=W[i]
        LOOP.append(i)

SCORE=[0]*(n+1)
USED=[0]*(n+1)

for l in LOOP:
    SCORE[l]=ANS
    USED[l]=1

Q=deque(LOOP)

while Q:
    x=Q.pop()

    for to in ELIST[x]:
        if USED[to]==1:
            continue

        SCORE[to]=W[to]+SCORE[x]
        Q.append(to)
        USED[to]=1

print(max(SCORE))


Solve in Python:
Alex is transitioning from website design to coding and wants to sharpen his skills with CodeWars.
He can do ten kata in an hour, but when he makes a mistake, he must do pushups. These pushups really tire poor Alex out, so every time he does them they take twice as long. His first set of redemption pushups takes 5 minutes. Create a function, `alexMistakes`, that takes two arguments: the number of kata he needs to complete, and the time in minutes he has to complete them. Your function should return how many mistakes Alex can afford to make.

from math import log

MINUTES_PER_KATA = 6.0
PUSHUPS_BASE_TIME = 5.0

def alex_mistakes(n_katas, time_limit):
    return int(log((time_limit - MINUTES_PER_KATA * n_katas) / PUSHUPS_BASE_TIME + 1, 2))


Solve in Python:
Alex just got a new hula hoop, he loves it but feels discouraged because his little brother is better than him

Write a program where Alex can input (n) how many times the hoop goes round and it will return him an encouraging message :)

-If Alex gets 10 or more hoops, return the string "Great, now move on to tricks".

-If he doesn't get 10 hoops, return the string "Keep at it until you get it".

def hoop_count(n):
    if 10<=n:
        x="Great, now move on to tricks"
    else:
        x="Keep at it until you get it"
    return(x)

    # Good Luck!


Solve in Python:
Alexandra has an even-length array $a$, consisting of $0$s and $1$s. The elements of the array are enumerated from $1$ to $n$. She wants to remove at most $\frac{n}{2}$ elements (where $n$ — length of array) in the way that alternating sum of the array will be equal $0$ (i.e. $a_1 - a_2 + a_3 - a_4 + \dotsc = 0$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.

For example, if she has $a = [1, 0, 1, 0, 0, 0]$ and she removes $2$nd and $4$th elements, $a$ will become equal $[1, 1, 0, 0]$ and its alternating sum is $1 - 1 + 0 - 0 = 0$.

Help her!

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^3$). Description of the test cases follows.

The first line of each test case contains a single integer $n$ ($2 \le n \le 10^3$, $n$ is even)  — length of the array.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 1$)  — elements of the array.

It is guaranteed that the sum of $n$ over all test cases does not exceed $10^3$.

-----Output-----

For each test case, firstly, print $k$ ($\frac{n}{2} \leq k \leq n$) — number of elements that will remain after removing in the order they appear in $a$. Then, print this $k$ numbers. Note that you should print the numbers themselves, not their indices.

We can show that an answer always exists. If there are several answers, you can output any of them.

-----Example-----
Input
4
2
1 0
2
0 0
4
0 1 1 1
4
1 1 0 0

Output
1
0
1
0
2
1 1
4
1 1 0 0

-----Note-----

In the first and second cases, alternating sum of the array, obviously, equals $0$.

In the third case, alternating sum of the array equals $1 - 1 = 0$.

In the fourth case, alternating sum already equals $1 - 1 + 0 - 0 = 0$, so we don't have to remove anything.

#OM GANESHAY NAMH
#GANPATI BAPPA MORYA
import math,queue,heapq
import sys
sys.setrecursionlimit(10**6)
fastinput=sys.stdin.readline
fastout=sys.stdout.write
t=int(fastinput())
while t:
    t-=1
    n=int(fastinput())
    a=list(map(int,fastinput().split()))
    c=a.count(1)
    if c==0 or c==n:
        print(n)
        print(*a)
    elif c<=n//2:
        print(n-c)
        print('0 '*(n-c))
    else:
        if c%2==0:
            print(c)
            print('1 '*c)
        else:
            c-=1
            print(c)
            print('1 '*c)


Solve in Python:
Alex and Lee continue their games with piles of stones.  There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].  The objective of the game is to end with the most stones.
Alex and Lee take turns, with Alex starting first.  Initially, M = 1.
On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M.  Then, we set M = max(M, X).
The game continues until all the stones have been taken.
Assuming Alex and Lee play optimally, return the maximum number of stones Alex can get.

Example 1:
Input: piles = [2,7,9,4,4]
Output: 10
Explanation:  If Alex takes one pile at the beginning, Lee takes two piles, then Alex takes 2 piles again. Alex can get 2 + 4 + 4 = 10 piles in total. If Alex takes two piles at the beginning, then Lee can take all three piles left. In this case, Alex get 2 + 7 = 9 piles in total. So we return 10 since it's larger.

Constraints:

1 <= piles.length <= 100
1 <= piles[i] <= 10 ^ 4

class Solution:
    def helper(self, s, M, n):
        if s >= n:
            return 0
        if (s, M) in self.mem:
            return self.mem[(s, M)]
        cur, best = 0, -float('inf')
        for x in range(1, 2*M + 1):
            if s + x > n:
                break
            cur += self.piles[s + x -1]
            best = max(best, cur - self.helper(s + x, max(x, M), n))
        self.mem[(s, M)] = best
        return best

    def stoneGameII(self, piles: List[int]) -> int:
        n = len(piles)
        self.mem = {}
        self.piles = piles
        return (sum(piles) + self.helper(0, 1, n))//2


Solve in Python:
Algorithmic predicament - Bug Fixing #9

Oh no! Timmy's algorithim has gone wrong! help Timmy fix his algorithim!

Task
Your task is to fix timmy's algorithim so it returns the group name with the highest total age.

You will receive two groups of `people` objects, with two properties `name` and `age`. The name property is a string and the age property is a number.
Your goal is to make the total the age of all people having the same name through both groups and return the name of the one with the highest age. If two names have the same total age return the first alphabetical name.

from collections import Counter
from itertools import chain

def highest_age(persons1, persons2):
    c = Counter()

    for p in chain(persons1, persons2):
        c[p['name']] += p['age']

    return min(iter(c.items()), key=lambda n_a: (-n_a[1], n_a[0]))[0] if c else None


Solve in Python:
Alice and Bob are playing a fun game of tree tag.

The game is played on a tree of $n$ vertices numbered from $1$ to $n$. Recall that a tree on $n$ vertices is an undirected, connected graph with $n-1$ edges.

Initially, Alice is located at vertex $a$, and Bob at vertex $b$. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most $da$ from the current vertex. And in a move, Bob can jump to a vertex with distance at most $db$ from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.

If after at most $10^{100}$ moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.

Determine the winner if both players play optimally.

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). Description of the test cases follows.

The first line of each test case contains five integers $n,a,b,da,db$ ($2\le n\le 10^5$, $1\le a,b\le n$, $a\ne b$, $1\le da,db\le n-1$)  — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.

The following $n-1$ lines describe the edges of the tree. The $i$-th of these lines contains two integers $u$, $v$ ($1\le u, v\le n, u\ne v$), denoting an edge between vertices $u$ and $v$. It is guaranteed that these edges form a tree structure.

It is guaranteed that the sum of $n$ across all test cases does not exceed $10^5$.

-----Output-----

For each test case, output a single line containing the winner of the game: "Alice" or "Bob".

-----Example-----
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4...

import sys
input = lambda: sys.stdin.readline().rstrip()

from collections import deque
T = int(input())
for _ in range(T):
    N, a, b, da, db = list(map(int, input().split()))
    a, b = a-1, b-1
    X = [[] for _ in range(N)]
    Y = [[] for _ in range(N)]
    for _ in range(N-1):
        u, v = list(map(int, input().split()))
        X[u-1].append(v-1)
        X[v-1].append(u-1)
        Y[u-1].append(v-1)
        Y[v-1].append(u-1)
    if 2 * da >= db:
        print("Alice")
        continue
    P = [-1] * N
    Q = deque([a])
    R = []
    D = [0] * N
    while Q:
        i = deque.popleft(Q)
        R.append(i)
        for j in X[i]:
            if j != P[i]:
                P[j] = i
                D[j] = D[i] + 1
                X[j].remove(i)
                deque.append(Q, j)
    if D[b] <= da:
        print("Alice")
        continue

    ma = max(D)
    for i in range(N):
        if D[i] == ma:
            break

    X = Y
    P = [-1] * N
    Q = deque([i])
    R = []
    D = [0] * N
    while Q:
        i = deque.popleft(Q)
        R.append(i)
        for j in X[i]:
            if j != P[i]:
                P[j] = i
                D[j] = D[i] + 1
                X[j].remove(i)
                deque.append(Q, j)

    print("Bob" if max(D) > 2 * da else "Alice")


Solve in Python:
Alice and Bob are walking on an infinite straight street. Initially, both are at the position $X=0$ and they start walking in the direction of increasing $X$. After $N$ seconds, they stop. Let's denote Alice's speed and Bob's speed during the $i$-th of these seconds by $A_i$ and $B_i$ respectively.
Sometimes, Alice and Bob walk together, i.e. with the same speed side by side. Let's define the weird distance as the total distance they walk this way. Find this weird distance.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.
- The third line contains $N$ space-separated integers $B_1, B_2, \ldots, B_N$.

-----Output-----
For each test case, print a single line containing one integer ― the total weird distance. It can be proved that this distance is an integer.

-----Constraints-----
- $1 \le T \le 20$
- $1 \le N \le 10^5$
- $1 \le A_i \le 10^5$ for each valid $i$
- $1 \le B_i \le 10^5$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $10^6$

-----Subtasks-----
Subtask #1 (30 points): $1 \le N \le 1,000$
Subtask #2 (70 points): original constraints

-----Example Input-----
3
4
1 3 3 4
1 2 4 4
2
2 3
3 2
2
3 3
3 3

-----Example Output-----
5
0
6

-----Explanation-----
Example case 1:
- Alice and Bob walk side by side during the first second, from $X=0$ to $X=1$.
- Then, Alice starts walking faster than Bob, so they do not walk side by side during second $2$. At the end of second $2$, Alice is at $X=4$, while Bob is at $X=3$.
- During the next second, they again do not walk side by side, but Bob walks faster, so they both end up at $X=7$.
- During the last second, they both walk side by side and the distance they walk is $4$.
- Alice and Bob walk side by side during the $1$-st and $4$-th second and the total weird distance they travel is...

for _ in range(int(input())):
 n = int(input())

 arr1 = list(map(int,input().split()))
 arr2 = list(map(int,input().split()))
 res=0
 presum1=0
 presum2=0
 for i in range(n):
  if arr1[i]== arr2[i] and presum1==presum2 :

   res+=arr1[i]
  presum1+=arr1[i]
  presum2 +=arr2[i]

 print(res)


Solve in Python:
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.
Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first remaining stones in the row.
The score of each player is the sum of values of the stones taken. The score of each player is 0 initially.
The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.
Assume Alice and Bob play optimally.
Return "Alice" if Alice will win, "Bob" if Bob will win or "Tie" if they end the game with the same score.

Example 1:
Input: values = [1,2,3,7]
Output: "Bob"
Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.

Example 2:
Input: values = [1,2,3,-9]
Output: "Alice"
Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score.
If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. The next move Alice will take the pile with value = -9 and lose.
If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. The next move Alice will take the pile with value = -9 and also lose.
Remember that both play optimally so here Alice will choose the scenario that makes her win.

Example 3:
Input: values = [1,2,3,6]
Output: "Tie"
Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.

Example 4:
Input: values = [1,2,3,-1,-2,-3,7]
Output: "Alice"

Example 5:
Input: values = [-1,-2,-3]
Output: "Tie"

Constraints:

1 <= values.length <= 50000
-1000 <= values[i] <= 1000

class Solution:
    def stoneGameIII(self, stoneValue: List[int]) -> str:
        # aliceScore = [0]
        # bobScore = [0]
        # INVALID = 's'
        # def helper(stoneValues,index,aliceScore,bobScore,aliceTurn):
        #     scoreToUpdate = aliceScore
        #     if not aliceTurn:
        #         scoreToUpdate = bobScore
        #     if len(stoneValues) - 1 == index:
        #         scoreToUpdate[0] += stoneValues[index]
        #         return
        #     bck = scoreToUpdate[0]
        #     sums = []
        #     for i in range(1,4):
        #         scoreToUpdate[0] = bck
        #         if i + index <= len(stoneValues):
        #             for j in range(i):
        #                 scoreToUpdate[0] += stoneValues[index+j]
        #             helper(stoneValues,index + i,aliceScore,bobScore,not aliceTurn)
        #             sums.append(scoreToUpdate[0])
        #     if len(sums) > 0:
        #         scoreToUpdate[0] = max(sums)
        #     else:
        #         scoreToUpdate[0] = bck
        #     return
        # helper(stoneValue,0,aliceScore,bobScore,True)
        # if aliceScore[0] > bobScore[0]:
        #     return 'Alice'
        # elif bobScore[0] > aliceScore[0]:
        #     return 'Bob'
        # return 'Tie'
        mem = {}
        def helper(stoneValues,index):
            if index in mem:
                return mem[index]
            if index >= len(stoneValues):
                return 0
            ans = stoneValues[index] - helper(stoneValues,index+1)
            if index + 1 < len(stoneValues):
                temp = stoneValues[index] + stoneValues[index+1] - helper(stoneValues,index+2)
                ans = max(ans,temp)
            if index + 2 < len(stoneValues):
                temp = stoneValues[index] + stoneValues[index+1] + stoneValues[index+2] - helper(stoneValues,index+3)
                ans = max(ans,temp)
            mem[index] = ans
            return ans
        ans = helper(stoneValue,0)
        if ans > 0:
            return...