Stdin issues using Python - python

I recently participated in hackathon for the first time and got stuck on the first problem. I solved the algorithm, but couldn't figure out how to take values from stdin using Python. This is the question:
There are two college students that want to room together in a dorm. There are rooms of various sizes in the dormitory. Some rooms can accomodate two additional students while others cannot.
Input: the first input line will be a number n (1 ≤ n ≤ 100), which is the total number of rooms in the dorm. There will be n lines following this, where each line contains two numbers, p and q (0 ≤ p ≤ q ≤ 100). P is the number students already in the room, while q is the maximum number of students that can live in the room.
Output: print the number of rooms that the two students can live in.
This is my solution. I've tested it using raw_input() and it works perfectly on my interpreter, but when I change it to just input() I get an error message.
def calcRooms(p, q):
availrooms = 0
if q - p >= 2:
availrooms += 1
return availrooms
def main():
totalrooms = 0
input_list = []
n = int(input())
print n
while n > 0:
inputln = input().split() #accepts 2 numbers from each line separated by whitespace.
p = int(inputln[0])
q = int(inputln[1])
totalrooms += calcRooms(p, q)
n -= 1
return totalrooms
print main()
The error message:
SyntaxError: unexpected EOF while parsing
How do I accept data correctly from stdin?

In this particular case, use raw_input to take the entire line as string input.
inputln = raw_input().split()
This takes input line as a string and split() method splits the string with space as delimiter and returns a list inputln
The following code works the way you wanted.
def main():
totalrooms = 0
input_list = []
#n = int(input("Enter the number of rooms: "))
n = input()
while n > 0: # You can use for i in range(n) :
inputln = raw_input().split() #Converts the string into list
p = int(inputln[0]) #Access first element of list and convert to int
q = int(inputln[1]) #Second element
totalrooms += calcRooms(p, q)
n -= 1
return totalrooms
Or, alternatively you may use fileinput.
If input file is not passed as command line argument, stdin will be the default input stream.
import fileinput
for line in fileinput.input() :
#do whatever with line : split() or convert to int etc
Please refer : docs.python.org/library/fileinput.html
Hope this helps, drop comments for clarification if needed.

Related

Hacker rank string separated challenge

I'm trying to solve a hacker rank challenge:
Given a string, s , of length n that is indexed from 0 to n-1 , print its even-indexed and odd-indexed characters as 2 space-separated strings. on a single line (see the Sample below for more detail)
link: https://www.hackerrank.com/challenges/30-review-loop/problem
Error:
for example:
The input "adbecf" should output "abc def"
When I run python Visualizer my code seem to have the correct output.. but on hacker rank it's saying I have the wrong answer. Does anyone know what might be wrong with my code.
This is the code I tried -
class OddEven:
def __init__(self, input_statement):
self.user_input = input_statement
def user_list(self):
main_list = list(user_input)
even = []
odd = []
space = [" "]
for i in range(len(main_list)):
if (i%2) == 0:
even.append(main_list[i])
else:
odd.append(main_list[i])
full_string = even + space + odd
return(full_string)
def listToString(self):
my_string = self.user_list()
return(''.join(my_string))
if __name__ == "__main__":
user_input = str(input ())
p = OddEven(user_input)
print(p.listToString())
First of all, input is always string, you don't need to convert it here.
user_input = str(input())
Each line is provided to you as separate input. Number of strings equal to num in the first line. In this case 2, so...
count = input()
for s in range(int(count)):
...
user_input variable inside user_list function should be accessed as self.user_input, it's a property of an object, which you pass to function as self.
Also you can iterate over list directly.
Here:
full_string = even + space + odd
you're trying to concatenate list, which is not a good idea, you'll still get a list.
You can join list with separating them with some string using join string method.
' '.join(list1, list2, ..., listN)
It's better do define odd and even as empty strings.
And then join them the using concatenation (+).
Here:
if (i%2) == 0
you don't have to compare with 0. Python will evaluate what's to the right from condition as True or False. So:
if i % 2:
...
There is simpler solution:
def divide(self):
odd = even = ''
for i, c in enumerate(self.user_input):
if i % 2:
odd += c
else:
even += c
return even + ' ' + odd
Here is the simple code for this problem:)
T=int(input())
for i in range(0,T):
S=input()
print(S[0::2],S[1::2])

Unable to extract numbers and sum them using regex and re.findall()

I try to extract numbers from a text file with regex. Afterward, I create the sum.
Here is the code:
import re
def main():
sum = 0
numbers = []
name = input("Enter file:")
if len(name) < 1 : name = "sample.txt"
handle = open(name)
for line in handle:
storage = line.split(" ")
for number in storage:
check = re.findall('([0-9]+)',number)
if check:
numbers.append(check)
print(numbers)
print(len(numbers))
for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(sum)
if __name__ == "__main__":
main()
The problem is, if this string "http://www.py4e.com/code3/"
I gets add as [4,3] into the list and later summed up as 43.
Any idea how I can fix that?
I think you just change numbers.append(check) into numbers.extend(check)because you want to add elements to an array. You have to use extend() function.
More, you do not need to use ( ) in your regex.
I also tried to check code on python.
import re
sum = 0;
strings = [
'http://www.py4e.com/code3/',
'http://www.py1e.com/code2/'
];
numbers = [];
for string in strings:
check = re.findall('[0-9]+', string);
if check:
numbers.extend(check)
for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(sum)
I am assuming instead of 43 you want to get 7
The number variable is an array of characters. So when you use join it becomes a string.
So instead of doing this you can either use a loop in to iterate through this array and covert elements of this array into int and then add to the sum.
Or
you can do this
import np
number np.array(number).astype('int').tolist()
This makes array of character into array on integers if conversion if possible for all the elements is possible.
When I add the string http://www.py4e.com/code3/" instead of calling a file which is not handled correctly in your code above fyi. The logic regex is running through two FOR loops and placing each value and it's own list[[4],[3]]. The output works when it is stepped through I think you issue is with methods of importing a file in the first statement. I replaced the file with the a string you asked about"http://www.py4e.com/code3/" you can find a running code here.
pyregx linkhttps://repl.it/join/cxercdju-shaunpritchard
I ran this method below calling a string with the number list and it worked fine?
#### Final conditional loop
``` for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(str(sum)) ```
You could also try using range or map:
for i in range(0, len(numbers)):
sum = sum + numbers
print(str(sum))

Reading an array from stdin using input() function throws an EOF error

Basically, I wish to sum the elements of the array provided in stdin. Why is it saying that list index is out of range? Is there anything special about the python input() function?
length = int(input())
li = []
for i in range(0, length):
li[i] = int(input())
sum = 0
for item in li:
sum = sum + item
Input
first line : length of array
second line : elements of the array.
EDIT : second line is a single string, not space separated integers.
3
1 2 3
Output:
Traceback (most recent call last):
File "./prog.py", line 6, in <module>
IndexError: list assignment index out of range
your question pretty much got answered, I just wanna show you a couple of tricks to make your program more simple and pythonic.
Instead of the for-loop try:
li = [int(i) for i in input().split(" ")]
And instead of the way you're calculating sum, try:
sum(li)
or even better:
sumOfItems = sum(int(i) for i in input().split(" "))
The thing with python lists is that you cannot assign a particular value to a position when that position originally does not exist, that is, the length of the list is less than the position that you want to change.
What you are trying to do is assign the value to a particular position in the list (called index) but since the list is empty, it's length is 0 and hence the index is out of range( that is it is not available for modifiying. That is why python is raising Index out of range error.
What you can try is:
l=[]
length=int(input())
for i in length:
l.append(int(input())
sum=0
for num in l:
sum=sum+num
You can solve this in a single line without even taking in the length. But you have to enter space separated values in a single line:
s = 0
for item in list(map(int, input ().split())):
s += item
If you want to input one integer per line, then you'll need the length(or a sentinel value):
s = 0
len = int(input())
li = [int(input ()) for _ in range(len)]
for item in li:
s = s + item
The second line of input turned out to be a single string and not space separated integers.
So I had to split the string, then convert the strings to integers to calculate their sum. Some of the methods mentioned above didn't work.
The list comprehension method will work in the space separated case, and is perfectly fine.
length = int(input())
l = input().split() # List of strings of integers.
S = 0
for item in l:
S += int(item) # Converting string to int
print(S)
You can't assign values to locations of a list that doesn't exist
try this:
length = int(input())
li = list(range(length))
for i in range(0, length):
li[i] = int(input())
sum = 0
for item in li:
sum = sum + item
you can also do something like this:
length = int(input())
li = []
for i in range(0, length):
li.append(int(input()))
total = sum(li)
print(total)

How to prompt the user to input a file into a function along with a min and max?

I need to make it so rather than this function relying on an parameters from the user when they call the function, it instead gets called, and then prompts the user to enter a FILE name for it to read (ex. they enter "dna.txt"), and then prompts them to enter a mink and a maxk and then it runs through the code of going through this file and finding the most common substring within the given mink and maxk. This is my current code:
def mostCommonSubstring(dna, mink, maxk):
count = 0
check = 0
answer = ""
k = mink
while k <= maxk:
for i in range(len(dna)-k+1):
sub = dna[i:i+k]
count = 0
for i in range(len(dna)-k+1):
if dna[i:i+k] == sub:
count = count + 1
if count >= check:
answer = sub
check = count
k=k+1
print(answer)
print(check)
I am under the impression that is needs to look something like this (but this code doesn't work?):
def mostCommonSubstring():
dnaFile = input("Enter file: ")
dna = open(dnaFile, "r")
mink = input("Enter a min: ")
maxk = input("Enter a max: ")
count = 0
check = 0
answer = ""
k = mink
while k <= maxk:
for i in range(len(dna)-k+1):
sub = dna[i:i+k]
count = 0
for i in range(len(dna)-k+1):
if dna[i:i+k] == sub:
count = count + 1
if count >= check:
answer = sub
check = count
k=k+1
print(answer)
print(check)
(The DNA file is a large file that contains many many a, g, t, and c, sequences. I wanted to be able to have the user input this file along with a min and max and then have the program find the longest common string.)
I know I have a high chance of being wrong here but I'll try to help anyway.
As a beginner I examined your code, and I think you could more use something like this:
with open(dna, 'r') as dnaFile:
# Do whatever you want here...
this will let you to run the file as a string.
IF I am not wrong, your problem was that you indeed opened the file, but you have not actually read it into a string. Thus you tried to access a file as if its contents we're already pressed into a string.
EDIT:
You could also do something like:
dna = open(dnaFile, 'r') # This is from your code.
dnaString = dna.read()
This way you also would read the file's content into a string and continue to run on your code.
Good luck and best regards!

How to take input in an array + PYTHON? [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 6 years ago.
I am new to Python and want to read keyboard input into an array. The python doc does not describe arrays well. Also I think I have some hiccups with the for loop in Python.
I am giving the C code snippet which I want in python:
C code:
int i;
printf("Enter how many elements you want: ");
scanf("%d", &n);
printf("Enter the numbers in the array: ");
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
You want this - enter N and then take N number of elements.I am considering your input case is just like this
5
2 3 6 6 5
have this in this way in python 3.x (for python 2.x use raw_input() instead if input())
Python 3
n = int(input())
arr = input() # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])
Python 2
n = int(raw_input())
arr = raw_input() # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])
raw_input is your helper here. From documentation -
If the prompt argument is present, it is written to standard output
without a trailing newline. The function then reads a line from input,
converts it to a string (stripping a trailing newline), and returns
that. When EOF is read, EOFError is raised.
So your code will basically look like this.
num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
n = raw_input("num :")
num_array.append(int(n))
print 'ARRAY: ',num_array
P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input does not do any type checking, so you need to be careful...
If the number of elements in the array is not given, you can alternatively make use of list comprehension like:
str_arr = raw_input().split(' ') //will take in a string of numbers separated by a space
arr = [int(num) for num in str_arr]
data = []
n = int(raw_input('Enter how many elements you want: '))
for i in range(0, n):
x = raw_input('Enter the numbers into the array: ')
data.append(x)
print(data)
Now this doesn't do any error checking and it stores data as a string.
arr = []
elem = int(raw_input("insert how many elements you want:"))
for i in range(0, elem):
arr.append(int(raw_input("Enter next no :")))
print arr

Categories

Resources