├── 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 ├── README.md ├── 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 ├── 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 └── 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 /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/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/Fall20/figures/ChangeTheme.png -------------------------------------------------------------------------------- /Fall20/figures/HTML_Browser.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/Fall20/figures/HTML_Browser.png -------------------------------------------------------------------------------- /Fall20/figures/HTML_Explorer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/Fall20/figures/HTML_Explorer.png -------------------------------------------------------------------------------- /Fall20/figures/Maintxt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/Fall20/figures/Maintxt.png -------------------------------------------------------------------------------- /Fall20/figures/Teaching.Codes New Version.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/Fall20/figures/Teaching.Codes New Version.png -------------------------------------------------------------------------------- /Fall20/figures/Teaching.Codes Uninstall.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/Fall20/figures/Teaching.Codes Uninstall.png -------------------------------------------------------------------------------- /Fall20/figures/Teaching.Codes Version 1212JB.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/Fall20/figures/Teaching.Codes Version 1212JB.png -------------------------------------------------------------------------------- /Fall20/figures/commit_and_push_failed1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/Fall20/figures/commit_and_push_failed1.png -------------------------------------------------------------------------------- /Fall20/figures/commit_and_push_failed2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/Fall20/figures/commit_and_push_failed2.png -------------------------------------------------------------------------------- /Fall20/figures/connection.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/Fall20/figures/connection.PNG -------------------------------------------------------------------------------- /Fall20/figures/could not open.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/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/week03/README.md: -------------------------------------------------------------------------------- 1 | # Loops 2 | 3 | ## Question 1 - Staaaars 4 | 5 | ### Question 1a 6 | Write a program that prints 1 star ('\*') to the screen. 7 | 8 | ### Question 1b 9 | Write a program that prints 10 stars ('\*') next to each other to the screen. 10 | 11 | ### Question 1c 12 | Write a program that reads an integer N and prints N stars ('\*') vertically to the screen. 13 | 14 | ### Question 1d 15 | Write a program that reads an integer N and prints N stars ('\*') next to each other to the screen. 16 | 17 | 18 | 19 | ## Question 2 - Numbeeeers 20 | 21 | Write a program that reads an integer N and prints numbers from 1 to N to the screen. 22 | 23 | | INPUT | OUTPUT | 24 | |:-------:|:-------:| 25 | | 5 | 1 2 3 4 5 | 26 | | 2 | 1 2 | 27 | 28 | 29 | 30 | ## Question 3 - Hooping Numbers 31 | 32 | ### Question 3a 33 | 34 | 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. 35 | 36 | | INPUT | OUTPUT | 37 | |:-------:|:-------:| 38 | | 7 16 3 | 7 10 13 16 | 39 | | 2 30 6 | 2 8 14 20 26 | 40 | 41 | 42 | ### Question 3b 43 | 44 | 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. 45 | 46 | | INPUT | OUTPUT | 47 | |:-------:|:-------:| 48 | | 7 16 3 | 16 13 10 7 | 49 | | 2 30 6 | 30 24 18 12 6 | 50 | 51 | 52 | 53 | ## Question 4 - Even Numbeeeers 54 | 55 | 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. 56 | 57 | | INPUT | OUTPUT | 58 | |:-------:|:-------:| 59 | | 3 8 | 10 | 60 | | 2 13 | 40 | 61 | | 3 5 | 4 | 62 | 63 | 64 | 65 | ## Question 5 - Average Team 66 | 67 | Write a program that reads a number N, then reads N more numbers. Calculate the average of those N numbers. 68 | 69 | | INPUT | OUTPUT | 70 | |:-------:|:-------:| 71 | | 4
4 9 5 2 | 5.0 | 72 | | 1
8 | 8.0 | 73 | 74 | 75 | ## Question 6 - Boom Boom POW 76 | 77 | Write a program that takes 2 integers a and b, then prints the result of a^b (a\*a\*a...\*a\*a). 78 | 79 | | INPUT | OUTPUT | 80 | |:-------:|:-------:| 81 | | 3 4 | 81 | 82 | | 2 10 | 1024 | 83 | 84 | 85 | ## Question 7 - Factorial 86 | 87 | Write a program that takes an integer n and then prints n!. 88 | 89 | | INPUT | OUTPUT | 90 | |:-------:|:-------:| 91 | | 5 | 120 | 92 | | 10 | 3628800 | 93 | 94 | 95 | ## Question 8 - Fibonacci 96 | 97 | Write a program which reads a positive integer number N , and prints the Nth fibonacci number. *0, 1, 1, 2, 3, 5, ...* 98 | 99 | F_0 = 0, F_1 = 1, F_n = F\_(n-2) + F\_(n-1) 100 | 101 | | INPUT | OUTPUT | 102 | |:-------:|:-------:| 103 | | 2 | 1 | 104 | | 4 | 2 | 105 | | 7 | 8 | 106 | 107 | 108 | ## Question 9 - Second Largest 109 | 110 | 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. 111 | 112 | | INPUT | OUTPUT | 113 | |:-------:|:-------:| 114 | | 12 25 3 8 0 | 13 | 115 | | 15 1 2 3 8 5 0 | 7 | 116 | 117 | 118 | ## Question 10 - Digiiiits 119 | 120 | Write a program that takes a number and prints its total digit count and also even digit sum. 121 | 122 | | INPUT | OUTPUT | 123 | |:-------:|:-------:| 124 | | 542175 | 6 6 | 125 | | 24680 | 5 20 | 126 | | 135 | 3 0 | 127 | 128 | 129 | ## Question 11 - Positive Mental Attitude 130 | 131 | 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. 132 | 133 | | INPUT | OUTPUT | 134 | |:-------:|:-------:| 135 | | 4 7 45 9 2 0 0 5 8 -4 | 66 | 136 | | 1 1 0 1 -1 | 3 | 137 | 138 | 139 | ## Question 12 - NoBig 140 | 141 | 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) 142 | 143 | | INPUT | OUTPUT | 144 | |:-------:|:-------:| 145 | | 5 4 3 3 8 | 3.75 | 146 | | 5 4 3 3 8 7 5 9 | 3.75 | 147 | | 1 2 | 1.0 | 148 | | 100 54 46 2 3 50| 50.5 | 149 | 150 | 151 | ## Question 13 - Guess 152 | 153 | 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. 154 | 155 | 156 | | Input | Output | 157 | | ----- | --------------- | 158 | | 35
67
73
71 | Too low!
Too low!
Too high!
You got it!
And it only took you 4 tries! | 159 | 160 | 161 | ## Question 14 - Basic Calculator 162 | 163 | Write a simple calculator that takes an integer and then performs + - \* / operations until user enters q. If user enters +-\*/ then take another integer and carry out appropriate calculation. If user enters, q then quit program. If user enters h, then print out these instructions. 164 | 165 | Example run 166 | 167 | ``` 168 | Please enter number: 15 169 | Please enter operation: * 170 | Enter another number: 2 171 | Number is 30 now 172 | Enter another operation (h for help): + 173 | Enter another number: 6 174 | Number is 36 now 175 | Enter another operation (h for help): - 176 | Enter another number: 9 177 | Number is 27 now 178 | Enter another operation (h for help): / 179 | Enter another number: 2 180 | Number is 13 now 181 | Enter another operation (h for help): h 182 | q for quit 183 | h for help 184 | + for addition 185 | - for subtraction 186 | * for multiplication 187 | / for integer division 188 | Number is 13 now 189 | Enter another operation (h for help): q 190 | 191 | Process finished with exit code 0 192 | ``` 193 | 194 | -------------------------------------------------------------------------------- /Fall20/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 | 36 | ## Question 2 - Numbeeeers 37 | 38 | ```python 39 | N = int(input()) 40 | 41 | for i in range(N): 42 | print(i+1, end=' ') 43 | 44 | # OR 45 | 46 | for i in range(1, N+1): 47 | print(i, end=' ') 48 | ``` 49 | 50 | 51 | ## Question 3 - Hooping Numbers 52 | 53 | ### Question 3a 54 | 55 | ```python 56 | A = int(input("A: ")) 57 | B = int(input("B: ")) 58 | t = int(input("t: ")) 59 | 60 | for i in range(A, B+1, t): 61 | print(i, end=' ') 62 | ``` 63 | 64 | 65 | ### Question 3b 66 | 67 | ```python 68 | A = int(input("A: ")) 69 | B = int(input("B: ")) 70 | t = int(input("t: ")) 71 | 72 | for i in range(B, A-1, -t): 73 | print(i, end=' ') 74 | ``` 75 | 76 | 77 | ## Question 4 - Even Numbeeeers 78 | 79 | ```python 80 | A = int(input("A: ")) 81 | B = int(input("B: ")) 82 | 83 | result = 0 84 | 85 | for i in range(A+1, B): 86 | if i % 2 == 0: 87 | result += i 88 | 89 | print(result) 90 | ``` 91 | 92 | 93 | ## Question 5 - Average Team 94 | 95 | ```python 96 | N = int(input("N: ")) 97 | 98 | result = 0 99 | 100 | for _ in range(N): 101 | x = int(input()) 102 | result += x 103 | 104 | print(result/N) 105 | ``` 106 | 107 | 108 | ## Question 6 - Boom Boom POW 109 | 110 | ```python 111 | a = int(input("a: ")) 112 | b = int(input("b: ")) 113 | 114 | result = 1 115 | 116 | for _ in range(b): 117 | result *= a 118 | 119 | print(result) 120 | 121 | ``` 122 | 123 | ## Question 7 Factorial 124 | 125 | ```python 126 | n = int(input()) 127 | 128 | resultFor = 1 129 | resultWhile = 1 130 | for i in range(n): 131 | resultFor *= i+1 132 | 133 | while n: 134 | resultWhile *= n 135 | n -= 1 136 | 137 | print(resultFor) 138 | print(resultWhile) 139 | 140 | ``` 141 | 142 | ## Question 8 - Fibonacci 143 | 144 | ```python 145 | N = int(input("N: ")) 146 | 147 | prev = 0 148 | curr = 1 149 | 150 | for _ in range(3, N+1): 151 | next = prev + curr 152 | prev = curr 153 | curr = next 154 | 155 | if N <= 0: 156 | print("Invalid!") 157 | elif N == 1: 158 | print(prev) 159 | else: 160 | print(curr) 161 | ``` 162 | 163 | ### Question 9 - Second Largest 164 | 165 | ```python 166 | x = int(input()) 167 | largest = 0 168 | second = 0 169 | 170 | while x != 0: 171 | if x > largest: 172 | second = largest 173 | largest = x 174 | elif x > second: 175 | second = x 176 | x = int(input()) 177 | 178 | print(largest-second) 179 | ``` 180 | 181 | ## Question 10 - Digiiiits 182 | 183 | ```python 184 | x = int(input()) 185 | 186 | count = 0 187 | even_sum = 0 188 | 189 | while x > 0: 190 | digit = x % 10 191 | if digit % 2 == 0: 192 | even_sum += digit 193 | count += 1 194 | 195 | x //= 10 196 | 197 | print(count, even_sum) 198 | ``` 199 | 200 | ## Question 11 - Positive Mental Attitude 201 | 202 | ```python 203 | odd_sum = 0 204 | 205 | x = int(input()) 206 | while x >= 0: 207 | if x % 2 == 1: 208 | odd_sum += x 209 | x = int(input()) 210 | 211 | print(odd_sum) 212 | ``` 213 | 214 | ## Question 12 - NoBig 215 | 216 | ```python 217 | total_sum = 0 218 | count = 1 219 | 220 | x = int(input()) 221 | y = int(input()) 222 | total_sum += x 223 | while y <= x: 224 | total_sum += y 225 | count += 1 226 | 227 | x = y 228 | y = int(input()) 229 | 230 | print(total_sum/count) 231 | ``` 232 | 233 | 234 | ## Question 13 - Guess 235 | 236 | ```python 237 | import random 238 | 239 | number = random.randint(1,100) 240 | count = 0 241 | 242 | while True: 243 | guess = input("Make your guess: ") 244 | guess = int(guess) 245 | count += 1 246 | 247 | if guess < number: 248 | print("Too low!") 249 | elif guess > number: 250 | print("Too high!") 251 | else: 252 | print("You got it!") 253 | print("And it only took you",count,"tries!") 254 | break 255 | ``` 256 | 257 | ## Question 14 - Basic Calculator 258 | 259 | ```python 260 | help = """q for quit 261 | h for help 262 | + for addition 263 | - for subtraction 264 | * for multiplication 265 | / for integer division""" 266 | print(help) 267 | number = int(input("Please enter number: ")) 268 | operation = input("Please enter operation: ").lower() 269 | 270 | while operation != "q": 271 | if operation == "+": 272 | second_number = int(input("Enter another number: ")) 273 | number += second_number 274 | elif operation == "-": 275 | second_number = int(input("Enter another number: ")) 276 | number -= second_number 277 | elif operation == "*": 278 | second_number = int(input("Enter another number: ")) 279 | number *= second_number 280 | elif operation == "/": 281 | second_number = int(input("Enter another number: ")) 282 | if second_number == 0: 283 | print("Can't divide by 0") 284 | else: 285 | number //= second_number 286 | elif operation == "h": 287 | print(help) 288 | else: 289 | print("Operation is invalid!") 290 | print("Number is {} now".format(number)) 291 | operation = input("Enter another operation (h for help): ").lower() 292 | 293 | ``` 294 | -------------------------------------------------------------------------------- /Fall20/week04/README.md: -------------------------------------------------------------------------------- 1 | # Nested Loops 2 | 3 | ## Question 1 - R\*\*\*tangle 4 | 5 | ### Question 1a 6 | Write a program which takes two positive integers as N and M then prints a rectangle with size NxM. 7 | 8 | | Input | Output | 9 | | :---: | ------------------------------------ | 10 | | 3 4 | \*\*\*\*
\*\*\*\*
\*\*\*\* | 11 | | 2 6 | \*\*\*\*\*\*
\*\*\*\*\*\* | 12 | 13 | 14 | ### Question 1b 15 | 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. 16 | 17 | | Input | Output | 18 | | :---: | --------------------------------------------------- | 19 | | 3 3 | \*\*\*
\*-\*
\*\*\* | 20 | | 4 5 | \*\*\*\*\*
\*---\*
\*---\*
\*\*\*\*\* | 21 | 22 | 23 | ## Question 2 - TriNumber 24 | 25 | ### Question 2a 26 | Write a program to display a right angle triangle using the number N, which will repeat the number for that row, like below. 27 | 28 | | Input | Output | 29 | | :---: | --------------------------------------- | 30 | | 3 | 1
22
333 | 31 | | 5 | 1
22
333
4444
55555 | 32 | 33 | 34 | ### Question 2b 35 | Write a program to display a right angle triangle with N number of rows, like below. 36 | 37 | | Input | Output | 38 | | :---: | --------------------------------------- | 39 | | 3 | 1
12
123 | 40 | | 5 | 1
12
123
1234
12345 | 41 | 42 |
Hint At each row, we iterate from 1 to the row number.
43 | 44 | 45 | ### Question 2c 46 | 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: 47 | 48 | | Input | Output | 49 | | :---: | ------------------------------------- | 50 | | 3 4 | 4
4 16
4 16 64 | 51 | | 4 3 | 3
3 9
3 9 27
3 9 27 81 | 52 | 53 |
Hint At each row, we take power of input integer from once to the row number times.
54 | 55 | 56 | ## Question 3 - TriHard 57 | 58 | Write a program which takes an integer N as input and prints a right triangle which consists of N many lines. 59 | 60 | ``` 61 | Input: 62 | 3 63 | 64 | Output: 65 | --* 66 | -** 67 | *** 68 | 69 | Input: 70 | 5 71 | 72 | Output: 73 | ----* 74 | ---** 75 | --*** 76 | -**** 77 | ***** 78 | ``` 79 | 80 | ### Question 4 - Zzz 81 | 82 | Write a program which takes positive integer n greater than 2 and prints letter 'Z' size of n using '\*'. 83 | 84 | ``` 85 | Input: 86 | 3 87 | 88 | Output: 89 | *** 90 | * 91 | *** 92 | 93 | Input: 94 | 6 95 | 96 | Output: 97 | ****** 98 | * 99 | * 100 | * 101 | * 102 | ****** 103 | ``` 104 | 105 | 106 | ## Question 5 - Sum Facts 107 | 108 | 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. 109 | 110 | | Input | Output | 111 | | ----- | ------ | 112 | | 572 | 5162 | 113 | | 27 | 5042 | 114 | 115 | 116 | ## Question 6 - Sum of Digits 117 | 118 | 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. 119 | 120 | ``` 121 | 16 --> 1 + 6 = 7 122 | 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 123 | ``` 124 | 125 | | INPUT | OUTPUT | 126 | |:-------:|:-------:| 127 | | 942 | 6 | 128 | | 17703 | 9 | 129 | 130 | 131 | ## Question 7 - Prime Example 132 | 133 | ### Question 7a 134 | Write a program that reads a positive integer number and prints "Prime" to the screen if the entered number is a Prime number, otherwise "Prime Not". 135 | 136 | ### Question 7b 137 | Write a program which takes an integer as input and prints prime numbers up to that integer. 138 | 139 | | INPUT | OUTPUT | 140 | |:-------:|:-------:| 141 | | 11 | 2 3 5 7 11 | 142 | | 15 | 2 3 5 7 11 13 | 143 | 144 | 145 | ## Question 8 - Prime factors 146 | 147 | ### Question 8a 148 | 149 | Write a program that reads an integer N and prints all the numbers that can divide N. 150 | 151 | | INPUT | OUTPUT | 152 | |:-------:|:-------:| 153 | | 21 | 1 3 7 21 | 154 | | 30 | 1 2 3 5 6 10 15 30 | 155 | 156 | ### Question 8b 157 | 158 | Write a program that reads an integer N and prints the prime factoriation of N. 159 | 160 | Hint: A non-prime number is always composed of prime numbers smaller than it. 161 | 162 | | INPUT | OUTPUT | 163 | |:-------:|:-------:| 164 | | 21 | 3 * 7 | 165 | | 60 | 2 * 2 * 3 * 5 | 166 | 167 | ### Question 8c 168 | 169 | Write a program that reads an integer N and prints the prime factorization of N in the form of exponents. 170 | 171 | | INPUT | OUTPUT | 172 | |:-------:|:-------:| 173 | | 21 | 3^1 * 7^1 | 174 | | 60 | 2^2 * 3^1 * 5^1 | 175 | 176 | 177 | 178 | ## Question 9 - Pascal's Triangle 179 | 180 | The entry in the nth row and kth column of Pascal's triangle is denoted C(n,k). For example, the entry in the topmost row is C(0,0)=1. 181 | Write a program which takes positive integer n and prints the first n line of Pascal's Triangle. You can use math module to compute factorial. (import math and use math.factorial) 182 | 183 | ``` 184 | Input: 185 | 3 186 | 187 | Output: 188 | 1 189 | 1 1 190 | 1 2 1 191 | 192 | Input: 193 | 8 194 | 195 | Output: 196 | 1 197 | 1 1 198 | 1 2 1 199 | 1 3 3 1 200 | 1 4 6 4 1 201 | 1 5 10 10 5 1 202 | 1 6 15 20 15 6 1 203 | 1 7 21 35 35 21 7 1 204 | ``` 205 | 206 | 207 | ## Question 10 - Half-Matrix 208 | 209 | ### Question 10a 210 | 211 | Write a program which takes an integer N as input and prints the half matrix of N * N with its indices. 212 | Indices increasing in the horizontal direction 213 | 214 | ``` 215 | 216 | Input: 217 | 3 218 | 219 | Output: 220 | 0 221 | 1 2 222 | 3 4 5 223 | 224 | Input: 225 | 5 226 | 227 | Output: 228 | 229 | 0 230 | 1 2 231 | 3 4 5 232 | 6 7 8 9 233 | 10 11 12 13 14 234 | 235 | ``` 236 | 237 | ### Question 10b 238 | 239 | Write a program which takes an integer N as input and prints the half matrix of N * N with its indices. 240 | Indices increasing in the vertical direction 241 | 242 | ``` 243 | 244 | Input: 245 | 3 246 | 247 | Output: 248 | 0 249 | 1 3 250 | 2 4 5 251 | 252 | Input: 253 | 5 254 | 255 | Output: 256 | 257 | 0 258 | 1 5 259 | 2 6 9 260 | 3 7 10 12 261 | 4 8 11 13 14 262 | 263 | ``` -------------------------------------------------------------------------------- /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/README.md: -------------------------------------------------------------------------------- 1 | ## Question 1 - Leap year 2 | 3 | A leap year in the Gregorian calendar system is a year that’s divisible by 4 but not by 100, unless it is also divisible by 400. Write a function that takes in a year as input and returns True or False indicating whether it’s a leap year (or not). For example, 1896, 1904, and 2000 were leap years but 1900 was not. Then, call this function with following inputs and print corresponding outputs depending on the function's result. 4 | 5 | | Input | Output | 6 | | ----- | --------------- | 7 | | 1904 | leap year | 8 | | 1900 | not a leap year | 9 | | 2000 | leap year | 10 | 11 | ## Question 2 - Discount 12 | 13 | Suppose you are purchasing a premium membership for a digital music service. If you are a student, you get a 50% discount. 14 | 15 | Write a function that takes as input the membership cost that you are purchasing and a Boolean variable indicating whether you are a student (or not), applies the discounts appropriately, and returns the final discounted value of the item. 16 | 17 | | Input | Output | 18 | | -------- | ------ | 19 | | 10 True | 5 | 20 | | 10 False | 10 | 21 | 22 | ## Question 3 - Power 23 | 24 | ### Question 3a 25 | 26 | Write a function called `power` that takes a required integer parameter as **number** and an optional integer parameter as **n**. The default value for **n** should be 2. The function should return the **nth** power of **number**. 27 | 28 | | Input | Output | 29 | | ----- | ------ | 30 | | 5 | 25 | 31 | | 3 2 | 9 | 32 | | 4 3 | 64 | 33 | 34 | ### Question 3b 35 | 36 | Write a function which takes a number and prints the first 6 powers of the number using **power()** function from previous question. 37 | 38 | | Input | Output | 39 | | ----- | ------------------------------------------ | 40 | | 2 | 2
4
8
16
32
64 | 41 | | 3 | 3
9
27
81
243
729 | 42 | 43 | ## Question 4 - Is Prime? 44 | 45 | Write a function called `is_prime` which takes a number as a parameter and returns True or False indicating whether this number is prime or not. 46 | 47 | | Input | Output | 48 | | ----- | ------ | 49 | | 7 | True | 50 | | 12 | False | 51 | 52 | ## Question 5 - Suuuper Number 53 | 54 | **A suuuper number** is a number whose all divisors are prime except 1. 55 | 56 | Write a function called `is_super` which takes a number as a parameter and prints whether this number is suuuper or not. 57 | 58 | **Example**: 15 is a suuuper number since its divisors except 1 (3 and 5) are prime. However, 12 is not a suuuper number since it is divisible by 4 and 6 and those are not prime. 59 | 60 | | Input | Output | 61 | | ----- | ------- | 62 | | 15 | Suuuper | 63 | | 12 | :( | 64 | 65 | ## Question 6 - Abundant Number 66 | 67 | An **abundant number** or **excessive number** is a **number** that is smaller than the sum of its proper divisors. 68 | 69 | Write a function which takes two integers and finds the abundant numbers between those numbers (including them). If there are abundant numbers in the range, the function prints these numbers; otherwise, prints no abundant number. 70 | 71 | **Example:** The integer 12 is the first **abundant number**. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16. The amount by which the sum exceeds the **number** is the **abundance**. 72 | 73 | | Input | Output | 74 | | ----- | -------------------- | 75 | | 20 35 | 20 24 30 | 76 | | 10 40 | 12 18 20 24 30 36 40 | 77 | | 3 10 | no abundant number | 78 | 79 | 80 | ## Question 7 - Relatively Prime 81 | 82 | Two integers are relatively prime if they have no common positive divisor except 1. 83 | 84 | Write a function which takes two positive integers and prints "Relatively Prime" if they are relatively prime numbers, otherwise prints "Not Relatively Prime". 85 | 86 | | Input | Output | 87 | | ----- | -------------------- | 88 | | 2 5 | Relatively Prime | 89 | | 12 8 | Not Relatively Prime | 90 | | 8 9 | Relatively Prime | 91 | | 15 30 | Not Relatively Prime | 92 | 93 | ## Question 8 - Elementary Number Theory 94 | 95 | ### Question 8a - Modulus 96 | 97 | Using only addition, subtraction and a ``while`` loop, write a function that takes two numbers ``A``, ``B`` and returns ``A % B``. 98 | 99 | | Input | Output | 100 | | ----- | ------ | 101 | | 17 3 | 2 | 102 | | 27 5 | 2 | 103 | | 11 17 | 11 | 104 | 105 | ### Question 8b - GCD 106 | 107 | The **greatest common divisor** or **GCD** of two integers is the largest number that divides both integers. 108 | 109 | Write a function which takes two positive integers and returns their GCD. 110 | 111 | Hint: Implement [Euler's method](https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm). 112 | 113 | | Input | Output | 114 | | ----- | ------ | 115 | | 2 5 | 1 | 116 | | 12 8 | 4 | 117 | | 8 9 | 1 | 118 | | 15 30 | 15 | 119 | 120 | ### Question 8c - LCM 121 | 122 | The **lowest common multiple** or **LCM** of two integers is the smallest number that is a multiple of both numbers 123 | 124 | Write a function which takes two positive integers and returns their LCM. 125 | 126 | Hint: GCD(a,b) * LCM(a,b) = a*b 127 | 128 | | Input | Output | 129 | | ----- | ------ | 130 | | 2 5 | 10 | 131 | | 12 8 | 24 | 132 | | 8 9 | 72 | 133 | | 15 30 | 30 | 134 | 135 | ## Question 9 - You're a Square! 136 | When you multiply a number by itself, the result is a square number. 137 | 138 | Write a function that takes an integer and determines whether it is a square number or not. 139 | 140 | | Input | Output | 141 | | ----- | ------ | 142 | | 25 | True | 143 | | 23 | False | 144 | | 0 | True | 145 | | -1 | False | 146 | 147 | ## Question 10 - Multiply 148 | 149 | Write a function that takes variable number of integers and returns multiply of them. 150 | 151 | | Input | Output | 152 | | --------------- | ------ | 153 | | multiply(2,5,3) | 30 | 154 | | multiply(7,2) | 14 | 155 | | multiply(7) | 7 | 156 | | multiply(42,96) | 4032 | 157 | 158 | 159 | -------------------------------------------------------------------------------- /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/README.md: -------------------------------------------------------------------------------- 1 | # Lists and Tuples 2 | 3 | ## Question 1 - Reverse 4 | 5 | Write a program which reads an integer N from the user, then reads N integers from the user and store them in a list. 6 | 7 | **a**. Then print them to the screen in reverse order. 8 | 9 | **b.** Then reverse the order of these integers in the array and print the array. 10 | 11 | | Input | Output | 12 | | ---------------------- | -------------- | 13 | | 5
3 1 -4 5 2 | 2 5 -4 1 3 | 14 | | 6
15 7 2 89 8 12 | 12 8 89 2 7 15 | 15 | 16 | 17 | 18 | ## Question 2 - Let's Count 19 | 20 | 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). 21 | 22 | | INPUT | OUTPUT | 23 | | ------------------------------- | ------------------------------------------------------------ | 24 | | 5 10 2 5 50 5 10 1 2 2 | 1 --> 1
2 --> 3
5 --> 3
10 --> 2
50 --> 1 | 25 | 26 | 27 | 28 | ## Question 3 - Inception 29 | 30 | Write a program which reads two integers: N and M from the user. Then the program should read N more integers, then M more integers from the user. Assume N < M < 50. 31 | 32 | If the first combination of N integers appears at least once in the second combination of M integers, the program should write the starting index of the first appearance in the second combination. Otherwise it should not print anything. 33 | 34 | | Input | Output | 35 | | -------------------------------------------------- | ------ | 36 | | 4 12
4 5 6 5
1 2 1 2 99 99 4 5 6 5 9 9 | 6 | 37 | | 3 5
2 2 2
1 2 2 2 2 5 | 1 | 38 | | 3 5
2 3 2
1 2 2 2 5 | | 39 | 40 | 41 | 42 | ## Question 4 - Pairs 43 | 44 | Write a function which takes a list and a number X, then find all pairs in the list whose sum is equal to X. 45 | 46 | - A number can not be a pair with itself. Pairs should consist of different numbers. 47 | - You can print either (3,4) or (4,3) for one pair. 48 | - You should print all the pairs even if they are same. 49 | 50 | | INPUT | OUTPUT | 51 | | ------------------------- | --------------------------------------------- | 52 | | [2, 4, 3, 5, 7, 8, 9], 7 | (2, 5)
(4, 3) | 53 | | [2, 4, 3, 5, 6, -2, 4, 7, 8, 9], 7 | (2, 5)
(4, 3)
(3, 4)
(-2, 9) | 54 | 55 | 56 | 57 | ## Question 5 - fix34 58 | 59 | Write a program which reads an integer N from the user, then reads N integers from the user to a list. Then rearrange the list so that every 3 is immediately followed by a 4. Do not move the 3's, but every other number may move. The list contains the same number of 3's and 4's, every 3 has number after it that is not a 3, and a 3 appears in the list before any 4. 60 | 61 | | INPUT | OUTPUT | 62 | | --------------------- | ------------- | 63 | | 4
1 3 1 4 | 1 3 4 1 | 64 | | 7
1 3 1 4 4 3 1 | 1 3 4 1 1 3 4 | 65 | | 4
3 2 2 4 | 3 4 2 2 | 66 | 67 | 68 | 69 | ## Question 6 - Bubble Sort 70 | 71 | Write a function that sorts elements of the list in ascending order. 72 | 73 | | INPUT | OUTPUT | 74 | | ----------------- | --------------- | 75 | | 4 2 8 6 7 3 1 5 | 1 2 3 4 5 6 7 8 | 76 | 77 | Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. 78 | 79 | Example: 80 | 81 | First Pass: 82 | 83 | - ( **5** **1** 4 2 8 ) –> ( **1** **5** 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. 84 | - ( 1 **5** **4** 2 8 ) –> ( 1 **4** **5** 2 8 ), Swap since 5 > 4 85 | - ( 1 4 **5** **2** 8 ) –> ( 1 4 **2** **5** 8 ), Swap since 5 > 2 86 | - ( 1 4 2 **5** **8** ) –> ( 1 4 2 **5** **8** ), Now, since these elements are already in order (8 > 5), algorithm does not swap them. 87 | 88 | Second Pass: 89 | 90 | - ( **1** **4** 2 5 8 ) –> ( **1** **4** 2 5 8 ) 91 | - ( 1 **4** **2** 5 8 ) –> ( 1 **2** **4** 5 8 ), Swap since 4 > 2 92 | - ( 1 2 **4** **5** 8 ) –> ( 1 2 **4** **5** 8 ) 93 | - ( 1 2 4 **5** **8** ) –> ( 1 2 4 **5** **8** ) 94 | 95 | Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted. 96 | 97 | Third Pass: 98 | 99 | - ( **1** **2** 4 5 8 ) –> ( **1** **2** 4 5 8 ) 100 | - ( 1 **2** **4** 5 8 ) –> ( 1 **2** **4** 5 8 ) 101 | - ( 1 2 **4** **5** 8 ) –> ( 1 2 **4** **5** 8 ) 102 | - ( 1 2 4 **5** **8** ) –> ( 1 2 4 **5** **8** ) 103 | 104 | 105 | ## Question 7 - Concatwise 106 | 107 | Write a function that concatenates two lists index-wise. 108 | 109 | | INPUT | OUTPUT | 110 | | --------------------- | ------------- | 111 | | list1 = ["M", "na", "i", "Pat"]
list2 = ["y", "me", "s", "rick"] | ['My', 'name', 'is', 'Patrick'] | 112 | 113 | 114 | ## Question 8 - Combine Reverse 115 | 116 | Write a function that iterates two lists simultaneously such that list1 should display item in original order and list2 in reverse order. 117 | 118 | | INPUT | OUTPUT | 119 | | --------------------- | ------------- | 120 | | list1 = [10, 20, 30, 40]
list2 = [100, 200, 300, 400] | 10 400
20 300
30 200
40 100 | 121 | 122 | 123 | ## Question 9 - Remove X 124 | 125 | Write a function that accepts a list and variable X and removes all occurrence of X from the list. 126 | 127 | | INPUT | OUTPUT | 128 | | --------------------- | ------------- | 129 | | [5, 20, 15, 20, 25, 50, 20], 20 | [5, 15, 25, 50] | -------------------------------------------------------------------------------- /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/week07/Solutions.md: -------------------------------------------------------------------------------- 1 | # Lists and Tuples 2 | 3 | ## Question 1 - All the Same 4 | 5 | ```python 6 | def check(sampleTuple): 7 | return all(i == sampleTuple[0] for i in sampleTuple) 8 | 9 | 10 | tuple1 = (45, 45, 45, 45) 11 | print(check(tuple1)) 12 | ``` 13 | 14 | ## Question 2 - Filter Even Numbers 15 | 16 | ```python 17 | # https://www.codewars.com/kata/53dbd5315a3c69eed20002dd 18 | 19 | def even_filter(list1): 20 | return [i for i in list1 if i % 2] 21 | 22 | 23 | example = [2, 4, 6, 8] 24 | print(even_filter(example)) 25 | 26 | ``` 27 | 28 | ## Question 3 - List Comprehension 29 | 30 | ### Question 3a 31 | 32 | ```python 33 | def sum_of_evens(list): 34 | return sum([num for num in list if num % 2 == 0]) 35 | 36 | print(sum_of_evens([1, 2, 3, 4, 5])) 37 | ``` 38 | 39 | ### Question 3b 40 | 41 | ```python 42 | def sum_of_odds(list): 43 | return sum([num for num in list if num % 2]) 44 | 45 | print(sum_of_odds([1, 2, 3, 4, 5])) 46 | ``` 47 | 48 | ## Question 4 - Remove Duplicates 49 | 50 | ```python 51 | def remove_duplicates(list1): 52 | result = [] 53 | for i in list1: 54 | if i not in result: 55 | result.append(i) 56 | return result 57 | # return list(dict.fromkeys(list1)) 58 | 59 | 60 | example = [1, 1, 1, 1, 1, 2, 2, 2, 3, 2, 2, 4, 5] 61 | print(remove_duplicates(example)) 62 | 63 | ``` 64 | 65 | ## Question 5 - Remove Consecutive Duplicates 66 | 67 | ```python 68 | def remove_consecutive_duplicates(list1): 69 | i = 1 70 | while i < len(list1): 71 | if list1[i - 1] == list1[i]: 72 | list1.pop(i) 73 | else: 74 | i += 1 75 | return list1 76 | 77 | 78 | example = [1, 1, 1, 1, 1, 2, 2, 2, 3, 2, 2, 4, 5] 79 | print(remove_consecutive_duplicates(example)) 80 | ``` 81 | 82 | ### Question 6 - Odd Occurrences 83 | 84 | ```python 85 | def oddones(*l): 86 | mylist = [] 87 | 88 | for i in range(len(l)): 89 | if not l[i] in mylist: 90 | mylist.append(l[i]) 91 | else: 92 | mylist.remove(l[i]) 93 | 94 | for i in range(len(mylist)): 95 | print(mylist[i], end=' ') 96 | 97 | 98 | oddones(1, 1, 2, 3, 3, 3) 99 | ``` 100 | 101 | ## Question 7 - Neighbors 102 | 103 | ```python 104 | def sum_neighbors(numbers): 105 | new_list = [numbers[0] + numbers[1]] 106 | x = 1 107 | while x < len(numbers) - 1: 108 | new_list.append(numbers[x - 1] + numbers[x] + numbers[x + 1]) 109 | x += 1 110 | new_list.append(numbers[x - 1] + numbers[x]) 111 | return new_list 112 | 113 | new_list = sum_neighbors([10, 20, 30, 40]) 114 | print(new_list) 115 | ``` 116 | 117 | ## Question 8 - Circulation 118 | 119 | ### Question 8a - To the left 120 | 121 | ```python 122 | def rotate(l, n): 123 | return l[n:] + l[:n] 124 | 125 | print(rotate([1, 2, 3, 4, 5], 2)) 126 | ``` 127 | 128 | ### Question 8b - Left or right? 129 | 130 | ```python 131 | def rotate(l, n, is_left): 132 | if is_left: 133 | return l[n:] + l[:n] 134 | else: 135 | return l[-n:] + l[:-n] 136 | 137 | print(rotate([1, 2, 3, 4, 5], 2, False)) 138 | ``` 139 | 140 | ## Question 9 - Points 141 | 142 | ### Question 9a - Distance 143 | 144 | ```python 145 | def distance(point1, point2): 146 | return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** (1/2) 147 | 148 | print(distance((3, 0), (0, 4))) 149 | ``` 150 | 151 | ### Question 9b - Closest 152 | 153 | ```python 154 | def distance(point1, point2): 155 | return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** (1/2) 156 | 157 | def closest(point1, point2): 158 | dist1 = distance(point1, (0, 0)) 159 | dist2 = distance(point2, (0, 0)) 160 | return point2 if dist1 > dist2 else point1 161 | 162 | print(closest((3, 0), (0, 4))) 163 | ``` 164 | 165 | ### Question 9c - Farthest 166 | 167 | ```python 168 | def distance(point1, point2): 169 | return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** (1/2) 170 | 171 | N = int(input()) 172 | points = [] 173 | for i in range(N): 174 | x, y = input().split() 175 | points.append((int(x), int(y))) 176 | 177 | max_dist = None 178 | for ix, p in enumerate(points): 179 | for p2 in points[ix+1:]: 180 | dist = distance(p, p2) 181 | if max_dist is None or dist > max_dist: 182 | max_dist = dist 183 | farthest = (p, p2) 184 | 185 | print(farthest) 186 | ``` 187 | 188 | ## Question 10 - Fractions 189 | 190 | ### Question 10a - Addition 191 | 192 | ```python 193 | def simplify(nom, denom): 194 | factor = min(nom, denom) 195 | while True: 196 | if nom % factor == 0 and denom % factor == 0: 197 | nom //= factor 198 | denom //= factor 199 | factor -= 1 200 | if factor == 1: 201 | break 202 | return nom, denom 203 | 204 | 205 | def addition(frac1, frac2): 206 | common_denominator = frac1[1] * frac2[1] 207 | nominator_sum = frac1[0] * frac2[1] + frac2[0] * frac1[1] 208 | return simplify(nominator_sum, common_denominator) 209 | 210 | print(addition((3,5), (4, 8))) 211 | ``` 212 | 213 | ### Question 10b - Multiplication 214 | 215 | ```python 216 | def simplify(nom, denom): 217 | factor = min(nom, denom) 218 | while True: 219 | if nom % factor == 0 and denom % factor == 0: 220 | nom //= factor 221 | denom //= factor 222 | factor -= 1 223 | if factor == 1: 224 | break 225 | return nom, denom 226 | 227 | 228 | def multiply(frac1, frac2): 229 | return simplify(frac1[0] * frac2[0], frac1[1] * frac2[1]) 230 | 231 | print(multiply((3,5), (1, 3))) 232 | ``` 233 | 234 | ## Question 11 - Tuples/Lists 235 | 236 | ### Question 11a - Lists inside Tuple 237 | 238 | ```python 239 | def replace_last_value(items, value): 240 | for item in items: 241 | item[-1] = value 242 | return items 243 | 244 | modified_list = replace_last_value(([10, 20, 40], [40, 50, 60], [70, 80, 90]), 100) 245 | print(modified_list) 246 | ``` 247 | 248 | ### Question 11b - Tuples inside List 249 | 250 | ```python 251 | def replace_last_value(items, value): 252 | for item in items: 253 | item = item[:-1] + (value, ) 254 | return items 255 | 256 | # Alternatively: 257 | def replace_last_value(items, value): 258 | return [tup[:-1] + (value,) for tup in items] 259 | 260 | modified_list = replace_last_value([(10, 20, 40), (40, 50, 60), (70, 80, 90)], 100) 261 | print(modified_list) 262 | ``` 263 | 264 | 265 | ## Question 12 - Tuple Sort Tuple 266 | 267 | ```python 268 | def sort_tuple2(sampleTuple): 269 | return tuple(sorted(list(sampleTuple), key=lambda x: x[1])) 270 | 271 | 272 | tuple1 = (('a', 23), ('b', 37), ('c', 11), ('d', 29)) 273 | tuple1 = sort_tuple2(tuple1) 274 | print(tuple1) 275 | ``` 276 | -------------------------------------------------------------------------------- /Fall20/week08/README.md: -------------------------------------------------------------------------------- 1 | ## Question 1 - Voweeels 2 | 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. 3 | 4 | | Input | Output | 5 | | ----------------------------- | ---------- | 6 | | "happy beaar" | 3 | 7 | | "how you doin?" | 2 | 8 | | "aiaiai" | 6 | 9 | | "try" | 0 | 10 | 11 | ## Question 2 - Palindrome 12 | 13 | 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. 14 | 15 | | Input | Output | 16 | | ----- | ------ | 17 | | madam | True | 18 | | radix | False | 19 | 20 | ## Question 3 - Lower/Upper Counts 21 | 22 | Write a program to calculate the number of uppercase and lowercase letters in a string. 23 | 24 | | Input | Output | 25 | | ---------------- | ------ | 26 | | CMPE will be fun | 9 4 | 27 | | HeLLo WoRLD | 7 3 | 28 | 29 | ## Question 4 - Requirements 30 | 31 | Write a function which takes a password as parameter and return whether the password is valid or not. The password has the following requirements: 32 | 33 | * The password must be at least 6 characters and at most 20 characters. 34 | 35 | * It must contain at least one lowercase letter, one uppercase letter, and one number. 36 | 37 | | Input | Output | 38 | | ------- | ------ | 39 | | Covid19 | True | 40 | | 123456 | False | 41 | 42 | ## Question 5 - Ing 43 | 44 | Write a program to add **'ing'** at the end of a given string (length should be at least 3). If the given string already ends with **'ing'** then add **'ly'** instead. If the string length of the given string is less than 3, leave it unchanged. 45 | 46 | | Input | Output | 47 | | ------ | -------- | 48 | | abc | abcing | 49 | | string | stringly | 50 | 51 | ## Question 6 - Trim 52 | 53 | #### Q6a 54 | 55 | Write a program to trim both leading and trailing white space characters in a string 56 | 57 | | Input | Output | 58 | | ----------------- | -------- | 59 | | " Hi all " | "Hi all" | 60 | 61 | #### Q6b 62 | 63 | Write a program which takes two strings sentence and a sequence of characters and 64 | 65 | * remove these characters only from the beginning of the sentence. 66 | 67 | | Input | Output | 68 | | ---------------------------------------------------- | ------------------------------------- | 69 | | 12.23this is string example....wow!!!23.11
123. | this is string example....wow!!!23.11 | 70 | 71 | * remove these characters only from the end of the sentence. 72 | 73 | | Input | Output | 74 | | ---------------------------------------------------- | ------------------------------------- | 75 | | 12.23this is string example....wow!!!23.11
123. | 12.23this is string example....wow!!! | 76 | 77 | ## Question 7 - Length 78 | 79 | Write a program to find shortest and largest word in a given string. 80 | 81 | | Input | Output | 82 | | ---------------------------------- | -------------- | 83 | | the house is a long way from here | a house | 84 | | This room is exclusively for women | is exclusively | 85 | 86 | ## Question 8 - Not poor 87 | 88 | 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. 89 | 90 | | Input | Output | 91 | | ---------------------------- | ------------------- | 92 | | The lyrics is not that poor! | The lyrics is good! | 93 | | The lyrics is poor! | The lyrics is poor! | 94 | 95 | ## Question 9 - Word Cases 96 | 97 | 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. 98 | 99 | | Input | Output | 100 | | -------------------------------------- | -------------------------------------- | 101 | | stop making sponge bob memes | STOP making SPONGE bob MEMES | 102 | | CMPE will be fun in the next few years | CMPE will BE fun IN the NEXT few YEARS | 103 | 104 | ## Question 10 - Capitalize First Letters 105 | 106 | Write a function that takes a string and for each word convert first letter to uppercase and other letters to lowercase. (You don't have to worry about punctuations, you can use split function however you can try it as a challenge. For example: "A bad written ,horrible sentence.And it continues" -> "A Bad Written ,Horrible Sentence.And It Continues") 107 | 108 | | Input | Output | 109 | | ----------------------------- | ---------- | 110 | | perFecT NORMAL sentence | Perfect Normal Sentence | 111 | | A true friend overlooks your failures and tolerates your success | A True Friend Overlooks Your Failures And Tolerates Your Success| 112 | | a WITTY saying proves nOthing| A Witty Saying Proves Nothing| 113 | 114 | ## Question 11 - Initials 115 | 116 | #### Q11a 117 | 118 | Write a function which takes a name and returns the initials of the name. 119 | 120 | | Input | Output | 121 | | ---------------- | ------ | 122 | | Evan Rachel Wood | E R W | 123 | | Jude Law | J L | 124 | | Jane Doe | J D | 125 | 126 | #### Q11b 127 | 128 | Write a function which takes a name and returns the initials of a name (uppercase) with last name(with first alphabet in uppercase) written in full separated by dots. 129 | 130 | | Input | Output | 131 | | -------------------------- | ---------- | 132 | | geeks for geeks | G.F.Geeks | 133 | | mohandas karamchand gandhi | M.K.Gandhi | 134 | 135 | ## Question 12 - Alphabetical order 136 | 137 | Write a program that accepts a comma separated sequence of words as input and prints the unique words in sorted form (alphanumerically). 138 | 139 | | Input | Output | 140 | | ------------------------------------ | ---------------------------- | 141 | | red, white, black, red, green, black | black, green, red, white,red | 142 | 143 | -------------------------------------------------------------------------------- /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/week09/Solutions.md: -------------------------------------------------------------------------------- 1 | # Strings 2 | 3 | ## Question 1 - Remove Odds 4 | 5 | ```python 6 | def even_string(my_str): 7 | res_str = "" 8 | for i in range(len(my_str)): 9 | if i % 2 == 0: 10 | res_str += my_str[i] 11 | return res_str 12 | 13 | def even_string2(my_str): 14 | res_str = "" 15 | for i, c in enumerate(my_str): 16 | if i % 2 == 0: 17 | res_str += c 18 | return res_str 19 | 20 | print(even_string("abcdef")) 21 | print(even_string2("abcdef")) 22 | 23 | ``` 24 | 25 | ## Question 2 - Initials 26 | 27 | ### Question 2a 28 | 29 | ```python 30 | def name(s): 31 | # split the string into a list 32 | l = s.split() 33 | return ' '.join([w[0].upper() for w in l]) 34 | 35 | s = "mohandas karamchand gandhi" 36 | print(name(s)) 37 | ``` 38 | 39 | ### Question 2b 40 | 41 | ```python 42 | def name(s): 43 | # split the string into a list 44 | l = s.split() 45 | new = "" 46 | 47 | # traverse in the list 48 | for i in range(len(l) - 1): 49 | s = l[i] 50 | # adds the capital first character 51 | new += (s[0].upper() + '.') 52 | # l[-1] gives last item of list l. We 53 | # use title to print first character in 54 | # capital. 55 | new += l[-1].title() 56 | return new 57 | 58 | s = "mohandas karamchand gandhi" 59 | print(name(s)) 60 | ``` 61 | 62 | ## Question 3 - Stop gninnipS My sdroW! 63 | 64 | ```python 65 | def spin_words(my_str): 66 | words = my_str.split() 67 | res_str = "" 68 | for word in words: 69 | if len(word) > 4: 70 | res_str += word[::-1] + " " 71 | else: 72 | res_str += word + " " 73 | res_str = res_str.strip() 74 | return res_str 75 | 76 | def spin_words2(my_str): 77 | words = my_str.split() 78 | return " ".join([word[::-1] if len(word) > 4 else word for word in words]) 79 | 80 | print(spin_words("This is another test")) 81 | print(spin_words2("This is another test")) 82 | 83 | ``` 84 | 85 | ## Question 4 - Convert string to camel case 86 | 87 | ```python 88 | # https://www.codewars.com/kata/517abf86da9663f1d2000003/train/python 89 | def to_camel_case(text): 90 | result = "" 91 | flag = True 92 | for i in text: 93 | if i in ["-", "_"]: 94 | flag = True 95 | else: 96 | result += i.upper() if flag else i.lower() 97 | flag = False 98 | 99 | return result 100 | 101 | def to_camel_case_s(text): 102 | text = text.replace('-', '_') 103 | words = text.split('_') 104 | return ''.join([word.capitalize() for word in words]) # word.capitalize() -> word[0].upper() + word[1:].lower() 105 | 106 | 107 | print(to_camel_case("to_camel_case")) 108 | print(to_camel_case("Hard_exam-pLe")) 109 | print(to_camel_case("unnecessarily-LONG-Example")) 110 | 111 | ``` 112 | 113 | ## Question 5 - Find and replace 114 | 115 | ```python 116 | def find_replace(input, a, b): 117 | res_str = "" 118 | i = 0 119 | while i <= len(input) - len(a): 120 | if input[i:i + len(a)] == a: 121 | res_str += b 122 | i += len(a) 123 | else: 124 | res_str += input[i] 125 | i += 1 126 | if i < len(input): 127 | res_str += input[i:] 128 | return res_str 129 | 130 | def find_replace2(input, a, b): 131 | ix = 0 132 | while input.find(a, ix) != -1: 133 | ix = input.find(a, ix) 134 | input = input[:ix] + b + input[ix+len(a):] 135 | ix = ix + len(b) 136 | return input 137 | 138 | print(find_replace("This is another test", "is", "is not")) 139 | print(find_replace2("This is another test", "is", "is not")) 140 | print("This is another test".replace("is", "is not")) 141 | 142 | ``` 143 | 144 | # Files 145 | 146 | ## Question 1 - Save input 147 | 148 | ```python 149 | 150 | string = input() 151 | 152 | f = open("inputs.txt", "w") 153 | f.write(string) 154 | f.close() 155 | 156 | # Alternative: closes file implicitly 157 | """with open("inputs.txt", "a+") as f: 158 | f.write(string)""" 159 | 160 | ``` 161 | 162 | ## Question 2 - To lines 163 | 164 | ```python 165 | 166 | with open("data/q2.txt", "r") as f: 167 | file_str = f.read() 168 | sentences = file_str.split(".") 169 | sentences = [s.strip() for s in sentences] 170 | sentences = sentences[:-1] 171 | 172 | with open("data/q2_splitted.txt", "w") as f: 173 | for sentence in sentences: 174 | f.write(sentence + ".\n") 175 | 176 | ``` 177 | 178 | ## Question 3 - Reverse 179 | 180 | ```python 181 | 182 | with open("data/q2_splitted.txt", "r") as f: 183 | lines = f.readlines() 184 | 185 | lines = [l.strip() for l in lines] 186 | lines = [l[::-1] for l in lines] 187 | 188 | with open("data/reverse.txt", "w") as f: 189 | f.write("\n".join(lines)) 190 | 191 | ``` 192 | 193 | ## Question 4 - Count occurrences 194 | 195 | ```python 196 | 197 | import string 198 | 199 | with open("data/q2.txt", "r") as f: 200 | txt = f.read() 201 | 202 | words = txt.split() 203 | words = [w.strip(string.punctuation).lower() for w in words] 204 | 205 | words_set = list(set(words)) 206 | counts = [0] * len(words_set) 207 | 208 | for word in words: 209 | counts[words_set.index(word)] += 1 210 | 211 | for word, count in zip(words_set, counts): 212 | print(word, count) 213 | 214 | ``` 215 | 216 | Alternative: (using dictionary) 217 | 218 | ```python 219 | 220 | import string 221 | 222 | with open("data/q2.txt", "r") as f: 223 | txt = f.read() 224 | 225 | words = txt.split() 226 | words = [w.strip(string.punctuation).lower() for w in words] 227 | 228 | dict = {} 229 | 230 | for word in words: 231 | if word not in dict: 232 | dict[word] = 1 233 | else: 234 | dict[word] += 1 235 | 236 | print(dict) 237 | 238 | ``` 239 | 240 | ## Question 5 - Pluralize 241 | 242 | ```python 243 | #This is from another university's intro to computing class. I hope it's ok to ask. It was due to October 26. 244 | 245 | with open('input.txt','r') as f: 246 | words = [line.strip() for line in f.readlines()] 247 | alphas = [word for word in words if word.isalpha()] 248 | 249 | with open('output.txt','w') as f: 250 | f.write("\n".join([word+'s' if word[-1] != 'y' else word[:-1]+'ies' for word in alphas])) 251 | ``` 252 | 253 | ## Question 6 - Grades 254 | 255 | ### Question 6a 256 | 257 | ```python 258 | 259 | with open("grades.txt", 'r') as f: 260 | mt1 = [str(max(0, int(grade))) for grade in f.readline().split()] 261 | mt2 = [str(max(0, int(grade))) for grade in f.readline().split()] 262 | final = [str(max(0, int(grade))) for grade in f.readline().split()] 263 | 264 | with open("corrected.txt", 'w') as f: 265 | f.write(' '.join(mt1)) 266 | f.write('\n') 267 | f.write(' '.join(mt2)) 268 | f.write('\n') 269 | f.write(' '.join(final)) 270 | ``` 271 | 272 | ### Question 6b 273 | 274 | ```python 275 | with open("corrected.txt", 'r') as f: 276 | mt1 = [float(grade) for grade in f.readline().split()] 277 | mt2 = [float(grade) for grade in f.readline().split()] 278 | final = [float(grade) for grade in f.readline().split()] 279 | n= len(mt1) 280 | avg = 0.3*sum(mt1)/n + 0.3*sum(mt1)/n + 0.4*sum(final)/n 281 | print(round(avg,2)) 282 | ``` -------------------------------------------------------------------------------- /Fall20/week10/README.md: -------------------------------------------------------------------------------- 1 | # Dictionaries 2 | 3 | ## Question 1 - Split the Bill 4 | 5 | Write a program that splits the bill. 6 | 7 | For example, 3 friends go out together: A spends £20, B spends £15, and C spends £10. The function should return a dictionary showing that A should receive £5, B should receive £0, and C should pay £5. 8 | 9 | | Input | Output | 10 | | ----------------------------- | ---------- | 11 | | {'A':20, 'B':15, 'C':10} | {'A':5, 'B':0, 'C':-5} | 12 | 13 | ## Question 2 - Different Types 14 | 15 | Write a script that takes list of different types, and creates a dictionary which has each different type as keys and the list of elements of that type as as value. Then display all elements of each type like in the example. 16 | 17 | | INPUT | OUTPUT | 18 | | ------------------------------- | ------------------------------------------------------------ | 19 | | [10, 4.20, False, 'Word', 'CMPE150', 30, 3.5, 9.99, 'oblivion', True, 68, 88, "88"] | -> [10, 30, 68, 88]
-> [4.2, 3.5, 9.99]
-> [False, True]
-> ['Word', 'CMPE150', 'oblivion', '88']| 20 | 21 | 22 | ## Question 3 - Sorting Dictionary 23 | 24 | Write a function that returns a sorted list of (key, value) tuples. The list must be sorted by the value and be sorted largest to smallest. 25 | 26 | | Input | Output | 27 | | ----------------------------- | ---------- | 28 | | {3:1, 2:2, 1:3} | [(1,3), (2,2), (3,1)] | 29 | | {'a' :5, 'b' :10, 'c' :2, 'd' :3, 'e' :8} | [('b',10), ('e',8), ('a',5), ('d',3), ('c',2)] | 30 | 31 | 32 | ## Question 4 - Letter Count 33 | 34 | Write a script that takes a string, then create a dictionary which has letters as keys and the counts of that letters as values. Then sort that dictionary by descending values and print out the letters and the frequency of that letters to console. 35 | 36 | | INPUT | OUTPUT | 37 | | ------------------------------- | ------------------------------------------------------------ | 38 | | What we think, we become. | e -> 0.21
w -> 0.16
h -> 0.11
t -> 0.11
a -> 0.05
b -> 0.05
c -> 0.05
i -> 0.05
k -> 0.05
m -> 0.05
n -> 0.05
o -> 0.05| 39 | 40 | 41 | ## Question 5 - Dictionary Merge 42 | 43 | Write a function that takes one or more dictionaries and combines them in one result dictionary. The keys in the given dictionaries can overlap. In that case you should combine all values in a list. Duplicate values should be preserved. 44 | 45 | | Input | Output | 46 | | ----------------------------- | ---------- | 47 | | {"A": 1, "B": 2}
{"A": 3} | {"A": [1, 3]}, "B": [2]} | 48 | | {"A": 1, "B": 2, "C": 3} | {"A": [1], "B": [2], "C": [3]} | 49 | | {"A": 1, "B": 2, "C": 3}
{"A": 4, "D": 5}
{"A": 4} | {"A": [1, 4, 4], "B": [2], "C": [3], "D": [5]} | 50 | 51 | 52 | 53 | ## Question 6 - Zip Two Lists 54 | 55 | Write a function that takes 2 lists, then returns a dictionary which has keys from the first one, values from the second one. 56 | 57 | | INPUT | OUTPUT | 58 | | ------------------------------- | ------------------------------------------------------------ | 59 | | list1 = ["melih", "burak", "ahmet", "recep", "melis"]
list2 = [1,2,3,4,5] |{'melih': 1, 'burak': 2, 'ahmet': 3, 'recep': 4, 'melis': 5} 60 | | 61 | 62 | 63 | 64 | # Sets 65 | 66 | ## Question 1 - List to Distinct 67 | 68 | Write a function that takes a list as an argument and returns distinct elements of the list. The order of elements 69 | doesn't matter. 70 | 71 | | Input | Output | 72 | | -------------------- | -------------- | 73 | | 3 5 4 4 7 11 2 8 | 2 3 4 5 7 8 11 | 74 | | 1 8 1 1 27 32 17 32 | 32 1 8 17 27 | 75 | 76 | ## Question 2 - Set Operations 77 | 78 | Write a function that takes two sets then prints union, intersection and difference operations between them. 79 | 80 | | Input | Output | 81 | | ----------------- | ------ | 82 | | 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} | 83 | 84 | 85 | ## Question 3 - Diff 86 | 87 | Write a program that find the missing and additional values of the first list from the second list. 88 | 89 | | Input | Output | 90 | | ---------------------------------- | ------------------------------------------------------------ | 91 | | [1, 2, 3, 4, 5, 6] [4, 5, 6, 7, 8] | Missing values in list1 = [8, 7]
Additional values in list1 = [1, 2, 3] | 92 | | [1, 3, 5, 7] [2, 4, 6, 8] | Missing values in list1 = [2, 4, 6, 8]
Additional values in list1 = [1, 3, 5, 7]| 93 | 94 | ## Question 4 - Distinct String 95 | 96 | **A distinct string** is a string whose all characters occurs only once. 97 | 98 | Write a function that takes a string as an argument and checks whether given string is distinct or not. 99 | 100 | | Input | Output | 101 | | --------- | ------ | 102 | | dwarf | True | 103 | | violate | True | 104 | | violation | False | 105 | 106 | ## Question 5 - Numgram 107 | 108 | **A numgram** is a string containing all digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9). 109 | 110 | Write a program which takes a string as input and prints whether this string is numgram or not. 111 | 112 | | Input | Output | 113 | | --------------------- | ------------- | 114 | | SAS102BAD347 HELP5689 | Numgram | 115 | | Wh4t 4 811ll7 q0386n | Not a numgram | 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /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 | * Follow the [Installation Guide](InstallationGuide.md). 5 | 6 | 2. How can I update Teaching Codes Plugin? 7 | * Follow the [Teaching Codes Update Guide](TeachingCodesGuide.md) 8 | 9 | 3. How can I open/submit a project? 10 | * Follow the [Teaching Codes Guide](TeachingCodesGuide.md) 11 | 12 | 4. I encountered an error during installation/using Teaching Codes, how can I get help? 13 | * 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 the mail address of your section: cmpe150.mail@gmail.com for CMPE150.01 and cmpe150.mail2@gmail.com for CMPE150.02. 14 | 15 | 5. I get one of the error listed below while installing Homebrew 16 | 17 | * curl (6): Could not resolve host: https 18 | * curl: (1) Protocol ' https not supported or disabled in libcurl 19 | 20 | Try the commands below. If any of them works, then continue installation. When the installation is completed, check it by typing ```brew help``` 21 | 22 | * ```bash 23 | /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" 24 | ``` 25 | 26 | * ```bash 27 | /bin/bash -c "$(curl -fsSL4 https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" 28 | ``` 29 | 30 | * ```bash 31 | /bin/bash -c "$(usr/bin/curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" 32 | ``` 33 | 34 | * ```bash 35 | ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 36 | ``` 37 | 6. I get 'brew not found' error 38 | 39 | * If you are using **zsh**, you need to add HomeBrew to your path in zsh profile: 40 | 41 | * Copy and the following line on the terminal, replace \ with your username and then press return (enter). 42 | 43 | ```bash 44 | echo 'eval $(/opt/homebrew/bin/brew shellenv)' >> /Users//.zprofile 45 | ``` 46 | * Then copy and paste the next line on the terminal, press return (enter) 47 | 48 | ```bash 49 | eval $(/opt/homebrew/bin/brew shellenv) 50 | ``` 51 | * Check whether it is succesfully added to the profile, by typing: 52 | 53 | ```bash 54 | brew help 55 | ``` 56 | 7. Teaching.Codes Plugin displays 'Nothing to show' 57 | 58 | * Make sure you do not extract the Teaching.Codes zip file. 59 | * Download the Teaching.Codes zip using Chrome instead of Safari. 60 | * If you are using Macbook M1, make sure you install **Intel version of PyCharm.** 61 | * Then, reinstall the plugin by following [Teaching.Codes guide](https://github.com/gokceuludogan/CmpE150-Python/blob/main/TeachingCodesGuide.md) 62 | * 63 | 8. I can't see the button names in the plugin 64 | 65 | * Change the theme by following these steps: 66 | 67 | * Inside PyCharm, for Windows, click ***File-->Settings***; for MacOS, click ***PyCharm-->Preferences*** and find ***Appearance&Behavior*** on the left. 68 | * Go into **Appearance** under ***Appearance&Behavior*** 69 | * Change Theme from Intellij Light to something else. (**Darcula** seems fine.) 70 | * Click **OK** 71 | 72 | ![](figures/ChangeTheme.png) 73 | 74 | 9. I have deleted the contents of **Main.py** 75 | * Restore it from **Main.py.txt** under corresponding question's **src** folder 76 | 77 | ![](figures/Maintxt.png) 78 | 79 | 10. I can't see the Question description 80 | * Open the **Question.html** under **WebContent** in a browser 81 | * Right click on **Question.html** file 82 | * Click **Open in Browser.** 83 | 84 | 85 | 86 | 11. If there are multiple questions and you see the same description for both questions or still blank page. 87 | 88 | * Right click on **Question.html** file 89 | * Choose "**Show in Explorer/Finder**". This step open the folder that contains the html file. 90 | 91 | 92 | 93 | * From the folder, open the html file. 94 | 95 | 12. I can't see the Exam Results 96 | 97 | * Log out, and log in to the Teaching.Codes plugin. 98 | * Select the class from the Navigator. Wait a while for the class to load. 99 | * Click the ExamResults tab. When you click Open under a question, if nothing is happening: 100 | * Click the Projects tab on the left of ExamResults 101 | * Then, go into ExamResults once again. Now, when you click Open, you should be able to see your results. 102 | 103 | 13. What counts as **cheating**: 104 | * **Information exchange between students:** Giving and Receiving information to/from your colleagues both count as cheating. 105 | * **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. 106 | -------------------------------------------------------------------------------- /InstallationGuide.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/InstallationGuide.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CmpE150 - Spring 2021 2 | 3 | Bogazici University CmpE 150 Introduction to Computing (Python programming language) Notes 4 | 5 | 6 | 7 | ## Materials 8 | 9 | * [Installation Guide](InstallationGuide.md) 10 | * [Teaching Codes Guide](TeachingCodesGuide.md) 11 | * [Frequently Asked Questions (FAQ)](FrequentlyAskedQuestions%20(FAQ).md) 12 | 13 | ## Exercises 14 | 15 | #### [Week1](week01/) 16 | * Introduction to tools 17 | * Installation 18 | 19 | #### [Week2](week02/) 20 | * Variables 21 | * Expressions 22 | * Statements 23 | 24 | #### [Week3](week03/) 25 | * Variables 26 | * Expressions 27 | * Statements 28 | 29 | #### [Week4](week04/) 30 | * Conditional Execution (if, elif, else) 31 | 32 | #### [Week5](week05/) 33 | * Loops 34 | 35 | #### [Week6](week06/) 36 | * Nested Loops 37 | 38 | #### [Week7](week07/) 39 | * Functions 40 | 41 | #### [Week8](week08/) 42 | * Lists 43 | 44 | #### [Week9](week09/) 45 | 46 | - Lists/Tuples 47 | 48 | #### [Week10](week10/) 49 | 50 | - Strings 51 | 52 | #### [Week11](week11/) 53 | 54 | - Files 55 | - Dictionaries 56 | 57 | #### [Week12](week12/) 58 | 59 | - Dictionaries 60 | - Sets 61 | - External Libraries 62 | 63 | 64 | # Fall 2021 Materials 65 | * [Notes](https://github.com/bouncmpe150/python-notes) 66 | * [Slides](https://bouncmpe150.github.io/python-slides/) 67 | -------------------------------------------------------------------------------- /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 for CMPE150.01 and cmpe150.mail2@gmail.com for CMPE150.02. 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 (2021 Spring) 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/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/Teaching.CodesProjectGuide.pdf -------------------------------------------------------------------------------- /TeachingCodesGuide.md: -------------------------------------------------------------------------------- 1 | ## Teaching.Codes Quiz/Project Guide 2 | 3 | **Quiz Guide Playlist: https://www.youtube.com/playlist?list=PLgnOcaYXEY3lEkkwZPPFV0FcXtVLhnKdB** 4 | 5 | 1. Configuring the default Python Interpreter (https://youtu.be/9Ou3WvXMQQU) 6 | 7 | This video explains how to **configure your default Python Interpreter**. You must only do this once, and the default interpreter will be determined for all projects you create, and all Quizzes you take. **If you don't perform this before your Quiz**, your code may be interpreted by a different version of Python in your computer, and **you may not get a full grade**. Please make sure that you set your default Python interpreter as Python 3.8.6 (location may differ in different systems, refer to the *Create a new project* section in the [Installation Guide](Installation%20Guide.pdf). 8 | 9 | 2. Teaching.Codes Login (https://youtu.be/AQX5aZXDSz8) 10 | 11 | You must **make sure that you can login** to your Teaching.Codes accounts before the Quiz. 12 | 13 | 3. Taking the Quiz (https://youtu.be/T1kNINEEPmI) 14 | 15 | This video shows you how a Quiz looks like, and how you submit your solutions. 16 | 17 | 4. Problems Encountered during the Quiz (https://youtu.be/1X0weYP8dyQ) 18 | 19 | Please watch the solutions to the **problems encountered during the Quiz**, so that you may take some precautions beforehand. 20 | 21 | 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: 22 | 23 | 1. Right click on the html file 24 | 2. Choose "**Show in Explorer/Finder**". This step open the folder that contains the html file. 25 | 3. From the folder, open the html file. 26 | 27 | You can find all videos inside this playlist (https://www.youtube.com/playlist?list=PLgnOcaYXEY3lEkkwZPPFV0FcXtVLhnKdB). 28 | 29 | 5. Open Grades 30 | 31 | In order to reach your grades, 32 | 33 | 1. Login to your Teaching.Codes account in PyCharm. 34 | 2. Select your class (double-click your class under ***Navigator***). 35 | 3. Check out your grade under ***ExamResults***. 36 | 37 | ## Teaching.Codes Plugin Update 38 | 39 | To update Teaching.Codes, **you need to uninstall and reinstall the Teaching.Codes plugin**. Please follow these steps: 40 | 41 | 1. Download: 42 | 43 | Windows: https://programming.cmpe.boun.edu.tr/downloads/StudentPlugin/TCPluginJetBrains_Windows.zip 44 | 45 | Linux: https://programming.cmpe.boun.edu.tr/downloads/StudentPlugin/TCPluginJetBrains_Linux.zip 46 | 47 | MacOS: https://programming.cmpe.boun.edu.tr/downloads/StudentPlugin/TCPluginJetBrains_MacOs.zip 48 | 49 | If you're using MacOS, please download the .zip file using **Chrome instead of Safari** to avoid any issues. 50 | 51 | 2. Open PyCharm. 52 | 53 | 3. Inside PyCharm, for Windows, click ***File-->Settings***; for MacOS, click ***PyCharm-->Preferences*** and find ***Plugins*** on the left. 54 | 55 | 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. 56 | 57 | ![Teaching.Codes Uninstall](figures/Teaching.Codes Uninstall.png) 58 | 59 | 5. **When the uninstallation is complete, click OK, and then** **close PyCharm**. 60 | 61 | 6. **Apply steps 2 and 3**. Go into ***Plugins***, click ***the gear icon*** on the top, and select ***Install Plugin from Disk…*** 62 | 63 | Navigate to the location of the zip file you've downloaded from the link above (TCPluginJetBrains_XXX.zip) and choose it. 64 | 65 | 7. After installation is complete, press the ***Restart IDE*** button appeared on the Teaching Codes plugin, or click ***OK***, and then **restart PyCharm** manually. 66 | 67 | When you restart PyCharm, the Teaching.Codes plugin may not appear on your window. Click ***View-->Tool Windows-->Teaching.Codes*** 68 | 69 | -------------------------------------------------------------------------------- /figures/1616341138563.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/1616341138563.png -------------------------------------------------------------------------------- /figures/1616342184949.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/1616342184949.png -------------------------------------------------------------------------------- /figures/1616342517499.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/1616342517499.png -------------------------------------------------------------------------------- /figures/ChangeTheme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/ChangeTheme.png -------------------------------------------------------------------------------- /figures/HTML_Browser.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/HTML_Browser.png -------------------------------------------------------------------------------- /figures/HTML_Explorer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/HTML_Explorer.png -------------------------------------------------------------------------------- /figures/Maintxt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/Maintxt.png -------------------------------------------------------------------------------- /figures/PythonInstaller.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/PythonInstaller.png -------------------------------------------------------------------------------- /figures/Teaching.Codes New Version.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/Teaching.Codes New Version.png -------------------------------------------------------------------------------- /figures/Teaching.Codes Uninstall.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/Teaching.Codes Uninstall.png -------------------------------------------------------------------------------- /figures/Teaching.Codes Version 1212JB.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/Teaching.Codes Version 1212JB.png -------------------------------------------------------------------------------- /figures/commit_and_push_failed1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/commit_and_push_failed1.png -------------------------------------------------------------------------------- /figures/commit_and_push_failed2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/commit_and_push_failed2.png -------------------------------------------------------------------------------- /figures/connection.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/connection.PNG -------------------------------------------------------------------------------- /figures/could not open.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/could not open.PNG -------------------------------------------------------------------------------- /figures/project-guide/1618485979513.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/project-guide/1618485979513.png -------------------------------------------------------------------------------- /figures/project-guide/1618486104949.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/project-guide/1618486104949.png -------------------------------------------------------------------------------- /figures/project-guide/1618486398394.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/project-guide/1618486398394.png -------------------------------------------------------------------------------- /figures/project-guide/1618486497781.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/project-guide/1618486497781.png -------------------------------------------------------------------------------- /figures/project-guide/1618486752521.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/project-guide/1618486752521.png -------------------------------------------------------------------------------- /figures/project-guide/1618486890025.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/project-guide/1618486890025.png -------------------------------------------------------------------------------- /figures/project-guide/1618487070207.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/project-guide/1618487070207.png -------------------------------------------------------------------------------- /figures/project-guide/1618487098652.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/project-guide/1618487098652.png -------------------------------------------------------------------------------- /figures/project-guide/1618487165943.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/project-guide/1618487165943.png -------------------------------------------------------------------------------- /figures/project-guide/1618487273664.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/project-guide/1618487273664.png -------------------------------------------------------------------------------- /figures/project-guide/1618487440503.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/project-guide/1618487440503.png -------------------------------------------------------------------------------- /figures/project-guide/1618487934948.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/project-guide/1618487934948.png -------------------------------------------------------------------------------- /figures/team-fixed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/figures/team-fixed.png -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /week01/figures/moodle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/week01/figures/moodle.png -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /week04/README.md: -------------------------------------------------------------------------------- 1 | ## Question 1 2 | 3 | Write a program which takes two integers and determines whether the first number is divisible by the second number. If it's not divisible, then the program prints the remainder of the division. 4 | 5 | | Input | Output | 6 | | ------ | --------------- | 7 | | 161 11 | Not divisible 7 | 8 | | 121 11 | Divisible | 9 | 10 | ## Question 2 11 | 12 | Write a program that takes 3 integers from the user and then prints the min and max of the numbers. 13 | 14 | | Input | Output | 15 | | -------- | ---------------- | 16 | | 13 27 14 | 13 27 | 17 | 18 | ## Question 3 19 | Write a program that calculates the body mass index with the given formula and print the appropriate class with the catalogue below. 20 | 21 | 22 | 23 | 24 | | Category | BMI | 25 | | ------------------------------------- | ------- | 26 | | Very severely underweight | -15 | 27 | | Severely underweight | 15-16 | 28 | | Underweight | 16-18.5 | 29 | | Normal (healthy weight) | 18.5-25 | 30 | | Overweight | 25-30 | 31 | | Obese Class I (Moderately obese) | 30-35 | 32 | | Obese Class II (Severely obese) | 35-40 | 33 | | Obese Class III (Very severely obese) | 40+ | 34 | 35 | | Input | Output | 36 | | ------ | --------------------------------- | 37 | | 83 174 | 27.4
Overweight | 38 | | 73 174 | 24.1
Normal (healthy weight) | 39 | 40 | ## Question 4 41 | Write a program which calculates whether any given two numbers are multiples of one another. 42 | 43 | | Input | Output | 44 | | ----- | ------------ | 45 | | 2 4 | Multiple | 46 | | 4 2 | Multiple | 47 | | 5 3 | Not Multiple | 48 | 49 | ## Question 5 50 | 51 | There is a cash machine with a finite (n) supply of 5tl banknotes and an infinite supply of 1tl coins inside it. 52 | 53 | Write a program that takes two integers as input representing the amount of money requested by a customer and the number of 5tl banknotes inside the machine (n). The program should then print the number of banknotes and coins given to the customer. (Machine must prefer giving away banknotes instead of coins if possible) 54 | 55 | | Input | Output | 56 | | ----- | ------ | 57 | | 38 4 | 4 18 | 58 | | 30 5 | 5 5 | 59 | | 14 3 | 2 4 | 60 | | 2 5 | 0 2 | 61 | 62 | ## Question 6 63 | 64 | ### Question 6a 65 | 66 | Write a program that takes 2 integers from the user and then prints these integeres in an ascending order using a single if statement. 67 | 68 | | Input | Output | 69 | | ----- | ------ | 70 | | 3 5 | 3 5 | 71 | | 5 3 | 3 5 | 72 | 73 | ### Question 6b 74 | 75 | Write a program that takes 3 integers from the user and then prints these integeres in an ascending order 76 | 77 | | Input | Output | 78 | | ----- | ------ | 79 | | 1 3 2 | 1 2 3 | 80 | | 3 2 1 | 1 2 3 | 81 | | 2 3 1 | 1 2 3 | 82 | 83 | ## Question 7 84 | 85 | Consider a classic case of [prisonner's dilemma](https://en.wikipedia.org/wiki/Prisoner%27s_dilemma). 86 | 87 | Bob and Sam are being interrogated by police as suspects of a theft case. Interrogation process is taking place in two seperate rooms. They can either stay silent about their crime or betray each other by admiting it. The possible outcomes are: 88 | - If Bob and Sam each betray the other, each of them serves two years in prison 89 | - If Bob betrays Sam but Sam remains silent, Bob will be set free and Sam will serve three years in prison 90 | - If Bob remains silent but Sam betrays Bob, Bob will serve three years in prison and Sam will be set free 91 | - If Bob and Sam both remain silent, both of them will serve only one year in prison (on the lesser charge). 92 | 93 | Write a program that takes decisions (silence/betrayal) of Bob and Sam as input, then outputs their punishments. 94 | 95 | | Input | Output | 96 | | ----------------- | ------ | 97 | | silence silence | 1 1 | 98 | | silence betrayal | 3 0 | 99 | | betrayal betrayal | 2 2 | 100 | 101 | ## Question 8 102 | 103 | Write a program to prompt the user for 3 integers x, y and z. Print out true if these integer can constitute the side lengths of a right triangle, False otherwise. Apart from taking the inputs, you should use only one line of code. 104 | 105 | Hint: 106 | * Sum of the squares of the two integers must be equal to the square of the other. 107 | * Each integer must be positive. 108 | 109 | 110 | | INPUT | OUTPUT | 111 | | ------ | ------ | 112 | | 7 0 7 | False | 113 | | 9 -12 15 | False | 114 | | 20 12 16 | True | 115 | 116 | ## Question 9 117 | 118 | Write a program that takes an integer as an input that takes an integer in the range 0-9999 (inclusive) and prints the sum of this number's digits. 119 | 120 | | INPUT | OUTPUT | 121 | | ------ | ------ | 122 | | 15 | 6 | 123 | | 1234 | 10 | 124 | | 9999 | 36 | 125 | | -5 | Input is not in the interval | 126 | | 0 | 0 | 127 | | 10000 | Input is not in the interval | 128 | 129 | ## Question 10 130 | 131 | Write a program that prints the physical state of the water for the given *(taken as input)* temperature. 132 | (Remember that in the phase change temperature, the matter can be in more than one state) 133 | 134 | Ex: in 100°C water can be liquid or gas 135 | 136 | (boiling point of water: 100°C and freezing point of water: 0°C ) 137 | 138 | | INPUT | OUTPUT | 139 | | ------ | ------ | 140 | | 142 | It is in the gas state. | 141 | | 62 | It is in the liquid state. | 142 | | -81 | It is in the solid state. | 143 | | 0 | It can be solid or liquid. | 144 | | 100 | It can be liquid or gas. | 145 | -------------------------------------------------------------------------------- /week04/Solutions.md: -------------------------------------------------------------------------------- 1 | # Conditional-Execution 2 | 3 | ## Q1 4 | ```python 5 | num1 = int(input("Please enter first number: ")) 6 | num2 = int(input("Please enter second number: ")) 7 | 8 | if(num1 % num2 == 0): 9 | print("First number can be divided by second number.") 10 | else: 11 | print("First number can be divided by second number. Remainder is: " + str(num1 % num2)) 12 | ``` 13 | 14 | 15 | ## Q2 16 | 17 | ```python 18 | num1 = int(input("Please enter first number: ")) 19 | num2 = int(input("Please enter second number: ")) 20 | num3 = int(input("Please enter third number: ")) 21 | 22 | if num1 > num2 and num2 > num3: 23 | minnum = num3 24 | maxnum = num1 25 | elif num1 > num3 and num3 > num2: 26 | minnum = num3 27 | maxnum = num1 28 | elif num2 > num3 and num3 > num1: 29 | minnum = num1 30 | maxnum = num2 31 | elif num2 > num1 and num1 > num3: 32 | minnum = num3 33 | maxnum = num2 34 | elif num3 > num1 and num1 > num2: 35 | minnum = num2 36 | maxnum = num3 37 | else: 38 | minnum = num1 39 | maxnum = num3 40 | 41 | print("Minimum is: " + str(minnum)) 42 | print("Maximum is: " + str(maxnum)) 43 | 44 | # We can also calculate min and max with builtin functions 45 | # print("Minimum is: " + str((min(num1,num2,num3)))) 46 | # print("Maximum is: " + str((max(num1,num2,num3)))) 47 | 48 | # Another solution 49 | minimum = c 50 | maximum = c 51 | 52 | if a >= b and a >= c: 53 | maximum = a 54 | elif b >= a and b >= c: 55 | maximum = b 56 | 57 | if a <= b and a <= c: 58 | minimum = a 59 | elif b <= a and b <= c: 60 | minimum = b 61 | 62 | print(minimum, maximum) 63 | ``` 64 | 65 | 66 | ## Q3 67 | ```python 68 | w = int(input("Plese enter your weight: ")) 69 | h = float(input("Plese enter your height (meters): ")) / 100 70 | 71 | bmi = w / h**2 72 | print("Your BMI score is: " + str(bmi)) 73 | 74 | if bmi < 15: 75 | print("You are very severely underweight.") 76 | elif bmi < 16: 77 | print("You are severely underweight.") 78 | elif bmi < 18.5: 79 | print("You are underweight.") 80 | elif bmi < 25: 81 | print("You are normal.") 82 | elif bmi < 30: 83 | print("You are overweight.") 84 | elif bmi < 35: 85 | print("You are Obese Class I.") 86 | elif bmi < 40: 87 | print("You are Obese Class II.") 88 | else: 89 | print("You are Obese Class III.") 90 | ``` 91 | 92 | 93 | ## Q4 94 | ```python 95 | num1 = int(input("Plese enter first number: ")) 96 | num2 = int(input("Plese enter second number: ")) 97 | 98 | if num1 % num2 == 0 or num2 % num1 == 0: 99 | print("Multiple") 100 | else: 101 | print("Not multiple") 102 | 103 | ``` 104 | 105 | 106 | ## Q5 107 | 108 | ```python 109 | amount = int(input("Please enter the amount of money requested by the customer: ")) 110 | n = int(input("Please enter the amount of banknotes inside the machine: ")) 111 | 112 | if (n < amount//5): #we will have more than or equal to 5 coins 113 | print(n, amount - 5*n) 114 | else: 115 | print(amount//5, amount%5) 116 | 117 | # Another solution 118 | if n * 5 > amount: 119 | print(amount // 5, amount % 5) 120 | else: 121 | print(n, amount - (n * 5)) 122 | 123 | ``` 124 | 125 | 126 | ## Q6 127 | 128 | ### Q6a 129 | 130 | ```python 131 | num1 = int(input("Please enter first number: ")) 132 | num2 = int(input("Please enter second number: ")) 133 | 134 | if (num1 > num2): 135 | tmp = num1 136 | num1 = num2 137 | num2 = tmp 138 | 139 | print(num1, num2) 140 | ``` 141 | 142 | ### Q6b 143 | 144 | ```python 145 | num1 = int(input("Please enter first number: ")) 146 | num2 = int(input("Please enter second number: ")) 147 | num3 = int(input("Please enter third number: ")) 148 | 149 | #1 and 2 150 | if (num1 > num2): 151 | tmp = num1 152 | num1 = num2 153 | num2 = tmp 154 | 155 | #1 and 3 156 | if (num1 > num3): 157 | tmp = num1 158 | num1 = num3 159 | num3 = tmp 160 | 161 | #2 and 3 162 | if (num2 > num3): 163 | tmp = num2 164 | num2 = num3 165 | num3 = tmp 166 | 167 | print(num1, num2, num3) 168 | 169 | # Another solution 170 | if a >= b and a >= c: 171 | maximum = a 172 | elif b >= a and b >= c: 173 | maximum = b 174 | else: 175 | maximum = c 176 | 177 | if a <= b and a <= c: 178 | minimum = a 179 | elif b <= a and b <= c: 180 | minimum = b 181 | else: 182 | minimum = c 183 | 184 | middle = a + b + c - minimum - maximum 185 | 186 | print(minimum, middle, maximum) 187 | 188 | """ We can find middle in another way 189 | if a != minimum and a != maximum: 190 | middle = a 191 | if b != minimum and b != maximum: 192 | middle = b 193 | if c != minimum and c != maximum: 194 | middle = c 195 | """ 196 | ``` 197 | 198 | 199 | ## Q7 200 | 201 | ```python 202 | Bob = input("Decision of Bob (silence/betrayal): ") 203 | Sam = input("Decision of Sam (silence/betrayal): ") 204 | 205 | #Solution 1 Does not print anything at incorrect input 206 | if (Bob=='silence'): 207 | if (Sam=='silence'): 208 | print("1 1") 209 | elif (Sam=='betrayal'): 210 | print("3 0") 211 | 212 | elif (Bob=='betrayal'): 213 | if (Sam=='silence'): 214 | print("0 3") 215 | elif (Sam=='betrayal'): 216 | print("2 2") 217 | 218 | #Solution 2 Prints at incorrect input 219 | if (Bob != "silence" and Bob != "betrayal") or (Sam != "silence" and Sam != "betrayal"): 220 | print("Wrong input!") 221 | else: 222 | if Bob == "silence": 223 | if Sam == "silence": 224 | print(1, 1) 225 | else: # Sam=='betrayal' 226 | print(3, 0) 227 | else: # Bob == "betrayal" 228 | if Sam == "silence": 229 | print(0, 3) 230 | else: # Sam=='betrayal' 231 | print(2, 2) 232 | 233 | ``` 234 | 235 | 236 | ## Q8 237 | 238 | ```python 239 | x = int(input()) 240 | y = int(input()) 241 | z = int(input()) 242 | 243 | # Solution 1 244 | print(not(x <= 0 or y <= 0 or z <= 0)and((x * x + y * y == z * z)or(x * x + z * z == y * y)or(y * y + z * z == x * x))) 245 | 246 | # Solution 2 247 | if x <= 0 or y <= 0 or z <= 0: 248 | print("False") 249 | elif x*x + y*y == z*z or x*x + z*z == y*y or y*y + z*z == x*x: 250 | print("True") 251 | else: 252 | print("False") 253 | ``` 254 | 255 | 256 | ## Q9 257 | 258 | ```python 259 | input = int(input("Please enter an integer from 0 to 9999:")) 260 | if (input<0 or input>9999): 261 | print("Input is not in the interval 0-9999") 262 | else: 263 | print(input//1000 + (input//100)%10 + (input//10)%10 + input%10) 264 | 265 | # More clearly 266 | if a < 0 or a > 9999: 267 | print("Input is not in the interval") 268 | else: # a = 1234 269 | summation = a % 10 # = 4 270 | a = a // 10 # a = 123 271 | summation = summation + (a % 10) # = 3 272 | a = a // 10 #12 273 | summation = summation + (a % 10) # = 2 274 | a = a // 10 #1 275 | summation = summation + a # = 1 276 | print(summation) 277 | ``` 278 | 279 | 280 | ## Q10 281 | ```python 282 | warm = int(input("Please enter the degress of water:")) 283 | if warm < 0: 284 | print("It is in the solid state.") 285 | elif warm == 0: 286 | print("It can be solid or liquid.") 287 | elif warm < 100: 288 | print("It is in the liquid state.") 289 | elif warm == 100: 290 | print("It can be liquid or gas.") 291 | else: 292 | print("It is in the gas state.") 293 | ``` 294 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /week05/Solutions.md: -------------------------------------------------------------------------------- 1 | ## Question 1 - Numbeeeers 2 | 3 | ```python 4 | N = int(input()) 5 | K = int(input()) 6 | 7 | while N <= K: 8 | print(N, end=" ") 9 | N = N + 1 10 | 11 | # OR 12 | 13 | for i in range(N, K+1): 14 | print(i, end=' ') 15 | ``` 16 | 17 | 18 | ## Question 2 - Hooping Numbers 19 | 20 | ```python 21 | A = int(input("A: ")) 22 | B = int(input("B: ")) 23 | T = int(input("T: ")) 24 | 25 | while A <= B: 26 | print(A, end=" ") 27 | A = A + T 28 | 29 | # OR 30 | 31 | for i in range(A, B+1, T): 32 | print(i, end=' ') 33 | ``` 34 | 35 | 36 | ## Question 3 - Even Numbeeeers 37 | 38 | ```python 39 | A = int(input("A: ")) 40 | B = int(input("B: ")) 41 | 42 | result = 0 43 | 44 | for i in range(A, B + 1): 45 | if i % 2 == 0: 46 | result += i 47 | 48 | print(result) 49 | 50 | # OR 51 | 52 | summation = 0 53 | 54 | while A <= B: 55 | if A % 2 == 0: 56 | summation = summation + A 57 | A = A + 1 58 | 59 | print(summation) 60 | ``` 61 | 62 | ## Question 4 - Average Team 63 | 64 | ```python 65 | N = int(input("N: ")) 66 | 67 | result = 0 68 | 69 | for _ in range(N): 70 | x = int(input()) 71 | result += x 72 | 73 | print(result/N) 74 | 75 | # OR 76 | 77 | index = 0 78 | summation = 0 79 | 80 | while index < N: 81 | a = int(input()) 82 | summation = summation + a 83 | index = index + 1 84 | 85 | print(summation / N) 86 | ``` 87 | 88 | 89 | ## Question 5 - Boom Boom POW 90 | 91 | ```python 92 | a = int(input("a: ")) 93 | b = int(input("b: ")) 94 | 95 | result = 1 96 | 97 | for _ in range(b): 98 | result *= a 99 | 100 | print(result) 101 | 102 | # OR 103 | 104 | power = 1 105 | index = 0 106 | 107 | while index < b: 108 | power = power * a 109 | index = index + 1 110 | 111 | print(power) 112 | ``` 113 | 114 | 115 | ## Question 6 - Fibonacci 116 | 117 | ```python 118 | N = int(input("N: ")) 119 | 120 | prev = 0 121 | curr = 1 122 | 123 | for _ in range(3, N+1): 124 | next = prev + curr 125 | prev = curr 126 | curr = next 127 | 128 | if N <= 0: 129 | print("Invalid!") 130 | elif N == 1: 131 | print(prev) 132 | else: 133 | print(curr) 134 | 135 | # OR 136 | 137 | """ 138 | F_x_2 + F_x_1 = F_x 139 | F_0: 0 140 | F_1: 1 141 | F_2: 0 + 1 = 1 142 | F_3: 1 + 1 = 2 143 | F_4: 1 + 2 = 3 144 | F_5: 2 + 3 = 5 145 | F_6: 3 + 5 = 8 146 | F_7: 5 + 8 = 13 147 | 148 | 0 1 1 2 3 5 8 13 149 | """ 150 | 151 | n = int(input()) - 1 152 | 153 | if n == 0: 154 | print(0) 155 | elif n == 1: 156 | print(1) 157 | else: 158 | F_x_2 = 0 159 | F_x_1 = 1 160 | index = 2 161 | while index < n: 162 | F_sum = F_x_2 + F_x_1 163 | F_x_2 = F_x_1 164 | F_x_1 = F_sum 165 | index = index + 1 166 | 167 | print(F_x_2 + F_x_1) 168 | ``` 169 | 170 | 171 | ## Question 7 - Second Largest 172 | 173 | ```python 174 | x = int(input()) 175 | largest = 0 176 | second = 0 177 | 178 | while x != 0: 179 | if x > largest: 180 | second = largest 181 | largest = x 182 | elif x > second: 183 | second = x 184 | x = int(input()) 185 | 186 | print(largest-second) 187 | 188 | # OR 189 | 190 | large_1 = int(input()) 191 | large_2 = 0 192 | 193 | while True: 194 | x = int(input()) 195 | if x == 0: 196 | break 197 | 198 | if x > large_1: 199 | large_2 = large_1 200 | large_1 = x 201 | elif x > large_2: 202 | large_2 = x 203 | 204 | print(large_1 - large_2) 205 | ``` 206 | 207 | 208 | ## Question 8 - Digiiiits 209 | 210 | ```python 211 | x = int(input()) 212 | 213 | count = 0 214 | even_sum = 0 215 | 216 | while x > 0: 217 | digit = x % 10 218 | if digit % 2 == 0: 219 | even_sum += digit 220 | count += 1 221 | 222 | x //= 10 223 | 224 | print(count, even_sum) 225 | ``` 226 | 227 | 228 | ## Question 9 - Positive Mental Attitude 229 | 230 | ```python 231 | odd_sum = 0 232 | 233 | x = int(input()) 234 | while x >= 0: 235 | if x % 2 == 1: 236 | odd_sum += x 237 | x = int(input()) 238 | 239 | print(odd_sum) 240 | ``` 241 | 242 | 243 | ## Question 10 - Guess 244 | 245 | ```python 246 | import random 247 | 248 | number = random.randint(1,100) 249 | count = 0 250 | 251 | while True: 252 | guess = input("Make your guess: ") 253 | guess = int(guess) 254 | count += 1 255 | 256 | if guess < number: 257 | print("Too low!") 258 | elif guess > number: 259 | print("Too high!") 260 | else: 261 | print("You got it!") 262 | print("And it only took you",count,"tries!") 263 | break 264 | 265 | # Limited number of tries 266 | 267 | import random 268 | 269 | number = random.randint(1, 10) 270 | 271 | count = 0 272 | trys = 3 273 | not_found = True 274 | 275 | while not_found and trys > 0: 276 | x = int(input()) 277 | count = count + 1 278 | trys = trys - 1 279 | if x > number: 280 | print("Too high!") 281 | elif x < number: 282 | print("Too low!") 283 | else: # x == number 284 | print("You got it!") 285 | not_found = False 286 | 287 | if not not_found: 288 | print("And it only took you", count, "tries!") 289 | else: 290 | print("You could not find!") 291 | ``` 292 | 293 | 294 | ## Question 11 - NoBig 295 | 296 | ```python 297 | total_sum = 0 298 | count = 1 299 | 300 | x = int(input()) 301 | y = int(input()) 302 | total_sum += x 303 | while y <= x: 304 | total_sum += y 305 | count += 1 306 | 307 | x = y 308 | y = int(input()) 309 | 310 | print(total_sum/count) 311 | ``` 312 | 313 | 314 | ## Question 12 - FizzBuzz 315 | 316 | ```python 317 | userNumber= int(input("Please enter a number: ")) 318 | for i in range(1,userNumber+1): 319 | output = "" 320 | if(i%2==0): 321 | output+= "Fizz" 322 | if(i%3==0): 323 | output+= "Buzz" 324 | if(output==""): 325 | output = i 326 | print(output) 327 | ``` 328 | 329 | 330 | ## Question 13 331 | 332 | ```python 333 | a = int(input()) 334 | b = int(input()) 335 | 336 | if a == 0 or b == 0: 337 | print(0) 338 | else: 339 | index = 1 340 | small = a 341 | if b < a: 342 | small = b 343 | 344 | result = 1 345 | 346 | while index <= small: 347 | if a % index == 0 and b % index == 0: 348 | result = index 349 | index = index + 1 350 | 351 | print(result) 352 | ``` 353 | 354 | 355 | ## Question 14 356 | 357 | ```python 358 | n = int(input()) 359 | 360 | copy = n 361 | count = 0 362 | 363 | while copy > 0: 364 | count = count + 1 365 | copy = copy // 10 366 | 367 | copy = n 368 | 369 | summation = 0 370 | 371 | while copy > 0: 372 | digit = copy % 10 373 | summation = summation + digit ** count 374 | count = count - 1 375 | copy = copy // 10 376 | 377 | print(n == summation) 378 | ``` 379 | -------------------------------------------------------------------------------- /week06/Solutions.md: -------------------------------------------------------------------------------- 1 | # Nested Loops 2 | 3 | ## Question 1 - R\*\*\*tangle 4 | 5 | ### Question 1a 6 | 7 | ```python 8 | N, M = map(int, input().split()) 9 | 10 | for _ in range(N): 11 | for _ in range(M): 12 | print("*", end="") 13 | print() 14 | ``` 15 | 16 | ### Question 1b 17 | 18 | ```python 19 | N, M = map(int, input().split()) 20 | 21 | for i in range(N): 22 | for j in range(M): 23 | if i == 0 or j == 0 or i == N - 1 or j == M - 1: 24 | print("*", end="") 25 | else: 26 | print("-", end="") 27 | print() 28 | ``` 29 | 30 | ## Question 2 - TriNumber 31 | 32 | ### Question 2a 33 | 34 | ```python 35 | N = int(input()) 36 | 37 | for i in range(1, N + 1): 38 | for j in range(i): 39 | print(i, end="") 40 | print() 41 | ``` 42 | 43 | ### Question 2b 44 | 45 | ```python 46 | N = int(input()) 47 | 48 | for i in range(1, N + 1): 49 | for j in range(i): 50 | print(j + 1, end="") 51 | print() 52 | ``` 53 | 54 | ### Question 2c 55 | 56 | ```python 57 | N, x = map(int, input().split()) 58 | 59 | for i in range(1, N+1): 60 | for j in range(i): 61 | print(x ** (j + 1), end=" ") 62 | print() 63 | ``` 64 | 65 | ## Question 3 - TriHard 66 | 67 | ```python 68 | N = int(input()) 69 | 70 | for i in range(N): 71 | for j in range(N - 1): 72 | if i + j < N: 73 | print("-", end="") 74 | else: 75 | print("*", end="") 76 | print() 77 | ``` 78 | 79 | ## Question 4 - Sum Facts 80 | 81 | ```python 82 | number = int(input()) 83 | 84 | sum = 0 85 | 86 | while number > 0: 87 | digit = number % 10 88 | number = number // 10 89 | factorial = 1 90 | for i in range(1, digit + 1): 91 | factorial *= i 92 | sum += factorial 93 | 94 | print(sum) 95 | ``` 96 | 97 | ## Question 5 - Prime Example 98 | 99 | ### Question 5a 100 | 101 | ```python 102 | n = int(input()) 103 | 104 | isPrime = True 105 | for i in range(2, n): 106 | if n % i == 0: 107 | isPrime = False 108 | break 109 | 110 | if isPrime: 111 | print("Prime") 112 | else: 113 | print("Prime Not") 114 | ``` 115 | 116 | ### Question 5b 117 | 118 | ```python 119 | n = int(input()) 120 | 121 | for j in range(2,n+1): 122 | isPrime = True 123 | for i in range(2, j): 124 | if j % i == 0: 125 | isPrime = False 126 | break 127 | if isPrime: 128 | print(j, end=" ") 129 | ``` 130 | 131 | ## Question 6 - Prime factors 132 | 133 | ### Question 6a 134 | 135 | ```python 136 | N = int(input()) 137 | 138 | for i in range(1, N + 1): 139 | if N % i == 0: 140 | print(i, end=" ") 141 | ``` 142 | 143 | ### Question 6b 144 | 145 | ```python 146 | number = int(input()) 147 | for i in range(2, number + 1): 148 | while number % i == 0: 149 | number //= i 150 | if number != 1: 151 | print(i, end=" * ") 152 | else: 153 | print(i) 154 | ``` 155 | 156 | ### Question 6c 157 | 158 | ```python 159 | number = int(input()) 160 | for i in range(2, number + 1): 161 | count = 0 162 | while number % i == 0: 163 | number //= i 164 | count += 1 165 | if count > 0: 166 | if number != 1: 167 | print(i, "^", count, end=" * ") 168 | else: 169 | print(i, "^", count) 170 | ``` 171 | 172 | ## Question 7 - Zzz 173 | 174 | ```python 175 | n = int(input("Enter number greater than 2: ")) 176 | 177 | for i in range(n): 178 | for j in range(n): 179 | if i == 0: 180 | print("*", end="") 181 | elif i == n - 1: 182 | print("*", end="") 183 | elif i + j == n - 1: 184 | print("*", end="") 185 | else: 186 | print(" ", end="") 187 | print() 188 | ``` 189 | 190 | ## Question 8 - Half-Matrix 191 | 192 | ### Question 8a 193 | 194 | ```python 195 | N = int(input()) 196 | 197 | counter = 0 198 | 199 | for i in range(1, N+1): 200 | for j in range(i): 201 | print(counter, end=" ") 202 | counter += 1 203 | print() 204 | ``` 205 | 206 | ### Question 8b 207 | 208 | ```python 209 | N = int(input()) 210 | 211 | for i in range(N): 212 | cur = i 213 | k = N - 1 214 | for j in range(i + 1): 215 | print(cur, end=" ") 216 | cur += k 217 | k -= 1 218 | print() 219 | ``` 220 | 221 | ## Question 9 - Sore Loser Bob 222 | 223 | ```python 224 | from random import randint 225 | 226 | max_score = int(input("Winning score: ")) 227 | iteration = 0 228 | bob_won = False 229 | while not bob_won: 230 | bob_score = 0 231 | iteration += 1 232 | while abs(bob_score)sam_number): 237 | bob_score+=1 238 | elif (bob_number sam_number: 263 | bob_score += 1 264 | elif sam_number > bob_number: 265 | sam_score += 1 266 | 267 | if bob_score == max_score and sam_score < max_score: 268 | bob_won = True 269 | 270 | print("Bob was able to win after", iteration, "iterations!") 271 | ``` 272 | 273 | ## Question 10 - Palindromic Primes 274 | 275 | ```python 276 | start, end = map(int, input().split()) 277 | 278 | for i in range(start, end + 1): 279 | num = i 280 | reverse = 0 281 | while num > 0: 282 | digit = num % 10 283 | num = num // 10 284 | reverse = reverse * 10 + digit 285 | if reverse == i: 286 | isPrime = True 287 | for j in range(2, i): 288 | if i % j == 0: 289 | isPrime = False 290 | break 291 | if isPrime: 292 | print(i, end=" ") 293 | ``` 294 | 295 | ## Question 11 - Draw a figure 296 | 297 | ```python 298 | size= int(input("Please enter the size: ")) 299 | 300 | backslash_pointer = 0 301 | slash_pointer = 2 * size 302 | middle_pointer = size 303 | 304 | for i in range(2 * size): 305 | if i == size: 306 | backslash_pointer += 1 307 | slash_pointer -= 1 308 | for j in range(2 * size + 1): 309 | if j == backslash_pointer: 310 | print("\\", end="") 311 | elif j == middle_pointer: 312 | print("|", end="") 313 | elif j == slash_pointer: 314 | print("/", end="") 315 | else: 316 | print(" ", end="") 317 | backslash_pointer += 1 318 | slash_pointer -= 1 319 | print() 320 | ``` 321 | 322 | 323 | -------------------------------------------------------------------------------- /week07/README.md: -------------------------------------------------------------------------------- 1 | # Functions 2 | 3 | ## Question 1 4 | 5 | Write a function called `power` that takes a required integer parameter as **number** and an optional integer parameter as **n**. The default value for **n** should be 2. The function should return the **nth** power of **number**. 6 | 7 | | Input | Output | 8 | | ----- | ------ | 9 | | 5 | 25 | 10 | | 3 2 | 9 | 11 | | 4 3 | 64 | 12 | 13 | ## Question 2 14 | 15 | Write a function which takes a number and prints the first 6 powers of the number using **power()** function from previous question. 16 | 17 | | Input | Output | 18 | | ----- | ------------------------------------------ | 19 | | 2 | 2
4
8
16
32
64 | 20 | | 3 | 3
9
27
81
243
729 | 21 | 22 | ## Question 3 23 | 24 | An **abundant number** or **excessive number** is a **number** that is smaller than the sum of its proper divisors. 25 | 26 | Write a function which takes two integers and finds the abundant numbers between those numbers (including them). If there are abundant numbers in the range, the function prints these numbers; otherwise, prints no abundant number. 27 | 28 | **Example:** The integer 12 is the first **abundant number**. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16. The amount by which the sum exceeds the **number** is the **abundance**. 29 | 30 | | Input | Output | 31 | | ----- | -------------------- | 32 | | 20 35 | 20 24 30 | 33 | | 10 40 | 12 18 20 24 30 36 40 | 34 | | 3 10 | no abundant number | 35 | 36 | ## Question 4 - Elementary Number Theory 37 | 38 | ### Question 4a - Modulus 39 | 40 | Using only addition, subtraction and a ``while`` loop, write a function that takes two numbers ``A``, ``B`` and returns ``A % B``. 41 | 42 | | Input | Output | 43 | | ----- | ------ | 44 | | 17 3 | 2 | 45 | | 27 5 | 2 | 46 | | 11 17 | 11 | 47 | 48 | ### Question 4b - GCD 49 | 50 | The **greatest common divisor** or **GCD** of two integers is the largest number that divides both integers. 51 | 52 | Write a function which takes two positive integers and returns their GCD. 53 | 54 | Hint: Implement [Euler's method](https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm). 55 | 56 | | Input | Output | 57 | | ----- | ------ | 58 | | 2 5 | 1 | 59 | | 12 8 | 4 | 60 | | 8 9 | 1 | 61 | | 15 30 | 15 | 62 | 63 | ### Question 4c - LCM 64 | 65 | The **lowest common multiple** or **LCM** of two integers is the smallest number that is a multiple of both numbers 66 | 67 | Write a function which takes two positive integers and returns their LCM. 68 | 69 | Hint: GCD(a,b) * LCM(a,b) = a*b 70 | 71 | | Input | Output | 72 | | ----- | ------ | 73 | | 2 5 | 10 | 74 | | 12 8 | 24 | 75 | | 8 9 | 72 | 76 | | 15 30 | 30 | 77 | 78 | ## Question 5 - Think 79 | 80 | Write a function that takes an integer and thinks that much. Default value is 1. 81 | 82 | | Input | Output | 83 | | ----- | ------ | 84 | | think() | hm | 85 | | think(2) | hmm | 86 | | think(5) | hmmmmm | 87 | 88 | ## Question 6 - You're a Square! 89 | When you multiply a number by itself, the result is a square number. 90 | 91 | Write a function that takes an integer and determines whether it is a square number or not. 92 | 93 | | Input | Output | 94 | | ----- | ------ | 95 | | 25 | True | 96 | | 23 | False | 97 | | 0 | True | 98 | |-1 | False| 99 | 100 | ## Question 7 101 | 102 | Write a floor function. If the input is anything other than integer or float, print a warning to the console that the input is invalid. 103 | 104 | | PARAMETER | RETURN | 105 | | - | - | 106 | | 123 | 123 | 107 | | 123.7 | 123 | 108 | | Hi! | Invalid input: Hi! | 109 | 110 | Hint: You can use type(var) function to get the type of var 111 | 112 | 113 | ## Question 8 - Points 114 | 115 | 116 | #### Question 8a - Distance 117 | 118 | Write a function **distance** which takes the coordinates of two points (x1, y1, x2, y2) and returns Euclidian distance between these points. 119 | 120 | | Input | Output | 121 | | --------------- | ------ | 122 | | 3, 0, 0, 4 | 5.0 | 123 | | 5, 8, 10, 20 | 13.0 | 124 | 125 | 126 | #### Question 8b - Closest 127 | 128 | Write a function which takes the coordinates of two points (x1, y1, x2, y2) and returns the point closest to the origin. *Use the distance 129 | function.* 130 | 131 | | Input | Output | 132 | | -------------- | ------ | 133 | | 3, 0, 0, 4 | 3, 0 | 134 | | 11, 7, 6, 8 | 6, 8 | 135 | 136 | #### Question 8c - Valid Triangle 137 | 138 | Write a function that takes three vertices of a triangle (x1, y1, x2, y2, x3, y3), and returns True if it is a valid triangle, False otherwise. If the distance between any two points is zero, raise ZeroDivisionError. 139 | 140 | | Input | Output | 141 | | -------------- | ------ | 142 | | 3, 0, 0, 4, 1, 1 | True | 143 | | 11, 7, 6, 8, 11, 7| ZeroDivisionError | 144 | | 0, 0, 0, 1, 0, 2 | False | 145 | 146 | #### Question 8d - Perimeter 147 | 148 | Write a function that takes three vertices of a triangle (x1, y1, x2, y2, x3, y3), and returns the perimeter (sum of edges). If the distance between any two points is zero, raise ZeroDivisionError. If the triangle is invalid, raise ValueError. 149 | 150 | | Input | Output | 151 | | -------------- | ------ | 152 | | 3, 0, 0, 4, 1, 1 | 10.39834563766817 | 153 | | 11, 7, 6, 8, 11, 7| ZeroDivisionError | 154 | | 0, 0, 0, 1, 0, 2 | ValueError | 155 | 156 | #### Question 8e - Area 157 | 158 | Write a function that takes three vertices of a triangle (x1, y1, x2, y2, x3, y3), and returns the area. If the distance between any two points is zero, return -1. If the triangle is invalid, return 0. 159 | 160 | | Input | Output | 161 | | -------------- | ------ | 162 | | 3, 0, 0, 4, 1, 1 | 2.5 | 163 | | 11, 7, 6, 8, 11, 7| -1 | 164 | | 0, 0, 0, 1, 0, 2 | 0 | 165 | 166 | 167 | #### Question 8f - Point in Triangle 168 | 169 | Write a function that takes three vertices of a triangle (x1, y1, x2, y2, x3, y3), and coordinates of a point. Return True if the point is inside the triangle, False otherwise. 170 | 171 | | Input | Output | 172 | | -------------- | ------ | 173 | | -3, 5, 9, 1, -6, -7, -2, 0 | True | 174 | | -3, 5, 9, 1, -6, -7, 9, 1| True | 175 | | -3, 5, 9, 1, -6, -7, 12, 1 | False | 176 | 177 | 178 | 179 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /week08/Solutions.md: -------------------------------------------------------------------------------- 1 | # Lists 2 | 3 | ## Question 1 - Large 4 | 5 | ```python 6 | N = int(input()) 7 | 8 | list1 = list() 9 | for i in range(N): 10 | list1.append(int(input())) 11 | 12 | average = 0 13 | for l in list1: 14 | average += l 15 | average /= N 16 | 17 | # average = sum(list1)/len(list1) 18 | 19 | for l in list1: 20 | if l > average: 21 | print(l, end=' ') 22 | ``` 23 | 24 | 25 | 26 | ## Question 2 - Let's Count 27 | 28 | ```python 29 | def find_freq(list1): 30 | freq = [0] * 101 31 | for l in list1: 32 | freq[l] += 1 33 | for i, f in enumerate(freq): 34 | if f > 0: 35 | print(str(i) + ' --> ' + str(f)) 36 | 37 | 38 | find_freq([5, 10, 2, 5, 50, 5, 10, 1, 2, 2]) 39 | ``` 40 | 41 | 42 | 43 | ## Question 3 - Fifth Powers 44 | 45 | ```python 46 | list1 = list(map(int, input().split())) 47 | print([x**5 for x in list1]) 48 | ``` 49 | 50 | 51 | 52 | ## Question 4 - Pairs 53 | 54 | ```python 55 | def find_pairs(list1, X): 56 | for i, l1 in enumerate(list1): 57 | for l2 in list1[i + 1:]: 58 | if l1 + l2 == X: 59 | print("(%d, %d)" % (l1, l2)) 60 | 61 | # [(l1,l2) for i, l1 in enumerate(list1) for l2 in list1[i+1:] if l1+l2==7] 62 | 63 | 64 | find_pairs([2, 4, 3, 5, 7, 8, 9], 7) 65 | ``` 66 | 67 | 68 | 69 | ## Question 5 - To the left 70 | 71 | ```python 72 | def rotate(l, n): 73 | return l[n:] + l[:n] 74 | 75 | 76 | print(rotate([1, 2, 3, 4, 5], 2)) 77 | ``` 78 | 79 | 80 | 81 | ## Question 6 - Reverse 82 | 83 | ```python 84 | N = int(input()) 85 | 86 | list1 = list() 87 | for i in range(N): 88 | list1.append(int(input())) 89 | 90 | # a 91 | print(list1[::-1]) 92 | 93 | # b 94 | list1 = list1[::-1] 95 | # list1.reverse() 96 | print(list1) 97 | ``` 98 | 99 | 100 | 101 | ## Question 7 - Remove X 102 | 103 | ```python 104 | list1 = [5, 20, 15, 20, 25, 50, 20] 105 | 106 | 107 | def removeValue(sampleList, val): 108 | return [value for value in sampleList if value != val] 109 | 110 | 111 | resList = removeValue(list1, 20) 112 | print(resList) 113 | ``` 114 | 115 | 116 | 117 | ## Question 8 - Remove Consecutive Duplicates 118 | 119 | ```python 120 | def remove_consecutive_duplicates(list1): 121 | i = 1 122 | while i < len(list1): 123 | if list1[i - 1] == list1[i]: 124 | list1.pop(i) 125 | else: 126 | i += 1 127 | return list1 128 | 129 | 130 | example = [1, 1, 1, 1, 1, 2, 2, 2, 3, 2, 2, 4, 5] 131 | print(remove_consecutive_duplicates(example)) 132 | ``` 133 | 134 | 135 | 136 | ## Question 9 - Remove Duplicates 137 | 138 | ```python 139 | def remove_duplicates(list1): 140 | result = [] 141 | for i in list1: 142 | if i not in result: 143 | result.append(i) 144 | return result 145 | # return list(dict.fromkeys(list1)) 146 | 147 | 148 | example = [1, 1, 1, 1, 1, 2, 2, 2, 3, 2, 2, 4, 5] 149 | print(remove_duplicates(example)) 150 | 151 | ``` 152 | 153 | 154 | 155 | ## Question 10 - Odd Occurrences 156 | 157 | ```python 158 | def oddones(l): 159 | mylist = [] 160 | 161 | for i in range(len(l)): 162 | if not l[i] in mylist: 163 | mylist.append(l[i]) 164 | else: 165 | mylist.remove(l[i]) 166 | 167 | for i in range(len(mylist)): 168 | print(mylist[i], end=' ') 169 | 170 | 171 | oddones([1, 1, 2, 3, 3, 3]) 172 | ``` 173 | 174 | 175 | 176 | ## Question 11 - Slice List Sum 177 | 178 | ```python 179 | def slice_list(list1, n): 180 | result = [] 181 | sind = 0 182 | for i in range(1, len(list1)+1): 183 | if sum(list1[sind:i]) > n: 184 | result.append(list1[sind:i]) 185 | sind = i 186 | return result 187 | 188 | print(slice_list([5, 3, 2, 1 ,4 ,51, 2, 1, 3, 5, 3, 5], 4))s 189 | ``` 190 | 191 | 192 | 193 | ## Question 12 - Inception 194 | 195 | ```python 196 | N = int(input()) 197 | M = int(input()) 198 | 199 | list1 = list() 200 | for i in range(N): 201 | list1.append(int(input())) 202 | 203 | list2 = list() 204 | for i in range(M): 205 | list2.append(int(input())) 206 | 207 | for j in range(len(list2) - len(list1)): 208 | isFound = True 209 | for i in range(len(list1)): 210 | if list1[i] != list2[j + i]: 211 | isFound = False 212 | break 213 | 214 | if isFound: 215 | print(j) 216 | break 217 | ``` 218 | 219 | 220 | 221 | ## Question 13 - Shuffle Double 222 | 223 | ```python 224 | 225 | def shuffle_double(list1): 226 | result = [list1[x] for x in range(0, len(list1), 2)] 227 | result.extend([list1[x] for x in range(1, len(list1), 2)]) 228 | return result 229 | 230 | print(shuffle_double([1, 2, 3, 4, 5, 6, 7, 8, 9])) 231 | ``` 232 | 233 | 234 | 235 | ## Question 14 - Bubble Sort 236 | 237 | ```python 238 | def bubble_sort(arr): 239 | n = len(arr) 240 | 241 | # Traverse through all array elements 242 | for i in range(n - 1): 243 | # range(n) also work but outer loop will repeat one time more than needed. 244 | 245 | # Last i elements are already in place 246 | for j in range(0, n - i - 1): 247 | 248 | # traverse the array from 0 to n-i-1 249 | # Swap if the element found is greater 250 | # than the next element 251 | if arr[j] > arr[j + 1]: 252 | arr[j], arr[j + 1] = arr[j + 1], arr[j] 253 | 254 | # temp = arr[j] 255 | # arr[j] = arr[j+1] 256 | # arr[j+1] = temp 257 | 258 | return arr 259 | 260 | 261 | print(bubble_sort([4, 2, 8, 6, 7, 3, 1, 5])) 262 | 263 | #print(sorted([4, 2, 8, 6, 7, 3, 1, 5])) 264 | ``` 265 | 266 | 267 | 268 | ## Question 15 - Consecutive Combo 269 | 270 | ```python 271 | def consecutive_combo(a, b): 272 | c = sorted(a+b) 273 | return len(c)-1 == c[-1] - c[0] 274 | 275 | print(consecutive_combo([7, 4, 5, 1], [2, 3, 6])) 276 | ``` 277 | -------------------------------------------------------------------------------- /week10/README.md: -------------------------------------------------------------------------------- 1 | # Strings 2 | 3 | ## Question 1 - SpOnGeBoB MeMe 4 | 5 | Write a function that takes a string and returns it by converting it into a spongebob meme. Every letter with odd index should be lowercase and every letter with even index should be uppercase. 6 | 7 | | Input | Output | 8 | | -------------------------------------- | -------------------------------------- | 9 | | stop making sponge bob memes | StOp mAkInG SpOnGe bOb mEmEs | 10 | | CMPE will be fun in the next few years | CmPe wIlL Be fUn iN ThE NeXt fEw yEaRs | 11 | 12 | 13 | ## Question 2 - Convert string to camel case 14 | There are different naming conventions: lowercase lower_case_with_under_scores UPPERCASE CamelCase. 15 | 16 | Write a function that converts dash/underscore delimited words into camel casing. Every word should start with a uppercase letter and continue with lowercase letters. (known as Upper Camel Case or Pascal Case. 17 | 18 | | Input | Output | 19 | | ----------------------------- | ---------- | 20 | | to_camel_case | ToCamelCase | 21 | | Hard_exam-pLe | HardExamPle | 22 | | unnecessarily-LONG-Example | UnnecessarilyLongExample | 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 - Stop gninnipS My sdroW! 40 | Write a function that takes a string of one or more words, and returns the same string, but with all five or more letter words reversed. 41 | 42 | | Input | Output | 43 | | ----------------------------- | ---------- | 44 | | This is another test | This is rehtona test | 45 | | You know you’re in love when you can’t fall asleep because reality is finally better than your dreams. | You know er’uoy in love when you t’nac fall peelsa esuaceb ytilaer is yllanif retteb than your .smaerd| 46 | | Challenges are what make life interesting and overcoming them is what makes life meaningful. | segnellahC are what make life gnitseretni and gnimocrevo them is what sekam life .lufgninaem | 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 - Alphabetical order 72 | 73 | Write a program that accepts a comma separated sequence of words as input and prints the words in sorted form (alphanumerically). 74 | 75 | | Input | Output | 76 | | ------------------------------------ | ---------------------------- | 77 | | red, white, black, red, green, black | black, black, green, red, red, white | 78 | 79 | 80 | ## Question 8 - Second Most Common 81 | 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. 82 | 83 | 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. 84 | Alternatively, you can use a dictionary to store the occurrences of each character. 85 | 86 | | INPUT | OUTPUT | 87 | | ------ | ------ | 88 | | " Hey there partner! " | "r" | 89 | | "CaN you CAn a CAN as a canner CaN CAn a CAN?"| "n" | 90 | | " LEsSer leather weaTheREd weTTer weathEr BettEr"| "t" | 91 | 92 | ## Question 9 - Not poor 93 | 94 | 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. 95 | 96 | | Input | Output | 97 | | ---------------------------- | ------------------- | 98 | | The lyrics is not that poor! | The lyrics is good! | 99 | | The lyrics is poor! | The lyrics is poor! | 100 | 101 | 102 | ## Question 10 - Find and replace 103 | 104 | Write a function that takes 3 strings ``input``, ``a`` and ``b`` and replaces all the instances of ``a`` in ``input`` with ``b``. 105 | 106 | | ``input`` |``a``|``b``| Output | 107 | | ----------------------------- |----|---| ---------- | 108 | | This is another test |"is"|"is not"| This not is not another test | 109 | | 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.| 110 | | Test test TeSt te st TEst teSt crest TEA | "st TE" |" test "|Test test TeSt te testst teSt cretestA | 111 | 112 | 113 | ## Question 11 - Reading Backwards 114 | You are a very skilled artist who can read sentences backwards. Jury will test you by giving you four strings. i value will be given by the jury. 115 | * Read the first one changing the order of the words in backwards. 116 | * Read the second one by changing the letters of the words as well. 117 | * Read the third one backwards but starting from the ith word (according to the given order) without changing the words. 118 | * Read the last one, again starting from the ith word but changing the words as well. 119 | 120 | | INPUT | OUTPUT | 121 | | ----- | ------ | 122 | | But then I took an arrow in the knee
i = 6 | knee the in arrow an took I then But
eenk eht ni worra na koot I neht tuB
in arrow an took I then But
ni worra na koot I neht tuB | 123 | | I want to play a game
i = 12 | game a play to want I
emag a yalp ot tnaw I
play to want I
yalp ot tnaw I | 124 | | It can't be for nothing
i = 4 | nothing for be can't It
gnihton rof eb t'nac tI
be can't It
eb t'nac tI | 125 | 126 | -------------------------------------------------------------------------------- /week10/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /week12/figures/1623750783722.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/week12/figures/1623750783722.png -------------------------------------------------------------------------------- /week12/figures/1623751368006.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/week12/figures/1623751368006.png -------------------------------------------------------------------------------- /week12/figures/1623752067689.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gokceuludogan/CmpE150-Python/da536c88ebb68f3723be28a2463e8b62db1e8aff/week12/figures/1623752067689.png --------------------------------------------------------------------------------