Skip to content

Instantly share code, notes, and snippets.

@ggurdanikita
Last active April 14, 2021 15:45
Show Gist options
  • Save ggurdanikita/96893e6dfe2293cb8ee21c8fdf3669bb to your computer and use it in GitHub Desktop.
Save ggurdanikita/96893e6dfe2293cb8ee21c8fdf3669bb to your computer and use it in GitHub Desktop.
from random import choice, shuffle
from collections import Counter
symbols = "abcdefghijklmnopqrstuvwxyz"
def gen_random_string(N):
"""
Generates a random string
"""
return ''.join(choice(symbols) for _ in range(N))
def normalize(res_dict):
"""
Может получиться так, что осталось добавить один символ, но все буквы уже встречаются нечетное кол-во раз
поэтому я решил вырезать все вхождения первой буквы и плюсовать их ко второй, ну и +1, чтоб получить нужную длину
"""
tmp = list(res_dict.keys())
tmp.sort()
if res_dict and list(symbols) == tmp:
res_dict[list(res_dict.keys())[1]] = res_dict.pop(list(res_dict.keys())[0]) + 1
def gen_odd_string(N, res_dict):
"""
Generates a string with an odd number of occurrences of characters
"""
s = gen_random_string(N)
c = Counter(s)
print(f"Counter: {c}")
# qwe(res_dict)
for symbol, frequency in c.items():
res_dict[symbol] = res_dict.get(symbol, 0) + frequency
for symbol, frequency in res_dict.items():
print(f"DEBUG: symbol: {symbol}, frequency {frequency}")
res_dict[symbol] = frequency - 1 if frequency % 2 == 0 else frequency
print(res_dict)
return "".join(i for i in [k * v for k, v in res_dict.items()])
def solution(N):
# write your code in Python 3.6
res_dict = {}
result = gen_odd_string(N, res_dict)
print(f"LEN: {len(result)}")
while len(result) != N:
result = gen_odd_string(N - len(result), res_dict)
print(f"LEN: {len(result)}")
if len(result) == N - 1:
normalize(res_dict)
break
# Shuffle string
tmp_list = list(result)
shuffle(tmp_list)
return ''.join(tmp_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment