├── .gitignore ├── Git-keyterm.pdf ├── Images ├── Data Science.png └── Programming.jpg ├── Project 1 ├── 1st-presentation-query.sql ├── 2nd-presentation-query.sql ├── 3rd-presentation-query.sql ├── 4th-presentation-query.sql ├── Project 1 for Submission │ ├── SQL Query.txt │ ├── Saurav Raghuvanshi SQL submission.pdf │ └── Saurav Raghuvanshi SQL submission.pptx ├── Project Question │ ├── set-1-question-1.sql │ ├── set-1-question-2.sql │ ├── set-1-question-3.sql │ ├── set-2-question-1.sql │ ├── set-2-question-2.sql │ └── set-2-question-3.sql └── SQL Project.zip ├── Project-2 ├── bikeshare.py └── requirements.txt ├── Project-3 ├── Git Commands Documentation.pdf └── Project 3.zip ├── Python practice code ├── Generator.ipynb ├── Lesson 4- Flow Control.ipynb ├── Lesson 5-Function.ipynb ├── Lesson 7 NumPy.ipynb ├── Pandas.ipynb ├── US bikeshare data practice questions.ipynb ├── goog-1.csv └── my_array.npy └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .vscode 3 | washington.csv 4 | new_york_city.csv 5 | chicago.csv 6 | 7 | -------------------------------------------------------------------------------- /Git-keyterm.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sauravraghuvanshi/Udacity-programming-for-Data-Science-With-Python-Nanodegree/7d0fd7f969b30ce172f118d372590388363c4088/Git-keyterm.pdf -------------------------------------------------------------------------------- /Images/Data Science.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sauravraghuvanshi/Udacity-programming-for-Data-Science-With-Python-Nanodegree/7d0fd7f969b30ce172f118d372590388363c4088/Images/Data Science.png -------------------------------------------------------------------------------- /Images/Programming.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sauravraghuvanshi/Udacity-programming-for-Data-Science-With-Python-Nanodegree/7d0fd7f969b30ce172f118d372590388363c4088/Images/Programming.jpg -------------------------------------------------------------------------------- /Project 1/1st-presentation-query.sql: -------------------------------------------------------------------------------- 1 | 2 | /* ---------- Query 1 - Number of rentals of top 10 renting countries ---------- */ 3 | 4 | WITH t1 AS (SELECT c3.customer_id, 5 | p.rental_id 6 | FROM country AS c1 7 | JOIN city AS c2 8 | ON c1.country_id = c2.country_id 9 | JOIN address a 10 | ON c2.city_id = a.city_id 11 | JOIN customer c3 12 | ON a.address_id = c3.address_id 13 | JOIN payment p 14 | ON c3.customer_id = p.customer_id 15 | JOIN ( 16 | SELECT c1.country_id 17 | FROM country AS c1 18 | JOIN city AS c2 19 | ON c1.country_id = c2.country_id 20 | JOIN address a 21 | ON c2.city_id = a.city_id 22 | JOIN customer c3 23 | ON a.address_id = c3.address_id 24 | JOIN payment p 25 | ON c3.customer_id = p.customer_id 26 | GROUP BY 1 27 | ORDER BY SUM(p.amount) DESC 28 | LIMIT 10) sub 29 | ON sub.country_id = c1.country_id), 30 | 31 | t2 AS (SELECT c.name, 32 | COUNT(r.rental_id) AS count_top10 33 | FROM t1 34 | JOIN rental AS r 35 | ON r.rental_id = t1.rental_id 36 | JOIN inventory AS i 37 | ON i.inventory_id = r.inventory_id 38 | JOIN film f 39 | ON f.film_id = i.film_id 40 | JOIN film_category fc 41 | ON f.film_id = fc.film_id 42 | JOIN category c 43 | ON c.category_id = fc.category_id 44 | GROUP BY 1), 45 | 46 | t3 AS (SELECT c.name, 47 | COUNT(r.rental_id) AS rental_count 48 | FROM rental AS r 49 | JOIN inventory AS i 50 | ON i.inventory_id = r.inventory_id 51 | JOIN film f 52 | ON f.film_id = i.film_id 53 | JOIN film_category fc 54 | ON f.film_id = fc.film_id 55 | JOIN category c 56 | ON c.category_id = fc.category_id 57 | GROUP BY 1) 58 | 59 | SELECT t2.name AS category, 60 | t3.rental_count - t2.count_top10 AS other_countries, 61 | t2.count_top10, 62 | CAST(t2.count_top10*100 AS FLOAT)/t3.rental_count AS "proportion(%)" 63 | FROM t2 64 | JOIN t3 65 | ON t2.name = t3.name 66 | ORDER BY 2 DESC; 67 | -------------------------------------------------------------------------------- /Project 1/2nd-presentation-query.sql: -------------------------------------------------------------------------------- 1 | /* ---------- Query 2 - Film rentals distribution by category ---------- */ 2 | 3 | SELECT f.title, 4 | c.name, 5 | COUNT(r.rental_id) AS rental_count, 6 | NTILE(4) OVER (PARTITION BY c.name ORDER BY COUNT(r.rental_id)) 7 | FROM category AS c 8 | JOIN film_category AS fc 9 | ON c.category_id = fc.category_id 10 | JOIN film AS f 11 | ON f.film_id = fc.film_id 12 | JOIN inventory AS i 13 | ON f.film_id = i.film_id 14 | JOIN rental AS r 15 | ON i.inventory_id = r.inventory_id 16 | GROUP BY 1, 2 17 | ORDER BY 2 DESC, 4; 18 | -------------------------------------------------------------------------------- /Project 1/3rd-presentation-query.sql: -------------------------------------------------------------------------------- 1 | /* ---------- Query 3 - Amount spent by the top 10 paying customers between February and April 2007 ---------- */ 2 | 3 | WITH t1 AS (SELECT (first_name || ' ' || last_name) AS name, 4 | c.customer_id, 5 | p.amount, 6 | p.payment_date 7 | FROM customer AS c 8 | JOIN payment AS p 9 | ON c.customer_id = p.customer_id), 10 | 11 | t2 AS (SELECT t1.customer_id 12 | FROM t1 13 | GROUP BY 1 14 | ORDER BY SUM(t1.amount) DESC 15 | LIMIT 10), 16 | 17 | t3 AS (SELECT t1.name, 18 | DATE_TRUNC('month', t1.payment_date) AS pay_mon, 19 | COUNT(*) AS pay_countpermon, 20 | SUM(t1.amount) AS pay_amount 21 | FROM t1 22 | JOIN t2 23 | ON t1.customer_id = t2.customer_id 24 | WHERE t1.payment_date BETWEEN '20070101' AND '20080101' 25 | GROUP BY 1, 2 26 | ORDER BY 1, 3, 2) 27 | 28 | SELECT t3.name, 29 | t3.pay_mon, 30 | t3.pay_amount, 31 | ROUND(AVG(t3.pay_amount) OVER (PARTITION BY t3.name), 2) AS avg_amount 32 | FROM t3 33 | ORDER BY 1, 2; 34 | -------------------------------------------------------------------------------- /Project 1/4th-presentation-query.sql: -------------------------------------------------------------------------------- 1 | /* ---------- Query 4 - Film rental distribution by category ---------- */ 2 | 3 | WITH t1 AS (SELECT c.customer_id, 4 | p.amount, 5 | DATE_TRUNC('month', p.payment_date) AS payment_date, 6 | p.rental_id 7 | FROM customer AS c 8 | JOIN payment AS p 9 | ON c.customer_id = p.customer_id), 10 | 11 | t2 AS (SELECT t1.customer_id, 12 | t1.payment_date, 13 | SUM(t1.amount) AS total_amtpaid, 14 | LEAD(SUM(t1.amount)) OVER(w) AS lead_num, 15 | LEAD(SUM(t1.amount)) OVER(w) - SUM(t1.amount) AS lead_dif, 16 | CASE 17 | WHEN LEAD(SUM(t1.amount)) OVER(w) - SUM(t1.amount) < 0 THEN 0 18 | WHEN LEAD(SUM(t1.amount)) OVER(w) - SUM(t1.amount) >= 0 THEN 1 19 | END AS progress 20 | FROM t1 21 | JOIN rental AS r 22 | ON r.rental_id = t1.rental_id 23 | AND t1.customer_id = r.customer_id 24 | GROUP BY 1, 2 25 | WINDOW w AS (PARTITION BY t1.customer_id ORDER BY DATE_TRUNC('month', t1.payment_date))) 26 | 27 | SELECT t2.payment_date, 28 | COUNT(*) AS total_count, 29 | SUM(t2.progress) AS progress_bymon, 30 | COUNT(*) - SUM(t2.progress) AS regress_bymon 31 | FROM t2 32 | WHERE t2.progress IS NOT NULL 33 | GROUP BY 1 34 | ORDER BY 1; 35 | -------------------------------------------------------------------------------- /Project 1/Project 1 for Submission/SQL Query.txt: -------------------------------------------------------------------------------- 1 | /* Query #1 */ 2 | 3 | WITH t1 AS 4 | 5 | (SELECT * 6 | FROM category c 7 | JOIN film_category fc 8 | ON c.category_id = fc.category_id 9 | JOIN film f 10 | ON f.film_id = fc.film_id 11 | JOIN inventory i 12 | ON i.film_id = f.film_id 13 | JOIN rental r 14 | ON r.inventory_id = i.inventory_id 15 | WHERE c.name IN ('Animation', 'Children', 'Classics', 'Comedy', 'Family','Music') ) 16 | 17 | 18 | SELECT t1.title film_title, t1.name category_name, COUNT(t1.title) rental_count 19 | FROM t1 20 | GROUP BY 1, 2 21 | ORDER BY category_name, film_title 22 | 23 | 24 | /* Query #2 */ 25 | 26 | WITH t1 AS 27 | 28 | (SELECT * 29 | FROM category c 30 | JOIN film_category fc 31 | ON c.category_id = fc.category_id 32 | JOIN film f 33 | ON f.film_id = fc.film_id 34 | WHERE c.name IN ('Animation', 'Children','Classics','Comedy','Family','Music') ) 35 | 36 | SELECT t1.title, t1.name, t1.rental_duration, 37 | NTILE(4) OVER (ORDER BY rental_duration) AS standard_quartile 38 | FROM t1 39 | ORDER BY standard_quartile 40 | 41 | 42 | /* Query #3 */ 43 | 44 | WITH t1 AS 45 | (SELECT c.name category, 46 | NTILE(4) OVER (ORDER BY f.rental_duration) AS standard_quartile 47 | 48 | FROM category c 49 | JOIN film_category fc 50 | ON c.category_id = fc.category_id 51 | JOIN film f 52 | ON f.film_id = fc.film_id 53 | WHERE c.name IN ('Animation', 'Children','Classics','Comedy','Family','Music') 54 | ORDER BY category, standard_quartile) 55 | 56 | SELECT t1.category, t1.standard_quartile, COUNT(*) 57 | FROM t1 58 | GROUP BY 1,2 59 | ORDER BY category, standard_quartile 60 | 61 | /* Query #4 */ 62 | 63 | WITH t1 AS 64 | (SELECT DATE_PART('month', rental_date) as month, DATE_PART('year', rental_date) as year, store_id, COUNT (film_id) OVER (PARTITION BY DATE_TRUNC('month', rental_date) ORDER BY store_id) as count_rentals 65 | FROM rental r 66 | JOIN inventory i 67 | ON i.inventory_id = r.inventory_id) 68 | 69 | SELECT t1.month rental_month, t1.year rental_year, t1.store_id, COUNT(count_rentals) count_rentals 70 | FROM t1 71 | GROUP BY 1, 2, 3 72 | ORDER BY count_rentals DESC 73 | -------------------------------------------------------------------------------- /Project 1/Project 1 for Submission/Saurav Raghuvanshi SQL submission.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sauravraghuvanshi/Udacity-programming-for-Data-Science-With-Python-Nanodegree/7d0fd7f969b30ce172f118d372590388363c4088/Project 1/Project 1 for Submission/Saurav Raghuvanshi SQL submission.pdf -------------------------------------------------------------------------------- /Project 1/Project 1 for Submission/Saurav Raghuvanshi SQL submission.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sauravraghuvanshi/Udacity-programming-for-Data-Science-With-Python-Nanodegree/7d0fd7f969b30ce172f118d372590388363c4088/Project 1/Project 1 for Submission/Saurav Raghuvanshi SQL submission.pptx -------------------------------------------------------------------------------- /Project 1/Project Question/set-1-question-1.sql: -------------------------------------------------------------------------------- 1 | /* Udacity 1st project: Investigate a Relational Database */ 2 | 3 | /* Question Set # 1 */ 4 | 5 | /* Question 1: 6 | We want to understand more about the movies that families are watching. 7 | The following categories are considered family movies: Animation, Children, Classics, Comedy, Family and Music. 8 | Create a query that lists each movie, the film category it is classified in, and the number of times it has been rented out. 9 | */ 10 | 11 | SELECT f.title, 12 | c.name, 13 | COUNT(r.rental_id) AS rental_count 14 | FROM category AS c 15 | JOIN film_category AS fc 16 | ON c.category_id = fc.category_id 17 | AND c.name IN ('Animation', 'Children', 'Classics', 'Comedy', 'Family', 'Music') 18 | 19 | JOIN film AS f 20 | ON f.film_id = fc.film_id 21 | 22 | JOIN inventory AS i 23 | ON f.film_id = i.film_id 24 | 25 | JOIN rental AS r 26 | ON i.inventory_id = r.inventory_id 27 | GROUP BY 1, 2 28 | ORDER BY 2, 1; 29 | -------------------------------------------------------------------------------- /Project 1/Project Question/set-1-question-2.sql: -------------------------------------------------------------------------------- 1 | /* Udacity 1st project: Investigate a Relational Database */ 2 | 3 | /* Question Set # 1 */ 4 | 5 | /* 6 | 7 | Question 2: Now we need to know how the length of rental duration of these family-friendly movies compares to the duration that all movies are rented for. Can you provide a table with the movie titles and divide them into 4 levels (first_quarter, second_quarter, third_quarter, and final_quarter) based on the quartiles (25%, 50%, 75%) of the rental duration for movies across all categories? Make sure to also indicate the category that these family-friendly movies fall into. 8 | 9 | Answer: The question is rather ambiguous about how one subset of data (duration of these family-friendly movies) should be compared to another subset of data (duration that all movies are rented for). Below I provide 3 ways to answer the above question. 10 | 11 | */ 12 | 13 | 14 | 15 | /* 2.a As the first possible answer, the two groups could be plotted in a Histogram or Box Plot, which would provide a comparison of how the data is distributed in both datasets. */ 16 | 17 | SELECT *, 18 | NTILE(4) OVER(ORDER BY t1.rental_duration) AS standard_quartile 19 | FROM (SELECT f.title, 20 | c.name, 21 | f.rental_duration 22 | FROM category AS c 23 | JOIN film_category AS fc 24 | ON c.category_id = fc.category_id 25 | AND c.name IN ('Animation', 'Children', 'Classics', 'Comedy', 'Family', 'Music') 26 | 27 | JOIN film AS f 28 | ON f.film_id = fc.film_id 29 | ORDER BY 2, 1) t1; 30 | 31 | /* 2.b */ 32 | 33 | SELECT *, 34 | NTILE(4) OVER(ORDER BY t1.rental_duration) AS standard_quartile 35 | FROM (SELECT f.title, 36 | c.name, 37 | f.rental_duration 38 | FROM category AS c 39 | JOIN film_category AS fc 40 | ON c.category_id = fc.category_id 41 | 42 | JOIN film AS f 43 | ON f.film_id = fc.film_id 44 | ORDER BY 2, 1) t1; 45 | 46 | 47 | /* 2.c As the second possible answer, a Bar Chart or a Pie Chart could provide a comparison of the average rental duration for each film category. */ 48 | 49 | SELECT t1.title, 50 | t1.name, 51 | t1.avg_title_duration, 52 | t1.avg_category_duration, 53 | NTILE(4) OVER(ORDER BY t1.avg_category_duration) AS standard_quartile 54 | FROM (SELECT f.title, 55 | c.name, 56 | AVG(f.rental_duration) OVER (PARTITION BY f.title) AS avg_title_duration, 57 | AVG(f.rental_duration) OVER (PARTITION BY c.name) AS avg_category_duration 58 | FROM category AS c 59 | JOIN film_category AS fc 60 | ON c.category_id = fc.category_id 61 | 62 | JOIN film f 63 | ON f.film_id = fc.film_id 64 | ORDER BY 4, 3) t1 65 | ORDER BY 4, 5; 66 | 67 | /* 2.d As a third possible answer, a Histogram could provide a comparison of the average rental duration for each film. */ 68 | 69 | SELECT t1.title, 70 | avg_category_durationt1.name, 71 | AVG(t1.avg_category_duration), 72 | NTILE(4) OVER(ORDER BY t1.avg_category_duration) AS standard_quartile 73 | FROM (SELECT f.title, 74 | c.name, 75 | AVG(f.rental_duration) OVER (PARTITION BY f.title) AS avg_title_duration, 76 | AVG(f.rental_duration) OVER (PARTITION BY c.name) AS avg_category_duration 77 | FROM category c 78 | JOIN film_category AS fc 79 | ON c.category_id = fc.category_id 80 | 81 | JOIN film AS f 82 | ON f.film_id = fc.film_id 83 | ORDER BY 4, 3) t1 84 | GROUP BY 1, 2, t1.avg_category_duration 85 | ORDER BY 3, 1; 86 | -------------------------------------------------------------------------------- /Project 1/Project Question/set-1-question-3.sql: -------------------------------------------------------------------------------- 1 | /* Udacity 1st project: Investigate a Relational Database */ 2 | 3 | /* Question Set # 1 */ 4 | 5 | /* 6 | Question 3: 7 | Finally, provide a table with the family-friendly film category, each of the quartiles, and the corresponding count of movies within each combination of film category for each corresponding rental duration category. 8 | */ 9 | 10 | SELECT t.name, 11 | t.standard_quartile, 12 | COUNT(*) 13 | FROM (SELECT c.name, 14 | f.rental_duration, 15 | NTILE(4) OVER(ORDER BY f.rental_duration) AS standard_quartile 16 | FROM category AS c 17 | JOIN film_category AS fc 18 | ON c.category_id = fc.category_id 19 | AND c.name IN ('Animation', 'Children', 'Classics', 'Comedy', 'Family', 'Music') 20 | JOIN film AS f 21 | ON f.film_id = fc.film_id) AS t 22 | GROUP BY 1, 2 23 | ORDER BY 1, 2; 24 | -------------------------------------------------------------------------------- /Project 1/Project Question/set-2-question-1.sql: -------------------------------------------------------------------------------- 1 | /* Udacity 1st project: Investigate a Relational Database */ 2 | 3 | /* Question Set # 2 */ 4 | 5 | /* 6 | Question 1: 7 | We want to find out how the two stores compare in their count of rental orders during every month for all the years 8 | we have data for. Write a query that returns the store ID for the store, the year and month and the number of rental 9 | orders each store has fulfilled for that month. Your table should include a column for each of the following: year, month, 10 | store ID and count of rental orders fulfilled during that month. 11 | */ 12 | 13 | SELECT DATE_PART('month', r1.rental_date) AS rental_month, 14 | DATE_PART('year', r1.rental_date) AS rental_year, 15 | ('Store ' || s1.store_id) AS store, 16 | COUNT(*) 17 | FROM store AS s1 18 | JOIN staff AS s2 19 | ON s1.store_id = s2.store_id 20 | 21 | JOIN rental r1 22 | ON s2.staff_id = r1.staff_id 23 | GROUP BY 1, 2, 3 24 | ORDER BY 2, 1; 25 | -------------------------------------------------------------------------------- /Project 1/Project Question/set-2-question-2.sql: -------------------------------------------------------------------------------- 1 | /* Udacity 1st project: Investigate a Relational Database */ 2 | 3 | /* Question Set # 2 */ 4 | 5 | /* 6 | Question 2 7 | We would like to know who were our top 10 paying customers, how many payments they made on a monthly basis during 2007, 8 | and what was the amount of the monthly payments. Can you write a query to capture the customer name, month and year of 9 | payment, and total payment amount for each month by these top 10 paying customers? 10 | */ 11 | 12 | WITH t1 AS (SELECT (first_name || ' ' || last_name) AS name, 13 | c.customer_id, 14 | p.amount, 15 | p.payment_date 16 | FROM customer AS c 17 | JOIN payment AS p 18 | ON c.customer_id = p.customer_id), 19 | 20 | t2 AS (SELECT t1.customer_id 21 | FROM t1 22 | GROUP BY 1 23 | ORDER BY SUM(t1.amount) DESC 24 | LIMIT 10) 25 | 26 | SELECT t1.name, 27 | DATE_PART('month', t1.payment_date) AS payment_month, 28 | DATE_PART('year', t1.payment_date) AS payment_year, 29 | COUNT (*), 30 | SUM(t1.amount) 31 | FROM t1 32 | JOIN t2 33 | ON t1.customer_id = t2.customer_id 34 | WHERE t1.payment_date BETWEEN '20070101' AND '20080101' 35 | GROUP BY 1, 2, 3; 36 | -------------------------------------------------------------------------------- /Project 1/Project Question/set-2-question-3.sql: -------------------------------------------------------------------------------- 1 | 2 | /* Udacity 1st project: Investigate a Relational Database */ 3 | 4 | /* Question Set # 2 */ 5 | 6 | /* 7 | Question 3 8 | Finally, for each of these top 10 paying customers, I would like to find out the difference across their monthly payments during 2007. Please go ahead and write a query to compare the payment amounts in each successive month. Repeat this for each of these 10 paying customers. Also, it will be tremendously helpful if you can identify the customer name who paid the most difference in terms of payments. 9 | */ 10 | 11 | WITH t1 AS (SELECT (first_name || ' ' || last_name) AS name, 12 | c.customer_id, 13 | p.amount, 14 | p.payment_date 15 | FROM customer AS c 16 | JOIN payment AS p 17 | ON c.customer_id = p.customer_id), 18 | 19 | t2 AS (SELECT t1.customer_id 20 | FROM t1 21 | GROUP BY 1 22 | ORDER BY SUM(t1.amount) DESC 23 | LIMIT 10), 24 | 25 | 26 | t3 AS (SELECT t1.name, 27 | DATE_PART('month', t1.payment_date) AS payment_month, 28 | DATE_PART('year', t1.payment_date) AS payment_year, 29 | COUNT (*), 30 | SUM(t1.amount), 31 | SUM(t1.amount) AS total, 32 | LEAD(SUM(t1.amount)) OVER(PARTITION BY t1.name ORDER BY DATE_PART('month', t1.payment_date)) AS lead, 33 | LEAD(SUM(t1.amount)) OVER(PARTITION BY t1.name ORDER BY DATE_PART('month', t1.payment_date)) - SUM(t1.amount) AS lead_dif 34 | FROM t1 35 | JOIN t2 36 | ON t1.customer_id = t2.customer_id 37 | WHERE t1.payment_date BETWEEN '20070101' AND '20080101' 38 | GROUP BY 1, 2, 3 39 | ORDER BY 1, 3, 2) 40 | 41 | SELECT t3.*, 42 | CASE 43 | WHEN t3.lead_dif = (SELECT MAX(t3.lead_dif) FROM t3 ORDER BY 1 DESC LIMIT 1) THEN 'this is the maximum difference' 44 | ELSE NULL 45 | END AS is_max 46 | FROM t3 47 | ORDER BY 1; 48 | -------------------------------------------------------------------------------- /Project 1/SQL Project.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sauravraghuvanshi/Udacity-programming-for-Data-Science-With-Python-Nanodegree/7d0fd7f969b30ce172f118d372590388363c4088/Project 1/SQL Project.zip -------------------------------------------------------------------------------- /Project-2/bikeshare.py: -------------------------------------------------------------------------------- 1 | import time 2 | import pandas as pd 3 | import numpy as np 4 | import datetime as dt 5 | import click 6 | 7 | CITY_DATA = {'chicago': 'chicago.csv', 8 | 'new york city': 'new_york_city.csv', 9 | 'washington': 'washington.csv'} 10 | 11 | months = ('january', 'february', 'march', 'april', 'may', 'june') 12 | 13 | weekdays = ('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 14 | 'saturday') 15 | 16 | 17 | def choice(prompt, choices=('y', 'n')): 18 | """Return a valid input from the user given an array of possible answers. 19 | """ 20 | 21 | while True: 22 | choice = input(prompt).lower().strip() 23 | # terminate the program if the input is end 24 | if choice == 'end': 25 | raise SystemExit 26 | # triggers if the input has only one name 27 | elif ',' not in choice: 28 | if choice in choices: 29 | break 30 | # triggers if the input has more than one name 31 | elif ',' in choice: 32 | choice = [i.strip().lower() for i in choice.split(',')] 33 | if list(filter(lambda x: x in choices, choice)) == choice: 34 | break 35 | 36 | prompt = ("\nSomething is not right. Please mind the formatting and " 37 | "be sure to enter a valid option:\n>") 38 | 39 | return choice 40 | 41 | 42 | def get_filters(): 43 | """Ask user to specify city(ies) and filters, month(s) and weekday(s). 44 | 45 | Returns: 46 | (str) city -name of the city(ies) to analyze 47 | (str) month -name of the month(s) to filter 48 | (str) day -name of the day(s) of week to filter 49 | """ 50 | 51 | print("\n\nLet's explore some US bikeshare data!\n") 52 | 53 | print("Type end at any time if you would like to exit the program.\n") 54 | 55 | while True: 56 | city = choice("\nFor what city(ies) do you want do select data, " 57 | "New York City, Chicago or Washington? Use commas " 58 | "to list the names.\n>", CITY_DATA.keys()) 59 | month = choice("\nFrom January to June, for what month(s) do you " 60 | "want do filter data? Use commas to list the names.\n>", 61 | months) 62 | day = choice("\nFor what weekday(s) do you want do filter bikeshare " 63 | "data? Use commas to list the names.\n>", weekdays) 64 | 65 | # confirm the user input 66 | confirmation = choice("\nPlease confirm that you would like to apply " 67 | "the following filter(s) to the bikeshare data." 68 | "\n\n City(ies): {}\n Month(s): {}\n Weekday(s)" 69 | ": {}\n\n [y] Yes\n [n] No\n\n>" 70 | .format(city, month, day)) 71 | if confirmation == 'y': 72 | break 73 | else: 74 | print("\nLet's try this again!") 75 | 76 | print('-'*40) 77 | return city, month, day 78 | 79 | 80 | def load_data(city, month, day): 81 | """Load data for the specified filters of city(ies), month(s) and 82 | day(s) whenever applicable. 83 | 84 | Args: 85 | (str) city - name of the city(ies) to analyze 86 | (str) month - name of the month(s) to filter 87 | (str) day - name of the day(s) of week to filter 88 | Returns: 89 | df - Pandas DataFrame containing filtered data 90 | """ 91 | 92 | print("\nThe program is loading the data for the filters of your choice.") 93 | start_time = time.time() 94 | 95 | # filter the data according to the selected city filters 96 | if isinstance(city, list): 97 | df = pd.concat(map(lambda city: pd.read_csv(CITY_DATA[city]), city), 98 | sort=True) 99 | # reorganize DataFrame columns after a city concat 100 | try: 101 | df = df.reindex(columns=['Unnamed: 0', 'Start Time', 'End Time', 102 | 'Trip Duration', 'Start Station', 103 | 'End Station', 'User Type', 'Gender', 104 | 'Birth Year']) 105 | except: 106 | pass 107 | else: 108 | df = pd.read_csv(CITY_DATA[city]) 109 | 110 | # create columns to display statistics 111 | df['Start Time'] = pd.to_datetime(df['Start Time']) 112 | df['Month'] = df['Start Time'].dt.month 113 | df['Weekday'] = df['Start Time'].dt.weekday_name 114 | df['Start Hour'] = df['Start Time'].dt.hour 115 | 116 | # filter the data according to month and weekday into two new DataFrames 117 | if isinstance(month, list): 118 | df = pd.concat(map(lambda month: df[df['Month'] == 119 | (months.index(month)+1)], month)) 120 | else: 121 | df = df[df['Month'] == (months.index(month)+1)] 122 | 123 | if isinstance(day, list): 124 | df = pd.concat(map(lambda day: df[df['Weekday'] == 125 | (day.title())], day)) 126 | else: 127 | df = df[df['Weekday'] == day.title()] 128 | 129 | print("\nThis took {} seconds.".format((time.time() - start_time))) 130 | print('-'*40) 131 | 132 | return df 133 | 134 | 135 | def time_stats(df): 136 | """Display statistics on the most frequent times of travel.""" 137 | 138 | print('\nDisplaying the statistics on the most frequent times of ' 139 | 'travel...\n') 140 | start_time = time.time() 141 | 142 | # display the most common month 143 | most_common_month = df['Month'].mode()[0] 144 | print('For the selected filter, the month with the most travels is: ' + 145 | str(months[most_common_month-1]).title() + '.') 146 | 147 | # display the most common day of week 148 | most_common_day = df['Weekday'].mode()[0] 149 | print('For the selected filter, the most common day of the week is: ' + 150 | str(most_common_day) + '.') 151 | 152 | # display the most common start hour 153 | most_common_hour = df['Start Hour'].mode()[0] 154 | print('For the selected filter, the most common start hour is: ' + 155 | str(most_common_hour) + '.') 156 | 157 | print("\nThis took {} seconds.".format((time.time() - start_time))) 158 | print('-'*40) 159 | 160 | 161 | def station_stats(df): 162 | """Display statistics on the most popular stations and trip.""" 163 | 164 | print('\nCalculating The Most Popular Stations and Trip...\n') 165 | start_time = time.time() 166 | 167 | # display most commonly used start station 168 | most_common_start_station = str(df['Start Station'].mode()[0]) 169 | print("For the selected filters, the most common start station is: " + 170 | most_common_start_station) 171 | 172 | # display most commonly used end station 173 | most_common_end_station = str(df['End Station'].mode()[0]) 174 | print("For the selected filters, the most common start end is: " + 175 | most_common_end_station) 176 | 177 | # display most frequent combination of start station and 178 | # end station trip 179 | df['Start-End Combination'] = (df['Start Station'] + ' - ' + 180 | df['End Station']) 181 | most_common_start_end_combination = str(df['Start-End Combination'] 182 | .mode()[0]) 183 | print("For the selected filters, the most common start-end combination " 184 | "of stations is: " + most_common_start_end_combination) 185 | 186 | print("\nThis took {} seconds.".format((time.time() - start_time))) 187 | print('-'*40) 188 | 189 | 190 | def trip_duration_stats(df): 191 | """Display statistics on the total and average trip duration.""" 192 | 193 | print('\nCalculating Trip Duration...\n') 194 | start_time = time.time() 195 | 196 | # display total travel time 197 | total_travel_time = df['Trip Duration'].sum() 198 | total_travel_time = (str(int(total_travel_time//86400)) + 199 | 'd ' + 200 | str(int((total_travel_time % 86400)//3600)) + 201 | 'h ' + 202 | str(int(((total_travel_time % 86400) % 3600)//60)) + 203 | 'm ' + 204 | str(int(((total_travel_time % 86400) % 3600) % 60)) + 205 | 's') 206 | print('For the selected filters, the total travel time is : ' + 207 | total_travel_time + '.') 208 | 209 | # display mean travel time 210 | mean_travel_time = df['Trip Duration'].mean() 211 | mean_travel_time = (str(int(mean_travel_time//60)) + 'm ' + 212 | str(int(mean_travel_time % 60)) + 's') 213 | print("For the selected filters, the mean travel time is : " + 214 | mean_travel_time + ".") 215 | 216 | print("\nThis took {} seconds.".format((time.time() - start_time))) 217 | print('-'*40) 218 | 219 | 220 | def user_stats(df, city): 221 | """Display statistics on bikeshare users.""" 222 | 223 | print('\nCalculating User Stats...\n') 224 | start_time = time.time() 225 | 226 | # Display counts of user types 227 | user_types = df['User Type'].value_counts().to_string() 228 | print("Distribution for user types:") 229 | print(user_types) 230 | 231 | # Display counts of gender 232 | try: 233 | gender_distribution = df['Gender'].value_counts().to_string() 234 | print("\nDistribution for each gender:") 235 | print(gender_distribution) 236 | except KeyError: 237 | print("We're sorry! There is no data of user genders for {}." 238 | .format(city.title())) 239 | 240 | # Display earliest, most recent, and most common year of birth 241 | try: 242 | earliest_birth_year = str(int(df['Birth Year'].min())) 243 | print("\nFor the selected filter, the oldest person to ride one " 244 | "bike was born in: " + earliest_birth_year) 245 | most_recent_birth_year = str(int(df['Birth Year'].max())) 246 | print("For the selected filter, the youngest person to ride one " 247 | "bike was born in: " + most_recent_birth_year) 248 | most_common_birth_year = str(int(df['Birth Year'].mode()[0])) 249 | print("For the selected filter, the most common birth year amongst " 250 | "riders is: " + most_common_birth_year) 251 | except: 252 | print("We're sorry! There is no data of birth year for {}." 253 | .format(city.title())) 254 | 255 | print("\nThis took {} seconds.".format((time.time() - start_time))) 256 | print('-'*40) 257 | 258 | 259 | def raw_data(df, mark_place): 260 | """Display 5 line of sorted raw data each time.""" 261 | 262 | print("\nYou opted to view raw data.") 263 | 264 | # this variable holds where the user last stopped 265 | if mark_place > 0: 266 | last_place = choice("\nWould you like to continue from where you " 267 | "stopped last time? \n [y] Yes\n [n] No\n\n>") 268 | if last_place == 'n': 269 | mark_place = 0 270 | 271 | # sort data by column 272 | if mark_place == 0: 273 | sort_df = choice("\nHow would you like to sort the way the data is " 274 | "displayed in the dataframe? Hit Enter to view " 275 | "unsorted.\n \n [st] Start Time\n [et] End Time\n " 276 | "[td] Trip Duration\n [ss] Start Station\n " 277 | "[es] End Station\n\n>", 278 | ('st', 'et', 'td', 'ss', 'es', '')) 279 | 280 | asc_or_desc = choice("\nWould you like it to be sorted ascending or " 281 | "descending? \n [a] Ascending\n [d] Descending" 282 | "\n\n>", 283 | ('a', 'd')) 284 | 285 | if asc_or_desc == 'a': 286 | asc_or_desc = True 287 | elif asc_or_desc == 'd': 288 | asc_or_desc = False 289 | 290 | if sort_df == 'st': 291 | df = df.sort_values(['Start Time'], ascending=asc_or_desc) 292 | elif sort_df == 'et': 293 | df = df.sort_values(['End Time'], ascending=asc_or_desc) 294 | elif sort_df == 'td': 295 | df = df.sort_values(['Trip Duration'], ascending=asc_or_desc) 296 | elif sort_df == 'ss': 297 | df = df.sort_values(['Start Station'], ascending=asc_or_desc) 298 | elif sort_df == 'es': 299 | df = df.sort_values(['End Station'], ascending=asc_or_desc) 300 | elif sort_df == '': 301 | pass 302 | 303 | # each loop displays 5 lines of raw data 304 | while True: 305 | for i in range(mark_place, len(df.index)): 306 | print("\n") 307 | print(df.iloc[mark_place:mark_place+5].to_string()) 308 | print("\n") 309 | mark_place += 5 310 | 311 | if choice("Do you want to keep printing raw data?" 312 | "\n\n[y]Yes\n[n]No\n\n>") == 'y': 313 | continue 314 | else: 315 | break 316 | break 317 | 318 | return mark_place 319 | 320 | 321 | def main(): 322 | while True: 323 | click.clear() 324 | city, month, day = get_filters() 325 | df = load_data(city, month, day) 326 | 327 | mark_place = 0 328 | while True: 329 | select_data = choice("\nPlease select the information you would " 330 | "like to obtain.\n\n [ts] Time Stats\n [ss] " 331 | "Station Stats\n [tds] Trip Duration Stats\n " 332 | "[us] User Stats\n [rd] Display Raw Data\n " 333 | "[r] Restart\n\n>", 334 | ('ts', 'ss', 'tds', 'us', 'rd', 'r')) 335 | click.clear() 336 | if select_data == 'ts': 337 | time_stats(df) 338 | elif select_data == 'ss': 339 | station_stats(df) 340 | elif select_data == 'tds': 341 | trip_duration_stats(df) 342 | elif select_data == 'us': 343 | user_stats(df, city) 344 | elif select_data == 'rd': 345 | mark_place = raw_data(df, mark_place) 346 | elif select_data == 'r': 347 | break 348 | 349 | restart = choice("\nWould you like to restart?\n\n[y]Yes\n[n]No\n\n>") 350 | if restart.lower() != 'y': 351 | break 352 | 353 | 354 | if __name__ == "__main__": 355 | main() 356 | -------------------------------------------------------------------------------- /Project-2/requirements.txt: -------------------------------------------------------------------------------- 1 | alabaster==0.7.12 2 | anaconda-client==1.7.2 3 | anaconda-navigator==1.9.6 4 | anaconda-project==0.8.2 5 | appnope==0.1.0 6 | appscript==1.0.1 7 | asn1crypto==0.24.0 8 | astroid==2.1.0 9 | astropy==3.1 10 | atomicwrites==1.2.1 11 | attrs==18.2.0 12 | Babel==2.6.0 13 | backcall==0.1.0 14 | backports.os==0.1.1 15 | backports.shutil-get-terminal-size==1.0.0 16 | beautifulsoup4==4.6.3 17 | bitarray==0.8.3 18 | bkcharts==0.2 19 | blaze==0.11.3 20 | bleach==3.0.2 21 | blessings==1.7 22 | bokeh==1.0.2 23 | boto==2.49.0 24 | Bottleneck==1.2.1 25 | certifi==2018.11.29 26 | cffi==1.11.5 27 | chardet==3.0.4 28 | Click==7.0 29 | cloudpickle==0.6.1 30 | clyent==1.2.2 31 | colorama==0.4.1 32 | conda==4.5.12 33 | conda-build==3.17.6 34 | conda-verify==3.1.1 35 | contextlib2==0.5.5 36 | cryptography==2.4.2 37 | cycler==0.10.0 38 | Cython==0.29.2 39 | cytoolz==0.9.0.1 40 | dask==1.0.0 41 | datashape==0.5.4 42 | decorator==4.3.0 43 | defusedxml==0.5.0 44 | distributed==1.25.1 45 | docutils==0.14 46 | entrypoints==0.2.3 47 | et-xmlfile==1.0.1 48 | fastcache==1.0.2 49 | filelock==3.0.10 50 | Flask==1.0.2 51 | Flask-Cors==3.0.7 52 | future==0.17.1 53 | gevent==1.3.7 54 | glob2==0.6 55 | gmpy2==2.0.8 56 | greenlet==0.4.15 57 | h5py==2.8.0 58 | heapdict==1.0.0 59 | html5lib==1.0.1 60 | idna==2.8 61 | imageio==2.4.1 62 | imagesize==1.1.0 63 | importlib-metadata==0.6 64 | inquirer==2.5.1 65 | ipykernel==5.1.0 66 | ipython==7.2.0 67 | ipython-genutils==0.2.0 68 | ipywidgets==7.4.2 69 | isort==4.3.4 70 | itsdangerous==1.1.0 71 | jdcal==1.4 72 | jedi==0.13.2 73 | Jinja2==2.10 74 | jsonschema==2.6.0 75 | jupyter==1.0.0 76 | jupyter-client==5.2.4 77 | jupyter-console==6.0.0 78 | jupyter-core==4.4.0 79 | jupyterlab==0.35.3 80 | jupyterlab-server==0.2.0 81 | keyring==17.0.0 82 | kiwisolver==1.0.1 83 | lazy-object-proxy==1.3.1 84 | libarchive-c==2.8 85 | lief==0.9.0 86 | llvmlite==0.26.0 87 | locket==0.2.0 88 | lxml==4.2.5 89 | MarkupSafe==1.1.0 90 | matplotlib==3.0.2 91 | mccabe==0.6.1 92 | mistune==0.8.4 93 | mkl-fft==1.0.6 94 | mkl-random==1.0.2 95 | more-itertools==4.3.0 96 | mpmath==1.1.0 97 | msgpack==0.5.6 98 | multipledispatch==0.6.0 99 | navigator-updater==0.2.1 100 | nbconvert==5.4.0 101 | nbformat==4.4.0 102 | networkx==2.2 103 | nltk==3.4 104 | nose==1.3.7 105 | notebook==5.7.8 106 | numba==0.41.0 107 | numexpr==2.6.8 108 | numpy==1.15.4 109 | numpydoc==0.8.0 110 | odo==0.5.1 111 | olefile==0.46 112 | openpyxl==2.5.12 113 | packaging==18.0 114 | pandas==0.23.4 115 | pandocfilters==1.4.2 116 | parso==0.3.1 117 | partd==0.3.9 118 | path.py==11.5.0 119 | pathlib2==2.3.3 120 | patsy==0.5.1 121 | pep8==1.7.1 122 | pexpect==4.6.0 123 | pickleshare==0.7.5 124 | Pillow==5.3.0 125 | pkginfo==1.4.2 126 | pluggy==0.8.0 127 | ply==3.11 128 | prometheus-client==0.5.0 129 | prompt-toolkit==2.0.7 130 | psutil==5.4.8 131 | ptyprocess==0.6.0 132 | py==1.7.0 133 | pycodestyle==2.4.0 134 | pycosat==0.6.3 135 | pycparser==2.19 136 | pycrypto==2.6.1 137 | pycurl==7.43.0.2 138 | pyflakes==2.0.0 139 | Pygments==2.3.1 140 | pylint==2.2.2 141 | pyodbc==4.0.25 142 | pyOpenSSL==18.0.0 143 | pyparsing==2.3.0 144 | PySocks==1.6.8 145 | pytest==4.0.2 146 | pytest-arraydiff==0.3 147 | pytest-astropy==0.5.0 148 | pytest-doctestplus==0.2.0 149 | pytest-openfiles==0.3.1 150 | pytest-remotedata==0.3.1 151 | python-dateutil==2.7.5 152 | pytz==2018.7 153 | PyWavelets==1.0.1 154 | PyYAML==3.13 155 | pyzmq==17.1.2 156 | QtAwesome==0.5.3 157 | qtconsole==4.4.3 158 | QtPy==1.5.2 159 | readchar==2.0.1 160 | requests==2.21.0 161 | rope==0.11.0 162 | ruamel-yaml==0.15.46 163 | scikit-image==0.14.1 164 | scikit-learn==0.20.1 165 | scipy==1.1.0 166 | seaborn==0.9.0 167 | Send2Trash==1.5.0 168 | simplegeneric==0.8.1 169 | singledispatch==3.4.0.3 170 | six==1.12.0 171 | snowballstemmer==1.2.1 172 | sortedcollections==1.0.1 173 | sortedcontainers==2.1.0 174 | Sphinx==1.8.2 175 | sphinxcontrib-websupport==1.1.0 176 | spyder==3.3.2 177 | spyder-kernels==0.3.0 178 | SQLAlchemy==1.2.15 179 | statsmodels==0.9.0 180 | sympy==1.3 181 | tables==3.4.4 182 | tblib==1.3.2 183 | terminado==0.8.1 184 | testpath==0.4.2 185 | toolz==0.9.0 186 | tornado==5.1.1 187 | tqdm==4.28.1 188 | traitlets==4.3.2 189 | unicodecsv==0.14.1 190 | urllib3==1.24.1 191 | wcwidth==0.1.7 192 | webencodings==0.5.1 193 | Werkzeug==0.14.1 194 | widgetsnbextension==3.4.2 195 | wrapt==1.10.11 196 | wurlitzer==1.0.2 197 | xlrd==1.2.0 198 | XlsxWriter==1.1.2 199 | xlwings==0.15.1 200 | xlwt==1.3.0 201 | zict==0.1.3 202 | -------------------------------------------------------------------------------- /Project-3/Git Commands Documentation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sauravraghuvanshi/Udacity-programming-for-Data-Science-With-Python-Nanodegree/7d0fd7f969b30ce172f118d372590388363c4088/Project-3/Git Commands Documentation.pdf -------------------------------------------------------------------------------- /Project-3/Project 3.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sauravraghuvanshi/Udacity-programming-for-Data-Science-With-Python-Nanodegree/7d0fd7f969b30ce172f118d372590388363c4088/Project-3/Project 3.zip -------------------------------------------------------------------------------- /Python practice code/Generator.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "def my_range(x):\n", 10 | " i = 0\n", 11 | " while i < x:\n", 12 | " yield i\n", 13 | " i += 1" 14 | ] 15 | }, 16 | { 17 | "cell_type": "code", 18 | "execution_count": 2, 19 | "metadata": {}, 20 | "outputs": [ 21 | { 22 | "name": "stdout", 23 | "output_type": "stream", 24 | "text": [ 25 | "0\n", 26 | "1\n", 27 | "2\n", 28 | "3\n", 29 | "4\n" 30 | ] 31 | } 32 | ], 33 | "source": [ 34 | "for x in my_range(5):\n", 35 | " print(x)" 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": 3, 41 | "metadata": {}, 42 | "outputs": [ 43 | { 44 | "name": "stdout", 45 | "output_type": "stream", 46 | "text": [ 47 | "Lesson 1: Why Python Programming\n", 48 | "Lesson 2: Data Types and Operators\n", 49 | "Lesson 3: Control Flow\n", 50 | "Lesson 4: Functions\n", 51 | "Lesson 5: Scripting\n" 52 | ] 53 | } 54 | ], 55 | "source": [ 56 | "#Quiz Solution: Implement my_enumerate\n", 57 | "lessons = [\"Why Python Programming\", \"Data Types and Operators\", \"Control Flow\", \"Functions\", \"Scripting\"]\n", 58 | "\n", 59 | "def my_enumerate(iterable, start=0):\n", 60 | " count = start\n", 61 | " for element in iterable:\n", 62 | " yield count, element\n", 63 | " count += 1\n", 64 | "\n", 65 | "for i, lesson in my_enumerate(lessons, 1):\n", 66 | " print(\"Lesson {}: {}\".format(i, lesson))" 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": 4, 72 | "metadata": {}, 73 | "outputs": [ 74 | { 75 | "name": "stdout", 76 | "output_type": "stream", 77 | "text": [ 78 | "[0, 1, 2, 3]\n", 79 | "[4, 5, 6, 7]\n", 80 | "[8, 9, 10, 11]\n", 81 | "[12, 13, 14, 15]\n", 82 | "[16, 17, 18, 19]\n", 83 | "[20, 21, 22, 23]\n", 84 | "[24]\n" 85 | ] 86 | } 87 | ], 88 | "source": [ 89 | "#Quiz Solution: Chunker\n", 90 | "def chunker(iterable, size):\n", 91 | " \"\"\"Yield successive chunks from iterable of length size.\"\"\"\n", 92 | " for i in range(0, len(iterable), size):\n", 93 | " yield iterable[i:i + size]\n", 94 | "\n", 95 | "for chunk in chunker(range(25), 4):\n", 96 | " print(list(chunk))" 97 | ] 98 | }, 99 | { 100 | "cell_type": "code", 101 | "execution_count": null, 102 | "metadata": {}, 103 | "outputs": [], 104 | "source": [] 105 | } 106 | ], 107 | "metadata": { 108 | "kernelspec": { 109 | "display_name": "Python 3", 110 | "language": "python", 111 | "name": "python3" 112 | }, 113 | "language_info": { 114 | "codemirror_mode": { 115 | "name": "ipython", 116 | "version": 3 117 | }, 118 | "file_extension": ".py", 119 | "mimetype": "text/x-python", 120 | "name": "python", 121 | "nbconvert_exporter": "python", 122 | "pygments_lexer": "ipython3", 123 | "version": "3.7.4" 124 | } 125 | }, 126 | "nbformat": 4, 127 | "nbformat_minor": 2 128 | } 129 | -------------------------------------------------------------------------------- /Python practice code/Lesson 4- Flow Control.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Flow control:" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "Quiz: 1:Guess My Number\n", 15 | "You decide you want to play a game where you are hiding a number from someone. Store this number in a variable called 'answer'. Another user provides a number called 'guess'. By comparing guess to answer, you inform the user if their guess is too high or too low.\n", 16 | "\n", 17 | "Fill in the conditionals below to inform the user about how their guess compares to the answer." 18 | ] 19 | }, 20 | { 21 | "cell_type": "markdown", 22 | "metadata": {}, 23 | "source": [ 24 | "Quiz:2: Tax Purchase\n", 25 | "Depending on where an individual is from we need to tax them appropriately. The states of CA, MN, and NY have taxes of 7.5%, 9.5%, and 8.9% respectively. Use this information to take the amount of a purchase and the corresponding state to assure that they are taxed by the right amount." 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": 1, 31 | "metadata": {}, 32 | "outputs": [ 33 | { 34 | "name": "stdout", 35 | "output_type": "stream", 36 | "text": [ 37 | "Oops! Your guess was too low.\n" 38 | ] 39 | } 40 | ], 41 | "source": [ 42 | "#Solution: Guess My Number\n", 43 | "answer = 35\n", 44 | "guess = 30 # this is just a sample answer and guess\n", 45 | "\n", 46 | "if guess < answer:\n", 47 | " result = \"Oops! Your guess was too low.\"\n", 48 | "elif guess > answer:\n", 49 | " result = \"Oops! Your guess was too high.\"\n", 50 | "elif guess==answer:\n", 51 | " result = \"Nice! Your guess matched the answer!\"\n", 52 | "print(result)" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": 4, 58 | "metadata": {}, 59 | "outputs": [ 60 | { 61 | "name": "stdout", 62 | "output_type": "stream", 63 | "text": [ 64 | "Since you're from CA, your total cost is 21.5.\n" 65 | ] 66 | } 67 | ], 68 | "source": [ 69 | "#Solution: Tax Purchase\n", 70 | "state = 'CA'\n", 71 | "purchase_amount = 20.00 # a sample state and purchase amount\n", 72 | "\n", 73 | "if state == 'CA':\n", 74 | " tax_amount = .075\n", 75 | " total_cost = purchase_amount*(1+tax_amount)\n", 76 | " result = \"Since you're from {}, your total cost is {}.\".format(state, total_cost)\n", 77 | "\n", 78 | "elif state == 'MN':\n", 79 | " tax_amount = .095\n", 80 | " total_cost = purchase_amount*(1+tax_amount)\n", 81 | " result = \"Since you're from {}, your total cost is {}.\".format(state, total_cost)\n", 82 | "\n", 83 | "elif state == 'NY':\n", 84 | " tax_amount = .089\n", 85 | " total_cost = purchase_amount*(1+tax_amount)\n", 86 | " result = \"Since you're from {}, your total cost is {}.\".format(state, total_cost)\n", 87 | "\n", 88 | "print(result)" 89 | ] 90 | }, 91 | { 92 | "cell_type": "raw", 93 | "metadata": {}, 94 | "source": [ 95 | "Practice: Quick Brown Fox\n", 96 | "Use a for loop to take a list and print each element of the list in its own line.\n", 97 | "\n", 98 | "Example:\n", 99 | "\n", 100 | "sentence = [\"the\", \"quick\", \"brown\", \"fox\", \"jumped\", \"over\", \"the\", \"lazy\", \"dog\"]\n", 101 | "Output:\n", 102 | "\n", 103 | " the\n", 104 | " quick\n", 105 | " brown\n", 106 | " fox\n", 107 | " jumped\n", 108 | " over\n", 109 | " the\n", 110 | " lazy\n", 111 | " dog" 112 | ] 113 | }, 114 | { 115 | "cell_type": "raw", 116 | "metadata": {}, 117 | "source": [ 118 | "Practice: Multiples of 5\n", 119 | "Write a for loop below that will print out every whole number that is a multiple of 5 and less than or equal to 30.\n", 120 | "\n", 121 | "This should output:\n", 122 | "\n", 123 | "5\n", 124 | "10\n", 125 | "15\n", 126 | "20\n", 127 | "25\n", 128 | "30" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": 5, 134 | "metadata": {}, 135 | "outputs": [ 136 | { 137 | "name": "stdout", 138 | "output_type": "stream", 139 | "text": [ 140 | "the\n", 141 | "quick\n", 142 | "brown\n", 143 | "fox\n", 144 | "jumped\n", 145 | "over\n", 146 | "the\n", 147 | "lazy\n", 148 | "dog\n" 149 | ] 150 | } 151 | ], 152 | "source": [ 153 | "#Solution for Quick Brown Fox\n", 154 | "sentence = [\"the\", \"quick\", \"brown\", \"fox\", \"jumped\", \"over\", \"the\", \"lazy\", \"dog\"]\n", 155 | "\n", 156 | "for word in sentence:\n", 157 | " print(word)" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "execution_count": 6, 163 | "metadata": {}, 164 | "outputs": [ 165 | { 166 | "name": "stdout", 167 | "output_type": "stream", 168 | "text": [ 169 | "5\n", 170 | "10\n", 171 | "15\n", 172 | "20\n", 173 | "25\n", 174 | "30\n" 175 | ] 176 | } 177 | ], 178 | "source": [ 179 | "#Solution: Multiples of 5\n", 180 | "for i in range(5, 35, 5):\n", 181 | " print(i)" 182 | ] 183 | }, 184 | { 185 | "cell_type": "raw", 186 | "metadata": {}, 187 | "source": [ 188 | "Quiz: Create Usernames\n", 189 | "Write a for loop that iterates over the names list to create a usernames list. To create a username for each name, make everything lowercase and replace spaces with underscores. Running your for loop over the list:\n", 190 | "\n", 191 | "names = [\"Joey Tribbiani\", \"Monica Geller\", \"Chandler Bing\", \"Phoebe Buffay\"]\n", 192 | "\n", 193 | "should create the list:\n", 194 | "\n", 195 | "usernames = [\"joey_tribbiani\", \"monica_geller\", \"chandler_bing\", \"phoebe_buffay\"]\n", 196 | "\n", 197 | "HINT: Use the .replace() method to replace the spaces with underscores. Check out how to use this method in this Stack Overflow answer." 198 | ] 199 | }, 200 | { 201 | "cell_type": "code", 202 | "execution_count": 7, 203 | "metadata": {}, 204 | "outputs": [ 205 | { 206 | "name": "stdout", 207 | "output_type": "stream", 208 | "text": [ 209 | "['joey_tribbiani', 'monica_geller', 'chandler_bing', 'phoebe_buffay']\n" 210 | ] 211 | } 212 | ], 213 | "source": [ 214 | "names = [\"Joey Tribbiani\", \"Monica Geller\", \"Chandler Bing\", \"Phoebe Buffay\"]\n", 215 | "usernames = []\n", 216 | "\n", 217 | "for name in names:\n", 218 | " usernames.append(name.lower().replace(\" \", \"_\"))\n", 219 | "\n", 220 | "print(usernames)" 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": 8, 226 | "metadata": {}, 227 | "outputs": [ 228 | { 229 | "name": "stdout", 230 | "output_type": "stream", 231 | "text": [ 232 | "['joey_tribbiani', 'monica_geller', 'chandler_bing', 'phoebe_buffay']\n" 233 | ] 234 | } 235 | ], 236 | "source": [ 237 | "#Quiz Solution: Modify Usernames with Range\n", 238 | "usernames = [\"Joey Tribbiani\", \"Monica Geller\", \"Chandler Bing\", \"Phoebe Buffay\"]\n", 239 | "\n", 240 | "for i in range(len(usernames)):\n", 241 | " usernames[i] = usernames[i].lower().replace(\" \", \"_\")\n", 242 | "\n", 243 | "print(usernames)" 244 | ] 245 | }, 246 | { 247 | "cell_type": "raw", 248 | "metadata": {}, 249 | "source": [ 250 | "Quiz: Tag Counter\n", 251 | "Write a for loop that iterates over a list of strings, tokens, and counts how many of them are XML tags. XML is a data language similar to HTML. You can tell if a string is an XML tag if it begins with a left angle bracket \"<\" and ends with a right angle bracket \">\". Keep track of the number of tags using the variable count.\n", 252 | "\n", 253 | "You can assume that the list of strings will not contain empty strings.\n", 254 | "\n", 255 | "tokens = ['', 'Hello World!', '']\n", 256 | "count = 0\n", 257 | "\n", 258 | "# write your for loop here\n", 259 | "\n", 260 | "\n", 261 | "print(count)\n" 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": 9, 267 | "metadata": {}, 268 | "outputs": [ 269 | { 270 | "name": "stdout", 271 | "output_type": "stream", 272 | "text": [ 273 | "2\n" 274 | ] 275 | } 276 | ], 277 | "source": [ 278 | "tokens = ['', 'Hello World!', '']\n", 279 | "\n", 280 | "count = 0\n", 281 | "for token in tokens:\n", 282 | " if token[0] == '<' and token[-1] == '>':\n", 283 | " count += 1\n", 284 | "\n", 285 | "print(count)" 286 | ] 287 | }, 288 | { 289 | "cell_type": "raw", 290 | "metadata": {}, 291 | "source": [ 292 | "Quiz: Create an HTML List\n", 293 | "Write some code, including a for loop, that iterates over a list of strings and creates a single string, html_str, which is an HTML list. For example, if the list is items = ['first string', 'second string'], printing html_str should output:\n", 294 | "\n", 295 | "\n", 299 | "That is, the string's first line should be the opening tag ." 300 | ] 301 | }, 302 | { 303 | "cell_type": "code", 304 | "execution_count": 10, 305 | "metadata": {}, 306 | "outputs": [ 307 | { 308 | "name": "stdout", 309 | "output_type": "stream", 310 | "text": [ 311 | "\n" 315 | ] 316 | } 317 | ], 318 | "source": [ 319 | "items = ['first string', 'second string']\n", 320 | "html_str = \"\"\n", 326 | "\n", 327 | "print(html_str)" 328 | ] 329 | }, 330 | { 331 | "cell_type": "code", 332 | "execution_count": 2, 333 | "metadata": {}, 334 | "outputs": [], 335 | "source": [ 336 | "book_title = ['great', 'expectations','the', 'adventures', 'of', 'sherlock','holmes','the','great','gasby','hamlet','adventures','of','huckleberry','fin']\n", 337 | "word_counter = {}\n", 338 | "for word in book_title:\n", 339 | " if word not in word_counter:\n", 340 | " word_counter[word] = 1\n", 341 | " else:\n", 342 | " word_counter[word] += 1" 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": 4, 348 | "metadata": {}, 349 | "outputs": [ 350 | { 351 | "name": "stdout", 352 | "output_type": "stream", 353 | "text": [ 354 | "{'great': 2, 'expectations': 1, 'the': 2, 'adventures': 2, 'of': 2, 'sherlock': 1, 'holmes': 1, 'gasby': 1, 'hamlet': 1, 'huckleberry': 1, 'fin': 1}\n" 355 | ] 356 | } 357 | ], 358 | "source": [ 359 | "print(word_counter)" 360 | ] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "execution_count": 6, 365 | "metadata": {}, 366 | "outputs": [ 367 | { 368 | "name": "stdout", 369 | "output_type": "stream", 370 | "text": [ 371 | "{'great': 2, 'expectations': 1, 'the': 2, 'adventures': 2, 'of': 2, 'sherlock': 1, 'holmes': 1, 'gasby': 1, 'hamlet': 1, 'huckleberry': 1, 'fin': 1}\n" 372 | ] 373 | } 374 | ], 375 | "source": [ 376 | "word_counter = {}\n", 377 | "for word in book_title:\n", 378 | " word_counter[word] = word_counter.get(word, 0) + 1\n", 379 | "print(word_counter)" 380 | ] 381 | }, 382 | { 383 | "cell_type": "code", 384 | "execution_count": 7, 385 | "metadata": {}, 386 | "outputs": [], 387 | "source": [ 388 | "cast = {\n", 389 | " \"Jerry Seinfeld\": \"Jerry Seinfeld\",\n", 390 | " \"Julia Louis-Dreyfus\": \"Elaine Benes\",\n", 391 | " \"Jason Alexander\": \"George Costanza\",\n", 392 | " \"Michael Richards\": \"Cosmo Kramer\"\n", 393 | " }" 394 | ] 395 | }, 396 | { 397 | "cell_type": "code", 398 | "execution_count": 8, 399 | "metadata": {}, 400 | "outputs": [ 401 | { 402 | "name": "stdout", 403 | "output_type": "stream", 404 | "text": [ 405 | "Jerry Seinfeld\n", 406 | "Julia Louis-Dreyfus\n", 407 | "Jason Alexander\n", 408 | "Michael Richards\n" 409 | ] 410 | } 411 | ], 412 | "source": [ 413 | "for key in cast:\n", 414 | " print(key)\n" 415 | ] 416 | }, 417 | { 418 | "cell_type": "code", 419 | "execution_count": 9, 420 | "metadata": {}, 421 | "outputs": [ 422 | { 423 | "name": "stdout", 424 | "output_type": "stream", 425 | "text": [ 426 | "Actor: Jerry Seinfeld Role: Jerry Seinfeld\n", 427 | "Actor: Julia Louis-Dreyfus Role: Elaine Benes\n", 428 | "Actor: Jason Alexander Role: George Costanza\n", 429 | "Actor: Michael Richards Role: Cosmo Kramer\n" 430 | ] 431 | } 432 | ], 433 | "source": [ 434 | "#If you wish to iterate through both keys and values, you can use the built-in method items like this:\n", 435 | "\n", 436 | "for key, value in cast.items():\n", 437 | " print(\"Actor: {} Role: {}\".format(key, value))" 438 | ] 439 | }, 440 | { 441 | "cell_type": "code", 442 | "execution_count": 10, 443 | "metadata": {}, 444 | "outputs": [ 445 | { 446 | "name": "stdout", 447 | "output_type": "stream", 448 | "text": [ 449 | "720\n" 450 | ] 451 | } 452 | ], 453 | "source": [ 454 | "#Solution: Factorials with While Loops\n", 455 | "# number to find the factorial of\n", 456 | "number = 6\n", 457 | "# start with our product equal to one\n", 458 | "product = 1\n", 459 | "# track the current number being multiplied\n", 460 | "current = 1\n", 461 | "\n", 462 | "while current <= number:\n", 463 | " # multiply the product so far by the current number\n", 464 | " product *= current\n", 465 | " # increment current with each iteration until it reaches number\n", 466 | " current += 1\n", 467 | "\n", 468 | "\n", 469 | "# print the factorial of number\n", 470 | "print(product)" 471 | ] 472 | }, 473 | { 474 | "cell_type": "code", 475 | "execution_count": 11, 476 | "metadata": {}, 477 | "outputs": [ 478 | { 479 | "name": "stdout", 480 | "output_type": "stream", 481 | "text": [ 482 | "720\n" 483 | ] 484 | } 485 | ], 486 | "source": [ 487 | "# number we'll find the factorial of\n", 488 | "number = 6\n", 489 | "# start with our product equal to one\n", 490 | "product = 1\n", 491 | "\n", 492 | "# calculate factorial of number with a for loop\n", 493 | "for num in range(2, number + 1):\n", 494 | " product *= num\n", 495 | "\n", 496 | "# print the factorial of number\n", 497 | "print(product)" 498 | ] 499 | }, 500 | { 501 | "cell_type": "markdown", 502 | "metadata": {}, 503 | "source": [ 504 | "Quiz: Count By\n", 505 | "Suppose you want to count from some number start_num by another number count_by until you hit a final number end_num. Use break_num as the variable that you'll change each time through the loop. For simplicity, assume that end_num is always larger than start_num and count_by is always positive.\n", 506 | "\n", 507 | "Before the loop, what do you want to set break_num equal to? How do you want to change break_num each time through the loop? What condition will you use to see when it's time to stop looping?\n", 508 | "\n", 509 | "After the loop is done, print out break_num, showing the value that indicated it was time to stop looping. It is the case that break_num should be a number that is the first number larger than end_num." 510 | ] 511 | }, 512 | { 513 | "cell_type": "markdown", 514 | "metadata": {}, 515 | "source": [ 516 | "Quiz: Count By Check\n", 517 | "Suppose you want to count from some number start_num by another number count_by until you hit a final number end_num, and calculate break_num the way you did in the last quiz.\n", 518 | "\n", 519 | "Now in addition, address what would happen if someone gives a start_num that is greater than end_num. If this is the case, set result to \"Oops! Looks like your start value is greater than the end value. Please try again.\" Otherwise, set result to the value of break_num." 520 | ] 521 | }, 522 | { 523 | "cell_type": "markdown", 524 | "metadata": {}, 525 | "source": [ 526 | "Quiz: Nearest Square\n", 527 | "Write a while loop that finds the largest square number less than an integerlimit and stores it in a variable nearest_square. A square number is the product of an integer multiplied by itself, for example 36 is a square number because it equals 6*6.\n", 528 | "\n", 529 | "For example, if limit is 40, your code should set the nearest_square to 36." 530 | ] 531 | }, 532 | { 533 | "cell_type": "code", 534 | "execution_count": 12, 535 | "metadata": {}, 536 | "outputs": [ 537 | { 538 | "name": "stdout", 539 | "output_type": "stream", 540 | "text": [ 541 | "101\n" 542 | ] 543 | } 544 | ], 545 | "source": [ 546 | "#Solution: Count By\n", 547 | "start_num = 5\n", 548 | "end_num = 100\n", 549 | "count_by = 2\n", 550 | "\n", 551 | "break_num = start_num\n", 552 | "while break_num < end_num:\n", 553 | " break_num += count_by\n", 554 | "\n", 555 | "print(break_num)" 556 | ] 557 | }, 558 | { 559 | "cell_type": "code", 560 | "execution_count": 13, 561 | "metadata": {}, 562 | "outputs": [ 563 | { 564 | "name": "stdout", 565 | "output_type": "stream", 566 | "text": [ 567 | "101\n" 568 | ] 569 | } 570 | ], 571 | "source": [ 572 | "start_num = 5\n", 573 | "end_num = 100\n", 574 | "count_by = 2\n", 575 | "\n", 576 | "if start_num > end_num:\n", 577 | " result = \"Oops! Looks like your start value is greater than the end value. Please try again.\"\n", 578 | "\n", 579 | "else:\n", 580 | " break_num = start_num\n", 581 | " while break_num < end_num:\n", 582 | " break_num += count_by\n", 583 | "\n", 584 | " result = break_num\n", 585 | "\n", 586 | "print(result)" 587 | ] 588 | }, 589 | { 590 | "cell_type": "code", 591 | "execution_count": 15, 592 | "metadata": {}, 593 | "outputs": [ 594 | { 595 | "name": "stdout", 596 | "output_type": "stream", 597 | "text": [ 598 | "81\n" 599 | ] 600 | } 601 | ], 602 | "source": [ 603 | "#Solution: Nearest Square\n", 604 | "limit = 100\n", 605 | "\n", 606 | "num = 0\n", 607 | "while (num+1)**2 < limit:\n", 608 | " num += 1\n", 609 | "nearest_square = num**2\n", 610 | "\n", 611 | "print(nearest_square)" 612 | ] 613 | }, 614 | { 615 | "cell_type": "markdown", 616 | "metadata": {}, 617 | "source": [ 618 | "Question: What type of loop should we use?\n", 619 | "You need to write a loop that takes the numbers in a given list named num_list:\n", 620 | "num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]\n", 621 | "\n", 622 | "Your code should add up the odd numbers in the list, but only up to the first 5 odd numbers together. If there are more than 5 odd numbers, you should stop at the fifth. If there are fewer than 5 odd numbers, add all of the odd numbers.\n", 623 | "\n", 624 | "Would you use a while or a for loop to write this code?" 625 | ] 626 | }, 627 | { 628 | "cell_type": "code", 629 | "execution_count": 16, 630 | "metadata": {}, 631 | "outputs": [ 632 | { 633 | "name": "stdout", 634 | "output_type": "stream", 635 | "text": [ 636 | "The numbers of odd numbers added are: 5\n", 637 | "The sum of the odd numbers added is: 993\n" 638 | ] 639 | } 640 | ], 641 | "source": [ 642 | "num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]\n", 643 | "\n", 644 | "count_odd = 0\n", 645 | "list_sum = 0\n", 646 | "i = 0\n", 647 | "len_num_list = len(num_list)\n", 648 | "\n", 649 | "while (count_odd < 5) and (i < len_num_list): \n", 650 | " if num_list[i] % 2 != 0:\n", 651 | " list_sum += num_list[i]\n", 652 | " count_odd += 1\n", 653 | " i += 1\n", 654 | "\n", 655 | "print (\"The numbers of odd numbers added are: {}\".format(count_odd))\n", 656 | "print (\"The sum of the odd numbers added is: {}\".format(list_sum))" 657 | ] 658 | }, 659 | { 660 | "cell_type": "code", 661 | "execution_count": 17, 662 | "metadata": {}, 663 | "outputs": [ 664 | { 665 | "name": "stdout", 666 | "output_type": "stream", 667 | "text": [ 668 | "METHOD 1\n", 669 | "current weight: 0\n", 670 | " adding bananas (15)\n", 671 | "current weight: 15\n", 672 | " adding mattresses (24)\n", 673 | "current weight: 39\n", 674 | " adding dog kennels (42)\n", 675 | "current weight: 81\n", 676 | " adding machine (120)\n", 677 | "current weight: 201\n", 678 | " breaking loop now!\n", 679 | "\n", 680 | "Final Weight: 201\n", 681 | "Final Items: ['bananas', 'mattresses', 'dog kennels', 'machine']\n", 682 | "\n", 683 | "METHOD 2\n", 684 | "current weight: 0\n", 685 | " adding bananas (15)\n", 686 | "current weight: 15\n", 687 | " adding mattresses (24)\n", 688 | "current weight: 39\n", 689 | " adding dog kennels (42)\n", 690 | "current weight: 81\n", 691 | " skipping machine (120)\n", 692 | "current weight: 81\n", 693 | " adding cheeses (5)\n", 694 | "\n", 695 | "Final Weight: 86\n", 696 | "Final Items: ['bananas', 'mattresses', 'dog kennels', 'cheeses']\n" 697 | ] 698 | } 699 | ], 700 | "source": [ 701 | "manifest = [(\"bananas\", 15), (\"mattresses\", 24), (\"dog kennels\", 42), (\"machine\", 120), (\"cheeses\", 5)]\n", 702 | "\n", 703 | "# the code breaks the loop when weight exceeds or reaches the limit\n", 704 | "print(\"METHOD 1\")\n", 705 | "weight = 0\n", 706 | "items = []\n", 707 | "for cargo_name, cargo_weight in manifest:\n", 708 | " print(\"current weight: {}\".format(weight))\n", 709 | " if weight >= 100:\n", 710 | " print(\" breaking loop now!\")\n", 711 | " break\n", 712 | " else:\n", 713 | " print(\" adding {} ({})\".format(cargo_name, cargo_weight))\n", 714 | " items.append(cargo_name)\n", 715 | " weight += cargo_weight\n", 716 | "\n", 717 | "print(\"\\nFinal Weight: {}\".format(weight))\n", 718 | "print(\"Final Items: {}\".format(items))\n", 719 | "\n", 720 | "# skips an iteration when adding an item would exceed the limit\n", 721 | "# breaks the loop if weight is exactly the value of the limit\n", 722 | "print(\"\\nMETHOD 2\")\n", 723 | "weight = 0\n", 724 | "items = []\n", 725 | "for cargo_name, cargo_weight in manifest:\n", 726 | " print(\"current weight: {}\".format(weight))\n", 727 | " if weight >= 100:\n", 728 | " print(\" breaking from the loop now!\")\n", 729 | " break\n", 730 | " elif weight + cargo_weight > 100:\n", 731 | " print(\" skipping {} ({})\".format(cargo_name, cargo_weight))\n", 732 | " continue\n", 733 | " else:\n", 734 | " print(\" adding {} ({})\".format(cargo_name, cargo_weight))\n", 735 | " items.append(cargo_name)\n", 736 | " weight += cargo_weight\n", 737 | "\n", 738 | "print(\"\\nFinal Weight: {}\".format(weight))\n", 739 | "print(\"Final Items: {}\".format(items))" 740 | ] 741 | }, 742 | { 743 | "cell_type": "markdown", 744 | "metadata": {}, 745 | "source": [ 746 | "Quiz: Break the String\n", 747 | "Write a loop with a break statement to create a string, news_ticker, that is exactly 140 characters long. You should create the news ticker by adding headlines from the headlines list, inserting a space in between each headline. If necessary, truncate the last headline in the middle so that news_ticker is exactly 140 characters long.\n", 748 | "\n", 749 | "Remember that break works in both for and while loops. Use whichever loop seems most appropriate. Consider adding print statements to your code to help you resolve bugs." 750 | ] 751 | }, 752 | { 753 | "cell_type": "code", 754 | "execution_count": 18, 755 | "metadata": {}, 756 | "outputs": [ 757 | { 758 | "name": "stdout", 759 | "output_type": "stream", 760 | "text": [ 761 | "Local Bear Eaten by Man Legislature Announces New Laws Peasant Discovers Violence Inherent in System Cat Rescues Fireman Stuck in Tree Brave\n" 762 | ] 763 | } 764 | ], 765 | "source": [ 766 | "headlines = [\"Local Bear Eaten by Man\",\n", 767 | " \"Legislature Announces New Laws\",\n", 768 | " \"Peasant Discovers Violence Inherent in System\",\n", 769 | " \"Cat Rescues Fireman Stuck in Tree\",\n", 770 | " \"Brave Knight Runs Away\",\n", 771 | " \"Papperbok Review: Totally Triffic\"]\n", 772 | "\n", 773 | "news_ticker = \"\"\n", 774 | "for headline in headlines:\n", 775 | " news_ticker += headline + \" \"\n", 776 | " if len(news_ticker) >= 140:\n", 777 | " news_ticker = news_ticker[:140]\n", 778 | " break\n", 779 | "\n", 780 | "print(news_ticker)" 781 | ] 782 | }, 783 | { 784 | "cell_type": "markdown", 785 | "metadata": {}, 786 | "source": [ 787 | "*Coding Quiz: Check for Prime Numbers*\n", 788 | "Prime numbers are whole numbers that have only two factors: 1 and the number itself. The first few prime numbers are 2, 3, 5, 7.\n", 789 | "\n", 790 | "For instance, 6 has four factors: 1, 2, 3, 6.\n", 791 | "1 X 6 = 6\n", 792 | "2 X 3 = 6\n", 793 | "So we know 6 is not a prime number.\n", 794 | "\n", 795 | "In the following coding environment, write code to check if the numbers provided in the list check_prime are prime numbers.\n", 796 | "\n", 797 | "If the numbers are prime, the code should print \"[number] is a prime number.\"\n", 798 | "If the number is NOT a prime number, it should print \"[number] is not a prime number\", and a factor of that number, other than 1 and the number itself: \"[factor] is a factor of [number]\".\n", 799 | "Example output:\n", 800 | "\n", 801 | "7 IS a prime number\n", 802 | "26 is NOT a prime number, because 2 is a factor of 26" 803 | ] 804 | }, 805 | { 806 | "cell_type": "code", 807 | "execution_count": 19, 808 | "metadata": {}, 809 | "outputs": [ 810 | { 811 | "name": "stdout", 812 | "output_type": "stream", 813 | "text": [ 814 | "26 is NOT a prime number, because 2 is a factor of 26\n", 815 | "39 is NOT a prime number, because 3 is a factor of 39\n", 816 | "51 is NOT a prime number, because 3 is a factor of 51\n", 817 | "53 IS a prime number\n", 818 | "57 is NOT a prime number, because 3 is a factor of 57\n", 819 | "79 IS a prime number\n", 820 | "85 is NOT a prime number, because 5 is a factor of 85\n" 821 | ] 822 | } 823 | ], 824 | "source": [ 825 | "check_prime = [26, 39, 51, 53, 57, 79, 85]\n", 826 | "\n", 827 | "# iterate through the check_prime list\n", 828 | "for num in check_prime:\n", 829 | "\n", 830 | "# search for factors, iterating through numbers ranging from 2 to the number itself\n", 831 | " for i in range(2, num):\n", 832 | "\n", 833 | "# number is not prime if modulo is 0\n", 834 | " if (num % i) == 0:\n", 835 | " print(\"{} is NOT a prime number, because {} is a factor of {}\".format(num, i, num))\n", 836 | " break\n", 837 | "\n", 838 | "# otherwise keep checking until we've searched all possible factors, and then declare it prime\n", 839 | " if i == num -1: \n", 840 | " print(\"{} IS a prime number\".format(num))" 841 | ] 842 | }, 843 | { 844 | "cell_type": "code", 845 | "execution_count": 20, 846 | "metadata": {}, 847 | "outputs": [ 848 | { 849 | "name": "stdout", 850 | "output_type": "stream", 851 | "text": [ 852 | "a: 1\n", 853 | "b: 2\n", 854 | "c: 3\n" 855 | ] 856 | } 857 | ], 858 | "source": [ 859 | "#*Zip*\n", 860 | "letters = ['a', 'b', 'c']\n", 861 | "nums = [1, 2, 3]\n", 862 | "\n", 863 | "for letter, num in zip(letters, nums):\n", 864 | " print(\"{}: {}\".format(letter, num))" 865 | ] 866 | }, 867 | { 868 | "cell_type": "code", 869 | "execution_count": 25, 870 | "metadata": {}, 871 | "outputs": [ 872 | { 873 | "name": "stdout", 874 | "output_type": "stream", 875 | "text": [ 876 | "('a', 'b', 'c')\n", 877 | "(1, 2, 3)\n" 878 | ] 879 | } 880 | ], 881 | "source": [ 882 | "some_list = [('a', 1), ('b', 2), ('c', 3)]\n", 883 | "letters, nums = zip(*some_list)\n", 884 | "print(letters)\n", 885 | "print(nums)" 886 | ] 887 | }, 888 | { 889 | "cell_type": "markdown", 890 | "metadata": {}, 891 | "source": [ 892 | "Quiz: Zip Coordinates\n", 893 | "Use zip to write a for loop that creates a string specifying the label and coordinates of each point and appends it to the list points. Each string should be formatted as label: x, y, z. For example, the string for the first coordinate should be F: 23, 677, 4." 894 | ] 895 | }, 896 | { 897 | "cell_type": "markdown", 898 | "metadata": {}, 899 | "source": [ 900 | "Quiz: Zip Lists to a Dictionary\n", 901 | "Use zip to create a dictionary cast that uses names as keys and heights as values." 902 | ] 903 | }, 904 | { 905 | "cell_type": "code", 906 | "execution_count": 26, 907 | "metadata": {}, 908 | "outputs": [ 909 | { 910 | "name": "stdout", 911 | "output_type": "stream", 912 | "text": [ 913 | "F: 23, 677, 4\n", 914 | "J: 53, 233, 16\n", 915 | "A: 2, 405, -6\n", 916 | "Q: -12, 433, -42\n", 917 | "Y: 95, 905, 3\n", 918 | "B: 103, 376, -6\n", 919 | "W: 14, 432, 23\n", 920 | "X: -5, 445, -1\n" 921 | ] 922 | } 923 | ], 924 | "source": [ 925 | "#Quiz Solution: Zip Coordinates\n", 926 | "x_coord = [23, 53, 2, -12, 95, 103, 14, -5]\n", 927 | "y_coord = [677, 233, 405, 433, 905, 376, 432, 445]\n", 928 | "z_coord = [4, 16, -6, -42, 3, -6, 23, -1]\n", 929 | "labels = [\"F\", \"J\", \"A\", \"Q\", \"Y\", \"B\", \"W\", \"X\"]\n", 930 | "\n", 931 | "points = []\n", 932 | "for point in zip(labels, x_coord, y_coord, z_coord):\n", 933 | " points.append(\"{}: {}, {}, {}\".format(*point))\n", 934 | "\n", 935 | "for point in points:\n", 936 | " print(point)" 937 | ] 938 | }, 939 | { 940 | "cell_type": "code", 941 | "execution_count": 27, 942 | "metadata": {}, 943 | "outputs": [ 944 | { 945 | "name": "stdout", 946 | "output_type": "stream", 947 | "text": [ 948 | "{'Barney': 72, 'Robin': 68, 'Ted': 72, 'Lily': 66, 'Marshall': 76}\n" 949 | ] 950 | } 951 | ], 952 | "source": [ 953 | "#Quiz Solution: Zip Lists to a Dictionary\n", 954 | "cast_names = [\"Barney\", \"Robin\", \"Ted\", \"Lily\", \"Marshall\"]\n", 955 | "cast_heights = [72, 68, 72, 66, 76]\n", 956 | "\n", 957 | "cast = dict(zip(cast_names, cast_heights))\n", 958 | "print(cast)" 959 | ] 960 | }, 961 | { 962 | "cell_type": "code", 963 | "execution_count": 29, 964 | "metadata": {}, 965 | "outputs": [ 966 | { 967 | "name": "stdout", 968 | "output_type": "stream", 969 | "text": [ 970 | "('Barney', 'Robin', 'Ted', 'Lily', 'Marshall')\n", 971 | "(72, 68, 72, 66, 76)\n" 972 | ] 973 | } 974 | ], 975 | "source": [ 976 | "#Quiz Solution: Unzip Tuples\n", 977 | "cast = ((\"Barney\", 72), (\"Robin\", 68), (\"Ted\", 72), (\"Lily\", 66), (\"Marshall\", 76))\n", 978 | "\n", 979 | "names, heights = zip(*cast)\n", 980 | "print(names)\n", 981 | "print(heights)" 982 | ] 983 | }, 984 | { 985 | "cell_type": "code", 986 | "execution_count": 31, 987 | "metadata": {}, 988 | "outputs": [ 989 | { 990 | "name": "stdout", 991 | "output_type": "stream", 992 | "text": [ 993 | "((0, 3, 6, 9), (1, 4, 7, 10), (2, 5, 8, 11))\n" 994 | ] 995 | } 996 | ], 997 | "source": [ 998 | "#Quiz Solution: Transpose with Zip\n", 999 | "data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))\n", 1000 | "\n", 1001 | "data_transpose = tuple(zip(*data))\n", 1002 | "print(data_transpose)" 1003 | ] 1004 | }, 1005 | { 1006 | "cell_type": "code", 1007 | "execution_count": 33, 1008 | "metadata": {}, 1009 | "outputs": [ 1010 | { 1011 | "name": "stdout", 1012 | "output_type": "stream", 1013 | "text": [ 1014 | "['Barney Stinson 72', 'Robin Scherbatsky 68', 'Ted Mosby 72', 'Lily Aldrin 66', 'Marshall Eriksen 76']\n" 1015 | ] 1016 | } 1017 | ], 1018 | "source": [ 1019 | "#Quiz Solution: Enumerate\n", 1020 | "cast = [\"Barney Stinson\", \"Robin Scherbatsky\", \"Ted Mosby\", \"Lily Aldrin\", \"Marshall Eriksen\"]\n", 1021 | "heights = [72, 68, 72, 66, 76]\n", 1022 | "\n", 1023 | "for i, character in enumerate(cast):\n", 1024 | " cast[i] = character + \" \" + str(heights[i])\n", 1025 | "\n", 1026 | "print(cast)" 1027 | ] 1028 | }, 1029 | { 1030 | "cell_type": "markdown", 1031 | "metadata": {}, 1032 | "source": [ 1033 | "Quiz: Extract First Names\n", 1034 | "Use a list comprehension to create a new list first_names containing just the first names in names in lowercase.\n", 1035 | "\n", 1036 | "names = [\"Rick Sanchez\", \"Morty Smith\", \"Summer Smith\", \"Jerry Smith\", \"Beth Smith\"]\n", 1037 | "\n", 1038 | "first_names = # write your list comprehension here\n", 1039 | "print(first_names)" 1040 | ] 1041 | }, 1042 | { 1043 | "cell_type": "markdown", 1044 | "metadata": {}, 1045 | "source": [ 1046 | "Quiz: Multiples of Three\n", 1047 | "Use a list comprehension to create a list multiples_3 containing the first 20 multiples of 3." 1048 | ] 1049 | }, 1050 | { 1051 | "cell_type": "markdown", 1052 | "metadata": {}, 1053 | "source": [ 1054 | "Quiz: Filter Names by Scores\n", 1055 | "Use a list comprehension to create a list of names passed that only include those that scored at least 65." 1056 | ] 1057 | }, 1058 | { 1059 | "cell_type": "code", 1060 | "execution_count": 34, 1061 | "metadata": {}, 1062 | "outputs": [ 1063 | { 1064 | "name": "stdout", 1065 | "output_type": "stream", 1066 | "text": [ 1067 | "['rick', 'morty', 'summer', 'jerry', 'beth']\n" 1068 | ] 1069 | } 1070 | ], 1071 | "source": [ 1072 | "#Quiz Solution: Extract First Names\n", 1073 | "names = [\"Rick Sanchez\", \"Morty Smith\", \"Summer Smith\", \"Jerry Smith\", \"Beth Smith\"]\n", 1074 | "\n", 1075 | "first_names = [name.split()[0].lower() for name in names]\n", 1076 | "print(first_names)" 1077 | ] 1078 | }, 1079 | { 1080 | "cell_type": "code", 1081 | "execution_count": 36, 1082 | "metadata": {}, 1083 | "outputs": [ 1084 | { 1085 | "name": "stdout", 1086 | "output_type": "stream", 1087 | "text": [ 1088 | "[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60]\n" 1089 | ] 1090 | } 1091 | ], 1092 | "source": [ 1093 | "#Quiz Solution: Multiples of Three\n", 1094 | "multiples_3 = [x * 3 for x in range(1, 21)]\n", 1095 | "print(multiples_3)" 1096 | ] 1097 | }, 1098 | { 1099 | "cell_type": "code", 1100 | "execution_count": 38, 1101 | "metadata": {}, 1102 | "outputs": [ 1103 | { 1104 | "name": "stdout", 1105 | "output_type": "stream", 1106 | "text": [ 1107 | "['Rick Sanchez', 'Summer Smith', 'Beth Smith']\n" 1108 | ] 1109 | } 1110 | ], 1111 | "source": [ 1112 | "#Quiz Solution: Filter Names by Scores\n", 1113 | "scores = {\n", 1114 | " \"Rick Sanchez\": 70,\n", 1115 | " \"Morty Smith\": 35,\n", 1116 | " \"Summer Smith\": 82,\n", 1117 | " \"Jerry Smith\": 23,\n", 1118 | " \"Beth Smith\": 98\n", 1119 | " }\n", 1120 | "\n", 1121 | "passed = [name for name, score in scores.items() if score >= 65]\n", 1122 | "print(passed)" 1123 | ] 1124 | }, 1125 | { 1126 | "cell_type": "code", 1127 | "execution_count": null, 1128 | "metadata": {}, 1129 | "outputs": [], 1130 | "source": [] 1131 | } 1132 | ], 1133 | "metadata": { 1134 | "kernelspec": { 1135 | "display_name": "Python 3", 1136 | "language": "python", 1137 | "name": "python3" 1138 | }, 1139 | "language_info": { 1140 | "codemirror_mode": { 1141 | "name": "ipython", 1142 | "version": 3 1143 | }, 1144 | "file_extension": ".py", 1145 | "mimetype": "text/x-python", 1146 | "name": "python", 1147 | "nbconvert_exporter": "python", 1148 | "pygments_lexer": "ipython3", 1149 | "version": "3.7.4" 1150 | } 1151 | }, 1152 | "nbformat": 4, 1153 | "nbformat_minor": 2 1154 | } 1155 | -------------------------------------------------------------------------------- /Python practice code/Lesson 5-Function.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "expected result: 10, actual result: 10.0\n", 13 | "expected result: 7123.6902801, actual result: 7123.690280065897\n" 14 | ] 15 | } 16 | ], 17 | "source": [ 18 | "#Population Density Function\n", 19 | "def population_density(population, land_area):\n", 20 | " return population/land_area\n", 21 | "\n", 22 | "# test cases for your function\n", 23 | "test1 = population_density(10, 1)\n", 24 | "expected_result1 = 10\n", 25 | "print(\"expected result: {}, actual result: {}\".format(expected_result1, test1))\n", 26 | "\n", 27 | "test2 = population_density(864816, 121.4)\n", 28 | "expected_result2 = 7123.6902801\n", 29 | "print(\"expected result: {}, actual result: {}\".format(expected_result2, test2))" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": 2, 35 | "metadata": {}, 36 | "outputs": [ 37 | { 38 | "name": "stdout", 39 | "output_type": "stream", 40 | "text": [ 41 | "1 week(s) and 3 day(s).\n" 42 | ] 43 | } 44 | ], 45 | "source": [ 46 | "# readable_timedelta\n", 47 | "def readable_timedelta(days):\n", 48 | " # use integer division to get the number of weeks\n", 49 | " weeks = days // 7\n", 50 | " # use % to get the number of days that remain\n", 51 | " remainder = days % 7\n", 52 | " return \"{} week(s) and {} day(s).\".format(weeks, remainder)\n", 53 | "\n", 54 | "# test your function\n", 55 | "print(readable_timedelta(10))" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": 10, 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "multiply = lambda x, y: x * y" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": 11, 70 | "metadata": {}, 71 | "outputs": [ 72 | { 73 | "data": { 74 | "text/plain": [ 75 | "28" 76 | ] 77 | }, 78 | "execution_count": 11, 79 | "metadata": {}, 80 | "output_type": "execute_result" 81 | } 82 | ], 83 | "source": [ 84 | "multiply(4, 7)" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": 13, 90 | "metadata": {}, 91 | "outputs": [ 92 | { 93 | "name": "stdout", 94 | "output_type": "stream", 95 | "text": [ 96 | "[57.0, 58.2, 50.6, 27.2]\n" 97 | ] 98 | } 99 | ], 100 | "source": [ 101 | "#Lambda with Map\n", 102 | "numbers = [\n", 103 | " [34, 63, 88, 71, 29],\n", 104 | " [90, 78, 51, 27, 45],\n", 105 | " [63, 37, 85, 46, 22],\n", 106 | " [51, 22, 34, 11, 18]\n", 107 | " ]\n", 108 | "\n", 109 | "averages = list(map(lambda x: sum(x) / len(x), numbers))\n", 110 | "print(averages)" 111 | ] 112 | }, 113 | { 114 | "cell_type": "code", 115 | "execution_count": 14, 116 | "metadata": {}, 117 | "outputs": [ 118 | { 119 | "name": "stdout", 120 | "output_type": "stream", 121 | "text": [ 122 | "['Chicago', 'Denver', 'Boston']\n" 123 | ] 124 | } 125 | ], 126 | "source": [ 127 | "#Lambda with Filter\n", 128 | "cities = [\"New York City\", \"Los Angeles\", \"Chicago\", \"Mountain View\", \"Denver\", \"Boston\"]\n", 129 | "\n", 130 | "short_cities = list(filter(lambda x: len(x) < 10, cities))\n", 131 | "print(short_cities)" 132 | ] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "execution_count": null, 137 | "metadata": {}, 138 | "outputs": [], 139 | "source": [] 140 | } 141 | ], 142 | "metadata": { 143 | "kernelspec": { 144 | "display_name": "Python 3", 145 | "language": "python", 146 | "name": "python3" 147 | }, 148 | "language_info": { 149 | "codemirror_mode": { 150 | "name": "ipython", 151 | "version": 3 152 | }, 153 | "file_extension": ".py", 154 | "mimetype": "text/x-python", 155 | "name": "python", 156 | "nbconvert_exporter": "python", 157 | "pygments_lexer": "ipython3", 158 | "version": "3.7.4" 159 | } 160 | }, 161 | "nbformat": 4, 162 | "nbformat_minor": 2 163 | } 164 | -------------------------------------------------------------------------------- /Python practice code/Lesson 7 NumPy.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import numpy as np" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 2, 15 | "metadata": {}, 16 | "outputs": [ 17 | { 18 | "name": "stdout", 19 | "output_type": "stream", 20 | "text": [ 21 | "x = [1 2 3 4 5]\n" 22 | ] 23 | } 24 | ], 25 | "source": [ 26 | "# We import NumPy into Python\n", 27 | "import numpy as np\n", 28 | "\n", 29 | "# We create a 1D ndarray that contains only integers\n", 30 | "x = np.array([1, 2, 3, 4, 5])\n", 31 | "\n", 32 | "# Let's print the ndarray we just created using the print() command\n", 33 | "print('x = ', x)" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": 3, 39 | "metadata": {}, 40 | "outputs": [ 41 | { 42 | "name": "stdout", 43 | "output_type": "stream", 44 | "text": [ 45 | "\n", 46 | "x = [1 2 3 4 5]\n", 47 | "\n", 48 | "x has dimensions: (5,)\n", 49 | "x is an object of type: \n", 50 | "The elements in x are of type: int32\n" 51 | ] 52 | } 53 | ], 54 | "source": [ 55 | "x = np.array([1, 2, 3, 4, 5])\n", 56 | "\n", 57 | "# We print x\n", 58 | "print()\n", 59 | "print('x = ', x)\n", 60 | "print()\n", 61 | "\n", 62 | "# We print information about x\n", 63 | "print('x has dimensions:', x.shape)\n", 64 | "print('x is an object of type:', type(x))\n", 65 | "print('The elements in x are of type:', x.dtype)" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": 4, 71 | "metadata": {}, 72 | "outputs": [ 73 | { 74 | "name": "stdout", 75 | "output_type": "stream", 76 | "text": [ 77 | "\n", 78 | "x = ['Hello' 'World']\n", 79 | "\n", 80 | "x has dimensions: (2,)\n", 81 | "x is an object of type: \n", 82 | "The elements in x are of type: \n", 114 | "The elements in x are of type: \n", 152 | "The elements in Y are of type: int32\n" 153 | ] 154 | } 155 | ], 156 | "source": [ 157 | "# We create a rank 2 ndarray that only contains integers\n", 158 | "Y = np.array([[1,2,3],[4,5,6],[7,8,9], [10,11,12]])\n", 159 | "\n", 160 | "# We print Y\n", 161 | "print()\n", 162 | "print('Y = \\n', Y)\n", 163 | "print()\n", 164 | "\n", 165 | "# We print information about Y\n", 166 | "print('Y has dimensions:', Y.shape)\n", 167 | "print('Y has a total of', Y.size, 'elements')\n", 168 | "print('Y is an object of type:', type(Y))\n", 169 | "print('The elements in Y are of type:', Y.dtype)" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": 7, 175 | "metadata": {}, 176 | "outputs": [ 177 | { 178 | "name": "stdout", 179 | "output_type": "stream", 180 | "text": [ 181 | "The elements in x are of type: int32\n", 182 | "The elements in y are of type: float64\n", 183 | "The elements in z are of type: float64\n" 184 | ] 185 | } 186 | ], 187 | "source": [ 188 | "# We create a rank 1 ndarray that contains integers\n", 189 | "x = np.array([1,2,3])\n", 190 | "\n", 191 | "# We create a rank 1 ndarray that contains floats\n", 192 | "y = np.array([1.0,2.0,3.0])\n", 193 | "\n", 194 | "# We create a rank 1 ndarray that contains integers and floats\n", 195 | "z = np.array([1, 2.5, 4])\n", 196 | "\n", 197 | "# We print the dtype of each ndarray\n", 198 | "print('The elements in x are of type:', x.dtype)\n", 199 | "print('The elements in y are of type:', y.dtype)\n", 200 | "print('The elements in z are of type:', z.dtype)" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": 8, 206 | "metadata": {}, 207 | "outputs": [ 208 | { 209 | "name": "stdout", 210 | "output_type": "stream", 211 | "text": [ 212 | "\n", 213 | "x = [1 2 3 4 5]\n", 214 | "\n", 215 | "The elements in x are of type: int64\n" 216 | ] 217 | } 218 | ], 219 | "source": [ 220 | "x = np.array([1.5, 2.2, 3.7, 4.0, 5.9], dtype = np.int64)\n", 221 | "\n", 222 | "# We print x\n", 223 | "print()\n", 224 | "print('x = ', x)\n", 225 | "print()\n", 226 | "\n", 227 | "# We print the dtype x\n", 228 | "print('The elements in x are of type:', x.dtype)" 229 | ] 230 | }, 231 | { 232 | "cell_type": "code", 233 | "execution_count": 9, 234 | "metadata": {}, 235 | "outputs": [], 236 | "source": [ 237 | "# We create a rank 1 ndarray\n", 238 | "x = np.array([1, 2, 3, 4, 5])\n", 239 | "\n", 240 | "# We save x into the current directory as \n", 241 | "np.save('my_array', x)" 242 | ] 243 | }, 244 | { 245 | "cell_type": "code", 246 | "execution_count": 10, 247 | "metadata": {}, 248 | "outputs": [ 249 | { 250 | "name": "stdout", 251 | "output_type": "stream", 252 | "text": [ 253 | "\n", 254 | "y = [1 2 3 4 5]\n", 255 | "\n", 256 | "y is an object of type: \n", 257 | "The elements in y are of type: int32\n" 258 | ] 259 | } 260 | ], 261 | "source": [ 262 | "y = np.load('my_array.npy')\n", 263 | "\n", 264 | "# We print y\n", 265 | "print()\n", 266 | "print('y = ', y)\n", 267 | "print()\n", 268 | "\n", 269 | "# We print information about the ndarray we loaded\n", 270 | "print('y is an object of type:', type(y))\n", 271 | "print('The elements in y are of type:', y.dtype)" 272 | ] 273 | }, 274 | { 275 | "cell_type": "code", 276 | "execution_count": 11, 277 | "metadata": {}, 278 | "outputs": [ 279 | { 280 | "name": "stdout", 281 | "output_type": "stream", 282 | "text": [ 283 | "\n", 284 | "X = \n", 285 | " [[0. 0. 0. 0.]\n", 286 | " [0. 0. 0. 0.]\n", 287 | " [0. 0. 0. 0.]]\n", 288 | "\n", 289 | "X has dimensions: (3, 4)\n", 290 | "X is an object of type: \n", 291 | "The elements in X are of type: float64\n" 292 | ] 293 | } 294 | ], 295 | "source": [ 296 | "X = np.zeros((3,4))\n", 297 | "\n", 298 | "# We print X\n", 299 | "print()\n", 300 | "print('X = \\n', X)\n", 301 | "print()\n", 302 | "\n", 303 | "# We print information about X\n", 304 | "print('X has dimensions:', X.shape)\n", 305 | "print('X is an object of type:', type(X))\n", 306 | "print('The elements in X are of type:', X.dtype)" 307 | ] 308 | }, 309 | { 310 | "cell_type": "code", 311 | "execution_count": 12, 312 | "metadata": {}, 313 | "outputs": [ 314 | { 315 | "name": "stdout", 316 | "output_type": "stream", 317 | "text": [ 318 | "\n", 319 | "X = \n", 320 | " [[1. 1.]\n", 321 | " [1. 1.]\n", 322 | " [1. 1.]]\n", 323 | "\n", 324 | "X has dimensions: (3, 2)\n", 325 | "X is an object of type: \n", 326 | "The elements in X are of type: float64\n" 327 | ] 328 | } 329 | ], 330 | "source": [ 331 | "# We create a 3 x 2 ndarray full of ones. \n", 332 | "X = np.ones((3,2))\n", 333 | "\n", 334 | "# We print X\n", 335 | "print()\n", 336 | "print('X = \\n', X)\n", 337 | "print()\n", 338 | "\n", 339 | "# We print information about X\n", 340 | "print('X has dimensions:', X.shape)\n", 341 | "print('X is an object of type:', type(X))\n", 342 | "print('The elements in X are of type:', X.dtype) " 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": 13, 348 | "metadata": {}, 349 | "outputs": [ 350 | { 351 | "name": "stdout", 352 | "output_type": "stream", 353 | "text": [ 354 | "\n", 355 | "X = \n", 356 | " [[5 5 5]\n", 357 | " [5 5 5]]\n", 358 | "\n", 359 | "X has dimensions: (2, 3)\n", 360 | "X is an object of type: \n", 361 | "The elements in X are of type: int32\n" 362 | ] 363 | } 364 | ], 365 | "source": [ 366 | "# We create a 2 x 3 ndarray full of fives. \n", 367 | "X = np.full((2,3), 5) \n", 368 | "\n", 369 | "# We print X\n", 370 | "print()\n", 371 | "print('X = \\n', X)\n", 372 | "print()\n", 373 | "\n", 374 | "# We print information about X\n", 375 | "print('X has dimensions:', X.shape)\n", 376 | "print('X is an object of type:', type(X))\n", 377 | "print('The elements in X are of type:', X.dtype) " 378 | ] 379 | }, 380 | { 381 | "cell_type": "code", 382 | "execution_count": 14, 383 | "metadata": {}, 384 | "outputs": [ 385 | { 386 | "name": "stdout", 387 | "output_type": "stream", 388 | "text": [ 389 | "\n", 390 | "X = \n", 391 | " [[1. 0. 0. 0. 0.]\n", 392 | " [0. 1. 0. 0. 0.]\n", 393 | " [0. 0. 1. 0. 0.]\n", 394 | " [0. 0. 0. 1. 0.]\n", 395 | " [0. 0. 0. 0. 1.]]\n", 396 | "\n", 397 | "X has dimensions: (5, 5)\n", 398 | "X is an object of type: \n", 399 | "The elements in X are of type: float64\n" 400 | ] 401 | } 402 | ], 403 | "source": [ 404 | "X = np.eye(5)\n", 405 | "\n", 406 | "# We print X\n", 407 | "print()\n", 408 | "print('X = \\n', X)\n", 409 | "print()\n", 410 | "\n", 411 | "# We print information about X\n", 412 | "print('X has dimensions:', X.shape)\n", 413 | "print('X is an object of type:', type(X))\n", 414 | "print('The elements in X are of type:', X.dtype) " 415 | ] 416 | }, 417 | { 418 | "cell_type": "code", 419 | "execution_count": 15, 420 | "metadata": {}, 421 | "outputs": [ 422 | { 423 | "name": "stdout", 424 | "output_type": "stream", 425 | "text": [ 426 | "\n", 427 | "X = \n", 428 | " [[10 0 0 0]\n", 429 | " [ 0 20 0 0]\n", 430 | " [ 0 0 30 0]\n", 431 | " [ 0 0 0 50]]\n", 432 | "\n" 433 | ] 434 | } 435 | ], 436 | "source": [ 437 | "# Create a 4 x 4 diagonal matrix that contains the numbers 10,20,30, and 50\n", 438 | "# on its main diagonal\n", 439 | "X = np.diag([10,20,30,50])\n", 440 | "\n", 441 | "# We print X\n", 442 | "print()\n", 443 | "print('X = \\n', X)\n", 444 | "print()" 445 | ] 446 | }, 447 | { 448 | "cell_type": "code", 449 | "execution_count": 16, 450 | "metadata": {}, 451 | "outputs": [ 452 | { 453 | "name": "stdout", 454 | "output_type": "stream", 455 | "text": [ 456 | "\n", 457 | "x = [0 1 2 3 4 5 6 7 8 9]\n", 458 | "\n", 459 | "x has dimensions: (10,)\n", 460 | "x is an object of type: \n", 461 | "The elements in x are of type: int32\n" 462 | ] 463 | } 464 | ], 465 | "source": [ 466 | "# We create a rank 1 ndarray that has sequential integers from 0 to 9\n", 467 | "x = np.arange(10)\n", 468 | "# We print the ndarray\n", 469 | "print()\n", 470 | "print('x = ', x)\n", 471 | "print()\n", 472 | "\n", 473 | "# We print information about the ndarray\n", 474 | "print('x has dimensions:', x.shape)\n", 475 | "print('x is an object of type:', type(x))\n", 476 | "print('The elements in x are of type:', x.dtype) " 477 | ] 478 | }, 479 | { 480 | "cell_type": "code", 481 | "execution_count": 17, 482 | "metadata": {}, 483 | "outputs": [ 484 | { 485 | "name": "stdout", 486 | "output_type": "stream", 487 | "text": [ 488 | "\n", 489 | "x = [4 5 6 7 8 9]\n", 490 | "\n", 491 | "x has dimensions: (6,)\n", 492 | "x is an object of type: \n", 493 | "The elements in x are of type: int32\n" 494 | ] 495 | } 496 | ], 497 | "source": [ 498 | "# We create a rank 1 ndarray that has sequential integers from 4 to 9. \n", 499 | "x = np.arange(4,10)\n", 500 | "\n", 501 | "# We print the ndarray\n", 502 | "print()\n", 503 | "print('x = ', x)\n", 504 | "print()\n", 505 | "\n", 506 | "# We print information about the ndarray\n", 507 | "print('x has dimensions:', x.shape)\n", 508 | "print('x is an object of type:', type(x))\n", 509 | "print('The elements in x are of type:', x.dtype) " 510 | ] 511 | }, 512 | { 513 | "cell_type": "code", 514 | "execution_count": 18, 515 | "metadata": {}, 516 | "outputs": [ 517 | { 518 | "name": "stdout", 519 | "output_type": "stream", 520 | "text": [ 521 | "\n", 522 | "x = [ 1 4 7 10 13]\n", 523 | "\n", 524 | "x has dimensions: (5,)\n", 525 | "x is an object of type: \n", 526 | "The elements in x are of type: int32\n" 527 | ] 528 | } 529 | ], 530 | "source": [ 531 | "# We create a rank 1 ndarray that has evenly spaced integers from 1 to 13 in steps of 3.\n", 532 | "x = np.arange(1,14,3)\n", 533 | "\n", 534 | "# We print the ndarray\n", 535 | "print()\n", 536 | "print('x = ', x)\n", 537 | "print()\n", 538 | "\n", 539 | "# We print information about the ndarray\n", 540 | "print('x has dimensions:', x.shape)\n", 541 | "print('x is an object of type:', type(x))\n", 542 | "print('The elements in x are of type:', x.dtype) " 543 | ] 544 | }, 545 | { 546 | "cell_type": "code", 547 | "execution_count": 19, 548 | "metadata": {}, 549 | "outputs": [ 550 | { 551 | "name": "stdout", 552 | "output_type": "stream", 553 | "text": [ 554 | "\n", 555 | "x = \n", 556 | " [ 0. 2.77777778 5.55555556 8.33333333 11.11111111 13.88888889\n", 557 | " 16.66666667 19.44444444 22.22222222 25. ]\n", 558 | "\n", 559 | "x has dimensions: (10,)\n", 560 | "x is an object of type: \n", 561 | "The elements in x are of type: float64\n" 562 | ] 563 | } 564 | ], 565 | "source": [ 566 | "# We create a rank 1 ndarray that has 10 integers evenly spaced between 0 and 25.\n", 567 | "x = np.linspace(0,25,10)\n", 568 | "\n", 569 | "# We print the ndarray\n", 570 | "print()\n", 571 | "print('x = \\n', x)\n", 572 | "print()\n", 573 | "\n", 574 | "# We print information about the ndarray\n", 575 | "print('x has dimensions:', x.shape)\n", 576 | "print('x is an object of type:', type(x))\n", 577 | "print('The elements in x are of type:', x.dtype) " 578 | ] 579 | }, 580 | { 581 | "cell_type": "code", 582 | "execution_count": 20, 583 | "metadata": {}, 584 | "outputs": [ 585 | { 586 | "name": "stdout", 587 | "output_type": "stream", 588 | "text": [ 589 | "\n", 590 | "x = [ 0. 2.5 5. 7.5 10. 12.5 15. 17.5 20. 22.5]\n", 591 | "\n", 592 | "x has dimensions: (10,)\n", 593 | "x is an object of type: \n", 594 | "The elements in x are of type: float64\n" 595 | ] 596 | } 597 | ], 598 | "source": [ 599 | "# We create a rank 1 ndarray that has 10 integers evenly spaced between 0 and 25,\n", 600 | "# with 25 excluded.\n", 601 | "x = np.linspace(0,25,10, endpoint = False)\n", 602 | "\n", 603 | "# We print the ndarray\n", 604 | "print()\n", 605 | "print('x = ', x)\n", 606 | "print()\n", 607 | "\n", 608 | "# We print information about the ndarray\n", 609 | "print('x has dimensions:', x.shape)\n", 610 | "print('x is an object of type:', type(x))\n", 611 | "print('The elements in x are of type:', x.dtype) " 612 | ] 613 | }, 614 | { 615 | "cell_type": "code", 616 | "execution_count": 21, 617 | "metadata": {}, 618 | "outputs": [ 619 | { 620 | "name": "stdout", 621 | "output_type": "stream", 622 | "text": [ 623 | "\n", 624 | "Original x = [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]\n", 625 | "\n", 626 | "\n", 627 | "Reshaped x = \n", 628 | " [[ 0 1 2 3 4]\n", 629 | " [ 5 6 7 8 9]\n", 630 | " [10 11 12 13 14]\n", 631 | " [15 16 17 18 19]]\n", 632 | "\n", 633 | "x has dimensions: (4, 5)\n", 634 | "x is an object of type: \n", 635 | "The elements in x are of type: int32\n" 636 | ] 637 | } 638 | ], 639 | "source": [ 640 | "# We create a rank 1 ndarray with sequential integers from 0 to 19\n", 641 | "x = np.arange(20)\n", 642 | "\n", 643 | "# We print x\n", 644 | "print()\n", 645 | "print('Original x = ', x)\n", 646 | "print()\n", 647 | "\n", 648 | "# We reshape x into a 4 x 5 ndarray \n", 649 | "x = np.reshape(x, (4,5))\n", 650 | "\n", 651 | "# We print the reshaped x\n", 652 | "print()\n", 653 | "print('Reshaped x = \\n', x)\n", 654 | "print()\n", 655 | "\n", 656 | "# We print information about the reshaped x\n", 657 | "print('x has dimensions:', x.shape)\n", 658 | "print('x is an object of type:', type(x))\n", 659 | "print('The elements in x are of type:', x.dtype) " 660 | ] 661 | }, 662 | { 663 | "cell_type": "code", 664 | "execution_count": 22, 665 | "metadata": {}, 666 | "outputs": [ 667 | { 668 | "name": "stdout", 669 | "output_type": "stream", 670 | "text": [ 671 | "\n", 672 | "Y = \n", 673 | " [[ 0 1 2 3 4]\n", 674 | " [ 5 6 7 8 9]\n", 675 | " [10 11 12 13 14]\n", 676 | " [15 16 17 18 19]]\n", 677 | "\n", 678 | "Y has dimensions: (4, 5)\n", 679 | "Y is an object of type: \n", 680 | "The elements in Y are of type: int32\n" 681 | ] 682 | } 683 | ], 684 | "source": [ 685 | "# We create a a rank 1 ndarray with sequential integers from 0 to 19 and\n", 686 | "# reshape it to a 4 x 5 array \n", 687 | "Y = np.arange(20).reshape(4, 5)\n", 688 | "\n", 689 | "# We print Y\n", 690 | "print()\n", 691 | "print('Y = \\n', Y)\n", 692 | "print()\n", 693 | "\n", 694 | "# We print information about Y\n", 695 | "print('Y has dimensions:', Y.shape)\n", 696 | "print('Y is an object of type:', type(Y))\n", 697 | "print('The elements in Y are of type:', Y.dtype) " 698 | ] 699 | }, 700 | { 701 | "cell_type": "code", 702 | "execution_count": 23, 703 | "metadata": {}, 704 | "outputs": [ 705 | { 706 | "name": "stdout", 707 | "output_type": "stream", 708 | "text": [ 709 | "\n", 710 | "X = \n", 711 | " [[ 0. 5.]\n", 712 | " [10. 15.]\n", 713 | " [20. 25.]\n", 714 | " [30. 35.]\n", 715 | " [40. 45.]]\n", 716 | "\n", 717 | "X has dimensions: (5, 2)\n", 718 | "X is an object of type: \n", 719 | "The elements in X are of type: float64\n" 720 | ] 721 | } 722 | ], 723 | "source": [ 724 | "# We create a rank 1 ndarray with 10 integers evenly spaced between 0 and 50,\n", 725 | "# with 50 excluded. We then reshape it to a 5 x 2 ndarray\n", 726 | "X = np.linspace(0,50,10, endpoint=False).reshape(5,2)\n", 727 | "\n", 728 | "# We print X\n", 729 | "print()\n", 730 | "print('X = \\n', X)\n", 731 | "print()\n", 732 | "\n", 733 | "# We print information about X\n", 734 | "print('X has dimensions:', X.shape)\n", 735 | "print('X is an object of type:', type(X))\n", 736 | "print('The elements in X are of type:', X.dtype)" 737 | ] 738 | }, 739 | { 740 | "cell_type": "code", 741 | "execution_count": 24, 742 | "metadata": {}, 743 | "outputs": [ 744 | { 745 | "name": "stdout", 746 | "output_type": "stream", 747 | "text": [ 748 | "\n", 749 | "X = \n", 750 | " [[0.47089728 0.35005305 0.52454707]\n", 751 | " [0.46738785 0.48583915 0.82068168]\n", 752 | " [0.92612258 0.318598 0.57275986]]\n", 753 | "\n", 754 | "X has dimensions: (3, 3)\n", 755 | "X is an object of type: \n", 756 | "The elements in x are of type: float64\n" 757 | ] 758 | } 759 | ], 760 | "source": [ 761 | "# We create a 3 x 3 ndarray with random floats in the half-open interval [0.0, 1.0).\n", 762 | "X = np.random.random((3,3))\n", 763 | "\n", 764 | "# We print X\n", 765 | "print()\n", 766 | "print('X = \\n', X)\n", 767 | "print()\n", 768 | "\n", 769 | "# We print information about X\n", 770 | "print('X has dimensions:', X.shape)\n", 771 | "print('X is an object of type:', type(X))\n", 772 | "print('The elements in x are of type:', X.dtype)" 773 | ] 774 | }, 775 | { 776 | "cell_type": "code", 777 | "execution_count": 25, 778 | "metadata": {}, 779 | "outputs": [ 780 | { 781 | "name": "stdout", 782 | "output_type": "stream", 783 | "text": [ 784 | "\n", 785 | "X = \n", 786 | " [[ 4 4]\n", 787 | " [14 8]\n", 788 | " [ 6 12]]\n", 789 | "\n", 790 | "X has dimensions: (3, 2)\n", 791 | "X is an object of type: \n", 792 | "The elements in X are of type: int32\n" 793 | ] 794 | } 795 | ], 796 | "source": [ 797 | "# We create a 3 x 2 ndarray with random integers in the half-open interval [4, 15).\n", 798 | "X = np.random.randint(4,15,size=(3,2))\n", 799 | "\n", 800 | "# We print X\n", 801 | "print()\n", 802 | "print('X = \\n', X)\n", 803 | "print()\n", 804 | "\n", 805 | "# We print information about X\n", 806 | "print('X has dimensions:', X.shape)\n", 807 | "print('X is an object of type:', type(X))\n", 808 | "print('The elements in X are of type:', X.dtype)" 809 | ] 810 | }, 811 | { 812 | "cell_type": "code", 813 | "execution_count": 26, 814 | "metadata": {}, 815 | "outputs": [ 816 | { 817 | "name": "stdout", 818 | "output_type": "stream", 819 | "text": [ 820 | "\n", 821 | "X = \n", 822 | " [[ 0.12511164 -0.02752587 0.1420215 ... 0.00797144 -0.03847892\n", 823 | " -0.18585822]\n", 824 | " [-0.08747705 -0.16683667 -0.05085764 ... -0.20539315 -0.07713024\n", 825 | " 0.088478 ]\n", 826 | " [-0.09891267 0.10802782 0.00852274 ... 0.05142707 0.16043037\n", 827 | " 0.02405662]\n", 828 | " ...\n", 829 | " [-0.01381603 0.00234542 0.25194382 ... 0.13087115 0.07262435\n", 830 | " 0.02460938]\n", 831 | " [ 0.01600749 0.11170208 0.0371197 ... 0.00782658 -0.10869874\n", 832 | " -0.18625481]\n", 833 | " [ 0.13550202 0.06628341 0.00594962 ... -0.01602089 0.22404048\n", 834 | " -0.2355207 ]]\n", 835 | "\n", 836 | "X has dimensions: (1000, 1000)\n", 837 | "X is an object of type: \n", 838 | "The elements in X are of type: float64\n", 839 | "The elements in X have a mean of: 0.000159801207710365\n", 840 | "The maximum value in X is: 0.452330225859304\n", 841 | "The minimum value in X is: -0.4722710865131903\n", 842 | "X has 499122 negative numbers\n", 843 | "X has 500878 positive numbers\n" 844 | ] 845 | } 846 | ], 847 | "source": [ 848 | "# We create a 1000 x 1000 ndarray of random floats drawn from normal (Gaussian) distribution\n", 849 | "# with a mean of zero and a standard deviation of 0.1.\n", 850 | "X = np.random.normal(0, 0.1, size=(1000,1000))\n", 851 | "\n", 852 | "# We print X\n", 853 | "print()\n", 854 | "print('X = \\n', X)\n", 855 | "print()\n", 856 | "\n", 857 | "# We print information about X\n", 858 | "print('X has dimensions:', X.shape)\n", 859 | "print('X is an object of type:', type(X))\n", 860 | "print('The elements in X are of type:', X.dtype)\n", 861 | "print('The elements in X have a mean of:', X.mean())\n", 862 | "print('The maximum value in X is:', X.max())\n", 863 | "print('The minimum value in X is:', X.min())\n", 864 | "print('X has', (X < 0).sum(), 'negative numbers')\n", 865 | "print('X has', (X > 0).sum(), 'positive numbers')" 866 | ] 867 | }, 868 | { 869 | "cell_type": "code", 870 | "execution_count": 27, 871 | "metadata": {}, 872 | "outputs": [ 873 | { 874 | "name": "stdout", 875 | "output_type": "stream", 876 | "text": [ 877 | "\n", 878 | "x = [1 2 3 4 5]\n", 879 | "\n", 880 | "This is First Element in x: 1\n", 881 | "This is Second Element in x: 2\n", 882 | "This is Fifth (Last) Element in x: 5\n", 883 | "\n", 884 | "This is First Element in x: 1\n", 885 | "This is Second Element in x: 2\n", 886 | "This is Fifth (Last) Element in x: 5\n" 887 | ] 888 | } 889 | ], 890 | "source": [ 891 | "x = np.array([1, 2, 3, 4, 5])\n", 892 | "\n", 893 | "# We print x\n", 894 | "print()\n", 895 | "print('x = ', x)\n", 896 | "print()\n", 897 | "\n", 898 | "# Let's access some elements with positive indices\n", 899 | "print('This is First Element in x:', x[0]) \n", 900 | "print('This is Second Element in x:', x[1])\n", 901 | "print('This is Fifth (Last) Element in x:', x[4])\n", 902 | "print()\n", 903 | "\n", 904 | "# Let's access the same elements with negative indices\n", 905 | "print('This is First Element in x:', x[-5])\n", 906 | "print('This is Second Element in x:', x[-4])\n", 907 | "print('This is Fifth (Last) Element in x:', x[-1])" 908 | ] 909 | }, 910 | { 911 | "cell_type": "code", 912 | "execution_count": 28, 913 | "metadata": {}, 914 | "outputs": [ 915 | { 916 | "name": "stdout", 917 | "output_type": "stream", 918 | "text": [ 919 | "\n", 920 | "Original:\n", 921 | " x = [1 2 3 4 5]\n", 922 | "\n", 923 | "Modified:\n", 924 | " x = [ 1 2 3 20 5]\n" 925 | ] 926 | } 927 | ], 928 | "source": [ 929 | "# We create a rank 1 ndarray that contains integers from 1 to 5\n", 930 | "x = np.array([1, 2, 3, 4, 5])\n", 931 | "\n", 932 | "# We print the original x\n", 933 | "print()\n", 934 | "print('Original:\\n x = ', x)\n", 935 | "print()\n", 936 | "\n", 937 | "# We change the fourth element in x from 4 to 20\n", 938 | "x[3] = 20\n", 939 | "\n", 940 | "# We print x after it was modified \n", 941 | "print('Modified:\\n x = ', x)" 942 | ] 943 | }, 944 | { 945 | "cell_type": "code", 946 | "execution_count": 29, 947 | "metadata": {}, 948 | "outputs": [ 949 | { 950 | "name": "stdout", 951 | "output_type": "stream", 952 | "text": [ 953 | "\n", 954 | "X = \n", 955 | " [[1 2 3]\n", 956 | " [4 5 6]\n", 957 | " [7 8 9]]\n", 958 | "\n", 959 | "This is (0,0) Element in X: 1\n", 960 | "This is (0,1) Element in X: 2\n", 961 | "This is (2,2) Element in X: 9\n" 962 | ] 963 | } 964 | ], 965 | "source": [ 966 | "# We create a 3 x 3 rank 2 ndarray that contains integers from 1 to 9\n", 967 | "X = np.array([[1,2,3],[4,5,6],[7,8,9]])\n", 968 | "\n", 969 | "# We print X\n", 970 | "print()\n", 971 | "print('X = \\n', X)\n", 972 | "print()\n", 973 | "\n", 974 | "# Let's access some elements in X\n", 975 | "print('This is (0,0) Element in X:', X[0,0])\n", 976 | "print('This is (0,1) Element in X:', X[0,1])\n", 977 | "print('This is (2,2) Element in X:', X[2,2])" 978 | ] 979 | }, 980 | { 981 | "cell_type": "code", 982 | "execution_count": 30, 983 | "metadata": {}, 984 | "outputs": [ 985 | { 986 | "name": "stdout", 987 | "output_type": "stream", 988 | "text": [ 989 | "\n", 990 | "Original:\n", 991 | " X = \n", 992 | " [[1 2 3]\n", 993 | " [4 5 6]\n", 994 | " [7 8 9]]\n", 995 | "\n", 996 | "Modified:\n", 997 | " X = \n", 998 | " [[20 2 3]\n", 999 | " [ 4 5 6]\n", 1000 | " [ 7 8 9]]\n" 1001 | ] 1002 | } 1003 | ], 1004 | "source": [ 1005 | "# We create a 3 x 3 rank 2 ndarray that contains integers from 1 to 9\n", 1006 | "X = np.array([[1,2,3],[4,5,6],[7,8,9]])\n", 1007 | "\n", 1008 | "# We print the original x\n", 1009 | "print()\n", 1010 | "print('Original:\\n X = \\n', X)\n", 1011 | "print()\n", 1012 | "\n", 1013 | "# We change the (0,0) element in X from 1 to 20\n", 1014 | "X[0,0] = 20\n", 1015 | "\n", 1016 | "# We print X after it was modified \n", 1017 | "print('Modified:\\n X = \\n', X)" 1018 | ] 1019 | }, 1020 | { 1021 | "cell_type": "code", 1022 | "execution_count": 31, 1023 | "metadata": {}, 1024 | "outputs": [ 1025 | { 1026 | "name": "stdout", 1027 | "output_type": "stream", 1028 | "text": [ 1029 | "\n", 1030 | "Original x = [1 2 3 4 5]\n", 1031 | "\n", 1032 | "Modified x = [2 3 4]\n", 1033 | "\n", 1034 | "Original Y = \n", 1035 | " [[1 2 3]\n", 1036 | " [4 5 6]\n", 1037 | " [7 8 9]]\n", 1038 | "\n", 1039 | "w = \n", 1040 | " [[4 5 6]\n", 1041 | " [7 8 9]]\n", 1042 | "\n", 1043 | "v = \n", 1044 | " [[2]\n", 1045 | " [5]\n", 1046 | " [8]]\n" 1047 | ] 1048 | } 1049 | ], 1050 | "source": [ 1051 | "# We create a rank 1 ndarray \n", 1052 | "x = np.array([1, 2, 3, 4, 5])\n", 1053 | "\n", 1054 | "# We create a rank 2 ndarray\n", 1055 | "Y = np.array([[1,2,3],[4,5,6],[7,8,9]])\n", 1056 | "\n", 1057 | "# We print x\n", 1058 | "print()\n", 1059 | "print('Original x = ', x)\n", 1060 | "\n", 1061 | "# We delete the first and last element of x\n", 1062 | "x = np.delete(x, [0,4])\n", 1063 | "\n", 1064 | "# We print x with the first and last element deleted\n", 1065 | "print()\n", 1066 | "print('Modified x = ', x)\n", 1067 | "\n", 1068 | "# We print Y\n", 1069 | "print()\n", 1070 | "print('Original Y = \\n', Y)\n", 1071 | "\n", 1072 | "# We delete the first row of y\n", 1073 | "w = np.delete(Y, 0, axis=0)\n", 1074 | "\n", 1075 | "# We delete the first and last column of y\n", 1076 | "v = np.delete(Y, [0,2], axis=1)\n", 1077 | "\n", 1078 | "# We print w\n", 1079 | "print()\n", 1080 | "print('w = \\n', w)\n", 1081 | "\n", 1082 | "# We print v\n", 1083 | "print()\n", 1084 | "print('v = \\n', v)" 1085 | ] 1086 | }, 1087 | { 1088 | "cell_type": "code", 1089 | "execution_count": 32, 1090 | "metadata": {}, 1091 | "outputs": [ 1092 | { 1093 | "name": "stdout", 1094 | "output_type": "stream", 1095 | "text": [ 1096 | "\n", 1097 | "Original x = [1 2 3 4 5]\n", 1098 | "\n", 1099 | "x = [1 2 3 4 5 6]\n", 1100 | "\n", 1101 | "x = [1 2 3 4 5 6 7 8]\n", 1102 | "\n", 1103 | "Original Y = \n", 1104 | " [[1 2 3]\n", 1105 | " [4 5 6]]\n", 1106 | "\n", 1107 | "v = \n", 1108 | " [[1 2 3]\n", 1109 | " [4 5 6]\n", 1110 | " [7 8 9]]\n", 1111 | "\n", 1112 | "q = \n", 1113 | " [[ 1 2 3 9]\n", 1114 | " [ 4 5 6 10]]\n" 1115 | ] 1116 | } 1117 | ], 1118 | "source": [ 1119 | "# We create a rank 1 ndarray \n", 1120 | "x = np.array([1, 2, 3, 4, 5])\n", 1121 | "\n", 1122 | "# We create a rank 2 ndarray \n", 1123 | "Y = np.array([[1,2,3],[4,5,6]])\n", 1124 | "\n", 1125 | "# We print x\n", 1126 | "print()\n", 1127 | "print('Original x = ', x)\n", 1128 | "\n", 1129 | "# We append the integer 6 to x\n", 1130 | "x = np.append(x, 6)\n", 1131 | "\n", 1132 | "# We print x\n", 1133 | "print()\n", 1134 | "print('x = ', x)\n", 1135 | "\n", 1136 | "# We append the integer 7 and 8 to x\n", 1137 | "x = np.append(x, [7,8])\n", 1138 | "\n", 1139 | "# We print x\n", 1140 | "print()\n", 1141 | "print('x = ', x)\n", 1142 | "\n", 1143 | "# We print Y\n", 1144 | "print()\n", 1145 | "print('Original Y = \\n', Y)\n", 1146 | "\n", 1147 | "# We append a new row containing 7,8,9 to y\n", 1148 | "v = np.append(Y, [[7,8,9]], axis=0)\n", 1149 | "\n", 1150 | "# We append a new column containing 9 and 10 to y\n", 1151 | "q = np.append(Y,[[9],[10]], axis=1)\n", 1152 | "\n", 1153 | "# We print v\n", 1154 | "print()\n", 1155 | "print('v = \\n', v)\n", 1156 | "\n", 1157 | "# We print q\n", 1158 | "print()\n", 1159 | "print('q = \\n', q)" 1160 | ] 1161 | }, 1162 | { 1163 | "cell_type": "code", 1164 | "execution_count": 33, 1165 | "metadata": {}, 1166 | "outputs": [ 1167 | { 1168 | "name": "stdout", 1169 | "output_type": "stream", 1170 | "text": [ 1171 | "\n", 1172 | "Original x = [1 2 5 6 7]\n", 1173 | "\n", 1174 | "x = [1 2 3 4 5 6 7]\n", 1175 | "\n", 1176 | "Original Y = \n", 1177 | " [[1 2 3]\n", 1178 | " [7 8 9]]\n", 1179 | "\n", 1180 | "w = \n", 1181 | " [[1 2 3]\n", 1182 | " [4 5 6]\n", 1183 | " [7 8 9]]\n", 1184 | "\n", 1185 | "v = \n", 1186 | " [[1 5 2 3]\n", 1187 | " [7 5 8 9]]\n" 1188 | ] 1189 | } 1190 | ], 1191 | "source": [ 1192 | "x = np.array([1, 2, 5, 6, 7])\n", 1193 | "\n", 1194 | "# We create a rank 2 ndarray \n", 1195 | "Y = np.array([[1,2,3],[7,8,9]])\n", 1196 | "\n", 1197 | "# We print x\n", 1198 | "print()\n", 1199 | "print('Original x = ', x)\n", 1200 | "\n", 1201 | "# We insert the integer 3 and 4 between 2 and 5 in x. \n", 1202 | "x = np.insert(x,2,[3,4])\n", 1203 | "\n", 1204 | "# We print x with the inserted elements\n", 1205 | "print()\n", 1206 | "print('x = ', x)\n", 1207 | "\n", 1208 | "# We print Y\n", 1209 | "print()\n", 1210 | "print('Original Y = \\n', Y)\n", 1211 | "\n", 1212 | "# We insert a row between the first and last row of y\n", 1213 | "w = np.insert(Y,1,[4,5,6],axis=0)\n", 1214 | "\n", 1215 | "# We insert a column full of 5s between the first and second column of y\n", 1216 | "v = np.insert(Y,1,5, axis=1)\n", 1217 | "\n", 1218 | "# We print w\n", 1219 | "print()\n", 1220 | "print('w = \\n', w)\n", 1221 | "\n", 1222 | "# We print v\n", 1223 | "print()\n", 1224 | "print('v = \\n', v)" 1225 | ] 1226 | }, 1227 | { 1228 | "cell_type": "code", 1229 | "execution_count": 34, 1230 | "metadata": {}, 1231 | "outputs": [ 1232 | { 1233 | "name": "stdout", 1234 | "output_type": "stream", 1235 | "text": [ 1236 | "\n", 1237 | "x = [1 2]\n", 1238 | "\n", 1239 | "Y = \n", 1240 | " [[3 4]\n", 1241 | " [5 6]]\n", 1242 | "\n", 1243 | "z = \n", 1244 | " [[1 2]\n", 1245 | " [3 4]\n", 1246 | " [5 6]]\n", 1247 | "\n", 1248 | "w = \n", 1249 | " [[3 4 1]\n", 1250 | " [5 6 2]]\n" 1251 | ] 1252 | } 1253 | ], 1254 | "source": [ 1255 | "# We create a rank 1 ndarray \n", 1256 | "x = np.array([1,2])\n", 1257 | "\n", 1258 | "# We create a rank 2 ndarray \n", 1259 | "Y = np.array([[3,4],[5,6]])\n", 1260 | "\n", 1261 | "# We print x\n", 1262 | "print()\n", 1263 | "print('x = ', x)\n", 1264 | "\n", 1265 | "# We print Y\n", 1266 | "print()\n", 1267 | "print('Y = \\n', Y)\n", 1268 | "\n", 1269 | "# We stack x on top of Y\n", 1270 | "z = np.vstack((x,Y))\n", 1271 | "\n", 1272 | "# We stack x on the right of Y. We need to reshape x in order to stack it on the right of Y. \n", 1273 | "w = np.hstack((Y,x.reshape(2,1)))\n", 1274 | "\n", 1275 | "# We print z\n", 1276 | "print()\n", 1277 | "print('z = \\n', z)\n", 1278 | "\n", 1279 | "# We print w\n", 1280 | "print()\n", 1281 | "print('w = \\n', w)" 1282 | ] 1283 | }, 1284 | { 1285 | "cell_type": "code", 1286 | "execution_count": 35, 1287 | "metadata": {}, 1288 | "outputs": [ 1289 | { 1290 | "name": "stdout", 1291 | "output_type": "stream", 1292 | "text": [ 1293 | "\n", 1294 | "X = \n", 1295 | " [[ 0 1 2 3 4]\n", 1296 | " [ 5 6 7 8 9]\n", 1297 | " [10 11 12 13 14]\n", 1298 | " [15 16 17 18 19]]\n", 1299 | "\n", 1300 | "Z = \n", 1301 | " [[ 7 8 9]\n", 1302 | " [12 13 14]\n", 1303 | " [17 18 19]]\n", 1304 | "\n", 1305 | "W = \n", 1306 | " [[ 7 8 9]\n", 1307 | " [12 13 14]\n", 1308 | " [17 18 19]]\n", 1309 | "\n", 1310 | "Y = \n", 1311 | " [[ 2 3 4]\n", 1312 | " [ 7 8 9]\n", 1313 | " [12 13 14]]\n", 1314 | "\n", 1315 | "v = [10 11 12 13 14]\n", 1316 | "\n", 1317 | "q = [ 2 7 12 17]\n", 1318 | "\n", 1319 | "R = \n", 1320 | " [[ 2]\n", 1321 | " [ 7]\n", 1322 | " [12]\n", 1323 | " [17]]\n" 1324 | ] 1325 | } 1326 | ], 1327 | "source": [ 1328 | "# We create a 4 x 5 ndarray that contains integers from 0 to 19\n", 1329 | "X = np.arange(20).reshape(4, 5)\n", 1330 | "\n", 1331 | "# We print X\n", 1332 | "print()\n", 1333 | "print('X = \\n', X)\n", 1334 | "print()\n", 1335 | "\n", 1336 | "# We select all the elements that are in the 2nd through 4th rows and in the 3rd to 5th columns\n", 1337 | "Z = X[1:4,2:5]\n", 1338 | "\n", 1339 | "# We print Z\n", 1340 | "print('Z = \\n', Z)\n", 1341 | "\n", 1342 | "# We can select the same elements as above using method 2\n", 1343 | "W = X[1:,2:5]\n", 1344 | "\n", 1345 | "# We print W\n", 1346 | "print()\n", 1347 | "print('W = \\n', W)\n", 1348 | "\n", 1349 | "# We select all the elements that are in the 1st through 3rd rows and in the 3rd to 4th columns\n", 1350 | "Y = X[:3,2:5]\n", 1351 | "\n", 1352 | "# We print Y\n", 1353 | "print()\n", 1354 | "print('Y = \\n', Y)\n", 1355 | "\n", 1356 | "# We select all the elements in the 3rd row\n", 1357 | "v = X[2,:]\n", 1358 | "\n", 1359 | "# We print v\n", 1360 | "print()\n", 1361 | "print('v = ', v)\n", 1362 | "\n", 1363 | "# We select all the elements in the 3rd column\n", 1364 | "q = X[:,2]\n", 1365 | "\n", 1366 | "# We print q\n", 1367 | "print()\n", 1368 | "print('q = ', q)\n", 1369 | "\n", 1370 | "# We select all the elements in the 3rd column but return a rank 2 ndarray\n", 1371 | "R = X[:,2:3]\n", 1372 | "\n", 1373 | "# We print R\n", 1374 | "print()\n", 1375 | "print('R = \\n', R)" 1376 | ] 1377 | }, 1378 | { 1379 | "cell_type": "code", 1380 | "execution_count": 36, 1381 | "metadata": {}, 1382 | "outputs": [ 1383 | { 1384 | "name": "stdout", 1385 | "output_type": "stream", 1386 | "text": [ 1387 | "\n", 1388 | "X = \n", 1389 | " [[ 0 1 2 3 4]\n", 1390 | " [ 5 6 7 8 9]\n", 1391 | " [10 11 12 13 14]\n", 1392 | " [15 16 17 18 19]]\n", 1393 | "\n", 1394 | "\n", 1395 | "Z = \n", 1396 | " [[ 7 8 9]\n", 1397 | " [12 13 14]\n", 1398 | " [17 18 19]]\n", 1399 | "\n", 1400 | "\n", 1401 | "X = \n", 1402 | " [[ 0 1 2 3 4]\n", 1403 | " [ 5 6 7 8 9]\n", 1404 | " [ 10 11 12 13 14]\n", 1405 | " [ 15 16 17 18 555]]\n", 1406 | "\n" 1407 | ] 1408 | } 1409 | ], 1410 | "source": [ 1411 | "# We create a 4 x 5 ndarray that contains integers from 0 to 19\n", 1412 | "X = np.arange(20).reshape(4, 5)\n", 1413 | "\n", 1414 | "# We print X\n", 1415 | "print()\n", 1416 | "print('X = \\n', X)\n", 1417 | "print()\n", 1418 | "\n", 1419 | "# We select all the elements that are in the 2nd through 4th rows and in the 3rd to 4th columns\n", 1420 | "Z = X[1:4,2:5]\n", 1421 | "\n", 1422 | "# We print Z\n", 1423 | "print()\n", 1424 | "print('Z = \\n', Z)\n", 1425 | "print()\n", 1426 | "\n", 1427 | "# We change the last element in Z to 555\n", 1428 | "Z[2,2] = 555\n", 1429 | "\n", 1430 | "# We print X\n", 1431 | "print()\n", 1432 | "print('X = \\n', X)\n", 1433 | "print()" 1434 | ] 1435 | }, 1436 | { 1437 | "cell_type": "code", 1438 | "execution_count": 37, 1439 | "metadata": {}, 1440 | "outputs": [ 1441 | { 1442 | "name": "stdout", 1443 | "output_type": "stream", 1444 | "text": [ 1445 | "\n", 1446 | "X = \n", 1447 | " [[ 0 1 2 3 4]\n", 1448 | " [ 5 6 7 8 9]\n", 1449 | " [10 11 12 13 14]\n", 1450 | " [15 16 17 18 19]]\n", 1451 | "\n", 1452 | "\n", 1453 | "X = \n", 1454 | " [[ 0 1 2 3 4]\n", 1455 | " [ 5 6 7 8 9]\n", 1456 | " [10 11 12 13 14]\n", 1457 | " [15 16 17 18 19]]\n", 1458 | "\n", 1459 | "Z = \n", 1460 | " [[ 7 8 9]\n", 1461 | " [ 12 13 14]\n", 1462 | " [ 17 18 555]]\n", 1463 | "\n", 1464 | "W = \n", 1465 | " [[ 7 8 9]\n", 1466 | " [ 12 13 14]\n", 1467 | " [ 17 18 444]]\n" 1468 | ] 1469 | } 1470 | ], 1471 | "source": [ 1472 | "# We create a 4 x 5 ndarray that contains integers from 0 to 19\n", 1473 | "X = np.arange(20).reshape(4, 5)\n", 1474 | "\n", 1475 | "# We print X\n", 1476 | "print()\n", 1477 | "print('X = \\n', X)\n", 1478 | "print()\n", 1479 | "\n", 1480 | "# create a copy of the slice using the np.copy() function\n", 1481 | "Z = np.copy(X[1:4,2:5])\n", 1482 | "\n", 1483 | "# create a copy of the slice using the copy as a method\n", 1484 | "W = X[1:4,2:5].copy()\n", 1485 | "\n", 1486 | "# We change the last element in Z to 555\n", 1487 | "Z[2,2] = 555\n", 1488 | "\n", 1489 | "# We change the last element in W to 444\n", 1490 | "W[2,2] = 444\n", 1491 | "\n", 1492 | "# We print X\n", 1493 | "print()\n", 1494 | "print('X = \\n', X)\n", 1495 | "\n", 1496 | "# We print Z\n", 1497 | "print()\n", 1498 | "print('Z = \\n', Z)\n", 1499 | "\n", 1500 | "# We print W\n", 1501 | "print()\n", 1502 | "print('W = \\n', W)" 1503 | ] 1504 | }, 1505 | { 1506 | "cell_type": "code", 1507 | "execution_count": 38, 1508 | "metadata": {}, 1509 | "outputs": [ 1510 | { 1511 | "name": "stdout", 1512 | "output_type": "stream", 1513 | "text": [ 1514 | "\n", 1515 | "X = \n", 1516 | " [[ 0 1 2 3 4]\n", 1517 | " [ 5 6 7 8 9]\n", 1518 | " [10 11 12 13 14]\n", 1519 | " [15 16 17 18 19]]\n", 1520 | "\n", 1521 | "indices = [1 3]\n", 1522 | "\n", 1523 | "\n", 1524 | "Y = \n", 1525 | " [[ 5 6 7 8 9]\n", 1526 | " [15 16 17 18 19]]\n", 1527 | "\n", 1528 | "Z = \n", 1529 | " [[ 1 3]\n", 1530 | " [ 6 8]\n", 1531 | " [11 13]\n", 1532 | " [16 18]]\n" 1533 | ] 1534 | } 1535 | ], 1536 | "source": [ 1537 | "# We create a 4 x 5 ndarray that contains integers from 0 to 19\n", 1538 | "X = np.arange(20).reshape(4, 5)\n", 1539 | "\n", 1540 | "# We create a rank 1 ndarray that will serve as indices to select elements from X\n", 1541 | "indices = np.array([1,3])\n", 1542 | "\n", 1543 | "# We print X\n", 1544 | "print()\n", 1545 | "print('X = \\n', X)\n", 1546 | "print()\n", 1547 | "\n", 1548 | "# We print indices\n", 1549 | "print('indices = ', indices)\n", 1550 | "print()\n", 1551 | "\n", 1552 | "# We use the indices ndarray to select the 2nd and 4th row of X\n", 1553 | "Y = X[indices,:]\n", 1554 | "\n", 1555 | "# We use the indices ndarray to select the 2nd and 4th column of X\n", 1556 | "Z = X[:, indices]\n", 1557 | "\n", 1558 | "# We print Y\n", 1559 | "print()\n", 1560 | "print('Y = \\n', Y)\n", 1561 | "\n", 1562 | "# We print Z\n", 1563 | "print()\n", 1564 | "print('Z = \\n', Z)" 1565 | ] 1566 | }, 1567 | { 1568 | "cell_type": "code", 1569 | "execution_count": 39, 1570 | "metadata": {}, 1571 | "outputs": [ 1572 | { 1573 | "name": "stdout", 1574 | "output_type": "stream", 1575 | "text": [ 1576 | "\n", 1577 | "X = \n", 1578 | " [[ 0 1 2 3 4]\n", 1579 | " [ 5 6 7 8 9]\n", 1580 | " [10 11 12 13 14]\n", 1581 | " [15 16 17 18 19]\n", 1582 | " [20 21 22 23 24]]\n", 1583 | "\n", 1584 | "z = [ 0 6 12 18 24]\n", 1585 | "\n", 1586 | "y = [ 1 7 13 19]\n", 1587 | "\n", 1588 | "w = [ 5 11 17 23]\n" 1589 | ] 1590 | } 1591 | ], 1592 | "source": [ 1593 | "# We create a 4 x 5 ndarray that contains integers from 0 to 19\n", 1594 | "X = np.arange(25).reshape(5, 5)\n", 1595 | "\n", 1596 | "# We print X\n", 1597 | "print()\n", 1598 | "print('X = \\n', X)\n", 1599 | "print()\n", 1600 | "\n", 1601 | "# We print the elements in the main diagonal of X\n", 1602 | "print('z =', np.diag(X))\n", 1603 | "print()\n", 1604 | "\n", 1605 | "# We print the elements above the main diagonal of X\n", 1606 | "print('y =', np.diag(X, k=1))\n", 1607 | "print()\n", 1608 | "\n", 1609 | "# We print the elements below the main diagonal of X\n", 1610 | "print('w = ', np.diag(X, k=-1))" 1611 | ] 1612 | }, 1613 | { 1614 | "cell_type": "code", 1615 | "execution_count": 40, 1616 | "metadata": {}, 1617 | "outputs": [ 1618 | { 1619 | "name": "stdout", 1620 | "output_type": "stream", 1621 | "text": [ 1622 | "\n", 1623 | "X = \n", 1624 | " [[1 2 3]\n", 1625 | " [5 2 8]\n", 1626 | " [1 2 3]]\n", 1627 | "\n", 1628 | "The unique elements in X are: [1 2 3 5 8]\n" 1629 | ] 1630 | } 1631 | ], 1632 | "source": [ 1633 | "# Create 3 x 3 ndarray with repeated values\n", 1634 | "X = np.array([[1,2,3],[5,2,8],[1,2,3]])\n", 1635 | "\n", 1636 | "# We print X\n", 1637 | "print()\n", 1638 | "print('X = \\n', X)\n", 1639 | "print()\n", 1640 | "\n", 1641 | "# We print the unique elements of X \n", 1642 | "print('The unique elements in X are:',np.unique(X))" 1643 | ] 1644 | }, 1645 | { 1646 | "cell_type": "code", 1647 | "execution_count": 41, 1648 | "metadata": {}, 1649 | "outputs": [ 1650 | { 1651 | "name": "stdout", 1652 | "output_type": "stream", 1653 | "text": [ 1654 | "\n", 1655 | "Original X = \n", 1656 | " [[ 0 1 2 3 4]\n", 1657 | " [ 5 6 7 8 9]\n", 1658 | " [10 11 12 13 14]\n", 1659 | " [15 16 17 18 19]\n", 1660 | " [20 21 22 23 24]]\n", 1661 | "\n", 1662 | "The elements in X that are greater than 10: [11 12 13 14 15 16 17 18 19 20 21 22 23 24]\n", 1663 | "The elements in X that less than or equal to 7: [0 1 2 3 4 5 6 7]\n", 1664 | "The elements in X that are between 10 and 17: [11 12 13 14 15 16]\n", 1665 | "\n", 1666 | "X = \n", 1667 | " [[ 0 1 2 3 4]\n", 1668 | " [ 5 6 7 8 9]\n", 1669 | " [10 -1 -1 -1 -1]\n", 1670 | " [-1 -1 17 18 19]\n", 1671 | " [20 21 22 23 24]]\n", 1672 | "\n" 1673 | ] 1674 | } 1675 | ], 1676 | "source": [ 1677 | "# We create a 5 x 5 ndarray that contains integers from 0 to 24\n", 1678 | "X = np.arange(25).reshape(5, 5)\n", 1679 | "\n", 1680 | "# We print X\n", 1681 | "print()\n", 1682 | "print('Original X = \\n', X)\n", 1683 | "print()\n", 1684 | "\n", 1685 | "# We use Boolean indexing to select elements in X:\n", 1686 | "print('The elements in X that are greater than 10:', X[X > 10])\n", 1687 | "print('The elements in X that less than or equal to 7:', X[X <= 7])\n", 1688 | "print('The elements in X that are between 10 and 17:', X[(X > 10) & (X < 17)])\n", 1689 | "\n", 1690 | "# We use Boolean indexing to assign the elements that are between 10 and 17 the value of -1\n", 1691 | "X[(X > 10) & (X < 17)] = -1\n", 1692 | "\n", 1693 | "# We print X\n", 1694 | "print()\n", 1695 | "print('X = \\n', X)\n", 1696 | "print()" 1697 | ] 1698 | }, 1699 | { 1700 | "cell_type": "code", 1701 | "execution_count": 42, 1702 | "metadata": {}, 1703 | "outputs": [ 1704 | { 1705 | "name": "stdout", 1706 | "output_type": "stream", 1707 | "text": [ 1708 | "\n", 1709 | "x = [1 2 3 4 5]\n", 1710 | "\n", 1711 | "y = [6 7 2 8 4]\n", 1712 | "\n", 1713 | "The elements that are both in x and y: [2 4]\n", 1714 | "The elements that are in x that are not in y: [1 3 5]\n", 1715 | "All the elements of x and y: [1 2 3 4 5 6 7 8]\n" 1716 | ] 1717 | } 1718 | ], 1719 | "source": [ 1720 | "# We create a rank 1 ndarray\n", 1721 | "x = np.array([1,2,3,4,5])\n", 1722 | "\n", 1723 | "# We create a rank 1 ndarray\n", 1724 | "y = np.array([6,7,2,8,4])\n", 1725 | "\n", 1726 | "# We print x\n", 1727 | "print()\n", 1728 | "print('x = ', x)\n", 1729 | "\n", 1730 | "# We print y\n", 1731 | "print()\n", 1732 | "print('y = ', y)\n", 1733 | "\n", 1734 | "# We use set operations to compare x and y:\n", 1735 | "print()\n", 1736 | "print('The elements that are both in x and y:', np.intersect1d(x,y))\n", 1737 | "print('The elements that are in x that are not in y:', np.setdiff1d(x,y))\n", 1738 | "print('All the elements of x and y:',np.union1d(x,y))" 1739 | ] 1740 | }, 1741 | { 1742 | "cell_type": "code", 1743 | "execution_count": 43, 1744 | "metadata": {}, 1745 | "outputs": [ 1746 | { 1747 | "name": "stdout", 1748 | "output_type": "stream", 1749 | "text": [ 1750 | "\n", 1751 | "Original x = [ 5 9 7 9 1 10 6 2 8 5]\n", 1752 | "\n", 1753 | "Sorted x (out of place): [ 1 2 5 5 6 7 8 9 9 10]\n", 1754 | "\n", 1755 | "x after sorting: [ 5 9 7 9 1 10 6 2 8 5]\n" 1756 | ] 1757 | } 1758 | ], 1759 | "source": [ 1760 | "# We create an unsorted rank 1 ndarray\n", 1761 | "x = np.random.randint(1,11,size=(10,))\n", 1762 | "\n", 1763 | "# We print x\n", 1764 | "print()\n", 1765 | "print('Original x = ', x)\n", 1766 | "\n", 1767 | "# We sort x and print the sorted array using sort as a function.\n", 1768 | "print()\n", 1769 | "print('Sorted x (out of place):', np.sort(x))\n", 1770 | "\n", 1771 | "# When we sort out of place the original array remains intact. To see this we print x again\n", 1772 | "print()\n", 1773 | "print('x after sorting:', x)" 1774 | ] 1775 | }, 1776 | { 1777 | "cell_type": "code", 1778 | "execution_count": 44, 1779 | "metadata": {}, 1780 | "outputs": [ 1781 | { 1782 | "name": "stdout", 1783 | "output_type": "stream", 1784 | "text": [ 1785 | "\n", 1786 | "Original x = [ 4 10 2 5 7 4 3 8 6 6]\n", 1787 | "\n", 1788 | "x after sorting: [ 2 3 4 4 5 6 6 7 8 10]\n" 1789 | ] 1790 | } 1791 | ], 1792 | "source": [ 1793 | "# We create an unsorted rank 1 ndarray\n", 1794 | "x = np.random.randint(1,11,size=(10,))\n", 1795 | "\n", 1796 | "# We print x\n", 1797 | "print()\n", 1798 | "print('Original x = ', x)\n", 1799 | "\n", 1800 | "# We sort x and print the sorted array using sort as a method.\n", 1801 | "x.sort()\n", 1802 | "\n", 1803 | "# When we sort in place the original array is changed to the sorted array. To see this we print x again\n", 1804 | "print()\n", 1805 | "print('x after sorting:', x)" 1806 | ] 1807 | }, 1808 | { 1809 | "cell_type": "code", 1810 | "execution_count": 45, 1811 | "metadata": {}, 1812 | "outputs": [ 1813 | { 1814 | "name": "stdout", 1815 | "output_type": "stream", 1816 | "text": [ 1817 | "\n", 1818 | "Original X = \n", 1819 | " [[ 3 6 3 2 5]\n", 1820 | " [ 6 5 3 9 6]\n", 1821 | " [10 7 9 5 2]\n", 1822 | " [10 10 1 6 9]\n", 1823 | " [ 9 5 7 4 6]]\n", 1824 | "\n", 1825 | "\n", 1826 | "X with sorted columns :\n", 1827 | " [[ 3 5 1 2 2]\n", 1828 | " [ 6 5 3 4 5]\n", 1829 | " [ 9 6 3 5 6]\n", 1830 | " [10 7 7 6 6]\n", 1831 | " [10 10 9 9 9]]\n", 1832 | "\n", 1833 | "X with sorted rows :\n", 1834 | " [[ 2 3 3 5 6]\n", 1835 | " [ 3 5 6 6 9]\n", 1836 | " [ 2 5 7 9 10]\n", 1837 | " [ 1 6 9 10 10]\n", 1838 | " [ 4 5 6 7 9]]\n" 1839 | ] 1840 | } 1841 | ], 1842 | "source": [ 1843 | "# We create an unsorted rank 2 ndarray\n", 1844 | "X = np.random.randint(1,11,size=(5,5))\n", 1845 | "\n", 1846 | "# We print X\n", 1847 | "print()\n", 1848 | "print('Original X = \\n', X)\n", 1849 | "print()\n", 1850 | "\n", 1851 | "# We sort the columns of X and print the sorted array\n", 1852 | "print()\n", 1853 | "print('X with sorted columns :\\n', np.sort(X, axis = 0))\n", 1854 | "\n", 1855 | "# We sort the rows of X and print the sorted array\n", 1856 | "print()\n", 1857 | "print('X with sorted rows :\\n', np.sort(X, axis = 1))" 1858 | ] 1859 | }, 1860 | { 1861 | "cell_type": "code", 1862 | "execution_count": 46, 1863 | "metadata": {}, 1864 | "outputs": [ 1865 | { 1866 | "name": "stdout", 1867 | "output_type": "stream", 1868 | "text": [ 1869 | "\n", 1870 | "x = [1 2 3 4]\n", 1871 | "\n", 1872 | "y = [5.5 6.5 7.5 8.5]\n", 1873 | "\n", 1874 | "x + y = [ 6.5 8.5 10.5 12.5]\n", 1875 | "add(x,y) = [ 6.5 8.5 10.5 12.5]\n", 1876 | "\n", 1877 | "x - y = [-4.5 -4.5 -4.5 -4.5]\n", 1878 | "subtract(x,y) = [-4.5 -4.5 -4.5 -4.5]\n", 1879 | "\n", 1880 | "x * y = [ 5.5 13. 22.5 34. ]\n", 1881 | "multiply(x,y) = [ 5.5 13. 22.5 34. ]\n", 1882 | "\n", 1883 | "x / y = [0.18181818 0.30769231 0.4 0.47058824]\n", 1884 | "divide(x,y) = [0.18181818 0.30769231 0.4 0.47058824]\n" 1885 | ] 1886 | } 1887 | ], 1888 | "source": [ 1889 | "# We create two rank 1 ndarrays\n", 1890 | "x = np.array([1,2,3,4])\n", 1891 | "y = np.array([5.5,6.5,7.5,8.5])\n", 1892 | "\n", 1893 | "# We print x\n", 1894 | "print()\n", 1895 | "print('x = ', x)\n", 1896 | "\n", 1897 | "# We print y\n", 1898 | "print()\n", 1899 | "print('y = ', y)\n", 1900 | "print()\n", 1901 | "\n", 1902 | "# We perfrom basic element-wise operations using arithmetic symbols and functions\n", 1903 | "print('x + y = ', x + y)\n", 1904 | "print('add(x,y) = ', np.add(x,y))\n", 1905 | "print()\n", 1906 | "print('x - y = ', x - y)\n", 1907 | "print('subtract(x,y) = ', np.subtract(x,y))\n", 1908 | "print()\n", 1909 | "print('x * y = ', x * y)\n", 1910 | "print('multiply(x,y) = ', np.multiply(x,y))\n", 1911 | "print()\n", 1912 | "print('x / y = ', x / y)\n", 1913 | "print('divide(x,y) = ', np.divide(x,y))" 1914 | ] 1915 | }, 1916 | { 1917 | "cell_type": "code", 1918 | "execution_count": 47, 1919 | "metadata": {}, 1920 | "outputs": [ 1921 | { 1922 | "name": "stdout", 1923 | "output_type": "stream", 1924 | "text": [ 1925 | "\n", 1926 | "X = \n", 1927 | " [[1 2]\n", 1928 | " [3 4]]\n", 1929 | "\n", 1930 | "Y = \n", 1931 | " [[5.5 6.5]\n", 1932 | " [7.5 8.5]]\n", 1933 | "\n", 1934 | "X + Y = \n", 1935 | " [[ 6.5 8.5]\n", 1936 | " [10.5 12.5]]\n", 1937 | "\n", 1938 | "add(X,Y) = \n", 1939 | " [[ 6.5 8.5]\n", 1940 | " [10.5 12.5]]\n", 1941 | "\n", 1942 | "X - Y = \n", 1943 | " [[-4.5 -4.5]\n", 1944 | " [-4.5 -4.5]]\n", 1945 | "\n", 1946 | "subtract(X,Y) = \n", 1947 | " [[-4.5 -4.5]\n", 1948 | " [-4.5 -4.5]]\n", 1949 | "\n", 1950 | "X * Y = \n", 1951 | " [[ 5.5 13. ]\n", 1952 | " [22.5 34. ]]\n", 1953 | "\n", 1954 | "multiply(X,Y) = \n", 1955 | " [[ 5.5 13. ]\n", 1956 | " [22.5 34. ]]\n", 1957 | "\n", 1958 | "X / Y = \n", 1959 | " [[0.18181818 0.30769231]\n", 1960 | " [0.4 0.47058824]]\n", 1961 | "\n", 1962 | "divide(X,Y) = \n", 1963 | " [[0.18181818 0.30769231]\n", 1964 | " [0.4 0.47058824]]\n" 1965 | ] 1966 | } 1967 | ], 1968 | "source": [ 1969 | "# We create two rank 2 ndarrays\n", 1970 | "X = np.array([1,2,3,4]).reshape(2,2)\n", 1971 | "Y = np.array([5.5,6.5,7.5,8.5]).reshape(2,2)\n", 1972 | "\n", 1973 | "# We print X\n", 1974 | "print()\n", 1975 | "print('X = \\n', X)\n", 1976 | "\n", 1977 | "# We print Y\n", 1978 | "print()\n", 1979 | "print('Y = \\n', Y)\n", 1980 | "print()\n", 1981 | "\n", 1982 | "# We perform basic element-wise operations using arithmetic symbols and functions\n", 1983 | "print('X + Y = \\n', X + Y)\n", 1984 | "print()\n", 1985 | "print('add(X,Y) = \\n', np.add(X,Y))\n", 1986 | "print()\n", 1987 | "print('X - Y = \\n', X - Y)\n", 1988 | "print()\n", 1989 | "print('subtract(X,Y) = \\n', np.subtract(X,Y))\n", 1990 | "print()\n", 1991 | "print('X * Y = \\n', X * Y)\n", 1992 | "print()\n", 1993 | "print('multiply(X,Y) = \\n', np.multiply(X,Y))\n", 1994 | "print()\n", 1995 | "print('X / Y = \\n', X / Y)\n", 1996 | "print()\n", 1997 | "print('divide(X,Y) = \\n', np.divide(X,Y))" 1998 | ] 1999 | }, 2000 | { 2001 | "cell_type": "code", 2002 | "execution_count": 48, 2003 | "metadata": {}, 2004 | "outputs": [ 2005 | { 2006 | "name": "stdout", 2007 | "output_type": "stream", 2008 | "text": [ 2009 | "\n", 2010 | "x = [1 2 3 4]\n", 2011 | "\n", 2012 | "EXP(x) = [ 2.71828183 7.3890561 20.08553692 54.59815003]\n", 2013 | "\n", 2014 | "SQRT(x) = [1. 1.41421356 1.73205081 2. ]\n", 2015 | "\n", 2016 | "POW(x,2) = [ 1 4 9 16]\n" 2017 | ] 2018 | } 2019 | ], 2020 | "source": [ 2021 | "# We create a rank 1 ndarray\n", 2022 | "x = np.array([1,2,3,4])\n", 2023 | "\n", 2024 | "# We print x\n", 2025 | "print()\n", 2026 | "print('x = ', x)\n", 2027 | "\n", 2028 | "# We apply different mathematical functions to all elements of x\n", 2029 | "print()\n", 2030 | "print('EXP(x) =', np.exp(x))\n", 2031 | "print()\n", 2032 | "print('SQRT(x) =',np.sqrt(x))\n", 2033 | "print()\n", 2034 | "print('POW(x,2) =',np.power(x,2)) # We raise all elements to the power of 2" 2035 | ] 2036 | }, 2037 | { 2038 | "cell_type": "code", 2039 | "execution_count": 49, 2040 | "metadata": {}, 2041 | "outputs": [ 2042 | { 2043 | "name": "stdout", 2044 | "output_type": "stream", 2045 | "text": [ 2046 | "\n", 2047 | "X = \n", 2048 | " [[1 2]\n", 2049 | " [3 4]]\n", 2050 | "\n", 2051 | "Average of all elements in X: 2.5\n", 2052 | "Average of all elements in the columns of X: [2. 3.]\n", 2053 | "Average of all elements in the rows of X: [1.5 3.5]\n", 2054 | "\n", 2055 | "Sum of all elements in X: 10\n", 2056 | "Sum of all elements in the columns of X: [4 6]\n", 2057 | "Sum of all elements in the rows of X: [3 7]\n", 2058 | "\n", 2059 | "Standard Deviation of all elements in X: 1.118033988749895\n", 2060 | "Standard Deviation of all elements in the columns of X: [1. 1.]\n", 2061 | "Standard Deviation of all elements in the rows of X: [0.5 0.5]\n", 2062 | "\n", 2063 | "Median of all elements in X: 2.5\n", 2064 | "Median of all elements in the columns of X: [2. 3.]\n", 2065 | "Median of all elements in the rows of X: [1.5 3.5]\n", 2066 | "\n", 2067 | "Maximum value of all elements in X: 4\n", 2068 | "Maximum value of all elements in the columns of X: [3 4]\n", 2069 | "Maximum value of all elements in the rows of X: [2 4]\n", 2070 | "\n", 2071 | "Minimum value of all elements in X: 1\n", 2072 | "Minimum value of all elements in the columns of X: [1 2]\n", 2073 | "Minimum value of all elements in the rows of X: [1 3]\n" 2074 | ] 2075 | } 2076 | ], 2077 | "source": [ 2078 | "# We create a 2 x 2 ndarray\n", 2079 | "X = np.array([[1,2], [3,4]])\n", 2080 | "\n", 2081 | "# We print x\n", 2082 | "print()\n", 2083 | "print('X = \\n', X)\n", 2084 | "print()\n", 2085 | "\n", 2086 | "print('Average of all elements in X:', X.mean())\n", 2087 | "print('Average of all elements in the columns of X:', X.mean(axis=0))\n", 2088 | "print('Average of all elements in the rows of X:', X.mean(axis=1))\n", 2089 | "print()\n", 2090 | "print('Sum of all elements in X:', X.sum())\n", 2091 | "print('Sum of all elements in the columns of X:', X.sum(axis=0))\n", 2092 | "print('Sum of all elements in the rows of X:', X.sum(axis=1))\n", 2093 | "print()\n", 2094 | "print('Standard Deviation of all elements in X:', X.std())\n", 2095 | "print('Standard Deviation of all elements in the columns of X:', X.std(axis=0))\n", 2096 | "print('Standard Deviation of all elements in the rows of X:', X.std(axis=1))\n", 2097 | "print()\n", 2098 | "print('Median of all elements in X:', np.median(X))\n", 2099 | "print('Median of all elements in the columns of X:', np.median(X,axis=0))\n", 2100 | "print('Median of all elements in the rows of X:', np.median(X,axis=1))\n", 2101 | "print()\n", 2102 | "print('Maximum value of all elements in X:', X.max())\n", 2103 | "print('Maximum value of all elements in the columns of X:', X.max(axis=0))\n", 2104 | "print('Maximum value of all elements in the rows of X:', X.max(axis=1))\n", 2105 | "print()\n", 2106 | "print('Minimum value of all elements in X:', X.min())\n", 2107 | "print('Minimum value of all elements in the columns of X:', X.min(axis=0))\n", 2108 | "print('Minimum value of all elements in the rows of X:', X.min(axis=1))" 2109 | ] 2110 | }, 2111 | { 2112 | "cell_type": "code", 2113 | "execution_count": 50, 2114 | "metadata": {}, 2115 | "outputs": [ 2116 | { 2117 | "name": "stdout", 2118 | "output_type": "stream", 2119 | "text": [ 2120 | "\n", 2121 | "X = \n", 2122 | " [[1 2]\n", 2123 | " [3 4]]\n", 2124 | "\n", 2125 | "3 * X = \n", 2126 | " [[ 3 6]\n", 2127 | " [ 9 12]]\n", 2128 | "\n", 2129 | "3 + X = \n", 2130 | " [[4 5]\n", 2131 | " [6 7]]\n", 2132 | "\n", 2133 | "X - 3 = \n", 2134 | " [[-2 -1]\n", 2135 | " [ 0 1]]\n", 2136 | "\n", 2137 | "X / 3 = \n", 2138 | " [[0.33333333 0.66666667]\n", 2139 | " [1. 1.33333333]]\n" 2140 | ] 2141 | } 2142 | ], 2143 | "source": [ 2144 | "# We create a 2 x 2 ndarray\n", 2145 | "X = np.array([[1,2], [3,4]])\n", 2146 | "\n", 2147 | "# We print x\n", 2148 | "print()\n", 2149 | "print('X = \\n', X)\n", 2150 | "print()\n", 2151 | "\n", 2152 | "print('3 * X = \\n', 3 * X)\n", 2153 | "print()\n", 2154 | "print('3 + X = \\n', 3 + X)\n", 2155 | "print()\n", 2156 | "print('X - 3 = \\n', X - 3)\n", 2157 | "print()\n", 2158 | "print('X / 3 = \\n', X / 3)" 2159 | ] 2160 | }, 2161 | { 2162 | "cell_type": "code", 2163 | "execution_count": 51, 2164 | "metadata": {}, 2165 | "outputs": [ 2166 | { 2167 | "name": "stdout", 2168 | "output_type": "stream", 2169 | "text": [ 2170 | "\n", 2171 | "x = [1 2 3]\n", 2172 | "\n", 2173 | "\n", 2174 | "Y = \n", 2175 | " [[1 2 3]\n", 2176 | " [4 5 6]\n", 2177 | " [7 8 9]]\n", 2178 | "\n", 2179 | "\n", 2180 | "Z = \n", 2181 | " [[1]\n", 2182 | " [2]\n", 2183 | " [3]]\n", 2184 | "\n", 2185 | "x + Y = \n", 2186 | " [[ 2 4 6]\n", 2187 | " [ 5 7 9]\n", 2188 | " [ 8 10 12]]\n", 2189 | "\n", 2190 | "Z + Y = \n", 2191 | " [[ 2 3 4]\n", 2192 | " [ 6 7 8]\n", 2193 | " [10 11 12]]\n" 2194 | ] 2195 | } 2196 | ], 2197 | "source": [ 2198 | "# We create a rank 1 ndarray\n", 2199 | "x = np.array([1,2,3])\n", 2200 | "\n", 2201 | "# We create a 3 x 3 ndarray\n", 2202 | "Y = np.array([[1,2,3],[4,5,6],[7,8,9]])\n", 2203 | "\n", 2204 | "# We create a 3 x 1 ndarray\n", 2205 | "Z = np.array([1,2,3]).reshape(3,1)\n", 2206 | "\n", 2207 | "# We print x\n", 2208 | "print()\n", 2209 | "print('x = ', x)\n", 2210 | "print()\n", 2211 | "\n", 2212 | "# We print Y\n", 2213 | "print()\n", 2214 | "print('Y = \\n', Y)\n", 2215 | "print()\n", 2216 | "\n", 2217 | "# We print Z\n", 2218 | "print()\n", 2219 | "print('Z = \\n', Z)\n", 2220 | "print()\n", 2221 | "\n", 2222 | "print('x + Y = \\n', x + Y)\n", 2223 | "print()\n", 2224 | "print('Z + Y = \\n',Z + Y)" 2225 | ] 2226 | }, 2227 | { 2228 | "cell_type": "code", 2229 | "execution_count": null, 2230 | "metadata": {}, 2231 | "outputs": [], 2232 | "source": [] 2233 | } 2234 | ], 2235 | "metadata": { 2236 | "kernelspec": { 2237 | "display_name": "Python 3", 2238 | "language": "python", 2239 | "name": "python3" 2240 | }, 2241 | "language_info": { 2242 | "codemirror_mode": { 2243 | "name": "ipython", 2244 | "version": 3 2245 | }, 2246 | "file_extension": ".py", 2247 | "mimetype": "text/x-python", 2248 | "name": "python", 2249 | "nbconvert_exporter": "python", 2250 | "pygments_lexer": "ipython3", 2251 | "version": "3.7.4" 2252 | } 2253 | }, 2254 | "nbformat": 4, 2255 | "nbformat_minor": 2 2256 | } 2257 | -------------------------------------------------------------------------------- /Python practice code/US bikeshare data practice questions.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [] 9 | } 10 | ], 11 | "metadata": { 12 | "kernelspec": { 13 | "display_name": "Python 3", 14 | "language": "python", 15 | "name": "python3" 16 | }, 17 | "language_info": { 18 | "codemirror_mode": { 19 | "name": "ipython", 20 | "version": 3 21 | }, 22 | "file_extension": ".py", 23 | "mimetype": "text/x-python", 24 | "name": "python", 25 | "nbconvert_exporter": "python", 26 | "pygments_lexer": "ipython3", 27 | "version": "3.7.4" 28 | } 29 | }, 30 | "nbformat": 4, 31 | "nbformat_minor": 2 32 | } 33 | -------------------------------------------------------------------------------- /Python practice code/my_array.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sauravraghuvanshi/Udacity-programming-for-Data-Science-With-Python-Nanodegree/7d0fd7f969b30ce172f118d372590388363c4088/Python practice code/my_array.npy -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Udacity-programming-for-Data-Science-using-Python-Nanodegree 2 | 3 | 4 | # Created by Saurav Raghuvanshi 5 | 6 | This repository contains projects and practice set for Udacity Programming For Data Science Using Python Nanodegree. 7 | 8 | ## Project 1 9 | 10 | ### Overview 11 | 12 | This project consisted in the exploration of a provided database movie rentals in which the student had to run SQL queries and build visualizations to showcase the output of the student's queries. 13 | 14 | For the presentation component, the student had to create four slides, and each should have (a) a question of interest, (b) a supporting SQL query needed to answer the question, (c) a supporting visualization created using the final data of the SQL queries that answer the questions of interest, and (d) a small summary on each slide. 15 | 16 | ### Project Submission 17 | 18 | [Check My Project Submission](https://github.com/sauravraghuvanshi/Udacity-programming-for-Data-Science-With-Python-Nanodegree/blob/master/Project%201/Project%201%20for%20Submission/Saurav%20Raghuvanshi%20SQL%20submission.pdf) 19 | 20 | ### Question Sets 21 | 22 | A set of questions have also been provided by Udacity so that we were free to consider and include them in our Project Submission. 23 | [Check this out](https://github.com/sauravraghuvanshi/Udacity-programming-for-Data-Science-using-Python-Nanodegree/tree/master/Project%201/Project%20Question) 24 | 25 | ## Project 2 26 | 27 | ### Overview 28 | 29 | In this project, the student had to make use of Python to explore data related to bike share systems for three major cities in the United States — Chicago, New York City, and Washington. The student had to write code to (a) import the data and answer interesting questions about it by computing descriptive statistics, and (b) write a script that takes in raw input to create an interactive experience in the terminal to present these statistics. 30 | 31 | ### Project Submission 32 | 33 | The developed CLI program allows the user to explore an US bikeshare system database and retrieve statistics information from the database. The user is able filter the information by city, month and weekday, in order to visualize statistics information related to a specific subset of data. The user is also able to chose to view raw data and to sort this data by columns, in ascending or descending order. 34 | 35 | [Check My Project Submission](https://github.com/sauravraghuvanshi/Udacity-programming-for-Data-Science-using-Python-Nanodegree/tree/master/Project-2). 36 | ### Python Learning In The Course 37 | 38 | Check the link for my learning material. 39 | [Check this out](https://github.com/sauravraghuvanshi/Udacity-programming-for-Data-Science-using-Python-Nanodegree/tree/master/Python%20practice%20code) 40 | 41 | #### Files Used 42 | 43 | The required files for running this program are: 44 | 45 | * washington.csv 46 | * new_york_city.csv 47 | * chicago.csv 48 | 49 | #### Requirements 50 | This program was written in Python (version 3.7.1) and relies on the following libraries: 51 | 52 | * pandas==0.23.4 53 | * numpy==1.15.4 54 | 55 | ## Project 3 56 | 57 | This project consisted in using Git and GitHub with a simulated workflow to refactor Project 2. 58 | 59 | ### Project Submission 60 | 61 | The Project Submission consisted in the filling of a template with all the Git commands used to perform the requested tasks. 62 | 63 | [Check My Project Submission](https://github.com/sauravraghuvanshi/Udacity-programming-for-Data-Science-With-Python-Nanodegree/blob/master/Project-3/Git%20Commands%20Documentation.pdf). 64 | 65 | # My Certificate of Completion 66 | 67 | --------------------------------------------------------------------------------