-
Notifications
You must be signed in to change notification settings - Fork 20
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
Week1 #22
base: main
Are you sure you want to change the base?
Week1 #22
Changes from all commits
0e19e59
7e863e6
06a235d
3cb12f0
45e224f
38f29a3
2fa9d2c
cb47fca
9317aa5
b7089c2
d1704cc
5dce0e1
b731245
62ef3bc
3986049
2793d99
211c608
835b498
45e9ef6
f25d7c7
e40df5b
597a416
e7f8524
cf6bf4e
e96fab2
6fe5cdf
c1ef49d
57848fa
21042cf
9d4b342
32b45f6
996adba
c771438
8e2177c
41261c6
e4dc9e8
1076374
031310e
5f6e285
585b8bf
c059195
9c0de59
0de2067
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
# 1. Opposite number. https://www.codewars.com/kata/reviews/56deebdf6a5c28baa900003b/groups/56ef47f804b6a49d7100190f | ||
|
||
```python | ||
def opposite(number): | ||
return -1 * number | ||
``` | ||
|
||
# 2. Even or Odd. https://www.codewars.com/kata/reviews/53da3de52a289a37bc00128a/groups/53ea21bc7b5dfef3e30006f8 | ||
|
||
```python | ||
def even_or_odd(number): | ||
if number % 2 != 0: | ||
return('Odd') | ||
else: | ||
return('Even') | ||
|
||
#второе решение | ||
|
||
def even_or_odd(number): | ||
return 'Odd' if x % 2 == 0 else 'Even' | ||
``` | ||
|
||
# 3. Vowel Count. https://www.codewars.com/users/VicDik/completed_solutions | ||
|
||
```python | ||
#Старое решение | ||
def get_count(input_str): | ||
# vowels = ['a', 'e', 'i', 'o', 'u'] | ||
vowels = "aeuoi" | ||
return sum(input_str.count(i) for i in vowels) | ||
|
||
#Новое решение | ||
def get_count(input_str): | ||
return sum(letter in 'aeiou' for letter in input_str) | ||
``` | ||
|
||
# 4. Disemvowel Trolls. https://www.codewars.com/users/VicDik/completed_solutions | ||
|
||
```python | ||
#Старое решение | ||
|
||
def disemvowel(string_): | ||
for i in 'aeiouAEIOU': | ||
string_ = string_.replace(i,'') | ||
return string_ | ||
|
||
#Новое решение | ||
|
||
def disemvowel2(string): | ||
return ''.join(i for i in string if i not in "aeiouAEIOU") | ||
|
||
#Еще одно | ||
|
||
def disemvowel(string): | ||
return ''.join(filter(lambda x: not x in "aeiouAEIOU", string)) | ||
``` | ||
|
||
# 5. Get the Middle Character. https://www.codewars.com/users/VicDik/completed_solutions | ||
|
||
```python | ||
def get_middle(s): | ||
if len(s) % 2 == 0: | ||
return s[(len(s) // 2) - 1 : (len(s) // 2) + 1] | ||
else: | ||
return s[len(s) // 2] | ||
``` | ||
|
||
# 6. All Star Code Challenge #1. https://www.codewars.com/kata/reviews/586435fe812998c93400129b/groups/586570e0ece9e8b0a2000ed8 | ||
|
||
```python | ||
def sum_ppg(player_one, player_two): | ||
return player_one['ppg'] + player_two['ppg'] | ||
``` | ||
|
||
# 7. Who likes it?. https://www.codewars.com/users/VicDik/completed_solutions | ||
|
||
```python | ||
def likes(names): | ||
if len(names) == 0: | ||
return 'no one likes this' | ||
elif len(names) == 1: | ||
return f'{names[0]} likes this' | ||
elif len(names) == 2: | ||
return f'{names[0]} and {names[1]} like this' | ||
elif len(names) == 3: | ||
return f'{names[0]}, {names[1]} and {names[2]} like this' | ||
else: | ||
return f'{names[0]}, {names[1]} and {len(names) - 2} others like this' | ||
``` | ||
|
||
# 8. Array_diff. https://www.codewars.com/users/VicDik/completed_solutions | ||
|
||
```python | ||
#Старое решение | ||
|
||
def array_diff(a, b): | ||
list_1 = [] | ||
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 i in a: | ||
if i in b: | ||
pass | ||
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. if ... pass else something не надо испльзовать |
||
else: | ||
list_1.append(i) | ||
return(list_1) | ||
|
||
#Новое решение | ||
|
||
def array_diff(a,b): | ||
return [i for i in a if not (i in b)] | ||
|
||
``` | ||
|
||
# 9. All Star Code Challenge #22. https://www.codewars.com/users/VicDik/completed_solutions | ||
|
||
```python | ||
def to_time(seconds): | ||
time = f'{seconds//3600} hour(s) and {seconds%3600//60} minute(s)' | ||
return time | ||
``` | ||
|
||
# 10. Unique on order. | ||
|
||
```python | ||
#Старое исправленное решение | ||
|
||
def unique_on_order(unique:str): | ||
elements = [] | ||
len_unique = len(unique) | ||
for id in range(len_unique): | ||
if id == len_unique - 1: | ||
elements.append(unique[id]) | ||
elif unique[id] == unique[id + 1]: | ||
pass | ||
else: | ||
elements.append(unique[id]) | ||
return elements | ||
|
||
#Сначала я сделала так | ||
|
||
def unique_on_order2(unique): | ||
unique_list = [] | ||
for i in unique: | ||
if len(unique_list) == 0 or i != unique_list[-1]: | ||
unique_list.append(i) | ||
print(unique_list) | ||
|
||
#Не поняла, как решать через filter в одну строчку, но сделала в одну вот так | ||
|
||
unique_on_order3 = lambda str_unique: [str_unique[i] for i in range(len(str_unique)) if i == 0 or str_unique[i] != str_unique[i - 1]] | ||
``` |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
GitHub: https://github.com/VicDik | ||
|
||
Розалинд: http://rosalind.info/users/VicDik/ | ||
|
||
Codewars: https://www.codewars.com/users/VicDik | ||
|
||
Codingame: https://www.codingame.com/profile/773f02f05bbfec669c2f6de7a19cc4560302934 |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
# Введение | ||
|
||
### Ясно: | ||
|
||
* **Адапционизм/Adaptationism** - also known as functionalism, is the Darwinian view that many physical and psychological traits of organisms are evolved adaptations. | ||
|
||
* **Панадаптационизм/Panadaptationism** - Is the strong form of this, deriving from the early 20th century modern synthesis, that all traits are adaptations, a view now shared by few biologists. Короче говоря, существует много штук в эволюции для выполнения различных функций, хотя их происхождение неадаптивно. В панадаптационизме все относят к адаптациям в ходе эволюции. | ||
|
||
### Непонятно: | ||
|
||
* **Синтетичсекая теория эволюции/Modern synthesis** | ||
|
||
# Глава 1. | ||
|
||
## Дарвин и первая синтетическая теория | ||
|
||
### Ясно: | ||
|
||
### Непонятно: | ||
|
||
* **Кошмар Дженкина или "болотный аргумент/Swamping argument** - Принципиальное возражение против теории Дарвина о постепенном образовании новых биологических видов путём сохранения благоприятного признака естественным отбором, выдвинутое английским инженером Дженкином. Согласно ему, случайно появившийся у отдельной особи полезный признак в группе организмов (популяции) постепенно будет нивелирован скрещиванием с обычными особями. Это логическое затруднение преодолено с созданием популяционной генетики. В 1870 году в журнале «Nature» была опубликована статья первого помощника редактора журнала, ботаника Альфреда Уильяма Беннетта под названием «Теория естественного отбора с математической точки зрения»[7], где высказывались соображения, сходные с идеями Дженкина. Суть их сводилась к следующему. Допустим, для получения полезного признака требуется 10 поколений, причём в каждом признак может изменяться 20 способами. В таком случае для обнаружения полезного признака требуется перебрать 2010 особей. Пусть численность особей в популяции не превышает 106. В этом случае для образования нового признака понадобится 1013 особей, или 107 поколений. Следовательно, естественный подбор не может быть эффективным как фактор образования новых видов. Возражения Дженкина основывались на непрерывной теории наследственности. Открытие дискретности наследственного материала позволило преодолеть «кошмар Дженкина». Генетика показала, что ген признака может не подвергаться естественному отбору, находясь в рецессивном состоянии, однако и здесь появились новые проблемы, раскрытые биологом Холдейном (см. дилемма Холдейна). Хотя новый полезный признак и не пропадает бесследно в генофонде популяции, его распространение в ней может быть процессом очень длительным, причём успех вовсе не гарантирован. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
# 1. Installing Python. http://rosalind.info/problems/ini1/ | ||
|
||
```python | ||
>>> import this | ||
The Zen of Python, by Tim Peters | ||
|
||
Beautiful is better than ugly. | ||
Explicit is better than implicit. | ||
Simple is better than complex. | ||
Complex is better than complicated. | ||
Flat is better than nested. | ||
Sparse is better than dense. | ||
Readability counts. | ||
Special cases aren't special enough to break the rules. | ||
Although practicality beats purity. | ||
Errors should never pass silently. | ||
Unless explicitly silenced. | ||
In the face of ambiguity, refuse the temptation to guess. | ||
There should be one-- and preferably only one --obvious way to do it. | ||
Although that way may not be obvious at first unless you're Dutch. | ||
Now is better than never. | ||
Although never is often better than *right* now. | ||
If the implementation is hard to explain, it's a bad idea. | ||
If the implementation is easy to explain, it may be a good idea. | ||
Namespaces are one honking great idea -- let's do more of those! | ||
>>> | ||
``` | ||
|
||
# 2. Variables and Some Arithmetic. http://rosalind.info/problems/ini2/ | ||
|
||
```python | ||
def hypotenuse(a, b): | ||
c = int(( a ** 2 + b ** 2)) | ||
return c | ||
``` | ||
|
||
# 3. Strings and Lists. http://rosalind.info/problems/ini3/ | ||
|
||
```python | ||
def file_slice(file): | ||
with open(file, 'r') as fr: | ||
data = fr.readlines() | ||
indexes = list(map(lambda x: int(x), data[1].split())) | ||
with open(file.replace('.txt', '_test.txt'), 'w') as fw: | ||
fw.write(' '.join([data[0][indexes[i]:indexes[i + 1] + 1] for i in range(0, len(indexes), 2)])) | ||
``` | ||
|
||
# 4. Conditions and Loops. http://rosalind.info/problems/ini4/ | ||
|
||
```python | ||
def sum_odd(file): | ||
with open(file, 'r') as fr: | ||
a, b = [int(i) for i in fr.readlines()[0].split()] | ||
with open(file.replace('.txt', '_sum.txt'), 'w') as fw: | ||
fw.write(str(sum((i for i in range(a, b + 1) if i % 2 != 0)))) | ||
``` | ||
|
||
# 5. Working files. http://rosalind.info/problems/ini5/ | ||
|
||
```python | ||
#решение без enumerate, читаемое | ||
|
||
def even_lines(file): | ||
# избавляемся от множестевенной вложенности, потому что это тоже не очень | ||
with open(file) as fr, open(file.replace('.txt', '_even.txt'), 'w') as fw: | ||
i = 0 | ||
for lines in fr: | ||
i += 1 | ||
if i % 2 == 0: | ||
fw.write(lines) | ||
|
||
#тоже самое, но с enumerate :) | ||
|
||
def even_lines2(file): | ||
with open(file) as fr, open(file.replace('.txt', '_even2.txt'), 'w') as fw: | ||
data = fr.readlines() | ||
for i in enumerate(data): | ||
if (i[0] + 1) % 2 == 0: | ||
fw.write(i[1]) | ||
``` | ||
|
||
# 6. Dictionaries. http://rosalind.info/problems/ini6/ | ||
|
||
```python | ||
def count_words(file): | ||
with open(file) as fr: | ||
words_list = fr.read().strip().split() | ||
words_set = set(words_list) | ||
words_dict = {x:words_list.count(x) for x in words_set} | ||
for i in words_dict: | ||
print(f'{i} {words_dict[i]}') | ||
``` |
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.
а еще можно без !=-