CS50 learning

Posted by Lance on December 3, 2018

Introduction

This is a simple introduction about computer science. You can learn it on YouTube:

https://www.youtube.com/results?search_query=cs50+2018

  • CS50 2018 - Lecture 0 - Computational Thinking, Scratch
  • CS50 2018 - Lecture 1 - C
  • CS50 2018 - Lecture 2 - Arrays
  • CS50 2018 - Lecture 3 - Memory
  • CS50 2018 - Lecture 4 - Data Structures
  • CS50 2018 - Lecture 5 - HTTP, HTML, CSS
  • CS50 2018 - Lecture 6 - Python
  • CS50 2018 - Lecture 7 - Web Programming
  • CS50 2018 - Lecture 8 - SQL
  • CS50 2018 - Lecture 9 - Life after 50

And here is some code practices downloaded from my personal online CS50 IDE. You can register EDX and use it for free. They also provide a offline IDE edition for coders.

git clone https://github.com/lance-lh/learning-cs50.git

python name attribute

This is a typical example from stackoverflow.

When the Python interpreter reads a source file, it executes all of the code found in it.

Before executing the code, it will define a few special variables. For example, if the Python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module’s name.

foo = 1

def functionA():
    print("Function A")

def functionB():
    print("Function B")

if __name__ == '__main__':
    functionA()
    functionB()
    print(foo)

Assume above python file called test.py, we run it by python test.py and it will output the following:

Function A 
Function B
1

And here is a python file called call_test.py and has the following content:

import test

print(__name__)
print(test.__name__)

run python call_test.py , it will get the following result:

__main__
test

As you can see now if statement in test fails to execute because the value of __name__ is set to test.

python argv

from sys import argv

if len(argv)==2:
    print("Hello, ", argv[1])
else:
    print("Hello, world")  # the case happens when python argv0.py or python argv.py plus plus plus...
                            # plus plus separated by space

'''
no count    0         1     2   ...
python  argv0.py    lance  this
'''

python print format

for i in range(3):
    for h in range(3):
        print("#",end="")
    print()

another example can be seen below

float-point imprecision

if you want to have an infinite amount of precision all the way out, you need an infinite amount of memory. And no Mac or PC or phone has an infinite amount of memory. And so imprecision was the analog in the floating point world to overflow, recall, where if you only have a finite number of bits you can do really well up to a point. But eventually, the computer’s got to estimate that value for you because you can’t represent an infinite number of values. For precision need, you need to import sth that allows you to use as much as memory as you want more than just the default amount of memory.

from cs50 import get_float

x = get_float("x: ")
y = get_float("y: ")
z = x / y
print(f"x / y = {z:.50f}")

struct

from cs50 import get_string

students = []

for i in range(3):
    name = get_string("Name: ")
    dorm = get_string("Dorm: ")

    # key:value
    student = {"name": name, "dorm": dorm}

    students.append(student)

for student in students:
    print(f"{student['name']} is in dorm {student['dorm']}")

python simple swap

x = 1
y = 2

print(f"x is {x}, y is {y}")
x, y = y, x
print(f"x is {x}, y is {y}")

C swap

#include<stdio.h>

void swap(int *x, int *y);

int main(void)
{
    int a = 1;
    int b = 2;

    printf("a is %i, b is %i\n",a,b);
    swap(&a,&b);
    printf("a is %i, b is %i\n",a,b);
}

void swap(int *x, int *y)
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

fontsize adjust

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>
            size
        </title>
    </head>
    <body>
        <p>
            haha, this is a simple practice for javascript.
        </p>
        <select>
            <option value="xx-large">xx-large</option>
            <option value="x-large">x-large</option>
            <option value="large">large</option>
            <option selected value="initial">initial</option>
            <option value="small">small</option>
            <option value="x-small">x-small</option>
            <option value="xx-small">xx-small</option>
        </select>
        <script>
            document.querySelector("select").onchange = function() {
                document.querySelector("body").style.fontSize = this.value;
            };
        </script>
    </body>
</html>

C struct

struct.h

// represent a student
typedef struct
{
    char *name; // string name
    char *dorm; // string dorm
}
student;

struct.c, and write the results to csv.

#include<stdio.h>
#include<string.h>
#include<cs50.h>

#include "struct.h"

int main(void)
{
    int enrollment = get_int("enrollment: ");
    student students[enrollment];s

    for (int i=0;i<enrollment;i++)
    {
        students[i].name = get_string("name: ");
        students[i].dorm = get_string("dorm: ");
        
    }

    FILE *file = fopen("students.csv","w");
    if (file)
    {
        for (int i=0;i<enrollment;i++)
        {
            fprintf(file, "%s,%s\n",students[i].name, students[i].dorm);
        }
        fclose(file);
    }
}

C linked list

#include<cs50.h>
#include<stdio.h>

typedef struct node
{
    int number;
    struct node *next;
}
node;

int main()
{
    // Memory for numbers
    node *numbers = NULL;

    // Prompt for numbers (until EOF)
    while(true)
    {
        // Prompt for number
        int number = get_int("Number: ");

        // Check for EOF
        if(number == INT_MAX)
        {
            break;
        }

        // Allocate space for number
        node *n = malloc(sizeof(node));
        if(!n) //if PC is out of memory, then malloc fails
        {
            return 1;
        }

        // Add number to list
        n->number = number;  // (*n).number, n is a pointer
        n->next = NULL;
        if(numbers) // error check, if(numbers!=NULL)
        {
            for(node *ptr = numbers; ptr!= NULL; ptr = ptr->next)
            {
                if(ptr->next == NULL) // if(!ptr->next), update ptr = ptr->next
                {
                    ptr->next = n;
                    break;
                }
            }
        }
        else
        {
            numbers = n;
        }
    }
}

malloc and free

#include<stdio.h>
#include<stdlib.h>  // the library contains malloc()

void f(void); // declaration

int main()
{
    f();
}

void f(void)
{
    int *x = malloc(10 * sizeof(int));
    x[9] = 50;
    printf("You inputted %i.\n",x[9]);
    free(x);
}

summary of searching and sorting

Algorithms Conception $O$ $\Omega$
Linear search left to right search $n$ $1$
Binary search sorted array, half $\log n$ $1$
Bubble sort bubble swap adjacent pairs $n^2$ $n$
Selection sort find the smallest one, place change $n^2$ $n^2$
Insertion sort proceed the array from left to right, shift and insert $n^2$ $n$
Merge sort split and merge $n log n$ $n log n$

Reference