Konstantinovich

Instructor email:  
Office hours: 
Periods 6+7 in room 301. (I get food at the start of 6, so I may be gone for a few minutes)
It helps to let me know you are coming so I am aware when you plan to come because sometimes I have meetings.
CS Dojo: 
A place to hone your skills, and practice with the guidance of caring supportive upperclassmen. 
(Will start soon)  Mon-Thur in 3073:40-4:40pm


Tools and References: 
OSX text editors:   textmate   Brackets

Network Proxy: 
Press the ubuntu start menu circle (top left)
Type: network    and click on the network icon.
click on Network Proxy, switch it to manual then fill in:
HTTP:   149.89.1.30                 3128
HTTPS:   149.89.1.30                3128
(3128 goes in the far right box of each line)

2018-02-14

posted Feb 14, 2018, 5:20 AM by Konstantinovich Samuel   [ updated Feb 14, 2018, 6:24 AM ]


This is a visualizer, so you can see what your code is actually doing:
http://pythontutor.com/visualize.html

,d88b.d88b,
88888888888
`Y8888888Y'
  `Y888Y'
    `Y'


Here is a large list of string methods:

Strings in Python are immutable. (They cannot be changed)
In order to 'change' them we re-assign them. 
Alternatively we make a new string that is different and use that modified copy.

Concatenation does not change the string:
x = "pan"
y = "duh"
print x + y #concatenation makes a new string for the result
            #it does not modify the operands (prints a modified copy)
print x     #still "pan"
print y     #still "duh"

String methods (see below) do not change the string:

print x.upper()  #Shows: PAN  (prints a modified copy)
print x          #shows: pan

Only assignment changes a string variable:
print y       #still "duh"
y = x + y     #change y to "pan"+"duh" (reassigns y to the modified copy)
print y       #shows: panduh
print x       #shows: pan



Here is a subset of string methods that exist:

Counting/Finding

str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring sub in the range [start, end]. 
Optional arguments start and end are interpreted as in slice notation.

str.find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found within the slice s[start:end]. 
Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

    str.rfind(sub[, start[, end]])    
    Return the highest index in the string where substring sub is found, such that sub is contained within s[start:end]. 
    Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

str.index(sub[, start[, end]])
Like find(), but raise ValueError when the substring is not found.

    str.rindex(sub[, start[, end]])
    Like rfind() but raises ValueError when the substring sub is not found.



Checking the string:

str.isalnum()
Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise.

str.isalpha()
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

str.isdigit()
Return true if all characters in the string are digits and there is at least one character, false otherwise.




Make Changes to string:
str.capitalize()
Return a copy of the string with its first character capitalized and the rest lowercased.

str.lower()
Return a copy of the string with all the cased characters [4] converted to lowercase.

str.upper()
Return a copy of the string with all the cased characters [4] converted to uppercase. Note that str.upper().isupper() might be False if s contains uncased characters or if the Unicode category of the resulting character(s) is not “Lu” (Letter, uppercase), but e.g. “Lt” (Letter, titlecase).

str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

str.strip([chars])
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

  str.lstrip([chars])
  Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped:

  str.rstrip([chars])
  Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:




2018-02-13

posted Feb 13, 2018, 5:33 AM by Konstantinovich Samuel   [ updated Feb 13, 2018, 7:17 AM ]

Both of these functions demonstrate that you can modify a 
numerical sequence in various ways within a single while loop.


def mrE(n):
    current = 0
    count = 0
    while current < n:
        if current % 3 == 0:
            current = current * 2 + 1
        else:
            current = current + 1
        count = count + 1
    return count

def mrF(n):
    current = 0
    count = 0
    increment = 1
    while current < n:
        current = current + increment
        increment = increment + 1
        count = count + 1
    return count


DO NOW: Evaluate the functions that are to be printed by tracing through the loop.
hint: write out the value of all variables and how they change EACH iteration of the loop.

print "mrE(29) =",mrE(29)
print "mrF(29) =",mrF(29)

DISCUSS + Write modifications
How can the functions be modified to :
a)calculate the sum of the values
b)print out all of the values.



STRINGS:

A complete list of string methods are here:

s='abcdbcA' 

#Get single characters:
s[0] # 'a'
s[1] # 'b'

#slices of the string s[i,j] gives you the charactes starting at index i
#up to but not including index j. This can be multiple characters! 
s[1:3] # 'bc'   
s[2:7] # 'cdbcA'

#using a variable:
s[x:x+n] gives you n letters, starting at x.

#There is a function to calculate the length.
len(s)  # 7 


#examples:
#Access and print each letter inside the string:

s = "Hello!!!"
i = 0
while i < len(s):
   print s[i]
   i = i + 1


Classwork + Complete the functions for homework (they will need to be submitted on codingbat at a later date.


Non loop functions:

Write a function hello(name) that returns the string "hello ???"
where ??? is the contents of the string stored in the parmeter name.
e.g.

Function Call Returned Value
hello("bob")      "hello bob"
hello("Keiko")    "hello Keiko"
hello("Bismark")  "hello Bismark"


Write a function firstHalf(s) that returns the first half of the string. 
(rounded down for odd length strings)

e.g.
Function Call                Returned Value
firstHalf("asdf")            "as"
firstHalf("asfdf")           "as"
firstHalf("fishfishfish")    "fishfi"
firstHalf("Y XT")            "Y "


Loop functions:


Write a function count(s,letter) that returns the number of occurences 
of letter inside the string s. Assume letter is length 1, and s is 0 
or more characters long. (Do not use the built in count)

e.g.  
Function Call                Returned Value
count("abba!","a")           2
count("ABBA","a")            0
count("Fish fry","f")        1

Write a function find(s,letter) that returns the index of the first  
occurence of letter inside the string s. Assume letter is length 1,
and s is 0 or more characters long. When letter is not found, return -1.
(do not use the built in find)

e.g.  
Function Call                Returned Value
find("abba!","a")           0
find("ABBA","a")            -1
find("Fish fry","f")        5


More Functions!


isVowel(letter) - returns true when letter is a vowel (not Y). False otherwise. 
Both upper and lower case vowels should be true.

e.g.

isVowel("A") -> True
isVowel("e") -> True
isVowel("Y") -> False
isVowel("f") -> False
isVowel("G") -> False



Write a function countVowels(s) that returns the number of occurences 
of vowels in the string s. Assume  s is 0 
or more characters long. 

e.g.  
Function Call                Returned Value
countVowels("abba!")           2
countVowels("ABBA")            2
countVowels("abcdeou")         4
countVowels("Fish fry")        1

2018-02-12 HW

posted Feb 11, 2018, 7:02 PM by Konstantinovich Samuel


Goal: Generating a sequence with a loop.


Notes on the print primitive:
You can print with a comma at the end of the line to prevent the new line from printing
e.g.
print 5,    #the next print is on the same line
print 6
print 7

outputs:
5 6
7

print 1
print 2,    #the next print is on the same line
print 3
print 4

outputs:
1
2 3
4


You can also separate values and print multiple things in one print statement:
print 5, 6

outputs:
5 6

print 5, 6
print 7
print 8,9

outputs:
5 6
7
8 9




Classwork:
The hailstone sequence starts at any natural number (positive integer), and always terminates with the value 1.
To generate the sequence you follow a simple set of rules:

if n = 1 : done
if n is even: the next number is n / 2
if n is odd: the next number is 3 * n + 1

So hailstone sequences starting with the first 6 values:
n:  sequence
1:  1
2:  2 1 
3:  3 10 5 16 8 4 2 1
4:  4 2 1
5:  5 16 8 4 2 1
6:  6 3 10 5 16 8 4 2 1
...


1. Write a function printHail(n) that will print the hailstone sequence (on one line for readability)
(Normally we don't print out things, instead we return them.  Since we know the starting/ending number of each sequence, it isn't a useful thing to return either. )





Once you complete the function that prints the sequence, we can move on to returning something again. 
Something we cannot predict is the length of the sequence!
2. Write a function that calculates the length of a hailstone sequence that starts with n: 
(look at the example sequences above to see why!) 
n ->  hailLen(n)
1 -> 1
2 -> 2
3 -> 8
4 -> 3
5 -> 6
6 -> 9
...


Homework:
Complete the hailstone problems on codingbat (under http://codingbat.com/home/konstans@stuy.edu/all  )

2018-02-09 HW

posted Feb 9, 2018, 6:20 AM by Konstantinovich Samuel   [ updated Feb 13, 2018, 3:57 AM ]

HW - New Problems on codngbat:   Looping Over Digits


Do Now: (On paper, do not use the computer!)
Evaluate each expression:
a) 3 / 4
b) 3 / 4.0
c) 16 % 5
d) 5 % 16
e) How can you look at the last (rightmost) digit of an integer? How about the second to last digit?
f) Would this pattern help you get any digit? Explain!

Classwork:
Write a function takes a single non-negative integer, and then prints each of the digits one at a time from right to left:
printDigits(432)
output:
2
3
4


formal parameter - the identifier used in a function to stand for the value that is passed into the method by a caller. For example, x is a formal parameter of sqrt in this example:

def sqrt(x):
   #code...

actual parameter - the (actual) value that is passed into the function by a caller. For example, the 200 used when sqrt(200) is called is an actual parameter. actual parameters are often called arguments

Discussion of a few older problems




2018-02-08 HW

posted Feb 8, 2018, 6:11 AM by Konstantinovich Samuel   [ updated Feb 8, 2018, 11:08 AM ]

Goal: While loops

(Exam Next Thursday. - All python up to loops)

Homework: (should be done over the next 2 nights)
Codingbat problems:  
Loop Numbers (some overlap the classwork)
Also complete Parrot_trouble (i forgot to assign it, but it is very easy)


Python while loops take the following format:
while boolean_expression:
    inside of loop   
    do code here
    #still inside of loop   
outside loop

Evaluate the boolean expression:
    When the boolean is true: Do the entire body, then check the boolean again.
    When the boolean is false: Skip the entire body, and continue with the rest of the code.

**See Examples below.



print "### Example 1: ###"

counter = 10
while counter > 0:
    print counter
    counter = counter - 1


print "### Example 2: ###"

i = 1
while i < 500:
    print i
    i = i * 2


print "### Example 3: ###"

temp = 200.0
while temp > 150:
    print "cooling off: ",temp
    temp = temp * .95
print "cool enough at ", temp

PROGRAM OUTPUT: 
### Example 1: ###
10
9
8
7
6
5
4
3
2
1
### Example 2: ###
1
2
4
8
16
32
64
128
256
### Example 3: ###
cooling off:  200.0
cooling off:  190.0
cooling off:  180.5
cooling off:  171.475
cooling off:  162.90125
cooling off:  154.7561875
cool enough at  147.018378125


Classwork:  PAIR PROGRAMMING
With a partner, open Idle, and write code to accomplish the following goals. 
Come up with tests to verify you are correct! BEFORE class ends, email the code to both you and your partner. You will switch who is typing halfway through.

    1. Write a loop that prints the sequence   2,4,6, ... 28,30.  (multiples of two from 2 to 30 inclusive)
    ...Give the keyboard to your partner!

    2. Write a loop that prints the multiples of 3 from 12 to 60 (inclusive).
    ...Give the keyboard to your partner!

    3a. Write a loop that prints all of the perfect squares from 1 to 5,000 inclusive (the squares are between 1 and 5000, you are not squaring 5000!!!!)
        e.g. The squares from 1 to 30 are : 1 4 9 16 25
   ...Give the keyboard to your partner!

    3b. Write a loop that prints the first 104 perfect squares starting with 1. 
    ...Give the keyboard to your partner!
    
    4. Write a loop that calculates the sum of all of the numbers between 1 and 3000 (inclusive) that are multiples 5. Print the sum.
    ...Give the keyboard to your partner!
    
    5.Write a loop that calculates the sum of all of the numbers between 1 and 3000 (inclusive) that are either multiples of 5 or multiples of 7. Print the sum.  


2018-02-07 HW

posted Feb 6, 2018, 8:26 PM by Konstantinovich Samuel   [ updated Feb 13, 2018, 3:57 AM ]

Python Reference sheet:


Goal: Top-Down Design of a program
1. Go over multiple ways to solve a few of the coding bat problems. 
2. Designing a function, and breaking it up into subproblems.

QUESTION:
What is an algorithm?


Many of the functions and programs you write are simple enough to complete without designing them. This is because you can easily understand the whole algorithm. A formula, or a simple set of if statements don't seem to require a design. 

As you write more complex code, you cannot understand the whole algorithm or process all of the consequences at once. This is why it is a good idea to DESIGN your program rather than just hack it together by writing code until it works, even though it may seem like a waste of time for now. This includes writing out your ideas on paper.

Your design will be in plain English, which makes it faster and easier to write than actual code. It is also easier to find errors in your logic, and faster to fix them rather than trying to work with a computer language.

3. Consider the following function:  DO NOT WRITE CODE until instructed.

 magicPair(n,m)   
        Look at the ones digit, and tens digit of both n and m. Larger places are ignored.
           (The hundreds digits or greater are ignored and not considered part of the problem)
        In order to be a magic pair, at least one of the two digits of n must match m.
        If there are any matching digits, the numbers are a magic pair only if the sum of the matching digits, equals the sum of the non matching digits. 

magicPair(12,10) -> True  (the 1's match, and the other two add up to 2)
magicPair(43,54) -> True  (the 4's match, and the other two add up to 8)
magicPair(53,31) -> True 

special case:
magicPair(13,13) -> False  (the 1's match and 3's match but don't add up to eachother)



Top down design: 
A plain English plan for your program.


***Write out your design, and answer the questions. DO NOT WRITE CODE until you do this.***

1. TASK: Write your steps out in English, tell the steps to your rubber ducky.

QUESTION:
Qb. There are some calculations that must be made, and it would be much easier to read code if you named the calculations by creating a function. What helper function(s) would be nice to have before you write your function?

2. Show your steps to two neighbors, and see if you both agree on each other's algorithm. Do you agree on your helper functions?

3. Write test cases for your program. Not my test cases. 

4. Write the function, and use your test cases. You must demonstrate via test cases that it works as described. 

5. Submit the problem on codingbat in the custom section of problems for the class:  codingbat.com/home/konstans@stuy.edu/all    

2018-02-06 HW

posted Feb 6, 2018, 6:22 AM by Konstantinovich Samuel   [ updated Feb 6, 2018, 11:08 AM ]

NEW STUFF

If statements in python work the same way they did in scheme and netlogo:

if a:
   statement1 #only executes when a is true

statement2 #executes all the time because it is not inside of the if




if a:
   statement1 #execute when a is true
else:
   statement2 #execute when a is false

statement3 #executes all the time because it is not inside of the if


Since an if-statement can be put inside another if statement we have to be careful. Different ways of connecting them can produce different effects. (discussed in class)

if a:
   statement1
else:
   if b: 
      statement2

OR...


if a:
   if b: 
      statement1
else:
   if c: 
      statement2

OR...

if a:
   if b: 
      statement1
   else:
      statement2
else:
   if c: 
      statement3

OR...

if a:
   if b: 
      statement1
   else:
      statement2
else:
   if c: 
      statement3
   else:
      statement4
 



You may have noticed that if/else statements that are connected start to indent too much.
if a:
   statement1
else:
   if b: 
      statement2
   else:
      if c:
          statement3
      else:
          statement4

You can re-write these statements by using an elif statement (else+if) as follows.

if a:
   statement1
elif b: 
   statement2
elif c:
   statement3
else:
   statement4


Classwork/Homework
http://codingbat.com/home/konstans@stuy.edu/all
Decisions (numerical)  + More Booleans
8 total problems.

2018-02-05 HW

posted Feb 4, 2018, 12:32 PM by Konstantinovich Samuel   [ updated Feb 5, 2018, 6:39 AM ]

Goal: Function in python

If you have not shared your Codingbat with me, please do so in your preferences: konstans@stuy.edu


Variable and function names in python:
    1. Start with a letter or underscore
    2. The rest of the characters can be letters, numbers, and underscores.
      OneFish
      blueKitten
      _what_
      x2
      c3p0
      y_u_so_n00b



-Testing code is important, codingbat does it for you. Try testing your code in IDLE, by using the test cases that codingbat provides. Keep your IDLE window open, and your test cases displayed. You can always test more problems later! (You will be more likely to do this if you have IDLE running and ready)

-These codingbat problems are easy enough to write in the codingbat window. This does not give you all the features of IDLE, so if you don't get the right answer, you can get better error messages and parenthesis matching in IDLE.
To find the custom problems that I assign here is the link:

Classwork warmup:
1 square 
2 negate 
3 funkyCalc 
4 distance 

Boolean functions generally do NOT need an if statement! Just write an EXPRESSION that uses and/or/comparisons!
5 isBig
6 isEven


Discussion about possible solutions...






HOMEWORK CODINGBAT: 
ftoc 
ctof 
evalQuadratic
pos_neg
near_hundred
sleep_in

2018-02-02 HW

posted Feb 2, 2018, 6:25 AM by Konstantinovich Samuel   [ updated Feb 3, 2018, 4:25 PM ]


Goal: Solve basic python problems

Variables in python:
There is no distinction between create/change variables in Python (like  set / let in Netlogo)

To create or change a variable in python we use the assignment operator the equals sign:

x = 3 #create a variable x make it store the value 3

name = "bob" 

pi = 3.14159

x = x + 1 #change x to: the old value of x plus 1

pi = 3 #change the value of pi

Booleans in python:

Python booleans are written as True and False. Capitalization matters.

The logical operators are:  and , or (they only work on booleans!)
The comparative operators:   
    < , >   
    <= , >=   
    == (equals)   
    !=  (not equals)   

QUESTION: Notice equals is written with two equal signs, why is this? 


Functions in python :
There is no distinction between functions/procedures in python (like to / to-report)

def <function_name> ( <comma separated parameters> ) :
    return <value or expression>

e.g.

#this is a simple function
def  foo(a,b):
    return a + b

#this shows you can have multiple statements in a function
def bar(nom):
    x = 3 * nom
    return  x == 12 #this is how you return a boolean

#this does not return a value explicitly. The function call has a special value when this happens.
def bah(name):
    print "Hello " + name

Classwork:

Boolean functions:  Tend to be tricky to students at first. They are not so bad after you practice a while.



Write a function between(number,a,b) that returns true when the number is between a and b. Assume a < b. 
Do not use   a<b<c syntax, use and/or.
Modify this to work when a is not always less than b.


Homework: (codingbat homework is not numbered)
1. Sign up for an account on codingbat.com (use your stuy.edu for consistency) 

2. Change your NAME in the preferences. Use the format   period,lastname,firstname
(copy paste, and change the value below)
  "01,Goldman,Kenji" 
( no spaces, if your name has a space or quote, remove it.)



2. Share your work with my account:  konstans@stuy.edu 
This allows me to see if you complete assignments!

3. Always log in before you work! 

4. Complete these problems on the PYTHON half of coding bat:
Warmup-1
make10 ,   sleep_in,   monkey_trouble


2018-02-01 HW01

posted Feb 1, 2018, 6:32 AM by Samuel Konstantinovich   [ updated Feb 2, 2018, 9:42 AM by Konstantinovich Samuel ]

Regarding Homework:
1. Everyone gets 4 late assignments for free! Beyond that, I will not accept late assignments. 
2. Late assignments should be no later than 1 day. 
3. If you are absent, you will have an appropriate amount of time to make up the assignment, usually one day unless it was started in class. It is your job to ask about this.

Regarding Exams:
1. The lowest grade will be dropped, provided you take all of the exams and quizzes. 
2. No make up exams. If you have a known reason to miss an exam (trip or something similar) then you can make arrangements with me and your trip organizer to take the exam.


HW01:   To be submitted on the homework server before 8am tomorrow
1. Log in to the homework server.
    Set your nickname, set your new password.
    VERIFY that they are both set.

2. Submit a plain text file on the homework server that contains:  (if you aren't sure what a plain text file is, you should stop and figure it out!)
Your header: 
    Last, First
    MKS22QA Period X 
    HW01

1. Tell me your primary computers specifications: OS, Hardware (brief summary), internet connection, Primary usage (short description)
2a. What was the most exciting topic from term1?  (Why?)
2b. What was the most challenging topic from term1? (Why?)
3. Tell me about your CS journey, skills, interests, etc. (Elaborate!)
A few paragraphs should be sufficient. (Plus a list of the computer stuff)
*If your goal is to write as little as possible to get credit, then you will probably get less credit!

3. Download and install python 2.7.x here  (x = the highest number)
  https://www.python.org/downloads/

Classwork

I. Opening a terminal
keyboard shortcuts: (because faster is better)
  Ctrl - Alt - T   : open a terminal
  Ctrl - Alt - Delete, then press ENTER :  log out


II. Change your password:
In the terminal type:
yppasswd

The terminal will then prompt you for your old password and new one twice. 
It will not show any letters or symbols as you type. This is normal. 
READ THE LAST LINE AGAIN before asking me questions about it not working.


III Basic Python
What is python?
How do we run python programs?
What editor should we use?
Basic python code.
  
IV. Development Environment
IDLE, but any plain text editor can change a python file.

Let's look at some python code:

#this line is a comment

#the next line is a print statement:
print 0

#the next line is commented out
#print 123

#this is a function we will talk about it later
def foo():
    print 1

print 2

def foo2():
    print 3

print 4
foo2()

1-10 of 10