0% found this document useful (0 votes)
68 views

# Blurs An Image: "Bridge - BMP" "Out - BMP"

The document contains code snippets from multiple Python and C programs that demonstrate fundamental programming concepts like input/output, variables, data types, conditional logic, loops, functions, and abstraction. The snippets progress from simple print statements and basic math operations to more complex examples using lists, functions, and parameterization.

Uploaded by

Ayush Tripathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

# Blurs An Image: "Bridge - BMP" "Out - BMP"

The document contains code snippets from multiple Python and C programs that demonstrate fundamental programming concepts like input/output, variables, data types, conditional logic, loops, functions, and abstraction. The snippets progress from simple print statements and basic math operations to more complex examples using lists, functions, and parameterization.

Uploaded by

Ayush Tripathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

6/filter/blur.

py

1 # Blurs an image
2
3 from PIL import Image, ImageFilter
4
5 # Blur image
6 before = Image.open("bridge.bmp")
7 after = before.filter(ImageFilter.BoxBlur(1))
8 after.save("out.bmp")
6/filter/edges.py

1 # Blurs an image
2
3 from PIL import Image, ImageFilter
4
5 # Find edges
6 before = Image.open("bridge.bmp")
7 after = before.filter(ImageFilter.FIND_EDGES)
8 after.save("out.bmp")
6/speller/dictionary.py

1 # Words in dictionary
2 words = set()
3
4
5 def check(word):
6 """Return true if word is in dictionary else false"""
7 if word.lower() in words:
8 return True
9 else:
10 return False
11
12
13 def load(dictionary):
14 """Load dictionary into memory, returning true if successful else false"""
15 file = open(dictionary, "r")
16 for line in file:
17 words.add(line.rstrip())
18 file.close()
19 return True
20
21
22 def size():
23 """Returns number of words in dictionary if loaded else 0 if not yet loaded"""
24 return len(words)
25
26
27 def unload():
28 """Unloads dictionary from memory, returning true if successful else false"""
29 return True
1/hello0.c

1 // A program that says hello to the world


2
3 #include <stdio.h>
4
5 int main(void)
6 {
7 printf("hello, world\n");
8 }
1/hello0.py

1 # A program that says hello to the world


2
3 print("hello, world")
1/hello1.c

1 // get_string and printf with %s


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 string answer = get_string("What's your name? ");
9 printf("hello, %s\n", answer);
10 }
1/hello1.py

1 # get_string and print, with concatenation


2
3 from cs50 import get_string
4
5 answer = get_string("What's your name? ")
6 print("hello, " + answer)
1/hello2.py

1 # get_string and print, with format strings


2
3 from cs50 import get_string
4
5 answer = get_string("What's your name? ")
6 print(f"hello, {answer}")
1/hello3.py

1 # input and print, with format strings


2
3 answer = input("What's your name? ")
4 print(f"hello, {answer}")
1/addition0.c

1 // Addition with int


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 // Prompt user for x
9 int x = get_int("x: ");
10
11 // Prompt user for y
12 int y = get_int("y: ");
13
14 // Perform addition
15 printf("%i\n", x + y);
16 }
1/addition0.py

1 # Addition with int [using get_int]


2
3 from cs50 import get_int
4
5 # Prompt user for x
6 x = get_int("x: ")
7
8 # Prompt user for y
9 y = get_int("y: ")
10
11 # Perform addition
12 print(x + y)
1/addition1.py

1 # Addition with int [using input]


2
3 # Prompt user for x
4 x = int(input("x: "))
5
6 # Prompt user for y
7 y = int(input("y: "))
8
9 # Perform addition
10 print(x + y)
1/division.py

1 # Division with int


2
3 # Prompt user for x
4 x = int(input("x: "))
5
6 # Prompt user for y
7 y = int(input("y: "))
8
9 # Perform division
10 print(x / y)
1/conditions.c

1 // Conditions and relational operators


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 // Prompt user for x
9 int x = get_int("x: ");
10
11 // Prompt user for y
12 int y = get_int("y: ");
13
14 // Compare x and y
15 if (x < y)
16 {
17 printf("x is less than y\n");
18 }
19 else if (x > y)
20 {
21 printf("x is greater than y\n");
22 }
23 else
24 {
25 printf("x is equal to y\n");
26 }
27 }
1/conditions.py

1 # Conditions and relational operators


2
3 from cs50 import get_int
4
5 # Prompt user for x
6 x = get_int("x: ")
7
8 # Prompt user for y
9 y = get_int("y: ")
10
11 # Compare x and y
12 if x < y:
13 print("x is less than y")
14 elif x > y:
15 print("x is greater than y")
16 else:
17 print("x is equal to y")
1/agree.c

1 // Logical operators
2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 // Prompt user to agree
9 char c = get_char("Do you agree? ");
10
11 // Check whether agreed
12 if (c == 'Y' || c == 'y')
13 {
14 printf("Agreed.\n");
15 }
16 else if (c == 'N' || c == 'n')
17 {
18 printf("Not agreed.\n");
19 }
20 }
1/agree0.py

1 # Logical operators
2
3 from cs50 import get_string
4
5 # Prompt user to agree
6 s = get_string("Do you agree? ")
7
8 # Check whether agreed
9 if s == "Y" or s == "y":
10 print("Agreed.")
11 elif s == "N" or s == "n":
12 print("Not agreed.")
1/agree1.py

1 # Logical operators, using lists


2
3 from cs50 import get_string
4
5 # Prompt user to agree
6 s = get_string("Do you agree? ")
7
8 # Check whether agreed
9 if s.lower() in ["y", "yes"]:
10 print("Agreed.")
11 elif s.lower() in ["n", "no"]:
12 print("Not agreed.")
1/meow0.c

1 // Opportunity for better design


2
3 #include <stdio.h>
4
5 int main(void)
6 {
7 printf("meow\n");
8 printf("meow\n");
9 printf("meow\n");
10 }
1/meow0.py

1 # Opportunity for better design


2
3 print("meow")
4 print("meow")
5 print("meow")
1/meow1.c

1 // Better design
2
3 #include <stdio.h>
4
5 int main(void)
6 {
7 for (int i = 0; i < 3; i++)
8 {
9 printf("meow\n");
10 }
11 }
1/meow1.py

1 # Better design
2
3 for i in range(3):
4 print("meow")
1/meow2.c

1 // Abstraction
2
3 #include <stdio.h>
4
5 void meow(void);
6
7 int main(void)
8 {
9 for (int i = 0; i < 3; i++)
10 {
11 meow();
12 }
13 }
14
15 // Meow once
16 void meow(void)
17 {
18 printf("meow\n");
19 }
1/meow2.py

1 # Abstraction
2
3 def main():
4 for i in range(3):
5 meow()
6
7 # Meow once
8 def meow():
9 print("meow")
10
11
12 meow()
1/meow3.c

1 // Abstraction with parameterization


2
3 #include <stdio.h>
4
5 void meow(int n);
6
7 int main(void)
8 {
9 meow(3);
10 }
11
12 // Meow some number of times
13 void meow(int n)
14 {
15 for (int i = 0; i < n; i++)
16 {
17 printf("meow\n");
18 }
19 }
1/meow3.py

1 # Abstraction with parameterization


2
3 def main():
4 meow(3)
5
6
7 # Meow some number of times
8 def meow(n):
9 for i in range(n):
10 print("meow")
11
12
13 meow()
1/positive.c

1 // Abstraction and scope


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int get_positive_int(void);
7
8 int main(void)
9 {
10 int i = get_positive_int();
11 printf("%i\n", i);
12 }
13
14 // Prompt user for positive integer
15 int get_positive_int(void)
16 {
17 int n;
18 do
19 {
20 n = get_int("Positive Integer: ");
21 }
22 while (n < 1);
23 return n;
24 }
1/positive.py

1 # Abstraction and scope


2
3 from cs50 import get_int
4
5
6 def main():
7 i = get_positive_int()
8 print(i)
9
10
11 # Prompt user for positive integer
12 def get_positive_int():
13 while True:
14 n = get_int("Positive Integer: ")
15 if n > 0:
16 break
17 return n
18
19
20 main()
1/mario0.py

1 # Prints a column of 3 bricks with a loop


2
3 for i in range(3):
4 print("#")
1/mario1.py

1 # Prints a row of 4 question marks with a loop


2
3 for i in range(4):
4 print("?", end="")
5 print()
1/mario2.py

1 # Prints a row of 4 question marks without a loop


2
3 print("?" * 4)
1/mario3.py

1 # Prints a 3-by-3 grid of bricks with loops


2
3 for i in range(3):
4 for j in range(3):
5 print("#", end="")
6 print()
1/int.py

1 # Integer non-overflow
2
3 # Iteratively double i
4 i = 1
5 while True:
6 print(i)
7 i *= 2
2/scores0.py

1 # Averages three numbers using a list


2
3 # Scores
4 scores = [72, 73, 33]
5
6 # Print average
7 print(f"Average: {sum(scores) / len(scores)}")
2/scores1.py

1 # Averages three numbers using an array and a loop


2
3 from cs50 import get_int
4
5 # Get scores
6 scores = []
7 for i in range(3):
8 scores.append(get_int("Score: "))
9
10 # Print average
11 print(f"Average: {sum(scores) / len(scores)}")
2/uppercase0.py

1 # Uppercases string one character at a time


2
3 from cs50 import get_string
4
5 s = get_string("Before: ")
6 print("After: ", end="")
7 for c in s:
8 print(c.upper(), end="")
9 print()
2/uppercase1.py

1 # Uppercases string all at once


2
3 from cs50 import get_string
4
5 s = get_string("Before: ")
6 print(f"After: {s.upper()}")
2/argv0.py

1 # Prints a command-line argument


2
3 from sys import argv
4
5 if len(argv) == 2:
6 print(f"hello, {argv[1]}")
7 else:
8 print("hello, world")
2/argv1.py

1 # Printing command-line arguments, indexing into argv


2
3 from sys import argv
4
5 for i in range(len(argv)):
6 print(argv[i])
2/argv2.py

1 # Printing command-line arguments


2
3 from sys import argv
4
5 for arg in argv:
6 print(arg)
2/exit.py

1 # Exits with explicit value, importing sys


2
3 import sys
4
5 if len(sys.argv) != 2:
6 print("missing command-line argument")
7 sys.exit(1)
8
9 print(f"hello, {sys.argv[1]}")
10 sys.exit(0)
3/numbers.py

1 # Implements linear search for numbers


2
3 import sys
4
5 # A list of numbers
6 numbers = [4, 6, 8, 2, 7, 5, 0]
7
8 # Search for 0
9 if 0 in numbers:
10 print("Found")
11 sys.exit(0)
12
13 print("Not found")
14 sys.exit(1)
3/names.py

1 # Implements linear search for names


2
3 import sys
4
5 # A list of names
6 names = ["Bill", "Charlie", "Fred", "George", "Ginny", "Percy", "Ron"]
7
8 # Search for Ron
9 if "Ron" in names:
10 print("Found")
11 sys.exit(0)
12
13 print("Not found")
14 sys.exit(1)
3/phonebook.py

1 # Implements a phone book


2
3 import sys
4
5 from cs50 import get_string
6
7 people = {
8 "Brian": "+1-617-495-1000",
9 "David": "+1-949-468-2750"
10 }
11
12 # Search for name
13 name = get_string("Name: ")
14 if name in people:
15 print(f"Number: {people[name]}")
4/compare.py

1 # Compares two strings


2
3 from cs50 import get_string
4
5 # Get two strings
6 s = get_string("s: ")
7 t = get_string("t: ")
8
9 # Compare strings
10 if s == t:
11 print("Same")
12 else:
13 print("Different")
4/copy.py

1 # Capitalizes a copy of a string


2
3 from cs50 import get_string
4
5 # Get a string
6 s = get_string("s: ")
7
8 # Capitalize copy of string
9 t = s.capitalize()
10
11 # Print strings
12 print(f"s: {s}")
13 print(f"t: {t}")
4/swap.py

1 # Swaps two integers


2
3 x = 1
4 y = 2
5
6 print(f"x is {x}, y is {y}")
7 x, y = y, x
8 print(f"x is {x}, y is {y}")
4/phonebook0.py

1 # Saves names and numbers to a CSV file


2
3 import csv
4 from cs50 import get_string
5
6 # Open CSV file
7 file = open("phonebook.csv", "a")
8
9 # Get name and number
10 name = get_string("Name: ")
11 number = get_string("Number: ")
12
13 # Print to file
14 writer = csv.writer(file)
15 writer.writerow([name, number])
16
17 # Close file
18 file.close()
4/phonebook1.py

1 # Saves names and numbers to a CSV file


2
3 import csv
4 from cs50 import get_string
5
6 # Get name and number
7 name = get_string("Name: ")
8 number = get_string("Number: ")
9
10 # Open CSV file
11 with open("phonebook.csv", "a") as file:
12
13 # Print to file
14 writer = csv.writer(file)
15 writer.writerow([name, number])
6/hogwarts/hogwarts.py

1 # Counts number of students in houses


2
3 import csv
4
5 # Numbers of students in houses
6 houses = {
7 "Gryffindor": 0,
8 "Hufflepuff": 0,
9 "Ravenclaw": 0,
10 "Slytherin": 0
11 }
12
13 # Count votes
14 with open("Sorting Hat - Form Responses 1.csv", "r") as file:
15 reader = csv.reader(file)
16 next(reader)
17 for row in reader:
18 houses[row[3]] += 1
19
20 # Print counts
21 for house in houses:
22 print(f"{house}: {houses[house]}")
1/agree2.py

1 # Logical operators, using regular expressions


2
3 import re
4
5 from cs50 import get_string
6
7 # Prompt user to agree
8 s = get_string("Do you agree? ")
9
10 # Check whether agreed
11 if re.search("^y(es)?$", s, re.IGNORECASE):
12 print("Agreed.")
13 elif re.search("^no?$", s, re.IGNORECASE):
14 print("Not agreed.")
6/speech/speech0.py

1 # Says hello
2
3 import pyttsx3
4
5 engine = pyttsx3.init()
6 engine.say("hello, world")
7 engine.runAndWait()
6/speech/speech1.py

1 # Says hello
2
3 import pyttsx3
4
5 engine = pyttsx3.init()
6 name = input("What's your name? ")
7 engine.say(f"hello, {name}")
8 engine.runAndWait()
6/faces/detect.py

1 # Find faces in picture


2 # https://github.com/ageitgey/face_recognition/blob/master/examples/find_faces_in_picture.py
3
4 from PIL import Image
5 import face_recognition
6
7 # Load the jpg file into a numpy array
8 image = face_recognition.load_image_file("office.jpg")
9
10 # Find all the faces in the image using the default HOG-based model.
11 # This method is fairly accurate, but not as accurate as the CNN model and not GPU accelerated.
12 # See also: find_faces_in_picture_cnn.py
13 face_locations = face_recognition.face_locations(image)
14
15 for face_location in face_locations:
16
17 # Print the location of each face in this image
18 top, right, bottom, left = face_location
19
20 # You can access the actual face itself like this:
21 face_image = image[top:bottom, left:right]
22 pil_image = Image.fromarray(face_image)
23 pil_image.show()
6/faces/recognize.py

1 # Identify and draw box on David


2 # https://github.com/ageitgey/face_recognition/blob/master/examples/identify_and_draw_boxes_on_faces.py
3
4 import face_recognition
5 import numpy as np
6 from PIL import Image, ImageDraw
7
8 # Load a sample picture and learn how to recognize it.
9 known_image = face_recognition.load_image_file("toby.jpg")
10 encoding = face_recognition.face_encodings(known_image)[0]
11
12 # Load an image with unknown faces
13 unknown_image = face_recognition.load_image_file("office.jpg")
14
15 # Find all the faces and face encodings in the unknown image
16 face_locations = face_recognition.face_locations(unknown_image)
17 face_encodings = face_recognition.face_encodings(unknown_image, face_locations)
18
19 # Convert the image to a PIL-format image so that we can draw on top of it with the Pillow library
20 # See http://pillow.readthedocs.io/ for more about PIL/Pillow
21 pil_image = Image.fromarray(unknown_image)
22
23 # Create a Pillow ImageDraw Draw instance to draw with
24 draw = ImageDraw.Draw(pil_image)
25
26 # Loop through each face found in the unknown image
27 for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
28
29 # See if the face is a match for the known face(s)
30 matches = face_recognition.compare_faces([encoding], face_encoding)
31
32 # Use the known face with the smallest distance to the new face
33 face_distances = face_recognition.face_distance([encoding], face_encoding)
34 best_match_index = np.argmin(face_distances)
35 if matches[best_match_index]:
36
37 # Draw a box around the face using the Pillow module
38 draw.rectangle(((left - 20, top - 20), (right + 20, bottom + 20)), outline=(0, 255, 0), width=20)
39
40 # Remove the drawing library from memory as per the Pillow docs
41 del draw
42
6/faces/recognize.py

43 # Display the resulting image


44 pil_image.show()
6/qr/qr.py

1 # Generates a QR code
2 # https://github.com/lincolnloop/python-qrcode
3
4 import os
5 import qrcode
6
7 # Generate QR code
8 img = qrcode.make("https://youtu.be/oHg5SJYRHA0")
9
10 # Save as file
11 img.save("qr.png", "PNG")
12
13 # Open file
14 os.system("open qr.png")
6/listen/listen0.py

1 # Recognizes a greeting
2
3 # Get input
4 words = input("Say something!\n").lower()
5
6 # Respond to speech
7 if "hello" in words:
8 print("Hello to you too!")
9 elif "how are you" in words:
10 print("I am well, thanks!")
11 elif "goodbye" in words:
12 print("Goodbye to you too!")
13 else:
14 print("Huh?")
6/listen/listen1.py

1 # Recognizes a voice
2 # https://pypi.org/project/SpeechRecognition/
3
4 import speech_recognition
5
6 # Obtain audio from the microphone
7 recognizer = speech_recognition.Recognizer()
8 with speech_recognition.Microphone() as source:
9 print("Say something:")
10 audio = recognizer.listen(source)
11
12 # Recognize speech using Google Speech Recognition
13 print("You said:")
14 print(recognizer.recognize_google(audio))
6/listen/listen2.py

1 # Responds to a greeting
2 # https://pypi.org/project/SpeechRecognition/
3
4 import speech_recognition
5
6 # Obtain audio from the microphone
7 recognizer = speech_recognition.Recognizer()
8 with speech_recognition.Microphone() as source:
9 print("Say something:")
10 audio = recognizer.listen(source)
11
12 # Recognize speech using Google Speech Recognition
13 words = recognizer.recognize_google(audio)
14
15 # Respond to speech
16 if "hello" in words:
17 print("Hello to you too!")
18 elif "how are you" in words:
19 print("I am well, thanks!")
20 elif "goodbye" in words:
21 print("Goodbye to you too!")
22 else:
23 print("Huh?")
6/listen/listen3.py

1 # Responds to a name
2 # https://pypi.org/project/SpeechRecognition/
3
4 import re
5 import speech_recognition
6
7 # Obtain audio from the microphone
8 recognizer = speech_recognition.Recognizer()
9 with speech_recognition.Microphone() as source:
10 print("Say something:")
11 audio = recognizer.listen(source)
12
13 # Recognize speech using Google Speech Recognition
14 words = recognizer.recognize_google(audio)
15
16 # Respond to speech
17 matches = re.search("my name is (.*)", words)
18 if matches:
19 print(f"Hey, {matches[1]}.")
20 else:
21 print("Hey, you.")

You might also like