-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconversion.py
More file actions
84 lines (58 loc) · 1.79 KB
/
conversion.py
File metadata and controls
84 lines (58 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from dataclasses import dataclass
import random
from typing import List
bindigits = "01"
hexdigits = "0123456789ABCDEF"
def randbin() -> str:
return "".join(random.choice(bindigits) for _ in range(8))
def randdec() -> int:
return random.randint(0, 255)
def randhex() -> str:
return "".join(random.choice(hexdigits) for _ in range(2))
def isbin(value: str) -> bool:
if len(value) < 2:
return False
if not value.startswith("0b"):
return False
for char in value[2:]:
if char not in "01":
return False
return True
def isdec(value: str) -> bool:
return value.isdecimal()
def ishex(value: str) -> bool:
if len(value) < 2:
return False
if not value.startswith("0x"):
return False
for char in value[2:]:
if char not in hexdigits:
return False
return True
def generate_questions(num: int) -> "List[Question]":
questions = []
for i in range(1, num + 1):
Question = random.choice((BinaryQuestion,
DecimalQuestion,
HexadecimalQuestion))
questions.append(Question.random(label=str(i)))
return questions
@dataclass(kw_only=True)
class Question:
label: str
value: str
class BinaryQuestion(Question):
type: str = "bin"
@classmethod
def random(cls, label: str) -> "BinaryQuestion":
return cls(label=label, value=randbin())
class DecimalQuestion(Question):
type: str = "dec"
@classmethod
def random(cls, label: str) -> "DecimalQuestion":
return cls(label=label, value=randdec())
class HexadecimalQuestion(Question):
type: str = "hex"
@classmethod
def random(cls, label: str) -> "HexadecimalQuestion":
return cls(label=label, value=randhex())