Special Input problems on competitive programming questions? - python

I am currently working on Constructing a Number on HackerRank (https://www.hackerrank.com/challenges/constructing-a-number/problem), and I have come across a certain type of input:
3
1
9
3
40 50 90
2
1 4
Apparently, there are 3 test cases inside those 7 lines of input. Can someone please explain why it's like that?

Quoting the section Input Format:
The first line contains a single integer t denoting the number of queries. The following lines describe the queries. Each query is described in two lines. The first of these lines contains a single integer n. The second contains space-separated integers a1, a2, ..., an.
Thus, the first number denotes how many queries you need to expect, but then there are the real queries as pairs of lines: first line in one pair has one integer, second line in the same pair has a list of integers. Such pairs just repeat. I believe you got confused by the fact that the length of the list of integers is not necessary constant.
In your example with comments:
3 // How many of the queries?
// 1st query:
1 // Integer
9 // List of integers
// 2nd query:
3 // Integer
40 50 90 // List of integers
// 3rd query:
2 // Integer
1 4 // List of integers

Related

I am getting time limit error in the competition platform for my code

I am trying to solve this problem in the online coding platform(question given below) with the below code. The competition platform shows time limit error.
QUESTION:
Tahir and Mamta are woking in a project in TCS. Tahir being a problem solver came up with an interesting problem for his friend Mamta.
Problem consists of a string of length N and contains only small case alphabets.
It will be followed by Q queries, in which each query will contain an integer P (1<=P<=N) denoting a position within the string.
Mamta's task is to find the alphabet present at that location and determine the number of occurrence of same alphabet preceding the given location P.
Mamta is busy with her office work. Therefore, she asked you to help her.
Constraints
1 <= N <= 500000
S consisting of small case alphabets
1 <= Q <= 10000
1 <= P <= N
Input Format
First line contains an integer N, denoting the length of string.
Second line contains string S itself consists of small case alphabets only ('a' - 'z').
Third line contains an integer Q denoting number of queries that will be asked.
Next Q lines contains an integer P (1 <= P <= N) for which you need to find the number occurrence of character present at the Pth location preceeding P.
Output
For each query, print an integer denoting the answer on single line.
Time Limit
1
My code:
n=int(input())
a=input()[:n]
for i in range(int(input())):
p=int(input())
print(a[:p-1].count(a[p-1]))
Sample Input,Output:
Example 1
Input
9
abacsddaa
2
9
3
Output
3
1
Explanation
Here Q = 2
For P=9, character at 9th location is 'a'. Number of occurrences of 'a' before P i.e., 9 is three.
Similarly for P=3, 3rd character is 'a'. Number of occurrences of 'a' before P. i.e., 3 is one.
I'm new to Python so please help me with the error.
Your solution's complexity is O(n2) and it causes the time limit error.
You should use the prefix sum array algorithm. Take a look at this link and define a prefix sum array for every alphabet.

Is there a method/Algorithm to generate unique integers from prime factors of a given number?

I'm trying to solve the following question https://open.kattis.com/problems/listgame2
and I am successfully able to generate all the prime factors of a given number but the problem demands that I need to get a list of unique numbers only.
for example -
1099511627776 = 2^40
but since the number 2 is repeated 40 times, the problem is to simplify 2^40 as 2*4*8* .... == 1099511627776 without repeating any integers to arrive that the product.
I found a similar question on Stackoverflow at Algorithm: Factorize a integer X to get as many distinct positive integers(Y1...Yk) as possible so that (Y1+1)(Y2+1)...(Yk+1) = X
but there was no logic provided
A counter example from the above link is the number 10307264 = 2^6 * 11^5 this should possibly reduce to 2 * 4 * 11* 22 * 44 * 121 == 10307264
I don't seek a solution but rather a discussion towards a concrete logic to find the optimal solution.
Thanks in advance!
Stop thinking of these as unique integers; think of them as tuples of powers. Your first example is 2^40; you have to partition 40 into as many distinct integers as possible. For this simple example, a greedy approach makes it trivial: you grab 1, then 2, ... until the remaining number isn't large enough to separate without stepping on a previous number. This is a simple application of triangle numbers:
`1 2 3 4 5 6 7 8`, and a remainder of 4
... that you can distribute among the upper numbers as you see fit (without duplication); you will get 8 distinct integers for your score. For instance: 1 2 3 4 6 7 8 9 are the powers of 2 you might want.
For a complex number, such as 2^6 11^5, you now have a pair (6, 5) to partition into distinct pairs. Now, you can have 0 components, so long as no pair is entirely 0. Your given 5-opint solution is sub-optimal; the linked question gives 6, represented by the power pairs
1 0
2 0
0 1
0 2
1 1
2 1
Giving us six 2s and 5 11s.
This is where a multi-dimansional solution comes in handy. The given solution is formed from the product of available small factors (again greedy) for 2 and 11:
{0 1 2} x {0 1 2}
... taking the least-cost choice at each juncture. Imagine this as a lattice in 2D space. Starting near the origin, we work outward through the lattice, consuming the least-cost point each time. "Least-cost" is the choice the leaves us the greatest range of options. I'll number the axes and label the choices in order:
11 \ 2 0 1 2
0 A C
1 B E F
2 D
There are various ways to work at "least-cost": fewest factors consumed (i.e. lowest tuple sum), greatest remaining product of powers (i.e. we take 2^1 first, because that leaves 5x5 factors, rather than 4x6 if we'd taken 11^1).
If recursion appeals to you, then you can write a simple recursive routine that iterates through the inner shell of the N-dim space, considering all of the tuples adjacent to the points already consumed (including the disqualified origin). Each choice leaves a separable, independent sub-problem. BTW, it's trivial to prove that this "inner shell" is sufficient to find the optimal solution.
For instance, in the above (6 5) examples, the two inner-shell points to try are (1 0) and (0 1), leaving sub-problems of (5 5) and (6 4). It's easy to see that the solution paths will converge: I strongly suggest that, if you attack this solution, that you memoize your results (dynamic programming) to avoid duplication.
Does that get you moving?

Permutations of 2 characters in Python into fixed length string with equal numbers of each character

I've looked through the 2 questions below, which seem closest to what I am asking, but don't get me to the answer to my question.
Permutation of x length of 2 characters
How to generate all permutations of a list in Python
I am trying to find a way to take 2 characters, say 'A' and 'B', and find all unique permutations of those characters into a 40 character string. Additionally - I need each character to be represented 20 times in the string. So all resulting strings each have 20 'A's and 20 'B's.
Like this:
'AAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBB'
'AAAAAAAAAAAAAAAAAAABABBBBBBBBBBBBBBBBBBB'
'AAAAAAAAAAAAAAAAAABAABBBBBBBBBBBBBBBBBBB'
etc...
All I really need is the count of unique combinations that follow these rules.
y=['A','A','A','A','B','B','B','B']
comb = set(itertools.permutations(y))
print("Combinations Found: {:,}".format(len(comb)))
This works, but it doesn't scale well to an input string of 20 'A's and 20 'B's. The above code takes 90 seconds to execute. Even just scaling up to 10 'A's and 10 'B's ran for 20 minutes before I killed it.
Is there more efficient way to approach this given the parameters I've described?
If all you need is the count, this can be generalized to n choose k. Your total size is n and the number of elements of "A" is k. So, your answer would be:
(n choose k) = (40 choose 20) = 137846528820

python elements in line without raw_input()

I have an input stream of numbers
1 2 3 4 5 6 7 8 9 10 11 12 and it goes on......
now in python, we have to take input by raw_input() and then map(int,raw_input.split()) and then do whatever processing one has to do.
for eg.
n = map(int,raw_input().split())
for i in n:
print i%2==0
So in the above code, i have first taken all inputs, converted them to integer and ran a loop to check if each integer is even number or not.
I can do the same thing in Java, but now i can simply give result just as soon as I get input.
for eg. Assuming number of inputs ( n ) is given, the following program, takes input from the above given input feed and keep on giving requisite output.
for(i = 0 ; i < n ; i++ ){
n = in.nextInt();
System.out.println(n%2==0);
}
I want to know, if there is some method in python by which we can take n inputs from a line and keep processing it in continuation.
And how are the two above programs differ performance wise.
I think you want something like this (assumes n is already set)
in = raw_input().split()
for i in range(n):
i = int(in[i])
print(i%0 == 0)
This is analogous to the Java code, but like the Java code, this will raise an error if there are fewer than n numbers, or if any of the items in the input are not integers.

How to add trailing zeros to an integer in python? or How to add ZEROS after any integer in python?

I'm without clues on how to do this in Python. The problem is the following: I have for example an orders numbers like:
1
2
...
10
The output should be
1000
2000
...
10000
That is I want to add 3 extra zeros after the integer
Multiply by 10 every time you want to add another 0.
This is the same as saying 10 to the power of how many zeroes you want. In python, that would be number * (10**extraZeroCount)
As I understand the question, the 3 extra zeros are for output purposes only. There is no need to obtain integers back. Strings (or for that mater, any other type) is enough. In this vein, any of
print(a*1000)
print(str(a)+"000")
print(a,"000",sep="")
and perhaps several others, would work.
Another way could be to append 3 zeroes after every integer like
int(str(number) + "000")
But I would just multiply them by 1000

Categories