blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
97d12c33b2d142eaf238ae867bf6324c08a02bf9 | lanvce/learn-Python-the-hard-way | /ex32.py | 1,033 | 4.46875 | 4 | the_count=[1,2,3,4,5]
fruits=['apples','oranges','pears','apricots']
change=[1,'pennies',2,'dimes',3,'quarters']
#this fruit kind of fora-loop goes through a list
for number in the_count:
print(f"this is count {number}")
#same as above
for fruit in fruits:
print(f"A fruit of type :{fruit}")
#also we can go through mixed lists too
#noticed we have to use {} since we don't know what's in it
for i in change:
print(f"I go {i}")
#we can built lists,first start with an emoty one
elements=[]
#then use the range function to da 0 to 5 counts
for i in range(0,6):
print(f"Adding {i} to the list.")
#append is a function that lists understand
elements.append(i)
#now we can print them out too
for i in range(1,100,10):
print(f"they are {i}")
elements.append(i)
elements.append('kugou')
elements.append('wangyiyun')
del elements[10]
print (elements)
print(len(elements))
#for i in elements:
# print(f"Elements was :{i}")
print(elements.count(1))
elements.reverse()
print (elements)
| true |
ce5457678e0742d76a9e7935a257cd1af6e05617 | RobertElias/PythonProjects | /GroceryList/main.py | 1,980 | 4.375 | 4 | #Grocery List App
import datetime
#create date time object and store current date/time
time = datetime.datetime.now()
month = str(time.month)
day = str(time.day)
hour = str(time.hour)
minute = str(time.minute)
foods = ["Meat", "Cheese"]
print("Welcome to the Grocery List App.")
print("Current Date and Time: " + month + "/" + day + "\t" + hour + ":" + minute)
print("You currently have " + foods[0] + " and " + foods[1] + " in your list.")
#Get user input
food = input("\nType of food to add to grocery list: ")
foods.append(food.title())
food = input("\nType of food to add to grocery list: ")
foods.append(food.title())
food = input("\nType of food to add to grocery list: ")
foods.append(food.title())
#Print and sort the list
print("Here is your grocery list: ")
print(foods)
foods.sort()
print("Here is you grocery list sorted: ")
print(foods)
#Shopping for your list
print("\nSimulating Grocery Shopping...")
print("\nCurrent grocery list: " + str(len(foods)) + " items")
print(foods)
buy_food = input("What food did you just buy: ").title()
foods.remove(buy_food)
print("Removing " + buy_food + " from the list...")
print("\nSimulating Grocery Shopping...")
print("\nCurrent grocery list: " + str(len(foods)) + " items")
print(foods)
buy_food = input("What food did you just buy: ").title()
foods.remove(buy_food)
print("Removing " + buy_food + " from the list...")
print("\nSimulating Grocery Shopping...")
print("\nCurrent grocery list: " + str(len(foods)) + " items")
print(foods)
buy_food = input("What food did you just buy: ").title()
foods.remove(buy_food)
print("Removing " + buy_food + " from the list...")
#The store is out of this item
print("\nCurrent grocery list: " + str(len(foods)) + " items")
print(foods)
no_item = foods.pop()
print("\nSorry, the store is out of " + no_item + ".")
new_food = input("What food would you like instead: ").title()
food.insert(0,new_food)
print("\nHere is what remains on your grocery list: ")
print(foods)
#New food
| true |
0cf8bac0a47bb1156eaaff40503bc1cdcadb50a1 | RobertElias/PythonProjects | /Arrays/main_1.py | 309 | 4.375 | 4 | #Write a Python program to create an array of 5 integers and display the array items.
from array import *
array_num = array('i', [1,3,5,7,9])
for i in array_num:
print("Loop through the array.",i)
print("Access first three items individually")
print(array_num[0])
print(array_num[1])
print(array_num[2])
| true |
2dae568f69ab9c93d43fb38f7f5a776844bb5e3e | Isco170/Python_tutorial | /Lists/listComprehension.py | 723 | 4.84375 | 5 | # List Comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
# Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name
# Without list comprehension
# fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
# newList = []
# for x in fruits:
# if "a" in x:
# newList.append(x)
# print(newList)
# With list comprehension
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
# newList = [ x for x in fruits if "a" in x]
# Only accept items that are not "apple"
# newList = [x.upper() for x in fruits if x != "apple"]
newList = ['Hello' for x in fruits if x != "apple"]
print(newList) | true |
a315863eeb4b603354fc7f681e053554a35582fc | IonutPopovici1992/Python | /LearnPython/if_statements.py | 276 | 4.25 | 4 | is_male = True
is_tall = True
if is_male and is_tall:
print("You are a tall male.")
elif is_male and not(is_tall):
print("You are a short male.")
elif not(is_male) and is_tall:
print("You are not a male, but you are tall.")
else:
print("You are not a male.")
| true |
3f4261421609d3248060d7b9d12de47ad8bac76d | becomeuseless/WeUseless | /204_Count_Primes.py | 2,069 | 4.125 | 4 | '''
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
'''
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
#attemp 1: for every number smaller than n+1, check if it is a prime. To check if a number p is a prime, see if it #divisible by the numbers smaller than p.
#Time Complexity : O(n**2)
#Space Complexity : O(1)
'''
cnt = 0
for i in range(1,n):
if self.isPrime(i):
cnt += 1
return cnt
def isPrime(self, x):
if x == 1:
return False
for i in range(2,x):
if x%i == 0:
return False
return True
'''
#attemp 2:To check if a number is p is a prime, we dont need to divide it by all the numbers smaller than p. Actually only
#the numbers smaller than p**1/2 would be enough.
#Time Complexity : O(n**1.5)
#Space Complexity : O(1)
'''
cnt = 0
for i in range(1,n):
if self.isPrime(i):
cnt += 1
return cnt
def isPrime(self, x):
if x == 1:
return False
i = 2
while i <= x**0.5:
if x%i == 0:
return False
i += 1
return True
'''
#attemp 3:When check if a number is a prime number, we will know for sure the multiples of the number are not prime numbers.
#Thus we dont need to check the multiples.
#Time Complexity : O(loglogn)
#Space Complexity : O(n)
if n < 3:
return 0
isPrime = [True]*n
isPrime[0] = isPrime[1] = False
for i in range(int(n**0.5) + 1):
if not isPrime[i]:
continue
j = i*i
while j< n:
isPrime[j] = False
j += i
return sum(isPrime)
| true |
77665880cde79a8f833fb1a3f8dfe9c88368d970 | codexnubes/Coding_Dojo | /api_ajax/OOP/bike/bikechain.py | 1,120 | 4.25 | 4 | class Bike(object):
def __init__(self,price,max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayinfo(self):
print "Here are your bike stats:\n\
Price: ${}\n\
Max Speed: {}\n\
Miles Rode: {}".format(self.price, self.max_speed, self.miles)
def ride(self):
self.miles += 10
print "Riding..."
return self
def reverse(self):
if self.miles >= 5:
self.miles -= 5
print "Reversing..."
else:
print "Can't reverse!"
return self
bike1 = Bike(200, "10mph")
bike2 = Bike(1000, "50mph")
bike3 = Bike(500, "38mph")
bike1.displayinfo()
bike2.displayinfo()
bike3.displayinfo()
for i in range(0,3):
bike1.ride().ride().ride().reverse()
bike2.ride().reverse().reverse().reverse()
bike3.reverse().ride().reverse()
bike1.displayinfo()
bike2.displayinfo()
bike3.displayinfo()
for i in range(0,2):
bike1.reverse()
bike2.ride()
bike3.ride()
bike1.displayinfo()
bike2.displayinfo()
bike3.displayinfo()
| true |
256f3e7cfe573c0bed1c8e5e62c6df1226d9cc79 | AlenaGB/hw | /5.py | 465 | 4.125 | 4 | gain = float(input("What is the revenue this month? $"))
costs = float(input("What is the monthly expenses? $"))
if gain == costs:
print ("Not bad. No losses this month")
elif gain < costs:
print("It's time to think seriosly about cutting costs")
else:
print("Great! This month you have a profit")
staff = int(input("How many employees do you have?"))
profit = (gain - costs)/staff
print ("Your profit is ${:.2f} per person".format(profit)) | true |
c619f9cd9cef317f81eab2637a5b454ef9c745e5 | TwiggyTwixter/Udemy-Project | /test.py | 309 | 4.15625 | 4 | print("This program calculates the average of two numbers")
firstNumber = float (input({"What will the first number be:"}))
secondNumber = float (input({"What will the second number be:"}))
print("The numbers are",firstNumber, "and",secondNumber)
print("The average is: ", (firstNumber + secondNumber )/ 2) | true |
37899a51d576727fdbde970880245b40e7e5b7b4 | dusanvojnovic/tic-tac-toe | /tic_tac_toe.py | 2,430 | 4.125 | 4 | import os
board = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]
def print_board(board):
print(board[7] + ' |' + board[8] + ' |' + board[9])
print("--------")
print(board[4] + ' |' + board[5] + ' |' + board[6])
print("--------")
print(board[1] + ' |' + board[2] + ' |' + board[3])
def game():
play = "X"
count = 0
global board
for i in range(10):
os.system('cls')
print ("Welcome to the TicTacToe! Use your num keypad(1-9) to play.")
print_board(board)
choice = input(f"Player {play} it's your turn to play: ")
move = int(choice)
if board[move] != " ":
print("That field is not empty, please try again.")
continue
else:
board[move] = play
count += 1
if count >= 5:
# checking rows
if board[7] == board[8] == board[9] == play or \
board[4] == board[5] == board[6] == play or \
board[1] == board[2] == board[3] == play:
os.system('cls')
print_board(board)
print (f"GAME OVER! The winner is {play} player!")
break
# checking columns
elif board[7] == board[4] == board[1] == play or \
board[8] == board[5] == board[2] == play or \
board[9] == board[6] == board[3] == play:
os.system('cls')
print_board(board)
print (f"GAME OVER! The winner is {play} player!")
break
# checking diagonals
elif board[1] == board[5] == board[9] == play or \
board[7] == board[5] == board[3] == play:
os.system('cls')
print_board(board)
print (f"GAME OVER! The winner is {play} player!")
break
if count == 9:
os.system('cls')
print_board(board)
print ("GAME OVER! It's tied!")
break
if play == "X":
play = "O"
else:
play = "X"
if input("Do you want to play again? (Y)es or (N)o: ").upper() == "Y":
board = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]
os.system('cls')
game()
else:
os.system('cls')
print("Goodbye")
game()
| true |
f4247987858702440a4739dc84674cec373d9384 | league-python-student/level0-module1-dencee | /_02_variables_practice/circle_area_calculator.py | 1,345 | 4.53125 | 5 | import turtle
from tkinter import messagebox, simpledialog, Tk
import math
import turtle
# Goal: Write a Python program that asks the user for the radius
# of a circle and displays the area of that circle.
# The formula for the area of a circle is πr^2.
# See example image in package to check your output.
if __name__ == '__main__':
window = Tk()
window.withdraw()
# Ask the user for the radius in pixels and store it in a variable
# simpledialog.askinteger()
num = simpledialog.askinteger("Enter a radius",None)
# Make a new turtle
Shivam = turtle.Turtle()
# Have your turtle draw a circle with the correct radius
# my_turtle.circle()
Shivam.circle(num)
# Call the turtle .penup() method
Shivam.penup()
# Move your turtle to a new x,y position using .goto()
Shivam.goto(100,80)
# Calculate the area of your circle and store it in a variable
# Hint, you can use math.pi
arnum = math.pi*num*num
# Write the area of your circle using the turtle .write() method
# my_turtle.write(arg="area = " + str(area), move=True, align='left', font=('Arial',8,'normal'))
Shivam.write(arg="area = " + str(arnum), move=True, align='left', font=('Arial',8,'normal'))
# Hide your turtle
Shivam.hideturtle()
# Call turtle.done()
turtle.done() | true |
6d63273b82815d33226d51ddf224e22434bbaded | WalterVives/Project_Euler | /4_largest_palindrome_product.py | 975 | 4.15625 | 4 | """
From: projecteuler.net
Problem ID: 4
Author: Walter Vives
GitHub: https://github.com/WalterVives
Problem:
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
part1 = []
part2 = []
result = 0
for i in range(100,1000):
for j in range(100,1000):
multiplication = i * j
multiplication = list(str(multiplication))
if len(multiplication) == 6:
part1 = multiplication[0], multiplication[1], multiplication[2]
part2 = multiplication[3], multiplication[4], multiplication[5]
# Palindrome
if part1[::-1] == part2:
# List of numbers to int number
num = int("".join(multiplication))
# Add the largest palindrome product
if num > result:
# result
result = num
# Number 1
x = i
# Number 2
y = j
#print(i, "*", j, "=", result)
print(x, "*", y, "=", result) | true |
74914ed8c197d826a7c557c8a1fcd3c8e3c805aa | aryanirani6/ICS4U-Classwork | /example.py | 866 | 4.5625 | 5 | """
create a text file with word on a number of lines
1. open the text file and print out 'f.read()'. What does it look like?
2. use a for loop to print out each line individually. 'for line in f:'
3. print our words only with "m", or some other specific letter.
"""
# with open("Some_file.txt", 'r') as f:
# print(f.read())
#2
#with open("Some_file.txt", 'r') as f:
# for line in f:
# print(line)
#3 to print the line it will give skip another line for each word
#4 with open("Some_file.txt", 'r') as f:
# for line in f:
# print(line.strip())
#4 print words only with m
#with open("Some_file.txt", 'r') as f:
# for line in f:
# if line.startswith("m"):
# print(line.strip())
#5 to check for both upper case and lower case letter
#with open("Some_file.txt", 'r') as f:
# for line in f:
# if line.lower().startswith("m"):
# print(line.strip())
| true |
6798074572ee5e82a5da113a6ace75b4670ae00c | aryanirani6/ICS4U-Classwork | /classes/classes2.py | 2,179 | 4.375 | 4 | """
name: str
cost: int
nutrition: int
"""
class Food:
""" Food class
Attributes:
name (str): name of food
cost (int): cost of food
nutrition (int): how nutritious it is
"""
def __init__(self, name: str, cost: int, nutrition: int):
""" Create a Food object.
Args:
name: name of food
cost: cost of food
nutrition: how nutritious it is
"""
self.name = name
self.cost = cost
self.nutrition = nutrition
class Dog:
""" Thing that goes ruff
Attributes:
breed (str): The dog's breed
name (str): The dog's name
happiness (int): The dog's happiness. Defualts to 100
"""
def __init__(self, breed: str, name: str):
""" Create a dog object.
Args:
breed: The breed of the dog
name: name of the dog.
"""
self.breed = breed
self.name = name
self.happiness = 100
def __str__(self):
return f"{self.happiness}, {self.name}"
def eat(self, food: Food):
""" Gets the dog to eat food.
increases dogs happiness by 10% of food eaten
Args:
food: The food for dog to eat.
"""
happiness_increase = food.nutrition * 0.1
self.happiness += happiness_increase
def bark(self):
""" Make the dog bark
"""
print("Ruff Ruff")
sausage = Food("Polish Sausage", 10, 100)
james = Dog("Husky", "James")
print(james)
print(james.happiness)
james.eat(sausage)
print(james.happiness)
james.bark()
"""if __name__ == "__main__":
main()
"""
""" Encapsulation
Basic definition: protecting your object's attributes.
"""
class Student:
def __init__(self, name: str, age: int):
self.name = name
self._age = age
def set_age(self, age: int):
if type(age) != int:
raise ValueError("Age must be an integer")
self._age = age
def age_in_5_years(self):
return self._age + 5
def get_age(self):
return self._age
s = Student("Sally", 15)
print(s.age_in_5_years())
print(s.get_age())
| true |
7416e1c946d17374332e7e4ebabb09eb159aaa97 | GribaHub/Python | /exercise15.py | 967 | 4.5 | 4 | # https://www.practicepython.org/
# PRACTICE PYTHON
# Beginner Python exercises
# Write a program (using functions!) that asks the user for a long string containing multiple words.
# Print back to the user the same string, except with the words in backwards order.
# clear shell
def cls():
print(50 * "\n")
# backwards order (loop)
def backwards(text):
result=text.split(" ")
lnth=len(result)
j=range(lnth)
text=[]
for i in j:
text.append(result[lnth-i-1])
result=[]
result=" ".join(text)
return(result)
# backwards order (reverse)
def backwards2(text):
result=text.split(" ")
result.reverse()
result=" ".join(result)
return(result)
# main program
cls()
print("Words in backwards order:",backwards(input("Enter a string containing multiple words: ")))
print()
print("Words in backwards order:",backwards2(input("Enter a string containing multiple words: ")))
| true |
dca9c5f3548711b16c7736adc0588fff766c95a1 | kirubakaran28/Python-codes | /valid palindrome.py | 359 | 4.15625 | 4 | import re
def isPalindrome(s):
s = s.lower()
#removes anything that is not a alphabet or number
s = re.sub('[^a-z0-9]','',s)
#checks for palindrome
if s == s[::-1]:
return True
else:
return False
s = str(input("Enter the string: "))
print(isPalindrome(s)) | true |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
4ef007bae17e06e2f2f81f160d2d07e8e029375f | kahnadam/learningOOP | /Lesson_2_rename.py | 688 | 4.3125 | 4 | # rename files with Python
import os
def rename_files():
#(1) get file names from a folder
file_list = os.listdir(r"C:\Users\adamkahn\learningOOP\lesson_2_prank")
#find the current working directory
saved_path = os.getcwd()
print("Current Working Directory is "+saved_path)
#change directory to the one with the files
os.chdir(r"C:\Users\adamkahn\learningOOP\lesson_2_prank")
#(2) for each file, rename file
for file_name in file_list:
print("Old Name - "+file_name)
print("New Name - "+file_name.translate(None, "0123456789"))
os.rename(file_name,file_name.translate(None, "0123456789"))
#return to original working directory
os.chdir(saved_path)
rename_files() | true |
7118bf76fbb295f78247342b3b341f25d2d0a5c0 | adikadu/DSA | /implementStack(LL).py | 1,181 | 4.21875 | 4 | class Stack:
def __init__(self):
self.top = None
self.bottom = None
self.length = 0
def node(self, value):
return {
"value": value,
"next": None
}
def peek(self):
if not self.length: return "Stack is empty!!!"
return self.top["value"]
def push(self, value):
node = self.node(value)
node["next"] = self.top
self.top = node
if not self.length: self.bottom = node
self.length+=1
def pop(self):
if not self.length:
print("Stack is empty!!!")
return
node = self.top
if self.length==1:
self.top = None
self.bottom = None
else: self.top = self.top["next"]
self.length -= 1
node["next"] = None
return node
def isEmpty(self):
return not bool(self.length)
def traverse(self):
if not self.length:
print("Stack is empty!!!")
return
x = self.top
for i in range(self.length):
print(x["value"])
x = x["next"]
stack = Stack()
print("Empty:",end=" ")
stack.traverse()
stack.push(1)
stack.push(2)
stack.push(3)
print("Three values:", end=" ")
stack.traverse()
print("peek=", end=" ")
print(stack.peek())
stack.pop()
print("Two values:", end=" ")
stack.traverse()
print("peek=", end=" ")
print(stack.peek())
| true |
c27205377f4de9ef50f141c30b502a795c6dc118 | wmjpillow/Algorithm-Collection | /how to code a linked list.py | 2,356 | 4.21875 | 4 | #https://www.freecodecamp.org/news/python-interview-question-guide-how-to-code-a-linked-list-fd77cbbd367d/
#Nodes
#1 value- anything strings, integers, objects
#2 the next node
class linkedListNode:
def __init__(self,value,nextNode=None):
self.value= value
self.nextNode= nextNode
def insertNode(head, valuetoInsert):
currentNode= head
while currentNode is not None:
if currentNode.nextNode is None:
currentNode.nextNode= linkedListNode(valuetoInsert)
return head
currentNode= currentNode.nextNode
#Delete node function
def deleteNode(head, valueToDelete):
currentNode= head
previousNode= None
while currentNode is not None:
if currentNode.value == valueToDelete:
if previousNode is None:
newHead = currentNode.nextNode
currentNode.nextNode = None
return newHead
previousNode.nextNode = currentNode.nextNode
return head
previousNode = currentNode
currentNode = currentNode.nextNode
return head # Value to delete was not found.
# "3" -> "7" -> "10"
node1 = linkedListNode("3") # "3"
node2 = linkedListNode("7") # "7"
node3 = linkedListNode("10") # "10"
node1.nextNode = node2 # node1 -> node2 , "3" -> "7"
node2.nextNode = node3 # node2 -> node3 , "7" -> "10"
# node1 -> node2 -> node3
head = node1
print "*********************************"
print "Traversing the regular linkedList"
print "*********************************"
# Regular Traversal
currentNode = head
while currentNode is not None:
print currentNode.value,
currentNode = currentNode.nextNode
print ''
print "*********************************"
print "deleting the node '7'"
newHead = deleteNode(head, "10")
print "*********************************"
print "traversing the new linkedList with the node 7 removed"
print "*********************************"
currentNode = newHead
while currentNode is not None:
print currentNode.value,
currentNode = currentNode.nextNode
print ''
print "*********************************"
print "Inserting the node '99'"
newHead = insertNode(newHead, "99")
print "*********************************"
print "traversing the new linkedList with the node 99 added"
print "*********************************"
currentNode = newHead
while currentNode is not None:
print currentNode.value,
currentNode = currentNode.nextNode | true |
ca845b51f55cef583bfc6b9ff05741d56f474fec | mbravofuentes/Codingpractice | /python/IfStatement.py | 625 | 4.21875 | 4 | import datetime
DOB = input("Enter your DOB: ")
CurrentYear = datetime.datetime.now().year
Age = CurrentYear-int(DOB) #This will change the string into an integer
if(Age>=18):
print("Your age is {} and you are an adult".format(Age))
if(Age<=18):
print("Your age is {} and you are a Kid".format(Age))
#In Python, if statements are included in "Blocks" which is just where the code is going to be running
#in that case, blocks run by spaces/indents
#If and Else Statements
num = input("Put in a number: ")
if (int(num) >= 0):
print("This is a positive number")
else:
print("This number is negative")
| true |
9bb1168da52c3bdbb7015f7a61f515b10dc69267 | ubercareerprep2019/Uber_Career_Prep_Homework | /Assignment-2/src/Part2_NumberOfIslands.py | 2,348 | 4.28125 | 4 | from typing import List, Tuple, Set
def number_of_islands(island_map: List[List[bool]]) -> int:
"""
[Graphs - Ex5] Exercise: Number of islands
We are given a 2d grid map of '1's (land) and '0's (water). We define an island as a body of land surrounded by
water and is formed by connecting adjacent lands horizontally or vertically. We may assume all four edges of the
grid are all surrounded by water. We need to write a method to find the number of islands in such a map.
Write a method number_of_islands(bool[][] island_map) that returns the number of islands in a 2dmap. For this
exercise you can think of a true in the island_map representing a '1' (land) and a false in the island_map
representing a '0' (water).
"""
counter: int = 0
visited: Set[Tuple[int, int]] = set()
for x in range(len(island_map)):
for y in range(len(island_map[x])):
if island_map[x][y] and (x, y) not in visited:
counter += 1
stack: List[Tuple[int, int]] = [(x, y)]
while stack:
node = stack.pop() # dfs
if node in visited:
continue
visited.add(node)
stack.extend(get_outward_edges(island_map, node))
return counter
def get_outward_edges(island_map: List[List[bool]], vertex: Tuple[int, int]) -> List[Tuple[int, int]]:
x, y = vertex
output: List[Tuple[int, int]] = []
for x1, y1 in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]:
if x1 < 0 or y1 < 0:
continue
if x1 >= len(island_map) or y1 >= len(island_map[x1]):
continue
if island_map[x1][y1]:
output.append((x1, y1))
return output
def main():
island_map1 = [[True, True, True, True, False],
[True, True, False, True, False],
[True, True, False, False, False],
[False, False, False, False, False]]
assert number_of_islands(island_map1) == 1
island_map2 = [[True, True, False, False, False],
[True, True, False, False, False],
[False, False, True, False, False],
[False, False, False, True, True]]
assert number_of_islands(island_map2) == 3
if __name__ == "__main__":
main() | true |
bd829c3ee9c8593b97d74d5a1820c050013581f0 | lepy/phuzzy | /docs/examples/doe/scatter.py | 924 | 4.15625 | 4 |
'''
==============
3D scatterplot
==============
Demonstration of a basic scatterplot in 3D.
'''
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
def randrange(n, vmin, vmax):
'''
Helper function to make an array of random numbers having shape (n, )
with each number distributed Uniform(vmin, vmax).
'''
return (vmax - vmin)*np.random.rand(n) + vmin
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100
# For each set of style and range settings, plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, zlow, zhigh)
ax.scatter(xs, ys, zs, c=c, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
| true |
529738259a0398c322cda396cfc79a6b3f5b38d3 | nancydyc/algorithms | /backtracking/distributeCandies.py | 909 | 4.21875 | 4 | def distributeCandies(candies, num_people):
"""
- loop through the arr and add 1 more candy each time
- at the last distribution n, one gets n/remaining candies
- until the remaining of the candies is 0
- if no candy remains return the arr of last distribution
>>> distributeCandies(7, 4)
[1, 2, 3, 1]
>>> distributeCandies(10, 3)
[5, 2, 3]
"""
arr = [0] * num_people
candy = 0
while candies > 0:
for i in range(len(arr)):
candy += 1
candies -= candy
if candies >= 0:
arr[i] += candy
else:
candies += candy
arr[i] += candies
return arr
return arr
#################################################
if __name__ == "__main__":
import doctest
if doctest.testmod().failed == 0:
print('Suceeded!')
| true |
f0fa4b9c13b33806a80c6582e15bda397fafe5b9 | JonRivera/cs-guided-project-time-and-space-complexity | /src/demonstration_1.py | 1,053 | 4.3125 | 4 | """
Given a sorted array `nums`, remove the duplicates from the array.
Example 1:
Given nums = [0, 1, 2, 3, 3, 3, 4]
Your function should return [0, 1, 2, 3, 4]
Example 2:
Given nums = [0, 1, 1, 2, 2, 2, 3, 4, 4, 5]
Your function should return [0, 1, 2, 3, 4, 5].
*Note: For your first-pass, an out-of-place solution is okay. However, after
solving out-of-place, try an in-place solution with a space complexity of O(1).
For that solution, you will need to return the length of the modified `nums`.
The length will tell the user where the end of the array is after removing all
of the duplicates.*
"""
# Track Time for Code to Execute:
t0 = time.time()
# CODE BLOCK
t1 = time.time()
time1 = t1 - t0
import time
# Understand
# Remove Duplicates for given list
# Plan
# Need a way of tracking repeated elements
# If we have a repeated element then remove it from list.pop based on index
# Option#2:Can simply convert given list to set and then reconvert it back to a list
def remove_duplicates(nums):
nums = list(set(nums))
return nums
| true |
0e9bb8e8d914754431f545af8cf6358012c52ca1 | MikeyABedneyJr/python_exercises | /challenge7.py | 677 | 4.1875 | 4 | '''
Write one line of Python that takes a given list and makes a new list that has only the even elements of this list in it. http://www.practicepython.org/exercise/2014/03/19/07-list-comprehensions.html
'''
import random
from random import randint
given_list = random.sample(xrange(101),randint(1, 101))
# even_numbers = [number % 2 == 0 for number in given_list]
# This only prints [false, true, false,...] and not actual values
even_numbers = [number for number in given_list if number % 2 == 0]
# This says even_numbers = [number] and "number" is determined by all the logic that follows it (i.e the for loop and if statement)
print given_list, "\n\n", even_numbers | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.