Issue
Actually I have two questions:
- How to preserve the order of elements in the list when converted to set? For example consider the following:
>>>set([7, 10, 78, 96, 13, 42, 88, 7, 12, 16])
{96, 7, 10, 42, 12, 13, 78, 16, 88}
The order was lost during conversion. How to preserve the order?
- How to get input without getting an error when we hit space or enter without actually entering the value?
For example, if the code was like : n = int(input())
and if the input given was just <Enter>
but the next line contains the actual input how to wait until a valid input is obtained?
I mean, I want like this as in C
language. If you write the code like scanf("%d",&n);
then it will ignore all the spaces and Enter key presses and will get the actual input. Also, there is another feature like getting the time like scanf("%d:%d", &h, &m);
which actually allows :
as an input that separates two different inputs.
I tried the input in two different ways: First:
>>>n = int(input())
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
n = int(input())
ValueError: invalid literal for int() with base 10: ''
Second:
>>> from sys import stdin
>>> n = int(stdin.readline())
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
n = int(stdin.readline())
ValueError: invalid literal for int() with base 10: '\n'
The only noticeable difference is that stdin
captures the return key while input()
just captures it as an empty string. But none of them implements the scanf()
function as explained above. How to implement this?
Solution
In order to preserve the order you cannot use the set
object.But you can use frozenset
.Frozen set is just an immutable version of a Python set object.
So it goes like this,
>>> a = [1,2,3,4,5]
>>> b = frozenset(a)
>>> print(a)
[1, 2, 3, 4, 5]
>>> print(b)
frozenset({1, 2, 3, 4, 5})
For your second issue I suggest using this code.It doesn't break from the loop until an integer is given.
>>> while 1:
try:
x = int(input().strip())
break
except ValueError:
pass
string.strip() is used to remove all leading and trailing whitespaces in a python string.It still works without string.strip() though. But it doesn't account for any '\n' of string values and loops until an integer is given.
In order to seperate the inputs by the ":" character in them you can simply use string.split(":")
.It returns a string with the values seperated.
>>> a = "1:2:3"
>>> b = a.split(":")
>>> print(b)
['1', '2', '3']
Hope this helps.
Answered By - AfiJaabb
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.