diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7b91a09 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +refactorlist.py +numpyedit.py +datastredit.py +pokeapi.py \ No newline at end of file diff --git a/Python-ifed.ipynb b/Python-ifed.ipynb index ee9444d..926fb73 100644 --- a/Python-ifed.ipynb +++ b/Python-ifed.ipynb @@ -62,15 +62,15 @@ "### Describe what each of the following means\n", "\n", "#### Production\n", - "(Insert answer here)\n", + "Production programming involves creating or modifying a software product to meet the needs of real customers. Production means anything that you need to work reliably, and consistently. When the code runs on a production system, that means it is being used by the intended audience in a real-world situation.\n", "#### Clean \n", - "(Insert answer here)\n", + "Clean coding is a reader-focused development style that produces software that’s easy to write, read, and maintain. Clean code is code that is easy to understand and easy to change.\n", "#### Modular\n", - "(Insert answer here)\n", + "Modular means a design approach that subdivides a system into smaller parts that can be independently created and then used in different systems. These design approach is actually increase development time for programmers. Writing modular code means breaking down big functions into several smaller functions.\n", "#### Module\n", - "(Insert answer here)\n", + "A module is a number of distinct but interrelated units from which a program may be built up or into which a complex activity may be analysed.\n", "#### Refactoring code\n", - "(Insert answer here)" + "In computer programming and software design, code refactoring is the process of restructuring existing computer code—changing the factoring—without changing its external behavior. Refactoring is intended to improve the design, structure, and/or implementation of the software, while preserving its functionality." ] }, { @@ -92,17 +92,17 @@ ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], "source": [ "import pandas as pd\n", "df = pd.read_csv('matches.csv', sep=',')\n", "df.set_index('id',inplace=True)\n", "df.drop('umpire3',axis=1,inplace=True)\n", "df.head()" - ] + ], + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", @@ -112,10 +112,6 @@ ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], "source": [ "new_df = df.rename(columns={'team 1': 'team_1',\n", " 'team 2': 'team_2',\n", @@ -128,7 +124,11 @@ " 'umpire 2':'umpire_2'\n", " })\n", "new_df.head()" - ] + ], + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", @@ -138,10 +138,6 @@ ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], "source": [ "labels = list(df.columns)\n", "labels[0] = labels[0].replace(' ', '_')\n", @@ -156,7 +152,11 @@ "labels[10] = labels[10].replace(' ', '_')\n", "df.columns = labels\n", "df.head()" - ] + ], + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", @@ -166,13 +166,14 @@ ] }, { + "source": [ + "df.columns=[x.replace(' ','_') for x in list(df.columns)]\n", + "df.head()" + ], "cell_type": "code", - "execution_count": null, "metadata": {}, - "outputs": [], - "source": [ - "# Insert your solution here" - ] + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", @@ -208,7 +209,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 4, "metadata": {}, "outputs": [], "source": [ @@ -219,7 +220,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 5, "metadata": {}, "outputs": [], "source": [ @@ -232,10 +233,6 @@ ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], "source": [ "start = time.time()\n", "verified_elements = []\n", @@ -246,7 +243,11 @@ "\n", "print(len(verified_elements))\n", "print('Duration: {} seconds'.format(time.time() - start))" - ] + ], + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", @@ -256,16 +257,15 @@ ] }, { + "source": [ + "start = time.time()\n", + "verified_elements=np.nonzero(np.isin(np.array(subset_elements), np.array(all_elements)))\n", + "print(len(verified_elements[0]),'Duration: {} seconds'.format(time.time() - start),sep='\\n')" + ], "cell_type": "code", - "execution_count": null, "metadata": {}, - "outputs": [], - "source": [ - "# Insert answer here\n", - "\n", - "print(len(verified_elements))\n", - "print('Duration: {} seconds'.format(time.time() - start))" - ] + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", @@ -275,20 +275,17 @@ ] }, { + "source": [ + "start = time.time()\n", + "verified_elements=set(subset_elements) & set(all_elements)\n", + "print(len(verified_elements),'Duration: {} seconds'.format(time.time() - start),sep='\\n')" + ], "cell_type": "code", - "execution_count": null, "metadata": {}, - "outputs": [], - "source": [ - "# Insert answer here\n", - "\n", - "print(len(verified_elements))\n", - "print('Duration: {} seconds'.format(time.time() - start))" - ] + "execution_count": null, + "outputs": [] }, { - "cell_type": "markdown", - "metadata": {}, "source": [ "# Step 4\n", "# Documentation\n", @@ -303,7 +300,9 @@ "https://www.datacamp.com/community/tutorials/documenting-python-code\n", "\n", "do not add this code to the notebook instead create a new python file called step_4.py and define the functions as well as a main to test the working of all the functions make sure to version this file as well on the commit message __step 4 completed__" - ] + ], + "cell_type": "markdown", + "metadata": {} }, { "cell_type": "markdown", @@ -329,13 +328,13 @@ ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], "source": [ "! pytest test_nearest_square.py" - ] + ], + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", @@ -385,13 +384,24 @@ ] }, { + "source": [ + "import requests as rq, sys\n", + "pokemon='golduck' #set pokemon here\n", + "def check(res): #check for errors\n", + " try:\n", + " res.raise_for_status()\n", + " except Exception as exc:\n", + " print('Error: '+exc)\n", + " sys.exit(1)\n", + "#code\n", + "res=rq.get('https://pokeapi.co/api/v2/pokemon/'+pokemon)\n", + "check(res)\n", + "print(res.json()['types'][0]['type']['name'])" + ], "cell_type": "code", - "execution_count": 1, "metadata": {}, - "outputs": [], - "source": [ - "# Insert your code here" - ] + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", @@ -403,13 +413,29 @@ ] }, { + "source": [ + "import requests as rq, sys\n", + "pokemon='golduck' #set pokemon here\n", + "def check(res): #check for errors\n", + " try:\n", + " res.raise_for_status()\n", + " except Exception as exc:\n", + " print('Error: '+exc)\n", + " sys.exit(1)\n", + "#code\n", + "res=rq.get('https://pokeapi.co/api/v2/pokemon/'+pokemon)\n", + "check(res)\n", + "res=rq.get(res.json()['types'][0]['type']['url'])\n", + "lst=res.json()['damage_relations']\n", + "l=[]\n", + "for x in ['double_damage_from','half_damage_from']:\n", + " l+=[lst[x][y]['name'] for y in range(len(lst[x]))]\n", + "print(l)" + ], "cell_type": "code", - "execution_count": 2, "metadata": {}, - "outputs": [], - "source": [ - "# Insert your code here" - ] + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", @@ -419,13 +445,32 @@ ] }, { + "source": [ + "import requests as rq, sys\n", + "pokemon='golduck' #set pokemon here\n", + "def check(res): #check for errors\n", + " try:\n", + " res.raise_for_status()\n", + " except Exception as exc:\n", + " print('Error: '+exc)\n", + " sys.exit(1)\n", + "#code\n", + "res=rq.get('https://pokeapi.co/api/v2/pokemon/'+pokemon)\n", + "check(res)\n", + "res=rq.get(res.json()['types'][0]['type']['url'])\n", + "lst=res.json()['damage_relations']\n", + "for x in ['double_damage_from']:\n", + " for y in range(len(lst[x])):\n", + " print('Type:'+lst[x][y]['name'])\n", + " r=rq.get('https://pokeapi.co/api/v2/type/'+lst[x][y]['name'])\n", + " check(r)\n", + " r=r.json()['pokemon']\n", + " print([r[z]['pokemon']['name'] for z in range(5)])" + ], "cell_type": "code", - "execution_count": 3, "metadata": {}, - "outputs": [], - "source": [ - "# Insert your code here" - ] + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", @@ -437,28 +482,13 @@ ] }, { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\u001b[1m============================= test session starts ==============================\u001b[0m\n", - "platform darwin -- Python 3.8.5, pytest-6.2.1, py-1.10.0, pluggy-0.13.1\n", - "rootdir: /Users/abhijitramesh/development/Python-ifed\n", - "collected 4 items \u001b[0m\n", - "\n", - "test_abilities.py \u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m [100%]\u001b[0m\n", - "\n", - "\u001b[32m============================== \u001b[32m\u001b[1m4 passed\u001b[0m\u001b[32m in 2.75s\u001b[0m\u001b[32m ===============================\u001b[0m\n" - ] - } - ], "source": [ "!pytest test_abilities.py" - ] + ], + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", @@ -515,7 +545,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.9" + "version": "3.9.1-final" } }, "nbformat": 4, diff --git a/__pycache__/ability.cpython-39.pyc b/__pycache__/ability.cpython-39.pyc new file mode 100644 index 0000000..a27be42 Binary files /dev/null and b/__pycache__/ability.cpython-39.pyc differ diff --git a/__pycache__/nearest_square.cpython-39.pyc b/__pycache__/nearest_square.cpython-39.pyc new file mode 100644 index 0000000..ca4ff23 Binary files /dev/null and b/__pycache__/nearest_square.cpython-39.pyc differ diff --git a/__pycache__/pokemon.cpython-39.pyc b/__pycache__/pokemon.cpython-39.pyc new file mode 100644 index 0000000..2b8ca61 Binary files /dev/null and b/__pycache__/pokemon.cpython-39.pyc differ diff --git a/__pycache__/test_abilities.cpython-39-pytest-6.2.1.pyc b/__pycache__/test_abilities.cpython-39-pytest-6.2.1.pyc new file mode 100644 index 0000000..4560262 Binary files /dev/null and b/__pycache__/test_abilities.cpython-39-pytest-6.2.1.pyc differ diff --git a/__pycache__/test_nearest_square.cpython-39-pytest-6.2.1.pyc b/__pycache__/test_nearest_square.cpython-39-pytest-6.2.1.pyc new file mode 100644 index 0000000..c00ef03 Binary files /dev/null and b/__pycache__/test_nearest_square.cpython-39-pytest-6.2.1.pyc differ diff --git a/ability.py b/ability.py new file mode 100644 index 0000000..12d3a9b --- /dev/null +++ b/ability.py @@ -0,0 +1,19 @@ +import requests as rq, sys +def check(res): #check for errors + try: + res.raise_for_status() + except Exception as exc: + print('Error: '+exc) + sys.exit(1) +def ability(pokemon): + '''Returns all abilities of the pokemon + + Parameters: + pokemon (str): Name of pokemon + + Returns: + list: A list of all abilities of the pokemon''' + res=rq.get('https://pokeapi.co/api/v2/pokemon/'+pokemon) + check(res) + lst=res.json()['abilities'] + return [lst[i]['ability']['name'] for i in range(len(lst))] \ No newline at end of file diff --git a/nearest_square.py b/nearest_square.py new file mode 100644 index 0000000..e2202b7 --- /dev/null +++ b/nearest_square.py @@ -0,0 +1,12 @@ +def nearest_square(num): + '''Returns a perfect square less than or equal to n. + If n is negative, returns 0 + + Parameters: + num (int): Upper limit of perfect square (inclusive) + + Returns: + int: Perfect number less than or equal to num''' + if num<0: + return 0 #returns 0 if n is negative + return int(num**0.5)**2 #First rooting the number, then removing fractional part, and then squaring the number \ No newline at end of file diff --git a/pokedex.py b/pokedex.py new file mode 100644 index 0000000..4eaa2d7 --- /dev/null +++ b/pokedex.py @@ -0,0 +1,31 @@ +#import all necessary packages +import pokemon as pk, os, PySimpleGUI as sg + +#code +layout = [ [sg.Text('Enter Pokemon:'), sg.Input(key='-INPUT-'),sg.Button('GO!')], + [sg.Text(size=(50,25), key='-OUTPUT-',background_color='RED')], + [sg.Button('About'),sg.Button('Quit')]] #window layout +sg.theme('Reds') #window theme +window = sg.Window('Pokedex', layout) +while True: + event, values = window.read() #read events + if event == sg.WINDOW_CLOSED or event == 'Quit': + break + message=''''''; color='WHITE' #message to be displayed and the color of the message's text + if event=='GO!': #search pokemon + pokemon=values['-INPUT-'].strip() + if pokemon=='' or not pk.checkPokemon(pokemon): #check if the pokemon exists or not + continue + message="This is "+pokemon+". It is a "+pk.pokemonType(pokemon)+" type pokemon. It's abilities are " + message+=', '.join(pk.pokemonAbilities(pokemon)) + message+='. It takes double damage from ' + message+=', '.join(pk.doubleDamageType(pokemon)) + message+=' type pokemons. Some of such pokemons to watch out for are ' + message+=', '.join(pk.doubleDamageFrom(pokemon)) + message+='.' + color='WHITE' + if event=='About': #about pokedex + message='''I'm Dexter, a Pokédex programmed by Professor Oak for Pokémon Trainer Aman Singh of the town of Pallet. My function is to provide Aman with information and advice regarding Pokémon and their training. If lost or stolen, I cannot be replaced.''' + color='GREEN' + window['-OUTPUT-'].update(message,text_color=color) #display message +window.close() #close window \ No newline at end of file diff --git a/pokemon.py b/pokemon.py new file mode 100644 index 0000000..1e691e7 --- /dev/null +++ b/pokemon.py @@ -0,0 +1,95 @@ +import requests as rq, sys #imports +def check(res): #check for errors + try: + res.raise_for_status() + except Exception as exc: + print('Error: '+exc) + sys.exit(1) +def checkPokemon(pokemon): + '''Checks if the pokemon exists + + Parameters: + pokemon (str): Name of pokemon + + Returns: + bool: True if exists, else False''' + res=rq.get('https://pokeapi.co/api/v2/pokemon/'+pokemon) + try: + res.raise_for_status() + except: + return False + return True +def pokemonType(pokemon): + '''Returns the type of the pokemon + + Parameters: + pokemon (str): Name of pokemon + + Returns: + str: Type of pokemon''' + res=rq.get('https://pokeapi.co/api/v2/pokemon/'+pokemon) + check(res) + return res.json()['types'][0]['type']['name'] +def pokemonAbilities(pokemon): + '''Returns all abilities of the pokemon + + Parameters: + pokemon (str): Name of pokemon + + Returns: + list: A list of all abilities of the pokemon''' + res=rq.get('https://pokeapi.co/api/v2/pokemon/'+pokemon) + check(res) + lst=res.json()['abilities'] + return [lst[i]['ability']['name'] for i in range(len(lst))] +def doubleDamageFrom(pokemon,count=5,random=True): + '''Returns list of pokemons which can do double damage to the pokemon + + Parameters: + pokemon (str): Name of pokemon + + Keyword Arguments: + count (int): number of entries to return (default=5) + random (bool): If the selection of entries would be random instead of linear (default=True) + + Returns: + list: A list of all pokemons which can do double damage''' + lst=doubleDamageType(pokemon) + l=[] + if random: + i=0 + while True: + for pos in range(len(lst)): + r=rq.get('https://pokeapi.co/api/v2/type/'+lst[pos]).json()['pokemon'] + if i>=len(r): + continue + if not count: + return l + l.append(r[i]['pokemon']['name']) + count-=1 + i+=1 + else: + for pos in range(len(lst)): + r=rq.get('https://pokeapi.co/api/v2/type/'+lst[pos]).json()['pokemon'] + for i in range(len(r)): + if not count: + return l + l.append(r[i]['pokemon']['name']) + count-=1 +def doubleDamageType(pokemon): + '''Returns type of pokemons the pokemon is weak to + + Parameters: + pokemon (str): Name of pokemon + + Returns: + list: A list of types to which the pokemon is at a disadvantage''' + res=rq.get('https://pokeapi.co/api/v2/pokemon/'+pokemon) + check(res) + res=rq.get(res.json()['types'][0]['type']['url']) + check(res) + lst=res.json()['damage_relations']['double_damage_from'] + l=[] + for pos in range(len(lst)): + l.append(lst[pos]['name']) + return l \ No newline at end of file diff --git a/step_4.py b/step_4.py new file mode 100644 index 0000000..16ae868 --- /dev/null +++ b/step_4.py @@ -0,0 +1,41 @@ +import time, pandas as pd, numpy as np #importing necessary libraries +timestamp,subset_elements, all_elements=[],[],[] #global variables +def readNumList(): + '''Reads the files subset_elements.txt and all_elements.txt, which contains the subset elements and all elements respectively + + Parameters: + None + + Returns: + None''' + global subset_elements,all_elements #making sure the vars are global here + with open('subset_elemets.txt') as f: + subset_elements = f.read().split('\n') #reading subset elements from file and storing in form of a list + with open('all_elements.txt') as f: + all_elements = f.read().split('\n') #reading all elements from file and storing in form of a list +def stopwatch(): + '''Captures the current time (a time stamp) + + Parameters: + None + + Returns: + None''' + timestamp.append(time.time()) #append current time (in seconds) and appends it to timestamp which as all captured time (from unix epoch) +def getCommonNum(a,b): + '''Returns the number of common elements between list a and b + + Paramters: + a (list): First list of elements + b (list): Second list of elements + + Returns: + int: number of elements common to a and b''' + return len(set(a) & set(b)) #uses & operator on sets to get a new set containing common element +if __name__ == "__main__": + #main + readNumList() #reading elements from the files + stopwatch() #capturing first timestamp + verified_elements=getCommonNum(subset_elements,all_elements) #getting number of common elements + stopwatch() #capturing second timestamp + print(verified_elements,'Duration: {} seconds'.format(timestamp[-1]-timestamp[-2]),sep='\n') #printing number of common elements, along with time taken to compute common elements \ No newline at end of file diff --git a/test_nearest_square.py b/test_nearest_square.py index c5d1e43..c6c6173 100644 --- a/test_nearest_square.py +++ b/test_nearest_square.py @@ -1,5 +1,6 @@ from nearest_square import nearest_square +#Test cases: def test_nearest_square_5(): assert(nearest_square(5)==4) def test_nearest_square_n12():