Skip to content

Instantly share code, notes, and snippets.

@sandutsar
Last active April 12, 2023 08:04
Show Gist options
  • Save sandutsar/4eba01da815299844ade59a9c0c82824 to your computer and use it in GitHub Desktop.
Save sandutsar/4eba01da815299844ade59a9c0c82824 to your computer and use it in GitHub Desktop.
Solution for Rosalind Python Village course
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Rosalind Python Village"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## INI1\n",
"\n",
"### Installing Python\n",
"\n",
"**Problem**\n",
"\n",
"After downloading and installing **Python**, type `import this` into the Python command line and see what happens. Then, click the \"Download dataset\" button below and copy the Zen of Python into the space provided."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter \"import this\" into your Python command line and see what happens.\n",
"\n"
]
}
],
"source": [
"with open('rosalind_ini1_1_dataset.txt', 'r') as file:\n",
" print(file.readline())"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The Zen of Python, by Tim Peters\n",
"\n",
"Beautiful is better than ugly.\n",
"Explicit is better than implicit.\n",
"Simple is better than complex.\n",
"Complex is better than complicated.\n",
"Flat is better than nested.\n",
"Sparse is better than dense.\n",
"Readability counts.\n",
"Special cases aren't special enough to break the rules.\n",
"Although practicality beats purity.\n",
"Errors should never pass silently.\n",
"Unless explicitly silenced.\n",
"In the face of ambiguity, refuse the temptation to guess.\n",
"There should be one-- and preferably only one --obvious way to do it.\n",
"Although that way may not be obvious at first unless you're Dutch.\n",
"Now is better than never.\n",
"Although never is often better than *right* now.\n",
"If the implementation is hard to explain, it's a bad idea.\n",
"If the implementation is easy to explain, it may be a good idea.\n",
"Namespaces are one honking great idea -- let's do more of those!\n"
]
}
],
"source": [
"import this"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Beautiful is better than ugly.\n",
"Explicit is better than implicit.\n",
"Simple is better than complex.\n",
"Complex is better than complicated.\n",
"Flat is better than nested.\n",
"Sparse is better than dense.\n",
"Readability counts.\n",
"Special cases aren't special enough to break the rules.\n",
"Although practicality beats purity.\n",
"Errors should never pass silently.\n",
"Unless explicitly silenced.\n",
"In the face of ambiguity, refuse the temptation to guess.\n",
"There should be one-- and preferably only one --obvious way to do it.\n",
"Although that way may not be obvious at first unless you're Dutch.\n",
"Now is better than never.\n",
"Although never is often better than *right* now.\n",
"If the implementation is hard to explain, it's a bad idea.\n",
"If the implementation is easy to explain, it may be a good idea.\n",
"Namespaces are one honking great idea -- let's do more of those!\n"
]
}
],
"source": [
"zen = \"\".join([this.d.get(c, c) for c in this.s][34:])\n",
"print(zen)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"with open('rosalind_ini1_1_output.txt', 'w') as file:\n",
" file.write(zen)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## INI2\n",
"\n",
"### Variables and Some Arithmetic\n",
"\n",
"**Problem**\n",
"\n",
"<span style='color:green'>Given:</span> Two positive integers **a** and **b**, each less than 1000.\n",
"\n",
"<span style='color:green'>Return:</span> The integer corresponding to the square of the hypotenuse of the right triangle whose legs have lengths **a** and **b**.\n",
"\n",
"**Notes:**\n",
"1. The dataset changes every time you click \"Download dataset\".\n",
"2. We check only your final answer to the *downloaded* dataset in the box below, not your code itself. If you would like to provide your code as well, you may use the upload tool. Please also note that the correct answer to this problem will not in general be 34; it is simply an example of what you should return in the specific case that the legs of the triangle have length 3 and 5.\n",
"\n",
"**Sample Dataset**\n",
"\n",
"```\n",
"3 5\n",
"```\n",
"\n",
"**Sample Output**\n",
"\n",
"```\n",
"34\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(842, 879)"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"with open('rosalind_ini2_1_dataset.txt', 'r') as file:\n",
" try:\n",
" a, b = list(map(int, file.readline().split()))\n",
" except ValueError as e:\n",
" print(f'Error: {e}!')\n",
"a, b"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"assert isinstance(a, int), f'Error: type(a) = {type(a).__name__} must be int!'\n",
"assert isinstance(b, int), f'Error: type(b) = {type(b).__name__} must be int!'\n",
"\n",
"assert a > 0, f'Error: a = {a} must be > 0!'\n",
"assert b > 0, f'Error: b = {b} must be > 0!'\n",
"\n",
"assert a < 1e3, f'Error: a = {a} must be < 1000!'\n",
"assert b < 1e3, f'Error: b = {b} must be < 1000!'"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1481605"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"hypotenuse_squared = a*a + b*b\n",
"hypotenuse_squared"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"with open('rosalind_ini2_1_output.txt', 'w') as file:\n",
" file.write(str(hypotenuse_squared))"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## INI3\n",
"\n",
"### Strings and Lists\n",
"\n",
"**Problem**\n",
"\n",
"<span style='color:green'>Given:</span> A string **s** of length at most 200 letters and four integers **a**, **b**, **c** and **d**.\n",
"\n",
"<span style='color:green'>Return:</span> The slice of this string from indices **a** through **b** and **c** through **d** (with space in between), *inclusively*. In other words, we should include elements **s[b]** and **s[d]** in our slice.\n",
"\n",
"**Sample Dataset**\n",
"\n",
"```\n",
"HumptyDumptysatonawallHumptyDumptyhadagreatfallAlltheKingshorsesandalltheKingsmenCouldntputHumptyDumptyinhisplaceagain.\n",
"22 27 97 102\n",
"```\n",
"\n",
"**Sample Output**\n",
"\n",
"```\n",
"Humpty Dumpty\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"20Gmkx6mKgyeSOdz1m2hAjLkTu6AnyVG6VYWfArxuoon2uzgxKubEqOdonthurus7jMuLdK3Y6IUAjfEkwuhCicLXzBlktYFblsrufQCNHxn1Clcocq0iOAKkHgSFvo8DkuhliqibUdiHVoly2mZk2FtJAEBt72ijZ4P9MWuckNwSfBuusG3QrxxQmbZN.\n",
"\n"
]
}
],
"source": [
"with open('rosalind_ini3_1_dataset.txt', 'r') as file:\n",
" s = file.readline()\n",
" try:\n",
" a, b, c, d = list(map(int, file.readline().split()))\n",
" except ValueError as e:\n",
" print(f'Error: {e}!')\n",
"print(s)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(54, 63, 129, 133)"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a, b, c, d"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"assert isinstance(s, str), f'Error: type(s) = {type(s).__name__} must be str!'\n",
"assert len(s) <= 2e2, f'Error: len(s) = {len(s)} must be <= 200!'\n",
"\n",
"assert isinstance(a, int), f'Error: type(a) = {type(a).__name__} must be int!'\n",
"assert isinstance(b, int), f'Error: type(b) = {type(b).__name__} must be int!'\n",
"assert isinstance(c, int), f'Error: type(c) = {type(c).__name__} must be int!'\n",
"assert isinstance(d, int), f'Error: type(d) = {type(d).__name__} must be int!'"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"('Odonthurus', 'kuhli')"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"string_slice = (s[a:b+1], s[c:d+1])\n",
"string_slice"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"with open('rosalind_ini3_1_output.txt', 'w') as file:\n",
" file.write(' '.join(string_slice))"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## INI4\n",
"\n",
"### Conditions and Loops\n",
"\n",
"**Problem**\n",
"\n",
"<span style='color:green'>Given:</span> Two positive integers **a** and **b** (**a** < **b** < **10000**).\n",
"\n",
"<span style='color:green'>Return:</span> The sum of all odd integers from **a** through **b**, inclusively.\n",
"\n",
"**Sample Dataset**\n",
"\n",
"```\n",
"100 200\n",
"```\n",
"\n",
"**Sample Output**\n",
"\n",
"```\n",
"7500\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(4694, 9007)"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"with open('rosalind_ini4_1_dataset.txt', 'r') as file:\n",
" try:\n",
" a, b = list(map(int, file.readline().split()))\n",
" except ValueError as e:\n",
" print(f'Error: {e}!')\n",
"a, b"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"assert isinstance(a, int), f'Error: type(a) = {type(a).__name__} must be int!'\n",
"assert isinstance(b, int), f'Error: type(b) = {type(b).__name__} must be int!'\n",
"\n",
"assert a < b, f'Error: a = {a} must be less than b = {b}!'\n",
"\n",
"assert a > 0, f'Error: a = {a} must be > 0!'\n",
"assert b > 0, f'Error: b = {b} must be > 0!'\n",
"\n",
"assert a < 1e4, f'Error: a = {a} must be < 10000!'\n",
"assert b < 1e4, f'Error: b = {b} must be < 10000!'"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"14777607"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"odd_sum = sum([num if num % 2 != 0 else 0 for num in range(a, b + 1)])\n",
"odd_sum"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"with open('rosalind_ini4_1_output.txt', 'w') as file:\n",
" file.write(str(odd_sum))"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## INI5\n",
"\n",
"### Working with Files\n",
"\n",
"**Problem**\n",
"\n",
"<span style='color:green'>Given:</span> A file containing at most 1000 lines.\n",
"\n",
"<span style='color:green'>Return:</span> A file containing all the even-numbered lines from the original file. Assume 1-based numbering of lines.\n",
"\n",
"**Sample Dataset**\n",
"\n",
"```\n",
"Bravely bold Sir Robin rode forth from Camelot\n",
"Yes, brave Sir Robin turned about\n",
"He was not afraid to die, O brave Sir Robin\n",
"And gallantly he chickened out\n",
"He was not at all afraid to be killed in nasty ways\n",
"Bravely talking to his feet\n",
"Brave, brave, brave, brave Sir Robin\n",
"He beat a very brave retreat\n",
"```\n",
"\n",
"**Sample Output**\n",
"\n",
"```\n",
"Yes, brave Sir Robin turned about\n",
"And gallantly he chickened out\n",
"Bravely talking to his feet\n",
"He beat a very brave retreat\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"`Twas brillig, and the slithy toves\n",
" Some things in life are bad, they can really make you mad\n",
" Did gyre and gimble in the wabe:\n",
" Other things just make you swear and curse\n",
" All mimsy were the borogoves,\n",
" When you're chewing on life's gristle, don't grumble give a whistle\n",
" And the mome raths outgrabe.\n",
" This will help things turn out for the best\n",
" \"Beware the Jabberwock, my son!\n",
" Always look on the bright side of life\n",
" The jaws that bite, the claws that catch!\n",
" Always look on the right side of life\n",
" Beware the Jubjub bird, and shun\n",
" If life seems jolly rotten, there's something you've forgotten\n",
" The frumious Bandersnatch!\"\n",
" And that's to laugh and smile and dance and sing\n",
" He took his vorpal sword in hand:\n",
" When you're feeling in the dumps, don't be silly, chumps\n",
" Long time the manxome foe he sought --\n",
" Just purse your lips and whistle, that's the thing\n",
" So rested he by the Tumtum tree,\n",
" So, always look on the bright side of death\n",
" And stood awhile in thought.\n",
" Just before you draw your terminal breath\n",
" And, as in uffish thought he stood,\n",
" Life's a counterfeit and when you look at it\n",
" The Jabberwock, with eyes of flame,\n",
" Life's a laugh and death's the joke, it's true\n",
" Came whiffling through the tulgey wood,\n",
" You see, it's all a show, keep them laughing as you go\n",
" And burbled as it came!\n",
" Just remember the last laugh is on you\n",
" One, two! One, two! And through and through\n",
" Always look on the bright side of life\n",
" The vorpal blade went snicker-snack!\n",
" And always look on the right side of life\n",
" He left it dead, and with its head\n",
" Always look on the bright side of life\n",
" He went galumphing back.\n",
" And always look on the right side of life\n",
"\n"
]
}
],
"source": [
"with open('rosalind_ini5_1_dataset.txt', 'r') as file:\n",
" lines = file.readlines()\n",
"print(*lines)"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"assert len(lines) <= 1e3, f'Error: len(lines) = {len(lines)} must be <= 1000!'"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Some things in life are bad, they can really make you mad\n",
" Other things just make you swear and curse\n",
" When you're chewing on life's gristle, don't grumble give a whistle\n",
" This will help things turn out for the best\n",
" Always look on the bright side of life\n",
" Always look on the right side of life\n",
" If life seems jolly rotten, there's something you've forgotten\n",
" And that's to laugh and smile and dance and sing\n",
" When you're feeling in the dumps, don't be silly, chumps\n",
" Just purse your lips and whistle, that's the thing\n",
" So, always look on the bright side of death\n",
" Just before you draw your terminal breath\n",
" Life's a counterfeit and when you look at it\n",
" Life's a laugh and death's the joke, it's true\n",
" You see, it's all a show, keep them laughing as you go\n",
" Just remember the last laugh is on you\n",
" Always look on the bright side of life\n",
" And always look on the right side of life\n",
" Always look on the bright side of life\n",
" And always look on the right side of life\n",
"\n"
]
}
],
"source": [
"even_lines = []\n",
"for i in range(len(lines)):\n",
" if i % 2 != 0:\n",
" even_lines += [lines[i]]\n",
"print(*even_lines)"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"with open('rosalind_ini5_1_output.txt', 'w') as file:\n",
" file.writelines(even_lines)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## INI6\n",
"\n",
"### Dictionaries\n",
"\n",
"**Problem**\n",
"\n",
"<span style='color:green'>Given:</span> A string **s** of length at most 10000 letters.\n",
"\n",
"<span style='color:green'>Return:</span> The number of occurrences of each word in ***s***, where words are separated by spaces. Words are case-sensitive, and the lines in the output can be in any order.\n",
"\n",
"**Sample Dataset**\n",
"\n",
"```\n",
"We tried list and we tried dicts also we tried Zen\n",
"```\n",
"\n",
"**Sample Output**\n",
"\n",
"```\n",
"and 1\n",
"We 1\n",
"tried 3\n",
"dicts 1\n",
"list 1\n",
"we 2\n",
"also 1\n",
"Zen 1\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"When I find myself in times of trouble Mother Mary comes to me Speaking words of wisdom let it be And in my hour of darkness she is standing right in front of me Speaking words of wisdom let it be Let it be let it be let it be let it be Whisper words of wisdom let it be And when the broken hearted people living in the world agree There will be an answer let it be For though they may be parted there is still a chance that they will see There will be an answer let it be Let it be let it be let it be let it be There will be an answer let it be Let it be let it be let it be let it be Whisper words of wisdom let it be Let it be let it be let it be let it be Whisper words of wisdom let it be And when the night is cloudy there is still a light that shines on me Shine until tomorrow let it be I wake up to the sound of music Mother Mary comes to me Speaking words of wisdom let it be Let it be let it be let it be yeah let it be There will be an answer let it be Let it be let it be let it be yeah let it be Whisper words of wisdom let it be\n",
"\n"
]
}
],
"source": [
"with open('rosalind_ini6_1_dataset.txt', 'r') as file:\n",
" s = file.readline()\n",
"print(s)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"assert isinstance(s, str), f'Error: type(s) = {type(s).__name__} must be str!'\n",
"assert len(s) <= 1e4, f'Error: len(s) = {len(s)} must be <= 10000!'"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'When': 1,\n",
" 'I': 2,\n",
" 'find': 1,\n",
" 'myself': 1,\n",
" 'in': 4,\n",
" 'times': 1,\n",
" 'of': 11,\n",
" 'trouble': 1,\n",
" 'Mother': 2,\n",
" 'Mary': 2,\n",
" 'comes': 2,\n",
" 'to': 3,\n",
" 'me': 4,\n",
" 'Speaking': 3,\n",
" 'words': 7,\n",
" 'wisdom': 7,\n",
" 'let': 30,\n",
" 'it': 36,\n",
" 'be': 41,\n",
" 'And': 3,\n",
" 'my': 1,\n",
" 'hour': 1,\n",
" 'darkness': 1,\n",
" 'she': 1,\n",
" 'is': 4,\n",
" 'standing': 1,\n",
" 'right': 1,\n",
" 'front': 1,\n",
" 'Let': 6,\n",
" 'Whisper': 4,\n",
" 'when': 2,\n",
" 'the': 4,\n",
" 'broken': 1,\n",
" 'hearted': 1,\n",
" 'people': 1,\n",
" 'living': 1,\n",
" 'world': 1,\n",
" 'agree': 1,\n",
" 'There': 4,\n",
" 'will': 5,\n",
" 'an': 4,\n",
" 'answer': 4,\n",
" 'For': 1,\n",
" 'though': 1,\n",
" 'they': 2,\n",
" 'may': 1,\n",
" 'parted': 1,\n",
" 'there': 2,\n",
" 'still': 2,\n",
" 'a': 2,\n",
" 'chance': 1,\n",
" 'that': 2,\n",
" 'see': 1,\n",
" 'night': 1,\n",
" 'cloudy': 1,\n",
" 'light': 1,\n",
" 'shines': 1,\n",
" 'on': 1,\n",
" 'Shine': 1,\n",
" 'until': 1,\n",
" 'tomorrow': 1,\n",
" 'wake': 1,\n",
" 'up': 1,\n",
" 'sound': 1,\n",
" 'music': 1,\n",
" 'yeah': 2}"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"word_dict = {}\n",
"words = s.split()\n",
"for word in words:\n",
" if word not in word_dict.keys():\n",
" word_dict[word] = 1\n",
" else:\n",
" word_dict[word] += 1\n",
"word_dict"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"with open('rosalind_ini6_1_output.txt', 'w') as file:\n",
" for key, value in word_dict.items():\n",
" file.write(f'{key} {value}\\n')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment