-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil.py
76 lines (52 loc) · 1.78 KB
/
util.py
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
#!/usr/bin/env python3
"""Various utility functions that aren't related to Challonge things."""
import argparse
import random
def shuffle(values):
"""Returns the list of values shuffled.
This is different from random.shuffle because it returns a new list
instead of operating in-place.
Args:
values: A list of arbitrary values.
Returns:
The values shuffled into a random order.
"""
return random.sample(values, len(values))
def flatten(lists):
"""Flattens a list of lists into a single list of values.
Args:
lists: A list of lists.
Returns:
The list flattened into a single list, with the same order of values.
"""
return [x for sublist in lists for x in sublist]
def str_to_bool(s):
"""Converts a string value to a boolean value.
Args:
s: The string to convert to a boolean value.
Raises:
argparse.ArgumentTypeError: If the string doesn't correspond to a bool.
Returns:
The corresponding boolean value for the string.
"""
if s.lower() in ("yes", "true", "t", "y", "1"):
return True
elif s.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise argparse.ArgumentTypeError("Boolean value expected.")
def prompt_yes_no(prompt):
"""Prompts the user to respond yes/no to a question.
Asks repeatedly until valid input is given.
Args:
prompt: The prompt to use. This should not include "[y/n]".
Returns:
True if the user answered yes, False if they answered yes.
"""
while True:
print((prompt + " [y/n]"), end=" ")
choice = input().lower()
try:
return str_to_bool(choice)
except argparse.ArgumentTypeError:
print("Invalid response. Please say 'y' or 'n'.")