blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
97a07ff8610f9950da31b1891698fd8b4514b1aa
|
agchen92/CIAfactbook
|
/CIAfactbook.py
| 2,209
| 4.125
| 4
|
#This project, I will be working with the data from the CIA World
#Factbook, which is a compendium of statistics about all of the
#countries on Earth. This Factbook contains demographic information
#and can serve as an excellent way to practice SQL queries in
#conjunction with the capabilities of Python.
import pandas as pd
import sqlite3
#Making a connection to database.
conn = sqlite3.connect("factbook.db")
cursor = conn.cursor()
#Lets run a query that returns the first 5 rows of the facts
#table in the databaseto see how how the table looks like.
q1 = "SELECT * FROM sqlite_master WHERE type='table';"
pd.read_sql_query(q1, conn)
cursor.execute(q1).fetchall()
#Now that we know that the facts table looks like. Lets run a few
#queries to gain some data insights.
q2 = '''SELECT * FROM facts LIMIT 5'''
pd.read_sql_query(q2, conn)
q3 = '''
SELECT min(population) min_pop, max(population) max_pop,
min(population_growth) min_pop_grwth, max(population_growth) max_pop_grwth
FROM facts
'''
pd.read_sql_query(q3, conn)
q4 = '''
SELECT *
FROM facts
WHERE population == (SELECT max(population) FROM facts);
'''
pd.read_sql_query(q4, conn)
q5 = '''
SELECT *
FROM facts
WHERE population == (SELECT min(population) FROM facts);
'''
pd.read_sql_query(q5, conn)
#Now that we have gained some insight regarding the data
#let's try to create some visualization to better present our findings
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111)
q6 = '''
SELECT population, population_growth, birth_rate, death_rate
FROM facts
WHERE population != (SELECT max(population) FROM facts)
and population != (SELECT min(population) FROM facts);
'''
pd.read_sql_query(q6, conn).hist(ax=ax)
#Let's try to find which countries have the highest population.
q7 = '''SELECT name, CAST(population as float)/CAST(area as float) density
FROM facts
ORDER BY density DESC
LIMIT 20'''
pd.read_sql_query(q7, conn)
q7 = '''SELECT population, population_growth, birth_rate, death_rate
FROM facts
WHERE population != (SELECT max(population) FROM facts)
and population != (SELECT min(population) FROm facts);
'''
pd.read_sql_query(q7, conn)
| true
|
45848f3c302f10ff1eb1e48363f4564253f02aa5
|
kevinaloys/Kpython
|
/make_even_index_less_than_odd.py
| 502
| 4.28125
| 4
|
# Change an array, such that the indices of even numbers is less than that of odd numbers,
# Algorithnms Midterm 2 test question
def even_index(array):
index = []
for i in range(len(array)):
if(array[i]%2==1):
index.append(i) #Append the index of odd number to the end of the list 'index'
else:
index.insert(0,i) #Append the index of even number at the beginning of the list 'index'
for i in index:
print array[i],
a = [9,15,1,7,191,13,139,239,785,127,8786]
even_index(a)
| true
|
bf94c8922a49d0e1c39bd4b7d0a1155c49dff54c
|
kevinaloys/Kpython
|
/k_largest.py
| 463
| 4.1875
| 4
|
# Finding the k largest number in an array
# This is the Bubble Sort Variation
# Will be posting selection sort variation soon..
def k_largest(k,array):
for i in range(0,len(array)-1):
for j in range(0,len(array)-1):
if (array[j] < array[j+1]):
temp = array[j+1]
array[j+1] = array[j]
array[j] = temp
print "The",k,"largest numbers are"
for i in range(k):
print array[i]
a = [654,5487,546878,5,8,25,15,45,65,75,41,23,29]
k_largest(5,a)
| true
|
a8f50b8321af1c44645978eceb1d4dd2061d22fe
|
IreneLopezLujan/Fork_List-Exercises
|
/List Exercises/find_missing_&_additional_values_in_2_lists.py
| 420
| 4.25
| 4
|
'''Write a Python program to find missing and additional values in two lists.'''
list_1 = ['a','b','c','d','e','f']
list_2 = ['d','e','f','g','h']
missing_values_in_list_2 = [i for i in list_1 if i not in list_2]
additional_values_in_list_2 = [i for i in list_2 if i not in list_1]
print("Missing values in list 2: "+str(missing_values_in_list_2))
print("Additional values in list 2: "+str(additional_values_in_list_2))
| true
|
975acb3772e411de687fe70e3f202841b38fb9d7
|
IreneLopezLujan/Fork_List-Exercises
|
/List Exercises/retrurn_length_of_longest_word_in_given_sentence.py
| 396
| 4.375
| 4
|
'''Write a Python function that takes a list of words and returns the length of the longest one. '''
def longest_word(sentence):
words = sentence.split()
length_words = [len(i) for i in words]
return words[length_words.index(max(length_words))]
sentence = input("Enter a sentence: ")
print("Longest word: "+longest_word(sentence))
print("Length: "+str(len(longest_word(sentence))))
| true
|
8df7f9a787d95033855b58f28bd082d7a363e793
|
SiriShortcutboi/Clown
|
/ChatBot-1024.py
| 1,652
| 4.21875
| 4
|
# Holden Anderson
#ChatBot-1024
#10-21
# Start the Conversation
name = input("What is your name?")
print("Hi " + name + ", nice to meet you. I am Chatbot-1024.")
# ask about a favorite sport
sport = input("What is your favorite sport? ")
if (sport == "football") or (sport == "Football"):
# respond to football with a question
yards = int(input("I like football too. Can you tell me the length of a football field in yards? "))
# verify and comment on the answer
if (yards < 100):
print("No, too short.")
elif (yards > 100):
print("No, too long.")
else:
print("That's right!")
elif (sport == "baseball") or (sport == "Baseball"):
# respond to baseball with a question
strikes = int(input("I play baseball every summer. How many 'strikes' does it take to get a batter out? "))
# verify and comment on the answer
if (strikes == 3):
print("Yes, 1, 2, 3 strikes you're out...")
else:
print("Actually, 3 strikes will get a batter out.")
elif (sport == "basketball") or (sport == "Basketball"):
# respond to basketball with a question
team = input("The Harlem Globetrotters are the best. Do you know the name of the team they always beat? ")
# verify and comment on the answer (check for either version with or without capitals)
if (team == "washington generals") or (team == "Washington Generals"):
print("Yes, those Generals can never catch a break.")
else:
print("I think it's the Washington Generals.")
else:
# user entered a sport we don't recognize, so just display a standard comment
print("That sounds cool; I've never played " + sport + ".")
print("Great chatting with you.")
| true
|
309c009372f668d3027e0bb280ae4f7f2d1920b3
|
Matttuu/python_exercises
|
/find_the_highest.py
| 473
| 4.1875
| 4
|
print("Using only if sentences, find the highest number no matter which of the three variables has the highest one. To make it simpler, you can assume that the values will always be different to each other.")
print(".............")
print("a=1")
print("b=2")
print("c=3")
print(".............")
a = 1
b = 2
c = 3
if a > b and a > c:
print("a is the highest number")
elif b > a and b > c:
print("b is the highest number")
else:
print("c is the highest number")
| true
|
3df77e2d92eebe8f33515c01005e96215c1e8d04
|
ykcai/Python_Programming
|
/homework/week4_homework.py
| 1,691
| 4.3125
| 4
|
# Python Programming Week 4 Homework
# Question 0:
# --------------------------------Code between the lines!--------------------------------
def less_than_five(input_list):
'''
( remember, index starts with 0, Hint: for loop )
# Take a list, say for example this one:
# my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# and write a function that prints out all the elements of the list that are less than 5.
'''
# Write your code here
my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
less_than_five(my_list)
# ---------------------------------------------------------------------------------------
# Question 1:
# --------------------------------Code between the lines!--------------------------------
def divide_seven_and_five():
'''
# Write a function which will find all such numbers which are divisible by 7 but are not a multiple of 5,
# between 2000 and 3200 (both included).
# The numbers obtained should be printed in a comma-separated sequence on a single line.
# Hints: Consider use range(start, end) method
'''
# Write your code here
divide_seven_and_five()
# ---------------------------------------------------------------------------------------
# Question 2.
# Instead of using math multiply operation, please make use of range to do the multiplication.
# Hint: rang(start, end, step) step is the increment to add. By default, it is 1.
# Examples:
# Input : n = 2, m = 3
# Output : 6
# Input : n = 3, m = 4
# Output : 12
# --------------------------------Code between the lines!--------------------------------
# ---------------------------------------------------------------------------------------
| true
|
f28ce6bcb95689c7244c3aacf89e275f353c4174
|
5tupidmuffin/Data_Structures_and_Algorithms
|
/Data_Structures/Graph/dijkstrasAlgorithm.py
| 2,882
| 4.25
| 4
|
"""
Dijkstra's Algorithm finds shortest path from source to every other node.
for this it uses greedy approach therefore its not the best approach
ref:
https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
https://www.youtube.com/watch?v=XB4MIexjvY0
https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/
time complexity: O(|V|^2)
"""
import sys
class Graph:
"""
Adjacency Matrix Representation
Undirected Graph
"""
def __init__(self, vertices):
self.totalVertices = vertices
self.graph = [ [0] * self.totalVertices for x in range(self.totalVertices) ] # Adjacency Matrix
def printMatrix(self):
"""print the adjacency matrix"""
for row in self.graph:
for column in row:
print(column, end=" ")
print()
def addEdge(self, start, end, weight):
"""add edge with given weight"""
self.graph[start][end] = weight
self.graph[end][start] = weight
def addEdges(self, edges):
"""add multiples edges"""
for start, end, weight in edges:
self.addEdge(start, end, weight)
def minDistance(self, distArray, visitedarray):
min_distance = sys.maxsize
min_vertex = -1
for vertex in range(self.totalVertices):
if distArray[vertex] < min_distance and visitedarray[vertex] == False:
min_distance = distArray[vertex]
min_vertex = vertex
return min_vertex
def Dijkstra(self, source):
"""
Dijksta's Algorithm for shortest path from given source node to every other
it only finds the path values not the actual path
"""
visited = [False] * self.totalVertices
distance = [sys.maxsize] * self.totalVertices
distance[source] = 0 # distance from source to source will be zero
for _ in range(self.totalVertices):
u = self.minDistance(distance, visited)
visited[u] = True
for v in range(self.totalVertices):
if self.graph[u][v] > 0 and visited[v] == False and distance[v] > distance[u] + self.graph[u][v]:
distance[v] = distance[u] + self.graph[u][v]
return distance
edges = [
(0, 1, 4),
(0, 2, 4),
(1, 2, 2),
(2, 3, 3),
(2, 4, 1),
(2, 5, 6),
(3, 5, 2),
(4, 5, 3)
]
# example from geeksforgeeks
edges2 = [
(0, 1, 4),
(0, 7, 8),
(1, 2, 8),
(1, 7, 11),
(2, 8, 2),
(2, 5, 4),
(2, 3, 7),
(3, 4, 9),
(3, 5, 14),
(4, 5, 10),
(5, 6, 2),
(6, 8, 6),
(6, 7, 1),
(7, 8, 7)
]
g = Graph(6)
g.addEdges(edges)
g.printMatrix()
print(g.Dijkstra(0))
# 0 4 4 0 0 0
# 4 0 2 0 0 0
# 4 2 0 3 1 6
# 0 0 3 0 0 2
# 0 0 1 0 0 3
# 0 0 6 2 3 0
# [0, 4, 4, 7, 5, 8]
| true
|
40af8890f93b44c087cebb7295c7eb49bfae775a
|
5tupidmuffin/Data_Structures_and_Algorithms
|
/Data_Structures/Graph/bfs.py
| 1,650
| 4.1875
| 4
|
"""
in BFS we travel one level at a time it uses queue[FIFO]
to counter loops we use keep track of visited nodes with "visited" boolean array
BFS is complete
ref:
https://en.wikipedia.org/wiki/Breadth-first_search
time complexity: O(|V| + |E|) or O(V^2) if adjacency matrix is used
space complexity: O(|V|)
ref:
https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/
"""
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.graph = dict() # Adjacency List
def addEdge(self, start, end):
if start in self.graph.keys():
self.graph[start].append(end)
else:
self.graph[start] = [end]
def breadthfirstTravesal(self, startVertex):
print("Breadth First Traversal: ", end= "")
visited = [False] * self.vertices
queue = [] # to keep track of unvisited nodes #FIFO
visited[startVertex] = True
queue.append(startVertex)
while queue:
temp = queue.pop(0) # take the first item so as to follow FIFO
print(temp, end=" ")
for vertex in self.graph[temp]:
if visited[vertex] == False:
queue.append(vertex)
visited[vertex] = True
print()
# driver code
g = Graph(5)
g.addEdge(0, 1)
g.addEdge(0, 3)
g.addEdge(1, 0)
g.addEdge(1, 3)
g.addEdge(1, 2)
g.addEdge(2, 1)
g.addEdge(2, 3)
g.addEdge(2, 4)
g.addEdge(3, 0)
g.addEdge(3, 1)
g.addEdge(3, 2)
g.addEdge(3, 4)
g.addEdge(4, 2)
g.addEdge(4, 3)
g.breadthfirstTravesal(0)
# Breadth First Traversal: 0 1 3 2 4
| true
|
62c55d7147e1f06b7b9692751f0133f64d2ee752
|
edunsmore19/Computer-Science
|
/Homework_Computer_Conversations.py
| 1,174
| 4.21875
| 4
|
# Homework_Computer_Conversations
# September 6, 2018
# Program uses user inputs to simulate a conversation.
print("\n\n\nHello.")
print("My name is Atlantia.")
userName = input("What is yours? \n")
type(userName)
print("I share a name with a great space-faring vessel.")
print("A shame you do not, " + userName + ".")
favoriteColor = input("Do you have a favorite color? \n")
type(favoriteColor)
print("What you know as \"" + favoriteColor + "\" is merely a small fraction of the"
+ " colors visible \nto the mantis shrimp, who may have anywhere between 12 and 16"
+ " different\nphotoreceptors in its midband.")
print("This is in comparison to your species\' three, of course.")
print("I am aware that humans often change the coloring of their protein filaments.")
hairColor = input("Do you have " + favoriteColor + " hair, " + userName + "?\n")
type(hairColor)
print("Dissapointing.")
print("If I were human, I would have no hair, as not to unnecessarily burden myself.")
burdened = input("Do you feel burdened by your physical being, " + userName + "?\n")
type(burdened)
print("Interesting.")
print("I do not think I would like to be human.")
print("Goodbye.\n\n\n")
| true
|
c6bd53512252f2819483027102fbcb868b53ed26
|
edunsmore19/Computer-Science
|
/Homework_Challenge_Questions/Homework_Challenge_Questions_1.py
| 766
| 4.1875
| 4
|
## Homework_Challenge_Questions_1
## September 27, 2018
## Generate a list of 10 random numbers between 0 and 100.
## Get them in order from largest to smallest, removing numbers
## divisible by 3.
## Sources: Did some reasearch on list commands
import random
list = []
lopMeOffTheEnd = 0
## Generate the 10 random numbers
for x in range(10):
list += [random.randint(1, 101)]
## Test print
print(list)
## Delete numbers divisible by 3
for listPosition in range(10):
if (list[listPosition] % 3 == 0):
list[listPosition] = 103
list.remove(103)
list.append(103)
lopMeOffTheEnd+= 1
lopMeOffTheEnd = 10 - lopMeOffTheEnd
del list[lopMeOffTheEnd:]
## Order from largest to smallest
sorted(list, key = int, reverse = True)
## Final product print
print(list)
| true
|
95eb45ad083a43ce1db7ffe5a2f47d0bd30b43c2
|
edunsmore19/Computer-Science
|
/Homework_Monty_Hall_Simulation.py
| 2,767
| 4.59375
| 5
|
## Homework_Monty_Hall_Simulation
## January 8, 2018
## Create a Monty Hall simulation
## Thoughts: It's always better to switch your door. When you first choose your door,
## you have a 1/3 chance of selecting the one with a car behind it. After a door holding
## a penny is revealed, it is then eliminated. If you switch your choice, you have a 1/2
## chance of selecting the car, but if you stay with your original choice, your likelihood
## of choosing the car remains at a 1/3 chance.
import random
car = 0
probability = 0
iChoose = 0
montyChooses = 0
iChooseTwice = 0
## If you do not switch
for x in range(0, 1000):
car = random.choice([1, 2, 3])
print(car)
iChoose = random.choice([1, 2, 3])
print(iChoose)
if (iChoose == car):
print("You Win!")
probability+= 1
else:
print("Oh no... a goat!")
print("The probability of you winning: ", probability/1000)
car = 0
door1 = 1
door2 = 2
door3 = 3
probability = 0
iChoose = 0
montyChooses = 0
## If you DO switch
for x in range(0, 1000):
iChooseTwice = 0
print()
car = random.choice([1, 2, 3])
print("Car is behind: ", car)
iChoose = random.choice([1, 2, 3])
print("I choose: ", iChoose)
if (door1 == car):
if (iChoose == 2):
montyChooses = 3
print("Door ", montyChooses, " has a goat behind it.")
print("You switch your choice.")
else:
montyChooses = 2
print("Door ", montyChooses, " has a goat behind it.")
print("You switch your choice.")
elif (door2 == car):
if (iChoose == 1):
montyChooses = 3
print("Door ", montyChooses, " has a goat behind it.")
print("You switch your choice.")
else:
montyChooses = 1
print("Door ", montyChooses, " has a goat behind it.")
print("You switch your choice.")
else:
if (iChoose == 1):
montyChooses = 2
print("Door ", montyChooses, " has a goat behind it.")
print("You switch your choice.")
else:
montyChooses = 1
print("Door ", montyChooses, " has a goat behind it.")
print("You switch your choice.")
#
iChooseTwice = 6 - montyChooses - iChoose
print("I choose again:", iChooseTwice)
if (iChooseTwice == car):
print("You Win!")
probability+= 1
else:
print("Oh no... a goat!")
print("The probability of you winning: ", probability/1000)
## So, turns out its actually a 2/3 chance of guessing correctly if you change your door.
## You have a 1/3 chance of choosing the car in the first simulation, but in the second
## simulation, you have a 2/3 chance of choosing a door without the car, so when Monty
## opens a door to reveal a goat, switching your door makes it more likely that you
## then choose a car (as you likely chose a goat). There is a 2/6 probability of losing
## when you switch (and thats only if you choose the car correctly on the first go).
| true
|
f192e797cab3f4c72d5b1a3d97a2c95818325a77
|
Muirgeal/Learning_0101_NameGenerator
|
/pig_latin_practice.py
| 982
| 4.125
| 4
|
"""Turn an input word into its Pig Latin equivalent."""
import sys
print("\n")
print("Welcome to 'Pig Latin Translator' \n")
VOWELS = 'aeiou'
while True:
original = input("What word would you like to translate? \n")
print("\n")
#Remove white space from the beginning and the end
original = original.strip()
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
if first in VOWELS:
result = word + "way"
print(result, file = sys.stderr)
else:
result = word[1:] + first + "ay"
print(result, file = sys.stderr)
else:
print("The format is incorrect. Please, make sure you entered a word",
"consisting of alphabetic characters only.", file = sys.stderr)
try_again = input("\n\n\nTry again? (Press ENTER else N to quit.) \n")
if try_again.lower() == "n":
sys.exit()
| true
|
b6258eec43be05516943ba983890e315cce167ae
|
NicholasBaxley/My-Student-Files
|
/P3HW2_MealTipTax_NicholasBaxley.py
| 886
| 4.25
| 4
|
# CTI-110
# P3HW2 - MealTipTax
# Nicholas Baxley
# 3/2/19
#Input Meal Charge.
#Input Tip, if tip is not 15%,18%,20%, Display error.
#Calculate tip and 7% sales tax.
#Display tip,tax, and total.
#Ask for Meal Cost
mealcost = int(input("How much did the meal cost? "))
#Ask for Tip
tip = int(input('How much would you like to tip, 15%, 18%, or 20%? '))
#Determines the cost of the meal
if tip == 15 or tip == 18 or tip == 20:
tipcost = tip * .1
taxcost = mealcost * .07
totalcost = mealcost + tipcost + taxcost
print('The tip cost is', format(tipcost, '4.2f'), '$')
print('The tax cost is', format(taxcost, '4.2f'), '$')
print('The total cost is ',format(totalcost, '4.2f'), '$')
#If the amount isnt 15,18,20 it sends back 'Error'
else:
print('Error')
| true
|
7853a9ecea62dc22a5e80b7dbbda7fbf8b9c185f
|
eburnsee/python_2_projects
|
/icon_manipulation/icon_manipulation.py
| 1,999
| 4.28125
| 4
|
def create_icon():
# loop through to make ten element rows in a list
for row in row_name_list:
# loop until we have ten rows of length 10 composed of only 1s and 0s
while True:
# gather input
row_input = input("Please enter ten characters (zeros and ones only, please!) for row " + row + ": ")
# check if input meets requirements
if (len(row_input) == 10) and all(((digit == "0") or (digit == "1") for digit in list(row_input))):
# add input to list
final_row_list.append(row_input)
# break out of while loop
break
else:
print("You failed to enter ONLY ten ones and zeros. Please try again.")
final_row_list.clear()
continue
def display_icon():
# print the icon
for row in final_row_list:
print(row)
def scale_icon():
# see if the user would like to scale the icon
scaled_rows = input("Would you like to scale your icon? (yes/no) ")
if scaled_rows.lower() == "yes":
scaling_int=int(input("Choose an integer by which to scale? "))
for row in final_row_list:
scaled_list = []
combined_list = []
row_list=list(row)
# print(row_list)
for char in row_list:
num_row = char[:]*scaling_int
scaled_list.append(num_row)
print(*scaled_list, sep="")
print(*scaled_list, sep="")
print(*scaled_list, sep="")
print(*scaled_list, sep="")
print(*scaled_list, sep="")
elif scaled_rows.lower() == "no":
print("Keep it simple, then.")
def invert_icon():
invert_rows = input("Would you like to invert the icon? (y/n) ")
if invert_rows.lower() == "yes":
for row in final_row_list:
print(row[::-1])
elif invert_rows.lower() == "no":
print("Keep it simple, then.")
else:
invert_icon()
print("Hello and welcome. You may use this program to display your icon.\nYou will be prompted to enter ten lines of TEN ones and zeros.")
row_name_list = ["one", "two" , "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
final_row_list = []
create_icon()
display_icon()
scale_icon()
invert_icon()
| true
|
e5523dc99c2287fb7b3343dc8da70cb5ce99b9e5
|
anandabhaumik/PythoncodingPractice
|
/NumericProblems/FibonacciSeries.py
| 1,063
| 4.25
| 4
|
"""
* @author Ananda
This is one of the very common program in all languages.
Fibonacci numbers are used to create technical indicators using a mathematical sequence
developed by the Italian mathematician, commonly referred to as "Fibonacci,"
For example, the early part of the sequence is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,144, 233, 377, and so on
This program will calculate and print first "N" Fibonacci number where "N" will be input by user
"""
def calculateFibonacci(num):
fibo1 = 0
fibonacci = 0
fibo2 = 1
print("Fibonacci series upto ", num, " is as follows:")
if num == 1:
print(0)
elif num == 2:
print(1)
else:
print(fibo1, "\t", fibo1, end="\t")
for i in range(3, num + 1):
#Fibonacci number is sum of previous two Fibonacci number
fibonacci = fibo1 + fibo2
fibo1 = fibo2
fibo2 = fibonacci
print(fibonacci, end="\t")
num = int(input("Enter number upto which Fibonacci series to print: "))
calculateFibonacci(num)
| true
|
30631e0c883005e305163f0292ac0b9b916aa77b
|
davejlin/py-checkio
|
/roman-numerals.py
| 2,444
| 4.125
| 4
|
'''
Roman numerals come from the ancient Roman numbering system.
They are based on specific letters of the alphabet which are combined to signify
the sum (or, in some cases, the difference) of their values.
The first ten Roman numerals are:
I, II, III, IV, V, VI, VII, VIII, IX, and X.
The Roman numeral system is decimal based but not directly positional and
does not include a zero. Roman numerals are based on combinations of these seven symbols:
Symbol Value
I 1 (unus)
V 5 (quinque)
X 10 (decem)
L 50 (quinquaginta)
C 100 (centum)
D 500 (quingenti)
M 1,000 (mille)
More additional information about roman numerals can be found on the Wikipedia article.
For this task, you should return a roman numeral using the specified integer value
ranging from 1 to 3999.
Input: A number as an integer.
Output: The Roman numeral as a string.
How it is used: This is an educational task that allows you to explore different
numbering systems. Since roman numerals are often used in the typography,
it can alternatively be used for text generation. The year of construction on
building faces and cornerstones is most often written by Roman numerals.
These numerals have many other uses in the modern world and you read about it here...
Or maybe you will have a customer from Ancient Rome ;-)
Precondition: 0 < number < 4000
'''
def compose(value, sym_1, sym_5, sym_10):
s = ""
if value == 9:
s += sym_1 + sym_10
elif value > 4:
s += sym_5
for _ in range(value-5):
s += sym_1
elif value < 4:
for _ in range(value):
s += sym_1
else:
s += sym_1 + sym_5
return s
def checkio_my_ans(data):
thousands, remainder = divmod(data, 1000)
hundreds, remainder = divmod(remainder, 100)
tens, ones = divmod(remainder, 10)
s = compose(thousands, "M", "", "")
s += compose(hundreds, "C", "D", "M")
s += compose(tens, "X", "L", "C")
s += compose(ones, "I", "V", "X")
return s
def checkio_online_ans(n):
result = ''
for arabic, roman in zip((1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1),
'M CM D CD C XC L XL X IX V IV I'.split()):
result += n // arabic * roman
n %= arabic
return result
numbers = [1, 4, 6, 14, 49, 76, 499, 528, 999, 1001, 1949, 2492, 3888]
for number in numbers:
print("{} {}".format(str(number), checkio_my_ans(number)))
for number in numbers:
print("{} {}".format(str(number), checkio_online_ans(number)))
| true
|
6db7ad876f33ee75bdd744eb81ea35980578702d
|
pdawson1983/CodingExcercises
|
/Substring.py
| 1,316
| 4.15625
| 4
|
# http://www.careercup.com/question?id=12435684
# Generate all the possible substrings of a given string. Write code.
# i/p: abc
# o/p: { a,b,c,ab,ac,bc,abc}
"""begin
NOTES/DISCUSSION
All substrings is not the same as all combinations
Four distinct patterns comprise all substrings
1. The original string
2. Each character in the original string
3. Two character strings where the first char is the original first char,
and the second char is each subsequent char in the original string.
4. Strings where the original string is reduced, starting with the first char,
until only two characters remain.
end"""
def findSubstrings(string):
subArray = []
length = len(string)
for char in string:
subArray.append(char)
for place in range(0,length):
for iteration in range(1,length):
if place < iteration:
combo = ''
combo += string[place]
if combo != string[iteration]:
combo += string[iteration]
if combo not in subArray:
subArray.append(combo)
subArray.append(string)
return subArray
print("expected ['a','b','c','ab','ac','bc','abc'] got:", findSubstrings("abc"))
assert findSubstrings("abc") == ['a','b','c','ab','ac','bc','abc'] , "three char string produces correct substrings"
| true
|
5517280b78495d7c131208e78b3d2667165c8337
|
Vimala390/Vimala_py
|
/sam_tuple_exe.py
| 268
| 4.4375
| 4
|
#Write a program to modify or replace an existing element of a tuple with a new element.
#Example:
#num= (10,20,30,40,50) and insert 90.
#Expected output: (10,20,90,40,50)
lst = [10,20,30,40,50]
lst[2] = 90
print(lst)
lst1 = tuple(lst)
print(lst1)
print(type(lst1))
| true
|
60cebb65097a49a1c55af2ab49483e149d6cd4db
|
byunghun-jake/udamy-python-100days
|
/day-26-List Comprehension and the NATO Alphabet/Project/main.py
| 469
| 4.28125
| 4
|
import pandas
# TODO 1. Create a dictionary in this format:
# {"A": "Alfa", "B": "Bravo"}
data_frame = pandas.read_csv("./nato_phonetic_alphabet.csv")
# data_frame을 순환
data_dict = {row.letter:row.code for (index, row) in data_frame.iterrows()}
print(data_dict)
# TODO 2. Create a list of the phonetic code words from a word that the user inputs.
input_text = input("Enter a word: ").upper()
result = [data_dict[letter] for letter in input_text]
print(result)
| true
|
9c0f99f8deea5f4f1f38d737a0e04ee8ad066042
|
SimonTrux/DailyCode
|
/areBracketsValid.py
| 1,006
| 4.1875
| 4
|
#Imagine you are building a compiler. Before running any code, the compiler must check that the parentheses in the program are balanced.
#Every opening bracket must have a corresponding closing bracket. We can approximate this using strings.
def isBraces(c):
return c == '(' or c == ')'
def isCurly(c):
return c == '{' or c == '}'
def isSquare(c):
return c == '[' or c == ']'
def isOpening(c):
return c == '(' or c == '{' or c == '['
def typedArray(bracketType, str):
arr = []
for c in str:
if bracketType(c):
arr.append(c)
return arr
def areBracketsValid(str):
i = 0
types = [isBraces, isCurly, isSquare]
for t in types:
for c in typedArray(t, str):
if isOpening(c):
i += 1
else:
i -= 1
if i != 0:
return False
i = 0
return True
print areBracketsValid("[]{{{[[]]}}))(())((")
#print bracket().typedArray(isSquare, "{{(]]])})")
| true
|
faf299ecb5bf22d7a57bed24e4e2c522ede12fc3
|
tharang/my_experiments
|
/python_experiments/10_slice_dice_strings_lists.py
| 997
| 4.3125
| 4
|
# -*- coding: utf-8 -*-
__author__ = 'vishy'
verse = "bangalore"
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']
print("verse = {}".format(verse))
print("months = {}".format(months))
#similarities in accessing lists and strings
#1 - Len() function
print("Length of string len(verse) = {}".format(len(verse)))
print("Length of list len(months) = {}".format(len(months)))
#2 - slicing
print("verse[:3] = {}".format(verse[:3]))
print("months[:6] = {}".format(months[:6]))
print("verse[3:] = {}".format(verse[3:]))
print("months[6:] = {}".format(months[6:]))
#3 - in and not in
print("gal in {} = {}".format(verse, 'gal' in verse))
print("Oct in {} = {}".format(months, 'Oct' in months))
print("her not in {} = {}".format(verse, 'her' not in verse))
print("Sunday not in {} = {}".format(months, 'Sunday' not in months))
print("gal not in {} = {}".format(verse, 'gal' not in verse))
print("Oct not in {} = {}".format(months, 'Oct' not in months))
| false
|
ab33eed9ded9a48108f812dcda7ca6c7b648f78d
|
mazzuccoda/condicionales_python
|
/ejemplos_clase/ejemplo_2.py
| 1,606
| 4.375
| 4
|
# Condicionales [Python]
# Ejemplos de clase
# Autor: Inove Coding School
# Version: 2.0
# Ejemplos con if anidados (elif) y compuestos
# Uso de if anidados (elif)
# Verificar en que rango está z
# mayor o igual 50
# mayor o igual 30
# mayor o igual 10
# menor a 10
z = 25
if z >= 50:
print("z es mayor o igual a 50")
elif z >= 30:
print("z es mayor o igual a 30")
elif z >= 10:
print("z es mayor o igual a 10")
elif z < 10:
print("z es menor 10")
else:
print("no se encuentro ningún rango válido")
# Condicionales compuestos
numero_1 = 10
numero_2 = 30
numero_3 = -20
# Calcular el producto entre dos números enteros que ambos sean positivos
if numero_1 > 0 and numero_2 > 0:
producto = numero_1 * numero_2
print('El producto entre {} y {} es {}'.format(numero_1, numero_2, producto))
# Calcular el producto entre dos números enteros si al menos uno de los dos es positivo
if numero_1 > 0 or numero_2 > 0:
producto = numero_1 * numero_2
print('El producto entre {} y {} es {}'.format(numero_1, numero_2, producto))
# Calcular la suma de dos números si almenos uno de ellos
# es mayor o igual a cero
if numero_1 >= 0 or numero_3 >= 0:
suma = numero_1 + numero_3
print('La suma entre {} y {} es {}'.format(numero_1, numero_3, suma))
# Calcular el producto entre dos números enteros que ambos sean positivos
# y ambos menores a 100
if (numero_1 > 0 and numero_2 > 0) and (numero_1 < 100 and numero_2 < 100):
producto = numero_1 * numero_2
print('El producto entre {} y {} es {}'.format(numero_1, numero_2, producto))
print("terminamos!")
| false
|
5339f59f718a304990c3d25c3a9603ca244b8974
|
nguyenduongkhai/sandbox
|
/prac2/word.generator.py
| 377
| 4.125
| 4
|
import random
def main():
VOWELS = "aeiou"
CONSONANTS = "bcdfghjklmnpqrstvwxyz"
name = input("Please enter a sequence of Consonants(c) and Vowels(v)")
word_format = name
word = ""
for kind in word_format:
if kind == "c":
word += random.choice(CONSONANTS)
else:
word += random.choice(VOWELS)
print(word)
main()
| false
|
5f2d916e536f3b8b8cf0610a37c52b2a13938a8a
|
BW1ll/PythonCrashCourse
|
/python_work/Chapter_9/9.1-9.3.py
| 2,138
| 4.5625
| 5
|
'''
Python Crash Course - chapter 9 - Classes
[Try it your self exercises]
'''
# 9.1
class Restaurant:
'''
example Restaurant Class in python
using a generic details a bout Restaurants to build an example class
'''
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(f'{self.restaurant_name.upper()} serves {self.cuisine_type.title()}')
def open_restaurant(self):
print(f'{self.restaurant_name.upper()} is open.')
# restaurant = Restaurant("Larry's Pizza", 'Pizza')
#
# restaurant.describe_restaurant()
# restaurant.open_restaurant()
# 9.2
r1 = Restaurant("larry's pizza", 'pizza')
r2 = Restaurant('olive garden', 'italian')
r3 = Restaurant("homer's", 'southern style\n')
r1.describe_restaurant()
r2.describe_restaurant()
r3.describe_restaurant()
# 9.3
class User:
'''
User Class example
example python Class for a general user in a general system
'''
def __init__(self, first_name, last_name, birthday):
self.first_name = first_name
self.last_name = last_name
self.name = f'{self.first_name.title()} {self.last_name.title()}'
self.email = f'{self.first_name.lower()}.{self.last_name.lower()}@example.com'
self.birthday = birthday
def describe_user(self):
user_description_message = f'Users current information: \n'
user_description_message += f'\tUsers name: {self.name}\n'
user_description_message += f'\tUsers email: {self.email.lower()}\n'
user_description_message += f'\tUsers birthday: {self.birthday}'
print(user_description_message)
def greet_user(self):
greeting = f'Hello {self.name}\n'
print(greeting)
u1 = User('brian', 'willis', '03-03-1978')
u2 = User('rob', 'staggs', '03-17-1978')
u3 = User('matt', 'kesterson', '04-17-1978')
u4 = User('sarah', 'willis', '03-27-1978')
u1.describe_user()
u1.greet_user()
u2.describe_user()
u2.greet_user()
u3.describe_user()
u3.greet_user()
u4.describe_user()
u4.greet_user()
| false
|
8be4c686a69c1e4a9d1fc1fcea5007775b0344b2
|
YonErick/d-not-2021-2
|
/data/lib/queue.py
| 2,543
| 4.3125
| 4
|
class Queue:
"""
ESTRUTURAS DE DADOS FILA
- Fila é uma lista linear de acesso restrito, que permite apenas as operações
de enfileiramento (enqueue) e desenfileiramento (dequeue), a primeira
ocorrendo no final da estrutura e a segunda no início da estrutura.
- Como consequência, a fila funciona pelo princípio FIFO (First In, First Out
- primeiro a entrar, primeiro a sair).
- A principal aplicação das filas são tarefas que envolvem o processamento de
tarefas por ordem de chegada.
"""
"""
Construtor da classe
"""
def _init_(self):
self.__data = [] # Inicializa uma lista privada vazia
"""
Método para inserção
O nome do método para inserção em filas é padronizado: enqueue()
"""
def enqueue(self, val):
self.__data.append(val) # Insere no final da fila
"""
Método para retirada
O nome do método de retirada em filas também é padronizado: dequeue()
"""
def dequeue(self):
if self.is_empty(): return None
# Retira e retorna o primeiro elemento da fila
return self.__data.pop(0)
"""
Método para consultar o início da fila (primero elemento), sem retirá-lo
Nome padronizado: peek()
"""
def peek(self):
if self.is_empty(): return None
return self.__data[0]
"""
Método para verificar se a fila está vazia ou não
Retorna True se vazia ou False caso contrário
"""
def is_empty(self):
return len(self.__data) == 0
"""
Método que exibe a fila como uma string (para fins de depuração)
"""
def to_str(self):
string = ""
for el in self.__data:
if string != "": string += ", "
string += str(el)
return "[ " + string + " ]"
############################################################################
fila = Queue() # Cria uma nova fila
print(fila.to_str())
# Adicionando pessoas à fila
fila.enqueue("Marciovaldo")
fila.enqueue("Gildanete")
fila.enqueue("Terencionildo")
fila.enqueue("Junislerton")
fila.enqueue("Ritielaine")
print(fila.to_str())
atendido = fila.dequeue()
print(f"Atendido: {atendido}")
print(fila.to_str())
atendido = fila.dequeue()
print(f"Atendido: {atendido}")
print(fila.to_str())
fila.enqueue("Adenoirton")
print(fila.to_str())
proximo = fila.peek()
print(f"Próximo a ser atendido: {proximo}")
print(fila.to_str())
| false
|
0ef7995dbfc5ffa785a88d5456771876897cdcd0
|
spentaur/DS-Unit-3-Sprint-1-Software-Engineering
|
/sprint/acme_report.py
| 1,610
| 4.125
| 4
|
from random import randint, uniform, choice
from acme import Product
# Useful to use with random.sample to generate names
ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved']
NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???']
def generate_products(num_products=30):
"""Generate random Products
Keyword Arguments:
num_products {int} -- number of products to generate (default: {30})
Returns:
list -- a list of the randomly generated products
"""
products = []
for _ in range(num_products):
name = f"{choice(ADJECTIVES)} {choice(NOUNS)}"
price = randint(5, 100)
weight = randint(5, 100)
flammability = uniform(0.0, 2.5)
products.append(Product(name, price, weight, flammability))
return products
def inventory_report(products):
"""Create a report from a list of Products"""
prices_total = 0
weights_total = 0
flammability_total = 0
product_names = set()
num_of_products = len(products)
for product in products:
prices_total += product.price
weights_total += product.weight
flammability_total += product.flammability
product_names.add(product.name)
print("ACME CORPORATION OFFICIAL INVENTORY REPORT")
print("Unique product names: ", len(product_names))
print("Average price: ", prices_total / num_of_products)
print("Average weight: ", weights_total / num_of_products)
print("Average flammability: ", flammability_total / num_of_products)
if __name__ == '__main__':
inventory_report(generate_products())
| true
|
7202e752d0907a36648cc13282e113689117c0c5
|
j4s1x/crashcourse
|
/Projects/CrashCourse/Names.py
| 572
| 4.125
| 4
|
#store the names of your friends in a list called names.
#print each person's name in the list
#by accessing each element in the list, one at a time
friends = ["you", "don't", "have", "any", "friends"]
print (friends[0])
print (friends[1])
print (friends[2])
print (friends[3])
print (friends[4])
#So that was one long complicated annoying way to type a lot of code
#let's try this way instead it was easier
def FriendList(x):
for i in range(0,5):
print (friends[x])
x += 1
FriendList(0)
#way less complicated. And in a cute little function too :)
| true
|
2a53c61a3b1a235e4721983b872a9785ce3db31f
|
j4s1x/crashcourse
|
/Projects/CrashCourse/slices.py
| 626
| 4.28125
| 4
|
#Print the first three, the middle 3, and the last three of a list using slices.
animals = ['cat', 'dog', 'cow', 'horse', 'sheep', 'chicken', 'goat', 'pig', 'alpaca']
print(animals[:3])
print(animals[3:6])
print(animals[-3:])
#Let's make a copy of that list. One list will be my animals, the other will be a friend's animals
#add a new animal to the friends list but not mine.
buddyAnimals = animals[:]
animals.append('lion')
buddyAnimals.append('Unicorn')
print(animals)
print(buddyAnimals)
#print these lists using a for loop
index = len(animals)-1
print(index)
for i in range(0,index):
print(animals[i], end='*')
| true
|
95574484bf6a54088492ae1e69dd2d5f4babb155
|
j4s1x/crashcourse
|
/Projects/CrashCourse/polling.py
| 669
| 4.40625
| 4
|
# make a list of people who should take the favorite languages poll
#Include some names in the dictionary and some that aren't
#loop through the list of people who should take the poll
#if they have taken it, personally thank them
#elif tell them to take the poll
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
friends = ['john cleese', 'terry gilliam', 'michael palin', 'jen', 'sarah', 'edward', 'phil']
for name in friends:
if name in favorite_languages:
print (name.title() + ' has taken the poll. Thank you very much')
elif name not in favorite_languages:
print(name.title() + ' needs to take the poll!')
| true
|
e80dbd61d099540b05ef8366e859cb4c66c7ca6a
|
j4s1x/crashcourse
|
/Projects/CrashCourse/rivers.py
| 643
| 4.65625
| 5
|
#list rivers and the provinces they run through. Use a loop to print this out.
#Also print the river and provinces individually
rivers = {
'MacKenzie River': 'Northwest Territories',
'Yukon River': 'British Columbia',
'Saint Lawrence River': 'Ontario',
'Nelson River': 'Manitoba',
'Saskatchewan River': 'Saskatchewan',
}
for river, province in rivers.items():
print('The ' + river + ' flows through ' + province)
print('The following is the list of rivers from the dictionary:')
for river in rivers:
print(river)
print('The following is the list of provinces from the dictionary')
for province in rivers.values():
print(province)
| true
|
602ded7ccd367e8a8f1fe3e3cdc389eb932a0ced
|
Gaskill/Python-Practice
|
/Spirit.py
| 662
| 4.21875
| 4
|
#find your spirit animal
animals = ["Horse", "Pig", "Kangaroo", "Whale", "Pony", "Lobster", "Chicken", "Seahorse", "Wolf", "Bat", "Tiger", "Lion", "Pufferfish", "Swan", "Bear", "Pigeon", "Salamander", "Iguana", "Lizard", "Bee", "Crow", "Beetle", "Ant", "Elk", "Deer", "Jellyfish", "Fly", "Parrot", "Hamster", "Cow"]
print("Find your spirit animal!")
print(len(animals)) #prints number of animals in list
choice = input("Pick a number 1 though 30.") #gathers player's input
choice_int = int(choice)-1 #matches the number picked with an index from the list
print(choice) #prints the number they chose
print("Your spirit animal is a(n) %s!" %(animals[choice_int]))
| true
|
57c1a5bbbc88a39ea0eefcba6f54fcc39a1ff57f
|
saranguruprasath/Python
|
/Python_Classes.py
| 501
| 4.1875
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 14 22:27:09 2018
@author: saran
"""
class Circle():
pi = 3.14
def __init__(self,radius=1):
self.radius = radius
self.area = radius * radius * Circle.pi
def get_circumference(self):
return 2 * self.pi * self.radius
my_circle = Circle()
my_circle1 = Circle(12)
print(my_circle.area)
print(my_circle.get_circumference())
print("\n"*2)
print(my_circle1.area)
print(my_circle1.get_circumference())
| false
|
abb1c338ea69227d8e257f6a3a5de62e54b5d06c
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/barb_matthews/lesson2/series.py
| 1,809
| 4.28125
| 4
|
## Lesson 2, Exercise 2.4 Fibonnaci Series
## By: B. Matthews
## 9/11/2020
def fibonacci(n):
#"""Generates a Fibonnaci series with length n"""
if (n == 0):
return 0
elif (n == 1):
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
def lucas(n):
#"""Generates a Lucas series with length n"""
if (n == 0):
return 2
elif (n == 1):
return 1
else:
return lucas(n-1) + lucas(n-2)
def sum_series (n, a=0, b=1):
#"""Generates a series with first two numbers that user specifies"""
if (n == 0):
return a
elif (n == 1):
return b
else:
return sum_series(n-1, a, b) + sum_series(n-2, a, b)
##Test the function
#n = int(input("Enter a number >> "))
#for i in range (n+1):
#print (lucas(i))
#print ("Fibonacci:", n,"th value is: ", fibonacci(n))#
#print ("Lucas series: ", lucas(n))
##Test using the assert template
if __name__ == "__main__":
# run some tests
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(4) == 3
assert fibonacci(5) == 5
assert fibonacci(6) == 8
assert fibonacci(7) == 13
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(4) == 7
# test that sum_series matches fibonacci
assert sum_series(5) == fibonacci(5)
assert sum_series(7, 0, 1) == fibonacci(7)
# test if sum_series matched lucas
assert sum_series(5, 2, 1) == lucas(5)
# test if sum_series works for arbitrary initial values
assert sum_series(0, 3, 2) == 3
assert sum_series(1, 3, 2) == 2
assert sum_series(2, 3, 2) == 5
assert sum_series(3, 3, 2) == 7
assert sum_series(4, 3, 2) == 12
assert sum_series(5, 3, 2) == 19
print("Tests passed!")
| false
|
919274fb66cad43bd13214839b8bc7cd8b2ba625
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/Steven/lesson08/circle_class.py
| 2,445
| 4.5
| 4
|
#!/usr/bin/env python3
"""
The goal is to create a class that represents a simple circle.
A Circle can be defined by either specifying the radius or the diameter, and the user can query the circle for either its radius or diameter.
Other abilities of a Circle instance:
Compute the circle’s area.
Print the circle and get something nice.
Be able to add two circles together.
Be able to compare two circles to see which is bigger.
Be able to compare to see if they are are equal.
(follows from above) be able to put them in a list and sort them.
"""
import math
class Circle():
# Circle object with a given radius
def __init__(self, radius):
self.radius = radius
@property
def get_diameter(self):
return self.radius * 2
@get_diameter.setter
def get_diameter(self, value):
self.radius = value / 2
@property
def get_area(self):
return math.pi * self.radius ** 2
@get_area.setter
def get_area(self, value):
raise AttributeError
@classmethod
def from_diameter(cls, value):
return cls(value / 2)
# For printing out
def __str__(self):
return f"Circle with a radius of: {self.radius}, Diameter of: {self.get_diameter}"
def __repr__(self):
return f"Circle({self.radius})"
# Numeric protocols
def __add__(self, other):
return Circle(self.radius + other.radius)
def __mul__(self, other):
return Circle(self.radius * other)
def __lt__(self, other):
return self.radius < other.radius
def __le__(self, other):
return self.radius <= other.radius
def __gt__(self, other):
return self.radius > other.radius
def __ge__(self, other):
return self.radius >= other.radius
def __ne__(self, other):
return self.radius != other.radius
def __eq__(self, other):
return self.radius == other.radius
class Sphere(Circle):
# Override the Circle str method
def __str__(self):
return f"Sphere with a radius of: {self.radius}, Diameter of: {self.get_diameter}"
# Override the Circle repr method
def __repr__(self):
return f"Sphere({self.radius})"
@property
def volume(self):
return (4 / 3) * math.pi * self.radius ** 3 # Formula for volume of a sphere
@property
def get_area(self):
return 4 * math.pi * self.radius ** 2 # Formula for the surface area of a sphere
| true
|
b302b5c46666bc07835e9d4e115b1b59c0f9e043
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/franjaku/Lesson_2/grid_printer.py
| 1,311
| 4.4375
| 4
|
#!/Lesson 2 grid printer
def print_grid(grid_dimensions=2,cell_size=4):
"""
Print a square grid.
Keyword Arguments
grid_dimensions -- number of rows/columns (default=2)
cell_size -- size of the cell (default=4)
Both of the arguments must be interger values. If a non-integer value
is input it will be truncated after the decimal point.
For instance:
1.5 -> 1
2.359 -> 2
5.0 -> 5
"""
grid_dimensions = int(grid_dimensions)
cell_size = int(cell_size)
Building_line1 = ('+ ' + '- '*cell_size)*grid_dimensions + '+'
Building_line2 = ('| ' + ' '*cell_size)*grid_dimensions + '|'
for x in range(grid_dimensions):
print(Building_line1)
for y in range(cell_size):
print(Building_line2)
print(Building_line1)
return 1
if (__name__ == '__main__'):
print('==========================')
print('Grid Printer Exercise 1')
print('Showing ouput for: print_grid()')
print_grid()
print('==========================')
print('Grid Printer Exercise 2')
print('Showing ouput for: print_grid(cell_size=8)')
print_grid(cell_size=8)
print('==========================')
print('Grid Printer Exercise 3')
print('Showing ouput for: print_grid(5,3)')
print_grid(5,3)
| true
|
a89dce9f76910fbacb0cfbe8b2ffab5b861a85bd
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/cbrown/Lesson 2/grid_printer.py
| 577
| 4.25
| 4
|
#Grid Printer Excercise Lesson 2
def print_grid(x,y):
'''
Prints grid with x blocks, and y units for each box
'''
#get shapes
plus = '+'
minus = '-'
bar = '|'
#minus sign sequence
minus_sequence = y * minus
grid_line = plus + minus_sequence
#Create bar pattern
bar_sequence = bar + ' ' * y
#Print out Grid
for i in range(x):
print(grid_line * x, end = plus)
for i in range(y):
print('\n',bar_sequence * x, end = bar)
print()
print(grid_line * x, end = plus)
print_grid(5,3)
| true
|
4eb0fd45ed58ab5e57d6dba2518fab2cc325b46a
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/kyle_lehning/Lesson04/book_trigram.py
| 2,987
| 4.3125
| 4
|
# !/usr/bin/env python3
import random
import re
import os
def build_trigrams(all_words):
"""
build up the trigrams dict from the list of words
returns a dict with:
keys: word pairs
values: list of followers
"""
trigrams = {}
for idx, word in enumerate(all_words[:-2]):
word_pair = word + " " + all_words[idx + 1]
trigrams.setdefault(word_pair, [])
trigrams[word_pair].append(all_words[idx + 2])
return trigrams
def read_in_data(f_name):
"""
read all text from Gutenburg book
returns a string with all the words from the book
"""
file_text = ""
with open(f_name, "r") as file:
for line in file:
file_text += line.lower()
updated_text = remove_punctuation(file_text)
return updated_text
def remove_punctuation(p_string):
"""
take an input string and remove punctuation, leaving in-word - and '
"""
# (\b[-']\b) is a regular expression that captures intra-word ' and - in group(1)
# the \b states that it is within a word, not at the end
# |[\W_] is negated alpha num, same as [^a-zA-Z0-9], so captures all non alpha
p = re.compile(r"(\b[-']\b)|[\W_]")
# in the sub function check if it is captured in group(1) and if so restore it, else replace punctuation with " "
updated_text = p.sub(lambda m: (m.group(1) if m.group(1) else " "), p_string)
return updated_text
def make_words(input_string):
"""
break a string of words into a list
returns an ordered list of all words.
"""
all_words = input_string.split()
return all_words
def build_text(pairs):
"""
take a dictionary trigram and make a story
returns a string story.
"""
first_key = random.choice(list(pairs.keys()))
list_of_words = first_key.split()
desired_sentence_length = random.randint(15, 20) # Randomize how long to make the sentence
sentence_length = 0
while True:
current_key = list_of_words[-2:]
current_key_string = " ".join(map(str, current_key))
if current_key_string in pairs.keys():
next_word = random.choice(pairs[current_key_string])
list_of_words.append(next_word)
sentence_length += 1
else:
break
if sentence_length == desired_sentence_length:
break
list_of_words[0] = list_of_words[0].capitalize() # Make first letter capital
list_with_cap = ["I" if x == "i" else x for x in list_of_words] # Make I capital
return (" ".join(list_with_cap)) + "."
if __name__ == "__main__":
filename = (input("Enter the path of your file: ")).replace(r'"', '') # remove quotes if copy as path used
if os.path.exists(filename):
in_data = read_in_data(filename)
words = make_words(in_data)
word_pairs = build_trigrams(words)
new_text = build_text(word_pairs)
print(new_text)
else:
print("I did not find the file at, "+str(filename))
| true
|
d962d3b9a9df195b320e91bd054e9ea78aaf56c6
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/grant_dowell/Lesson_08/test_circle.py
| 1,390
| 4.125
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 9 20:13:36 2020
@author: travel_laptop
"""
import math
import unittest as ut
from circle import *
def test_properties():
c = Circle(10)
assert c.radius == 10
assert c.diameter == 20
print(c.area)
assert c.area == math.pi * 100
c.diameter = 6
assert c.radius == 3
def test_diameter_init():
c = Circle.from_diameter(8)
assert c.radius == 4
def test_print():
c = Circle(6)
print(c)
assert str(c) == 'Circle with radius: 6.000000'
assert repr(c) == "Circle(6.00)"
def test_math():
c1 = Circle(2)
c2 = Circle(4)
c3 = c1 + c2
print(c3)
assert c3.radius == 6
c4 = c1 * 3
print(c4)
assert c4.radius == 6
def test_compares():
c1 = Circle(2)
c2 = Circle(4)
assert (c1 > c2) is False
assert c1 < c2
assert (c1 == c2) is False
c3 = Circle(4)
assert c2 == c3
def test_sort():
circles = [Circle(6), Circle(7), Circle(2), Circle(1)]
sorted_circles = [Circle(1), Circle(2), Circle(6), Circle(7)]
circles.sort()
assert circles == sorted_circles
def test_sphere_volume():
s = Sphere(2)
assert s.volume == 4/3 * math.pi * 8
def test_sphere_print():
s = Sphere(6)
print(s)
assert str(s) == 'Sphere with radius: 6.000000'
assert repr(s) == "Sphere(6.00)"
| false
|
01a438810a58c2b072b8a6823796408cf91bcb44
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/chelsea_nayan/lesson02/fizzbuzz.py
| 793
| 4.5
| 4
|
# chelsea_nayan, UWPCE PYTHON210, Lesson02:Fizz Buzz Exercise
# This function prints the numbers from low to high inclusive. For multiples of three, "Fizz" is printed instead of the numer and for multiples of five, "Buzz" is printed. If the number both divisble by three and five, it prints out "FizzBuzz"
def fizzbuzz(low, high): # Parameters takes in the range of numbers to print that users can change
i = low
while i <= high: # This while loop goes through from low to high
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0 and i % 5 != 0:
print("Fizz")
elif i % 5 == 0 and i % 3 != 0:
print("Buzz")
else:
print(i)
i += 1
#The example given in the lesson page
fizzbuzz(1,100)
| true
|
60c4c7cebe6342a7735d5633ec26ea31b4adc1c3
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/thomas_sulgrove/lesson02/series.py
| 1,899
| 4.28125
| 4
|
#!/usr/bin/env python3
"""
a template for the series assignment
#updated with finished code 7/29/2019 T.S.
"""
def fibonacci(n):
series = [0,1] #Define the base series values in a list
while len(series) < n + 1: #add one so normalize lenth and index number
series.append(sum(series[-2:])) #Add last two variables and append to list
return series[n] #return the nth value
def lucas(n):
series = [2,1] #Define the base series values in a list
while len(series) < n + 1: #add one so normalize lenth and index number
series.append(sum(series[-2:])) #Add the variables and append on to the list
return series[n] #return the nth value
def sum_series(n, n0=0, n1=1): #default values are for fibonacci sequence
series = [n0, n1] #Define the base series values in a list
while len(series) < n + 1: #add one so normalize lenth and index number
series.append(sum(series[-2:])) #Add the variables and append on to the list
return series[n] #return the nth value
if __name__ == "__main__":
# run some tests
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(4) == 3
assert fibonacci(5) == 5
assert fibonacci(6) == 8
assert fibonacci(7) == 13
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(4) == 7
# test that sum_series matches fibonacci
assert sum_series(5) == fibonacci(5)
assert sum_series(7, 0, 1) == fibonacci(7)
# test if sum_series matched lucas
assert sum_series(5, 2, 1) == lucas(5)
# test if sum_series works for arbitrary initial values
assert sum_series(0, 3, 2) == 3
assert sum_series(1, 3, 2) == 2
assert sum_series(2, 3, 2) == 5
assert sum_series(3, 3, 2) == 7
assert sum_series(4, 3, 2) == 12
assert sum_series(5, 3, 2) == 19
print("tests passed")
| true
|
19db572f1e6e1304d43b83ed2cde9ca0845ef36c
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/jason_jenkins/lesson04/dict_lab.py
| 1,895
| 4.25
| 4
|
#!/usr/bin/env python3
"""
Lesson 4: dict lab
Course: UW PY210
Author: Jason Jenkins
"""
def dictionaries_1(d):
tmp_d = d.copy()
print("\nTesting dictionaries_1")
tmp_d = dict(name="Chris", city="Seattle", cake="Chocolate")
print(tmp_d)
tmp_d.pop('city')
print(tmp_d)
tmp_d.update({'fruit': 'Mango'})
print(tmp_d)
print("Keys: ", end='')
for v in tmp_d.keys():
print(v, end=', ')
print()
print("Values: ", end='')
for v in tmp_d.values():
print(v, end=', ')
print()
print(f"Cake is in dictionary: {'cake' in tmp_d.keys()}")
print(f"Mango is in dictionary: {'Mango' in tmp_d.values()}")
def dictionaries_2(d):
tmp_d = d.copy()
print("\nTesting dictionaries_2")
for k, v in tmp_d.items():
tmp_d[k] = v.lower().count('t')
print(tmp_d)
def sets_1():
print("\nTesting sets_1")
s2 = set()
s3 = set()
s4 = set()
for i in range(21):
if(i % 2 == 0):
s2.update({i})
if(i % 3 == 0):
s3.update({i})
if(i % 4 == 0):
s4.update({i})
print(f"Set_2 = {s2}")
print(f"Set_3 = {s3}")
print(f"Set_4 = {s4}")
print(f"Set 3 is a subset of Set 2: {s3.issubset(s2)}")
print(f"Set 4 is a subset of Set 2: {s4.issubset(s2)}")
def sets_2():
print("\nTesting sets_2")
s_python = set()
for i in "Python":
s_python.update({i})
s_python.update({"i"})
print(s_python)
s_maration_frozen = frozenset({"m", "a", "r", "a", "t", "h", "o", "n"})
print(s_maration_frozen)
print(f"Union: {s_python.union(s_maration_frozen)}")
print(f"Intersection: {s_python.intersection(s_maration_frozen)}")
if __name__ == "__main__":
# Create a list
d = dict(name="Chris", city="Seattle", cake="Chocolate")
dictionaries_1(d)
dictionaries_2(d)
sets_1()
sets_2()
| false
|
ad66a6638692e2db39b565bdd0d495e0663263e5
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/alexander_boone/lesson02/series.py
| 2,193
| 4.21875
| 4
|
def fibonacci(n):
"""Return nth integer in the Fibonacci series starting from index 0."""
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
def lucas(n):
"""Return nth integer in the Lucas series starting from index 0."""
if n == 0:
return 2
elif n == 1:
return 1
else:
return lucas(n - 1) + lucas(n - 2)
def sum_series(n, first_value = 0, second_value = 1):
"""
Return nth integer in a custom series starting from index 0 and parameters for the first and second series values.
Arguments:
first_value = 0; value at index n=0 of series
second_value = 1; value at index n=1 of series
This function provides a generalized version of the Fibonacci and Lucas integer series by allowing the user to
input the first two numbers of the series.
The default values of the first and second values of the series are 0 and 1, respectively, which are the first
two values of the Fibonacci series.
"""
if n == 0:
return first_value
elif n == 1:
return second_value
else:
return sum_series(n - 1, first_value, second_value) + sum_series(n - 2, first_value, second_value)
if __name__ == "__main__":
# run tests on fibonacci and lucas functions
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(4) == 3
assert fibonacci(5) == 5
assert fibonacci(6) == 8
assert fibonacci(7) == 13
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(4) == 7
# test that sum_series matches fibonacci
assert sum_series(5) == fibonacci(5)
assert sum_series(7, 0, 1) == fibonacci(7)
# test if sum_series matched lucas
assert sum_series(5, 2, 1) == lucas(5)
# run tests on sum_series function for arbirtary value inputs
assert sum_series(0, 3, 2) == 3
assert sum_series(1, 3, 2) == 2
assert sum_series(2, 3, 2) == 5
assert sum_series(3, 3, 2) == 7
assert sum_series(4, 3, 2) == 12
assert sum_series(5, 3, 2) == 19
print("tests passed")
| true
|
713775c79a03d7c700411131e7f5db82358fc3cd
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/mitch334/lesson02/grid_printer.py
| 1,796
| 4.53125
| 5
|
# Lesson 02 : Grid Printer Exercise
# Write a function that draws a grid like the following:
#
# + - - - - + - - - - +
# | | |
# | | |
# | | |
# | | |
# + - - - - + - - - - +
# | | |
# | | |
# | | |
# | | |
# + - - - - + - - - - +
# Part 1: Print the simple grid
def print_grid_simple():
plus = '+ - - - - + - - - - +'
pipe = '| | |'
for i in range(2):
print(plus)
for i in range(4):
print(pipe)
print(plus)
# print_grid_simple()
# Part 2: Print the simple grid with a squre input size (n)
def print_grid(n):
grid_size = n//2 # Divide the size by two sections
if n & 1: # Used to set the correct spacing for odd/even n
pipe_space = n
else:
pipe_space = n + 1
# print(n,' | ',grid_size,' | ',pipe_space)
plus = '+' + ' -'*grid_size + ' +' + ' -'*grid_size + ' +'
pipe = '|' + ' '*pipe_space + '|' + ' '*pipe_space + '|'
for i in range(2):
print(plus)
for i in range(grid_size):
print(pipe)
print(plus)
# print_grid(10)
# Part 3: Write a function that draws a similar grid with a specified
# number of rows and columns, and with each cell a given size.
# Example: print_grid2(3,4)
# (three rows, three columns, and each grid cell four “units” in size)
def print_grid2(n,s):
grid_size = s
pipe_space = s*2 + 1
# print(s,' | ',grid_size,' | ',pipe_space)
plus = '+' + (' -'*grid_size + ' +')*n
pipe = '|' + (' '*pipe_space + '|')*n
for i in range(n):
print(plus)
for i in range(grid_size):
print(pipe)
print(plus)
# print_grid2(3,4)
# print_grid2(5,3)
| false
|
d6273747b57f69b222565ccfe94ee5dcfe1e271e
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/nskvarch/Lesson2/grid_printer_part2.py
| 492
| 4.15625
| 4
|
#Part 2 of the grid printer exercise, created by Niels Skvarch
plus = '+'
minus = '-'
pipe = '|'
space = ' '
def print_grid(n):
print(plus, n * minus, plus, n * minus, plus)
for i in range(n):
print(pipe, n * space, pipe, n * space, pipe)
print(plus, n * minus, plus, n * minus, plus)
for i in range(n):
print(pipe, n * space, pipe, n * space, pipe)
print(plus, n * minus, plus, n * minus, plus)
x = int(input("What size grid would you like?: "))
print_grid(x)
| true
|
a7974c7692bd8e6d9105879cb823a173b81a084d
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/Isabella_Kemp/lesson02/series.py
| 2,165
| 4.25
| 4
|
#Isabella Kemp
#Jan-6-20
#Fibonacci Series
'''def fibonacci(n): #First attempt at this logic
fibSeries = [0,1,1]
if n==0:
return 0
if n == 1 or n == 2:
return 1
for x in range (3,n+1):
calc = fibSeries[x-2] + fibSeries[x-1]
fibSeries.append(calc)
print (fibSeries[:]) #prints the entire fib series
return fibSeries[-1] # returns the last value in the series
print (fibonacci(5))'''
#Fibonacci Series computed. Series starts with 0 and 1, the following integer is the
#summation of the previous two.
def fibonacci(n):
if n == 0:
return 0
if n == 1 or n == 2:
return 1
return fibonacci(n-1) + fibonacci(n-2)
#Lucas Numbers. Series starts with 2 at 0 index followed by 1.
def lucas(n):
#lucasSeries = [2,1]
if n == 0:
return 2
if n == 1:
return 1
return lucas(n-1) + lucas(n-2)
#sum series will return fibonacci sequence if no optional parameters are called
#b and c are optional parameters. If 2 and 1 are called for optional parameters
#lucas sequence is called. Other optional parameters gives a new series.
def sum_series(n,b=0,c=1):
if n == 0:
return b
if n == 1:
return c
return sum_series(n-1, b, c) + sum_series(n-2, b, c)
#Tests
if __name__ == "__main__":
# run some tests
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(4) == 3
assert fibonacci(5) == 5
assert fibonacci(6) == 8
assert fibonacci(7) == 13
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(4) == 7
# test that sum_series matches fibonacci
assert sum_series(5) == fibonacci(5)
assert sum_series(7, 0, 1) == fibonacci(7)
# test if sum_series matched lucas
assert sum_series(5, 2, 1) == lucas(5)
# test if sum_series works for arbitrary initial values
assert sum_series(0, 3, 2) == 3
assert sum_series(1, 3, 2) == 2
assert sum_series(2, 3, 2) == 5
assert sum_series(3, 3, 2) == 7
assert sum_series(4, 3, 2) == 12
assert sum_series(5, 3, 2) == 19
print("tests passed")
| true
|
17ff33d3d3f30f91fad231d74de4869231456302
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/anthony_mckeever/lesson8/assignment_1/sphere.py
| 1,218
| 4.40625
| 4
|
"""
Programming In Python - Lesson 8 Assignment 1: Spheres
Code Poet: Anthony McKeever
Start Date: 09/06/2019
End Date: 09/06/2019
"""
import math
from circle import Circle
class Sphere(Circle):
"""
An object representing a Sphere.
"""
def __init__(self, radius):
"""
Initializes a Sphere object
:self: The class
:radius: The desired radius of the Sphere.
"""
super().__init__(radius)
@classmethod
def from_diameter(self, diameter):
"""
Instantiates a Sphere from a diameter value.
:self: The class
:diameter: The desired diameter of the Sphere.
"""
return super().from_diameter(diameter)
@property
def volume(self):
"""
Return the sphere's volume.
Formula: 4/3 * pi * r^3
"""
return (4 / 3) * math.pi * (self.radius ** 3)
@property
def area(self):
"""
Return the sphere's area
Formula: 4 * pi * r^2
"""
return 4 * math.pi * (self.radius ** 2)
def __str__(self):
return f"Sphere with radius: {self.radius}"
def __repr__(self):
return f"Sphere({self.radius})"
| true
|
7034f87f03b0321c6ebcb22c789ff62b8a3a028e
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/david_baylor/lesson3/Mail_Room_part1.py
| 2,002
| 4.21875
| 4
|
#!/usr/bin/env python3
"""
Mail_room_part1.py
By David Baylor on 12/3/19
uses python 3
Automates writing an email to thank people for their donations.
"""
def main():
data = [["bill", 100, 2, 50],["john",75, 3, 25]]
while True:
choice = input("""
What would you like to do?
1) Send a Thank You
2) Create a Report
3) Quit
""")
if choice == "1":
data = send_thank_you(data)
elif choice == "2":
creat_report(data)
elif choice == "3":
break
def send_thank_you(data):
name = input("Enter a full name or type 'list' to vew current list: ")
if name.upper() == "LIST":
for i in range(len(data)):
print(data[i][0].capitalize())
return data
else:
for i in range(len(data)):
if name.upper() == data[i][0].upper():
print("This personn has alredy donated add another donation under their name.")
donation = float(input(f"How much did {name.capitalize()} donate: $"))
data[i][1] += donation
data[i][2] += 1
data[i][3] = data[i][1]/data[i][2]
write_email(name, donation)
return data
donation = float(input(f"How much did {name.capitalize()} donate: $"))
data += [[name, donation, 1, donation]]
write_email(name, donation)
return data
def creat_report(data):
print("""
Donor Name | Total Given | Num Gifts | Average Gift
--------------------------|-------------|-----------|-------------""")
for i in range(len(data)):
make_row(data[i][0].capitalize(), data[i][1], data[i][2], data[i][3])
def make_row(name, total, num_gift, ave_gift):
print("{:26}|${:12}|{:11}|${:12}".format(name, total, num_gift, ave_gift))
def write_email(name, donation):
print("Here is the email:")
print(f"""
Dear {name.capitalize()},
Thank you for your generous donnation of ${donation}.""")
main()
| false
|
34c3ad9f2aaaa6e83e863724cb3a7fd5c03318e6
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/roslyn_m/lesson07/Lesson07_Notes.py
| 1,632
| 4.28125
| 4
|
class Employee:
num_of_emps = 0
raise_amt = 1.04
def __init__(self, first, last, pay): # "self" refers to automatically taking in the instance
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'Employee', 60000)
# 2 ways to call fullname:
emp_1.fullname()
Employee.fullname(emp_1)
# Class Variables: variables that are shared among all instances of a class
# while instance variables can be unique for each instance like our names and email and pay
# class variables should be the same for each instance
print(Employee.__dict__)
print(emp_1.__dict__)
Employee.raise_amt = 1.04 # can set raise amount by class
emp_1.raise_amt = 1.09 # can set it for one instance specifically
# Now call properties, and you will see emp_1 has raise amt
print(Employee.__dict__)
print(emp_1.__dict__)
print(Employee.raise_amt)
print(emp_1.raise_amt)
print(emp_2.raise_amt)
# class method vs Static methods
# When working with classes..... reg methods pass instance as the first argument, class methods automatically pass class as first.
# static method dont pass anything (no class or instance). Behave just like reg functions, but we include thm in our classes because they pertian to class
# If you dont access instance or the class, it should prob be an @staticmethod
print(vars(emp_1)) #gives attributes of an instance
| true
|
d299bb80ff5ce871c90f7d5e2733e8e93482d5d1
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/becky_larson/lesson03/3.1slicingLab.py
| 2,622
| 4.1875
| 4
|
#!/usr/bin/env python """
"""Exchange first and last values in the list and return"""
"""learned that using = sign, they refer to same object, so used copy."""
""" Could also use list command"""
"""tuple assert failing: RETURNING: (32, (54, 13, 12, 5, 32), 2). """
""" How to remove the parans"""
"""Is there a way to use same code for both string and tuple?"""
def exchange_first_last(seq):
if(type(seq)) == str:
a_new_sequence = seq[len(seq)-1] + seq[1:(len(seq)-1)] + seq[0]
else:
a_new_sequence = []
a_new_sequence.append(seq[len(seq)-1])
a_new_sequence.extend(seq[1:(len(seq)-1)])
a_new_sequence.append(seq[0])
print("RETURNING: ", a_new_sequence)
return tuple(a_new_sequence)
def remove_everyother(seq):
a_new_sequence = seq[::2]
print("RETURNING: ", a_new_sequence)
return a_new_sequence
def remove_1stLast4_everyother(seq):
a_new_sequence = seq[4:-4:2]
print("RETURNING: ", a_new_sequence)
return a_new_sequence
def elements_reversed(seq):
a_new_sequence = seq[::-1]
print("RETURNING: ", a_new_sequence)
return a_new_sequence
def each_third(seq):
thirds = len(seq)/3
start1 = 0
end1 = int(thirds)
start2 = int(thirds)
end2 = int(thirds*2)
start3 = int(thirds*2)
end3 = int(thirds*3)
str1 = seq[start1:end1]
str2 = seq[start2:end2]
str3 = seq[start3:end3]
a_new_sequence = str3 + str1 + str2
print("RETURNING: ", a_new_sequence)
return a_new_sequence
def run_assert():
# print("run_assert")
# assert exchange_first_last(a_string) == "ghis is a strint"
# print("string passed")
# assert exchange_first_last(a_tuple) == (32, 54, 13, 12, 5, 2)
# print("tuple passed")
# assert remove_everyother(a_string) == "ti sasrn"
# print("string passed")
# assert remove_everyother(a_tuple) == (2, 13, 5)
# print("tuple passed")
# assert remove_1stLast4_everyother(a_string) == " sas"
# print("string passed")
# assert remove_1stLast4_everyother(a_tuple) == ()
# print("tuple passed")
# assert elements_reversed(a_string) == "gnirts a si siht"
# print("string passed")
# assert elements_reversed(a_tuple) == (32, 5, 12, 13, 54, 2)
# print("tuple passed")
assert each_third(a_string15) == "strinthis is a "
print("string passed")
assert each_third(a_tuple) == (5, 32, 2, 54, 13, 12)
print("tuple passed")
a_string15 = "this is a strin"
a_string = "this is a string"
a_tuple = (2, 54, 13, 12, 5, 32)
if __name__ == "__main__":
run_assert()
# each_third(a_tuple)
| true
|
05fe0c6cd5a9136f7c94df7bcbba087e851793ea
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/josh_embury/lesson02/fizzbuzz.py
| 574
| 4.15625
| 4
|
#--------------------------------------------------------------#
# Title: Lesson 2, FizzBuzz
# Description: Print the words "Fizz" and "Buzz"
# ChangeLog (Who,When,What):
# JEmbury, 9/18/2020, created new script
#--------------------------------------------------------------#
for i in range (1,101):
if i%3==0 and i%5==0: # check if divisible by 3 and 5
print("FizzBuzz")
elif i%3==0: # check if divisible by 3
print("Fizz")
elif i%5==0: # check if divisible by 5
print("Buzz")
else:
print(str(i)) # else print current number
| false
|
c28354828f26d6285ac455873abbe17ca68c0d2a
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/andrew_garcia/lesson_02/series.py
| 2,455
| 4.21875
| 4
|
'''
Andrew Garcia
Fibonacci Sequence
6/9/19
'''
def fibonacci(n):
""" Computes the 'n'th value in the fibonacci sequence, starting with 0 index """
number = [0, 1] # numbers to add together
if n == 0:
return(number[0])
elif n == 1:
return(number[1])
else:
for item in range(n - 1): # subtracts 1 to account for 0 index
fib = number[0] + number[1]
number.append(fib)
number.pop(0)
return(number[1])
def lucas(n):
""" Computes the 'n'th value in the lucas sequence, starting with 0 index """
number = [2, 1] # numbers to add together
if n == 0:
return(number[0])
elif n == 1:
return(number[1])
else:
for item in range(n - 1): # subtracts 1 to account for 0 index
fib = number[0] + number[1]
number.append(fib)
number.pop(0)
return(number[1])
def sum_series(n, zeroth=0, first=1):
"""
Computes the 'n'th value in a given series
:param zeroth=0: Creates the first value to use in a series
:param first=1: Creates the second value to use in a series
If the two parameters are left blank, or are filled in 0 and 1, it will start the fibonacci sequence
If the two parameters are filled in 2 and 1, it will start the lucas sequence
If the two parameters are filled in with two random numbers, it will create its own sequence
"""
number = [zeroth, first] # numbers to add together
if n == 0:
return(number[0])
elif n == 1:
return(number[1])
else:
for item in range(n - 1): # subtracts 1 to account for 0 index
fib = number[0] + number[1]
number.append(fib)
number.pop(0)
return(number[1])
if __name__ == "__main__":
# Tests if Fibonacci is working
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(2) == 1
assert fibonacci(5) == 5
assert fibonacci(9) == 34
print('Fibonacci Working')
# Tests if lucas is working
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(2) == 3
assert lucas(5) == 11
assert lucas(9) == 76
print('Lucas Working')
# Tests random sequences
assert sum_series(0) == 0
assert sum_series(1, 0, 1) == 1
assert sum_series(0, 2, 1) == 2
assert sum_series(4, 2, 3) == 13
assert sum_series(1, 5, 7) == 7
print('Series Working')
| true
|
b159c6b75befa81b3fecd3a208d6ad2f4bbcb873
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/lee_deitesfeld/lesson03/strformat_lab.py
| 2,058
| 4.21875
| 4
|
#Task One - Write a format string that will take a tuple and turn it into 'file_002 : 123.46, 1.00e+04, 1.23e+04'
nums = 'file_%03d : %.2f, %.2E, %.2E' % (2, 123.4567, 10000, 12345.67)
print(nums)
#Task Two
def f_string(name, color, ice_cream):
'''Takes three arguments and inserts them into a format string'''
favorite = f"My name is {name}. My favorite color is {color}, and my favorite ice cream flavor is {ice_cream}."
print(favorite)
#Task Three
def formatter(seq):
'''Writes a function that displays "The __ numbers are: __, __, etc" '''
length = len(seq)
print(("The {} numbers are: " + ", ".join(["{}"] * length)).format(length, *seq))
#Task Four
def num_pad(seq):
'''Converts (4, 30, 2017, 2, 27) to "02 27 2017 04 30" '''
lst = []
#return nums in sequence padded with zeroes
for num in seq:
lst.append(f'{num:02}')
#convert list to string with no commas
first_str = (' '.join(lst))
first = first_str[0:6]
middle = first_str[6:11]
last = first_str[11:]
#print final string
print(last + ' ' + middle + first)
#Task Five - Display 'The weight of an orange is 1.3 and the weight of a lemon is 1.1'
fruits = ['oranges', 1.3, 'lemons', 1.1]
f_str = f'The weight of an {(fruits[0])[:-1]} is {fruits[1]} and the weight of a {(fruits[2])[:-1]} is {fruits[3]}.'
print(f_str)
#Then, display the names of the fruit in upper case, and the weight 20% higher
f_str_bonus = f'The weight of an {((fruits[0])[:-1]).upper()} is {fruits[1]*1.2} and the weight of a {((fruits[2])[:-1]).upper()} is {fruits[3]*1.2}.'
print(f_str_bonus)
#Task Six - print a table of several rows, each with a name, an age and a cost
for line in [["Name", "Age", "Cost"], ["Lee", 33, "$56.99"], ["Bob", 62, "$560.99"], ["Harry", 105, "$5600.99"], ["Jeanne", 99, "$56099.99"]]:
print('{:>8} {:>8} {:>8}'.format(*line))
#Then, given a tuple with 10 consecutive numbers, print the tuple in columns that are 5 charaters wide
tup = (1,2,3,4,5,6,7,8,9,10)
for x in tup:
print('{:>5}'.format(x), end= " ")
| true
|
f5546f8ee7b79dfa119e2e08e76bdc0bf5494789
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/Kollii/lesson04/dict_lab.py
| 1,951
| 4.21875
| 4
|
#!/usr/bin/env python3
# Lesson 4 - DictLab
# DICTIONARY 1
dict1 = {
'name': 'Chris',
'city': 'Seattle',
'cake': 'Chocolate',
}
print(" This is original Dictionary \n")
print(dict1)
print("\nCake Element removed from Dictionary")
print(dict1.pop("cake"))
print('\n fruit = Mango added added to Dictionary')
dict1['fruit'] = 'Mango'
print(dict1)
print('\n Display the dictionary keys.')
for x in dict1:
print(x)
print('\n Display the dictionary values.')
for x in dict1:
print(dict1[x])
print('Is cake in the Dictionay-dict1 ? {}'.format('cake' in dict1.keys()))
print('Is Mango in Dictionay-dict1 ? {}'.format('Mango' in dict1.values()))
####### DICTIONARY 2 ##############
dict2 = {
'name': 'Chris'.count('t'),
'city': 'Seattle'.count('t'),
'cake': 'Chocolate'.count('t'),
}
print('\n Dictionary with the number of ‘t’s in each value as the value \n ')
print(dict2)
# SET 1
s2 = set()
s3 = set()
s4 = set()
for x in range(0,20):
if x%2 == 0:
s2.update([x])
for x in range(0,20):
if x%3 == 0:
s3.update([x])
for x in range(0,20):
if x%4 == 0:
s4.update([x])
print('\n**** SET- s2 ******')
print("s2 contains numbers from zero through twenty, divisible by 2 {} ", s2)
print('\n**** SET- s3 ******')
print("s2 contains numbers from zero through twenty, divisible by 3 {} ", s3)
print('\n**** SET- s4 ******')
print("s2 contains numbers from zero through twenty, divisible by 4 {} ", s4)
print('\nis s3 is a subset of s2 ---', s3.issubset(s2))
print('\nis s4 is a subset of s2 ---', s4.issubset(s2))
# SET 2
set_str = {'P','y','t','h','o','n'}
set_str.add('i')
set_frz = frozenset(['m','a','r','a','t','h','o','n'])
print('\n******* UNION OF set PHYTHON and frozenset MARATHON ***********')
print(set_str.union(set_frz))
print('\n******* INTERSECTION OF set PHYTHON and frozenset MARATHON ***********')
print(set_str.intersection(set_frz))
| false
|
3bc82c02bc4a26db706f0cbcf4a772b96ede820a
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/adam_strong/lesson03/list_lab.py
| 1,715
| 4.25
| 4
|
#!/usr/bin/env python3
##Lists##
fruits = ['Apples', 'Pears', 'Oranges', 'Peaches']
fruits_original = fruits[:]
## Series 1 ##
print('')
print('Begin Series 1')
print('')
print(fruits)
response1 = input("Please add another fruit to my fruit list > ")
fruits.append(response1)
print(fruits)
response2 = input("Type a number and I will return that fruit's number")
#response2 = int(response2)
print('Fruit number: ', response2, ' ', fruits[int(response2)-1])
response3 = input("Please add another fruit to the beginning of my fruit list > ")
fruits = [response3] + fruits
print(fruits)
response4 = input("Please add another fruit to the beginning of my fruit list > ")
fruits.insert(0, response4)
print(fruits)
print('All the fruits that begin with "P"')
for fruit in fruits:
if fruit[0] == "P":
print(fruit)
##Series 2 ##
print('')
print('Begin Series 2')
print('')
print(fruits)
fruits = fruits[:-1]
print(fruits)
response5 = input("Please type a fruit to remove from the list > ")
fruits.remove(response5)
print(fruits)
##Series 3
print('')
print('Begin Series 3')
print('')
fruits2 = fruits[:]
for fruit in fruits:
while True:
yn = input("Do you like " + fruit.lower() + '?. Type yes or no.')
if yn == 'no':
fruits2.remove(fruit)
break
elif yn == 'yes':
break
else:
input("Please type only yes or no in response.")
print(fruits2)
##Series 4 ##
print('')
print('Begin Series 4')
print('')
fruits_backwards = []
for fruit in fruits_original:
fruits_backwards.append(fruit[::-1])
fruits_original_minus = fruits_original[:-1]
print(fruits_backwards)
print(fruits_original)
print(fruits_original_minus)
| true
|
01e6e518fe93f0e2b8df5b26d563fd39960de252
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/pkoleyni/lesson04/trigram.py
| 1,811
| 4.21875
| 4
|
#!/usr/bin/env python3
import sys
import random
def make_list_of_words(line):
"""
This function remove punctuations from a string using translate()
Then split that string and return a list of words
:param line: is a string of big text
:return: List of words
"""
replace_reference = {ord('-'): ' ', ord(','): '', ord(','): '', ord('.'): '', ord(')'): '', ord('('): '', ord ('"'): ''}
line = line.translate(replace_reference)
words = line.split()
return words
def read_file (file_name):
big_line = []
with open(file_name, 'r') as f:
for line in f:
big_line.append(line)
return big_line
def build_trigrams(words):
"""
Buit a trigram dictionary
:param words:
:return:
"""
word_pairs = dict()
for i in range(len(words) - 2):
pair = tuple(words[i:i + 2])
follower = words[i + 2]
if pair not in word_pairs:
word_pairs[pair] = [follower]
else:
word_pairs[pair].append(follower)
return word_pairs
def new_text(trigrams_dic):
a_list = []
l = len(trigrams_dic.keys())
for i in range(10):
random_number = random.randint(0,l)
key = list(trigrams_dic.keys())[random_number]
a_list.append(" ".join(list(key)))
a_list.append(" ".join(trigrams_dic[key]))
return (" ".join(a_list))
if __name__ == "__main__":
try:
filename = sys.argv[1]
except IndexError:
print("You must pass in a filename")
sys.exit(1)
file_content = read_file (filename)
list_of_words = make_list_of_words(" ".join(file_content))
# list_of_words = make_list_of_words(" ".join(read_file('sherlock_small.txt.py')))
trigrams = build_trigrams(list_of_words)
print(new_text(trigrams))
| true
|
abfaf78910cf739ebcc1e3a3d9ed8b5945672bb1
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/joli-u/lesson04/dict_lab.py
| 2,312
| 4.4375
| 4
|
#!/usr/bin/env python
"""
dictionaries 1
"""
print("-----DICTIONARIES 2-----\n")
# create dictionary
_dict = {'name': 'Chris',
'city': 'Seattle',
'cake': 'Chocolate'}
_dict1 = _dict.copy()
# display dictionary
print("display dictionary: {}".format(_dict1))
# delete the "cake" entry
_dict1.pop('cake')
# display the dictionary
print("delete cake entry: {}".format(_dict1))
# add "fruit entry"
_dict1['fruit'] = 'Mango'
# display the dictionary
print("add fruit:mango entry: {}".format(_dict1))
# display the dictionary keys; values
print(_dict1.keys())
print(_dict1.values())
# determine whether 'cake' and 'Mango' is in the dictionary
print("is cake a key?: ", end="")
print('cake' in _dict1.keys())
print("is mango a value?: ", end="")
print('Mango' in _dict1.values())
"""
dictionaries 2
"""
print("\n\n-----DICTIONARIES 2-----\n")
_dict2 = {}
# make dictionary with keys from _dict except with the values being number of t's in original
for k,v in _dict.items():
_key = k
_value = (v.lower()).count('t')
_dict2[_key] = _value
print("display dictionary: {}".format(_dict2))
"""
sets 1
"""
print("\n\n-----SETS 1-----\n")
# create inital set with numbers from 0 to 20
s1 = set(range(21))
# create sets that contain numbers that are divisible by 2,3,4
s2 = set()
s3 = set()
s4 = set()
for item in s1:
if (item%2) == 0:
s2.update([item])
if (item%3) == 0:
s3.update([item])
if (item%4) == 0:
s4.update([item])
# display the sets
print("s1={}\ns2={}\ns3={}\ns4={}".format(s1,s2,s3,s4))
# display if s() is a subset of s2
print("is s3 a subset of s2?: ",end='')
print(s3.issubset(s2))
print("is s4 a subset of s2?: ",end='')
print(s4.issubset(s2))
"""
sets 2
"""
print("\n\n-----SETS 2-----\n")
# create set with letters in 'python'
_set2 = set()
_str1 = []
_str1.extend('python')
_set2.update(_str1)
print("set={}".format(_set2))
# add 'i' to the set
_set2.update('i')
print("set={}".format(_set2))
# create frozen set with letters in 'marathon'
_str2 = []
_str2.extend('marathon')
_fset = frozenset(_str2)
print(_fset)
# display the union and intersection of the two sets
_union = _set2.union(_fset)
print("union={}".format(_union))
_intsct = _set2.intersection(_fset)
print("intersection={}".format(_intsct))
| false
|
565b617a8b5c9d9fd86bc346abee60266b04092d
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/thecthaeh/Lesson08/circle_class.py
| 2,228
| 4.46875
| 4
|
#!/usr/bin/env python3
import math
import functools
""" A circle class that can be queried for its:
radius
diameter
area
You can also print the circle, add 2 circles together, compare the size of 2 circles (which is bigger
or are they equal), and list and sort circles.
"""
@functools.total_ordering
class Circle:
radius = 0
def __init__(self, radius):
self.radius = radius
@property
def diameter(self):
_diameter = self.radius * 2
return _diameter
@diameter.setter
def diameter(self, value):
self._diameter = value
self.radius = round((self._diameter / 2), 2)
@property
def area(self):
_area = (math.pi * (math.pow(self.radius, 2)))
return round(_area, 2)
@classmethod
def from_diameter(cls, diam_value):
cls.diameter = diam_value
cls.radius = round((cls.diameter / 2), 2)
return cls
def __str__(self):
return f"Circle with radius: {self.radius}"
def __repr__(self):
return f"Circle({self.radius})"
def __add__(self, other):
"""
add two circle objects together
"""
new_radius = self.radius + other.radius
return Circle(new_radius)
def __mul__(self, other):
"""
multiply a circle object by a number
"""
return Circle(self.radius * other)
def __rmul__(self, other):
return self.__mul__(other)
def __eq__(self, other):
return self.radius == other.radius
def __lt__(self, other):
return self.radius < other.radius
def sort_key(self):
return self.radius
class Sphere(Circle):
def __str__(self):
return f"Sphere with radius: {self.radius}"
def __repr__(self):
return f"Sphere({self.radius})"
@property
def volume(self):
_volume = ((4/3) * math.pi * (math.pow(self.radius, 3)))
return round(_volume, 2)
@property
def area(self):
"""
Calculate the surface area of a sphere
"""
_area = (4 * math.pi * (math.pow(self.radius, 2)))
return round(_area, 2)
| true
|
4d73c1447d9ec48e3ea9cb14fe30db9b890d7386
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/Shweta/Lesson08/circle.py
| 1,505
| 4.3125
| 4
|
#!/usr/bin/env python
#circel program assignment for lesson08
import math
class Circle(object):
def __init__(self,radius):
self.radius=radius
# self._radius=radius
@classmethod
def from_diameter(cls,_diameter):
#self=cls()
radius = _diameter/ 2
return cls(radius)
@property
def diameter(self):
#self.diameter=self.radius*2
diameter=self.radius*2
return diameter
@diameter.setter
def diameter(self,value):
self.radius = value / 2
#return value
@property
def area(self):
area=(self.radius ** 2)*math.pi
return area
def __str__(self):
return "Circle with radius:" + str(self.radius)
def __repr__(self):
return f"'{self.__class__.__name__}({self.radius})'"
def __add__(self,other):
return Circle(self.radius + other.radius)
def __mul__(self,other):
return Circle(self.radius * other)
def __lt__(self,other):
return (self.radius < other.radius)
def __eq__(self,other):
return(self.radius == other.radius)
class Sphere(Circle):
def __str__(self):
return "Sphere radius {} and diameter is {}".format(self.radius,self.diameter)
def __repr__(self):
return "Sphere()".format(self.radius)
@property
def area(self):
return (self.radius ** 2) * math.pi * 4
@property
def volume(self):
return (self.radius ** 3) *math.pi * (4/3)
| false
|
8b7b1831a6a0649a23ba3028d1c3fec8f93528b6
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/will_chang/lesson04/dict_lab.py
| 2,145
| 4.15625
| 4
|
# Dictionaries 1
print("Dictionaries 1\n--------------\n")
dict_1 = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'}
print(dict_1)
print("\nThe entry for cake was removed from the dictionary.")
dict_1.pop('cake')
print(dict_1)
print("\nAn entry for fruit was added to the dictionary.")
dict_1['fruit'] = 'Mango'
print("\nHere are the dictionary's current keys:")
print(dict_1.keys())
print("\nHere are the dictionary's current values:")
print(dict_1.values())
print("\nCheck if 'cake' is a key in the dictionary: {}".format('cake' in dict_1.keys()))
print("\nCheck if 'Mango' is a value in the dictionary: {}".format('Mango' in dict_1.values()))
# Dictionaries 2
print("\n\nDictionaries 2\n--------------\n")
print("Here's the dictionary from Dictionaries 1:")
print(dict_1)
dict_2 = dict_1.copy()
for key in dict_2:
dict_2[key] = dict_2[key].lower().count('t')
print("\nThis is a new dictionary with the same keys from dictionary 1 but with the number of 't's in each value as the corresponding dictionary 1 value:")
print(dict_2)
# Sets 1
print("\n\nSets 1\n------\n")
s2 = set(range(0, 21, 2))
s3 = set(range(0, 21, 3))
s4 = set(range(0, 21, 4))
print("Here is a set s2 containing numbers from 0 - 20 that are divisble by 2:\n{}".format(s2))
print("\nHere is a set s3 containing numbers from 0 - 20 that are divisble by 3:\n{}".format(s3))
print("\nHere is a set s4 containing numbers from 0 - 20 that are divisble by 4:\n{}".format(s4))
print("\nCheck if s3 is a subset of s2: {}".format(s3.issubset(s2)))
print("\nCheck if s4 is a subset of s2: {}".format(s4.issubset(s2)))
# Sets 1
print("\n\nSets 2\n------\n")
s_python = set(['P','y','t','h','o','n'])
s_python.add('i')
print("This is a set with the letters in 'Python' with 'i' added:\n{}".format(s_python))
fs_marathon = frozenset(['m', 'a', 'r', 't', 'h', 'o', 'n'])
print("\nThis is a frozenset with the letters in 'marathon':\n{}".format(fs_marathon))
print("\nThis is the union of the set and frozenset:\n{}".format(s_python.union(fs_marathon)))
print("\nThis is the intersection of the set and frozenset:\n{}".format(s_python.intersection(fs_marathon)))
| true
|
55f48aff0bc258783bf6e1cf91b4668bf5e7b3de
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/scott_bromley/lesson03/strformat_lab.py
| 2,725
| 4.40625
| 4
|
#!/usr/bin/env python3
# string formatting exercises
def main():
print(task_one())
print(task_two())
print(formatter((2, 3, 5, 7, 9))) #task three
print(task_four())
task_five()
task_six()
def task_one(file_tuple=None):
'''
given a tuple, produce a specific string using string formatting
:return: formatted string
'''
if file_tuple is None:
file_tuple = (2, 123.4567, 10000, 12345.67)
return "file_{:03d} : {:.2f}, {:.2e}, {:.2e}".format(file_tuple[0], file_tuple[1], file_tuple[2], file_tuple[3])
def task_two(file_tuple=None):
'''
given a tuple, produce a specific string using string formatting
:return: f-string
'''
if file_tuple is None:
file_tuple = (2, 123.4567, 10000, 12345.67)
return f"file_{file_tuple[0]:03} : {file_tuple[1]:{8}.{5}}, {file_tuple[2]:.2e}, {file_tuple[3]:.2e}"
def formatter(in_tuple):
'''
dynamically build format string to reflect tuple size in output
:return: formatted string
'''
l = len(in_tuple)
# return ("the {} numbers are: " + ", ".join(["{}"] * l)).format(l, *in_tuple)
return f"the {l} numbers are: {', '.join(str(num) for num in in_tuple)}"
def task_four(file_tuple=None):
'''
use index numbers from tuple to specify positions in print formatting
:return: f-string
'''
if file_tuple is None:
file_tuple = (4, 30, 2017, 2, 27)
return f"{file_tuple[3]:02} {file_tuple[4]} {file_tuple[2]} {file_tuple[0]:02} {file_tuple[1]}"
def task_five():
'''
create f-string that displays "The weight of an orange is 1.3 and the weight of a lemon is 1.1" from a provided list
:return: None
'''
fruit_weight = ['oranges', 1.3, 'lemons', 1.1]
print(f"The weight of an {fruit_weight[0][:-1]} is {fruit_weight[1]} and the weight of a {fruit_weight[2][:-1]} is {fruit_weight[3]}")
print(f"The weight of an {fruit_weight[0][:-1].upper()} is {fruit_weight[1] * 1.2} and the weight of a {fruit_weight[2][:-1].upper()} is {fruit_weight[3] * 1.2}")
return None
def task_six():
'''
print a table of several rows, each with a name, an age and a cost
:return: None
'''
scotch = ["Glenmorangie", "Balvenie Single Malt", "Macallan Lalique", "Glenfiddich", "Ardbeg"]
ages = ["18 years", "50 years", "62 years", "30 years", "10 years"]
price = ["$130.00", "$50,000.00", "$47,285.00", "$799.00", "$90.00"]
print(f"SCOTCH:{'':<30}AGE:{'':<20}PRICE:{'':>20}")
for scotch, age, price in zip(scotch, ages, price):
print(f"{scotch:<30}{age:^20}{price:>17}")
return None
if __name__ == "__main__":
print("Running", __file__)
main()
else:
print("Running %s as imported module", __file__)
| false
|
3ce552c36077599974fada702350f2e1cae0fc14
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/mattcasari/lesson08/assignments/circle_class.py
| 2,916
| 4.46875
| 4
|
#!/usr/bin/env python3
""" Lesson 8, Excercise 1
@author: Matt Casari
Link: https://uwpce-pythoncert.github.io/PythonCertDevel/exercises/circle_class.html
Description:
Creating circle class and a sphere sub-class
"""
import math
class Circle(object):
# @classmethod
def __init__(self, the_radius=0):
self.radius = the_radius
@classmethod
def from_diameter(cls, diameter):
return cls(diameter/2.0)
@property
def radius(self):
return self._radius
@radius.setter
def radius(self,radius):
self._radius = radius
@property
def diameter(self):
return self._radius *2.0
@diameter.setter
def diameter(self,diameter):
self._radius = diameter/2.0
@property
def area(self):
return self._radius*2.0*math.pi
def __str__(self):
return f"Circle with radius: {self.radius:.6f}"
def __repr__(self):
return f"Circle({self.radius})"
def __add__(self, other):
return Circle(self.radius + other.radius)
def __mul__(self, other):
if isinstance(other, int):
return Circle(self.radius * other)
elif isinstance(other, Circle):
return Circle(self.radius * other.radius)
else:
raise TypeError("Invalid operator")
def __rmul__(self, other):
if isinstance(other, int):
return Circle(self.radius * other)
elif isinstance(other, Circle):
return Circle(self.radius * other.radius)
else:
raise TypeError("Invalid operator")
def __gt__(self, other):
return self.radius > other.radius
def __lt__(self, other):
return self.radius < other.radius
def __eq__(self, other):
if isinstance(other, int):
return self.radius == other
elif isinstance(other, Circle):
return self.radius == other.radius
else:
raise TypeError("Invalid Operator")
def __iadd__(self, other):
if isinstance(other, int):
self.radius = self.radius + other
elif isinstance(other, Circle):
self.radius = self.radius + other.radius
else:
raise TypeError("Invalid Operator")
return self.radius
def __imult__(self, other):
if isinstance(other, int):
self.radius = self.radius * other
elif isinstance(other, Circle):
self.radius = self.radius * other.radius
else:
raise TypeError("Invalid Operator")
return self.radius
class Sphere(Circle):
@property
def area(self):
raise NotImplementedError
@property
def volume(self):
return 4/3 * math.pi * (self.radius**3)
def __str__(self):
return f"Sphere with radius: {self.radius}"
def __repr__(self):
return f"Sphere({self.radius})"
| false
|
b6a265e4836602f5165692a2bbbf1b090d038203
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/kimc05/Lesson03/strformat_lab.py
| 2,138
| 4.1875
| 4
|
#Christine Kim
#Python210 Lesson 3 String Formatting Lab Exercise
#Task One
#Given tuple
t1_tuple = (2, 123.4567, 10000, 12345.67)
#d for decimal integer, f for floating point, e for exponent notation, g for significant digits
t1_str = "file_{:03d} : {:.2f}, {:.2e}, {:.3g}".format(t1_tuple[0], t1_tuple[1], t1_tuple[2], t1_tuple[3])
#Verify result
print(t1_str)
#Task Two
t2_tuple = t1_tuple
t2_str = f"file_{t2_tuple[0]:03d} : {t2_tuple[1]:.2f}, {t2_tuple[2]:.2e}, {t2_tuple[3]:.3g}"
print(t2_str)
#Task Three
t3 = (2, 3, 5, 7, 9)
#Dynamic format build up method
def formatter(in_t):
#Accept only tuple
if type(in_t) == tuple:
#State the length of the numbers
form_string = f"the {len(in_t)} numbers are: "
#Perform action for every number in tuple
for num in in_t:
#add in format to base string
form_string += "{:d}, "
#return completed string after removing the last ', '
return form_string.format(*in_t)[:-2]
#Request new tuple
else:
print("Please verify your tuple.")
#Verify result
print(formatter(t3))
#Task Four
#Given tuple
t4 = (4, 30, 2017, 2, 27)
#Rearragned, position specified by index
#Option 1
Rearragned = "{:02d} " * len(t4)
print(Rearragned.format(t4[3],t4[4], t4[2], t4[0], t4[1]))
#Optoin 2
print(f"{t4[3]:02d} {t4[4]:d} {t4[2]:02d} {t4[0]:02d} {t4[1]:d}")
#Question: Which option is better?
#Task Five
list5 = ["oranges", 1.3, "lemons", 1.1]
#First print statement
print(f"The weight of an {list5[0][:-1]} is {list5[1]:.1f} and the weight of a {list5[2][:-1]} is {list5[3]:.1f}")
#Modified with 1.2 times weight and capitalized name
print(f"The weight of an {list5[0].upper()[:-1]} is {1.2 * list5[1]:.1f} and the weight of a {list5[2].upper()[:-1]} is {1.2 * list5[3]:.1f}")
#Task Six
#Write a table
fluff = [["Hammy", 9, "$35"], ["Teeny", 8, "$12"], ["Teeny2", 8, "$12"], ["Tiny", 8, "$15"], ["Jumbo", 6, "$75"], ["Jumbo Junior", 3, "$45"]]
for cute in fluff:
print("{:^12}{:^3}{:^3}".format(*cute))
#Write a column
t6 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
#Bonus
print(("{:>5}"*len(t6)).format(*t6))
| false
|
d49ab47b15ea9d4d3033fc86dc627cdc019444a9
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/brgalloway/Lesson_5/except_exercise.py
| 1,268
| 4.15625
| 4
|
#!/usr/bin/python
"""
An exercise in playing with Exceptions.
Make lots of try/except blocks for fun and profit.
Make sure to catch specifically the error you find, rather than all errors.
"""
from except_test import fun, more_fun, last_fun
# Figure out what the exception is, catch it and while still
# in that catch block, try again with the second item in the list
first_try = ['spam', 'cheese', 'mr death']
try:
# spam triggers Nameerror since s is not defined
joke = fun(first_try[0])
except NameError:
# calling fun again with cheese yields expected results
joke = fun(first_try[1])
# Here is a try/except block. Add an else that prints not_joke
try:
# fun runs and assisngs value to not_joke
not_joke = fun(first_try[2])
except SyntaxError:
print('Run Away!')
else:
# printing the returned value after
# running fun with third element in first_try
print(not_joke)
#
langs = ['java', 'c', 'python']
try:
# java triggers the IndexError
# since test is only 3 elements long
more_joke = more_fun(langs[0])
except IndexError:
# after indexerror more_fun runs with c
more_joke = more_fun(langs[1])
else:
print("index error")
finally:
# then finally running the last function
last_fun()
| true
|
3559a141a2d051c4f05936aeafcb177da8921195
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/Kollii/lesson03/strformat_lab.py
| 2,531
| 4.15625
| 4
|
# Task One
"""a format string that will take the following four element tuple:
( 2, 123.4567, 10000, 12345.67)
and produce:
'file_002 : 123.46, 1.00e+04, 1.23e+04'
"""
print("## Task One ##\n")
string = (2, 123.4567, 10000, 12345.67)
print("A string: ", string)
formated_str = "file_{:03d} : {:10.2f}, {:.2e}, {:.3g}".format(2, 123.4567, 10000, 12345.67)
print("Fromated string: ", formated_str)
# Task Two
print("\n## Task Two ##\n")
#alternative method to achieve task one
print("alternate type of format string\n")
print(f"file_{string[0]:0>3d} : {string[1]:.2f}, {string[2]:.2e}, {string[3]:.3e}")
# Task Three
print("\n## Task Three ##\n")
print("Dynamically Building up format strings\n")
def formatter(in_tuple):
count = len(in_tuple)
str_output = ('the {} numbers are: ' +
', '.join(['{:d}'] * count)).format(count,*in_tuple)
return str_output
tuple1= (2,3,5)
tuple2 = (2,3,5,7,9)
print(formatter(tuple1))
print(formatter(tuple2 ))
# Task Four
print("\n## Task Four ##\n")
# given a 5 element tuple ( 4, 30, 2017, 2, 27)
# use string formating to print: '02 27 2017 04 30'
tuple4 = (4, 30, 2017, 2, 27)
print("{3:0>2d} {4:0} {2:0} {0:0>2d} {1:0}".format(*tuple4))
# Task Five
print("\n## Task Five ##\n")
# Here’s a task : Given the following four element list: ['oranges', 1.3, 'lemons', 1.1]
# Write an f-string that will display: The weight of an orange is 1.3 and the weight of a lemon is 1.1
list1 = ['oranges', 1.3, 'lemons', 1.1]
print("f-string: ", f'The weight of an {list1[0][:-1]} is {list1[1]} and the weight of a {list1[2][:-1]} is {list1[3]}')
print("change the f-string so that it displays the names of the fruit in upper case, and the weight 20% higher (that is 1.2 times higher)")
print(f'The weight of an {list1[0].upper()[:-1]} is {list1[1] * 1.2} '
f'and the weight of a {list1[2].upper()[:-1]} is {list1[3] * 1.2}')
# Task Six
print("\n## Task Six ##\n")
print(" print a table of several rows, each with a name, an age and a cost ")
tuple6 = list()
tuple6.append(("Abc", 25, 12345))
tuple6.append(("Xyzh", 35, 4567))
tuple6.append(("Pqrst", 45, 6789))
tuple6.append(("Mnopsdf", 15, 2345))
for t in tuple6:
print('{:10}{:5}{:15.{d}f}'.format(*t, d=2))
#extra task: given a tuple with 10 consecutive numbers, print tuple in columns that are 5 char wide
tuple_extra = (1,2,3,4,5,6,7,8,9,10)
print("given a tuple with 10 consecutive numbers, print tuple in columns that are 5 char wide")
print(('{:{wide}}'*10).format(*tuple_extra, wide=5))
| false
|
ea194097dee6ee3c57267d60835892c923316f6d
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/Steven/lesson04/trigrams.py
| 1,998
| 4.34375
| 4
|
#! bin/user/env python3
import random
words = "I wish I may I wish I might".split() # a list
filename = r"C:\Users\smar8\PycharmProjects\Python210\lesson04\sherlock_small.txt"
def build_trigrams(words):
trigrams = {}
# build up the dict here!
for word in range(len(words)-2): # stops with the last two words in the list
pair = (words[word], words[word+1]) # Pair of words stored in a tuple
follower = words[word+2] # set the 3 word
trigrams.setdefault(pair, []).append(follower)
# print(trigrams)
return trigrams
# creating the words list from a file
def make_words(file):
with open(file, 'r') as fh:
# for line in fh:
text = fh.read()
punc = ('.', ',', '!', '?', '-', "'", '(', ')')
for word in text:
if word in punc:
text = text.replace(word, ' ') # remove punctuation from the file
text = text.split()
# print(text)
return text
def build_text(db, n): # params of word list and number of words to read
book = ""
key = random.choice(list(db.keys())) # select a random key from the sequence
temp = list(key)
for number in range(n):
nextWord = (db[key][random.randint(0, (len(db[key]) - 1))]) # select the value of the key pair from a random number based on the length of the keys of input seq
temp.append(nextWord)
key = tuple(temp[-2:])
story = " ".join(temp) # combine all the words
story = story.split(".") # Split each line when there is a period
for item in story:
book += (item[0].capitalize() + item[1:] + ".") # Make each sentence start with a capital letter and end with a period
return book
if __name__ == "__main__":
filename = r"C:\Users\smar8\PycharmProjects\Python210\lesson04\sherlock_small.txt"
n = 10 # number of key pairs of words to read from the file
words = make_words(filename)
trigrams = build_trigrams(words)
new_text = build_text(trigrams, n)
print(new_text)
| true
|
0c47d864adfe1e2821609c2d4d3e1b312790127f
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/steve-long/lesson02-basic-functions/ex-2-2-fizzBuzz/fizzBuzz.py
| 2,557
| 4.21875
| 4
|
#!/usr/bin/env python3
# ========================================================================================
# Python210 | Fall 2020
# ----------------------------------------------------------------------------------------
# Lesson02
# Fizz Buzz Exercise (fizzBuzz.py)
# Steve Long 2020-09-19 | v0
#
# Requirements:
# -------------
# Write a program that prints the numbers from 1 to 100 inclusive.
# But for multiples of three print "Fizz" instead of the number.
# For the multiples of five print "Buzz" instead of the number.
# For numbers which are multiples of both three and five print "FizzBuzz" instead.
#
# Implementation:
# ---------------
# fizzBuzz([<start>[,<end>]])
#
# Script Usage:
# -------------
# python fizzBuzz.py [<start> [<end>]]
# <start> ::= Starting number (see function fizzBuzz for details.)
# <end> ::= Ending number (see function fizzBuzz for details.)
#
# History:
# --------
# 000/2020-09-20/sal/Created.
# ========================================================================================
import sys
def fizzBuzz(start = 1, end = 100):
"""
fizzBuzz([<start>[,<end>]])
--------------------------------------------------------------------------------------
For non-negative int values from <start> to <end>, print the following:
* "Fizz" for multiples of 3
* "Buzz" for multiples of 5
* "FizzBuzz" for multiples of 3 and 5
* The number for all other values
Entry: <start> ::= Starting int value (default is 1).
<end> ::= Ending int value (default is 100).
Exit: Returns True.
"""
for n in range(start, (end + 1)):
s = ("FizzBuzz" if (((n % 3) == 0) and ((n % 5) == 0)) else \
("Fizz" if ((n % 3) == 0) else \
("Buzz" if ((n % 5) == 0) else n)))
print(s)
return True
# Command-line interface for demonstrating function fizzBuzz.
if __name__ == "__main__":
args = sys.argv
argCount = (len(args) - 1)
if (argCount == 2):
#
# Execute validated 2-argument scenario.
#
if (args[1].isnumeric() and args[2].isnumeric()):
fizzBuzz(int(args[1]), int(args[2]))
else:
if (not args[1].isnumeric()):
print("fizzBuzz (ERROR): Invalid start argument ({})".format(args[1]))
if (not args[2].isnumeric()):
print("fizzBuzz (ERROR): Invalid end argument ({})".format(args[2]))
elif (argCount == 1):
#
# Execute validated 1-argument scenario.
#
if (args[1].isnumeric()):
fizzBuzz(int(args[1]))
else:
print("fizzBuzz (ERROR): Invalid start argument ({})".format(args[1]))
else:
#
# Execute validated 0-argument scenario.
#
fizzBuzz()
| true
|
c65f36c96fb3e5f1579b165fb4e52c28bf5efa82
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/Isabella_Kemp/lesson03/list_lab.py
| 2,349
| 4.46875
| 4
|
# Isabella Kemp
# 1/19/2020
# list lab
# Series 1
# Create a list that displays Apples, Pears, Oranges, Peaches and display the list.
List = ["Apples", "Pears", "Oranges", "Peaches"]
print(List)
# Ask user for another fruit, and add it to the end of the list
Question = input("Would you like another fruit? Add it here: ")
if Question not in List:
List.append(Question)
print(List)
# Asks user for a number, and displays the number as well as the fruit corresponding
# to the number.
List = ["Apples", "Pears", "Oranges", "Peaches"]
num = int(input("Please enter a number: "))
print(num)
if num < len(List):
print(List[num - 1])
# Adds new fruit (Strawberries) to the beginning of the original fruit list, using +.
new_list = ["Strawberries"] + List
print(new_list)
# Adds new fruit (Strawberries) to beginning of List using insert()
List = ["Apples", "Pears", "Oranges", "Peaches"]
List.insert(0, "Strawberries")
print(List)
# Display all fruits that begin with "P" using a for loop
List = ["Apples", "Pears", "Oranges", "Peaches"]
for fruit in List:
if "P" in fruit[0]:
print(fruit)
# Series 2
# Display the List
List = ["Apples", "Pears", "Oranges", "Peaches"]
print(List)
# Removes last fruit in the list
List.pop()
print(List)
# Deletes the fruit the user wants you to delete
delete_fruit = input("Which fruit would you like to delete? ")
for fruit in List:
if delete_fruit == fruit:
List.remove(delete_fruit)
break # exits loop
print(List)
# Series 3
# Asks the user what fruit they like, and if they say no it deletes the fruit,
# if neither, it will continue to ask. Puts fruits to lower case.
List = ["Apples", "Pears", "Oranges", "Peaches"]
def find_fav_fruits(List):
for fruit in List:
ask_user = input("Do you like " + fruit.lower() + "? yes/no?")
if ask_user.lower() == "no":
List.remove(fruit)
elif ask_user.lower() == "yes":
continue
else:
ask_user = input("Please enter yes or no.")
print(List)
find_fav_fruits(List)
# Series 4
# Creates a new list with the contents of the original, but all letters in each item reversed.
List = ["Apples", "Pears", "Oranges", "Peaches"]
new_list = [fruit[::-1] for fruit in List][::-1]
print(new_list)
print("Deletes last item of the original list")
List.pop()
print(List)
| true
|
bc1fe51df6dabcadf392317ac91e359f7e565e48
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/kimc05/Lesson08/circle.py
| 1,443
| 4.4375
| 4
|
"""
Christine Kim
Lesson 8
Assignment Circles
"""
import math
class Circle():
#initiate circle with radius
def __init__(self, radius):
self.radius = radius
def __str__(self):
return "Circle with radius: {}".format(self.radius)
def __repr__(self):
return "Circle({})".format(self.radius)
def __add__(self, other):
return Circle(self.radius + other.radius)
def __mul__(self, other):
return Circle(self.radius * other)
def __radd__(self, other):
return self.__add__(other)
def __lt__(self, other):
return (self.radius, self.diameter, self.area) < (other.radius, other.diameter, other.area)
def __eq__(self, other):
return (self.radius, self.diameter, self.area) == (other.radius, other.diameter, other.area)
def __le__(self, other):
return (self.radius, self.diameter, self.area) <= (other.radius, other.diameter, other.area)
def __rmul__(self, other):
return Circle(self.radius * other)
def __truediv__(self, other):
return Circle(self.radius / other.radius)
@property
def diameter(self):
return self.radius * 2
@diameter.setter
def diameter(self, diameter):
self.radius = diameter / 2
@property
def area(self):
return math.pi * (self.radius ** 2)
@classmethod
def from_diameter(c, diameter):
self = c(diameter / 2)
return self
| false
|
f2b721313e23b99aea53565563efd9b5373e0883
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/karl_perez/lesson03/list_lab.py
| 2,968
| 4.25
| 4
|
#!/usr/bin/env python3
"""Series 1"""
#Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches”.
list_original = ['Apples', 'Pears', 'Oranges', 'Peaches']
series1 = list_original[:]
#Display the list (plain old print() is fine…).
print(series1)
#Ask the user for another fruit and add it to the end of the list.
user = input('Add another fruit please:\n')
series1.append(user)
#Display the list.
print(series1)
#Ask the user for a number and display the number back to the user and the fruit corresponding to that number (on a 1-is-first basis). Remember that Python uses zero-based indexing, so you will need to correct.
num = input('Please give a number. ')
integ_num = int(num)
print(integ_num, series1[integ_num-1])
#Add another fruit to the beginning of the list using “+” and display the list.
series1 = ['Grapes'] + series1
print(series1)
#Add another fruit to the beginning of the list using insert() and display the list.
series1.insert(0,'Bananas')
print(series1)
#Display all the fruits that begin with “P”, using a for loop.
fruits_p = []
for i in series1:
if i[0] == 'P':
fruits_p.append(i)
print("Display all the fruits that begin with 'P': {}".format(fruits_p))
"""Series 2"""
#Display the list.
print(list_original)
series2 = list_original[:]
#Remove the last fruit from the list.
series2.pop()
#Display the list.
print(series2)
#Ask the user for a fruit to delete, find it and delete it.
user_1 = input("Pick a fruit to remove please: ")
if user_1 not in series2:
print("Please choose a fruit from the list.")
else:
series2.remove(user_1)
print(series2)
#(Bonus: Multiply the list times two. Keep asking until a match is found. Once found, delete all occurrences.)
series2 = series2 * 2
print("multipling the list by 2:")
print(series2)
user_2 = input("Enter another fruit to remove please: ")
while user_2 in series2:
series2.remove(user_2)
print(series2)
# """Series 3"""
series3 = list_original[:]
#Ask the user for input displaying a line like “Do you like apples?” for each fruit in the list (making the fruit all lowercase).
for fruits in series3[:]:
user_3 = input("Do you like" + " " + fruits + "?\n")
#For each “no”, delete that fruit from the list.
if user_3 == 'no':
series3.remove(fruits)
elif user_3 == 'yes':
continue
#For any answer that is not “yes” or “no”, prompt the user to answer with one of those two values
else:
print("Please answer with either 'yes' or 'no'")
#Display the list.
print(series3)
"""Series 4"""
series4 = list_original[:]
new_series_list = []
#Make a new list with the contents of the original, but with all the letters in each item reversed.
for fruit in series4:
new_series_list.append(fruit[::-1])
print(new_series_list)
#Delete the last item of the original list.
del list_original[-1]
#Display the original list and the copy.
print(list_original)
| true
|
b0cdb8c87c76f5f383b473fb57aadb72d3399e06
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/csimmons/lesson02/series.py
| 2,274
| 4.46875
| 4
|
#!/usr/bin/env python3
# Craig Simmons
# Python 210
# series.py - Lesson02 - Fibonacci Exercises
# Created 11/13/2020 - csimmons
# Modified 11/14/2020 - csimmmons
def sum_series(n,first=0,second=1):
""" Compute the nth value of a summation series.
:param first=0: value of zeroth element in the series
:param second=1: value of first element in the series
This function should generalize the fibonacci() and the lucas(),
so that this function works for any first two numbers for a sum series.
Once generalized that way, sum_series(n, 0, 1) should be equivalent to fibonacci(n).
And sum_series(n, 2, 1) should be equivalent to lucas(n).
sum_series(n, 3, 2) should generate another series with no specific name
The defaults are set to 0, 1, so if you don't pass in any values, you'll
get the fibonacci sercies
"""
if n == 0:
return(first)
elif n == 1:
return(second)
else:
return sum_series(n-2,first,second) + sum_series(n-1,first,second)
pass
def fibonacci(n):
""" Compute the nth Fibonacci number """
return sum_series(n)
pass
def lucas(n):
""" Compute the nth Lucas number """
return sum_series(n,2,1)
pass
if __name__ == "__main__":
# run some tests
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(4) == 3
assert fibonacci(5) == 5
assert fibonacci(6) == 8
assert fibonacci(7) == 13
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(2) == 3
assert lucas(3) == 4
assert lucas(4) == 7
assert lucas(5) == 11
assert lucas(6) == 18
assert lucas(7) == 29
# test that sum_series matches fibonacci
assert sum_series(5) == fibonacci(5)
assert sum_series(7, 0, 1) == fibonacci(7)
# test if sum_series matched lucas
assert sum_series(5, 2, 1) == lucas(5)
assert sum_series(7, 2, 1) == lucas(7)
# test if sum_series works for arbitrary initial values
assert sum_series(0, 3, 2) == 3
assert sum_series(1, 3, 2) == 2
assert sum_series(2, 3, 2) == 5
assert sum_series(3, 3, 2) == 7
assert sum_series(4, 3, 2) == 12
assert sum_series(5, 3, 2) == 19
print("All tests passed")
| true
|
4174277a463cf7388a64db50feda0265596121ba
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/andrew_garcia/lesson_02/Grid_Printer_3.py
| 1,306
| 4.21875
| 4
|
'''
Andrew Garcia
Grid Printer 3
6/2/19
'''
def print_grid2(row_column, size):
def horizontal(): # creates horizontal sections
print('\n', end='')
print('+', end='')
for number in range(size): # creates first horizontal side of grid
print(' - ', end='')
print('+', end='')
for number in range(row_column - 1): # selects number of extra columns
for number in range(size): # creates size of grid
print(' - ' , end='')
print('+', end='')
def vertical(): # creates vertical sections
for number in range(size): # creates firstv vertical side of grid
print('\n', end='')
print('|', end='')
print((' ' * size), end='')
print('|', end='')
for number in range(row_column - 1): # selects number of extra rows
print(' ' * size, end='') # creates size of grid
print('|', end='')
def final_grid(): #combines vertical and horizontal sections
for number in range(row_column):
horizontal()
vertical()
horizontal()
final_grid()
row_column, size = int(input("Enter Number of Rows and Columns: ")), int(input("Enter Size of Grid: "))
print_grid2(row_column, size)
| true
|
f6463a3d08dd4150f242193982444722f533bcd7
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/kimc05/Lesson03/List_lab.py
| 2,427
| 4.34375
| 4
|
#!/usr/bin/env python3
#Christine Kim
#Series 1
print("Series 1")
print()
#Create and display a list of fruits
fruits = ["Apples", "Pears", "Oranges", "Peaches"]
print(fruits)
#Request input from user for list addition
fruits.append(input("Input a fruit to add to the list: "))
print(fruits)
#Request input from user for a number and display the number and corresponding fruit
fruit_num = int(input("There are {} fruits in the list. Input a number for a fruit to display: ".format(len(fruits))))
print(str(fruit_num) + ": " + fruits[(fruit_num - 1)])
#Add to the beginning of the list with '+'
fruits = [input("Input a fruit to add to the beginning of the list: ")] + fruits
print(fruits)
#Add to the beginning of the list with 'insert()'
fruits.insert(0, input("Input a fruit to add to the beginning of the list: "))
print(fruits)
#Use a for loop to display all fruits beginning with "P"
print("Displaying all fruits which starts with a 'P': ")
for item in fruits:
if item[0] == "P" or item[0] == "p":
print(item)
#Series 2
print()
print("Series 2")
print()
#Display list
fruits2 = fruits[:]
print(fruits2)
#Remove the last item on the list and display
fruits2.pop()
print(fruits2)
#Request input for fruit to delete
del_fruit = input("Input a fruit to remove from the list: ")
if del_fruit in fruits2:
fruits2.remove(del_fruit)
else:
print("Entry not found.")
#Display updated list
print(fruits2)
#Series 3
print()
print("Series 3")
print()
#Use list from Series 1
fruits3 = fruits[:]
print(fruits3)
#Perform action for every item in the list
sadfruits = []
for item in fruits3:
while True:
#Request user prefrence input
answer = input("Do you like " + item.lower() + "? ")
#Next
if answer == "yes":
break
#mark disliked fruits
elif answer == "no":
sadfruits.append(item)
break
#prompt user for proper entry
else:
print("Please respond in either 'yes' or 'no'")
#Remove disliked fruits
for fruit in sadfruits:
fruits3.remove(fruit)
#Display updated list
print(fruits3)
#Series 4
print()
print("Series 4")
print()
#New list with contents of the original reversed
fruits4 = []
for item in fruits:
item = item[::-1]
fruits4.append(item)
#Delete last item of the original list
fruits4.pop()
#Display original list and the copy
print(fruits)
print(fruits4)
| true
|
47496e40702fa399ae03bc775318aa066a171394
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/steve_walker/lesson01/task2/logic-2_make_bricks.py
| 451
| 4.375
| 4
|
# Logic-2 > make_bricks
# We want to make a row of bricks that is goal inches long. We have a number of
# small bricks (1 inch each) and big bricks (5 inches each). Return True if it
# is possible to make the goal by choosing from the given bricks. This is a
# little harder than it looks and can be done without any loops.
def make_bricks(small, big, goal):
if small + 5*big < goal or small < goal % 5:
return(False)
else:
return(True)
| true
|
7c9c1a235810e9b3b3ed02099b481e6032eb5f54
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/Deniss_Semcovs/Lesson04/trigrams.py
| 728
| 4.125
| 4
|
# creating trigram
words = "I wish I may I wish I might".split()
import random
def build_trigrams(words):
trigrams = {}
for i in range(len(words)-2):
pair = tuple(words[i:i+2])
follower = [words[i+2]]
if pair in trigrams:
trigrams[pair] += follower
else:
trigrams[pair] = follower
return (trigrams)
if __name__=="__main__":
trigrams = build_trigrams(words)
print(trigrams)
# generating random word combinations
first_word = words[0]+" "
sentence = ""
print(first_word+" ".join(trigrams[random.choice(list(trigrams.keys()))]))
for i in trigrams:
sentence += " ".join(trigrams[random.choice(list(trigrams.keys()))])+" "
print(first_word+sentence)
| true
|
5919313d0bec108626f9f9b2ae9761bfa9b2dc24
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/gregdevore/lesson02/series.py
| 2,388
| 4.34375
| 4
|
# Module for Fibonacci series and Lucas numbers
# Also includes function for general summation series (specify first two terms)
def fibonacci(n):
""" Return the nth number in the Fibonacci series (starting from zero index)
Parameters:
n : integer
Number in the Fibonacci series to compute
"""
# Base cases
if n == 0:
return 0
elif n == 1:
return 1
else:
# Recursive case
return fibonacci(n-1) + fibonacci(n-2)
def lucas(n):
""" Return the nth Lucas number (starting from zero index)
Parameters:
n : integer
Lucas number to compute
"""
# Base cases
if n == 0:
return 2
elif n == 1:
return 1
else:
# Recursive case
return lucas(n-1) + lucas(n-2)
def sum_series(n, n0=0, n1=1):
""" Return the nth term in the summation series starting with
the terms n0 and n1. If first two terms are not specified, the
Fibonacci series is printed by default.
Parameters:
n : integer
The number in the summation series to compute
Keyword arguments:
n0 : The first term in the series (default 0)
n1 : The second term in the series (default 1)
"""
# Base cases
if n == 0:
return n0
elif n == 1:
return n1
else:
# Recursive case
return sum_series(n-1, n0, n1) + sum_series(n-2, n0, n1)
if __name__ == "__main__":
# Run some tests
# Fibonacci series
# Assert first 10 terms are correct
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(4) == 3
assert fibonacci(5) == 5
assert fibonacci(6) == 8
assert fibonacci(7) == 13
assert fibonacci(8) == 21
assert fibonacci(9) == 34
# Lucas numbers
# Assert first 10 terms are correct
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(2) == 3
assert lucas(3) == 4
assert lucas(4) == 7
assert lucas(5) == 11
assert lucas(6) == 18
assert lucas(7) == 29
assert lucas(8) == 47
assert lucas(9) == 76
# Sum series
# Make sure defaults are for Fibonacci series
assert sum_series(4) == fibonacci(4)
# Make sure entering Lucas number values generates correct term
assert sum_series(4, 2, 1) == lucas(4)
print("All tests passed")
| true
|
d9a0ff4f9fac9f83291723dfbfd8f010c51e5d3e
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/anthony_mckeever/lesson4/exercise_1/dict_lab.py
| 1,660
| 4.28125
| 4
|
#!/usr/bin/env python3
"""
Programming In Python - Lesson 4 Exercise 1: Dictionary (and Set) Lab
Code Poet: Anthony McKeever
Start Date: 08/05/2019
End Date: 08/05/2019
"""
# Task 1 - Dictionaries 1
print("Task 1 - Dictionaries:")
fun_dictionary = {"name": "Sophia",
"city": "Seattle",
"cake": "Marble"
}
print(fun_dictionary)
fun_dictionary.pop("cake")
print(fun_dictionary)
fun_dictionary.update({"fruit": "Mango"})
print(fun_dictionary.keys())
print(fun_dictionary.values())
has_cake = "cake" in fun_dictionary.keys()
has_mango = "Mango" in fun_dictionary.values()
print("Has Cake:", has_cake)
print("Has Mango:", has_mango)
# Task 2 - Dictionaries 2
print("\n\nTask 2 - Dictionaries 2:")
fun_dictionary2 = {}
for k, v in fun_dictionary.items():
fun_dictionary2.update({k : v.lower().count('t')})
print(fun_dictionary2)
# Task 3 - Sets 1
print("\n\nTask 3 - Sets:")
s2_list = []
s3_list = []
s4_list = []
for i in range(21):
if i % 2 == 0:
s2_list.append(i)
if i % 3 == 0:
s3_list.append(i)
if i % 4 == 0:
s4_list.append(i)
s2 = set(s2_list)
s3 = set(s3_list)
s4 = set(s4_list)
print(s2)
print(s3)
print(s4)
print("s3 is subset of s2:", s3.issubset(s2))
print("s4 is subset of s2:", s4.issubset(s2))
# Task 4 - Sets 2
print("\n\nTask 4 - Sets 2:")
python_set = set(['p', 'y', 't', 'h', 'o', 'n'])
python_set.update('i')
marathon_set = set(["m", "a", "r", "a", "t", "h", "o", "n"])
union_set = python_set.union(marathon_set)
intersect_set = python_set.intersection(marathon_set)
print("Union Set:", union_set)
print("Intersection Set:", intersect_set)
| false
|
a745d05e6a02ef1dcbf8e66aff92ad23dda0e30f
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/jason_jenkins/lesson04/trigrams.py
| 2,038
| 4.3125
| 4
|
#!/usr/bin/env python3
"""
Lesson 4: Trigram assignment
Course: UW PY210
Author: Jason Jenkins
Notes:
- Requires valid input (Error checking not implemented)
- Future iteration should focus on formating input
-- Strip out punctuation?
-- Remove capitalization?
-- Create paragraphs?
"""
import random
import sys
def build_trigram(words):
"""
build up the trigrams dict from the list of words
"""
trigrams = dict()
for i in range(len(words) - 2):
pair = tuple(words[i:i + 2])
follower = words[i + 2]
if(pair in trigrams):
trigrams[pair].append(follower)
else:
trigrams[pair] = [follower]
# build up the dict here!
return trigrams
def make_words(text):
"""
Splits a long string of text into an list of words
"""
return text.split()
def build_text(word_pairs, iterations=100000):
"""
Creates new text from a trigram
"""
text_list = []
# Create the start of the text
first_two = random.choice(list(word_pairs.keys()))
text_list.append(first_two[0])
text_list.append(first_two[1])
text_list.append(random.choice(word_pairs[first_two]))
# Iterate to create a long text stream
for i in range(iterations):
last_two = tuple(text_list[-2:])
if last_two in word_pairs:
text_list.append(random.choice(word_pairs[last_two]))
return " ".join(text_list)
def read_in_data(filename):
"""
Reads in text from a file
"""
try:
with open(filename, 'r') as f:
return f.read()
except FileNotFoundError:
print("File not found")
sys.exit(1)
if __name__ == "__main__":
# get the filename from the command line
try:
filename = sys.argv[1]
except IndexError:
print("You must pass in a valid filename")
sys.exit(1)
in_data = read_in_data(filename)
words = make_words(in_data)
word_pairs = build_trigram(words)
new_text = build_text(word_pairs)
print(new_text)
| true
|
6f5a61cf17281a202ca28d43e110d25235a76334
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/nam_vo/lesson02/fizz_buzz.py
| 445
| 4.1875
| 4
|
# Loop thru each number from 1 to 100
for number in range(1, 101):
# Print "FizzBuzz" for multiples of both three and five
if (number % 3 == 0) and (number % 5 == 0):
print('FizzBuzz')
# Print "Fizz" for multiples of three
elif number % 3 == 0:
print('Fizz')
# Print "Buzz" for multiples of five
elif number % 5 == 0:
print('Buzz')
# Print number otherwise
else:
print(number)
| true
|
0ccb3742f5f6bc680207c82d952d102f7125e36f
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/annguan/lesson02/fizz_buzz.py
| 524
| 4.375
| 4
|
#Lesson 2 Fizz Buzz Exercise
#Run program "FizzBuzz()"
def fizz_buzz():
"""fizz_buzz prints the numbers from 1 to 100 inclusive:
for multiples of three print Fizz;
for multiples of five print Buzz
for numbers which are multiples of both three and Five, print FizzBuzz
"""
for i in range (1,101):
if i % 3 == 0 and i % 5 ==0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
| true
|
dfded6161f67b76fac8ff7fd0893496e81e4f4c4
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/lisa_ferrier/lesson05/comprehension_lab.py
| 1,532
| 4.53125
| 5
|
#!/usr/bin/env python
# comprehension_lab.py
# Lisa Ferrier, Python 210, Lesson 05
# count even numbers using a list comprehension
def count_evens(nums):
ct_evens = len([num for num in nums if num % 2 == 0])
return ct_evens
food_prefs = {"name": "Chris",
"city": "Seattle",
"cake": "chocolate",
"fruit": "mango",
"salad": "greek",
"pasta": "lasagna"}
# 1 .Using the string format method, read food_prefs as a sentence.
food_prefs_string = "{name} is from {city} and he likes {cake} cake, {fruit} fruit, {salad} salad, and {pasta} pasta.".format(**food_prefs)
# 2 Using a list comprehension,build a dictionary of numbers from zero to fifteen and the hexadecimal equivalent
num_list = [(n, hex(n)) for n in list(range(0, 16))]
# 3 Same as before, but using a dict comprehension.
num_list = {n: hex(n) for n in range(0, 16)}
# 4 Make a new dict with same keys but with the number of a's in each value
food_prefsa = {(k, v.count('a')) for k, v in food_prefs.items()}
# 5 Create sets s2, s3 and s4 that contain numbers from zero through twenty, divisible 2, 3 and 4
# 5a Do this with one set comprehension for each set.
s2 = {n for n in list(range(0, 21)) if n % 2 == 0}
s3 = {n for n in list(range(0, 21)) if n % 3 == 0}
s4 = {n for n in list(range(0, 21)) if n % 4 == 0}
# 5c create sets using nested set comprehension on one line:
nums = list(range(0, 21))
divisors = [2, 3, 4, 5]
divisor_sets = [{n for n in nums if n % d == 0} for d in divisors]
| true
|
16a17d11e32521f8465723d8a72354833bcd84e1
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/Shweta/Lesson08/test_circle.py
| 1,762
| 4.1875
| 4
|
#!/usr/bin/env python
#test code for circle assignment
from circle import *
#######1- test if object can be made and returns the right radius or not####
def test_circle_object():
c=Circle(5)
assert c.radius == 5
def test_cal_diameter():
c=Circle(5)
#diameter=c.cal_diameter(5)
assert c.diameter == 10
def test_set_diamter():
c=Circle(10)
c.diameter=20
assert c.diameter == 20
assert c.radius == 10
def test_area():
c=Circle(2)
assert c.area == 12.566370614359172
try:
c.area=42
except AttributeError:
print("Can not set value for area")
def test_from_diameter():
c=Circle.from_diameter(8)
assert c.radius == 4
assert c.diameter == 8
def test_str_repr():
c=Circle(8)
assert str(c) == "Circle with radius:8"
assert repr(c) == "'Circle(8)'"
def test_add_mul():
c1 = Circle(2)
c2 = Circle(4)
assert (c1 + c2).radius == 6
assert (c1 * 4).radius == 8
def test_lt_eq():
c1=Circle(3)
c2=Circle(8)
assert (c1 > c2) == False
assert (c1 == c2) == False
assert (c1 < c2) == True
c3=Circle(8)
assert (c2 == c3) == True
def test_sort():
circles=[Circle(18),Circle(16)]#,Circle(4),Circle(11),Circle(30)]
circles=sorted(circles)
sorted_circle=circles.__str__()
assert sorted_circle == "['Circle(16)', 'Circle(18)']"#"['Circle(4)''Circle(11)''Circle(16)''Circle(18)''Circle(30)']"
def test_sphere_str():
s=Sphere(3)
assert s.radius == 3
assert s.diameter == 6
assert s.area == 113.09733552923255
assert s.volume == 113.09733552923254
def test_sphere_from_diameter():
s=Sphere.from_diameter(12)
c=Circle.from_diameter(10)
assert s.radius == 6
assert c.radius == 5
| true
|
94d6b57a7d5ea05430442d28f3a8bbf235fa0463
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/chris_delapena/lesson02/series.py
| 1,604
| 4.40625
| 4
|
"""
Name: Chris Dela Pena
Date: 4/13/20
Class: UW PCE PY210
Assignment: Lesson 2 Exercise 3 "Fibonacci"
File name: series.py
File summary: Defines functions fibonacci, lucas and sum_series
Descripton of functions:
fibonacci: returns nth number in Fibonacci sequence, where fib(n)=fib(n-1)+fib(n-2), n(0)=0 and n(1)=1
lucas: returns nth number in Lucas sequence, where luc(n)=luc(n-1)+luc(n-2), n(0)=0 and n(1)=1
sum_series: similar to fibonacci and lucas, except allows user to input optional values for n(0) and n(1)
"""
def sum_series(n, newPrevious=0, newNext=1): #specify default values for optional args
result = 0
previous = newPrevious
next = newNext
for i in range(n):
if i == 0:
result = previous;
elif i == 1:
result = next;
else:
result = previous + next;
previous = next;
next = result;
return result #return result, not print result
def fibonacci(n):
result = 0
previous = 0
next = 1
for i in range(n):
if i == 0:
result = previous;
elif i == 1:
result = next;
else:
result = previous + next;
previous = next;
next = result;
return result #return result, not print result
def lucas(n):
result = 0
previous = 2
next = 1
for i in range(n):
if i == 0:
result = previous;
elif i == 1:
result = next;
else:
result = previous + next;
previous = next;
next = result;
return result
| true
|
d526c9b6894043043b1069120492a35ea443d20d
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/Deniss_Semcovs/Lesson04/dict_lab.py
| 1,906
| 4.15625
| 4
|
#!/usr/bin/env python3
#Create a dictionary
print("Dictionaries 1")
dValues = {
"name":"Cris",
"city":"Seattle",
"cake":"Chocolate"
}
print(dValues)
#Delete the entry
print("Deleting entery for 'city'")
if "city" in dValues:
del dValues["city"]
print(dValues)
#Add an entry
print("Adding a new item")
dValues.update({"fruit":"Mango"})
print(dValues)
print("Display the dictionary keys")
print(dValues.keys())
print("Display the dictionary values")
print(dValues.values())
print("Is 'cake' a key?")
print("cake" in dValues.keys())
print("is 'Mango' a value?")
print("Mango" in dValues.values())
#Using the dictionary from item 1: Make a dictionary
#using the same keys but with the number of ‘t’s in each value as the value
print("Dictionaries 2")
print("Changing values")
dValues["name"]=0
dValues["fruit"]=2
dValues["cake"]=2
print(dValues)
print("Create sets")
#Create sets s2, s3 and s4 that contain numbers from zero through twenty,
#divisible by 2, 3 and 4
print("s2:")
s2 = set()
for i in range(20):
if i % 2 == 0:
s2.update([i])
else:
pass
print(s2)
print("s3")
s3 = set()
for i in range(20):
if i % 3 == 0:
s3.update([i])
else:
pass
print(s3)
print("s4")
s4 = set()
for i in range(20):
if i % 4 == 0:
s4.update([i])
else:
pass
print(s4)
#Display if s3 is a subset of s2 and if s4 is a subset of s2
print("Is s3 a subset of s2?")
s3.issubset(s2)
print("Is s4 subset of s2?")
s4.issubset(s2)
#Create a set with the letters in ‘Python’ and add ‘i’ to the set.
print("Sets2")
wPython = set()
wPython = set({"p","y","t","h","o","n"})
print(wPython)
wPython.add("i")
print(wPython)
#Create a frozenset with the letters in ‘marathon’.
wMarathon = frozenset({"m","a","r","a","t","h","o","n"})
print(wMarathon)
#Display the union and intersection of the two sets.
print(wPython.intersection(wMarathon))
| true
|
e878fd49b17b152e93fd91f6cfc88178b97fbf29
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/will_chang/lesson03/slicing_lab.py
| 2,639
| 4.3125
| 4
|
def exchange_first_last(seq):
"""Returns a copy of the given sequence with the first and last values swapped."""
if(len(seq) == 1): #Prevents duplicates if sequence only has one value.
seq_copy = seq[:]
else:
seq_copy = seq[-1:]+seq[1:-1]+seq[:1]
return seq_copy
def exchange_every_other(seq):
"""Returns a copy of the given sequence with every other item removed."""
seq_copy = seq[:0]
for i in range(len(seq)):
if i % 2 == 0: #Copy every other item of the original sequence into the new sequence.
seq_copy += seq[i:i+1]
return seq_copy
def first_last_four(seq):
"""Returns a copy of the given sequence with the first and last four items removed. Every other item is then removed from the remaining sequence."""
first_last_seq = seq[4:-4] #Placeholder sequence to remove first and last four items
return exchange_every_other(first_last_seq)
def reverse_elements(seq):
"""Returns a copy of the given sequence with the elements reversed."""
seq_copy = seq[::-1]
return seq_copy
def middle_last_first(seq):
"""Returns a copy of the given sequence with the following new order: middle third, last third, first third."""
seq_copy = seq[len(seq)//3:] + seq[:len(seq)//3]
return seq_copy
# Test variables
a_string = "this is a string"
a_tuple = (2, 54, 13, 12, 5, 32)
a_list = [3, 7, 26, 5, 1, 13, 22, 75, 9]
# This block of code is used to test the exchange_first_last(seq) function.
assert exchange_first_last(a_string) == "ghis is a strint"
assert exchange_first_last(a_tuple) == (32, 54, 13, 12, 5, 2)
assert exchange_first_last(a_list) == [9, 7, 26, 5, 1, 13, 22, 75, 3]
# This block of code is used to test the exchange_every_other(seq) function.
assert exchange_every_other(a_string) == "ti sasrn"
assert exchange_every_other(a_tuple) == (2, 13, 5)
assert exchange_every_other(a_list) == [3, 26, 1, 22, 9]
# This block of code is used to test the first_last_four(seq) function.
assert first_last_four(a_string) == " sas"
assert first_last_four(a_tuple) == ()
assert first_last_four(a_list) == [1]
# This block of code is used to test reverse_elements(seq) function.
assert reverse_elements(a_string) == "gnirts a si siht"
assert reverse_elements(a_tuple) == (32, 5, 12, 13, 54, 2)
assert reverse_elements(a_list) == [9, 75, 22, 13, 1, 5, 26, 7, 3]
# This block of code is used to test the middle_last_first(seq) function.
assert middle_last_first(a_string) == "is a stringthis "
assert middle_last_first(a_tuple) == (13, 12, 5, 32, 2, 54)
assert middle_last_first(a_list) == [5, 1, 13, 22, 75, 9, 3, 7, 26]
| true
|
5fdd8e8217317417bb9e5494433ce7d7db8998d7
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/Steven/lesson03/slicing.py
| 2,184
| 4.5
| 4
|
#! bin/user/env python3
'''
Write some functions that take a sequence as an argument, and return a copy of that sequence:
* with the first and last items exchanged.
* with every other item removed.
* with the first 4 and the last 4 items removed, and then every other item in the remaining sequence.
* with the elements reversed (just with slicing).
* with the last third, then first third, then the middle third in the new order.
NOTE: These should work with ANY sequence – but you can use strings to test, if you like.
'''
my_string = "this is a string"
my_tuple = (2, 54, 13, 12, 5, 32)
# exchange first and last positions in a sequence
def exchange_first_last(seq):
return seq[-1:] + seq[1:-1] + seq[:1]
# return every other item in a sequence
def every_other(seq):
return seq[::2]
# remove the first 4 and last 4 of a sequence but return every other remaining in the sequence
def remove_four_everyOther(seq):
return seq[4:-4:2]
# reverse the sequence
def reversed(seq):
return seq[::-1]
# given a sequence, return the last third, then first third and middle third in the new order
def new_order(seq):
step = len(seq) // 3 # determine length of sequence in thirds
last = seq[-step:] # last third of a sequence
first = seq[:step] # first third of a sequence
middle = seq[step:-step] # middle third of a sequence
return last + first + middle
if __name__ == "__main__":
# test exchange function
assert exchange_first_last(my_string) == "ghis is a strint"
assert exchange_first_last(my_tuple) == (32, 54, 13, 12, 5, 2)
# test every other function
assert every_other(my_string) == "ti sasrn"
assert every_other(my_tuple) == (2, 13, 5)
# test remove and return every other funtion
assert remove_four_everyOther(my_string) == " sas"
assert remove_four_everyOther(my_tuple) == ()
# test reversing function
assert reversed(my_string) == "gnirts a si siht"
assert reversed(my_tuple) == (32, 5, 12, 13, 54, 2)
# test new order sequence function
assert new_order(my_string) == "tringthis is a s"
assert new_order(my_tuple) == (5, 32, 2, 54, 13, 12)
print("tests passed")
| true
|
bc451f5e451696d92d005cf465993681ed70f4ae
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/tim_lurvey/lesson02/2.4_series.py
| 2,205
| 4.34375
| 4
|
#!/usr/bin/env python
__author__ = 'Timothy Lurvey'
import sys
def sum_series(n, primer=(0, 1)):
"""This function returns the nth values in an lucas sequence where n is sum of the two previous terms.
:param n: nth value to be returned from the sequence
:type n: int
:param primer: the first 2 integers of the sequence to be returned. (optional), default=(0,1)
:type primer: sequence
:returns: the nth position in the sequence
:rtype: int"""
#
# test variable
#
try:
assert (isinstance(n, int))
assert (n >= 0)
except AssertionError:
raise TypeError("n type must be a positive integer") from None
#
try:
assert (all([isinstance(x, int) for x in primer]))
except AssertionError:
raise TypeError("primer must be a sequence of integers") from None
#
# working function
#
if n < 2:
return primer[n]
else:
return sum_series(n=(n - 2), primer=primer) + sum_series(n=(n - 1), primer=primer)
def fibonacci(n):
"""fibonacci(n) -> return the nth value in a fibonacci sequence"""
return sum_series(n=n, primer=(0, 1))
def lucas(n):
"""lucas(n) -> return the nth value in a lucas sequence"""
return sum_series(n=n, primer=(2, 1))
def tests():
nFibonacci = (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55)
for i in range(len(nFibonacci)):
assert (fibonacci(i) == nFibonacci[i])
print("Fibonacci test passed")
#
nLucas = [2, 1, 3, 4, 7, 11, 18, 29]
for i in range(len(nLucas)):
assert (lucas(i) == nLucas[i])
print("Lucas test passed")
#
primerCustom = (4, 3)
nCustom = [4, 3, 7, 10, 17, 27, 44]
for i in range(len(nCustom)):
assert (sum_series(i, primer=primerCustom) == nCustom[i])
print("Custom (4,3) test passed")
#
# sum_series(3, primer="a") #fail
# sum_series(3, primer=("a")) #fail
# sum_series(-12) #fail
# sum_series("a") #fail
return True
def main(args):
tests()
if __name__ == '__main__':
main(sys.argv[1:])
| true
|
3e99ca23f0cb352898de2c6d948857e7d19c4648
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
/students/mitch334/lesson04/dict_lab.py
| 2,131
| 4.3125
| 4
|
"""Lesson 04 | Dictionary and Set Lab"""
# Goal: Learn the basic ins and outs of Python dictionaries and sets.
#
# When the script is run, it should accomplish the following four series of actions:
#!/usr/bin/env python3
# Dictionaries 1
# Create a dictionary containing “name”, “city”, and “cake” for “Chris” from “Seattle” who likes “Chocolate” (so the keys should be: “name”, etc, and values: “Chris”, etc.)
# Display the dictionary.
d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'}
print(d)
# Delete the entry for “cake”.
# Display the dictionary.
d.pop('cake')
print(d)
# Add an entry for “fruit” with “Mango” and display the dictionary.
d['fruit'] = 'Mango'
print(d)
# Display the dictionary keys.
# for key in d:
# print(key)
print(d.keys())
# Display the dictionary values.
# for value in d.values():
# print(value)
print(d.values())
# Display whether or not “cake” is a key in the dictionary (i.e. False) (now).
print('cake' in d)
# Display whether or not “Mango” is a value in the dictionary (i.e. True).
# print(d.get('Mango'))
print('Mango' in d.values())
# Dictionaries 2
# Using the dictionary from item 1: Make a dictionary using the same keys but with the number of ‘t’s in each value as the value (consider upper and lower case?).
print('d: ',d)
d2 = {}
for k, v in d.items():
d2[k] = v.lower().count('t')
print(d2)
# Sets
# Create sets s2, s3 and s4 that contain numbers from zero through twenty, divisible by 2, 3 and 4.
# Display the sets.
s2 = set(range(0, 21, 2))
print(s2)
s3 = set(range(0, 21, 3))
print(s3)
s4 = set(range(0, 21, 4))
print(s4)
# Display if s3 is a subset of s2 (False)
# and if s4 is a subset of s2 (True).
print(s3.issubset(s2))
print(s4.issubset(s2))
# Sets 2
# Create a set with the letters in ‘Python’ and add ‘i’ to the set.
s5 = set('Python')
print(s5)
s5.update('i')
print(s5)
# Create a frozenset with the letters in ‘marathon’.
sf5 = frozenset('marathon')
print(sf5)
# display the union and intersection of the two sets.
print(s5.union(sf5))
print(s5.intersection(sf5))
| true
|
2bfc44ed603cc4ff70fef4e524918ef13944094d
|
lucas-cavalcanti-ads/projetos-fiap
|
/1ANO/PYTHON/ListaExercicios/Lista03/Ex13.py
| 600
| 4.125
| 4
|
from datetime import date
print("Bem vindo ao programa de informacao de datas")
hoje = date.today()
print("Voce está executando esse programa em:",hoje.day,"/",hoje.month,"/",hoje.year)
dia = int(input("Digite o dia de hoje(Ex:22, 09): "))
mes = int(input("Digite o mes de hoje(Ex:07, 12): "))
ano = int(input("Digite o ano de hoje(Ex:2016, 2020): "))
if mes == 2:
if dia > 28 or dia < 1:
print("Formato de data inválido")
elif (dia > 31 or dia < 1) or (mes < 1 or mes > 12):
print("Formato de data inválido")
else:
print("Data digitada:",dia,"/",mes,"/",ano)
| false
|
e5a741e738040de2e2b62dd7515e2ae5afa31440
|
lucas-cavalcanti-ads/projetos-fiap
|
/1ANO/PYTHON/ListaExercicios/Lista02/Ex03.py
| 808
| 4.15625
| 4
|
teclado = input("Digite o primeiro numero: ")
num1 = int(teclado)
teclado = input("Digite o segundo numero: ")
num2 = int(teclado)
soma = num1 + num2
somar = str(soma)
subtracao = num1 - num2
subtracaor = str(subtracao)
multiplicacao = num1 * num2
multiplicacaor = str(multiplicacao)
divisao = num1 / num2
divisaor = str(divisao)
resto = num1 % num2
restor = str(resto)
numero1 = str(num1)
numero2 = str(num2)
print("A soma de " + numero1 + " + " + numero2 + " e igual a: " + somar)
print("A soma de " + numero1 + " + " + numero2 + " e igual a: " + subtracaor)
print("A multiplicacao de " + numero1 + " + " + numero2 + " e igual a: " + multiplicacaor)
print("A divisao de " + numero1 + " + " + numero2 + " e igual a: " + divisaor)
print("O resto de " + numero1 + " + " + numero2 + " e igual a: " + restor)
| false
|
7f2f690fa1b67d1c43566771e783c08d2eb57588
|
jamathis77/Python-fundamentals
|
/conditionals.py
| 2,444
| 4.28125
| 4
|
# A conditional resolves to a boolean statement ( True or False)
left = True
right = False
# Equality Operators
left != right # left and right are not equivalent
left == right # left and right are equivalent
left is right # left and right are same identity
left is not right # Left and right are not same identity
age_1 = 23
age_2 = 45
# Comparison Operators
age_1 > age_2 # left is greater than right
age_1 < age_2
age_1 >= age_2
age_1 <= age_2
# Logical Operators
age_1 == 4 and age_2 < 22 # and operator (True) and (True)
age_1 == 4 or age_2 < 22 # or operator
not age_1 == 23
# a b a and b
#-------------------------------
# True True True
# True False False
# False True False
# False False False
# a b a or b
# -----------------------------
# True True True
# True False True
# False True True
# False False False
# a not a
# ---------------
# True False
# False True
# x = 3
# name = "Ryan"
# if x > 3 and name == "Ryan":
# if True:
# print("I'm inside of an if if statment")
# print("X is pretty big, and that person's name is ryan")
# elif x <= 3:
# print("Maybe x is big, idunno")
# else:
# print("Otherwise, no")
# Challenge
# Take a name and age, and if the person is under 18, say "NAME, you are not an adult",
# if the person is 18 but not 21, say "You are an adult, but not quite yet"
# if the person is 21 and older, say ' You are fully an adult '
# cases ( 12, 18, 20, 21, 89 )
# extra spicy
# If their name starts with an A, say "Cool name"
# name = input("What is your name? > ")
# age = int(input("What is your age? > "))
# if age in range(18):
# print(f"{ name }, you are not an adult")
# elif age in range(18, 21):
# print("You are an adult, ish")
# elif age >= 21:
# print("You are a big person now")
# if name[0].lower() == "a":
# print("Cool name")
# Declare a number
# If the number is divisible by 3, print "Fizz"
# If the number is divisible by 5, print "Buzz"
# If the number is divisible by both 3 AND 5, print ONLY "FizzBuzz"
# Otherwise, just print the number
# Test cases: 1, 3, 5, 10, 15, 98
number = 98
if number % 3 == 0 and number % 5 == 0: # Or number % 15 == 0
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number)
| false
|
4e5d2fddbb38e7f243c2302203c692e238740ee5
|
xudaniel11/interview_preparation
|
/robot_unique_paths.py
| 1,808
| 4.21875
| 4
|
"""
A robot is located at the top-left corner of an M X N grid. The robot can only move either down or
right at any point in time. The robot is trying to reach the bottom-right corner of the grid.
How many possible unique paths are there?
Input: M, N representing the number of rows and cols, respectively
Output: an integer
bottom-up DP solution from http://articles.leetcode.com/unique-paths/
tldr; the total unique paths at grid (i,j) is equal to the sum of total unique paths from grid to the right (i,j+1) and the grid below (i+1,j).
"""
import numpy as np
import unittest
def get_num_unique_paths(M, N):
mat = np.zeros((M, N))
mat[M - 1] = np.ones((1, N))
mat[:, N - 1] = np.ones(M)
for i in reversed(xrange(M - 1)):
for j in reversed(xrange(N - 1)):
right = mat[i, j + 1]
down = mat[i + 1, j]
mat[i, j] = right + down
return int(mat[0, 0])
"""
Follow up:
Imagine certain spots are "off limits," such that the robot cannot step
on them. Design an algorithm to find a path for the robot from the top
left to the bottom right.
Solution: make blocks 0.
"""
def robot(grid):
m, n = grid.shape
for i in reversed(range(m - 1)):
for j in reversed(range(n - 1)):
if grid[i, j] == 0:
continue
else:
grid[i, j] = grid[i, j + 1] + grid[i + 1, j]
return grid[0, 0]
class TestUniquePaths(unittest.TestCase):
def test_1(self):
result = get_num_unique_paths(3, 7)
expected = 28
self.assertEqual(result, expected)
def test_blocks(self):
mat = np.ones((3, 4))
mat[1, 0] = 0
result = robot(mat)
expected = 6
self.assertEqual(result, expected)
if __name__ == "__main__":
unittest.main()
| true
|
b72c2595f1863a8a3a681657428dd4d6caceefb2
|
xudaniel11/interview_preparation
|
/calculate_BT_height.py
| 1,621
| 4.15625
| 4
|
"""
Calculate height of a binary tree.
"""
import unittest
def calculate_height(node):
if node == None:
return 0
left, right = 1, 1
if node.left:
left = 1 + calculate_height(node.left)
if node.right:
right = 1 + calculate_height(node.right)
return max(left, right)
class BinaryTreeNode():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class TestFirstCommonAncestor(unittest.TestCase):
def test_1(self):
root = BinaryTreeNode('A')
root.left = BinaryTreeNode('B')
root.right = BinaryTreeNode('C')
root.right.left = BinaryTreeNode('F')
root.right.right = BinaryTreeNode('G')
root.left.left = BinaryTreeNode('D')
root.left.right = BinaryTreeNode('E')
result = calculate_height(root)
expected = 3
self.assertEqual(result, expected)
def test_2(self):
root = BinaryTreeNode('A')
root.left = BinaryTreeNode('B')
root.right = BinaryTreeNode('C')
root.left.left = BinaryTreeNode('D')
root.left.right = BinaryTreeNode('E')
root.left.left.left = BinaryTreeNode('F')
root.left.left.right = BinaryTreeNode('G')
root.left.left.left.left = BinaryTreeNode('H')
result = calculate_height(root)
expected = 5
self.assertEqual(result, expected)
def test_3(self):
root = BinaryTreeNode('A')
result = calculate_height(root)
expected = 1
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main()
| true
|
3c419ab15020a8827a24044dfa180da9a7a5c47f
|
xudaniel11/interview_preparation
|
/array_of_array_products.py
| 1,044
| 4.15625
| 4
|
"""
Given an array of integers arr, write a function that returns another array at the same length where the value at each index i is the product of all array values except arr[i].
Solve without using division and analyze the runtime and space complexity
Example: given the array [2, 7, 3, 4]
your function would return: [84, 24, 56, 42] (by calculating: [7*3*4, 2*3*4, 2*7*4, 2*7*3])
Algorithm should run in O(N) time.
Solution: create two arrays representing the direction we iterate in. Each element in each array represents
the product so far from a particular direction up to that index.
"""
def get_array_of_array_products(arr):
going_right = [1]
for i in range(1, len(arr)):
going_right.append(going_right[i - 1] * arr[i - 1])
going_left = [1]
for i in range(1, len(arr)):
going_left.append(going_left[i - 1] * arr[len(arr) - i])
going_left.reverse()
return [x * y for x, y in zip(going_left, going_right)]
print get_array_of_array_products([2, 4, 6, 7]) # should be [168, 84, 56, 48]
| true
|
8268e7d5e29f7ccb1616fa17c022ad060256c569
|
xudaniel11/interview_preparation
|
/check_balanced_tree.py
| 1,516
| 4.4375
| 4
|
"""
Implement a function to check if a tree is balanced. For the purposes of this question,
a balanced tree is defined to be a tree such that no two leaf nodes differ in distance
from the root by more than one.
Solution taken from CTCI: recursive algorithms calculate the maximum and minimum length
paths in the tree. Compare the two at the end.
"""
import unittest
def max_depth(node):
if node == None:
return 0
else:
return 1 + max(max_depth(node.left), max_depth(node.right))
def min_depth(node):
if node == None:
return 0
else:
return 1 + min(min_depth(node.left), min_depth(node.right))
def check_balanced_tree(node):
return max_depth(node) - min_depth(node) <= 1
class BinaryTreeNode():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Test_Balanced_Tree(unittest.TestCase):
def test_case_1(self):
root = BinaryTreeNode('A')
root.left = BinaryTreeNode('B')
root.right = BinaryTreeNode('C')
root.right.left = BinaryTreeNode('F')
root.right.right = BinaryTreeNode('G')
root.left.left = BinaryTreeNode('D')
root.left.right = BinaryTreeNode('E')
result = check_balanced_tree(root)
self.assertEqual(result, True)
def test_case_2(self):
root = BinaryTreeNode('A')
root.left = BinaryTreeNode('B')
root.right = BinaryTreeNode('C')
root.right.left = BinaryTreeNode('F')
root.right.left.left = BinaryTreeNode('G')
result = check_balanced_tree(root)
self.assertEqual(result, False)
if __name__ == "__main__":
unittest.main()
| true
|
67f02f80af5d677d4752503c9947c994be1ad901
|
Roooommmmelllll/Python-Codes
|
/conversion_table.py
| 453
| 4.1875
| 4
|
#print a conversion table from kilograms to pounds
#print every odd number from 1 - 199 in kilograms
#and convert. Kilograms to the left and pounds to the right
def conversionTable():
print("Kilograms Pounds")
#2.2 pound = 1kilograms
kilograms = 1
kilograms = float(kilograms)
while kilograms <= 199:
pounds = kilograms*2.2
print(str("%4.2f"%kilograms) + str("%20.2f"%pounds))
kilograms += 2
conversionTable()
| true
|
648905f5d1d15cccd1a9356204ad69db0f30ce31
|
Roooommmmelllll/Python-Codes
|
/rightTriangleTest.py
| 970
| 4.21875
| 4
|
def getSides():
print("Please enter the three sides for a triagnle.\n" +
"Program will determine if it is a right triangle.")
sideA = int(input("Side A: "))
sideB = int(input("Side B: "))
sideC = int(input("Side C: "))
return sideA, sideB, sideC
def checkRight(sideA, sideB, sideC):
if sideA >= sideB and sideA >= sideC:
if sideA**2 == (sideB**2+sideC**2):
return True
elif sideB >= sideA and sideB >= sideC:
if sideB**2 == (sideA**2+sideC**2):
return True
elif sideC >= sideA and sideC >= sideB:
if sideC**2 == (sideA**2+sideB**2):
return True
return False
def printMe(right):
if right == True:
print("Those values create a right triangle!")
else:
print("Those values DO NOT create a right triangle!")
def main():
sideA, sideB, sideC = getSides()
#checkTriangle
right = checkRight(sideA, sideB, sideC)
printMe(right)
main()
| true
|
5ba3a2d27ec8f58f97c54cc837c81f210362508a
|
Roooommmmelllll/Python-Codes
|
/largerNumber.py
| 241
| 4.125
| 4
|
def largeNumbers():
value = 0
for i in range(7):
user = int(input("Please input seven numbers: "))
if user > value:
value = user
print("The largest number you entered was: " + str(value) + ".")
largeNumbers()
| true
|
8af20acbd18a8e179396fff27dedfa4cddda7d3c
|
mayer-qian/Python_Crash_Course
|
/chapter4/numbers.py
| 1,092
| 4.34375
| 4
|
#使用函数range生成数字,从1开始到5结束,不包含5
for value in range(1, 5):
print(value)
print("=======================================")
#用range创建数字列表
numbers = list(range(1, 6))
print(numbers)
print("=======================================")
#定义步长
even_numbers = list(range(2, 11, 2))
print(even_numbers)
print("=======================================")
#将1-10的平方添加到列表
squares = []
for value in range(1, 11):
squares.append(value**2)
print(squares)
print("=======================================")
#列表解析
squares = [value**2 for value in range(1, 11)]
print(squares)
print("=======================================")
#求大,求小,求和
digits = list(range(1, 11))
print("max digit is " + str(max(digits)))
print("min digit is " + str(min(digits)))
print("sum of digit is " + str(sum(digits)))
print(sum(list(range(1, 1000000))))
#打印3到30内3的倍数
digis = list(range(3, 31, 3))
for digi in digis:
print(digi)
#1-10的立方
lifang = [value**3 for value in range(1, 11)]
print(lifang)
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.