-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Added phone number generator and normaliser script file #11
Changes from 1 commit
81120a7
882adba
ed7ed92
df6ff7e
621afa2
e078b83
2c05a41
3cf67e2
664b056
f34a47d
775b00b
ef85dbb
541f166
d8e1c73
bea61fc
7b09b78
61993df
25c7aaf
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
- Loading branch information
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
#!/usr/bin/env python3 | ||
|
||
import random | ||
|
||
|
||
def rand_num_gen(): | ||
# генерирует случайный номер для теста | ||
# args: none | ||
# return: 11-digit number | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Когда пишем код, докстринги обязательно на английском! По формату докстрингов лучше придерживаться чего-то типа: def rand_num_gen() -> str:
"""
Generates random numbers for the test
:return: string representation of the number
""" Если аргументов нет, их можно не вносить в доки. И лучше добавлять аннотацию типов :) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. fixed |
||
ans = '8' | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. К сожалению, данная логика будет работать только для +7-... или 8-... номеров, т.е. для России. В контексте ru номеров - ок, но в общем случае тяжеловато. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. В принципе, для нас, для начала (как стартовая точка отсчета) - норм. В дальнейшем надо будет подумать как ставить код, или может использовать API какой-нибудь. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Можно попробовать погуглить, есть ли какие-нибудь онлайн сервисы генерации разных форматов. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. fixed for now, might need a second review |
||
for i in range(1, 11): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Можно немного проще: for _ in range(10) Т.к. i ты не используешь здесь, а просто генерируешь случайно. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. fixed |
||
ans += str(random.randint(1, 9)) | ||
return ans | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Можно сделать так: return "8" + "".join([str(random.randint(1, 9)) for _ in range(10)]) Попробуй разобраться в этой строке. Если не поймешь, посмотрим вместе. Тут python list comprehension, можешь погуглить. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. поняла и исправила, так что тоже fixed :) |
||
|
||
|
||
def normalise(phone_num): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Добавить type annotation, какой тип у аргумента и какой возвращается |
||
# приводит любой номер в определенный формат - 7xxxxxxxxxxx | ||
# args: номер для нормализации в виде строки | ||
# return: 7xxxxxxxxxxx | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Заменить на английский комментарий, как в других скриптах. """
description
:param phone_num:
:return:
""" |
||
numbers = [digit for digit in phone_num if digit.isdigit()] | ||
norm_num = "".join(numbers) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ага, как раз list comprehension. хорошо :) |
||
if len(norm_num) == 11: | ||
norm_num = '7' + norm_num | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Смотри :)
Это результат работы нормалайзера. Если мы говорим про ru номера, то у нас 11 знаков, а тут, получается, если у нас уже есть 11 знаков, мы добавляем 7. 7-8-913-881-11-11 Немножко неправильно :) |
||
return norm_num | ||
|
||
|
||
def gen_all(norm_num): | ||
# генерирует все возможные варианты написания | ||
# args: нормализированный номер | ||
# return: список строк номеров | ||
number_groups = [norm_num[0], norm_num[1:4], norm_num[4:7], norm_num[7:9], norm_num[9:11]] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ok 👌 number_groups = [norm_num[first: second] for first, second in [(0, 1), (1, 4), (4, 7), (7, 9), (9, 11)]] |
||
num_list = [] | ||
separators = ["", "-", "."] | ||
for sep in separators: # автоматизированный процесс для некоторых | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. И коммент лучше ставить над кодом, и на английском # Automate some separations of numbers, etc...
for sep ... |
||
num_list.append(sep.join(number_groups)) | ||
num_list.append("+" + sep.join(number_groups)) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Как пример: joined = sep.join(number_groups)
num_list.extend((joined, f"+{joined}")) Один раз собираем цифры, один раз делаем добавление в лист - вместо 2 джойнов 1, вместо 2 аппендов 1 экстенд) |
||
# отдельный пример вне цикла | ||
num_list.append( | ||
number_groups[0] + "(" + number_groups[1] + ")" + number_groups[2] + number_groups[3] + number_groups[4]) | ||
num_list.append( | ||
"+" + number_groups[0] + "(" + number_groups[1] + ")" + number_groups[2] + number_groups[3] + number_groups[4]) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Можно сделать вот так до цикла phone_w_brackets = "{prefix}({code}){rest}".format(
prefix=number_groups[0],
code=number_groups[1],
rest="".join(number_groups[2:])
)
num_list.extend((phone_w_brackets, f"+{phone_w_brackets}")) |
||
|
||
return num_list | ||
|
||
|
||
# тест для проверки кода | ||
def test(): | ||
rand_number_test = rand_num_gen() | ||
normal_num = normalise(rand_number_test) | ||
final_list = gen_all(normal_num) | ||
print(final_list) | ||
# этот цикл чтобы убедиться, что нормализатор работает на любых форматах | ||
for number in final_list: | ||
print(normalise(number)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Если не ошибаюсь, то в скрипте из
random
используется толькоrandint
. В этом случае можно толькоrandint
и импортировать:Или:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixed