Browse Source

Initial Loops

asathyagal18 1 year ago
parent
commit
3098590b42

+ 16 - 0
loops1/data/answer1.txt

@@ -0,0 +1,16 @@
+def every_nth_character(s, n):
+    """ (str, int) -> str
+    Return every nth character in s starting at index 0.
+    >>> every_nth_character('Computer Science', 3)
+    'CpeSee'
+    """
+    result = ''
+    i = 0
+    # TODO add the rest of the code here
+    while(i < len(s)):
+        result = result + s[i]
+        i = i + n
+
+    return result
+
+print(every_nth_character('Computer Science', 3))

+ 39 - 0
loops1/data/answer10.txt

@@ -0,0 +1,39 @@
+'''
+Fully design and write a function that given a list of temperatures,
+returns a new list containing the min temp, the max temp, and the average temp.
+Iterate over the original list one time only.
+'''
+
+'''
+Fully design and write a function that given a list of temperatures,
+returns a new list containing the min temp, the max temp, and the average temp.
+Iterate over the original list one time only.
+'''
+
+def for_temperature_stats(temps):
+    ''' list(int) => list(int)
+
+    Returns a list consisting of the minimum, maximum, and average temperatures of a list.
+
+    >>> for_temperature_stats([1, 2, 3]):
+    [1, 3, 2]
+    '''
+
+    max = temps[0]
+    min = temps[0]
+    total = 0
+
+    for val in temps:
+        if val > max:
+            max = val
+        if val < min:
+            min = val
+        total = total + val
+
+    return [min, max, total/len(temps)]
+
+data = for_temperature_stats([1, 2, 3])
+
+print("Min: " + str(data[0]))
+print("Max: " + str(data[1]))
+print("Avg: " + str(data[2]))

+ 20 - 0
loops1/data/answer2.txt

@@ -0,0 +1,20 @@
+def find_letter_n_times(s, letter, n):
+    """ (str, str, int) -> str
+    Precondition: letter occurs at least n times in s
+
+    Return the smallest substring of s starting from index
+    0 that contains n occurrences of letter.
+    >>> find_letter_n_times('Computer Science', 'e', 2)
+    'Computer Scie'
+    """
+    i = 0
+    count = 0
+
+    while(count < n):
+        if(letter == s[i]):
+            count = count + 1
+        i = i + 1
+    
+    return s[:i]
+
+print(find_letter_n_times('Computer Science', 'e', 2))

+ 20 - 0
loops1/data/answer3.txt

@@ -0,0 +1,20 @@
+def count_collatz_steps(n):
+    """ (int) -> int
+    Return the number of steps it takes to reach 1,
+    by repeating the two steps
+    of the Collatz conjecture beginning from n.
+    >>> count_collatz_steps(6)
+    8
+    """
+
+    steps = 0
+    while(n > 1):
+        if(n % 2 == 0):
+            n = n / 2
+        else:
+            n = 3 * n + 1
+        steps = steps + 1
+    
+    return steps
+
+print(str(count_collatz_steps(6)))

+ 12 - 0
loops1/data/answer4.txt

@@ -0,0 +1,12 @@
+import math
+
+def print_square_roots(n):
+    '''
+    Design and implement function print_square_roots(), which prints the square root of 
+    the first n positive numbers, starting at 1.
+    '''
+
+    for i in range(1,n):
+        print(math.sqrt(i))
+
+print_square_roots(25)

+ 18 - 0
loops1/data/answer5.txt

@@ -0,0 +1,18 @@
+'''
+Define and Implement a function that prints the first parameter n numbers starting from one.
+Then, repeat the process, but in reverse.
+
+This problem is technically supposed to be solved with while loops, but for loops work better.
+'''
+
+def print_first_n(n):
+        for i in range(1, n):
+                print(str(i))
+
+def print_first_n_reverse(n):
+        for i in range(0, n):
+                print(str(n-i))
+
+
+print_first_n(10)
+print_first_n_reverse(10)

+ 28 - 0
loops1/data/answer6.txt

@@ -0,0 +1,28 @@
+'''
+Add at least 2 examples to the docstring and complete the function.
+'''
+
+def all_fluffy(s):
+    ''' (str) -> bool
+    Return True if every letter in s appears in the word 'fluffy'
+
+    >>> all_fluffy("fluffy")
+    True
+
+    >>> all_fluffy("no")
+    False
+    '''
+
+    i = 0
+    
+    for ltr in s:
+      if ltr in "fluffy":
+        i = i + 1
+        
+    if i == len(s):
+      return True
+    else:
+      return False
+    
+if all_fluffy("fluffy"):
+  print("Fluffy!")

+ 20 - 0
loops1/data/answer7.txt

@@ -0,0 +1,20 @@
+def add_underscores(s):
+    """(str) -> str
+
+    Return s with an underscore between each pair of characters
+    # TODO: add at least two examples
+
+    >>> add_underscores("Test")
+    T_e_s_t
+
+    >>> add_underscores("Example")
+    E_x_a_m_p_l_e
+    """
+
+    text = ""
+    for ltr in s:
+        text = text + ltr + "_"
+
+    return text[:-1]
+
+print(add_underscores("Example"))

+ 25 - 0
loops1/data/answer8.txt

@@ -0,0 +1,25 @@
+def digital_sum(nums_list):
+    """ (list of str) -> int
+       
+    Precondition: s.isdigit() holds for each string s
+    in nums_list.
+    Return the sum of all the digits
+    in all strings in nums_list.
+    >>> digital_sum(['64', '128', '256'])
+    34
+    >>> digital_sum(['12', '3'])
+    6
+    # TODO: fill in the expected return of this example call.
+    """
+
+    total = 0
+
+    for i in nums_list:
+        for j in i:
+            total = total + int(j)
+
+    return total
+
+
+
+print(str(digital_sum(['64', '128', '256'])))

+ 17 - 0
loops1/data/answer9.txt

@@ -0,0 +1,17 @@
+def has_vowel(s):
+    """(str) -> bool
+    Return True if and only if s has at least one vowel, not including y.
+    >>> has_vowel("Anniversary")
+    True
+    >>> has_vowel("xyz")
+    False
+    """
+
+    for ltr in s:
+        if ltr in "aeiouAEIOU":
+            return True
+    
+    return False
+
+if(has_vowel("Anniversary")):
+    print("Has a vowel!")

+ 12 - 0
loops1/data/question1.txt

@@ -0,0 +1,12 @@
+def every_nth_character(s, n):
+    """ (str, int) -> str
+    Return every nth character in s starting at index 0.
+    >>> every_nth_character('Computer Science', 3)
+    'CpeSee'
+    """
+    result = ''
+    i = 0
+    # TODO add the rest of the code here
+    return result
+
+print(every_nth_character('Computer Science', 3))

+ 5 - 0
loops1/data/question10.txt

@@ -0,0 +1,5 @@
+'''
+Fully design and write a function that given a list of temperatures,
+returns a new list containing the min temp, the max temp, and the average temp.
+Iterate over the original list one time only.
+'''

+ 15 - 0
loops1/data/question2.txt

@@ -0,0 +1,15 @@
+def find_letter_n_times(s, letter, n):
+    """ (str, str, int) -> str
+    Precondition: letter occurs at least n times in s
+
+    Return the smallest substring of s starting from index
+    0 that contains n occurrences of letter.
+    >>> find_letter_n_times('Computer Science', 'e', 2)
+    'Computer Scie'
+    """
+    i = 0
+    count = 0
+
+    #TODO complete the rest of the function below
+
+print(find_letter_n_times('Computer Science', 'e', 2))

+ 10 - 0
loops1/data/question3.txt

@@ -0,0 +1,10 @@
+def count_collatz_steps(n):
+    """ (int) -> int
+    Return the number of steps it takes to reach 1,
+    by repeating the two steps
+    of the Collatz conjecture beginning from n.
+    >>> count_collatz_steps(6)
+    8
+    """
+
+print(str(count_collatz_steps(6)))

+ 9 - 0
loops1/data/question4.txt

@@ -0,0 +1,9 @@
+import math
+
+def print_square_roots(n):
+    '''
+    Design and implement function print_square_roots(), which prints the square root of 
+    the first n positive numbers, starting at 1.
+    '''
+
+print_square_roots(25)

+ 11 - 0
loops1/data/question5.txt

@@ -0,0 +1,11 @@
+'''
+Define and Implement a function that prints the first parameter n numbers starting from one.
+Then, repeat the process, but in reverse.
+'''
+
+def print_first_n(n):
+
+def print_first_n_reverse(n):
+
+print_first_n(10)
+print_first_n_reverse(10)

+ 11 - 0
loops1/data/question6.txt

@@ -0,0 +1,11 @@
+'''
+Add at least 2 examples to the docstring and complete the function.
+'''
+
+def all_fluffy(s):
+    ''' (str) -> bool
+    Return True if every letter in s appears in the word 'fluffy'
+    '''
+
+if all_fluffy("fluffy"):
+    print("Word is fluffy!")

+ 8 - 0
loops1/data/question7.txt

@@ -0,0 +1,8 @@
+def add_underscores(s):
+    """(str) -> str
+
+    Return s with an underscore between each pair of characters
+    # TODO: add at least two examples
+    """
+
+print(add_underscores("Example"))

+ 16 - 0
loops1/data/question8.txt

@@ -0,0 +1,16 @@
+def digital_sum(nums_list):
+    """ (list of str) -> int
+       
+    Precondition: s.isdigit() holds for each string s
+    in nums_list.
+    Return the sum of all the digits
+    in all strings in nums_list.
+    >>> digital_sum(['64', '128', '256'])
+    34
+    >>> digital_sum(['12', '3'])
+    # TODO: fill in the expected return of this example call.
+    """
+
+
+
+print(str(digital_sum(['64', '128', '256'])))

+ 11 - 0
loops1/data/question9.txt

@@ -0,0 +1,11 @@
+def has_vowel(s):
+    """(str) -> bool
+    Return True if and only if s has at least one vowel, not including y.
+    >>> has_vowel("Anniversary")
+    True
+    >>> has_vowel("xyz")
+    False
+    """
+
+if(has_vowel("Anniversary")):
+    print("Has a vowel!")

+ 5 - 0
loops1/functions_intro.html

@@ -0,0 +1,5 @@
+<div>
+<p>In this lab you will exercise writing simple While and For loops.</p>
+<p>Before you begin, review lectures about functions: Slides 04.01,
+and Slides 04.02.
+</div>

+ 5 - 0
loops1/hints/hint0.html

@@ -0,0 +1,5 @@
+<div>
+<p><strong>Hint</strong></p>
+<p>Use string indexing: String[index].</p>
+<p>Use a while or for loop to iterate over the length of the string.</p>
+</div>

+ 5 - 0
loops1/hints/hint1.html

@@ -0,0 +1,5 @@
+<div>
+<p><strong>Hint</strong></p>
+<p>Use an if statement to check if a string index is equal to the given letter.</p>
+<p>Use a while or for loop to iterate over the length of the string.</p>
+</div>

+ 5 - 0
loops1/hints/hint2.html

@@ -0,0 +1,5 @@
+<div>
+<p><strong>Hint</strong></p>
+<p>Remember the % function: if(x%2==0) means the number is even.</p>
+<p>Use a while loop to repeat the process until it ends.</p>
+</div>

+ 5 - 0
loops1/hints/hint3.html

@@ -0,0 +1,5 @@
+<div>
+<p><strong>Hint</strong></p>
+<p>Coding everything by hand is not always the best choice; use the Math.sqrt() function.</p>
+<p>Use a for loop to automatically check all integers.</p>
+</div>

+ 5 - 0
loops1/hints/hint4.html

@@ -0,0 +1,5 @@
+<div>
+<p><strong>Hint</strong></p>
+<p>Use 'for x in range(1,int):' or a while loop.</p>
+<p>Don't overthink this problem; it's really incredibly simple.</p>
+</div>

+ 6 - 0
loops1/hints/hint5.html

@@ -0,0 +1,6 @@
+<div>
+<p><strong>Hint</strong></p>
+<p>Remember that you can use the `if x in xyz' statement to check if a word contains a letter..</p>
+<p>Count the number of letters in the word and compare it to the word's length.</p>
+<p>Don't forget to complete the docstring.</p>
+</div>

+ 6 - 0
loops1/hints/hint6.html

@@ -0,0 +1,6 @@
+<div>
+<p><strong>Hint</strong></p>
+<p>Create an additional string to return, rather than modifying the original.</p>
+<p>Try to keep your loop as simple as possible: there's usually ways to catch exceptions outside of the loop.</p>
+<p>Don't forget to complete the docstring.</p>
+</div>

+ 5 - 0
loops1/hints/hint7.html

@@ -0,0 +1,5 @@
+<div>
+    <p><strong>Hint</strong></p>
+    <p>Strings and Integers are different types of variables. Be careful which one you're using.</p>
+    <p>You have to nest loops for this problem: just one loop isn't enough.</p>
+    </div>

+ 6 - 0
loops1/hints/hint8.html

@@ -0,0 +1,6 @@
+<div>
+    <p><strong>Hint</strong></p>
+    <p>Remember the 'if x in xyz' statement.</p>
+    <p>You have to nest loops for this problem: just one loop isn't enough.</p>
+    <p>You only need one return statement out of the loop: 'return False'.</p>
+    </div>

+ 6 - 0
loops1/hints/hint9.html

@@ -0,0 +1,6 @@
+<div>
+    <p><strong>Hint</strong></p>
+    <p>Think about and plan the function before you start writing.</p>
+    <p>Use a list or other type of data structure (that's easy to loop over).</p>
+    <p>Declare your variables outside of the loop.</p>
+    </div>

+ 55 - 0
loops1/index.html

@@ -0,0 +1,55 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+<title>Lab 2: Loops</title>
+<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
+<link rel="stylesheet" type="text/css" href="../css/style.css" />
+<script src="js/main.js"></script>
+</head>
+<body>
+<div id="container">
+
+<div id="header"><br><a href="../index.html">Home</a>
+<h1><a href="https://hope.simons-rock.edu/~mbarsky/intro18/tutorials/loops/LoopExercises.pdf">Lab 2: Simple Loops</a></h1></div>
+  <div id="wrapper">
+    <div id="content">
+<iframe id="contentframe" height="400px" width="100%" src="functions_intro.html" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe>  
+  <div id="buttons" style="display: none;">
+  <button onclick="show_task()">Solve</button>
+  <button onclick="show_hint()">Hint</button>
+  <button onclick="show_solution()">Solution</button>
+  <button onclick="show_explanation()">Explanation</button>
+  <button id="completed" onclick="mark_completed()">Do not show again</button>
+  </div>
+ </div>
+  </div>
+  <div id="navigation"> 
+  <a href="">Functions</a>
+			<ol>
+			<li><a href="javascript:load_problem(0)">Every N-th Character</a>
+			</li>
+			<li><a href="javascript:load_problem(1)">Find Letter N Times</a>
+			</li>			
+			<li><a href="javascript:load_problem(2)">Count Collatz Steps</a>
+			</li>
+			<li><a href="javascript:load_problem(3)">Print Square Roots</a>
+			</li>
+			<li><a href="javascript:load_problem(4)">First N Numbers</a>
+			</li>
+			<li><a href="javascript:load_problem(5)">All-Fluffy</a>
+			</li>
+			<li><a href="javascript:load_problem(6)">Add_Underscores</a>
+			</li>
+			<li><a href="javascript:load_problem(7)">Digital Sum</a>
+			</li>
+			<li><a href="javascript:load_problem(8)">Has Vowel</a>
+			</li>
+			<li><a href="javascript:load_problem(9)">Temperature Stats</a>
+			</ol>		
+  </div>  
+  <div id="footer">
+    <p>Footer</p>
+  </div>
+</div>
+</body>
+</html>

+ 109 - 0
loops1/js/main.js

@@ -0,0 +1,109 @@
+var data = [
+{problem:"data/question1.txt", 
+solution:"data/answer1.txt",
+hint:"hints/hint0.html",
+explanation:"https://hope.simons-rock.edu/~mbarsky/intro18/tutorials/loops/every_nth_character.mp4"},
+{problem:"data/question2.txt", 
+solution:"data/answer2.txt",
+hint:"hints/hint1.html",
+explanation:"https://hope.simons-rock.edu/~mbarsky/intro18/tutorials/loops/find_letter_ntimes.mp4"},
+{problem:"data/question3.txt", 
+solution:"data/answer3.txt",
+hint:"hints/hint2.html",
+explanation:"https://hope.simons-rock.edu/~mbarsky/intro18/tutorials/loops/collatz_steps.mp4"},
+{problem:"data/question4.txt", 
+solution:"data/answer4.txt",
+hint:"hints/hint3.html",
+explanation:""},
+{problem:"data/question5.txt", 
+solution:"data/answer5.txt",
+hint:"hints/hint4.html",
+explanation:""},
+{problem:"data/question6.txt", 
+solution:"data/answer6.txt",
+hint:"hints/hint5.html",
+explanation:"https://hope.simons-rock.edu/~mbarsky/intro18/tutorials/loops/all_fluffy1.mp4"},
+{problem:"data/question7.txt", 
+solution:"data/answer7.txt",
+hint:"hints/hint6.html",
+explanation:"https://hope.simons-rock.edu/~mbarsky/intro18/tutorials/loops/add_underscores.mp4"},
+{problem:"data/question8.txt", 
+solution:"data/answer8.txt",
+hint:"hints/hint7.html",
+explanation:"https://hope.simons-rock.edu/~mbarsky/intro18/tutorials/loops/digital_sum.mp4"},
+{problem:"data/question9.txt", 
+solution:"data/answer9.txt",
+hint:"hints/hint8.html",
+explanation:""},
+{problem:"data/question10.txt", 
+solution:"data/answer10.txt",
+hint:"hints/hint9.html",
+explanation:""}
+];
+
+var current_problem = -1;
+var current_included = 1;
+
+var problems = new Array(data.length);
+
+
+for (var i=0; i<problems.length; i++){
+	problems[i] = 1;
+}
+
+function load_problem(id){
+	current_problem = id;
+	current_included = problems[current_problem];
+	var iframe_elem = document.getElementById("contentframe");
+	iframe_elem.src = data[current_problem].problem;
+	show_buttons();
+}
+
+
+function show_buttons(){
+	var buttons_elem = document.getElementById("buttons");
+	if (current_problem >=0){
+		buttons_elem.style.display = "inline-block";
+	}
+	else {
+		buttons_elem.style.display = "none";
+	}
+}
+
+function show_task(){
+	var iframe_elem = document.getElementById("contentframe");
+	iframe_elem.src = data[current_problem].problem;
+	show_buttons();
+}
+
+function show_hint(){
+	var iframe_elem = document.getElementById("contentframe");
+	iframe_elem.src = data[current_problem].hint;
+	show_buttons();
+}
+
+function show_solution(){
+	var iframe_elem = document.getElementById("contentframe");
+	iframe_elem.src = data[current_problem].solution;
+	show_buttons();
+}
+
+function show_explanation(){
+	var iframe_elem = document.getElementById("contentframe");
+	iframe_elem.src = data[current_problem].explanation;
+	show_buttons();
+}
+
+function mark_completed(){
+	var include_elem = document.getElementById("completed");
+	if (current_included == 1){
+		include_elem.innerHTML = "Show again";
+		current_included = 0;
+		problems[current_problem] = 0;
+	}
+	else{
+		include_elem.innerHTML = "Do not show again";
+		current_included = 1;
+		problems[current_problem] = 1;
+	}
+}