Asked  10 Months ago    Answers:  5   Viewed   177 times

I wonder if it is possible to input two or more integer numbers in one line of standard input. In C/C++ it's easy:

C++:

#include <iostream>
int main() {
    int a, b;
    std::cin >> a >> b;
    return 0;
}

C:

#include <stdio.h>
void main() {
    int a, b;
    scanf("%d%d", &a, &b);
}

In Python, it won't work:

enedil@notebook:~$ cat script.py 
#!/usr/bin/python3
a = int(input())
b = int(input())
enedil@notebook:~$ python3 script.py 
3 5
Traceback (most recent call last):
  File "script.py", line 2, in <module>
    a = int(input())
ValueError: invalid literal for int() with base 10: '3 5'

So how to do it?

 Answers

2

Split the entered text on whitespace:

a, b = map(int, input().split())

Demo:

>>> a, b = map(int, input().split())
3 5
>>> a
3
>>> b
5
Thursday, August 5, 2021
 
4

input takes a prompt string as its argument, which it will print automatically, but print returns None; it is this that gets printed by input. Your code is equivalent to:

prompt = print(...) # prompt == None
ans = int(input(prompt)) 

Instead, use str.format to build the prompt and pass it straight to input:

ans = int(input('{0}x{1}='.format(multi, num)))
Wednesday, June 2, 2021
 
Manmay
 
4

No. The method for appending an entire sequence is list.extend().

>>> L = [1, 2]
>>> L.extend((3, 4, 5))
>>> L
[1, 2, 3, 4, 5]
Sunday, June 13, 2021
 
1

You remember correctly.

It's in the sys module (sys.ps1 & sys.ps2):

Strings specifying the primary and secondary prompt of the interpreter. These are only defined if the interpreter is in interactive mode. Their initial values in this case are '>>> ' and '... '. If a non-string object is assigned to either variable, its str() is re-evaluated each time the interpreter prepares to read a new interactive command; this can be used to implement a dynamic prompt.

For example:

   >>> import sys
   >>> sys.ps1 = "3.5>>> "
   3.5>>> sys.ps2 = "3.5... "
   3.5>>>
Friday, August 13, 2021
 
4

Read the line, split the line, copy the array result into a set. If the size of the set is less than the size of the array, the file contains repeated elements

with open('filename', 'r') as f:
    for line in f:
        # Here is where you do what I said above

To read the file word by word, try this

import itertools

def readWords(file_object):
    word = ""
    for ch in itertools.takewhile(lambda c: bool(c), itertools.imap(file_object.read, itertools.repeat(1))):
        if ch.isspace():
            if word: # In case of multiple spaces
                yield word
                word = ""
            continue
        word += ch
    if word:
        yield word # Handles last word before EOF

Then you can do:

with open('filename', 'r') as f:
    for num in itertools.imap(int, readWords(f)):
        # Store the numbers in a set, and use the set to check if the number already exists

This method should also work for streams because it only reads one byte at a time and outputs a single space delimited string from the input stream.


After giving this answer, I've updated this method quite a bit. Have a look

<script src="https://gist.github.com/smac89/bddb27d975c59a5f053256c893630cdc.js"></script>
Tuesday, December 7, 2021
 
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :