├── Fall20 ├── Guide.md ├── README.md ├── figures │ ├── ChangeTheme.png │ ├── HTML_Browser.png │ ├── HTML_Explorer.png │ ├── Maintxt.png │ ├── Teaching.Codes New Version.png │ ├── Teaching.Codes Uninstall.png │ ├── Teaching.Codes Version 1212JB.png │ ├── commit_and_push_failed1.png │ ├── commit_and_push_failed2.png │ ├── connection.PNG │ └── could not open.PNG ├── week01 │ ├── README.md │ └── Solutions.md ├── week02 │ ├── README.md │ └── Solutions.md ├── week03 │ ├── README.md │ └── Solutions.md ├── week04 │ ├── README.md │ └── Solutions.md ├── week05 │ ├── README.md │ └── Solutions.md ├── week06 │ ├── README.md │ └── Solutions.md ├── week07 │ ├── README.md │ └── Solutions.md ├── week08 │ ├── README.md │ └── Solutions.md ├── week09 │ ├── README.md │ └── Solutions.md └── week10 │ ├── README.md │ └── Solutions.md ├── FrequentlyAskedQuestions (FAQ).md ├── InstallationGuide.md ├── InstallationGuide.pdf ├── PS └── README.md ├── README.md ├── Spring21 ├── figures │ ├── 1616341138563.png │ ├── 1616342184949.png │ ├── 1616342517499.png │ ├── ChangeTheme.png │ ├── HTML_Browser.png │ ├── HTML_Explorer.png │ ├── Maintxt.png │ ├── PythonInstaller.png │ ├── Teaching.Codes New Version.png │ ├── Teaching.Codes Uninstall.png │ ├── Teaching.Codes Version 1212JB.png │ ├── commit_and_push_failed1.png │ ├── commit_and_push_failed2.png │ ├── connection.PNG │ ├── could not open.PNG │ ├── project-guide │ │ ├── 1618485979513.png │ │ ├── 1618486104949.png │ │ ├── 1618486398394.png │ │ ├── 1618486497781.png │ │ ├── 1618486752521.png │ │ ├── 1618486890025.png │ │ ├── 1618487070207.png │ │ ├── 1618487098652.png │ │ ├── 1618487165943.png │ │ ├── 1618487273664.png │ │ ├── 1618487440503.png │ │ └── 1618487934948.png │ ├── python-customize.png │ ├── python-final.png │ ├── python-optional.png │ └── team-fixed.png ├── week01 │ ├── README.md │ └── figures │ │ └── moodle.png ├── week02 │ ├── README.md │ └── Solutions.md ├── week03 │ ├── README.md │ └── Solutions.md ├── week04 │ ├── README.md │ └── Solutions.md ├── week05 │ ├── README.md │ └── Solutions.md ├── week06 │ ├── README.md │ └── Solutions.md ├── week07 │ ├── README.md │ └── Solutions.md ├── week08 │ ├── README.md │ └── Solutions.md ├── week09 │ ├── README.md │ └── Solutions.md ├── week10 │ ├── README.md │ └── Solutions.md ├── week11 │ ├── README.md │ ├── Solutions.md │ └── data │ │ └── paragraph.txt └── week12 │ ├── Exploring 'Game of Thrones' Battles.ipynb │ ├── External Libraries.md │ ├── README.md │ ├── Solutions.md │ ├── Widely used Python libraries Numpy and Pandas.ipynb │ └── figures │ ├── 1623750783722.png │ ├── 1623751368006.png │ └── 1623752067689.png ├── Teaching.CodesProjectGuide.md ├── Teaching.CodesProjectGuide.pdf ├── TeachingCodesGuide.md ├── figures ├── 1616341138563.png ├── 1616342184949.png ├── 1616342517499.png ├── ChangeTheme.png ├── HTML_Browser.png ├── HTML_Explorer.png ├── Maintxt.png ├── TC.png ├── Teaching.Codes New Version.png ├── Teaching.Codes Uninstall.png ├── Teaching.Codes Version 1212JB.png ├── commit_and_push_failed1.png ├── commit_and_push_failed2.png ├── connection.PNG ├── correspondence.png ├── could not open.PNG ├── project-guide │ ├── 1618485979513.png │ ├── 1618486104949.png │ ├── 1618486398394.png │ ├── 1618486497781.png │ ├── 1618486752521.png │ ├── 1618486890025.png │ ├── 1618487070207.png │ ├── 1618487098652.png │ ├── 1618487165943.png │ ├── 1618487273664.png │ ├── 1618487440503.png │ └── 1618487934948.png ├── python-customize.png ├── python-final.png └── python-optional.png ├── spring2022 ├── ReadME └── python2022spring22 │ ├── week10 │ ├── README.md │ ├── ps7 chapter list week10.pptx │ └── solutions.md │ ├── week12 │ ├── README.md │ ├── Solutions.md │ └── ps8 chapter dict week12.pptx │ ├── week4 │ ├── Solutions.md │ ├── lab3.pdf │ └── questions.md │ ├── week6 │ ├── README.md │ ├── Solutions.md │ └── chapter4.pdf │ ├── week7 │ ├── README.md │ ├── Solutions.md │ └── cmpe150-chp4-p2.pptx │ └── week9 │ ├── README.md │ ├── Solutions.md │ └── string.pptx ├── week01 ├── README.md └── Solutions.md ├── week02 ├── README.md ├── Solutions.md └── q9.png ├── week03 ├── README.md └── Solutions.md ├── week04 ├── README.md └── Solutions.md ├── week05 ├── README.md └── Solutions.md ├── week06 ├── README.md └── Solution.md ├── week07 ├── README.md └── Solutions.md ├── week08 ├── README.md └── Solutions.md ├── week09 ├── README.md └── Solutions.md └── week10 ├── README.md └── Solutions.md /Fall20/README.md: -------------------------------------------------------------------------------- 1 | # CmpE150 - Fall 2020 2 | 3 | Bogazici University CmpE 150 Introduction to Computing (Python programming language) Notes 4 | 5 | **E-mails:** 6 | 7 | - [burak.suyunu@boun.edu.tr](mailto:burak.suyunu@boun.edu.tr) 8 | - [gokce.uludogan@boun.edu.tr](mailto:gokce.uludogan@boun.edu.tr) 9 | - [zeynep.yirmibesoglu@boun.edu.tr](mailto:zeynep.yirmibesoglu@boun.edu.tr) 10 | 11 | **Additional Materials** 12 | 13 | - http://www.pythontutor.com/visualize.html 14 | 15 | 16 | ### [Week 1](week01/) 17 | 18 | - Variables 19 | - Expressions 20 | - Statements 21 | 22 | ### [Week 2](week02/) 23 | 24 | - Conditional Execution 25 | 26 | ### [Week 3](week03/) 27 | 28 | - Loops and Iterations 29 | 30 | ### [Week 4](week04/) 31 | 32 | - Nested Loops 33 | 34 | ### [Week 5](week05/) 35 | 36 | - Functions 37 | 38 | ### [Week 6](week06/) 39 | 40 | - Lists and Tuples 41 | 42 | ### [Week 7](week07/) 43 | 44 | - Lists and Tuples 45 | 46 | ### [Week 8](week08/) 47 | 48 | - Strings 49 | 50 | ### [Week 9](week09/) 51 | 52 | - Strings and Files 53 | 54 | ### [Week 10](week10/) 55 | 56 | - Dictionaries and Sets 57 | -------------------------------------------------------------------------------- /Fall20/figures/ChangeTheme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Fall20/figures/ChangeTheme.png -------------------------------------------------------------------------------- /Fall20/figures/HTML_Browser.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Fall20/figures/HTML_Browser.png -------------------------------------------------------------------------------- /Fall20/figures/HTML_Explorer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Fall20/figures/HTML_Explorer.png -------------------------------------------------------------------------------- /Fall20/figures/Maintxt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Fall20/figures/Maintxt.png -------------------------------------------------------------------------------- /Fall20/figures/Teaching.Codes New Version.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Fall20/figures/Teaching.Codes New Version.png -------------------------------------------------------------------------------- /Fall20/figures/Teaching.Codes Uninstall.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Fall20/figures/Teaching.Codes Uninstall.png -------------------------------------------------------------------------------- /Fall20/figures/Teaching.Codes Version 1212JB.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Fall20/figures/Teaching.Codes Version 1212JB.png -------------------------------------------------------------------------------- /Fall20/figures/commit_and_push_failed1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Fall20/figures/commit_and_push_failed1.png -------------------------------------------------------------------------------- /Fall20/figures/commit_and_push_failed2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Fall20/figures/commit_and_push_failed2.png -------------------------------------------------------------------------------- /Fall20/figures/connection.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Fall20/figures/connection.PNG -------------------------------------------------------------------------------- /Fall20/figures/could not open.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Fall20/figures/could not open.PNG -------------------------------------------------------------------------------- /Fall20/week01/README.md: -------------------------------------------------------------------------------- 1 | # Variables / Expressions / Statements 2 | 3 | ## Question 1 4 | 5 | Write a program that takes 3 integers from the user and then prints the sum, mean and multiple of the numbers. 6 | 7 | | Input | Output | 8 | | -------- | ---------------- | 9 | | 13 27 14 | 54 18.00 4914| 10 | 11 |
12 | 13 | ## Question 2 14 | 15 | Using the formula below of compound interest, take the **principal amount (A)**, **interest rate (i)** (per month) and **duration (n)** (months) and print the final amount. 16 | 17 | 18 | 19 | 20 | | Input | Output | 21 | | --------- | ------- | 22 | | 1000 12 5 | 1762.34 | 23 | | 500 12 5 | 881.17 | 24 | 25 |
26 | 27 | ## Question 3 28 | 29 | Write a program which takes radius of a circle from user and calculate the perimeter and surface of the defined circle. 30 | 31 | **You can get the value of pi from math module (from math import pi)** 32 | 33 | | Input | Output | 34 | | ----- | --------------------------- | 35 | | 4 | 25.1327412287 50.2654824574 | 36 | | 8 | 50.2654824574 201.06192983 | 37 | 38 |
39 | 40 | ## Question 4 41 | 42 | Write a program that takes a positive number from user and calculate the sum from 0 to that positive number. 43 | 44 | **You do not need to use any loops or developed coding** 45 | 46 | | Input | Output | 47 | | ----- | ------ | 48 | | 10 | 55 | 49 | | 5 | 15 | 50 | 51 |
52 | 53 | ## Question 5 54 | 55 | Write a program which takes the values in **Ohm** of two parallel resistances and the generator's voltage in **Volt** respectively and print the currents that passes by each resistance. 56 | 57 | 58 | 59 | 60 | | Input | Output | 61 | | ------ | ------ | 62 | | 2 8 40 | 20 5 | 63 | | 5 5 10 | 2 2 | 64 | 65 |
66 | 67 | ## Question 6 68 | 69 | Write a program which replaces the values of two integers. 70 | 71 | | Input | Output | 72 | | ----- | ------ | 73 | | 5 10 | 10 5 | 74 | 75 |
76 | 77 | ## Question 7 78 | 79 | Write a program which takes a character and prints its ASCII value. 80 | 81 | | Input | Output | 82 | | ----- | ------ | 83 | | A | 65 | 84 | | E | 69 | 85 | 86 |
87 | 88 | ## Question 8 89 | 90 | Write a program which takes a lowercase letter as input and print the uppercase version of the given letter. 91 | 92 | | Input | Output | 93 | | ----- | ------ | 94 | | a | A | 95 | | b | B | 96 | | B | B | 97 | 98 |
99 | 100 | ## Question 9 101 | 102 | Write a program that calculates the volume of a sphere by taking its radius from user. 103 | 104 | | Input | Output | 105 | | ----- | ------------- | 106 | | 3 | 113.097335529 | 107 | | 6 | 904.778684234 | 108 | 109 |
110 | 111 | ## Question 10 112 | 113 | Write a program that calculates the amount of seconds in a given period of years, months, days, hours and minutes respectively. 114 | 115 | * 1 year = 365 days 116 | * 1 month = 30 days 117 | 118 | | Input | Output | 119 | | --------- | --------- | 120 | | 5 2 4 3 0 | 163220400 | 121 | | 1 1 1 1 1 | 34218060 | 122 | 123 |
124 | 125 | ## Question 11 126 | 127 | Write a program that takes 3 integers from the user and then prints the sum of odd numbers. 128 | 129 | | INPUT | OUTPUT | 130 | | ------ | ------ | 131 | | 3 4 5 | 8 | 132 | | 2 2 4 | 0 | 133 | | 1 9 15 | 25 | -------------------------------------------------------------------------------- /Fall20/week01/Solutions.md: -------------------------------------------------------------------------------- 1 | # Variables / Expressions / Statements 2 | 3 | ## Q1 4 | 5 | ```python 6 | num1 = int(input("Please enter first number: ")) 7 | num2 = int(input("Please enter second number: ")) 8 | num3 = int(input("Please enter third number: ")) 9 | 10 | print("Sum is: " + str(num1+num2+num3)) 11 | print("Mean is: %.2f" % ((num1+num2+num3)/3)) 12 | print("Multiple is: %d" % (num1*num2*num3)) 13 | ``` 14 | 15 |
16 | 17 | ## Q2 18 | ```python 19 | A = int(input("Plese enter the principal amount: ")) 20 | i = int(input("Plese enter the interest rate per month: ")) 21 | n = int(input("Plese enter the duration in months: ")) 22 | 23 | print("Final amount is: " + str(A*(1+i/100)**n)) 24 | ``` 25 | 26 |
27 | 28 | ## Q3 29 | ```python 30 | from math import pi 31 | 32 | r = int(input("Plese enter a radius: ")) 33 | 34 | print("The perimeter of the circle with given radius is: " + str(2*pi*r)) 35 | print("The surface of the circle with given radius is: " + str(pi*r**2)) 36 | ``` 37 | 38 |
39 | 40 | ## Q4 41 | ```python 42 | n = int(input("Plese enter a number: ")) 43 | 44 | print("The sum till the given number is: " + str((n*(n+1))/2)) 45 | 46 | ``` 47 | 48 |
49 | 50 | ## Q5 51 | ```python 52 | r1 = int(input("Plese enter the value of first resistance in OHMs: ")) 53 | r2 = int(input("Plese enter the value of first resistance in OHMs: ")) 54 | v = int(input("Plese enter the value of tension voltage in volts: ")) 55 | 56 | print("The current in R1 is: " + str(v/r1)) 57 | print("The current in R2 is: " + str(v/r2)) 58 | ``` 59 | 60 |
61 | 62 | ## Q6 63 | ```python 64 | a = int(input("Plese enter the first number: ")) 65 | b = int(input("Plese enter the second number: ")) 66 | 67 | # Version 1 (Classic Swap): 68 | temp = a 69 | a = b 70 | b = temp 71 | 72 | # Version 2 (Without using extra variable): 73 | # a = a + b 74 | # b = a - b 75 | # a = a - b 76 | 77 | # Version 3 (Python Variation): 78 | # a, b = b, a 79 | 80 | print("Here they are inversed: " + str(a) + " " + str(b)) 81 | ``` 82 | 83 |
84 | 85 | ## Q7 86 | ```python 87 | ch = (input("Enter a character: ")) 88 | 89 | print("The ascii value of " + ch + " is: " + str(ord(ch))) 90 | ``` 91 | 92 |
93 | 94 | ## Q8 95 | ```python 96 | ll = input("Plese enter a lowercase letter: ") 97 | 98 | ul = chr(ord(ll) + ord("A") - ord("a")) 99 | 100 | print("Here is the upparcase version: " + ul) 101 | ``` 102 | 103 |
104 | 105 | ## Q9 106 | ```python 107 | import math 108 | 109 | r = int(input("Plese enter a radius: ")) 110 | 111 | print("The volume of the sphere with the given radius is: " + str(4.0/3*math.pi*math.pow(r,3))) 112 | ``` 113 | 114 |
115 | 116 | ## Q10 117 | ```python 118 | y = int(input("Plese enter the amount of years: ")) 119 | mo = int(input("Plese enter the amount of months: ")) 120 | d = int(input("Plese enter the amount of days: ")) 121 | h = int(input("Plese enter the amount of hours: ")) 122 | mi = int(input("Plese enter the amount of minutes: ")) 123 | 124 | summ = 0 125 | 126 | summ += y * 365 * 24 * 60 * 60 127 | summ += mo * 30 * 24 * 60 * 60 128 | summ += d * 24 * 60 * 60 129 | summ += h * 60 * 60 130 | summ += mi * 60 131 | 132 | print("Given duration is: " + str(summ)+" seconds.") 133 | ``` 134 | 135 |
136 | 137 | ## Q11 138 | ```python 139 | a = int(input("Please enter the first number: ")) 140 | b = int(input("Please enter the second number: ")) 141 | c = int(input("Please enter the third number: ")) 142 | 143 | print(a * (a % 2) + b * (b % 2) + c * (c % 2)) 144 | ``` 145 | -------------------------------------------------------------------------------- /Fall20/week02/README.md: -------------------------------------------------------------------------------- 1 | ## Question 1 2 | 3 | Write a program which takes a float and prints **absolute value** of this float **without using abs() function**. 4 | 5 | | Input | Output | 6 | | ----- | ------ | 7 | | 5.8 | 5.8 | 8 | | -11.5 | 11.5 | 9 | 10 | ## Question 2 11 | 12 | Write a program which takes two integers and determines **whether the first one is divisible by the second one.** If it's divisible, then the program prints **quotient** of the division; otherwise it prints **remainder** of the division. 13 | 14 | | Input | Output | 15 | | ------ | ------ | 16 | | 161 11 | 7 | 17 | | 30 6 | 5 | 18 | 19 | ## Question 3 20 | 21 | Write a program that takes 3 integers from the user and then prints **minimum** and **maximum** of these numbers. 22 | 23 | | Input | Output | 24 | | -------- | ------ | 25 | | 13 27 14 | 13 27 | 26 | 27 | ## Question 4 28 | 29 | Write a program which takes an integer from user and then prints whether this integer is **divisible by 2, 3 and 5.** 30 | 31 | | Input | Output | 32 | | ----- | ------------------------------------------------------ | 33 | | 8 | Divisible by 2 | 34 | | 30 | Divisible by 2
Divisible by 3
Divisible by 5 | 35 | 36 | ## Question 5 37 | 38 | Write a program which takes the age of the user and give the appropriate output looking the table below. 39 | 40 | | Age | Group | 41 | | ----- | -------- | 42 | | 0-17 | Child | 43 | | 18-64 | Can Work | 44 | | 65+ | Retired | 45 | 46 | | Input | Output | 47 | | ----- | -------- | 48 | | 15 | Child | 49 | | 28 | Can Work | 50 | | 18 | Can Work | 51 | 52 | **Don't forget to test your code on 18 and 65 as inputs.** 53 | 54 | ## Question 6 55 | 56 | Write a program that determines whether a given year is a leap year or not. 57 | 58 | - **Multiples of 4 are leap years** 59 | - **Multiples of 100 are *not* leap years** 60 | - **Multiples of 400 are leap years** 61 | 62 | | Input | Output | 63 | | ----- | --------------- | 64 | | 1600 | Leap year | 65 | | 1700 | Not a leap year | 66 | | 2020 | Leap year | 67 | 68 | ## Question 7 69 | 70 | Write a program that computes the letter grade of a CMPE150 student with the aid of percentages and catalogue below: 71 | 72 | | Type | Percentage | 73 | | ----------- | ---------- | 74 | | Midterm | 20 | 75 | | Labs | 10 | 76 | | Assignments | 15 | 77 | | Project | 25 | 78 | | Final | 30 | 79 | 80 | | Note | Letter Grade | 81 | | ------ | ------------ | 82 | | 75-100 | A | 83 | | 55-75 | B | 84 | | 35-55 | C | 85 | | 0-35 | F | 86 | 87 | | Input | Output | 88 | | ----------------- | ------ | 89 | | 100 100 100 90 80 | A | 90 | | 60 60 60 80 65 | B | 91 | 92 | ## Question 8 93 | 94 | Write a program that calculates the body mass index with the given formula and print the appropriate class with the catalogue below. 95 | 96 | 97 | 98 | 99 | | Category | BMI | 100 | | ------------------------------------- | ------- | 101 | | Very severely underweight | -15 | 102 | | Severely underweight | 15-16 | 103 | | Underweight | 16-18.5 | 104 | | Normal (healthy weight) | 18.5-25 | 105 | | Overweight | 25-30 | 106 | | Obese Class I (Moderately obese) | 30-35 | 107 | | Obese Class II (Severely obese) | 35-40 | 108 | | Obese Class III (Very severely obese) | 40+ | 109 | 110 | | Input | Output | 111 | | ------- | --------------------------------- | 112 | | 83 1.74 | 27.4
Overweight | 113 | | 73 1.74 | 24.1
Normal (healthy weight) | 114 | 115 | ## Question 9 116 | 117 | Write a program which calculates whether any given two numbers are multiples of one another. 118 | 119 | | Input | Output | 120 | | ----- | ------------ | 121 | | 2 4 | Multiple | 122 | | 4 2 | Multiple | 123 | | 5 3 | Not Multiple | 124 | 125 | ## Question 10 126 | 127 | Write a program which takes three floats as **a, b, c** and calculates **real roots** for a quadratic equation using the formula 128 | 129 | The expression under the square root is known as **the discriminant.** 130 | 131 | * If the discriminant is **negative**, the roots are **imaginary.** 132 | * If the discriminant is **zero**, there is **only one root.** 133 | * If the discriminant is **positive**, there are **two roots.** 134 | 135 | *Note: Ignore imaginary roots.* 136 | 137 | | Input | Output | 138 | | ------ | --------- | 139 | | 1 5 6 | -2.0 -3.0 | 140 | | 1 -4 4 | 2.0 | 141 | 142 | -------------------------------------------------------------------------------- /Fall20/week02/Solutions.md: -------------------------------------------------------------------------------- 1 | ## Question 1 2 | 3 | ```python 4 | number = float(input()) 5 | if number >= 0: 6 | print(number) 7 | else: 8 | print(-number) 9 | ``` 10 | 11 | ## Question 2 12 | 13 | ```python 14 | num1 = int(input()) 15 | num2 = int(input()) 16 | if num1 % num2 == 0: 17 | print(num1//num2) 18 | else: 19 | print(num1%num2) 20 | ``` 21 | 22 | ## Question 3 23 | 24 | ```python 25 | a = int(input()) 26 | b = int(input()) 27 | c = int(input()) 28 | if a > b and b > c: 29 | print(c, a) 30 | elif a > c and c > b: 31 | print(b, a) 32 | elif b > c and c > a: 33 | print(a, b) 34 | elif b > a and a > c: 35 | print(c, b) 36 | elif c > a and a > b: 37 | print(b, c) 38 | else: 39 | print(a, c) 40 | ``` 41 | 42 | 43 | 44 | ```python 45 | a = int(input()) 46 | b = int(input()) 47 | c = int(input()) 48 | max_num, min_num = None, None 49 | if (a >= b) and (a >= c): 50 | max_num = a 51 | elif (b >= a) and (b >= c): 52 | max_num = b 53 | else: 54 | max_num = c 55 | 56 | if (a <= b) and (a <= c): 57 | min_num = a 58 | elif (b <= a) and (b <= c): 59 | min_num = b 60 | else: 61 | min_num = c 62 | 63 | print(min_num, max_num) 64 | ``` 65 | 66 | 67 | 68 | ```python 69 | a = int(input()) 70 | b = int(input()) 71 | c = int(input()) 72 | 73 | max_num = a if a > b else b 74 | max_num = c if c > max_num else max_num 75 | 76 | min_num = a if a < b else b 77 | min_num = c if c < min_num else min_num 78 | 79 | print(min_num, max_num) 80 | ``` 81 | 82 | 83 | 84 | ## Question 4 85 | 86 | ```python 87 | num_input = int(input()) 88 | if num_input % 2 == 0: 89 | print('Divisible by 2') 90 | if num_input % 3 == 0: 91 | print('Divisible by 3') 92 | if num_input % 5 == 0: 93 | print('Divisible by 5') 94 | 95 | ``` 96 | 97 | ## Question 5 98 | 99 | ```python 100 | age = int(input()) 101 | if age >= 0 and age <= 17: 102 | print('Child') 103 | elif age >= 18 and age <= 64: 104 | print('Can Work') 105 | elif age >= 65: 106 | print('Retired') 107 | ``` 108 | 109 | ## Question 6 110 | 111 | ```python 112 | year = int(input()) 113 | 114 | if year % 400 == 0: 115 | print('Leap year') 116 | elif year % 100 == 0: 117 | print('Not a leap year') 118 | elif year % 4 == 0: 119 | print('Leap year') 120 | else: 121 | print('Not a leap year') 122 | 123 | ``` 124 | 125 | ```python 126 | year = int(input()) 127 | 128 | if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): 129 | print('Leap year') 130 | else: 131 | print('Not a leap year') 132 | ``` 133 | 134 | ## Question 7 135 | 136 | ```python 137 | mt = int(input()) 138 | lab = int(input()) 139 | ass = int(input()) 140 | proj = int(input()) 141 | final = int(input()) 142 | overall_grade = mt * 0.2 + lab * 0.1 + ass * 0.15 + proj * 0.25 + final * 0.3 143 | if overall_grade >= 75: 144 | print('A') 145 | elif overall_grade >= 55: 146 | print('B') 147 | elif overall_grade >= 35: 148 | print('C') 149 | else: 150 | print('F') 151 | ``` 152 | 153 | ## Question 8 154 | 155 | ```python 156 | mass = int(input()) 157 | height = float(input()) 158 | bmi = mass / height ** 2 159 | print('%.1f' % bmi) 160 | if bmi <= 15: 161 | print('Very severely underweight') 162 | elif bmi <= 16: 163 | print('Severely underweight') 164 | elif bmi <= 18.5: 165 | print('Underweight') 166 | elif bmi <= 25: 167 | print('Normal (healthy weight)') 168 | elif bmi <= 30: 169 | print('Overweight') 170 | elif bmi <= 35: 171 | print('Obese Class I (Moderately obese)') 172 | elif bmi <= 40: 173 | print('Obese Class II (Severely obese)') 174 | else: 175 | print('Obese Class III (Very severely obese)') 176 | ``` 177 | 178 | ## Question 9 179 | 180 | ```python 181 | a = int(input()) 182 | b = int(input()) 183 | 184 | if a % b == 0 or b % a == 0: 185 | print('Multiple') 186 | else: 187 | print('Not Multiple') 188 | ``` 189 | 190 | ## Question 10 191 | 192 | ```python 193 | import math 194 | a = float(input()) 195 | b = float(input()) 196 | c = float(input()) 197 | disc = b ** 2 - 4 * a * c 198 | if disc > 0: 199 | print((-b + math.sqrt(disc)) / 2 * a, (-b - math.sqrt(disc)) / 2 * a) 200 | elif disc == 0: 201 | print((-b + math.sqrt(disc)) / 2 * a) 202 | ``` 203 | 204 | -------------------------------------------------------------------------------- /Fall20/week04/Solutions.md: -------------------------------------------------------------------------------- 1 | # Nested Loops 2 | 3 | ## Question 1 - R\*\*\*tangle 4 | 5 | ### Question 1a 6 | 7 | ```python 8 | N = int(input("N: ")) 9 | M = int(input("M: ")) 10 | 11 | for _ in range(N): 12 | for _ in range(M): 13 | print("*", end='') 14 | print() 15 | ``` 16 | 17 | ### Question 1b 18 | 19 | ```python 20 | N = int(input("N: ")) 21 | M = int(input("M: ")) 22 | 23 | for _ in range(M): 24 | print("*", end='') 25 | print() 26 | 27 | for _ in range(N-2): 28 | print("*", end='') 29 | for _ in range(M-2): 30 | print("-", end='') 31 | print("*") 32 | 33 | for _ in range(M): 34 | print("*", end='') 35 | ``` 36 | 37 | 38 | ## Question 2 - TriNumber 39 | 40 | ### Question 2a 41 | 42 | ```python 43 | N = int(input("N: ")) 44 | 45 | for i in range(1, N+1): 46 | for j in range(i): 47 | print(i, end='') 48 | print() 49 | ``` 50 | 51 | ### Question 2b 52 | 53 | ```python 54 | N = int(input("N: ")) 55 | 56 | for i in range(1, N+1): 57 | for j in range(i): 58 | print(j+1, end='') 59 | print() 60 | ``` 61 | 62 | ### Question 2c 63 | 64 | ```python 65 | N = int(input("N: ")) 66 | x = int(input("x: ")) 67 | 68 | for i in range(1, N+1): 69 | for j in range(1, i+1): 70 | power = 1 71 | for k in range(j): 72 | power *= x 73 | print(power, end=' ') 74 | print() 75 | ``` 76 | 77 | 78 | ## Question 3 - TriHard 79 | 80 | ```python 81 | N = int(input()) 82 | 83 | for i in range(1, N+1): 84 | for j in range(N - i): 85 | print('-', end='') 86 | for j in range(i): 87 | print('*', end='') 88 | print() 89 | ``` 90 | 91 | 92 | ### Question 4 - Zzz 93 | 94 | ```python 95 | n=int(input()) 96 | 97 | for i in range(n): 98 | for j in range(n): 99 | if i==0: 100 | print('*', end='') 101 | elif i+j==n-1: 102 | print('*',end='') 103 | elif i==n-1: 104 | print('*', end='') 105 | else: 106 | print(' ', end='') 107 | print('\n') 108 | ``` 109 | 110 | 111 | ## Question 5 - Sum Facts 112 | 113 | ```python 114 | x = int(input()) 115 | 116 | fact_sum = 0 117 | 118 | while x > 0: 119 | digit = x % 10 120 | fact = 1 121 | for i in range(2, digit+1): 122 | fact *= i 123 | fact_sum += fact 124 | 125 | x //= 10 126 | 127 | print(fact_sum) 128 | ``` 129 | 130 | 131 | ## Question 6 - Sum of Digits 132 | 133 | ```python 134 | n = int(input()) 135 | 136 | while n >= 10: 137 | sum = 0 138 | while n: 139 | sum += n%10 140 | n //= 10 141 | n = sum 142 | 143 | print(n) 144 | ``` 145 | 146 | 147 | ## Question 7 - Prime Example 148 | 149 | ### Question 7a 150 | 151 | ```python 152 | x = int(input()) 153 | 154 | isPrime = True 155 | 156 | for i in range(2, x): 157 | if x % i == 0: 158 | isPrime = False 159 | break 160 | 161 | if isPrime: 162 | print("Prime") 163 | else: 164 | print("Prime Not") 165 | ``` 166 | 167 | 168 | ### Question 7b 169 | 170 | ```python 171 | N = int(input()) 172 | 173 | for x in range(2, N+1): 174 | isPrime = True 175 | for i in range(2, x): 176 | if x % i == 0: 177 | isPrime = False 178 | break 179 | 180 | if isPrime: 181 | print(x, end=' ') 182 | ``` 183 | 184 | 185 | ## Question 8 - Prime factors 186 | 187 | ### Question 8a 188 | 189 | ```python 190 | number = int(input()) 191 | for i in range(1, number + 1): 192 | if number % i == 0: 193 | print(i, end = " ") 194 | ``` 195 | 196 | ### Question 8b 197 | 198 | ```python 199 | number = int(input()) 200 | for i in range(2, number + 1): 201 | while number % i == 0: 202 | number //= i 203 | print(i, end=" ") 204 | ``` 205 | 206 | This works because at any point in the loop, number doesn't have any factors smaller than ``i``. Therefore, ``i`` has to be prime if it divides ``number``. 207 | 208 | ### Question 8c 209 | 210 | ```python 211 | number = int(input()) 212 | firstPrime = True 213 | for i in range(2, number + 1): 214 | count = 0 215 | while number % i == 0: 216 | number //= i 217 | count += 1 218 | if count > 0: 219 | if firstPrime: 220 | firstPrime = False 221 | else: 222 | print(" * ", end="") 223 | print(i, "^", count, end="") 224 | ``` 225 | 226 | 227 | 228 | ## Question 9 - Pascal's Triangle 229 | 230 | ```python 231 | import math 232 | 233 | n=int(input()) 234 | 235 | for i in range(n): 236 | for j in range(i+1): 237 | c_ij=int( math.factorial(i) / ( math.factorial(j) * math.factorial(i-j) )) 238 | print(str(c_ij), end=' ') 239 | print('\n') 240 | ``` 241 | 242 | 243 | ## Question 10 - Half-Matrix 244 | 245 | ### Question 10a 246 | 247 | ```python 248 | n=int(input()) 249 | cur = 0 250 | 251 | for i in range(n): 252 | for j in range(i+1): 253 | print(cur , end = ' ') 254 | cur+=1 255 | print() 256 | ``` 257 | 258 | ### Question 10b 259 | 260 | ```python 261 | 262 | n = int(input()) 263 | 264 | for i in range(n): 265 | cur = i 266 | j = n-1 267 | for k in range(i+1): 268 | print(cur ,end=' ') 269 | cur+=j 270 | j=j-1 271 | print() 272 | 273 | ``` -------------------------------------------------------------------------------- /Fall20/week05/Solutions.md: -------------------------------------------------------------------------------- 1 | # Q1 2 | 3 | ```python 4 | def is_leap_year(year): 5 | if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): 6 | return True 7 | else: 8 | return False 9 | leap = is_leap_year(1904) 10 | if leap: 11 | print('leap year') 12 | else: 13 | print('not a leap year') 14 | ``` 15 | 16 | # Q2 17 | 18 | ```python 19 | def calculate_cost(cost, is_student): 20 | if is_student: 21 | cost /= 2 22 | return cost 23 | print(calculate_cost(10, True)) 24 | ``` 25 | 26 | # Q3 27 | 28 | ## a 29 | 30 | ```python 31 | def power(number, n=2): 32 | result = 1 33 | for i in range(n): 34 | result *= number 35 | return result 36 | print(power(5)) 37 | print(power(3, 2)) 38 | print(power(4, 3)) 39 | ``` 40 | 41 | ## b 42 | 43 | ```python 44 | def print_powers(number): 45 | for i in range(6): 46 | print(power(number, i+1)) 47 | print_powers(3) 48 | ``` 49 | 50 | # Q4 51 | 52 | ```python 53 | def is_prime(number): 54 | for i in range(2, number): 55 | if number % i == 0: 56 | return False 57 | return True 58 | print(is_prime(7)) 59 | print(is_prime(12)) 60 | ``` 61 | 62 | # Q5 63 | 64 | ```python 65 | def is_super(number): 66 | for i in range(2, number): 67 | if number % i == 0 and not is_prime(i): 68 | return False 69 | return True 70 | 71 | res = is_super(15) 72 | if res: 73 | print('Suuuper') 74 | else: 75 | print(':(') 76 | ``` 77 | 78 | # Q6 79 | 80 | ```python 81 | def abundant_number(number): 82 | sum_divisors = 0 83 | for i in range(1, number): 84 | if number % i == 0: 85 | sum_divisors += i 86 | if sum_divisors > number: 87 | return True 88 | else: 89 | return False 90 | 91 | def numbers_in_range(lower, upper): 92 | flag = 1 93 | for i in range(lower, upper + 1): 94 | if abundant_number(i): 95 | flag = 0 96 | print(i, end=' ') 97 | if flag: 98 | print('no abundant number') 99 | 100 | numbers_in_range(3, 10) 101 | numbers_in_range(10, 40) 102 | ``` 103 | 104 | # Q7 105 | 106 | ```python 107 | def is_relatively_prime(a, b): 108 | isrltprime = True 109 | 110 | for i in range(2,a+1): 111 | if a % i == 0 and b % i == 0: 112 | isrltprime = False 113 | 114 | if isrltprime: 115 | print("Relatively Prime") 116 | else: 117 | print("Not Relatively Prime") 118 | 119 | is_relatively_prime(2, 5) 120 | is_relatively_prime(12, 8) 121 | ``` 122 | 123 | # Q8 124 | 125 | ## a 126 | 127 | ```python 128 | def modulus(a, b): 129 | while a > b: 130 | a -= b 131 | return a 132 | 133 | print(modulus(17, 3)) 134 | print(modulus(27, 5)) 135 | ``` 136 | 137 | ## b & c 138 | 139 | ```python 140 | def gcd(a, b): 141 | if a < b: 142 | a, b = b, a 143 | while b != 0: 144 | mod = a % b 145 | a, b = b, mod 146 | return a 147 | 148 | def lcm(a, b): 149 | return a * b // gcd(a, b) 150 | 151 | print(gcd(2, 5)) # 1 152 | print(gcd(12, 8)) # 4 153 | 154 | print(lcm(2, 5)) # 10 155 | print(lcm(12, 8)) # 24 156 | ``` 157 | 158 | # Q9 159 | 160 | ```python 161 | def is_square(n): 162 | if n >= 0: 163 | root = n ** (1 / 2) 164 | if root == int(root): 165 | return True 166 | else: 167 | return False 168 | return False 169 | ``` 170 | 171 | # Q10 172 | 173 | ```python 174 | def multiply(*args): 175 | result = 1 176 | for i in args: 177 | result *= i 178 | return result 179 | 180 | print(multiply(42,96)) 181 | ``` 182 | 183 | -------------------------------------------------------------------------------- /Fall20/week06/Solutions.md: -------------------------------------------------------------------------------- 1 | ## Question 1 - Reverse 2 | 3 | ```python 4 | N = int(input()) 5 | 6 | list1 = list() 7 | for i in range(N): 8 | list1.append(int(input())) 9 | 10 | # a 11 | print(list1[::-1]) 12 | 13 | # b 14 | list1 = list1[::-1] 15 | # list1.reverse() 16 | print(list1) 17 | ``` 18 | 19 | ## Question 2 - Let's Count 20 | 21 | ```python 22 | def find_freq(list1): 23 | freq = [0] * 100 24 | for l in list1: 25 | freq[l] += 1 26 | for i, f in enumerate(freq): 27 | if f > 0: 28 | print(str(i) + ' --> ' + str(f)) 29 | 30 | 31 | find_freq([5, 10, 2, 5, 50, 5, 10, 1, 2, 2]) 32 | ``` 33 | 34 | ## Question 3 - Inception 35 | 36 | ```python 37 | N = int(input()) 38 | M = int(input()) 39 | 40 | list1 = list() 41 | for i in range(N): 42 | list1.append(int(input())) 43 | 44 | list2 = list() 45 | for i in range(M): 46 | list2.append(int(input())) 47 | 48 | for j in range(len(list2) - len(list1)): 49 | isFound = True 50 | for i in range(len(list1)): 51 | if list1[i] != list2[j + i]: 52 | isFound = False 53 | break 54 | 55 | if isFound: 56 | print(j) 57 | break 58 | ``` 59 | 60 | ## Question 4 - Pairs 61 | 62 | ```python 63 | def find_pairs(list1, X): 64 | for i, l1 in enumerate(list1): 65 | for l2 in list1[i + 1:]: 66 | if l1 + l2 == X: 67 | print("(%d, %d)" % (l1, l2)) 68 | 69 | 70 | find_pairs([2, 4, 3, 5, 7, 8, 9], 7) 71 | ``` 72 | 73 | ## Question 5 - fix34 74 | 75 | ```python 76 | N = int(input()) 77 | list1 = list() 78 | for i in range(N): 79 | list1.append(int(input())) 80 | 81 | for i in range(len(list1)): 82 | if list1[i] == 3: 83 | for j in range(len(list1)): 84 | if list1[j] == 4 and list1[j - 1] != 3: 85 | list1[i + 1], list1[j] = list1[j], list1[i + 1] 86 | 87 | print(list1) 88 | ``` 89 | 90 | ## Question 6 - Bubble Sort 91 | 92 | ```python 93 | def bubbleSort(arr): 94 | n = len(arr) 95 | 96 | # Traverse through all array elements 97 | for i in range(n - 1): 98 | # range(n) also work but outer loop will repeat one time more than needed. 99 | 100 | # Last i elements are already in place 101 | for j in range(0, n - i - 1): 102 | 103 | # traverse the array from 0 to n-i-1 104 | # Swap if the element found is greater 105 | # than the next element 106 | if arr[j] > arr[j + 1]: 107 | arr[j], arr[j + 1] = arr[j + 1], arr[j] 108 | 109 | # temp = arr[j] 110 | # arr[j] = arr[j+1] 111 | # arr[j+1] = temp 112 | 113 | return arr 114 | 115 | 116 | print(bubbleSort([4, 2, 8, 6, 7, 3, 1, 5])) 117 | ``` 118 | 119 | ## Question 7 - Concatwise 120 | 121 | ```python 122 | def concatwise(list1, list2): 123 | return [i + j for i, j in zip(list1, list2)] 124 | 125 | 126 | list1 = ["M", "na", "i", "Pat"] 127 | list2 = ["y", "me", "s", "rick"] 128 | print(concatwise(list1, list2)) 129 | ``` 130 | 131 | ## Question 8 - Combine Reverse 132 | 133 | ```python 134 | def combine_reverse(list1, list2): 135 | for x, y in zip(list1, list2[::-1]): 136 | print(x, y) 137 | 138 | 139 | list1 = [10, 20, 30, 40] 140 | list2 = [100, 200, 300, 400] 141 | combine_reverse(list1, list2) 142 | ``` 143 | 144 | ## Question 9 - Remove X 145 | 146 | ```python 147 | list1 = [5, 20, 15, 20, 25, 50, 20] 148 | 149 | 150 | def removeValue(sampleList, val): 151 | return [value for value in sampleList if value != val] 152 | 153 | 154 | resList = removeValue(list1, 20) 155 | print(resList) 156 | ``` -------------------------------------------------------------------------------- /Fall20/week08/Solutions.md: -------------------------------------------------------------------------------- 1 | ## Question 1 - Voweeels 2 | 3 | ```python 4 | def vowel(s): 5 | max_length, length = 0, 0 6 | for c in s: 7 | if c in 'oeaiu': 8 | length += 1 9 | else: 10 | length = 0 11 | max_length = max(length, max_length) 12 | return max_length 13 | 14 | print(vowel("happy beaar")) 15 | print(vowel("how you doin?")) 16 | print(vowel("aiaiai")) 17 | print(vowel("try")) 18 | ``` 19 | 20 | ## Question 2 - Palindrome 21 | 22 | ```python 23 | def is_palindrome(str): 24 | return str == str[::-1] 25 | ``` 26 | 27 | ## Question 3 - Lower/Upper Counts 28 | 29 | ```python 30 | str = "HeLLo WoRLD" 31 | lower_count, upper_count = 0, 0 32 | for c in str: 33 | lower_count += c.islower() 34 | upper_count += c.isupper() 35 | 36 | print(upper_count, lower_count) 37 | ``` 38 | 39 | ## Question 4 - Requirements 40 | 41 | ```python 42 | def is_valid(password): 43 | length = len(password) 44 | if length < 6 or length > 20: 45 | return False 46 | lower, upper, digit = 0, 0, 0 47 | for c in password: 48 | lower += c.islower() 49 | upper += c.isupper() 50 | digit += c.isdigit() 51 | return lower >= 1 and upper >= 1 and digit >= 1 52 | ``` 53 | 54 | ## Question 5 - Ing 55 | 56 | ```python 57 | str = 'abc' 58 | if len(str) >= 3: 59 | if str.endswith('ing'): 60 | str = str + 'ly' 61 | else: 62 | str = str + 'ing' 63 | print(str) 64 | ``` 65 | 66 | ## Question 6 - Trim 67 | 68 | #### Question 6a 69 | 70 | ```python 71 | str = input() 72 | str = input.strip() 73 | print(str) 74 | ``` 75 | 76 | #### Question 6b 77 | 78 | ```python 79 | sentence = input() 80 | characters = input() 81 | sentence = sentence.lstrip(characters) 82 | print(sentence) 83 | ``` 84 | 85 | ```python 86 | sentence = input() 87 | characters = input() 88 | sentence = sentence.rstrip(characters) 89 | print(sentence) 90 | ``` 91 | 92 | ## Question 7 - Length 93 | 94 | ```python 95 | sentence = input() 96 | words = sentence.split() 97 | lengths = [len(w) for w in words] 98 | shortest_index = lengths.index(min(lengths)) 99 | longest_index = lengths.index(max(lengths)) 100 | print(words[shortest_index], words[longest_index]) 101 | ``` 102 | 103 | ## Question 8 - Not poor 104 | 105 | ```python 106 | def not_poor(str1): 107 | snot = str1.find('not') 108 | spoor = str1.find('poor') 109 | if spoor > snot and snot > 0 and spoor > 0: 110 | str1 = str1.replace(str1[snot:(spoor+4)], 'good') 111 | return str1 112 | else: 113 | return str1 114 | print(not_poor('The lyrics is not that poor!')) 115 | print(not_poor('The lyrics is poor!')) 116 | ``` 117 | 118 | ## Question 9 - Word Cases 119 | 120 | ```python 121 | def modify(str): 122 | words = str.split() 123 | new_str = '' 124 | for ix, word in enumerate(words): 125 | if ix % 2 == 0: 126 | new_str += word.upper() + ' ' 127 | else: 128 | new_str += word.lower() + ' ' 129 | return new_str 130 | 131 | def modify2(str): 132 | return ' '.join([word.upper() if ix % 2 == 0 else word.lower() for ix, word in enumerate(str.split())]) 133 | 134 | print(modify('stop making sponge bob memes')) 135 | print(modify2('stop making sponge bob memes')) 136 | 137 | ``` 138 | 139 | ## Question 10 - Capitalize First Letters 140 | 141 | ```python 142 | def capitalize(sentence): 143 | return " ".join([word[0].upper() + word[1:].lower() for word in sentence.split()]) 144 | 145 | # Title method performs this 146 | print("perFecT NORMAL sentence".title()) 147 | 148 | print(capitalize("perFecT NORMAL sentence")) 149 | print(capitalize("A true friend overlooks your failures and tolerates your success")) 150 | print(capitalize("a WITTY saying proves nOthing")) 151 | 152 | ``` 153 | 154 | ## Question 11 - Initials 155 | 156 | ### Question 11a 157 | 158 | ```python 159 | def name(s): 160 | # split the string into a list 161 | l = s.split() 162 | return ' '.join([w[0].upper() for w in l]) 163 | 164 | s = "mohandas karamchand gandhi" 165 | print(name(s)) 166 | ``` 167 | 168 | ### Question 11b 169 | 170 | ```python 171 | def name(s): 172 | # split the string into a list 173 | l = s.split() 174 | new = "" 175 | 176 | # traverse in the list 177 | for i in range(len(l) - 1): 178 | s = l[i] 179 | # adds the capital first character 180 | new += (s[0].upper() + '.') 181 | # l[-1] gives last item of list l. We 182 | # use title to print first character in 183 | # capital. 184 | new += l[-1].title() 185 | return new 186 | 187 | s = "mohandas karamchand gandhi" 188 | print(name(s)) 189 | ``` 190 | 191 | ## Question 12 - Alphabetical order 192 | 193 | ```python 194 | items = input("Input comma separated sequence of words") 195 | words = [word for word in items.split(",")] 196 | print(",".join(sorted(list(set(words))))) 197 | ``` -------------------------------------------------------------------------------- /Fall20/week10/Solutions.md: -------------------------------------------------------------------------------- 1 | # Dictionaries 2 | 3 | ## Question 1 - Split the Bill 4 | ```python 5 | # https://www.codewars.com/kata/5641275f07335295f10000d0/python 6 | group = { 7 | 'A': 20, 8 | 'B': 15, 9 | 'C': 10 10 | } 11 | 12 | def split_the_bill(x): 13 | diff = sum(x.values())/float(len(x)) 14 | return {k: x[k]-diff for k in x} 15 | 16 | print(split_the_bill(group)) 17 | ``` 18 | 19 | ## Question 2 - Different Types 20 | This was from another school's intro to computing question. It was due to 10.11. 21 | ```python 22 | def separate(my_list): 23 | my_dict = dict() 24 | for i in my_list: 25 | if type(i) in my_dict: 26 | my_dict[type(i)].append(i) 27 | else: 28 | my_dict[type(i)] = [i] 29 | return my_dict 30 | 31 | original_list = [10, 4.20, False, 'Word', 'CMPE150', 30, 3.5, 9.99, 'oblivion', True, 68, 88, "88"] 32 | seperated_list = separate(original_list) 33 | 34 | for k,v in seperated_list.items(): 35 | print(k," -> ",v) 36 | ``` 37 | 38 | ## Question 3 - Sorting Dictionary 39 | 40 | ```python 41 | def sort_dict(d): 42 | return sorted(d.items(), key=lambda x: x[1], reverse=True) 43 | 44 | print(sort_dict({3:1, 2:2, 1:3})) 45 | ``` 46 | 47 | ## Question 4 - Letter Count 48 | 49 | ```python 50 | sentence = input() 51 | my_dict = dict() 52 | total_letter =0 53 | for letter in sentence: 54 | if letter.isalpha(): 55 | letter = letter.lower() 56 | total_letter+=1 57 | if letter not in my_dict: 58 | my_dict[letter] = 1 59 | else: 60 | my_dict[letter] += 1 61 | 62 | sorted_dict = sorted(my_dict.items(), key=lambda x: (-x[1],x[0])) 63 | for k,v in sorted_dict: 64 | print(k,"->","{:.2f}".format(v/total_letter)) 65 | 66 | ``` 67 | 68 | ## Question 5 - Dictionary Merge 69 | ```python 70 | def merge(*dicts): 71 | mydict = dict() 72 | for d in dicts: 73 | for k, v in d.items(): 74 | if k in mydict: 75 | mydict[k].append(d[k]) 76 | else: 77 | mydict[k] = [v] 78 | return mydict 79 | 80 | print(merge({"A": 1, "B": 2} , {"A": 3})) 81 | ``` 82 | 83 | 84 | ## Question 6 - Zip Two Lists 85 | 86 | ```python 87 | list1 = ["melih", "burak", "ahmet", "recep", "melis"] 88 | list2 = [1,2,3,4,5] 89 | def dict_2_lists(list1, list2): 90 | return dict(zip(list1, list2)) 91 | 92 | print(dict_2_lists(list1,list2)) 93 | 94 | 95 | ``` 96 | 97 | 98 | # Sets 99 | 100 | ## Question 1 - List to Distinct 101 | 102 | ```python 103 | def distinct_elements(lst): 104 | return list(set(lst)) 105 | distinct_list = distinct_elements([3,5,4,4,7,11,2,8]) 106 | print(distinct_list) 107 | ``` 108 | 109 | ## Question 2 - Set Operations 110 | 111 | ```python 112 | A = {1, 2, 3, 4, 5, 6} 113 | B = {1, 1, 2, 7, 11} 114 | 115 | def set_operations(set1, set2): 116 | print("A ∪ B = {}".format(set1.union(set2))) 117 | print("A ∩ B = {}".format(set1.intersection(set2))) 118 | print("A / B = {}".format(set1.difference(set2))) 119 | print("B / A = {}".format(set2.difference(set1))) 120 | 121 | set_operations(A, B) 122 | 123 | ``` 124 | 125 | ## Question 3 - Diff 126 | 127 | ```python 128 | def list_values(list1, list2): 129 | print('Missing values in list1', set(list2).difference(set(list1))) 130 | print('Additional values in list1', set(list1).difference(set(list2))) 131 | 132 | 133 | lst1 = [1, 2, 3, 4, 5, 6] 134 | lst2 = [4, 5, 6, 7, 8] 135 | list_values(lst1, lst2) 136 | ``` 137 | 138 | ## Question 4 - Distinct String 139 | 140 | ```python 141 | def is_distinct(string): 142 | return len(set(string)) == len(string) 143 | 144 | 145 | print(is_distinct('violate')) 146 | ``` 147 | 148 | ## Question 5 - Numgram 149 | 150 | ```python 151 | def is_numgram(string): 152 | numbers = ''.join([str(i) for i in list(range(10))]) 153 | common_digits = set(string).intersection(set(numbers)) 154 | return len(common_digits) == len(numbers) 155 | 156 | 157 | numgram_result = is_numgram('SAS102BAD347 HELP5689') 158 | if numgram_result: 159 | print('Numgram') 160 | else: 161 | print('Not a numgram') 162 | ``` 163 | -------------------------------------------------------------------------------- /FrequentlyAskedQuestions (FAQ).md: -------------------------------------------------------------------------------- 1 | # Frequently Asked Question (FAQ) 2 | 3 | 1. How can I install the software required for this course? 4 | 5 | * Follow the [Installation Guide](InstallationGuide.md). 6 | 7 | 2. How can I update Teaching Codes Plugin? 8 | 9 | * Follow the [Teaching Codes Update Guide](TeachingCodesGuide.md) 10 | 11 | 3. How can I open/submit a project? 12 | 13 | * Follow the [Teaching Codes Guide](TeachingCodesGuide.md) 14 | 15 | 4. I encountered an error during installation/using Teaching Codes, how can I get help? 16 | 17 | * Check the questions/solutions in this document and then Technical Support Forum on Moodle. If you can't find the solution, send an email to cmpe150.mail@gmail.com. 18 | 19 | 7. Teaching.Codes Plugin displays 'Nothing to show' 20 | * If you have a Macbook with M1 chip 21 | 22 | * Make sure that you install PyCharm 2021.2.2 for Intel with Rosetta 2. 23 | * Then follow the next steps in [Installation Guide](InstallationGuide.md) 24 | * You may also have to disable SIP following [this link](https://developer.apple.com/documentation/security/disabling_and_enabling_system_integrity_protection). 25 | * Otherwise, 26 | * Make sure you do not extract the Teaching.Codes zip file. 27 | * Download the Teaching.Codes zip using Chrome instead of Safari. 28 | * Then, reinstall the plugin by following [Teaching.Codes guide](TeachingCodesGuide.md) 29 | 8. I can't see the button names in the plugin 30 | 31 | * Change the theme by following these steps: 32 | 33 | * Inside PyCharm, for Windows, click ***File-->Settings***; for MacOS, click ***PyCharm-->Preferences*** and find ***Appearance&Behavior*** on the left. 34 | * Go into **Appearance** under ***Appearance&Behavior*** 35 | * Change Theme from Intellij Light to something else. (**Darcula** seems fine.) 36 | * Click **OK** 37 | 38 | ![](figures/ChangeTheme.png) 39 | 9. Teaching.Codes plugin disappeared 40 | * To open the plugin, click *View > Tool Windows > Teaching.Codes* 41 | 42 | ![](figures/TC.png) 43 | 44 | 10. I have deleted the contents of **Main.py** 45 | * Restore it from **Main.py.txt** under corresponding question's **src** folder 46 | 47 | ![](figures/Maintxt.png) 48 | 49 | 11. I can't see the Question description 50 | * Open the **Question.html** under **WebContent** in a browser 51 | * Right click on **Question.html** file 52 | * Click **Open in Browser.** 53 | 54 | 55 | 56 | 12. If there are multiple questions and you see the same description for both questions or still blank page. 57 | 58 | * Right click on **Question.html** file 59 | * Choose "**Show in Explorer/Finder**". This step open the folder that contains the html file. 60 | 61 | 62 | 63 | * From the folder, open the html file. 64 | 65 | 13. I can't see the Exam Results 66 | 67 | * Log out, and log in to the Teaching.Codes plugin. 68 | * Select the class from the Navigator. Wait a while for the class to load. 69 | * Click the ExamResults tab. When you click Open under a question, if nothing is happening: 70 | * Click the Projects tab on the left of ExamResults 71 | * Then, go into ExamResults once again. Now, when you click Open, you should be able to see your results. 72 | 73 | 14. What counts as **cheating**: 74 | * **Information exchange between students:** Giving and Receiving information to/from your colleagues both count as cheating. 75 | * **Using codes from any source other than the materials of our course:** You can consult internet or books to learn and improve your programming skills. But you shouldn't use any material that is not your own work in the projects and exams. 76 | -------------------------------------------------------------------------------- /InstallationGuide.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/InstallationGuide.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CmpE150 - Fall 2021 2 | 3 | Bogazici University CmpE 150 Introduction to Computing (Python programming language) Notes 4 | 5 | ## Materials 6 | 7 | * [Installation Guide](InstallationGuide.md) 8 | * [Teaching Codes Guide](TeachingCodesGuide.md) 9 | * [Frequently Asked Questions (FAQ)](FrequentlyAskedQuestions%20(FAQ).md) 10 | 11 | ## Exercises 12 | 13 | ### [Week1](week01/) 14 | 15 | * Introduction 16 | * Variables 17 | * Expressions 18 | * Functions 19 | 20 | ### [Week2](week02/) 21 | 22 | * Functions 23 | 24 | 25 | ### [Week3](week03/) 26 | 27 | * For Loops 28 | 29 | 30 | ### [Week4](week04/) 31 | 32 | * Conditional Statements 33 | 34 | ### [Week5](week05/) 35 | 36 | * While Loops 37 | 38 | ### [Week6](week06/) 39 | 40 | * Loops 41 | 42 | ### [Week7](week07/) 43 | 44 | * String 45 | 46 | ### [Week8](week08/) 47 | 48 | * Lists 49 | * Tuples 50 | 51 | ### [Week9](week09/) 52 | 53 | * Dictionary 54 | 55 | ### [Week10](week10/) 56 | 57 | * Sets 58 | * Files 59 | -------------------------------------------------------------------------------- /Spring21/figures/1616341138563.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/1616341138563.png -------------------------------------------------------------------------------- /Spring21/figures/1616342184949.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/1616342184949.png -------------------------------------------------------------------------------- /Spring21/figures/1616342517499.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/1616342517499.png -------------------------------------------------------------------------------- /Spring21/figures/ChangeTheme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/ChangeTheme.png -------------------------------------------------------------------------------- /Spring21/figures/HTML_Browser.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/HTML_Browser.png -------------------------------------------------------------------------------- /Spring21/figures/HTML_Explorer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/HTML_Explorer.png -------------------------------------------------------------------------------- /Spring21/figures/Maintxt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/Maintxt.png -------------------------------------------------------------------------------- /Spring21/figures/PythonInstaller.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/PythonInstaller.png -------------------------------------------------------------------------------- /Spring21/figures/Teaching.Codes New Version.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/Teaching.Codes New Version.png -------------------------------------------------------------------------------- /Spring21/figures/Teaching.Codes Uninstall.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/Teaching.Codes Uninstall.png -------------------------------------------------------------------------------- /Spring21/figures/Teaching.Codes Version 1212JB.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/Teaching.Codes Version 1212JB.png -------------------------------------------------------------------------------- /Spring21/figures/commit_and_push_failed1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/commit_and_push_failed1.png -------------------------------------------------------------------------------- /Spring21/figures/commit_and_push_failed2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/commit_and_push_failed2.png -------------------------------------------------------------------------------- /Spring21/figures/connection.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/connection.PNG -------------------------------------------------------------------------------- /Spring21/figures/could not open.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/could not open.PNG -------------------------------------------------------------------------------- /Spring21/figures/project-guide/1618485979513.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/project-guide/1618485979513.png -------------------------------------------------------------------------------- /Spring21/figures/project-guide/1618486104949.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/project-guide/1618486104949.png -------------------------------------------------------------------------------- /Spring21/figures/project-guide/1618486398394.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/project-guide/1618486398394.png -------------------------------------------------------------------------------- /Spring21/figures/project-guide/1618486497781.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/project-guide/1618486497781.png -------------------------------------------------------------------------------- /Spring21/figures/project-guide/1618486752521.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/project-guide/1618486752521.png -------------------------------------------------------------------------------- /Spring21/figures/project-guide/1618486890025.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/project-guide/1618486890025.png -------------------------------------------------------------------------------- /Spring21/figures/project-guide/1618487070207.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/project-guide/1618487070207.png -------------------------------------------------------------------------------- /Spring21/figures/project-guide/1618487098652.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/project-guide/1618487098652.png -------------------------------------------------------------------------------- /Spring21/figures/project-guide/1618487165943.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/project-guide/1618487165943.png -------------------------------------------------------------------------------- /Spring21/figures/project-guide/1618487273664.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/project-guide/1618487273664.png -------------------------------------------------------------------------------- /Spring21/figures/project-guide/1618487440503.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/project-guide/1618487440503.png -------------------------------------------------------------------------------- /Spring21/figures/project-guide/1618487934948.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/project-guide/1618487934948.png -------------------------------------------------------------------------------- /Spring21/figures/python-customize.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/python-customize.png -------------------------------------------------------------------------------- /Spring21/figures/python-final.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/python-final.png -------------------------------------------------------------------------------- /Spring21/figures/python-optional.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/python-optional.png -------------------------------------------------------------------------------- /Spring21/figures/team-fixed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/figures/team-fixed.png -------------------------------------------------------------------------------- /Spring21/week01/README.md: -------------------------------------------------------------------------------- 1 | ## Welcome to CMPE150 Lab Session and programming! 2 | 3 | 4 | 5 | 6 | 7 | ### Assistants: 8 | 9 | ![1616505237530](../figures/team-fixed.png) 10 | 11 | ## Announcements 12 | 13 | - We will use **PyCharm** and **Teaching Codes** plug-in in projects and exams. Student accounts will be created for this plug-in. 14 | 15 | - The username and password will be sent to **the e-mail in BUIS** **after add drop period**. We will make an announcement when the credentials are sent. 16 | 17 | - If your email address that you use in BUIS (registration.boun.edu.tr) is anything other than 18 | 19 | - **@gmail** 20 | - **@boun.edu.tr** 21 | 22 | Please change it to @gmail.com, or @boun.edu.tr. In order to do that, 23 | 24 | - Go to https://registration.boun.edu.tr, and Login. 25 | - Enter General Settings, and then E-Mail Management. 26 | - You should change your current Contact E-mail Address to @boun.edu.tr or @gmail.com. 27 | 28 | - Please check announcements on Moodle **regularly**! 29 | 30 | - Lab hours are dedicated to **practical programming exercises not for covering lecture materials**. I **strongly** suggest you to attend the lectures. 31 | 32 | - Follow the Installation Guide and TeachingCodes Guide to complete installation and get familiar with the environment. 33 | 34 | - The installation must be completed **until April 9, 2021**. After that date, questions regarding installation **WILL NOT BE ANSWERED.** 35 | 36 | - What counts as **cheating**: 37 | - **Information exchange between students:** Giving and Receiving information to/from your colleagues both count as cheating. 38 | - **Using codes from any source other than the materials of our course:** You can consult internet or books to learn and improve your programming skills. But you shouldn't use any material that is not your own work in the projects and exams. 39 | 40 | - Check **FAQ** and **Technical Support** to get help. 41 | 42 | ![1616502949955](figures/moodle.png) 43 | -------------------------------------------------------------------------------- /Spring21/week01/figures/moodle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/week01/figures/moodle.png -------------------------------------------------------------------------------- /Spring21/week02/README.md: -------------------------------------------------------------------------------- 1 | # Variables / Expressions / Statements 2 | 3 | ## Question 1 4 | 5 | **a)** Create two integer variables, and print them 6 | 7 | **b)** Take two integers from the user, and print them 8 | 9 | **c)** Take two integers from the user (a, b), and then print their sum, difference, product, power and remainder. 10 | 11 | | Input | Output | 12 | | -------- | ---------------- | 13 | | 13 5 | 18 8 65 371293 3 | 14 | 15 | ## Question 2 16 | 17 | **a)** Create an integer, a float, and a string variable. Print their types, using the type() function. 18 | 19 | **b)** Take an integer, a float, and a string variable from the user. Print the variables. 20 | 21 | ## Question 3 22 | 23 | Write a program that takes 3 integers from the user and then prints the sum, mean and multiple of the numbers. 24 | 25 | | Input | Output | 26 | | -------- | ---------------- | 27 | | 13 27 14 | 54 18.00 4914| 28 | 29 |
30 | 31 | ## Question 4 32 | 33 | Using the formula below of compound interest, take the **principal amount (A)**, **interest rate (i)** (per month) and **duration (n)** (months) and print the final amount. 34 | 35 | 36 | 37 | 38 | | Input | Output | 39 | | --------- | ------- | 40 | | 1000 12 5 | 1762.34 | 41 | | 500 12 5 | 881.17 | 42 | 43 |
44 | 45 | ## Question 5 46 | 47 | Write a program which takes the values in **Ohm** of two parallel resistances and the generator's voltage in **Volt** respectively and print the currents that passes by each resistance. 48 | 49 | 50 | 51 | 52 | | Input | Output | 53 | | ------ | ------ | 54 | | 2 8 40 | 20 5 | 55 | | 5 5 10 | 2 2 | 56 | 57 |
58 | 59 | ## Question 6 60 | 61 | Write a program that calculates the amount of seconds in a given period of years, months, days, hours and minutes respectively. 62 | 63 | * 1 year = 365 days 64 | * 1 month = 30 days 65 | 66 | | Input | Output | 67 | | --------- | --------- | 68 | | 5 2 4 3 0 | 163220400 | 69 | | 1 1 1 1 1 | 34218060 | 70 | 71 |
72 | -------------------------------------------------------------------------------- /Spring21/week02/Solutions.md: -------------------------------------------------------------------------------- 1 | # Variables / Expressions / Statements 2 | 3 | ## Q1.a 4 | 5 | ```python 6 | number1 = 13 7 | number2 = 5 8 | 9 | # Printing numbers in separate lines 10 | print(number1) 11 | print(number2) 12 | 13 | # Printing numbers in a single line 14 | print(number1, number2) 15 | ``` 16 | 17 | ## Q1.b 18 | 19 | ```python 20 | number1 = int(input()) 21 | number2 = int(input()) 22 | 23 | print(number1) 24 | print(number2) 25 | ``` 26 | 27 | ## Q1.c 28 | 29 | ```python 30 | a = int(input()) 31 | b = int(input()) 32 | 33 | print(a + b, a - b, a * b, a ** b, a % b) 34 | ``` 35 | 36 | ## Q2.a 37 | 38 | ```python 39 | number = 5 40 | my_float = 9.8 41 | my_str = "Helloo" 42 | 43 | print(type(number)) 44 | print(type(my_float)) 45 | print(type(my_str)) 46 | ``` 47 | 48 |
49 | 50 | ## Q2.b 51 | 52 | ```python 53 | number = int(input("Enter an integer: ")) 54 | my_float = float(input("Enter a float ")) 55 | my_str = input("Please enter third number: ") 56 | 57 | print(number, my_float, my_str) 58 | # Same print with + operator (concatenation of strings)) 59 | print(str(number) + " " + str(my_float) + " " + my_str) 60 | ``` 61 | 62 |
63 | 64 | 65 | 66 | ## Q3 67 | ```python 68 | number1 = int(input("First number: ")) 69 | number2 = int(input("Second number: ")) 70 | number3 = int(input("Third number: ")) 71 | 72 | sum = number1 + number2 + number3 73 | 74 | print(sum) 75 | print(sum / 3) 76 | print(number1 * number2 * number3) 77 | ``` 78 | 79 |
80 | 81 | ## Q4 82 | ```python 83 | A = int(input("Enter principal amount: ")) 84 | i = int(input("Enter interest rate: ")) 85 | n = int(input("Enter duration: ")) 86 | 87 | S = A * (1 + i/100) ** n 88 | 89 | print("{:.2f}".format(S)) 90 | ``` 91 | 92 |
93 | 94 | ## Q5 95 | ```python 96 | r1 = int(input("First resistance: ")) 97 | r2 = int(input("Second resistance: ")) 98 | 99 | v = int(input("Voltage: ")) 100 | 101 | print(int(v / r1), int(v / r2)) 102 | 103 | ``` 104 | 105 |
106 | 107 | ## Q6 108 | ```python 109 | y = int(input("Year: ")) 110 | m = int(input("Month: ")) 111 | d = int(input("Days: ")) 112 | h = int(input("Hours: ")) 113 | min = int(input("Minutes: ")) 114 | 115 | y = y * 365 * 24 * 60 * 60 116 | m = m * 30 * 24 * 60 * 60 117 | d = d * 24 * 60 * 60 118 | h = h * 60 * 60 119 | min = min * 60 120 | 121 | sum = y + m + d + h + min 122 | 123 | print(sum) 124 | ``` 125 | 126 | Alternative: 127 | 128 | ```python 129 | y = int(input("Year: ")) 130 | m = int(input("Month: ")) 131 | d = int(input("Days: ")) 132 | h = int(input("Hours: ")) 133 | min = int(input("Minutes: ")) 134 | 135 | sum = (((y * 365 + m * 30 + d) * 24 + h) * 60 + min) * 60 136 | 137 | print(sum) 138 | ``` 139 | 140 |
141 | -------------------------------------------------------------------------------- /Spring21/week03/README.md: -------------------------------------------------------------------------------- 1 | # Variables / Expressions / Statements 2 | continued.. 3 | 4 | ## Question 1 5 | 6 | Write a program which takes radius of a circle from user and calculate the perimeter and surface of the defined circle. 7 | 8 | **You can get the value of pi from math module (from math import pi)** 9 | 10 | | Input | Output | 11 | | ----- | --------------------------- | 12 | | 4 | 25.1327412287 50.2654824574 | 13 | | 8 | 50.2654824574 201.06192983 | 14 | 15 |
16 | 17 | ## Question 2 18 | 19 | Write a program that calculates the volume of a sphere by taking its radius from user. 20 | 21 | | Input | Output | 22 | | ----- | ------------- | 23 | | 3 | 113.097335529 | 24 | | 6 | 904.778684234 | 25 | 26 |
27 | 28 | ## Question 3 29 | 30 | Write a program that takes a positive number from user and calculate the sum from 0 to that positive number. 31 | 32 | **You do not need to use any loops or developed coding** 33 | 34 | | Input | Output | 35 | | ----- | ------ | 36 | | 10 | 55 | 37 | | 5 | 15 | 38 | 39 |
40 | 41 | ## Question 4 42 | 43 | Write a program which replaces the values of two integers. 44 | 45 | | Input | Output | 46 | | ----- | ------ | 47 | | 5 10 | 10 5 | 48 | 49 |
50 | 51 | ## Question 5 52 | 53 | Write a program which takes a lowercase letter as input and print the uppercase version of the given letter. 54 | 55 | | Input | Output | 56 | | ----- | ------ | 57 | | a | A | 58 | | b | B | 59 | 60 |
61 | 62 | ## Question 6 63 | 64 | Write a program that takes 3 integers from the user and then prints the sum of odd numbers. 65 | 66 | | INPUT | OUTPUT | 67 | | ------ | ------ | 68 | | 3 4 5 | 8 | 69 | | 2 2 4 | 0 | 70 | | 1 9 15 | 25 | 71 | 72 |
73 | 74 | ## Question 7 75 | 76 | There is a cash machine with an infinite supply of 5tl banknotes and 1tl coins inside it. 77 | 78 | Write a program that takes an integer as input representing the amount of money requested by a customer. The program then prints the number of banknotes and coins given to the customer. (Machine must prefer giving away banknotes instead of coins if possible) 79 | 80 | | INPUT | OUTPUT | 81 | | ------ | ------ | 82 | | 57 | 11 2 | 83 | | 269 | 53 4 | 84 | 85 |
86 | 87 | ## Question 8 88 | 89 | Guess the outcome of each statement. Then check the results. 90 | 91 | Hint: You can multiply strings with integers. It basically performs the concatenation operation n many times. 92 |
93 | 94 | * print(int('6') + int('4'))
95 | * print('1' + '4')
96 | * print(int(3.9)) 97 | * print(str(5.3) + '2.7')
98 | * print(int('5') * str(0.6))
99 | * print(float('3' + '8.6'))
100 | * print(3.5 + 6.7)
101 | * print(2 ** 3 ** 2 / 32) 102 | * print(str(4.4) + str(7.3))
103 | * print(int(6.5) + float('6.5'))
104 | * print(int(4.5 + 3.2))
105 | * print(int(3.2) + int(float(str(3.2))))
106 | 107 | Remarks: 108 |
109 | 110 | * Observe that float-to-int type conversion is not a rounding operation. int(3.9) = 3. To round floats, we will use a built-in function called round(). Stay tuned!
111 | * As you see, we can multiply strings with integers, but not floats. What does 3.14 times "pi" mean, anyway?
112 | * Exponent operator ** has right-to-left associativity.
113 |
114 |
115 | 116 | ## Question 9 117 | 118 | We want to simulate a division operation. In order to do that, write a program to prompt the user for 2 integers, dividend and divisor respectively. Perform the division operation and print out the quotient and the remainder. 119 | 120 | | INPUT | OUTPUT | 121 | | ------ | ------ | 122 | | 9 2 | quotient = 4 remainder = 1| 123 | | 156 13 | quotient = 12 remainder = 0 | 124 | | 84 16 | quotient = 5 remainder = 4 | 125 | 126 |
127 | 128 | ## Question 10 129 | 130 | In mathematics and computer science, the [floor function](https://en.wikipedia.org/wiki/Floor_and_ceiling_functions) is the function that takes as input a real number x, and gives as output the greatest integer less than or equal to x, denoted as `⌊x⌋`. The fractional part is the sawtooth function, denoted by `{x}` for real x and defined by the formula `{x} = x - ⌊x⌋`. Write a function that takes 3 positive floats from the input and prints out the fractional part of each value respectively. Do not use float-to-int type casting. There might occur some [floating-point error](https://www.geeksforgeeks.org/floating-point-error-in-python/), you do not have to deal with that.
131 | Hint: Integer division by 1 can be helpful to find `⌊x⌋`. Notice that for negative numbers, we have to perform extra steps to find `⌊x⌋`. 132 | 133 | | INPUT | OUTPUT | 134 | | ------ | ------ | 135 | | 4.8 6.4 3.5| 0.8 0.4 0.5| 136 | | 67.32 23.53 13.98 | 0.32 0.53 0.98 | 137 | | 65.12 49.32 30.09 | 0.12 0.32 0.09 | 138 | 139 |
140 | 141 | -------------------------------------------------------------------------------- /Spring21/week03/Solutions.md: -------------------------------------------------------------------------------- 1 | # Variables / Expressions / Statements 2 | 3 | You may clean strings in input and print functions. 4 | 5 | ## Q1 6 | ```python 7 | from math import pi 8 | 9 | r = int(input("Plese enter a radius: ")) 10 | 11 | print("The perimeter of the circle with given radius is: " + str(2*pi*r)) 12 | print("The surface of the circle with given radius is: " + str(pi*r**2)) 13 | ``` 14 | 15 |
16 | 17 | ## Q2 18 | ```python 19 | import math 20 | 21 | r = int(input("Plese enter a radius: ")) 22 | 23 | print("The volume of the sphere with the given radius is: " + str(4.0/3*math.pi*math.pow(r,3))) 24 | ``` 25 | 26 |
27 | 28 | ## Q3 29 | ```python 30 | n = int(input("Plese enter a number: ")) 31 | 32 | print("The sum till the given number is: " + str((n*(n+1))/2)) 33 | 34 | ``` 35 | 36 |
37 | 38 | ## Q4 39 | ```python 40 | a = int(input("Plese enter the first number: ")) 41 | b = int(input("Plese enter the second number: ")) 42 | 43 | # Version 0 (Easy Swap): 44 | original_a = a 45 | original_b = b 46 | a = original_b 47 | b = original_a 48 | 49 | # Version 1 (Classic Swap): 50 | temp = a 51 | a = b 52 | b = temp 53 | 54 | # Version 2 (Without using extra variable): 55 | # a = a + b 56 | # b = a - b 57 | # a = a - b 58 | 59 | # Version 3 (Python Variation): 60 | # a, b = b, a 61 | 62 | print("Here they are inversed: " + str(a) + " " + str(b)) 63 | ``` 64 | 65 |
66 | 67 | ## Q5 68 | ```python 69 | ll = input("Plese enter a lowercase letter: ") 70 | 71 | ul = chr(ord(ll) + ord("A") - ord("a")) 72 | 73 | print("Here is the upparcase version: " + ul) 74 | 75 | # Built-in function 76 | # print(ll.upper()) 77 | ``` 78 | 79 |
80 | 81 | 82 | ## Q6 83 | ```python 84 | a = int(input("Please enter the first number: ")) 85 | b = int(input("Please enter the second number: ")) 86 | c = int(input("Please enter the third number: ")) 87 | 88 | print(a * (a % 2) + b * (b % 2) + c * (c % 2)) 89 | ``` 90 | 91 | **Alternative solution (using if)** 92 | 93 | ```python 94 | a = int(input("Please enter the first number: ")) 95 | b = int(input("Please enter the second number: ")) 96 | c = int(input("Please enter the third number: ")) 97 | 98 | sum = 0 99 | 100 | if a % 2 == 1: 101 | sum = sum + a 102 | # Equivalent expression: sum += a 103 | 104 | if b % 2 == 1: 105 | sum = sum + b 106 | # Equivalent expression: sum += b 107 | 108 | if c % 2 == 1: 109 | sum = sum + c 110 | # Equivalent expression: sum += c 111 | 112 | print(sum) 113 | ``` 114 | 115 |
116 | 117 | ## Q7 118 | ```python 119 | amount = int(input("Please enter the amount of money requested by the customer: ")) 120 | 121 | print("Number of 5tl banknotes: %d" % (amount//5)) 122 | print("Number of 1tl coins: %d" % (amount%5)) 123 | ``` 124 | 125 |
126 | 127 | ## Q8 128 | 129 | ```python 130 | print(int('6') + int('4')) 10 131 | print('1' + '4') 14 132 | print(int(3.9)) 3 133 | print(str(5.3) + '2.7') 5.32.7 134 | print(int('5') * str(0.6)) 0.60.60.60.60.6 135 | print(float('3' + '8.6')) 38.6 136 | print(3.5 + 6.7) 10.2 137 | print(2 ** 3 ** 2 / 32) 16.0 138 | print(str(4.4) + str(7.3)) 4.47.3 139 | print(int(6.5) + float('6.5')) 12.5 140 | print(int(4.5 + 3.2)) 7 141 | print(int(3.2) + int(float(str(3.2)))) 6 142 | ``` 143 | 144 |
145 | 146 | ## Q9 147 | ```python 148 | dividend = int(input()) 149 | divisor = int(input()) 150 | 151 | quotient = dividend // divisor 152 | remainder = dividend % divisor 153 | # remainder = dividend - (quotient * divisor) 154 | 155 | print("quotient =", str(quotient), "remainder =", str(remainder)) 156 | ``` 157 | 158 |
159 | 160 | ## Q10 161 | ```python 162 | a = float(input()) 163 | b = float(input()) 164 | c = float(input()) 165 | 166 | floor_a = a // 1 167 | floor_b = b // 1 168 | floor_c = c // 1 169 | 170 | fraction_a = a - floor_a 171 | fraction_b = b - floor_b 172 | fraction_c = c - floor_c 173 | 174 | # print(str(fraction_a), str(fraction_b), str(fraction_c)) 175 | print("%.2f %.2f %.2f" % (fraction_a, fraction_b, fraction_c)) 176 | 177 | ``` 178 | 179 |
180 | -------------------------------------------------------------------------------- /Spring21/week05/README.md: -------------------------------------------------------------------------------- 1 | # Loops 2 | 3 | ## Question 1 - Numbeeeers 4 | 5 | Write a program that reads two integers N and K. Then, it prints numbers from N to K to the screen. 6 | 7 | | INPUT | OUTPUT | 8 | |:-------:|:-------:| 9 | | 5 9 | 5 6 7 8 9 | 10 | | 2 3 | 2 3 | 11 | 12 | 13 | ## Question 2 - Hooping Numbers 14 | 15 | Write a program that reads 3 integers A, B and T from the user. Then prints numbers from A to B with increment of T. Assume that B > A. 16 | 17 | | INPUT | OUTPUT | 18 | |:-------:|:-------:| 19 | | 7 16 3 | 7 10 13 16 | 20 | | 2 30 6 | 2 8 14 20 26 | 21 | 22 | 23 | ## Question 3 - Even Numbeeeers 24 | 25 | Write a program that reads two integers A and B. Then prints the sum of even numbers between A and B. Assume that B > A. A and B are included. 26 | 27 | | INPUT | OUTPUT | 28 | |:-------:|:-------:| 29 | | 3 8 | 18 | 30 | | 2 13 | 42 | 31 | | 3 5 | 4 | 32 | 33 | 34 | ## Question 4 - Average Team 35 | 36 | Write a program that reads a number N, then reads N more numbers. Calculate the average of those N numbers. 37 | 38 | | INPUT | OUTPUT | 39 | |:-------:|:-------:| 40 | | 4
4 9 5 2 | 5.0 | 41 | | 1
8 | 8.0 | 42 | 43 | 44 | ## Question 5 - Boom Boom POW 45 | 46 | Write a program that takes 2 integers a and b, then prints the result of a^b (a\*a\*a...\*a\*a). 47 | 48 | | INPUT | OUTPUT | 49 | |:-------:|:-------:| 50 | | 3 4 | 81 | 51 | | 2 10 | 1024 | 52 | 53 | 54 | ## Question 6 - Fibonacci 55 | 56 | Write a program which reads a positive integer number N , and prints the Nth fibonacci number. *0, 1, 1, 2, 3, 5, ...* 57 | 58 | F_0 = 0, F_1 = 1, F_n = F\_(n-2) + F\_(n-1) 59 | 60 | | INPUT | OUTPUT | 61 | |:-------:|:-------:| 62 | | 2 | 1 | 63 | | 4 | 2 | 64 | | 7 | 8 | 65 | 66 | 67 | ## Question 7 - Second Largest 68 | 69 | Write a program that will take nonnegative integers as inputs until the user enters 0. Then prints the difference between the largest two numbers among given inputs. 70 | 71 | | INPUT | OUTPUT | 72 | |:-------:|:-------:| 73 | | 12 25 3 8 0 | 13 | 74 | | 15 1 2 3 8 5 0 | 7 | 75 | 76 | 77 | ## Question 8 - Digiiiits 78 | 79 | Write a program that takes a number and prints its total digit count and also even digit sum. 80 | 81 | | INPUT | OUTPUT | 82 | |:-------:|:-------:| 83 | | 542175 | 6 6 | 84 | | 24680 | 5 20 | 85 | | 135 | 3 0 | 86 | 87 | 88 | 89 | ## Question 9 - Positive Mental Attitude 90 | 91 | Write a program that will take integers as inputs until the user enters a negative number. Then shows the user the sum of all ODD non-negative numbers that is entered. 92 | 93 | | INPUT | OUTPUT | 94 | |:-------:|:-------:| 95 | | 4 7 45 9 2 0 0 5 8 -4 | 66 | 96 | | 1 1 0 1 -1 | 3 | 97 | 98 | 99 | ## Question 10 - Guess 100 | 101 | Generate a random number between 1 and 100 (including 1 and 100). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. Also print the number of tries. 102 | 103 | 104 | | Input | Output | 105 | | ----- | --------------- | 106 | | 35
67
73
71 | Too low!
Too low!
Too high!
You got it!
And it only took you 4 tries! | 107 | 108 | 109 | ## Question 11 - NoBig 110 | 111 | Write a program that reads numbers until the entered number is greater than the previous entered number. Then print the average of all entered numbers except the last one. (At least two numbers will be entered) 112 | 113 | | INPUT | OUTPUT | 114 | |:-------:|:-------:| 115 | | 5 4 3 3 8 | 3.75 | 116 | | 1 2 | 1.0 | 117 | | 100 54 46 2 3 | 50.5 | 118 | 119 | 120 | ## Question 12 - FizzBuzz 121 | Take an integer N from the user as an input. And then print all the numbers from 1 to N (inclusive), but if a number is a multiple of 2, print "Fizz", 122 | if a number is a multiple of 3, print "Buzz", and if a number is a multiple of 6 print "FizzBuzz". 123 | 124 | | Input | Output | 125 | | :---: | ------------------------------------ | 126 | | 6 | 1 Fizz Buzz Fizz 5 FizzBuzz | 127 | | 12 | 1 Fizz Buzz Fizz 5 FizzBuzz 7 Fizz Buzz Fizz 11 FizzBuzz | 128 | 129 | 130 | ## Question 13 131 | 132 | Write a program that takes two nonnegative integers as input and finds their greatest common divisor. 133 | 134 | 13 91 -> 13
135 | 87 15 -> 3
136 | 432 0 -> 0
137 | 18 18 -> 18
138 | 139 | 140 | ## Question 14 141 | 142 | A number is said to be "Disarium" if the sum of its digits raised to their respective positions is the number itself. 143 | Write a program that determines whether a number is a Disarium or not. 144 | 145 | 75 ➞ False 146 | 147 | 7^1 + 5^2 = 7 + 25 = 32 148 | 149 | 135 ➞ True 150 | 151 | 1^1 + 3^2 + 5^3 = 1 + 9 + 125 = 135 152 | 153 | Example Inputs/Outputs:
154 | 155 | 544 ➞ False
156 | 157 | 518 ➞ True
158 | 159 | 466 ➞ False
160 | 161 | 8 ➞ True
162 | -------------------------------------------------------------------------------- /Spring21/week07/Solutions.md: -------------------------------------------------------------------------------- 1 | ## Question 1 2 | 3 | ```python 4 | def power(number, n=2): 5 | result = 1 6 | for i in range(n): 7 | result *= number 8 | return result 9 | print(power(5)) 10 | print(power(3, 2)) 11 | print(power(4, 3)) 12 | ``` 13 | 14 | 15 | ## Question 2 16 | 17 | ```python 18 | def print_powers(number): 19 | for i in range(6): 20 | print(power(number, i+1)) 21 | print_powers(3) 22 | ``` 23 | 24 | 25 | ## Question 3 26 | 27 | ```python 28 | def abundant_number(number): 29 | sum_divisors = 0 30 | for i in range(1, number): 31 | if number % i == 0: 32 | sum_divisors += i 33 | if sum_divisors > number: 34 | return True 35 | else: 36 | return False 37 | 38 | def numbers_in_range(lower, upper): 39 | flag = 1 40 | for i in range(lower, upper + 1): 41 | if abundant_number(i): 42 | flag = 0 43 | print(i, end=' ') 44 | if flag: 45 | print('no abundant number') 46 | 47 | numbers_in_range(3, 10) 48 | numbers_in_range(10, 40) 49 | ``` 50 | 51 | 52 | ## Question 4 53 | 54 | ### Question 4a 55 | 56 | ```python 57 | def modulus(a, b): 58 | while a > b: 59 | a -= b 60 | return a 61 | 62 | print(modulus(17, 3)) 63 | print(modulus(27, 5)) 64 | ``` 65 | 66 | ### Question 4b and 4c 67 | 68 | ```python 69 | def gcd(a, b): 70 | if a < b: 71 | temp = a 72 | a = b 73 | b = temp 74 | while b != 0: 75 | mod = a % b # You may use modulus function 76 | a = b 77 | b = mod 78 | return a 79 | 80 | def lcm(a, b): 81 | return a * b // gcd(a, b) 82 | 83 | print(gcd(2, 5)) # 1 84 | print(gcd(12, 8)) # 4 85 | 86 | print(lcm(2, 5)) # 10 87 | print(lcm(12, 8)) # 24 88 | ``` 89 | 90 | 91 | ## Question 5 Think 92 | 93 | ```python 94 | def think(size=1): 95 | thought = "h" 96 | if size > 0: 97 | thought += "m"*size 98 | return thought 99 | 100 | print(think(5)) 101 | 102 | # OR 103 | def think(n=1): 104 | print("h" + "m" * n) 105 | ``` 106 | 107 | 108 | ## Question 6 You're a Square! 109 | 110 | ```python 111 | def square(n): 112 | if n < 0: 113 | return False 114 | if n == 0: 115 | return True 116 | for i in range(1, n + 1): 117 | if i ** 2 == n: 118 | return True 119 | return False 120 | 121 | 122 | n = int(input()) 123 | print(square(n)) 124 | ``` 125 | 126 | 127 | ## Question 7 128 | 129 | ```python 130 | def floor(n): 131 | try: 132 | n = int(n) 133 | return n 134 | except: 135 | try: 136 | n = float(n) 137 | return n 138 | except: 139 | print("Invalid input:", n) 140 | 141 | 142 | n = input() 143 | result = floor(n) 144 | print(result, type(result)) 145 | ``` 146 | 147 | 148 | ## Question 8 149 | 150 | ### Question 8a - Distance 151 | 152 | ```python 153 | def distance(x1, y1, x2, y2): 154 | return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) 155 | ``` 156 | 157 | 158 | ### Question 8b - Closest 159 | 160 | ```python 161 | def closest(x1, y1, x2, y2): 162 | d1 = distance(0, 0, x1, y1) 163 | d2 = distance(0, 0, x2, y2) 164 | 165 | if d1 < d2: 166 | print(x1, y1) 167 | elif d1 == d2: 168 | print("Equal distance") 169 | else: 170 | print(x2, y2) 171 | ``` 172 | 173 | ### Question 8c - Valid Triangle 174 | 175 | ```python 176 | def valid_triangle(x1, y1, x2, y2, x3, y3): 177 | d1 = distance(x1, y1, x2, y2) 178 | d2 = distance(x1, y1, x3, y3) 179 | d3 = distance(x2, y2, x3, y3) 180 | 181 | if d1 == 0 or d2 == 0 or d3 == 0: 182 | raise ZeroDivisionError 183 | 184 | if d1 >= d2 + d3 or d2 >= d1 + d3 or d3 >= d1 + d2: 185 | return False 186 | return True 187 | ``` 188 | 189 | ### Question 8d - Perimeter 190 | 191 | ```python 192 | def perimeter(x1, y1, x2, y2, x3, y3): 193 | d1 = distance(x1, y1, x2, y2) 194 | d2 = distance(x1, y1, x3, y3) 195 | d3 = distance(x2, y2, x3, y3) 196 | 197 | if d1 == 0 or d2 == 0 or d3 == 0: 198 | raise ZeroDivisionError 199 | 200 | if d1 >= d2 + d3 or d2 >= d1 + d3 or d3 >= d1 + d2: 201 | raise ValueError 202 | 203 | return d1 + d2 + d3 204 | ``` 205 | 206 | 207 | ### Question 8e - Area 208 | 209 | ```python 210 | def area(x1, y1, x2, y2, x3, y3): 211 | try: 212 | if valid_triangle(x1, y1, x2, y2, x3, y3): 213 | return 0.5 * abs((x1 * y2 + x2 * y3 + x3 * y1) - (y1 * x2 + y2 * x3 + y3 * x1)) 214 | return 0 215 | except ZeroDivisionError: 216 | return -1 217 | ``` 218 | 219 | ### Question 8f - Point in Triangle 220 | 221 | ```python 222 | def point_inside_triangle(x1, y1, x2, y2, x3, y3, m, n): 223 | at = area(x1, y1, x2, y2, x3, y3) 224 | a1 = area(x1, y1, x2, y2, m, n) 225 | a2 = area(x1, y1, m, n, x3, y3) 226 | a3 = area(m, n, x2, y2, x3, y3) 227 | 228 | if a1 == -1: 229 | a1 = 0 230 | if a2 == -1: 231 | a2 = 0 232 | if a3 == -1: 233 | a3 = 0 234 | 235 | if at == a1 + a2 + a3: 236 | return True 237 | return False 238 | ``` 239 | -------------------------------------------------------------------------------- /Spring21/week11/Solutions.md: -------------------------------------------------------------------------------- 1 | ## Files 2 | 3 | ### Q1 4 | 5 | ```python 6 | with open('data/paragraph.txt', 'r') as f_read: 7 | content = f_read.read() 8 | lines = content.split('.') 9 | with open('paragraph_splitted.txt', 'w') as f_write: 10 | for line in lines: 11 | f_write.write(line + '\n') 12 | ``` 13 | 14 | ```python 15 | f_read = open('data/paragraph.txt', 'r') 16 | content = f_read.read() 17 | f_read.close() 18 | lines = content.split('.') 19 | f_write = open('paragraph_splitted.txt', 'w') 20 | for line in lines: 21 | f_write.write(line + '\n') 22 | f_write.close() 23 | ``` 24 | 25 | ### Q2 26 | 27 | ```python 28 | filename = input() 29 | input_f = open(filename, 'r') 30 | output_f = open('output.txt', 'w') 31 | for line in input_f: 32 | output_f.write(line[::-1]) 33 | input_f.close() 34 | output_f.close() 35 | ``` 36 | 37 | ### Q3 38 | 39 | ```python 40 | filename = input() 41 | f = open(filename, 'r') 42 | content = f.read() 43 | words = content.split(' ') 44 | print(' '.join(sorted(words))) 45 | f.close() 46 | ``` 47 | 48 | ### Q4 49 | 50 | ```python 51 | with open('input.txt','r') as f: 52 | words = [line.strip() for line in f.readlines()] 53 | alphas = [word for word in words if word.isalpha()] 54 | 55 | with open('output.txt','w') as f: 56 | f.write("\n".join([word +'s' if word[-1] != 'y' else word[:-1]+'ies' for word in alphas])) 57 | ``` 58 | 59 | ### Q5 60 | 61 | ```python 62 | with open("grades.txt", 'r') as f: 63 | mt1 = [str(max(0, int(grade))) for grade in f.readline().split()] 64 | mt2 = [str(max(0, int(grade))) for grade in f.readline().split()] 65 | final = [str(max(0, int(grade))) for grade in f.readline().split()] 66 | 67 | with open("corrected.txt", 'w') as f: 68 | f.write(' '.join(mt1)) 69 | f.write('\n') 70 | f.write(' '.join(mt2)) 71 | f.write('\n') 72 | f.write(' '.join(final)) 73 | ``` 74 | 75 | ### Q6 76 | 77 | ```python 78 | with open("corrected.txt", 'r') as f: 79 | mt1 = [float(grade) for grade in f.readline().split()] 80 | mt2 = [float(grade) for grade in f.readline().split()] 81 | final = [float(grade) for grade in f.readline().split()] 82 | n = len(mt1) 83 | avg = 0.3 * sum(mt1) / n + 0.3 * sum(mt2) / n + 0.4 * sum(final) / n 84 | # avg = sum([0.3*mt1[i] + 0.3 * mt2[i] + 0.4 * final[i] for i in range(n)])/n 85 | print('{:.2f}'.format(avg)) 86 | ``` 87 | 88 | ## Dictionaries 89 | 90 | ### Q1 91 | 92 | ```python 93 | elements = [10, 4.20, False, 'Word', 'CMPE150', 30, 3.5, 9.99, 'oblivion', True, 68, 88, "88"] 94 | element_dict = {} 95 | for el in elements: 96 | if el not in element_dict: 97 | element_dict[type(el)] = [el] 98 | else: 99 | element_dict[type(el)].append(el) 100 | for el_type, el_list in element_dict.items(): 101 | print(el_type, '->', el_list) 102 | ``` 103 | 104 | ### Q2 105 | 106 | ```python 107 | sentence = input() 108 | my_dict = dict() 109 | total_letter =0 110 | for letter in sentence: 111 | if letter.isalpha(): 112 | letter = letter.lower() 113 | total_letter += 1 114 | if letter not in my_dict: 115 | my_dict[letter] = 1 116 | else: 117 | my_dict[letter] += 1 118 | 119 | sorted_dict = sorted(my_dict.items(), key=lambda x: (-x[1], x[0])) 120 | for k,v in sorted_dict: 121 | print(k,"->","{:.2f}".format(v/total_letter)) 122 | ``` 123 | 124 | ### Q3 125 | 126 | ```python 127 | list1 = ["melih", "burak", "ahmet", "recep", "melis"] 128 | list2 = [1,2,3,4,5] 129 | def dict_2_lists(list1, list2): 130 | return dict(zip(list1, list2)) 131 | 132 | print(dict_2_lists(list1,list2)) 133 | ``` 134 | 135 | ### Q4 136 | 137 | ```python 138 | def merge(*dicts): 139 | mydict = dict() 140 | for d in dicts: 141 | for k, v in d.items(): 142 | if k in mydict: 143 | mydict[k].append(d[k]) 144 | else: 145 | mydict[k] = [v] 146 | return mydict 147 | 148 | print(merge({"A": 1, "B": 2} , {"A": 3})) 149 | ``` 150 | 151 | #### Q5 152 | 153 | ```python 154 | lines = [] 155 | line = str(input()) 156 | while line != "exit": 157 | lines.append(line) 158 | line = str(input()) 159 | 160 | mydict = {} 161 | for line in lines: 162 | line = line.split() # transform into a list 163 | info = {'genre' : line[1], 'release_date': line[2], 'producer':line[3]} 164 | mydict[line[0]] = info 165 | print(mydict) 166 | ``` 167 | 168 | ### Q6 169 | 170 | ```python 171 | def sort_dict(d): 172 | return sorted(d.items(), key=lambda x: x[1], reverse=True) 173 | 174 | print(sort_dict({3:1, 2:2, 1:3})) 175 | ``` 176 | 177 | ### Q7 178 | 179 | ```python 180 | mylist = str(input()).split() 181 | mydict = {} 182 | 183 | for i in mylist: 184 | mydict[i] = 1 if mydict.get(i) is None else mydict[i] + 1 185 | for i in sorted(mydict, key=mydict.get, reverse=True): 186 | print(i, end = " ") 187 | ``` 188 | 189 | ### Q8 190 | 191 | ```python 192 | word_list = ["percussion", "supersonic", "car", "tree", "boy", "girl", "arc"] 193 | 194 | def freq(word): 195 | freq_dict = {} 196 | for char in word: 197 | freq_dict[char] = freq_dict.get(char, 0) + 1 198 | return freq_dict 199 | 200 | anagram_list = [] 201 | for word_1 in word_list: 202 | for word_2 in word_list: 203 | if word_1 != word_2 and (freq(word_1) == freq(word_2)): 204 | anagram_list.append(word_1) 205 | print(anagram_list) 206 | ``` 207 | 208 | -------------------------------------------------------------------------------- /Spring21/week11/data/paragraph.txt: -------------------------------------------------------------------------------- 1 | Eating raw fish didn't sound like a good idea. "It's a delicacy in Japan," didn't seem to make it any more appetizing. Raw fish is raw fish, delicacy or not -------------------------------------------------------------------------------- /Spring21/week12/External Libraries.md: -------------------------------------------------------------------------------- 1 | # External Libraries 2 | 3 | ## Outline 4 | 5 | * How to Install External Libraries 6 | * Widely used Python libraries: Numpy and Pandas 7 | * **Demo:** Exploring ‘Game Of Thrones’ Battles 8 | 9 | ## How to Install External Libraries 10 | 11 | ![img](https://pypi.org/static/images/logo-large.72ad8bf1.svg) 12 | 13 | * The Python Package Index (PyPI) is a repository of software for the Python programming language. 14 | 15 | **~ 310K packages** 16 | 17 | * To install these packages, a package manager is required. PIP is the default package installer for Python. The packages can be downloaded by running the following command on the command line: 18 | 19 | ```bash 20 | pip install 21 | ``` 22 | 23 | * However, the projects could have the same dependency, but depend on incompatible versions of the shared package. For example, you can have ProjectA and ProjectB depending on packageX where ProjectA requires the first version of packageX and ProjectB requires the second version of packageX which are not compatible. If you use the same "environment" for both projects, Python cannot differentiate between these versions. Thus, we need separate environments for projects. 24 | 25 | * We can create a new virtual environment while creating a new project in PyCharm: 26 | 27 | ![1623750783722](figures/1623750783722.png) 28 | 29 | * When we open the terminal after the project is created, we can see that the environment is activated (the name of the virtual environment in brackets). 30 | 31 | ![1623751368006](figures/1623751368006.png) 32 | 33 | * We need the following libraries for this session: 34 | 35 | * Numpy (NumericalPython) 36 | * Pandas (Data Manipulation) 37 | * Scikit-Learn (Machine Learning) 38 | * Matplotlib (Visualization) 39 | * Seaborn (Extension of Matplotlib) 40 | * Jupyter Notebook (Web based application for documents) 41 | 42 | * To install the required packages, open the terminal and run these lines: 43 | 44 | ```bash 45 | pip install numpy 46 | ``` 47 | 48 | ```bash 49 | pip install pandas 50 | ``` 51 | 52 | ```bash 53 | pip install scikit-learn 54 | ``` 55 | 56 | ```bash 57 | pip install matplotlib 58 | ``` 59 | 60 | ```bash 61 | pip install seaborn 62 | ``` 63 | 64 | ```bash 65 | pip install notebook 66 | ``` 67 | 68 | * If the installation is completed successfully, you can open Jupyter Notebook by typing `jupyter-notebook` on the command line. 69 | 70 | ![1623752067689](figures/1623752067689.png) 71 | 72 | 73 | ## Widely used Python libraries: Numpy and Pandas: available [here](Widely%20used%20Python%20libraries%20Numpy%20and%20Pandas.ipynb) as a jupyter notebook 74 | ## Exploring ‘Game Of Thrones’ Battles: available [here](Exploring%20'Game%20of%20Thrones'%20Battles.ipynb) as a jupyter notebook 75 | 76 | 77 | -------------------------------------------------------------------------------- /Spring21/week12/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | # Dictionaries 6 | 7 | ## Question 1 - Name Length to Age Ratio 8 | 9 | Write a function that takes a dictionary consisting of string:int values. 10 | The key values are names of and int are their ages. 11 | You need to return a list that contains their name length to age ratio in order. 12 | Note: Don't count spaces 13 | 14 | **Example-1 code snippet:** 15 | 16 | ``` 17 | a = {"Frederick Vought": 103, "Homelander": 52, "William Butcher": 56} 18 | 19 | print(name_to_age_ratio(a)) 20 | ``` 21 | 22 | **Example-1 Expected Output:** 23 | 24 | ``` 25 | [0.14563106796116504, 0.19230769230769232, 0.25] 26 | ``` 27 | 28 | **Example-2 code snippet:** 29 | 30 | ``` 31 | b = {"Sirus": 6012, "Maven": 9901, "Kalandra": 5123} 32 | 33 | print(name_to_age_ratio(b)) 34 | ``` 35 | 36 | **Example-2 Expected Output:** 37 | 38 | ``` 39 | [0.00083166999334664, 0.000504999495000505, 0.0015615850087839158] 40 | ``` 41 | 42 | ## Question 2 - Word Frequency 43 | 44 | Write a program that prompts the user for a sentence. Split the sentence into words and store the frequency of each word (number of occurrences). Then print the words in a sorted manner from most common to the least common. If there is a tie, print the word that comes first in the original sentence. 45 | 46 | *Hint: You can use sorted(dict_, key=dict_.get) function to sort a dictionary according to the values. In order to get the reversed version of this, add reverse = True parameter.* 47 | 48 | | INPUT | OUTPUT | 49 | | ------------------------------------------------------------ | ------------------------------------------------------- | 50 | | "one two two three three four four four four" | "four two three one" | 51 | | "fair is foul and foul is fair" | "fair is foul and" | 52 | | "How much wood would a woodchuck chuck if a woodchuck could chuck wood?" | "a woodchuck chuck How much wood would if could wood? " | 53 | 54 | ## Question 3 - Vasya - Clerk 55 | 56 | The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 dollar bill. An "Avengers" ticket costs 25 dollars. 57 | 58 | Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line. 59 | 60 | Can Vasya sell a ticket to every person and give change if he initially has no money and sells the tickets strictly in the order people queue? 61 | 62 | Return YES, if Vasya can sell a ticket to every person and give change with the bills he has at hand at that moment. Otherwise return NO. 63 | 64 | | Input | Output | Explanation | 65 | | --------------------- | ------ | ------------------------------------------------------------ | 66 | | [25, 25, 50] | YES | | 67 | | [25, 100] | NO | Vasya will not have enough money to give change to 100 dollars | 68 | | [25, 25, 50, 50, 100] | NO | Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50) | 69 | 70 | # Sets 71 | 72 | ## Question 1 - Set Operations 73 | 74 | Write a function that takes two sets then prints union, intersection and difference operations between them. 75 | 76 | | Input | Output | 77 | | ------------------------------------------- | ------------------------------------------------------------ | 78 | | A = {1, 2, 3, 4, 5, 6} B = {1, 1, 2, 7, 11} | A ∪ B = {1, 2, 3, 4, 5, 6, 7, 11} A ∩ B = {1, 2} A / B = {3, 4, 5, 6} B / A = {11, 7} | 79 | 80 | ## Question 2 - Eligible to graduate? 81 | 82 | You are given 2 sets one of which is the set of all courses that has to be taken to graduate from CmpE department. Other one is the courses that has been taken by a student so far. Write a function indicating whether student can graduate or not. 83 | 84 | | Input | Output | 85 | | ------------------------------------------------------------ | ------------ | 86 | | {"CmpE150","CmpE160","CmpE220","CmpE250","CmpE260"} {"Cmpe150"} | Not Eligible | 87 | 88 | ## Question 3 - How good friends can they be? 89 | 90 | People need to have common things to be friends. Let's say we have a set for every person consisting of the ID's of their personality traits. Two people can make as better friendship as the sum of their common personality trait IDs. Write a function that calculates the sum of common personality trait IDs. 91 | 92 | | Input | Output | 93 | | --------------------- | ------ | 94 | | {1,2,3,4,5} {4,5,6,7} | 9 | 95 | 96 | ## Question 4 - Distinct 97 | 98 | A distinct string is a string whose all characters occurs only once. 99 | 100 | Write a function that takes a string as an argument and checks whether given string is distinct or not. 101 | 102 | | Input | Output | 103 | | --------------------- | ------ | 104 | | dwarf | True | 105 | | violate | True | 106 | | violation | False | 107 | -------------------------------------------------------------------------------- /Spring21/week12/Solutions.md: -------------------------------------------------------------------------------- 1 | # Dictionaries 2 | 3 | ## Question 1 4 | 5 | ```python 6 | def name_to_age_ratio(a): 7 | result = [] 8 | for name, age in a.items(): 9 | total_characters = sum([len(word) for word in name.split()]) 10 | result.append(totalCharacters / age) 11 | return result 12 | ``` 13 | 14 | ### Alternative 15 | 16 | ```python 17 | def name_to_age_ratio(info): 18 | results = [] 19 | for name in info: 20 | results.append(sum([for ch in name if not ch.isspace()]) / info[name]) 21 | return results 22 | ``` 23 | 24 | ## Question 2 25 | 26 | ```python 27 | mylist = str(input()).split() 28 | mydict = {} 29 | 30 | for i in mylist: 31 | mydict[i] = 1 if mydict.get(i) is None else mydict[i] + 1 32 | for i in sorted(mydict, key = mydict.get, reverse = True): 33 | print(i, end = " ") 34 | ``` 35 | 36 | ### Alternative 37 | 38 | ```python 39 | words = str(input()).split() 40 | counts = {} 41 | for word in words: 42 | # counts[word] = counts.get(word, 0) + 1 43 | if word not in counts: 44 | counts[word] = 1 45 | else: 46 | counts[word] += 1 47 | counts_sorted = sorted(counts, key=counts.get, reverse=True) # returns words 48 | print(' '.join(counts_sorted)) 49 | ``` 50 | 51 | ## Question 3 52 | 53 | ```python 54 | def tickets(people): 55 | change = {25: 0, 50: 0, 100: 0} 56 | for money in people: 57 | if money == 25: 58 | change[25] += 1 59 | elif money == 50: 60 | change[25] -= 1 61 | change[50] += 1 62 | elif money == 100 and change[50] > 0: 63 | change[25] -= 1 64 | change[50] -= 1 65 | elif money==100 and change[50] == 0: 66 | change[25] -= 3 67 | 68 | if change[25] < 0 or change[50] < 0: 69 | return 'NO' 70 | return 'YES' 71 | 72 | print(tickets([25, 25, 50])) # => YES 73 | print(tickets([25, 100])) # => NO. Vasya will not have enough money to give change to 100 dollars 74 | print(tickets([25, 25, 50, 50, 100])) # => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50) 75 | ``` 76 | 77 | # Sets 78 | 79 | ## Question 1 80 | 81 | ```python 82 | A = {1, 2, 3, 4, 5, 6} 83 | B = {1, 1, 2, 7, 11} 84 | 85 | def set_operations(set1, set2): 86 | print("A ∪ B = {}".format(set1.union(set2))) 87 | print("A ∩ B = {}".format(set1.intersection(set2))) 88 | print("A / B = {}".format(set1.difference(set2))) 89 | print("B / A = {}".format(set2.difference(set1))) 90 | 91 | set_operations(A, B) 92 | ``` 93 | 94 | ## Question 2 95 | 96 | ```python 97 | required = {"CmpE150","CmpE160","CmpE220","CmpE250","CmpE260"} 98 | def is_eligible(current): 99 | if len(required.intersection(current)) == len(required): 100 | return "Eligible" 101 | else: 102 | return "Not Eligible" 103 | print(is_eligible({"Cmpe150"})) 104 | ``` 105 | 106 | ## Question 3 107 | 108 | ```python 109 | def overall_traits(traits1, traits2): 110 | intersection = traits1.intersection(traits2) 111 | return sum(intersections) 112 | ``` 113 | 114 | ## Question 4 115 | 116 | ```python 117 | def is_distinct(string): 118 | return len(set(string)) == len(string) 119 | 120 | print(is_distinct('violate')) 121 | ``` 122 | 123 | -------------------------------------------------------------------------------- /Spring21/week12/figures/1623750783722.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/week12/figures/1623750783722.png -------------------------------------------------------------------------------- /Spring21/week12/figures/1623751368006.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/week12/figures/1623751368006.png -------------------------------------------------------------------------------- /Spring21/week12/figures/1623752067689.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Spring21/week12/figures/1623752067689.png -------------------------------------------------------------------------------- /Teaching.CodesProjectGuide.md: -------------------------------------------------------------------------------- 1 | ## Teaching.Codes Project Guide 2 | 3 | You can find the PDF version of this file [here](Teaching.CodesProjectGuide.pdf) 4 | 5 | - Open Teaching.Codes plugin. Enter your user name/password and click **Login.** 6 | 7 | 1618485979513 8 | 9 | If you have login issues, send an email to the mail address of your section: cmpe150.mail@gmail.com. Please include the error messages/screenshots. 10 | 11 | - If you have logged in successfully, you will see the **Navigator window**: 12 | 13 | 1618486104949 14 | 15 | ​ Select the term and double click on your section: 16 | 17 | 1618486398394 18 | 19 | ​ When the content of the course is loaded, a Welcome message will appear like below: 20 | 21 | 1618486497781 22 | 23 | - After you see the welcome message, you can navigate to **Projects** tab by clicking on it. You can find the assigned projects under this tab. 24 | 25 | 1618486752521 26 | 27 | ​ To open a project, click on the project and then **Open** button. 28 | 29 | 30 | 31 | ​ This will download and open the project. When the project is opened, you will see a new project named **questionXXX** under Project Explorer: 32 | 33 | 1618487934948 34 | 35 | ​ You will also see **Submit** and **Description** buttons under the project: 36 | 37 | 1618487098652 38 | 39 | - Click **Description** button to see the project description. The description will be available under **Content Browser**. Please read the description carefully and check the input/output examples. 40 | 41 | 1618487165943 42 | 43 | ​ You can also view the description in your favorite browser. To do this, click on the project (i.e. questionXXX) under Project Explorer, open **WebContent** directory and find the file named **Question.html.** Then, right click on this file and move to **Open in** and select **Browser**. 44 | 45 | 1618487273664 46 | 47 | - To write your code, click on the project (i.e. **questionXXX**), open **src** directory and click **Main.py**. This will open this file in the editor and you will see the code provided to you. You must write your code to this file between the comments (i.e. # DO_NOT_EDIT_ANYTHING_ABOVE_THIS_LINE and # DO_NOT_EDIT_ANYTHING_BELOW_THIS_LINE). You are **NOT ALLOWED TO MODIFY** these comments or anything outside the region marked by the comments. If you delete/modify these statements, you can restore them from **Main.py.txt** 48 | 49 | 1618487070207 50 | 51 | - After you write your solution, please make sure that 52 | 53 | - You write your solution to **Main.py** (Not Main.py.txt) 54 | - You do not modify/delete the statements already given to to you. *You can compare these statements with the ones in Main.py.txt* 55 | - You do not use any import's. 56 | - The input and output of your code are exactly same with the input/outputs in the description. (*You don't have unnecessary input or print statements*) 57 | 58 | Then, you can submit your code by clicking **Submit** button. 59 | 60 | 1618487098652 61 | 62 | If your submission is successful, the following window will pop up: 63 | 64 | 1618487440503 65 | 66 | You can submit many times. The last version you submit before the deadline will be graded. 67 | 68 | If you can't submit successfully, send an email explaining your situation before the deadline. 69 | -------------------------------------------------------------------------------- /Teaching.CodesProjectGuide.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/Teaching.CodesProjectGuide.pdf -------------------------------------------------------------------------------- /TeachingCodesGuide.md: -------------------------------------------------------------------------------- 1 | ## Teaching.Codes Exam/Quiz/Project Guide 2 | 3 | **Quiz/Exam Guide Playlist: https://www.youtube.com/playlist?list=PLgnOcaYXEY3lEkkwZPPFV0FcXtVLhnKdB** 4 | 5 | 1. Teaching.Codes Login (https://youtu.be/AQX5aZXDSz8) 6 | 7 | You must **make sure that you can login** to your Teaching.Codes accounts before the Quiz. 8 | 9 | 2. Taking the Quiz (https://youtu.be/T1kNINEEPmI) 10 | 11 | This video shows you how a Quiz looks like, and how you submit your solutions. 12 | 13 | Note that the quiz in the video contains only one question; however, there might be multiple questions in an exam or a quiz. If that's the case, then you are supposed to write your solution to corresponding questionXXX/src/Main.py. Please see the example below that shows the correspondence between the questions displayed on the Teaching.Codes plugin and the project folders under Project window. **Make sure you write your code to the correct file.** 14 | 15 | ![](figures/correspondence.png) 16 | 17 | If there are multiple questions in an exam, please 18 | 19 | 3. Problems Encountered during the Quiz (https://youtu.be/1X0weYP8dyQ) 20 | 21 | Please watch the solutions to the **problems encountered during the Quiz**, so that you may take some precautions beforehand. 22 | 23 | At the end of the video, we show you how to open question description if you can't see it via Teaching Codes. The solution in the video can sometimes give inconsistent results. So here is the updated solution: 24 | 25 | 1. Right click on the html file 26 | 2. Choose "**Show in Explorer/Finder**". This step open the folder that contains the html file. 27 | 3. From the folder, open the html file. 28 | 29 | You can find all videos inside this playlist (https://www.youtube.com/playlist?list=PLgnOcaYXEY3lEkkwZPPFV0FcXtVLhnKdB). 30 | 31 | 4. Teaching.Codes Window disappeared 32 | 33 | You can open it by clicking View>Tool Windows>Teaching.Codes 34 | 35 | 5. Open Grades 36 | 37 | In order to reach your grades, 38 | 39 | 1. Login to your Teaching.Codes account in PyCharm. 40 | 2. Select your class (double-click your class under ***Navigator***). 41 | 3. Check out your grade under ***ExamResults***. 42 | 43 | 44 | ## Teaching.Codes Plugin Update 45 | 46 | To update Teaching.Codes, **you need to uninstall and reinstall the Teaching.Codes plugin**. Please follow these steps: 47 | 48 | 1. Download: 49 | 50 | Windows: https://programming.cmpe.boun.edu.tr/downloads/StudentPlugin/TCPluginJetBrains_Windows.zip 51 | 52 | Linux: https://programming.cmpe.boun.edu.tr/downloads/StudentPlugin/TCPluginJetBrains_Linux.zip 53 | 54 | MacOS: https://programming.cmpe.boun.edu.tr/downloads/StudentPlugin/TCPluginJetBrains_MacOS.zip 55 | 56 | If you're using MacOS, please download the .zip file using **Chrome instead of Safari** to avoid any issues. 57 | 58 | 2. Open PyCharm. 59 | 60 | 3. Inside PyCharm, for Windows, click ***File-->Settings***; for MacOS, click ***PyCharm-->Preferences*** and find ***Plugins*** on the left. 61 | 62 | 4. Go into ***Plugins***, and select the ***Teaching Codes JB*** plugin. From the right, click **the arrow next to the *Disable* button**, and select ***Uninstall***. Select ***Yes*** if it asks for confirmation. 63 | 64 | ![Teaching.Codes Uninstall](figures/Teaching.Codes Uninstall.png) 65 | 66 | 5. **When the uninstallation is complete, click OK, and then** **close PyCharm**. 67 | 68 | 6. **Apply steps 2 and 3**. Go into ***Plugins***, click ***the gear icon*** on the top, and select ***Install Plugin from Disk…*** 69 | 70 | Navigate to the location of the zip file you've downloaded from the link above (TCPluginJetBrains_XXX.zip) and choose it. 71 | 72 | 7. After installation is complete, press the ***Restart IDE*** button appeared on the Teaching Codes plugin, or click ***OK***, and then **restart PyCharm** manually. 73 | 74 | When you restart PyCharm, the Teaching.Codes plugin may not appear on your window. Click ***View-->Tool Windows-->Teaching.Codes*** 75 | 76 | 77 | -------------------------------------------------------------------------------- /figures/1616341138563.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/1616341138563.png -------------------------------------------------------------------------------- /figures/1616342184949.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/1616342184949.png -------------------------------------------------------------------------------- /figures/1616342517499.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/1616342517499.png -------------------------------------------------------------------------------- /figures/ChangeTheme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/ChangeTheme.png -------------------------------------------------------------------------------- /figures/HTML_Browser.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/HTML_Browser.png -------------------------------------------------------------------------------- /figures/HTML_Explorer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/HTML_Explorer.png -------------------------------------------------------------------------------- /figures/Maintxt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/Maintxt.png -------------------------------------------------------------------------------- /figures/TC.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/TC.png -------------------------------------------------------------------------------- /figures/Teaching.Codes New Version.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/Teaching.Codes New Version.png -------------------------------------------------------------------------------- /figures/Teaching.Codes Uninstall.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/Teaching.Codes Uninstall.png -------------------------------------------------------------------------------- /figures/Teaching.Codes Version 1212JB.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/Teaching.Codes Version 1212JB.png -------------------------------------------------------------------------------- /figures/commit_and_push_failed1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/commit_and_push_failed1.png -------------------------------------------------------------------------------- /figures/commit_and_push_failed2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/commit_and_push_failed2.png -------------------------------------------------------------------------------- /figures/connection.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/connection.PNG -------------------------------------------------------------------------------- /figures/correspondence.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/correspondence.png -------------------------------------------------------------------------------- /figures/could not open.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/could not open.PNG -------------------------------------------------------------------------------- /figures/project-guide/1618485979513.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/project-guide/1618485979513.png -------------------------------------------------------------------------------- /figures/project-guide/1618486104949.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/project-guide/1618486104949.png -------------------------------------------------------------------------------- /figures/project-guide/1618486398394.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/project-guide/1618486398394.png -------------------------------------------------------------------------------- /figures/project-guide/1618486497781.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/project-guide/1618486497781.png -------------------------------------------------------------------------------- /figures/project-guide/1618486752521.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/project-guide/1618486752521.png -------------------------------------------------------------------------------- /figures/project-guide/1618486890025.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/project-guide/1618486890025.png -------------------------------------------------------------------------------- /figures/project-guide/1618487070207.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/project-guide/1618487070207.png -------------------------------------------------------------------------------- /figures/project-guide/1618487098652.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/project-guide/1618487098652.png -------------------------------------------------------------------------------- /figures/project-guide/1618487165943.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/project-guide/1618487165943.png -------------------------------------------------------------------------------- /figures/project-guide/1618487273664.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/project-guide/1618487273664.png -------------------------------------------------------------------------------- /figures/project-guide/1618487440503.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/project-guide/1618487440503.png -------------------------------------------------------------------------------- /figures/project-guide/1618487934948.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/project-guide/1618487934948.png -------------------------------------------------------------------------------- /figures/python-customize.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/python-customize.png -------------------------------------------------------------------------------- /figures/python-final.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/python-final.png -------------------------------------------------------------------------------- /figures/python-optional.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/figures/python-optional.png -------------------------------------------------------------------------------- /spring2022/ReadME: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /spring2022/python2022spring22/week10/README.md: -------------------------------------------------------------------------------- 1 | # Week 10 2 | 3 | ## Question 1 - What is your Type? 4 | 5 | Write a program that only prints the strings and integers from a given list. The outputs should look like the example 6 | 7 | | INPUT | OUTPUT | 8 | | ------------------------- | ------------------------------------------------------------ | 9 | |["pasta",14, False, "True", 3.5,"makarna",(3,8),12] | pasta 14 True makarna 12 | 10 | |[13,51.5,(False,3),"9"] | 13 9 | 11 | 12 | ## Question 2 - Slice and Dice 13 | 14 | Write a program that takes a list. If the list has more than 5 items in it and the number of items is odd, the program prints the list without the 3 items in the middle. If the list is shorter than 5 or the number of items are even, the original list is printed. 15 | 16 | | INPUT | OUTPUT | 17 | | ------------------------- | ------------------------------------------------------------ | 18 | |[3,325,12365,21,41,3,5,1,5] | [3, 325, 12365, 5, 1, 5] | 19 | |["horse","chicken","pig","lamb","cow","ox","rooster","dog"] | ["horse","chicken","pig","lamb","cow","ox","rooster","dog"] | 20 | |[1,22,333,444] | [1,22,333,444] | 21 | 22 | ## Question 3 - To the left, to the left 23 | 24 | Write a function that takes a list and an integer N and shift the every member by N number to the left and return the new shifted list back. 25 | 26 | 27 | | INPUT | OUTPUT | 28 | | ------------------------- | ------------------------------------------------------------ | 29 | | N=3
["everything","you","own","in","the", "box"] | ["in","the", "box","everything", "you", "own"] | 30 | | N=11
["i","r","r","e","p","l","a","c","a","b","l","e"] | ['a', 'b', 'l', 'e', 'i', 'r', 'r', 'e', 'p', 'l', 'a', 'c'] | 31 | 32 | ## Question 4 - The Odd Ones 33 | 34 | Write a function that takes a lists and remove the odd integers from the list and return the list with only even integers. 35 | 36 | | INPUT | OUTPUT | 37 | | ------------------------- | ------------------------------------------------------------ | 38 | | [1,5,2,3,5,6,82,63,5,6,12,5,436] | [2, 6, 82, 6, 12, 436] | 39 | | [0,12,4,21,53,346,234] | [0, 12, 4, 346, 234] | 40 | 41 | ## Question 5 - Let's add on that! 42 | 43 | Write a function that takes a list full of integers that adds every 2 consecutive items together and returns a list with the addition results between the added items. 44 | 45 | | INPUT | OUTPUT | 46 | | ------------------------- | ------------------------------------------------------------ | 47 | | [1,3,5,7,8] | [1, 4, 3, 8, 5, 12, 7, 15, 8] | 48 | | [3,5,4,124,5,3,9,7] | [3, 8, 5, 9, 4, 128, 124, 129, 5, 8, 3, 12, 9, 16, 7] | 49 | 50 | ## Question 6 - The Cloning Machine 51 | 52 | Write a function that takes a list of integers and duplicates them by their value and returns the list with the duplicates. 53 | 54 | | INPUT | OUTPUT | 55 | | ------------------------- | ------------------------------------------------------------ | 56 | | [1,2,3,4,5] | [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5] | 57 | | [3,2,6,9,3,1] | [3, 3, 3, 2, 2, 6, 6, 6, 6, 6, 6, 9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 3, 3, 1] | 58 | 59 | ## Question 7 - Assassination 60 | 61 | Write a function that takes a list and returns a list without the "N"th item on that list. 62 | 63 | Hint= You can use pop(), remove() functions. 64 | 65 | | INPUT | OUTPUT | 66 | | ------------------------- | ------------------------------------------------------------ | 67 | | ["apples","oranges", "JFK", "potato","tomato"]
3 | ["apples","oranges","potato","tomato"] | 68 | | ["euro","dollar","won","yen","tl"]
5 | ["euro","dollar","won","yen"] | 69 | 70 | ## Question 8 - Flip It and Reverse It 71 | 72 | Write a program that takes a list of strings from the user and store them in a list until it reads ".". Then, it reverses the each string and reverses the order of the strings and prints the result as a single string without the ".". 73 | 74 | | INPUT | OUTPUT | 75 | | ------------------------- | ------------------------------------------------------------ | 76 | |I
put
my
thang
down
flip
it
and
reverse
it
. | ti esrever dna ti pilf nwod gnaht ym tup I | 77 | 78 | ## Question 9 - Sorter Hat 79 | 80 | Write a program that takes a list of strings or list of integers and prints the list in alphabetical order/ascending order. 81 | 82 | | INPUT | OUTPUT | 83 | | ------------------------- | ------------------------------------------------------------ | 84 | | [1,5,54,312,52,9] | [1, 5, 9, 52, 54, 312] | 85 | | ["Slytherin","Gryffindor", "Ravenclaw","Hufflepuff"] | ['Gryffindor', 'Hufflepuff', 'Ravenclaw', 'Slytherin'] | 86 | 87 | ## Question 10 - Popular Item 88 | 89 | Write a function that finds the most recurring integer in list of integers and prints that integer. 90 | 91 | | INPUT | OUTPUT | 92 | | ------------------------- | ------------------------------------------------------------ | 93 | | [3,2,1,2,2,2,3,1,1,3,2,5,1] | 2 | 94 | -------------------------------------------------------------------------------- /spring2022/python2022spring22/week10/ps7 chapter list week10.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/spring2022/python2022spring22/week10/ps7 chapter list week10.pptx -------------------------------------------------------------------------------- /spring2022/python2022spring22/week10/solutions.md: -------------------------------------------------------------------------------- 1 | ## Question 1 2 | ```python 3 | list=["pasta",14, False, "True", 3.5,"makarna",(3,8),12] 4 | 5 | for item in list: 6 | if type(item)==str or type(item)==int: 7 | print (item, end=" ") 8 | ``` 9 | 10 | ## Question 2 11 | ```python 12 | the_list=["horse","chicken","pig","lamb","cow","ox","rooster"] 13 | 14 | if len(the_list)>= 5 and len(the_list)%2!=0: 15 | a=len(the_list) 16 | the_list=the_list[0:int((a-3)/2)]+the_list[-int((a-3)/2):a] 17 | print(the_list) 18 | else: 19 | print(the_list) 20 | ``` 21 | 22 | ## Question 3 23 | ```python 24 | def to_the_left(list,N): 25 | return list[N:] + list[:N] 26 | 27 | print(to_the_left(["i","r","r","e","p","l","a","c","a","b","l","e"], 8)) 28 | ``` 29 | ## Question 4 30 | ``` python 31 | def remove_odd_ones(list): 32 | return [value for value in list if value%2!= 1] 33 | 34 | print(remove_odd_ones([0,12,4,21,53,346,234])) 35 | ``` 36 | ## Question 5 37 | ```python 38 | def adding_additions(list): 39 | new_list=[] 40 | for i in range(0,len(list)-1): 41 | addition=list[i]+list[i+1] 42 | new_list.append(list[i]) 43 | new_list.append(addition) 44 | new_list.append(list[len(list)-1]) 45 | 46 | return new_list 47 | 48 | print(adding_additions([1,3,5,7,8])) 49 | ``` 50 | ## Question 6 51 | ```python 52 | def create_duplicates(list): 53 | result = [] 54 | for item in list: 55 | for i in range(item): 56 | result.append(item) 57 | 58 | return result 59 | 60 | 61 | print(create_duplicates([3,2,6,9,3,1])) 62 | ``` 63 | ## Question 7 64 | ```python 65 | def popper(list,N): 66 | list.pop(N-1) 67 | return list 68 | 69 | def remover(list,N): 70 | Nth_item= list[N-1] 71 | for item in list: 72 | if item==Nth_item: 73 | list.remove(item) 74 | 75 | return list 76 | 77 | print(remover(["apples","oranges", "JFK", "potato","tomato"],3)) 78 | ``` 79 | ## Question 8 80 | ```python 81 | N=str(input()) 82 | list_of_strings=[N] 83 | 84 | while N != ".": 85 | N=str(input()) 86 | list_of_strings.append(N) 87 | 88 | def reverse_strings(string): 89 | return " ".join([letter[::-1] for letter in string.split()]) 90 | 91 | result=[] 92 | 93 | for string in list_of_strings: 94 | string=reverse_strings(string) 95 | result.append(string) 96 | 97 | result.reverse() 98 | 99 | def join_strings_as_one(strings): 100 | return " ".join(string if string!="." else "" for string in strings) 101 | 102 | print (join_strings_as_one(result)) 103 | ``` 104 | ## Question 9 105 | ```python 106 | list_of_integers= [1,5,54,312,52,9] 107 | list_of_strings= ["Slytherin","Gryffindor", "Ravenclaw","Hufflepuff"] 108 | 109 | list_of_integers.sort() 110 | list_of_strings.sort() 111 | 112 | print(list_of_integers) 113 | print(list_of_strings) 114 | ``` 115 | ## Question 10 116 | ```python 117 | def counter(list): 118 | the_most_recurring=0 119 | counter=0 120 | 121 | for item in list: 122 | a=list.count(item) 123 | if a>counter: 124 | the_most_recurring=item 125 | counter=a 126 | 127 | return the_most_recurring 128 | 129 | print(counter([3,2,1,2,2,2,3,1,1,3,2,5,1])) 130 | ``` 131 | -------------------------------------------------------------------------------- /spring2022/python2022spring22/week12/README.md: -------------------------------------------------------------------------------- 1 | # Week 12 - Dictionary and Sets 2 | 3 | ## Question 1- Disctinctness 4 | 5 | A distinct string is a string whose all characters occurs only once. Write a function that takes a string as an argument and checks whether given string is distinct or not. 6 | 7 | 8 | | Input | Output | 9 | |-----------| ------ | 10 | | slay | True | 11 | | obliviate | False | 12 | | mahmut | False | 13 | 14 | ## Question 2 - Seperating the Types 15 | 16 | Write a program that takes lists of different types, then seperates the inputs according to their types. The program should print the inputs with their types just like in the example. 17 | 18 | | Input | Output | 19 | | ------------------------------------------------------------ | ---------- | 20 | | ["music",13,True, "black", (26,1),"16", "False","pencil"] | ==> ['music', 'black', '16', 'False', 'pencil']
==> [13]
==> [True]
==> [(26, 1)] | 21 | 22 | ## Question 3 - imdB 23 | 24 | Write a program that reads lines from the input. Each line will be composed of 4 words, name of the movie, genre of the movie, year of release and the director respectively. If a line is equal to "exit", stop reading. Store the games in a dictionary. Their values should also correspond to dictionaries composed of their genre, release_data and director 25 | 26 | | Input | Output | 27 | | ------------------------------------------------------------ | ---------- | 28 | | Black Swan, Thriller, 2010, Darren Aronofsky

Dunkirk, Action, 2017, Christopher Nolan

The Rocky Horror Picture Show, Musical, 1975, Jim Sherman

The Matrix, Sci-Fi, 1999, Wachowski Sisters

exit | {'Black Swan': {'genre': ' Thriller', 'release_date': ' 2010', 'director': ' Darren Aronofsky'}, 'Dunkirk': {'genre': ' Action', 'release_date': ' 2017', 'director': ' Christopher Nolan'}, 'The Rocky Horror Picture Show': {'genre': ' Musical', 'release_date': ' 1975', 'director': ' Jim Sherman'}, 'The Matrix': {'genre': ' Sci-Fi', 'release_date': ' 1999', 'director': ' Wachowski Sisters'}} | 29 | 30 | ## Question 4 - String Who Should Not Be Written 31 | 32 | Anagram is a word formed by rearranging the letters of a different word (heart, earth). Write a program that takes a tuple of two strings and prints out "Anagram" if the tuple has an anagram. 33 | 34 | | Input | Output | 35 | |----------------------------------------------| ---------- | 36 | | ("peach","cheap") | Anagram | 37 | | ("TOM MARVOLO RIDDLE","I AM LORD VOLDEMORT") | Anagram | 38 | 39 | ## Question 5 - Cooking Oil Lines 40 | 41 | The cooking oil prices have just been raised! There are a lot of people at the supermarket check-out line. Each of them has a single 200,100,50 Turkish liras. A liter of cooking oil costs 50 Turkish liras. 42 | 43 | Yiğit is currently working as a cashier. He wants to sell cooking oil to every single person before the prices are raised again next week but he cannot accept credit cards at the moment or has any cash. 44 | 45 | Can Yiğit sell cooking oil (only a liter to each) to every person and give change to all of them strictly in the order of the line? 46 | 47 | Return YES, if Yiğit can sell cooking oil to every person and give change with the bills he has at that moment. Otherwise return NO. 48 | 49 | | Input | Output | Explanation | 50 | | --------------------- | ------ | ------------------------------------------------------------ | 51 | | [50, 50, 100] | YES | | 52 | | [50, 200] | NO | Yiğit will not have enough money to give change to 200 Turkish liras. | 53 | | [50, 50, 100, 100, 200] | NO | Yiğit will not have the right bills to give 150 Turkish liras of change (you can't make two bills of 50 from one of 100) | 54 | 55 | 56 | -------------------------------------------------------------------------------- /spring2022/python2022spring22/week12/Solutions.md: -------------------------------------------------------------------------------- 1 | ## Question 1 - Distinctness 2 | ```python 3 | def is_distinct(string): 4 | print(set(string)) 5 | return len(set(string)) == len(string) 6 | 7 | print(is_distinct('slay')) 8 | ``` 9 | 10 | ## Question 2 - Seperating the Types 11 | ```python 12 | the_list= ["music",13,True, "black", (26,1),"16", "False","pencil"] 13 | the_dictionary= {} 14 | 15 | for item in the_list: 16 | if type(item) not in the_dictionary: 17 | the_dictionary[type(item)]=[item] 18 | else: 19 | the_dictionary[type(item)].append(item) 20 | 21 | for item_type, item_list in the_dictionary.items(): 22 | print(item_type, '->',item_list) 23 | 24 | ``` 25 | 26 | ## Question 3 - imdB 27 | ```python 28 | lines = [] 29 | line = str(input()) 30 | while line != "exit": 31 | lines.append(line) 32 | line = str(input()) 33 | 34 | my_dict = {} 35 | for line in lines: 36 | line = line.split(",") 37 | info = {'genre' : line[1], 'release_date': line[2], 'director':line[3]} 38 | my_dict[line[0]] = info 39 | print(my_dict) 40 | ``` 41 | 42 | ## Question 4 - String Who Should Not Be Written 43 | ```python 44 | the_tuple=("TOM MARVOLO RIDDLE","I AM LORD VOLDEMORT") 45 | 46 | def freq(word): 47 | freq_dict = {} 48 | for char in word: 49 | if char != (" ") : 50 | freq_dict[char] = freq_dict.get(char, 0) + 1 51 | return freq_dict 52 | 53 | if (freq(the_tuple[0])) == (freq(the_tuple[1])): 54 | print ("Anagram") 55 | else: 56 | print("Not an anagram") 57 | ``` 58 | 59 | ## Question 5 - Cooking Oil Lines 60 | ``` python 61 | def cashier(people): 62 | change = {50: 0, 100: 0, 200: 0} 63 | for money in people: 64 | if money == 50: 65 | change[50] += 1 66 | elif money == 100: 67 | change[50] -= 1 68 | change[100] += 1 69 | elif money == 200 and change[100] > 0: 70 | change[50] -= 1 71 | change[100] -= 1 72 | elif money==200 and change[100] == 0: 73 | change[50] -= 3 74 | 75 | if change[100] < 0 or change[50] < 0: 76 | return 'NO' 77 | return 'YES' 78 | 79 | print(cashier([50, 50, 100])) 80 | print(cashier([50, 200])) 81 | print(cashier([50, 50, 100, 100, 200])) 82 | ``` 83 | -------------------------------------------------------------------------------- /spring2022/python2022spring22/week12/ps8 chapter dict week12.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/spring2022/python2022spring22/week12/ps8 chapter dict week12.pptx -------------------------------------------------------------------------------- /spring2022/python2022spring22/week4/lab3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/spring2022/python2022spring22/week4/lab3.pdf -------------------------------------------------------------------------------- /spring2022/python2022spring22/week6/README.md: -------------------------------------------------------------------------------- 1 | # Conditional Execution 2 | 3 | ## Question 1 - Multiple 4 | Write a program which calculates whether any given two numbers are multiples of one another. 5 | 6 | | Input | Output | 7 | | ----- | ------------ | 8 | | 2 4 | Multiple | 9 | | 4 2 | Multiple | 10 | | 5 3 | Not Multiple | 11 | 12 | ## Question 2 - Simple Sort 13 | 14 | ### Question 2a 15 | 16 | Write a program that takes 2 integers from the user and then prints these integeres in an ascending order using a single if statement. 17 | 18 | | Input | Output | 19 | | ----- | ------ | 20 | | 3 5 | 3 5 | 21 | | 5 3 | 3 5 | 22 | 23 | ### Question 2b 24 | 25 | Write a program that takes 3 integers from the user and then prints these integeres in an ascending order 26 | 27 | | Input | Output | 28 | | ----- | ------ | 29 | | 1 3 2 | 1 2 3 | 30 | | 3 2 1 | 1 2 3 | 31 | | 2 3 1 | 1 2 3 | 32 | 33 | ## Question 3 - Leap 34 | A leap year is a calendar year that contains an additional day added to keep the calendar year synchronized with the astronomical year. In the Gregorian calendar, each leap year has 366 days instead of 365, by extending February to 29 days rather than the common 28. 35 | These extra days occur in each year which is an integer multiple of 4, except for the years evenly divisible by 100, but not by 400. Given a year between 1 and 10000, you will write a function that find whether it is a leap year or not. 36 | 37 | | INPUT | OUTPUT | 38 | | :------: | :------: | 39 | | 1005 | not a leap year | 40 | | 4 | leap year | 41 | | 1000 | not a leap year | 42 | | 4000 | leap year | 43 | 44 | ## Question 4 - Parking Fee 45 | A parking lot "Park150" is charging its users as follows: 46 | <= 15 minutes ---> 15 liras 47 | After 15 minutes, users pay 10 liras per hour, as well as the first 15 liras. 48 | Given two integers hour and minute, write a program to calculate and print the total amount the user has to pay. 49 | For example: An input "1 28" means that the customer's car stayed in "Park150" for an hour and 28 minutes. So s/he has to pay 15 + 2\*10 liras. 50 | You can assume that hour and minute will always be non-negative integers and minute will always be less than 60. 51 | | INPUT | OUTPUT | 52 | | :------: | :------: | 53 | | 0 45 | 25 | 54 | | 1 34 | 35 | 55 | | 2 0 | 35 | 56 | | 4 59 | 65 | 57 | 58 | ## Question 5 - GCD 59 | In mathematics, the greatest common divisor (GCD) of two or more integers is the largest positive integer that divides each of the integers. For two integers x, y, the greatest common divisor of x and y is denoted by gcd(x,y). 60 | For example, gcd(8,12)=4. Without using recursion, write a function that finds GCD of two given integers. 61 | 62 | | INPUT | OUTPUT | 63 | | :------: | :------: | 64 | | 14, 21 | 7 | 65 | | 1, 300 | 1 | 66 | | 256, 16 | 16 | 67 | | 109, 109 | 109 | 68 | 69 | ## Question 6 - Prime 70 | Given two integers A and B, find and print all the prime integers that are between A and B (including A and B). You can assume that B will always be bigger than or equal to A. 71 | | INPUT | OUTPUT | 72 | | :------: | :------: | 73 | | 1 5 | 2 3 5 | 74 | | 50 100 | 53 59 61 67 71 73 79 83 89 97 | 75 | | -3 10 | 2 3 5 7 | 76 | | 24 28 | | 77 | 78 | ## Question 7 - Grade 79 | There are n students enrolled in the CmpE150 course. At the end of the semester students can pass the course only if they attended at least 75% of the lectures and have a minimum overall score of 50, otherwise they fail. 80 | A student passes CmpE150 81 |       with "A" if s/he has an overall score that is greater than or equal to 80, 82 |       with "B" if s/he has an overall score that is greater than or equal to 65, 83 |       with "C" if s/he has an overall score that is greater than or equal to 50. 84 | Write a program that prints the number of students that passed with "A", "B", "C" and the students that failed the course by taking n (the number of students), then the attendance (as a percentage) and the overall scores of these students. 85 | | INPUT | OUTPUT | 86 | | :------: | :------: | 87 | | 4
75 90
75 60
60 60
75 40 | Passed with A: 1
Passed with B: 0
Passed with C: 1
Failed the course: 2 | 88 | | 3
5 40
80 100
98 50 | Passed with A: 1
Passed with B: 0
Passed with C: 1
Failed the course: 1 | 89 | 90 | ## Question 8 - FizzBuzz 91 | FizzBuzz is a simple game played by 2 people. Players should count in turns, yet they are forbidden from saying numbers divisible by 3 or 5. Instead they should say "Fizz" instead of numbers divisible by 3,"Buzz" instead of numbers divisible by 5, and "FizzBuzz" for numbers divisible by 15. 92 | 93 | A demonstration: 94 | 95 | Player1: 1 96 | 97 | Player2: 2 98 | 99 | Player1: Fizz 100 | 101 | Player2: 4 102 | 103 | Player1: Buzz 104 | 105 | ... 106 | 107 | Player2: 14 108 | 109 | Player1: FizzBuzz 110 | 111 | Create a script that inputs a number and simulates a player's decision for a single number. 112 | 113 | ## Question 9 - Odd Print 114 | Given an integer N, prints N line such that i'th line consists of i times the number "i" if i is odd, else just print i. 115 | 116 | | Input| Output| 117 | | :------: | :------: | 118 | | 3 | 1
2
333| 119 | | 5 | 1
2
333
4
55555| 120 | 121 | 122 | -------------------------------------------------------------------------------- /spring2022/python2022spring22/week6/chapter4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/spring2022/python2022spring22/week6/chapter4.pdf -------------------------------------------------------------------------------- /spring2022/python2022spring22/week7/Solutions.md: -------------------------------------------------------------------------------- 1 | ## Question 1 - Fibonacci 2 | 3 | ```python 4 | N = int(input()) 5 | 6 | prev = 0 7 | curr = 1 8 | 9 | for _ in range(3, N+1): 10 | next = prev + curr 11 | prev = curr 12 | curr = next 13 | 14 | if N <= 0: 15 | print("Invalid!") 16 | elif N == 1: 17 | print(prev) 18 | else: 19 | print(curr) 20 | ``` 21 | 22 | ## Question 2 - Second Largest 23 | 24 | ```python 25 | x = int(input()) 26 | largest = 0 27 | second = 0 28 | 29 | while x != 0: 30 | if x > largest: 31 | second = largest 32 | largest = x 33 | elif x > second: 34 | second = x 35 | x = int(input()) 36 | 37 | print(largest-second) 38 | ``` 39 | 40 | ## Question 3 - Digiiiits 41 | 42 | ```python 43 | x = int(input()) 44 | 45 | count = 0 46 | even_sum = 0 47 | 48 | while x > 0: 49 | digit = x % 10 50 | if digit % 2 == 0: 51 | even_sum += digit 52 | count += 1 53 | 54 | x //= 10 55 | 56 | print(count, even_sum) 57 | ``` 58 | 59 | ## Question 4 - Positive Mental Attitude 60 | 61 | ```python 62 | odd_sum = 0 63 | 64 | x = int(input()) 65 | while x >= 0: 66 | if x % 2 == 1: 67 | odd_sum += x 68 | x = int(input()) 69 | 70 | print(odd_sum) 71 | ``` 72 | 73 | ## Question 5 - NoBig 74 | 75 | ```python 76 | total_sum = 0 77 | count = 1 78 | 79 | x = int(input()) 80 | y = int(input()) 81 | total_sum += x 82 | while y <= x: 83 | total_sum += y 84 | count += 1 85 | 86 | x = y 87 | y = int(input()) 88 | 89 | print(total_sum/count) 90 | ``` 91 | 92 | ## Question 6 - Guess 93 | 94 | ```python 95 | import random 96 | 97 | number = random.randint(1,100) 98 | count = 0 99 | 100 | while True: 101 | guess = input("Make your guess: ") 102 | guess = int(guess) 103 | count += 1 104 | 105 | if guess < number: 106 | print("Too low!") 107 | elif guess > number: 108 | print("Too high!") 109 | else: 110 | print("You got it!") 111 | print("And it only took you",count,"tries!") 112 | break 113 | ``` 114 | 115 | ## Question 7 - Sum Facts 116 | 117 | ```python 118 | x = int(input()) 119 | 120 | fact_sum = 0 121 | 122 | while x > 0: 123 | digit = x % 10 124 | fact = 1 125 | for i in range(2, digit+1): 126 | fact *= i 127 | fact_sum += fact 128 | 129 | x //= 10 130 | 131 | print(fact_sum) 132 | ``` 133 | 134 | ## Question 8 - Sum of Digits 135 | 136 | ```python 137 | n = int(input()) 138 | 139 | while n >= 10: 140 | sum = 0 141 | while n: 142 | sum += n%10 143 | n //= 10 144 | n = sum 145 | 146 | print(n) 147 | ``` 148 | 149 | ## Question 9 - Prime factors 150 | 151 | ### Question 9a 152 | 153 | ```python 154 | number = int(input()) 155 | for i in range(1, number + 1): 156 | if number % i == 0: 157 | print(i, end =" ") 158 | 159 | ``` 160 | 161 | ### Question 9b 162 | 163 | ```python 164 | number = int(input()) 165 | for i in range(2, number + 1): 166 | while number % i == 0: 167 | number //= i 168 | print(i, end=" ") 169 | 170 | ``` 171 | 172 | This works because at any point in the loop, number doesn't have any factors smaller than `i`. Therefore, `i` has to be prime if it divides `number`. 173 | 174 | ### Question 9c 175 | 176 | ```python 177 | number = int(input()) 178 | firstPrime = True 179 | for i in range(2, number + 1): 180 | count = 0 181 | while number % i == 0: 182 | number //= i 183 | count += 1 184 | if count > 0: 185 | if firstPrime: 186 | firstPrime = False 187 | else: 188 | print(" * ", end="") 189 | print(i, "^", count, end="") 190 | 191 | ``` 192 | 193 | ## Question 10 - Palindromic Primes 194 | 195 | ```python 196 | def reverse_number(number): 197 | reverse = 0 198 | while num != 0: 199 | digit = num % 10 200 | num = num // 10 201 | reverse = reverse * 10 + digit 202 | return reverse 203 | 204 | def is_prime(number): 205 | if number <= 1: 206 | return False 207 | for i in range(2, number): 208 | if number % i == 0: 209 | return False 210 | return True 211 | start = int(input()) 212 | end = int(input()) 213 | 214 | for i in range(start, end + 1): 215 | if reverse_number(i) == i and is_prime(i): 216 | print(i, end = " ") 217 | 218 | ``` 219 | 220 | ## Question 11 221 | ```python 222 | A = int(input()) 223 | B = int(input()) 224 | 225 | flag = False 226 | for i in range(0, A): 227 | if A == B ** i: 228 | flag = True 229 | break 230 | if flag: 231 | print("Yes") 232 | else: 233 | print("No") 234 | ``` 235 | 236 | Alternative solution: 237 | 238 | ```python 239 | A = int(input()) 240 | B = int(input()) 241 | 242 | for i in range(0, A): 243 | if B ** i == A: 244 | print("Yes") 245 | break 246 | elif B ** i > A: 247 | print("No") 248 | break 249 | ``` 250 | 251 | ## Question 12 252 | 253 | ```python 254 | def is_perfect(num): 255 | sum_of_divisors = 0 256 | for i in range(1, num): 257 | if num % i == 0: 258 | sum_of_divisors += i 259 | return sum_of_divisors == num 260 | 261 | def all_the_perfects(N, M): 262 | for i in range(N, M + 1): 263 | if is_perfect(i): 264 | print(i, end=" ") 265 | 266 | all_the_perfects(1, 10000) 267 | ``` -------------------------------------------------------------------------------- /spring2022/python2022spring22/week7/cmpe150-chp4-p2.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/spring2022/python2022spring22/week7/cmpe150-chp4-p2.pptx -------------------------------------------------------------------------------- /spring2022/python2022spring22/week9/README.md: -------------------------------------------------------------------------------- 1 | # Strings 2 | 3 | ## Question 1 - Voweeels 4 | Write a function which takes a string that all characters are lowercase and returns the length of longest sequence of consecutive vowels. It should return 0 for the empty string. Vowels are a,e,i,o,u. 5 | 6 | | Input | Output | 7 | | ----------------------------- | ---------- | 8 | | "happy beaar" | 3 | 9 | | "how you doin?" | 2 | 10 | | "aiaiai" | 6 | 11 | | "try" | 0 | 12 | 13 | 14 | 15 | ## Question 2 - Palindrome 16 | 17 | Write a function to check whether given string is palindrome or not. A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward. 18 | 19 | | Input | Output | 20 | | ----- | ------ | 21 | | madam | True | 22 | | radix | False | 23 | 24 | ## Question 3 - Abbreviate 25 | 26 | Write a function called abbreviation() that takes a string st.
27 | If st has strictly more than 14 characters: returned string:
28 | * has the same first and last two characters as st. 29 | * the characters in the middle should be replaced by the number of characters being replaced. (if you are replacing 15 characters return value should look like ww15ww)
30 | 31 | Else return st as is. 32 | 33 | | INPUT | OUTPUT | 34 | | ------ | ------ | 35 | | afyonkarahisarlarstiramadiklarimizdan | af33an | 36 | | helo| helo | 37 | 38 | 39 | ## Question 4 - Lower/Upper Counts 40 | 41 | Write a program to calculate the number of uppercase and lowercase letters in a string. 42 | 43 | | Input | Output | 44 | | ---------------- | ------ | 45 | | CMPE will be fun | 9 4 | 46 | | HeLLo WoRLD | 7 3 | 47 | 48 | ## Question 5 - Requirements 49 | 50 | Write a function which takes a password as parameter and return whether the password is valid or not. The password has the following requirements: 51 | 52 | * The password must be at least 6 characters and at most 20 characters. 53 | 54 | * It must contain at least one lowercase letter, one uppercase letter, and one number. 55 | 56 | | Input | Output | 57 | | ------- | ------ | 58 | | Covid19 | True | 59 | | 123456 | False | 60 | 61 | ## Question 6 - Length 62 | 63 | Write a program to find shortest and largest word in a given string. 64 | 65 | | Input | Output | 66 | | ---------------------------------- | -------------- | 67 | | the house is a long way from here | a house | 68 | | This room is exclusively for women | is exclusively | 69 | 70 | 71 | ## Question 7 - Word Cases 72 | 73 | Write a function that takes a string and returns it by modifying it such that every word with odd index should be lowercase and every word with even index should be uppercase. 74 | 75 | | Input | Output | 76 | | -------------------------------------- | -------------------------------------- | 77 | | stop making sponge bob memes | STOP making SPONGE bob MEMES | 78 | | CMPE will be fun in the next few years | CMPE will BE fun IN the NEXT few YEARS | 79 | 80 | 81 | ## Question 8 - Second Most Common 82 | Write a program that prompts the user for a string. Then find and print out the second most repeated character (lowercase) in the string (not case-sensitive). Do not take whitespaces into consideration. 83 | 84 | Hint : You can use replace() method of strings to get rid of whitespaces. Then you can use count() method to check if a character is in the string. 85 | Alternatively, you can use a dictionary to store the occurrences of each character. 86 | 87 | | INPUT | OUTPUT | 88 | | ------ | ------ | 89 | | " Hey there partner! " | "r" | 90 | | "CaN you CAn a CAN as a canner CaN CAn a CAN?"| "n" | 91 | | " LEsSer leather weaTheREd weTTer weathEr BettEr"| "t" | 92 | 93 | ## Question 9 - Not poor 94 | 95 | Write a function to find the first appearance of the substring **'not'** and **'poor'** from a given string, if **'not'** follows the **'poor'**, replace the whole '**not'...'poor'** substring with **'good'. ** and return the resulting string. 96 | 97 | | Input | Output | 98 | | ---------------------------- | ------------------- | 99 | | The lyrics is not that poor! | The lyrics is good! | 100 | | The lyrics is poor! | The lyrics is poor! | 101 | 102 | 103 | ## Question 10 - Find and replace 104 | 105 | Write a function that takes 3 strings ``input``, ``a`` and ``b`` and replaces all the instances of ``a`` in ``input`` with ``b``. 106 | 107 | | ``input`` |``a``|``b``| Output | 108 | | ----------------------------- |----|---| ---------- | 109 | | This is another test |"is"|"is not"| This not is not another test | 110 | | I mean, it went badly last time but surely it will go much better this time. |"it"|"filling zepplins with hydrogen"|I mean, filling zepplins with hydrogen went badly last time but surely filling zepplins with hydrogen will go much better this time.| 111 | | Test test TeSt te st TEst teSt crest TEA | "st TE" |" test "|Test test TeSt te testst teSt cretestA | 112 | 113 | 114 | 115 | -------------------------------------------------------------------------------- /spring2022/python2022spring22/week9/Solutions.md: -------------------------------------------------------------------------------- 1 | # Strings 2 | 3 | ## Question 1 - Voweeels 4 | 5 | ```python 6 | def vowel(s): 7 | max_length, length = 0, 0 8 | for c in s: 9 | if c in 'oeaiu': 10 | length += 1 11 | else: 12 | length = 0 13 | max_length = max(length, max_length) 14 | return max_length 15 | 16 | print(vowel("happy beaar")) 17 | print(vowel("how you doin?")) 18 | print(vowel("aiaiai")) 19 | print(vowel("try")) 20 | ``` 21 | 22 | 23 | ## Question 2 - Palindrome 24 | 25 | ```python 26 | def is_palindrome(str): 27 | return str == str[::-1] 28 | ``` 29 | 30 | ## Question 3 - Abbreviate 31 | 32 | ```python 33 | def abbreviation(st): 34 | if (len(st) <= 14): 35 | return st 36 | else: 37 | return st[0:2] + str(len(st) - 4) + st[-2:] 38 | ``` 39 | 40 | ## Question 4 - Lower/Upper Counts 41 | 42 | ```python 43 | str = "HeLLo WoRLD" 44 | lower_count, upper_count = 0, 0 45 | for c in str: 46 | lower_count += c.islower() 47 | upper_count += c.isupper() 48 | 49 | print(upper_count, lower_count) 50 | ``` 51 | 52 | ## Question 5 - Requirements 53 | 54 | ```python 55 | def is_valid(password): 56 | length = len(password) 57 | if length < 6 or length > 20: 58 | return False 59 | lower, upper, digit = 0, 0, 0 60 | for c in password: 61 | lower += c.islower() 62 | upper += c.isupper() 63 | digit += c.isdigit() 64 | return lower >= 1 and upper >= 1 and digit >= 1 65 | 66 | print(is_valid("Covid19")) 67 | ``` 68 | 69 | ## Question 6 - Length 70 | 71 | ```python 72 | sentence = input() 73 | words = sentence.split() 74 | lengths = [len(w) for w in words] 75 | shortest_index = lengths.index(min(lengths)) 76 | longest_index = lengths.index(max(lengths)) 77 | print(words[shortest_index], words[longest_index]) 78 | ``` 79 | 80 | ## Question 7 - Word Cases 81 | 82 | ```python 83 | def modify(str): 84 | words = str.split() 85 | new_str = '' 86 | for ix, word in enumerate(words): 87 | if ix % 2 == 0: 88 | new_str += word.upper() + ' ' 89 | else: 90 | new_str += word.lower() + ' ' 91 | return new_str 92 | 93 | def modify2(str): 94 | return ' '.join([word.upper() if ix % 2 == 0 else word.lower() for ix, word in enumerate(str.split())]) 95 | 96 | print(modify('stop making sponge bob memes')) 97 | print(modify2('stop making sponge bob memes')) 98 | 99 | ``` 100 | 101 | 102 | ## Question 8 - Second Most Common 103 | ```python 104 | string = str(input()) 105 | modified = string.replace(" ", "").lower() 106 | Max = 0 107 | secondMax = 0 108 | second = '' 109 | first = '' 110 | for i in modified: 111 | occur = modified.count(i) 112 | if(occur > Max): 113 | second = first 114 | first = i 115 | secondMax = Max 116 | Max = occur 117 | elif(occur < Max and occur > secondMax): 118 | second = i 119 | secondMax = occur 120 | print(first, second) 121 | ``` 122 | 123 | ## Question 9 - Not poor 124 | ```python 125 | def not_poor(str1): 126 | snot = str1.find('not') 127 | spoor = str1.find('poor') 128 | if spoor > snot and snot > 0 and spoor > 0: 129 | str1 = str1.replace(str1[snot:(spoor+4)], 'good') 130 | return str1 131 | print(not_poor('The lyrics is not that poor!')) 132 | print(not_poor('The lyrics is poor!')) 133 | ``` 134 | 135 | ## Question 10 - Find and replace 136 | 137 | ```python 138 | 139 | def find_and_replace(string, a, b): 140 | ix = 0 141 | while string.find(a, ix) != -1: 142 | ix = string.find(a, ix) 143 | string = string[:ix] + b + string[ix+len(a):] 144 | ix = ix + len(b) 145 | return string 146 | 147 | 148 | print(find_and_replace("This is another test", "is", "is not")) 149 | print(find_and_replace("I mean, it went badly last time but surely it will go much better this time.", "it", "filling zeppelins with hydrogen")) 150 | print(find_and_replace("Test test TeSt te st TEst teSt crest TEA", "st TE", "test")) 151 | ``` 152 | 153 | -------------------------------------------------------------------------------- /spring2022/python2022spring22/week9/string.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/spring2022/python2022spring22/week9/string.pptx -------------------------------------------------------------------------------- /week01/README.md: -------------------------------------------------------------------------------- 1 | ## Question 1 2 | 3 | **a)** Create two integer variables, and print them 4 | 5 | **b)** Take two integers from the user, and print them 6 | 7 | **c)** Take two integers from the user (a, b), and then print their sum, difference, product, power and remainder. 8 | 9 | | Input | Output | 10 | | ----- | ---------------- | 11 | | 13 5 | 18 8 65 371293 3 | 12 | 13 | ## Question 2 14 | 15 | **a)** Create an integer, a float, and a string variable. Print their types, using the type() function. 16 | 17 | **b)** Take an integer, a float, and a string variable from the user. Print the variables. 18 | 19 | ## Question 3 20 | 21 | Write a program that takes 3 integers from the user and then prints the sum, mean and multiple of the numbers. 22 | 23 | | Input | Output | 24 | | -------- | ------------- | 25 | | 13 27 14 | 54 18.00 4914 | 26 | 27 | ## Question 4 28 | 29 | Using the formula below of compound interest, take the **principal amount (A)**, **interest rate (i)** (per month) and **duration (n)** (months) and print the final amount. 30 | 31 | 32 | 33 | 34 | | Input | Output | 35 | | --------- | ------- | 36 | | 1000 12 5 | 1762.34 | 37 | | 500 12 5 | 881.17 | 38 | 39 | ## Question 5 40 | 41 | Guess the outcome of each statement. Then check the results. 42 | 43 | Hint: You can multiply strings with integers. It basically performs the concatenation operation n many times. 44 |
45 | 46 | - print(int('6') + int('4'))
47 | - print('1' + '4')
48 | - print(int(3.9)) 49 | - print(str(5.3) + '2.7')
50 | - print(int('5') * str(0.6))
51 | - print(float('3' + '8.6'))
52 | - print(3.5 + 6.7)
53 | - print(2 ** 3 ** 2 / 32) 54 | - print(str(4.4) + str(7.3))
55 | - print(int(6.5) + float('6.5'))
56 | - print(int(4.5 + 3.2))
57 | - print(int(3.2) + int(float(str(3.2))))
58 | 59 | Remarks: 60 |
61 | 62 | 63 | - Observe that float-to-int type conversion is not a rounding operation. int(3.9) = 3. To round floats, we will use a built-in function called round(). Stay tuned!
64 | - As you see, we can multiply strings with integers, but not floats. What does 3.14 times "pi" mean, anyway?
65 | - Exponent operator ** has right-to-left associativity.
66 |
67 |
68 | 69 | ## Question 6 70 | 71 | Write a program that calculates the amount of seconds in a given period of years, months, days, hours and minutes respectively. 72 | 73 | * 1 year = 365 days 74 | * 1 month = 30 days 75 | 76 | | Input | Output | 77 | | --------- | --------- | 78 | | 5 2 4 3 0 | 163220400 | 79 | | 1 1 1 1 1 | 34218060 | 80 | 81 | ## Question 7 82 | 83 | There is a cash machine with an infinite supply of 5tl banknotes and 1tl coins inside it. 84 | 85 | Write a function that takes an integer representing the amount of money requested by a customer. The function then prints the number of banknotes and coins given to the customer. (Machine must prefer giving away banknotes instead of coins if possible) 86 | 87 | | Input | Output | 88 | | ----- | ---------------------------------------- | 89 | | 57 | 5tl banknotes: 11
1tl banknotes: 2 | 90 | | 269 | 5tl banknotes: 53
1tl banknotes: 4 | 91 | 92 | ## Question 8 93 | 94 | Write a function that takes a radius and returns the volume of the sphere. 95 | 96 | | Input | Output | 97 | | ----- | ------------- | 98 | | 3 | 113.097335529 | 99 | | 6 | 904.778684234 | 100 | 101 | ## Question 9 102 | 103 | Write a function called `power` that takes two integer parameter as **number** and **n**. The function should return the **nth** power of **number**. 104 | 105 | | Input | Output | 106 | | ----- | ------ | 107 | | 5 2 | 25 | 108 | | 3 2 | 9 | 109 | | 4 3 | 64 | 110 | 111 | ## Question 10 & 11 requires knowledge of Boolean expressions and they are for those with Python background. Solve them without using if statements. 112 | 113 | ## Question 10 114 | 115 | Write a program that takes 3 integers from the user and then prints the sum of odd numbers. 116 | 117 | | Input | Output | 118 | | ------ | ------ | 119 | | 3 4 5 | 8 | 120 | | 2 2 4 | 0 | 121 | | 1 9 15 | 25 | 122 | 123 | ## Question 11 124 | 125 | When you multiply an integer by itself, the result is a square number. 126 | 127 | Write a function that takes an integer and determines whether it is a square number or not. 128 | 129 | | Input | Output | 130 | | ----- | ------ | 131 | | 25 | True | 132 | | 23 | False | 133 | | 0 | True | 134 | | -1 | False | 135 | -------------------------------------------------------------------------------- /week01/Solutions.md: -------------------------------------------------------------------------------- 1 | ## Question1 2 | 3 | ### a 4 | 5 | ```python 6 | x = 5 7 | y = 3 8 | print(x) 9 | print(y) 10 | ``` 11 | 12 | ### b 13 | 14 | ```python 15 | x = int(input()) 16 | y = int(input()) 17 | print(x) 18 | print(y) 19 | ``` 20 | 21 | ### c 22 | 23 | ```python 24 | x = int(input()) 25 | y = int(input()) 26 | print(x+y, x-y, x*y, x**y, x%y) 27 | ``` 28 | 29 | ## Question 2 30 | 31 | ### a 32 | 33 | ```python 34 | x = 5 35 | y = 1.7 36 | z = "I am a string!" 37 | print(type(x)) 38 | print(type(y)) 39 | print(type(z)) 40 | ``` 41 | 42 | ### b 43 | 44 | ```python 45 | x = int(input()) 46 | y = float(input()) 47 | z = input() 48 | print(x, y, z) 49 | ``` 50 | 51 | ## Question 3 52 | 53 | ```python 54 | x = int(input()) 55 | y = int(input()) 56 | z = int(input()) 57 | sum = x + y + z 58 | print(sum, sum/3, x * y * z) 59 | ``` 60 | 61 | ## Question 4 62 | 63 | ```python 64 | A = int(input()) 65 | i = int(input()) 66 | n = int(input()) 67 | # print(A * (1 + (i / 100)) ** n) 68 | print('%.2f' % (A * (1 + (i / 100)) ** n)) 69 | ``` 70 | 71 | ## Question 5 72 | 73 | ```python 74 | print(int('6') + int('4')) 75 | print('1' + '4') 76 | print(int(3.9)) 77 | print(str(5.3) + '2.7') 78 | print(int('5') * str(0.6)) 79 | print(float('3' + '8.6')) 80 | print(3.5 + 6.7) 81 | print(2 ** 3 ** 2 / 32) 82 | print(str(4.4) + str(7.3)) 83 | print(int(6.5) + float('6.5')) 84 | print(int(4.5 + 3.2)) 85 | print(int(3.2) + int(float(str(3.2)))) 86 | ``` 87 | 88 | ## Question 6 89 | 90 | ```python 91 | years = int(input()) 92 | months = int(input()) 93 | days = int(input()) 94 | hours = int(input()) 95 | minutes = int(input()) 96 | 97 | total_days = years * 365 + month * 30 + days 98 | total_hours = total_days * 24 + hours 99 | total_minutes = total_hours * 60 + minutes 100 | print(total_minutes * 60) 101 | ``` 102 | 103 | ## Question 7 104 | 105 | ```python 106 | # as a program 107 | # money = int(input()) 108 | # print('5tl banknotes:', money / 5) 109 | # print('1tl banknotes:', money % 5) 110 | # with functions 111 | def to_banknotes(money): 112 | print('5tl banknotes:', money / 5) 113 | print('1tl banknotes:', money % 5) 114 | 115 | to_banknotes(57) 116 | to_banknotes(269) 117 | ``` 118 | 119 | ## Question 8 120 | 121 | ```python 122 | def volume(radius): 123 | return 4 / 3 * radius ** 3 * 3 124 | 125 | print(volume(3)) 126 | result = volume(6) 127 | print(result) 128 | ``` 129 | 130 | ## Question 9 131 | 132 | ```python 133 | def power(number, n): 134 | return number ** n 135 | 136 | print(power(5, 2)) 137 | print(power(3, 2)) 138 | ``` 139 | 140 | ## Question 10 141 | 142 | ```python 143 | a = int(input()) 144 | b = int(input()) 145 | c = int(input()) 146 | 147 | print(a * (a % 2) + b * (b % 2) + c * (c % 2)) 148 | ``` 149 | 150 | ## Question 11 151 | 152 | ```python 153 | def is_square(number): 154 | sqroot = number ** 0.5 155 | sqroot_int = int(sqroot) 156 | return number == sqroot_int ** 2 157 | 158 | print(is_square(23)) 159 | print(is_square(25)) 160 | ``` 161 | 162 | -------------------------------------------------------------------------------- /week02/Solutions.md: -------------------------------------------------------------------------------- 1 | ## Question 1 2 | 3 | ```python 4 | X = float(input()) 5 | Y = float(input()) 6 | total = X + Y 7 | percent_X = X/total * 100 8 | percent_Y = Y/total * 100 9 | #print("%.2f%% %.2f%%" % (percent_X, percent_Y)) 10 | print("{:.2f}% {:.2f}%".format(percent_X, percent_Y)) 11 | ``` 12 | 13 | ## Question 2 14 | 15 | ```python 16 | weight = float(input()) 17 | height = int(input()) / 100 18 | bmi = weight / (height ** 2) 19 | # print('%.2f' % bmi) 20 | print("{:.2f}".format(bmi)) 21 | ``` 22 | 23 | ## Question 3 24 | 25 | ```python 26 | x = int(input()) 27 | print((5 ** 5628) % 100 * (x - 1)) 28 | ``` 29 | 30 | ## Question 4 31 | 32 | ```python 33 | a = float(input()) 34 | b = float(input()) 35 | c = float(input()) 36 | 37 | fraction_a = a - a // 1 38 | fraction_b = b - b // 1 39 | fraction_c = c - c // 1 40 | 41 | print(fraction_a, fraction_b, fraction_c) 42 | ``` 43 | 44 | ## Question 5 45 | 46 | ```python 47 | def division(dividend, divisor) 48 | quotient = dividend // divisor 49 | remainder = dividend % divisor 50 | print("quotient =", quotient, "remainder =", remainder) 51 | 52 | division(9, 2) 53 | division(156, 13) 54 | 55 | ``` 56 | 57 | ## Question 6 58 | 59 | ```python 60 | def number_of_bacteria(initial, t1, total_time): 61 | return initial * 2**int(total_time/t1) 62 | print(number_of_bacteria(1, 1, 2)) 63 | print(number_of_bacteria(5, 3, 8)) 64 | ``` 65 | 66 | ## Question 7 67 | 68 | ```python 69 | def distance(x1, y1, x2, y2): 70 | return ((x2-x1)**2 + (y2-y1)**2)**0.5 71 | 72 | print(distance(5, 10, 10, 22)) 73 | ``` 74 | 75 | ## Question 8 76 | 77 | ```python 78 | def laps(r, x1, x2, total_time): 79 | pi = 3.14 80 | circumference = 2 * pi * r 81 | total_run_1 = total_time * x1 82 | total_run_2 = total_time * x2 83 | total_laps1 = int(total_run_1 / circumference) 84 | total_laps2 = int(total_run_2 / circumference) 85 | return total_laps1, total_laps 86 | runner1, runner2 = laps(100, 300, 400, 30) 87 | ``` 88 | 89 | ## Question 9 90 | 91 | ```python 92 | import math 93 | N = 20 94 | C = 5 95 | def find_index(X): 96 | page_index = math.ceil(X / (N*C)) 97 | page_items = X % (N*C) 98 | line_index = math.ceil(page_items / C) 99 | col_index = page_items - (line_index - 1) * C 100 | return page_index, line_index, col_index 101 | num = int(input("Number: ")) 102 | page_ix, line_ix, col_ix = find_index(num) 103 | print(page_ix, line_ix, col_ix) 104 | ``` 105 | 106 | ## Question 10 107 | 108 | ```python 109 | def passer_rating(comp, att, yards, td, inter): 110 | C = (((comp/att * 100)-30) / 20) 111 | Y = (((yards/att)-3) / 4) 112 | T = ((td/att) * 20) 113 | I = (2.375 - ((inter/att) * 35)) 114 | return ((C + Y + T + I) / 6) * 100 115 | comp = int(input()) 116 | att = int(input()) 117 | yards = int(input()) 118 | td = int(input()) 119 | inter = int(input()) 120 | print(passer_rating(cmp, att, yards, td, inter)) 121 | ``` 122 | 123 | ## Question 11 124 | 125 | ```python 126 | def estimated_population(year): 127 | num_year = year - 2021 128 | seconds = 365 * 24 * 60 * 60 # days * hours * minutes * seconds 129 | birth_per_year = seconds // 15 130 | death_per_year = seconds // 20 131 | immigrant_per_year = seconds // 100 132 | return population + num_year * (birth_per_year + immigrant_per_year - death_per_year) 133 | population = 84.5 * (10** 6) 134 | print(estimated_population(2030)) 135 | ``` 136 | 137 | -------------------------------------------------------------------------------- /week02/q9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bouncmpe150/python-notes/d5c5be38fb5e7a3b830cadc36060816929ec2a16/week02/q9.png -------------------------------------------------------------------------------- /week03/README.md: -------------------------------------------------------------------------------- 1 | # Loops 2 | 3 | ## Question 1 - Staaaars 4 | 5 | ### Question 1a 6 | 7 | Write a program that prints 1 star ('\*') to the screen. 8 | 9 | ### Question 1b 10 | 11 | Write a program that prints 10 stars ('\*') next to each other to the screen. 12 | 13 | ### Question 1c 14 | 15 | Write a program that reads an integer N and prints N stars ('\*') vertically to the screen. 16 | 17 | ### Question 1d 18 | 19 | Write a program that reads an integer N and prints N stars ('\*') next to each other to the screen. 20 | 21 | 22 | 23 | ## Question 2 - Numbeeeers 24 | 25 | Write a program that reads an integer N and prints numbers from 1 to N to the screen. 26 | 27 | | INPUT | OUTPUT | 28 | | :---: | :-------: | 29 | | 5 | 1 2 3 4 5 | 30 | | 2 | 1 2 | 31 | 32 | 33 | 34 | ## Question 3 - Hooping Numbers 35 | 36 | ### Question 3a 37 | 38 | Write a program that reads 3 integers A, B and t from the user. Then prints numbers from A to B with increment of t. Assume that B > A. 39 | 40 | | INPUT | OUTPUT | 41 | | :----: | :----------: | 42 | | 7 16 3 | 7 10 13 16 | 43 | | 2 30 6 | 2 8 14 20 26 | 44 | 45 | ### Question 3b 46 | 47 | Write a program that reads 3 integers A, B and t from the user. Then prints numbers from B to A with decrement of t. Assume that B > A. 48 | 49 | | INPUT | OUTPUT | 50 | | :----: | :-----------: | 51 | | 7 16 3 | 16 13 10 7 | 52 | | 2 30 6 | 30 24 18 12 6 | 53 | 54 | 55 | 56 | ## Question 4 - Numbeeeers 57 | 58 | Write a program that reads two integers A and B. Then prints the sum of numbers between A and B (excluding A and B). Assume that B > A. 59 | 60 | | INPUT | OUTPUT | 61 | | :---: | :----: | 62 | | 3 8 | 10 | 63 | | 2 13 | 22 | 64 | | 3 5 | 75 | 65 | 66 | 67 | 68 | ## Question 5 - Average Team 69 | 70 | Write a program that reads a number N, then reads N more numbers. Calculate the average of those N numbers. 71 | 72 | | INPUT | OUTPUT | 73 | | :----------: | :----: | 74 | | 4
4 9 5 2 | 5.0 | 75 | | 1
8 | 8.0 | 76 | 77 | ## Question 6 - Boom Boom POW 78 | 79 | Write a program that takes 2 integers a and b, then prints the result of a^b (a\*a\*a...\*a\*a). 80 | 81 | | INPUT | OUTPUT | 82 | | :---: | :----: | 83 | | 3 4 | 81 | 84 | | 2 10 | 1024 | 85 | 86 | ## Question 7 - Factorial 87 | 88 | Write a program that takes an integer n and then prints n!. 89 | 90 | | INPUT | OUTPUT | 91 | | :---: | :-----: | 92 | | 5 | 120 | 93 | | 10 | 3628800 | 94 | 95 | ## Question 8 - Sum of Products 96 | 97 | Write a program that takes an integer and then reads n lines containing two integers. The program then multiplies the integers in the same line and sums all the products. 98 | 99 | 100 | | INPUT | OUTPUT | 101 | | :---: | :-----: | 102 | | 3
1 2
2 3
3 4
| 20 | 103 | | 2
3 4
5 10 | 62 | 104 | 105 | 106 | # Nested Loops 107 | 108 | ## Question 1 - R\*\*\*tangle 109 | 110 | ### Question 1a 111 | 112 | Write a program which takes two positive integers as N and M then prints a rectangle with size NxM. 113 | 114 | | Input | Output | 115 | | :---: | ------------------------------------ | 116 | | 3 4 | \*\*\*\*
\*\*\*\*
\*\*\*\* | 117 | | 2 6 | \*\*\*\*\*\*
\*\*\*\*\*\* | 118 | 119 | ### Question 1b 120 | 121 | Write a program which takes two positive integers as N and M then prints a rectangle with size NxM which has stars (\*) at borders, and lines (-) inside. 122 | 123 | | Input | Output | 124 | | :---: | ---------------------------------------------------- | 125 | | 3 3 | \*\*\*
\*-\*
\*\*\* | 126 | | 4 5 | \*\*\*\*\*
\*---\*
\*---\*
\*\*\*\*\* | 127 | 128 | ## Question 2 - TriNumber 129 | 130 | ### Question 2a 131 | 132 | Write a program to display a right angle triangle using the number N, which will repeat the number for that row, like below. 133 | 134 | | Input | Output | 135 | | :---: | --------------------------------------- | 136 | | 3 | 1
22
333 | 137 | | 5 | 1
22
333
4444
55555 | 138 | 139 | ### Question 2b 140 | 141 | Write a program to display a right angle triangle with N number of rows, like below. 142 | 143 | | Input | Output | 144 | | :---: | --------------------------------------- | 145 | | 3 | 1
12
123 | 146 | | 5 | 1
12
123
1234
12345 | 147 | 148 |
Hint At each row, we iterate from 1 to the row number.
149 | 150 | ### Question 2c 151 | 152 | Write a program which takes two integer as N and x and display a right angle triangle with N number of rows formed by powers of x as follows: 153 | 154 | | Input | Output | 155 | | :---: | ------------------------------------- | 156 | | 3 4 | 4
4 16
4 16 64 | 157 | | 4 3 | 3
3 9
3 9 27
3 9 27 81 | 158 | 159 |
Hint At each row, we take power of input integer from once to the row number times.
160 | 161 | ## Question 3 - TriHard 162 | 163 | Write a program which takes an integer N as input and prints a right triangle which consists of N many lines. 164 | 165 | | Input | Output | 166 | | :---: | ------------------------------------------------------------ | 167 | | 3 | --\*
-\*\*
\*\*\* | 168 | | 5 | ----\*
---\*\*
--\*\*\*
-\*\*\*\*
\*\*\*\*\* | 169 | 170 | 171 | 172 | -------------------------------------------------------------------------------- /week03/Solutions.md: -------------------------------------------------------------------------------- 1 | # Loops 2 | 3 | ## Question 1 - Staaaars 4 | 5 | ### Question 1a 6 | 7 | ```python 8 | print('*') 9 | ``` 10 | 11 | ### Question 1b 12 | 13 | ```python 14 | print('**********') 15 | ``` 16 | 17 | ### Question 1c 18 | 19 | ```python 20 | N = int(input()) 21 | 22 | for i in range(N): 23 | print('*') 24 | ``` 25 | 26 | ### Question 1d 27 | 28 | ```python 29 | N = int(input()) 30 | 31 | for i in range(N): 32 | print('*', end='') 33 | ``` 34 | 35 | ## Question 2 - Numbeeeers 36 | 37 | ```python 38 | N = int(input()) 39 | 40 | for i in range(N): 41 | print(i+1, end=' ') 42 | 43 | # OR 44 | 45 | for i in range(1, N+1): 46 | print(i, end=' ') 47 | ``` 48 | 49 | ## Question 3 - Hooping Numbers 50 | 51 | ### Question 3a 52 | 53 | ```python 54 | A = int(input()) 55 | B = int(input()) 56 | t = int(input()) 57 | 58 | for i in range(A, B+1, t): 59 | print(i, end=' ') 60 | ``` 61 | 62 | ### Alternative 63 | 64 | ```python 65 | A, B, t = input().strip().split() 66 | A = int(A) 67 | B = int(B) 68 | t = int(t) 69 | 70 | for i in range(A, B+1, t): 71 | print(i, end=' ') 72 | ``` 73 | 74 | 75 | 76 | ### Question 3b 77 | 78 | ```python 79 | A = int(input()) 80 | B = int(input()) 81 | t = int(input()) 82 | 83 | for i in range(B, A-1, -t): 84 | print(i, end=' ') 85 | ``` 86 | 87 | ### Alternative 88 | 89 | ```python 90 | A, B, t = input().strip().split() 91 | A = int(A) 92 | B = int(B) 93 | t = int(t) 94 | 95 | for i in range(B, A-1, -t): 96 | print(i, end=' ') 97 | ``` 98 | 99 | 100 | 101 | 102 | 103 | ## Question 4 - Numbeeeers 104 | 105 | ```python 106 | A = int(input()) 107 | B = int(input()) 108 | 109 | result = 0 110 | 111 | for i in range(A+1, B): 112 | result += i 113 | 114 | print(result) 115 | ``` 116 | 117 | ## Question 5 - Average Team 118 | 119 | ```python 120 | N = int(input()) 121 | 122 | result = 0 123 | 124 | for _ in range(N): 125 | x = int(input()) 126 | # result = result + x 127 | result += x 128 | 129 | print(result/N) 130 | ``` 131 | 132 | ## Question 6 - Boom Boom POW 133 | 134 | ```python 135 | a = int(input("a: ")) 136 | b = int(input("b: ")) 137 | 138 | result = 1 139 | 140 | for _ in range(b): 141 | result *= a 142 | 143 | print(result) 144 | 145 | ``` 146 | 147 | ## Question 7 - Factorial 148 | 149 | ```python 150 | n = int(input()) 151 | 152 | result = 1 153 | for i in range(n): 154 | result *= i+1 155 | 156 | print(result) 157 | ``` 158 | 159 | ## Question 8 - Sum of Products 160 | 161 | ```python 162 | n = int(input()) 163 | total = 0 164 | 165 | for i in range(n): 166 | x1, x2 = input().strip().split() 167 | total += int(x1) * int(x2) 168 | print(total) 169 | ``` 170 | 171 | 172 | 173 | # Nested Loops 174 | 175 | ## Question 1 - R\*\*\*tangle 176 | 177 | ### Question 1a 178 | 179 | ```python 180 | N = int(input("N: ")) 181 | M = int(input("M: ")) 182 | 183 | for _ in range(N): 184 | for _ in range(M): 185 | print("*", end='') 186 | print() 187 | ``` 188 | 189 | ### Question 1b 190 | 191 | ```python 192 | N = int(input("N: ")) 193 | M = int(input("M: ")) 194 | 195 | for _ in range(M): 196 | print("*", end='') 197 | print() 198 | 199 | for _ in range(N-2): 200 | print("*", end='') 201 | for _ in range(M-2): 202 | print("-", end='') 203 | print("*") 204 | 205 | for _ in range(M): 206 | print("*", end='') 207 | ``` 208 | 209 | ## Question 2 - TriNumber 210 | 211 | ### Question 2a 212 | 213 | ```python 214 | N = int(input()) 215 | 216 | for i in range(1, N+1): 217 | for j in range(i): 218 | print(i, end='') 219 | print() 220 | ``` 221 | 222 | ### Question 2b 223 | 224 | ```python 225 | N = int(input()) 226 | 227 | for i in range(1, N+1): 228 | for j in range(i): 229 | print(j+1, end='') 230 | print() 231 | ``` 232 | 233 | ### Question 2c 234 | 235 | ```python 236 | N = int(input()) 237 | x = int(input()) 238 | 239 | for i in range(1, N+1): 240 | for j in range(1, i+1): 241 | print(x ** j, end=' ') 242 | print() 243 | ``` 244 | 245 | ## Question 3 - TriHard 246 | 247 | ```python 248 | N = int(input()) 249 | 250 | for i in range(1, N+1): 251 | for j in range(N - i): 252 | print('-', end='') 253 | for j in range(i): 254 | print('*', end='') 255 | print() 256 | ``` 257 | 258 | 259 | 260 | -------------------------------------------------------------------------------- /week05/README.md: -------------------------------------------------------------------------------- 1 | ## Question 1 - Fibonacci 2 | 3 | Write a program which reads a positive integer number N and prints the Nth fibonacci number. *0, 1, 1, 2, 3, 5, ...* 4 | 5 | F0 = 0 6 | 7 | F1 = 1 8 | 9 | Fn = Fn-2 + Fn-1 10 | 11 | | INPUT | OUTPUT | 12 | | ----- | ------ | 13 | | 2 | 1 | 14 | | 4 | 2 | 15 | | 7 | 8 | 16 | 17 | ## Question 2 - Second Largest 18 | 19 | Write a program that will take nonnegative integers as inputs until the user enters 0. Then prints the difference between of largest two numbers among given inputs. 20 | 21 | | INPUT | OUTPUT | 22 | | -------------------------------------------------- | ------ | 23 | | 12
25
3
8
0 | 13 | 24 | | 15
1
2
3
8
5
0 | 7 | 25 | 26 | ## Question 3 - Digiiiits 27 | 28 | Write a program that takes a number and prints its total digit count and sum of even digits. 29 | 30 | | INPUT | OUTPUT | 31 | | ------ | ------ | 32 | | 542175 | 6 6 | 33 | | 24680 | 5 20 | 34 | | 135 | 3 0 | 35 | 36 | ## Question 4 - Positive Mental Attitude 37 | 38 | Write a program that will take integers as inputs until the user enters a negative number. Then shows the user the sum of all ODD non-negative numbers that is entered. 39 | 40 | | INPUT | OUTPUT | 41 | | ------------------------------------------------------------ | ------ | 42 | | 4
7
45
9
2
0
0
5
8
-4 | 66 | 43 | | 1
1
0
1
-1 | 3 | 44 | 45 | ## Question 5 - NoBig 46 | 47 | Write a program that reads numbers until the entered number is greater than the previous entered number. Then print the average of all entered numbers except the last one. Assume that at least two numbers will be entered. 48 | 49 | | INPUT | OUTPUT | 50 | | --------------------------------------------------------- | ------ | 51 | | 5
4
3
3
8 | 3.75 | 52 | | 5
4
3
3
8
7
5
9 | 3.75 | 53 | | 1
2 | 1.0 | 54 | | 100
54
46
2
3
50 | 50.5 | 55 | 56 | ## Question 6 - Guess 57 | 58 | Generate a random number between 1 and 100 (including 1 and 100). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. Also print the number of tries. 59 | 60 | | Input | Output | 61 | | ----------------------------- | ------------------------------------------------------------ | 62 | | 35
67
73
71 | Too low!
Too low!
Too high!
You got it! And it only took you 4 tries! | 63 | 64 | 65 | 66 | ## Question 7 - Sum Facts 67 | 68 | Write a program which takes an integer as input and computes the sum of the factorial of each digit. For example, assume that the user enters 572 as the input. For each digit of the integer, you will compute the factorial. Then you will compute the sum of these factorials: 5! + 7! + 2! = 120 + 5040 + 2 = 5162. 69 | 70 | | Input | Output | 71 | | ----- | ------ | 72 | | 572 | 5162 | 73 | | 27 | 5042 | 74 | 75 | ## Question 8 - Sum of Digits 76 | 77 | Write a program that takes an integer n and calculates sum of all digits. If the result has more than one digit, continue to calculate in this way until a single digit number is produced. 78 | 79 | ``` 80 | 16 --> 1 + 6 = 7 81 | 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 82 | ``` 83 | 84 | | INPUT | OUTPUT | 85 | | ----- | ------ | 86 | | 942 | 6 | 87 | | 17703 | 9 | 88 | 89 | ## Question 9 - Prime factors 90 | 91 | ### Question 9a 92 | 93 | Write a program that reads an integer N and prints all the numbers that can divide N. 94 | 95 | | INPUT | OUTPUT | 96 | | ----- | ------------------ | 97 | | 21 | 1 3 7 21 | 98 | | 30 | 1 2 3 5 6 10 15 30 | 99 | 100 | ### Question 9b 101 | 102 | Write a program that reads an integer N and prints the prime factorization of N. 103 | 104 | *Hint: A non-prime number is always composed of prime numbers smaller than it.* 105 | 106 | | INPUT | OUTPUT | 107 | | ----- | ------------- | 108 | | 21 | 3 * 7 | 109 | | 60 | 2 * 2 * 3 * 5 | 110 | 111 | ### Question 9c 112 | 113 | Write a program that reads an integer N and prints the prime factorization of N in the form of exponents. 114 | 115 | | INPUT | OUTPUT | 116 | | ----- | --------------- | 117 | | 21 | 3^1 * 7^1 | 118 | | 60 | 2^2 * 3^1 * 5^1 | 119 | 120 | ## Question 10 - Palindromic Primes 121 | 122 | Palindromic number is a number that remains the same when its digits are reversed. A [palindromic prime](https://en.wikipedia.org/wiki/Palindromic_prime) is a prime number that is also a palindromic number. 123 | 124 | Write a program that prompts the user for two integers, starting and ending points. Then print out all the palindromic primes between starting and ending points inclusively. 125 | 126 | | INPUT | OUTPUT | 127 | | ------------- | --------------- | 128 | | 10
150 | 11 101 131 | 129 | | 150
350 | 151 181 191 313 | 130 | | 700
800 | 727 757 787 797 | 131 | -------------------------------------------------------------------------------- /week05/Solutions.md: -------------------------------------------------------------------------------- 1 | ## Question 1 - Fibonacci 2 | 3 | ```python 4 | N = int(input()) 5 | 6 | prev = 0 7 | curr = 1 8 | 9 | for _ in range(3, N+1): 10 | next = prev + curr 11 | prev = curr 12 | curr = next 13 | 14 | if N <= 0: 15 | print("Invalid!") 16 | elif N == 1: 17 | print(prev) 18 | else: 19 | print(curr) 20 | ``` 21 | 22 | ## Question 2 - Second Largest 23 | 24 | ```python 25 | x = int(input()) 26 | largest = 0 27 | second = 0 28 | 29 | while x != 0: 30 | if x > largest: 31 | second = largest 32 | largest = x 33 | elif x > second: 34 | second = x 35 | x = int(input()) 36 | 37 | print(largest-second) 38 | ``` 39 | 40 | ## Question 3 - Digiiiits 41 | 42 | ```python 43 | x = int(input()) 44 | 45 | count = 0 46 | even_sum = 0 47 | 48 | while x > 0: 49 | digit = x % 10 50 | if digit % 2 == 0: 51 | even_sum += digit 52 | count += 1 53 | 54 | x //= 10 55 | 56 | print(count, even_sum) 57 | ``` 58 | 59 | ## Question 4 - Positive Mental Attitude 60 | 61 | ```python 62 | odd_sum = 0 63 | 64 | x = int(input()) 65 | while x >= 0: 66 | if x % 2 == 1: 67 | odd_sum += x 68 | x = int(input()) 69 | 70 | print(odd_sum) 71 | ``` 72 | 73 | ## Question 5 - NoBig 74 | 75 | ```python 76 | total_sum = 0 77 | count = 1 78 | 79 | x = int(input()) 80 | y = int(input()) 81 | total_sum += x 82 | while y <= x: 83 | total_sum += y 84 | count += 1 85 | 86 | x = y 87 | y = int(input()) 88 | 89 | print(total_sum/count) 90 | ``` 91 | 92 | ## Question 6 - Guess 93 | 94 | ```python 95 | import random 96 | 97 | number = random.randint(1,100) 98 | count = 0 99 | 100 | while True: 101 | guess = input("Make your guess: ") 102 | guess = int(guess) 103 | count += 1 104 | 105 | if guess < number: 106 | print("Too low!") 107 | elif guess > number: 108 | print("Too high!") 109 | else: 110 | print("You got it!") 111 | print("And it only took you",count,"tries!") 112 | break 113 | ``` 114 | 115 | ## Question 7 - Sum Facts 116 | 117 | ```python 118 | x = int(input()) 119 | 120 | fact_sum = 0 121 | 122 | while x > 0: 123 | digit = x % 10 124 | fact = 1 125 | for i in range(2, digit+1): 126 | fact *= i 127 | fact_sum += fact 128 | 129 | x //= 10 130 | 131 | print(fact_sum) 132 | ``` 133 | 134 | ## Question 8 - Sum of Digits 135 | 136 | ```python 137 | n = int(input()) 138 | 139 | while n >= 10: 140 | sum = 0 141 | while n: 142 | sum += n%10 143 | n //= 10 144 | n = sum 145 | 146 | print(n) 147 | ``` 148 | 149 | ## Question 9 - Prime factors 150 | 151 | ### Question 9a 152 | 153 | ```python 154 | number = int(input()) 155 | for i in range(1, number + 1): 156 | if number % i == 0: 157 | print(i, end =" ") 158 | 159 | ``` 160 | 161 | ### Question 9b 162 | 163 | ```python 164 | number = int(input()) 165 | for i in range(2, number + 1): 166 | while number % i == 0: 167 | number //= i 168 | print(i, end=" ") 169 | 170 | ``` 171 | 172 | This works because at any point in the loop, number doesn't have any factors smaller than `i`. Therefore, `i` has to be prime if it divides `number`. 173 | 174 | ### Question 9c 175 | 176 | ```python 177 | number = int(input()) 178 | firstPrime = True 179 | for i in range(2, number + 1): 180 | count = 0 181 | while number % i == 0: 182 | number //= i 183 | count += 1 184 | if count > 0: 185 | if firstPrime: 186 | firstPrime = False 187 | else: 188 | print(" * ", end="") 189 | print(i, "^", count, end="") 190 | 191 | ``` 192 | 193 | ## Question 10 - Palindromic Primes 194 | 195 | ```python 196 | def reverse_number(number): 197 | reverse = 0 198 | while num != 0: 199 | digit = num % 10 200 | num = num // 10 201 | reverse = reverse * 10 + digit 202 | return reverse 203 | 204 | def is_prime(number): 205 | if number <= 1: 206 | return False 207 | for i in range(2, number): 208 | if number % i == 0: 209 | return False 210 | return True 211 | start = int(input()) 212 | end = int(input()) 213 | 214 | for i in range(start, end + 1): 215 | if reverse_number(i) == i and is_prime(i): 216 | print(i, end = " ") 217 | 218 | ``` 219 | 220 | -------------------------------------------------------------------------------- /week06/README.md: -------------------------------------------------------------------------------- 1 | ## Question 1 2 | 3 | Write a program that takes an integer n and then prints related hailstone sequence until 1. If number is even, divide it by 2. If number is odd, multiply it by 3 and add 1. 4 | 5 | | INPUT | OUTPUT | 6 | | ----- | ---------------------- | 7 | | 20 | 20 10 5 16 8 4 2 1 | 8 | | 12 | 12 6 3 10 5 16 8 4 2 1 | 9 | 10 | ## 11 | 12 | ## Question 2 13 | 14 | Given a positive integer N, calculate the sum of the series that consist of N numbers and goes like: N, NN, NNN... For example if N is 2, we calculate 2 + 22; if N is 5 we calculate 5 + 55 + 555 + 5555 + 55555 15 | 16 | | INPUT | OUTPUT | 17 | | ----- | ------ | 18 | | 2 | 24 | 19 | | 6 | 740736 | 20 | | 3 | 369 | 21 | 22 | ## Question 3 23 | 24 | Binary search is a searching algorithm that finds an element n in a sorted list L of size s. Firstly it compares n to L[s//2]. If n is bigger than L[s//2], it means that n is in upper half of the list. Likewise, if n is smaller than L[s//2], it means n is in lower half of the list. Then, the half of list which does not contain n is discarded. This process repeated until k th step where L[s//2**k] equals to n or list is empty. 25 | 26 | Write a function which implements binary search to find whether or nor a float exists in a list of floats. 27 | 28 | | Input | Output | 29 | | ----------------------------------------- | ------------------------- | 30 | | L = [ 1 , 3 , 4 , 5 , 6] , num = 5 | 5 exists in list | 31 | | L = [ 21 , 13 , 4.4 , 85 , 60] , num = 16 | 16 does not exist in list | 32 | 33 | ## Question 4 34 | 35 | A number is said to be "Disarium" if the sum of its digits raised to their respective positions is the number itself. Write a program that determines whether a number is a Disarium or not. 36 | 37 | 75 ➞ False 38 | 39 | *7^1 + 5^2 = 7 + 25 = 32* 40 | 41 | 135 ➞ True 42 | 43 | *1^1 + 3^2 + 5^3 = 1 + 9 + 125 = 135* 44 | 45 | Example Inputs/Outputs: 46 | 47 | 544 ➞ False 48 | 49 | 518 ➞ True 50 | 51 | 466 ➞ False 52 | 53 | 8 ➞ True 54 | 55 | 56 | 57 | 58 | 59 | ## Question 5 60 | 61 | In number theory, [Euler's Totient function](https://en.wikipedia.org/wiki/Euler's_totient_function) counts the positive integers up to a given integer *n* that are relatively prime to n. Write three functions, respectively `gcd(a, b)`, `relatively_prime(a, b)` and `euler_totient(a)`. To find `euler_totient(a)`, count the number of integers between 1 and *n* that are relatively prime with *n*. A number *a* is relatively prime with *b* iff `gcd(a, b) = 1`. To implement `gcd(a, b)`, follow the steps below. Given an integer *n*, print out the `euler_totient(n)`. To find the greates common divisor between *a* and *b*: 62 | 63 | - Repeatedly replace (*a*,*b*) with (*b*,*a %* b) until the second integer in the pair is zero. 64 | - Return the first integer in the pair as the gcd. 65 | 66 | | INPUT | OUTPUT | 67 | | ----- | ------ | 68 | | 10 | 4 | 69 | | 342 | 108 | 70 | | 76 | 36 | 71 | 72 | ## Question 6 73 | 74 | Consider that you need to fill containers to a trans-atlantic bulk carrier. You want to choose containers such that total profit of ships cargo is maximized. However, there is a mass limit the of the cargo. 75 | 76 | Write a function that inputs the ships mass capacity and 2 arrays: weight and profit. weight[i] indicates the mass of container[i] and profit[i] is the profit earned from container[i]. Note: Each container[i] indicates a unique container. 77 | 78 | | Input | Output | 79 | | --------------------------------------------------------- | --------------- | 80 | | weight = [10, 20, 30], profit = [4 , 5 , 60] , limit = 30 | Max Profit = 60 | 81 | 82 | -------------------------------------------------------------------------------- /week06/Solution.md: -------------------------------------------------------------------------------- 1 | ## Question 1 2 | 3 | ```python 4 | n = int(input()) 5 | 6 | while n != 1: 7 | print(n,end=" ") 8 | n = n*3 +1 if n %2 else n//2 9 | print(1) 10 | ``` 11 | 12 | ## Question 2 13 | 14 | ```python 15 | N = int(input()) 16 | 17 | my_sum = 0 18 | for i in range(1, N+1): 19 | my_sum *= 10 20 | for j in range(i): 21 | my_sum += N 22 | 23 | print(my_sum) 24 | ``` 25 | 26 | ## Question 3 27 | 28 | ```python 29 | def binary_find(num, L): 30 | while len(L) != 0: 31 | if num == L[len(L)//2]: 32 | return True 33 | elif num > L[len(L)//2]: 34 | L = L[len(L)//2+1:] 35 | else: 36 | L = L[:len(L)//2] 37 | return False 38 | 39 | 40 | ``` 41 | 42 | ## Question 4 43 | 44 | ```python 45 | def reverse(num): 46 | reversed_num = 0 47 | while num > 0: 48 | digit = num % 10 49 | reversed_num = reversed_num * 10 + digit 50 | num = num // 10 51 | return reversed_num 52 | n = int(input()) 53 | reversed = reverse(n) 54 | digit = 1 55 | total = 0 56 | while reversed > 0: 57 | total += (reversed % 10) ** digit 58 | digit += 1 59 | reversed = reversed // 10 60 | print(n == total) 61 | 62 | ``` 63 | 64 | ## Question 5 65 | 66 | ```python 67 | def gcd(a, b): 68 | a = abs(a) 69 | b = abs(b) 70 | 71 | while(b != 0): 72 | rem = a 73 | a = b 74 | b = rem % b 75 | return a 76 | 77 | def relatively_prime(a, b): 78 | return gcd(a, b) ==1 79 | 80 | def euler_totient(n): 81 | cnt = 0 82 | for i in range(n+1): 83 | cnt = cnt + 1 if relatively_prime(i, n) else cnt 84 | return cnt 85 | 86 | a = int(input()) 87 | print(euler_totient(a)) 88 | ``` 89 | 90 | ## Question 6 91 | 92 | ```python 93 | def max(limit, weight, profit): 94 | total_profit = 0 95 | sum = 0 96 | max_profit = -1 97 | max_index = -1 98 | while sum < limit: 99 | for i in range(len(weight)): 100 | profit_per_mass = profit[i]/weight[i] 101 | if profit_per_mass > max_profit: 102 | max_index = i 103 | max_profit = profit_per_mass 104 | if max_index == -1: 105 | break 106 | if sum + weight[max_index] <= weight[max_index]: 107 | total_profit += profit[max_index] 108 | sum += weight[max_index] 109 | profit[max_index] = 0 110 | max_index = -1 111 | max_profit = -1 112 | return total_profit 113 | 114 | weight = [10, 20, 30] 115 | profit = [4 , 5 , 60] 116 | limit = 30 117 | 118 | print(max(limit, weight, profit)) 119 | ``` 120 | 121 | -------------------------------------------------------------------------------- /week07/Solutions.md: -------------------------------------------------------------------------------- 1 | # Strings 2 | 3 | ## Question 1 - SpOnGeBoB MeMe 4 | 5 | ```python 6 | # https://www.codewars.com/kata/5982619d2671576e90000017 7 | def sponge_bob(sentence): 8 | return "".join([sentence[i].lower() if i % 2 else sentence[i].upper() for i in range(len(sentence))]) 9 | 10 | def spongebob(input_str): 11 | result_str = "" 12 | for i, s in enumerate(input_str): 13 | if i % 2 == 0: 14 | result_str += s.upper() 15 | else: 16 | result_str += s.lower() 17 | 18 | return result_str 19 | 20 | print(sponge_bob("stop making sponge bob memes")) 21 | ``` 22 | 23 | 24 | ## Question 2 - Convert string to camel case 25 | 26 | ```python 27 | # https://www.codewars.com/kata/517abf86da9663f1d2000003/train/python 28 | def to_camel_case(text): 29 | result = "" 30 | flag = True 31 | for i in text: 32 | if i in ["-", "_"]: 33 | flag = True 34 | else: 35 | result += i.upper() if flag else i.lower() 36 | flag = False 37 | 38 | return result 39 | 40 | def to_camel_case_s(text): 41 | text = text.replace('-', '_') 42 | words = text.split('_') 43 | return ''.join([word.title() for word in words]) 44 | 45 | print(to_camel_case("to_camel_case")) 46 | print(to_camel_case("Hard_exam-pLe")) 47 | print(to_camel_case("unnecessarily-LONG-Example")) 48 | ``` 49 | 50 | ## Question 3 - Abbreviate 51 | 52 | ```python 53 | def abbreviation(st): 54 | if (len(st) <= 14): 55 | return st 56 | else: 57 | return st[0:2] + str(len(st) - 4) + st[-2:] 58 | ``` 59 | 60 | ## Question 4 - Stop gninnipS My sdroW 61 | 62 | ```python 63 | # https://www.codewars.com/kata/5264d2b162488dc400000001/train/python 64 | def spin_words(sentence): 65 | return " ".join([word[::-1] if len(word) > 4 else word for word in sentence.split()]) 66 | 67 | 68 | print(spin_words("This is another test")) 69 | print(spin_words( 70 | "You know you’re in love when you can’t fall asleep because reality is finally better than your dreams.")) 71 | print(spin_words("Challenges are what make life interesting and overcoming them is what makes life meaningful.")) 72 | ``` 73 | 74 | ## Question 5 - Requirements 75 | 76 | ```python 77 | def is_valid(password): 78 | length = len(password) 79 | if length < 6 or length > 20: 80 | return False 81 | lower, upper, digit = 0, 0, 0 82 | for c in password: 83 | lower += c.islower() 84 | upper += c.isupper() 85 | digit += c.isdigit() 86 | return lower >= 1 and upper >= 1 and digit >= 1 87 | ``` 88 | 89 | ## Question 6 - Length 90 | 91 | ```python 92 | sentence = input() 93 | words = sentence.split() 94 | lengths = [len(w) for w in words] 95 | shortest_index = lengths.index(min(lengths)) 96 | longest_index = lengths.index(max(lengths)) 97 | print(words[shortest_index], words[longest_index]) 98 | ``` 99 | 100 | ## Question 7 - Alphabetical order 101 | 102 | ```python 103 | items = input("Input comma separated sequence of words") 104 | words = [word.strip() for word in items.split(",")] 105 | print(", ".join(sorted(list(words)))) 106 | ``` 107 | 108 | 109 | ## Question 8 - Second Most Common 110 | ```python 111 | string = str(input()) 112 | modified = string.replace(" ", "").lower() 113 | Max = 0 114 | secondMax = 0 115 | second = '' 116 | first = '' 117 | for i in modified: 118 | occur = modified.count(i) 119 | if(occur > Max): 120 | second = first 121 | first = i 122 | secondMax = Max 123 | Max = occur 124 | elif(occur < Max and occur > secondMax): 125 | second = i 126 | secondMax = occur 127 | print(first, second) 128 | ``` 129 | 130 | ## Question 9 - Not poor 131 | 132 | ```python 133 | def not_poor(str1): 134 | snot = str1.find('not') 135 | spoor = str1.find('poor') 136 | if spoor > snot and snot > 0 and spoor > 0: 137 | str1 = str1.replace(str1[snot:(spoor+4)], 'good') 138 | return str1 139 | else: 140 | return str1 141 | print(not_poor('The lyrics is not that poor!')) 142 | print(not_poor('The lyrics is poor!')) 143 | ``` 144 | 145 | ## Question 10 - Find and replace 146 | 147 | ```python 148 | def find_and_replace(string, a, b): 149 | output = "" 150 | i = 0 151 | while i <= len(string) - len(a): 152 | if string[i:i + len(a)] == a[0:len(a)]: 153 | output += b 154 | i += len(a) 155 | else: 156 | output += string[i] 157 | i += 1 158 | return output 159 | 160 | def find_and_replace2(string, a, b): 161 | ix = 0 162 | while string.find(a, ix) != -1: 163 | ix = string.find(a, ix) 164 | string = string[:ix] + b + string[ix+len(a):] 165 | ix = ix + len(b) 166 | return string 167 | 168 | print(find_and_replace("This is another test", "is", "is not")) 169 | print(find_and_replace("I mean, it went badly last time but surely it will go much better this time.", "it", "filling zeppelins with hydrogen")) 170 | print(find_and_replace("Test test TeSt te st TEst teSt crest TEA", "st TE", "test")) 171 | ``` 172 | 173 | 174 | ## Question 11 - Reading Backwards 175 | ```python 176 | string = input() 177 | i = int(input()) 178 | 179 | words = string.split(" ") 180 | 181 | #1 182 | words.reverse() 183 | print(" ".join(words)) 184 | #2 185 | changed_words = list(words) 186 | for i in range(0,len(changed_words)): 187 | changed_words[i] = changed_words[i][::-1] 188 | print(" ".join(changed_words)) 189 | #3 190 | i_reverse = len(words)-i +1 191 | print(" ".join(words[i_reverse:])) 192 | #4 193 | print(" ".join(changed_words[i_reverse:])) 194 | ``` 195 | -------------------------------------------------------------------------------- /week08/README.md: -------------------------------------------------------------------------------- 1 | # Lists 2 | 3 | ## Question 1 - Large 4 | 5 | Write a program that reads an integer N from the user, then reads N more integers from the user and store them in a list. Then prints elements larger than the average of numbers held in the array. 6 | 7 | | Input | Output | 8 | | ------------------------------------------------------------ | ---------- | 9 | | 10
1
2
3
4
5
6
7
8
9
10 | 6 7 8 9 10 | 10 | | 4
4
1
3
8 | 8 | 11 | 12 | 13 | 14 | ## Question 2 - Let's Count 15 | 16 | Write a function that takes a list and find frequency of each element in the list then prints. Assume the numbers in the list will be between 0 and 100 (inclusive). 17 | 18 | | INPUT | OUTPUT | 19 | | ---------------------- | ------------------------------------------------------------ | 20 | | 5 10 2 5 50 5 10 1 2 2 | 1 --> 1
2 --> 3
5 --> 3
10 --> 2
50 --> 1 | 21 | 22 | 23 | 24 | ## Question 3 - Fifth Powers 25 | 26 | List comprehensions might enable you to turn loop-based codes into one line elegant expressions. Write a program that takes 5 integers as input and prints a new list consisting of the fifth power of each number. Try to construct and print the new list in just one line. 27 | 28 | | INPUT | OUTPUT | 29 | | ----------------- | --------------------------- | 30 | | [1, 2, 3, 5, 0] | [1, 32, 243, 3125, 0] | 31 | | [4, 1, 6, -2, -3] | [1024, 1, 7776, -32, -243] | 32 | | [-3, -6, 2, 9, 0] | [-243, -7776, 32, 59049, 0] | 33 | 34 | 35 | ## Question 4 - To the left 36 | 37 | Write a function which takes a list of numbers and an integer k and shifts the numbers to the left circularly by *k* and 38 | return the shifted list. 39 | 40 | | Input | Output | 41 | | ----------------- | --------------- | 42 | | [1, 2, 3, 4, 5] 2 | [3, 4, 5, 1, 2] | 43 | | [2, 18, 6, 0] 3 | [0, 2, 18, 6] | 44 | 45 | 46 | ## Question 5 - Reverse 47 | 48 | Write a program which reads a list of integers from the user and store them in a list. 49 | 50 | **a**. Then print them to the screen in reverse order. 51 | 52 | **b.** Then reverse the order of these integers in the array and print the array. 53 | 54 | | Input | Output | 55 | | -------------- | -------------- | 56 | | 3 1 -4 5 2 | 2 5 -4 1 3 | 57 | | 15 7 2 89 8 12 | 12 8 89 2 7 15 | 58 | 59 | 60 | 61 | ## Question 6 - Remove X 62 | 63 | Write a function that accepts a list and variable X and removes all occurrence of X from the list. 64 | 65 | | INPUT | OUTPUT | 66 | | ------------------------------- | --------------- | 67 | | [5, 20, 15, 20, 25, 50, 20], 20 | [5, 15, 25, 50] | 68 | 69 | 70 | ## Question 7 - Remove Duplicates 71 | 72 | Write a function that takes a list of integers then returns without all duplicates. 73 | 74 | | Input | Output | 75 | | --------------------------------------- | :-------------- | 76 | | [1, 1, 1, 1, 1, 2, 2, 2, 3, 2, 2, 4, 5] | [1, 2, 3, 4, 5] | 77 | | [0,0,0,0,0,0,0] | [0] | 78 | 79 | 80 | 81 | ## Question 8 - Odd Occurrences 82 | 83 | Write a function that takes a list and prints the elements that occur 2n+1 times. If there is no element with odd number 84 | of occurrences then it should not print anything. 85 | 86 | | Input | Output | 87 | | ----------------------------------------------- | --------- | 88 | | [1, 1, 2, 3, 4, 2, 'apple', 'banana', 'banana'] | 3 4 apple | 89 | | [2, 2, 3, 3, 2] | 2 | 90 | | [ 'a' , 'b' , 'c' , 'c' , 'b' , 'a' ] | | 91 | 92 | # Tuples 93 | 94 | ## Question 9 - Fractions 95 | 96 | Fractions can be expressed as as tuple: (numerator, denominator). 97 | 98 | Write a function that adds two fractions that are passed as tuples. 99 | 100 | | Input | Output | 101 | | ------------- | -------- | 102 | | (1, 3) (4, 5) | (17, 15) | 103 | | (3, 5) (1, 2) | (11, 10) | 104 | 105 | ## Question 10 - Points 106 | 107 | Points can be expressed as as tuple: (x, y). 108 | 109 | #### Question 10a - Distance 110 | 111 | Write a function **distance** which takes two tuples (points) and returns Euclidian distance between these points. 112 | 113 | | Input | Output | 114 | | --------------- | ------ | 115 | | (3, 0) (0, 4) | 5.0 | 116 | | (5, 8) (10, 20) | 13.0 | 117 | 118 | #### Question 10b - Closest 119 | 120 | Write a function which takes two tuples (points) and returns the point closest to the origin. *Use the distance 121 | function.* 122 | 123 | | Input | Output | 124 | | -------------- | ------ | 125 | | (3, 0) (0, 4) | (3, 0) | 126 | | (11, 7) (6, 8) | (6, 8) | 127 | 128 | #### Question 10c - Farthest 129 | 130 | Write a program which takes an integer N and reads N points (given by their x and y coordinates) and determines the pair 131 | that is the farthest apart. 132 | 133 | | Input | Output | 134 | | ------------------------------------------- | ------------------- | 135 | | 3
3 0
0 0
0 4 | (0, 4)
(3, 0) | 136 | | 5
10 5
4 8
0 8
4 5
-1 2 | (-1, 2)
(10, 5) | 137 | 138 | 139 | -------------------------------------------------------------------------------- /week08/Solutions.md: -------------------------------------------------------------------------------- 1 | # Lists 2 | 3 | ## Question 1 - Large 4 | 5 | ```python 6 | N = int(input()) 7 | 8 | list1 = list() 9 | num_sum = 0 10 | for i in range(N): 11 | num = int(input()) 12 | list1.append(num) 13 | num_sum += num 14 | 15 | average = num_sum / N 16 | # average = sum(list1)/len(list1) 17 | 18 | for item in list1: 19 | if item > average: 20 | print(item, end=' ') 21 | 22 | """for i in range(N): 23 | if list1[i] > average: 24 | print(list1[i], end=' ')""" 25 | 26 | ``` 27 | 28 | ## Question 2 - Let's Count 29 | 30 | ```python 31 | def find_freq(list1): 32 | freq_list = [0] * 101 33 | for l in list1: 34 | freq_list[l] += 1 35 | for i, frequency in enumerate(freq_list): 36 | if frequency != 0: 37 | print(i, ' --> ', frequency) 38 | 39 | 40 | find_freq([5, 10, 2, 5, 50, 5, 10, 1, 2, 2]) 41 | ``` 42 | 43 | 44 | 45 | ## Question 3 - Fifth Powers 46 | 47 | ```python 48 | list1 = list(map(int, input().split())) 49 | print([x**5 for x in list1]) 50 | 51 | """Alternative solution: 52 | new_list = list() 53 | for x in list1: 54 | new_list.append(x ** 5) 55 | print(new_list) 56 | """ 57 | 58 | ``` 59 | 60 | ## Question 4 - To the left 61 | 62 | ```python 63 | def rotate(l, n): 64 | return l[n:] + l[:n] 65 | 66 | 67 | print(rotate([1, 2, 3, 4, 5], 2)) 68 | ``` 69 | 70 | 71 | 72 | ## Question 5 - Reverse 73 | 74 | ```python 75 | N = int(input()) 76 | 77 | list1 = list() 78 | for i in range(N): 79 | list1.append(int(input())) 80 | 81 | # a 82 | print(list1[::-1]) 83 | 84 | # b 85 | list1 = list1[::-1] 86 | # list1.reverse() 87 | print(list1) 88 | ``` 89 | 90 | 91 | ## Question 6 - Remove X 92 | 93 | ```python 94 | list1 = [5, 20, 15, 20, 25, 50, 20] 95 | 96 | 97 | def removeValue(sampleList, val): 98 | return [value for value in sampleList if value != val] 99 | 100 | """ Alternative solution: 101 | def removeValue(sampleList, val): 102 | new_list = [] 103 | for item in sampleList: 104 | if item != X: 105 | new_list.append(item) 106 | return new_list 107 | """ 108 | 109 | resList = removeValue(list1, 20) 110 | print(resList) 111 | 112 | 113 | 114 | ``` 115 | 116 | ## Question 7 - Remove Duplicates 117 | 118 | ```python 119 | def remove_duplicates(list1): 120 | result = [] 121 | for i in list1: 122 | if i not in result: 123 | result.append(i) 124 | return result 125 | # return list(dict.fromkeys(list1)) 126 | 127 | 128 | example = [1, 1, 1, 1, 1, 2, 2, 2, 3, 2, 2, 4, 5] 129 | print(remove_duplicates(example)) 130 | 131 | ``` 132 | 133 | ## Question 8 - Odd Occurrences 134 | 135 | ```python 136 | def oddones(l): 137 | mylist = [] 138 | 139 | for i in range(len(l)): 140 | if not l[i] in mylist: 141 | mylist.append(l[i]) 142 | else: 143 | mylist.remove(l[i]) 144 | 145 | for i in range(len(mylist)): 146 | print(mylist[i], end=' ') 147 | 148 | 149 | oddones([1, 1, 2, 3, 3, 3]) 150 | ``` 151 | 152 | # Tuples 153 | 154 | ## Question 9 - Fractions 155 | 156 | ```python 157 | def simplify(nom, denom): 158 | factor = min(nom, denom) 159 | while factor > 1: 160 | if nom % factor == 0 and denom % factor == 0: 161 | nom //= factor 162 | denom //= factor 163 | factor -= 1 164 | return nom, denom 165 | 166 | 167 | def addition(frac1, frac2): 168 | common_denominator = frac1[1] * frac2[1] 169 | nominator_sum = frac1[0] * frac2[1] + frac2[0] * frac1[1] 170 | return simplify(nominator_sum, common_denominator) 171 | 172 | print(addition((3, 5), (4, 8))) 173 | ``` 174 | 175 | ## Question 10 - Points 176 | 177 | ### Question 10a - Distance 178 | 179 | ```python 180 | def distance(point1, point2): 181 | return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** (1 / 2) 182 | 183 | 184 | print(distance((3, 0), (0, 4))) 185 | ``` 186 | 187 | ### Question 10b - Closest 188 | 189 | ```python 190 | def distance(point1, point2): 191 | return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** (1 / 2) 192 | 193 | 194 | def closest(point1, point2): 195 | dist1 = distance(point1, (0, 0)) 196 | dist2 = distance(point2, (0, 0)) 197 | return point2 if dist1 > dist2 else point1 198 | 199 | 200 | print(closest((3, 0), (0, 4))) 201 | ``` 202 | 203 | ### Question 10c - Farthest 204 | 205 | ```python 206 | def distance(point1, point2): 207 | return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** (1 / 2) 208 | 209 | 210 | N = int(input()) 211 | points = [] 212 | for i in range(N): 213 | x, y = input().split() 214 | points.append((int(x), int(y))) 215 | 216 | max_dist = None 217 | for i, p1 in enumerate(points): 218 | for p2 in points[i + 1:]: 219 | dist = distance(p1, p2) 220 | if max_dist is None or dist > max_dist: 221 | max_dist = dist 222 | farthest = (p1, p2) 223 | 224 | print(farthest) 225 | ``` 226 | 227 | -------------------------------------------------------------------------------- /week09/Solutions.md: -------------------------------------------------------------------------------- 1 | # Dictionary 2 | 3 | ## Question 1 - Letter Count 4 | 5 | ```python 6 | sentence = input() 7 | my_dict = dict() 8 | total_letter =0 9 | for letter in sentence: 10 | if letter.isalpha(): 11 | letter = letter.lower() 12 | total_letter += 1 13 | if letter not in my_dict: 14 | my_dict[letter] = 1 15 | else: 16 | my_dict[letter] += 1 17 | 18 | sorted_dict = sorted(my_dict.items(), key=lambda x: (-x[1], x[0])) 19 | for k,v in sorted_dict: 20 | print(k,"->","{:.2f}".format(v/total_letter)) 21 | ``` 22 | 23 | ## Question 2 - Different Types 24 | 25 | ```python 26 | elements = [10, 4.20, False, 'Word', 'CMPE150', 30, 3.5, 9.99, 'oblivion', True, 68, 88, "88"] 27 | element_dict = {} 28 | for el in elements: 29 | if el not in element_dict: 30 | element_dict[type(el)] = [el] 31 | else: 32 | element_dict[type(el)].append(el) 33 | for el_type, el_list in element_dict.items(): 34 | print(el_type, '->', el_list) 35 | ``` 36 | 37 | ## Question 3 - Zip Two Lists 38 | 39 | ```python 40 | list1 = ["melih", "burak", "ahmet", "recep", "melis"] 41 | list2 = [1,2,3,4,5] 42 | def dict_2_lists(list1, list2): 43 | return dict(zip(list1, list2)) 44 | 45 | print(dict_2_lists(list1,list2)) 46 | ``` 47 | 48 | Alternative: 49 | 50 | ```python 51 | list1 = ["melih", "burak", "ahmet", "recep", "melis"] 52 | list2 = [1,2,3,4,5] 53 | zip_dict = {} 54 | for l1, l2 in zip(list1, list2): 55 | zip_dict[l1] = l2 56 | 57 | print(zip_dict) 58 | ``` 59 | 60 | ## Question 4 - Dictionary Merge 61 | 62 | ```python 63 | def merge(*dicts): 64 | mydict = dict() 65 | for d in dicts: 66 | for k, v in d.items(): 67 | if k in mydict: 68 | mydict[k].append(d[k]) 69 | else: 70 | mydict[k] = [v] 71 | return mydict 72 | 73 | print(merge({"A": 1, "B": 2} , {"A": 3})) 74 | ``` 75 | 76 | Alternative: 77 | 78 | ```python 79 | def merge(l_dicts): 80 | result_dict = {} 81 | for dictionary in l_dicts: 82 | for k, v in dictionary.items(): 83 | if k not in result_dict: 84 | result_dict[k] = [] 85 | result_dict[k].append(v) 86 | return result_dict 87 | 88 | print(merge({"A": 1, "B": 2} , {"A": 3})) 89 | ``` 90 | 91 | ## Question 5 - Data Collection 92 | 93 | ```python 94 | lines = [] 95 | line = str(input()) 96 | while line != "exit": 97 | lines.append(line) 98 | line = str(input()) 99 | 100 | mydict = {} 101 | for line in lines: 102 | line = line.split() # transform into a list 103 | info = {'genre' : line[1], 'release_date': line[2], 'producer':line[3]} 104 | mydict[line[0]] = info 105 | print(mydict) 106 | ``` 107 | 108 | Alternative: 109 | 110 | ```python 111 | game_dict = {} 112 | while True: 113 | data = input().strip() 114 | if data == "exit": 115 | break 116 | name, genre, year, producer = data.split() 117 | game_dict[name] = {"genre": genre, "release_date": year, 'producer': producer} 118 | 119 | for k, v in game_dict.items(): 120 | print(k, v) 121 | 122 | print(game_dict["Fifa14"]["genre"]) 123 | ``` 124 | 125 | ## Question 6 - Sorting Dictionary 126 | 127 | ```python 128 | def sort_dict(d): 129 | return sorted(d.items(), key=lambda x: x[1], reverse=True) 130 | 131 | print(sort_dict({3:1, 2:2, 1:3})) 132 | ``` 133 | 134 | ## Question 7 - Word Frequency 135 | 136 | ```python 137 | mylist = str(input()).split() 138 | mydict = {} 139 | 140 | for i in mylist: 141 | mydict[i] = 1 if mydict.get(i) is None else mydict[i] + 1 142 | for i in sorted(mydict, key=mydict.get, reverse=True): 143 | print(i, end = " ") 144 | ``` 145 | 146 | Alternative: 147 | 148 | ```python 149 | words = input().strip().split() 150 | word_count = {} 151 | 152 | for word in words: 153 | word_count[word] = 1 if word not in word_count else word_count[word] + 1 154 | for k, v in sorted(word_count.items(), key=lambda item: item[1], reverse=True): 155 | print(k, end = " ") 156 | ``` 157 | 158 | ## Question 8 - Anagrams 159 | 160 | ```python 161 | word_list = ["percussion", "supersonic", "car", "tree", "boy", "girl", "arc"] 162 | 163 | def freq(word): 164 | freq_dict = {} 165 | for char in word: 166 | freq_dict[char] = freq_dict.get(char, 0) + 1 167 | return freq_dict 168 | 169 | anagram_list = [] 170 | for word_1 in word_list: 171 | for word_2 in word_list: 172 | if word_1 != word_2 and (freq(word_1) == freq(word_2)): 173 | anagram_list.append(word_1) 174 | print(anagram_list) 175 | ``` 176 | 177 | ## Question 9 - Vasya - Clerk 178 | 179 | ```python 180 | def tickets(people): 181 | change = {25: 0, 50: 0, 100: 0} 182 | for money in people: 183 | if money == 25: 184 | change[25] += 1 185 | elif money == 50: 186 | change[25] -= 1 187 | change[50] += 1 188 | elif money == 100 and change[50] > 0: 189 | change[25] -= 1 190 | change[50] -= 1 191 | elif money==100 and change[50] == 0: 192 | change[25] -= 3 193 | 194 | if change[25] < 0 or change[50] < 0: 195 | return 'NO' 196 | return 'YES' 197 | 198 | print(tickets([25, 25, 50])) # => YES 199 | print(tickets([25, 100])) # => NO. Vasya will not have enough money to give change to 100 dollars 200 | print(tickets([25, 25, 50, 50, 100])) # => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50) 201 | ``` 202 | -------------------------------------------------------------------------------- /week10/Solutions.md: -------------------------------------------------------------------------------- 1 | # Sets 2 | 3 | ## Question 1 - Set Operations 4 | 5 | ```python 6 | A = {1, 2, 3, 4, 5, 6} 7 | B = {1, 1, 2, 7, 11} 8 | 9 | def set_operations(set1, set2): 10 | print("A ∪ B = {}".format(set1.union(set2))) 11 | print("A ∩ B = {}".format(set1.intersection(set2))) 12 | print("A / B = {}".format(set1.difference(set2))) 13 | print("B / A = {}".format(set2.difference(set1))) 14 | 15 | set_operations(A, B) 16 | ``` 17 | 18 | ## Question 2 - Eligible to graduate? 19 | 20 | ```python 21 | required = {"CmpE150","CmpE160","CmpE220","CmpE250","CmpE260"} 22 | def is_eligible(current): 23 | if len(required.intersection(current)) == len(required): 24 | return "Eligible" 25 | else: 26 | return "Not Eligible" 27 | print(is_eligible({"Cmpe150"})) 28 | ``` 29 | 30 | Alternative: 31 | 32 | ```python 33 | required = {"CmpE150","CmpE160","CmpE220","CmpE250","CmpE260"} 34 | def is_eligible(current): 35 | if required.intersection(current) == required: 36 | return "Eligible" 37 | else: 38 | return "Not Eligible" 39 | print(is_eligible({"Cmpe150"})) 40 | ``` 41 | 42 | ## Question 3 - How good friends can they be? 43 | 44 | ```python 45 | def overall_traits(traits1, traits2): 46 | intersection = traits1.intersection(traits2) 47 | return sum(intersections) 48 | ``` 49 | 50 | ## Question 4 - Distinct 51 | 52 | ```python 53 | def is_distinct(string): 54 | return len(set(string)) == len(string) 55 | 56 | print(is_distinct('violate')) 57 | ``` 58 | 59 | # Files 60 | 61 | ## Question 5 - Reverse Lines 62 | 63 | ```python 64 | filename = input() 65 | input_f = open(filename, 'r') 66 | output_f = open('output.txt', 'w') 67 | for line in input_f: 68 | output_f.write(line[::-1]) 69 | input_f.close() 70 | output_f.close() 71 | ``` 72 | 73 | Alternative: 74 | 75 | ```python 76 | filename = input() 77 | 78 | with open(filename, 'r') as input_f: 79 | lines = input_f.readlines() 80 | 81 | with open('output.txt', 'w') as output_f: 82 | for line in lines: 83 | line = line.strip() 84 | output_f.write(line[::-1] + "\n") 85 | ``` 86 | 87 | ## Question 6 - Pluralize 88 | 89 | ```python 90 | with open('input.txt','r') as f: 91 | words = [line.strip() for line in f.readlines()] 92 | alphas = [word for word in words if word.isalpha()] 93 | 94 | with open('output.txt','w') as f: 95 | f.write("\n".join([word +'s' if word[-1] != 'y' else word[:-1]+'ies' for word in alphas])) 96 | ``` 97 | 98 | Alternative: 99 | 100 | ```python 101 | input_filename = "q6.txt" 102 | output_filename = "pluralWords.txt" 103 | 104 | with open(input_filename, "r") as input_file: 105 | lines = input_file.readlines() 106 | words = [line.strip() for line in lines] 107 | alphas = [word for word in words if word.isalpha()] 108 | 109 | with open(output_filename, "w") as output_file: 110 | for word in alphas: 111 | if word[-1] == "y": 112 | plural_word = word[:-1] + "ies" 113 | else: 114 | plural_word = word + "s" 115 | output_file.write(plural_word + "\n") 116 | ``` 117 | 118 | ## Question 7 - Correct Grades 119 | 120 | ```python 121 | with open("grades.txt", 'r') as f: 122 | mt1 = [str(max(0, int(grade))) for grade in f.readline().split()] 123 | mt2 = [str(max(0, int(grade))) for grade in f.readline().split()] 124 | final = [str(max(0, int(grade))) for grade in f.readline().split()] 125 | 126 | with open("corrected.txt", 'w') as f: 127 | f.write(' '.join(mt1)) 128 | f.write('\n') 129 | f.write(' '.join(mt2)) 130 | f.write('\n') 131 | f.write(' '.join(final)) 132 | ``` 133 | 134 | # List Bonus Question 135 | 136 | ## Question 8 - Bubble Sort 137 | 138 | ```python 139 | def bubble_sort(arr): 140 | n = len(arr) 141 | 142 | # Traverse through all array elements 143 | for i in range(n - 1): 144 | # range(n) also work but outer loop will repeat one time more than needed. 145 | 146 | # Last i elements are already in place 147 | for j in range(0, n - i - 1): 148 | 149 | # traverse the array from 0 to n-i-1 150 | # Swap if the element found is greater 151 | # than the next element 152 | if arr[j] > arr[j + 1]: 153 | arr[j], arr[j + 1] = arr[j + 1], arr[j] 154 | 155 | # temp = arr[j] 156 | # arr[j] = arr[j+1] 157 | # arr[j+1] = temp 158 | 159 | return arr 160 | 161 | 162 | print(bubble_sort([4, 2, 8, 6, 7, 3, 1, 5])) 163 | 164 | #print(sorted([4, 2, 8, 6, 7, 3, 1, 5])) 165 | ``` 166 | 167 | 168 | --------------------------------------------------------------------------------