0

In my script, If the input-length is > 1. It outputs NO and then terminates.

This is what I tried.

import re
N = input("Enter your integer N: ")
if len(N) > 1:
    print('no')
    quit()

Take notice that the if statement is not encountered before input, this does not allow me to instantly terminate before pressing enter. I want to instantly terminate the script once I give more than one element.

Output

Enter your integer N: 10
no

Intended results after trying to enter 10. ( See that my script is intended to ignore more than one-element)

Output

    Enter your integer N: 1
    no

With this restriction, the space-complexity will truly be O(1).

Question

Is there some function in python that will restrict the input as I intend?

Travis Wells
  • 321
  • 1
  • 2
  • 11
  • No there is not. However there are some OS-specific ways of reading single characters, like `msvcrt.getch()` for Windows, which would provide a way for you to limit it. – martineau Sep 01 '20 at 17:55
  • @martineau That's a shame. An O(1) algorithm cannot be truly O(1) without O(1) space. Especially there is a user-input because inputs are not fixed. (in my case, the computer takes more than O(1) time to store the input as memory) – Travis Wells Sep 01 '20 at 17:56
  • Generally one isn't concerned with computational complexity when dealing with user input, so you comment doesn't really make any sense (to me). – martineau Sep 01 '20 at 18:01
  • @martineau I apologize, what I'm trying to say is that storing 1-million bits takes more time than storing 1-bit. – Travis Wells Sep 01 '20 at 18:02
  • Does this answer your question? [Python read a single character from the user](https://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user) – MEE Sep 01 '20 at 18:04
  • Travis:That's O(n) complexity—and not really that bad (although not as good as O(1)). I think you may need to [edit] your question and ,make what you're asking more clear… – martineau Sep 01 '20 at 18:05

1 Answers1

1

This should give you a Θ(2) space:

import readchar

x = readchar.readchar()
rest = readchar.readchar()
if rest != '\r':
    print('no')
    quit()
MEE
  • 2,114
  • 17
  • 21