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.
Related
I'm new to competitive coding and was doing a practice USACO question with an input structure like this:
5 3
1
6
4
3
1
the first number is the number of numbers below it, and the second number next to it would be needed for something else in the problem
heres the code I wrote to try to recieve the input
a = list(input())
n = int(a[0])
k = int(a[2])
diamonds = []
for x in range(n):
this = int(input())
diamonds.append(this)
the first two numbers I put in a list, converted to int, then assigned them to two variables, I then created an array with a for loop to receive the list of numbers below, converting them to int first
although it works, I feel like this is inefficent and is wasting time, is there another, faster way of doing this?
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
So i'm trying to solve this problem and the question goes like this
Probably, You all Know About The Famous Japanese Cartoon Character Nobita and Shizuka. Nobita Shizuka are very Good friend. However , Shizuka Love a special kind of string Called Tokushuna.
A string T is called Tokushuna if
The length of the string is greater or equal then 3 (|T| ≥ 3 )
It start and end with a charecter ‘1’ (one)
It contain (|T|-2) number of ‘0’ (zero)
here |T| = length of string T . Example , 10001 ,101,10001 is Tokushuna string But 1100 ,1111, 0000 is not.
One Day Shizuka Give a problem to nobita and promise to go date with him if he is able to solve this problem. Shizuka give A string S and told to Count number of Tokushuna string can be found from all possible the substring of string S . Nobita wants to go to date with Shizuka But You Know , he is very weak in Math and counting and always get lowest marks in Math . And In this Time Doraemon is not present to help him .So he need your help to solve the problem .
Input
First line of the input there is an integer T, the number of test cases. In each test case, you are given a binary string S consisting only 0 and 1.
Subtasks
Subtask #1 (50 points)
1 ≤ T ≤ 100
1 ≤ |S| ≤ 100
Subtask #2 (50 points)
1 ≤ T ≤ 100
1 ≤ |S| ≤ 105
Output
For each test case output a line Case X: Y where X is the case number and Y is the number of Tokushuna string can be found from all possible the substring of string S
Sample
Input
3
10001
10101
1001001001
Output
Case 1: 1
Case 2: 2
Case 3: 3
Look, in first case 10001 is itself is Tokushuna string.
In second Case 2 Substring S[1-3] 101 and S[3-6] 101 Can be found which is Tokushuna string.
What I've done so far
I've already solved the problem but the problem is it shows my code exceeds memory limit (512mb). I'm guessing it is because of the large input size. To solve that I've tried to clear the list which holds all the substring of one string after completing each operation. But this isn't helping.
My code
num = int(input())
num_list = []
for i in range(num):
i = input()
num_list.append(i)
def condition(a_list):
case = 0
case_no = 1
sub = []
for st in a_list:
sub.append([st[i:j] for i in range(len(st)) for j in range(i + 1, len(st) + 1)])
for i in sub:
for item in i:
if len(item) >= 3 and (item[0] == '1' and item[-1] == '1') and (len(item) - 2 == item.count('0')):
case += 1
print("Case {}: {}".format(case_no, case))
case = 0
case_no += 1
sub.clear()
condition(num_list)
Is there any better approach to solve the memory consumption problem?
Have you tried taking java heap dump and java thread dump? These will tell the memory leak and also the thread that is consuming memory.
Your method of creating all possible substrings won't scale very well to larger problems. If the input string is length N, the number of substrings is N * (N + 1) / 2 -- in other words, the memory needed will grow roughly like N ** 2. That said, it is a bit puzzling to me why your code would exceed 512MB if the length of the input string is always less than 105.
In any case, there is no need to store all of those substrings in memory, because a Tokushuna string cannot contain other Tokushuna strings nested within
it:
1 # Leading one.
0... # Some zeros. Cannot be or contain a Tokushuna.
1 # Trailing one. Could also be the start of the next Tokushuna.
That means a single scan over the string should be sufficient to find them all.
You could write your own algorithmic code to scan the characters and keep track
of whether it finds a Tokushuna string. But that requires some tedious
bookkeeping.
A better option is regex, which is very good at character-by-character analysis:
import sys
import re
# Usage: python foo.py 3 10001 10101 1001001001
cases = sys.argv[2:]
# Match a Tokushuna string without consuming the last '1', using a lookahead.
rgx = re.compile(r'10+(?=1)')
# Check the cases.
for i, c in enumerate(cases):
matches = list(rgx.finditer(c))
msg = 'Case {}: {}'.format(i + 1, len(matches))
print(msg)
If you do not want to use regex, my first instinct would be to start the algorithm by finding the indexes of all of the ones: indexes = [j for j, c in enumerate(case) if c == '1']. Then pair those indexes up: zip(indexes, indexes[1:]). Then iterate over the pairs, checking whether the part in the middle is all zeros.
A small note regarding your current code:
# Rather than this,
sub = []
for st in a_list:
sub.append([...]) # Incurs memory cost of the temporary list
# and a need to drill down to the inner list.
...
sub.clear() # Also requires a step that's easy to forget.
# just do this.
for st in a_list:
sub = [...]
...
I am trying to code something that should find trailing zeros in a factorial. My problem is, when I send the following piece of code(Python3) to the online judge of SPOJ, it gives me time limit exceeded error. However, if I change the language from Python3 to Python 2, and transform inputs into raw_inputs, it is accepted under 3 seconds. The time limit for this problem is 6 seconds.
This got me thinking. Is this difference just because of a raw_input? As I know, Python3 has no raw_input. So I don't know what to do in order to reduce the time in Python3.
def Z(n):
count = 0
while n >= 5:
n //= 5
count += n
return int(count)
for i in range(int(input())): #get the number of test cases
print(Z(int(input()))) # get trailing zeros
More information about the problem input
Input
There is a single positive integer T on the first line of input (equal
to about 100000). It stands for the number of numbers to follow. Then
there are T lines, each containing exactly one positive integer number
N, 1 <= N <= 1000000000.
Below is a section of code which is part of a functional decryption and encryption program.
while checkvar < maxvar: # is set to < as maxvar is 1 to high for the index of var
#output.append("%02d" % number)
i =ord(var[checkvar]) - 64 # Gets postional value of i
i = ("%02d" % i)
if (checkvar + 1) < maxvar:
j =ord(var[(checkvar + 1)]) - 64 # Gets postional value of i
j = ("%02d" % j)
i = str(i) + str(j) #'Adds' the string i and j to create a new i
li.append(int(i))
checkvar = checkvar + 2
print li
As you can see the two variables i and j are first treated as string to add a 0 in front of any single digit numbers (as string). These variables then are combined to make a four digit number (still as a string). Later in the program the number created are used in a pow() function, as ints remove any leading zeros.
My question: Is it possible to force python to keep the leading zero for ints? I have and continued to search online.
Edit
To help people I have included the encryption part of the program. This is where the problem lies. The variables created in the above code are passed through a pow() function. As this can't handle strings I have to convert the variables to ints where the leading zero is lost.
#a = li[]
b=int(17)#pulic = e
c=int(2773)#=n
lenli=int(len(li))
enchecker = int(0)
#encrpted list
enlist = []
while enchecker < lenli:
en = pow(li[enchecker],b,c)#encrpyt the message can only handle int
enlist.append(int(en))
enchecker = enchecker + 1
print enlist
Though the comments above are true regarding 1, 01, and 001, are all the same as an int, it can be very helpful in temporal modeling, or sequential movie making to maintain the leading zeros. I do it often to ensure movie clips are in proper order. The easy way to do that is using zfill() to ensure the str version of the number has at least the number of characters you tell it, and does so by filling in the left-side of the string "number" with zeros.
>>> x = int(1)
>>> NewStringVariable = str(x).zfill(3)
>>> print NewStringVariable
001
>>> NewStringVariable = str(x).zfill(5)
>>> print NewStringVariable
00001
The concept of leading zeros is a display concept, not a numerical one. You can put an infinite number of leading zeros on a number without changing its value. Since it's not a numeric concept, it's not stored with the number.
You have to decide how many zeros you want when you convert the number to a string. You could keep that number separately if you want.
I was getting date strings in the format of hhmmss coming from the serial line of my Arduino.
Suppose I got s = "122041"; this would be 12:20:41, however 9am would be 090000.
The statement print "%d" % (s) provokes a run time error because the 9 is not an octal number and is hence an illegal character.
To fix this problem:
print "%06d" % (int(s))
Try this:
number = 1
print("%02d" % (number,))
or:
print("{:02d}".format(number))
The explanation of "%02d":
% - This tells the interpreter that a variable should be inserted here.
02 - This tells the interpreter to expect the variable to be 2 in length.
d - This tells the interpreter to expect a number, or should we say a"'d’igit".