blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
1e6c18666c699243d9a04f744dc5c689f503b4a4
Akshatha-Udupa/AITPL2108
/astringinalphabeticorder.py
391
4.53125
5
#Program to sort the words in a string str = "Hello world bangalore Karnataka India" words = str.split() words.sort() for word in words: print(word) #using function def sortstr(str): words = str.split() words.sort() for word in words: print(word) str=input("Enter a string") sortstr(str) '''output Hello India Karnataka bangalore world '''
false
ea2a65c9fb49c5b2270268739807fbc7b24f0af3
Ruturaj4/leetcode-python
/easy/confusing-number.py
1,181
4.125
4
# Given a number N, return true if and only if it is a confusing number, which # satisfies the following condition: # # We can rotate digits by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are # rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively. When 2, 3, 4, 5 and 7 # are rotated 180 degrees, they become invalid. # A confusing number is a number that when rotated 180 degrees becomes a # different number with each digit valid. class Solution: def confusingNumber(self, N: int) -> bool: temp = {"0":"0", "1":"1", "6":"9", "8":"8", "9":"6"} number = [] for i in str(N)[::-1]: if i not in temp: return False number.append(temp[i]) if "".join(number)!=str(N): return True # another approach class Solution: def confusingNumber(self, N: int) -> bool: temp = {"0":"0", "1":"1", "6":"9", "8":"8", "9":"6"} n = str(N) for i in n[::-1]: if i not in temp: return False for i in range((len(n)+1)//2): if temp[n[i]]!=n[-i-1]: return True return False
true
c2832722502bbe1f382ea21c6cee47aae524f067
reiinakano/personal_exercises
/CTCI19.8.py
641
4.1875
4
def find_all_pairs(array, sum): my_dict = {} for number in array: difference = sum - number if difference in my_dict: for i in range(my_dict[difference]): print str(difference) + ", " + str(number) if number in my_dict: my_dict[number] += 1 else: my_dict[number] = 1 if __name__ == "__main__": find_all_pairs([1, 4, 2, 4, 25, 34, 33, 2, 1], 67) # This algorithm finds ALL possible pairs regardless of whether the pair of values has appeared before. # Example: The pair 1 at index 0, 4 at index 1 AND the pair 1 and index 0, 4 at index 3 will be printed separately.
true
742469227931080d7172d529cd0cf9f2a30c2909
ifpb/exercises
/src/pages/exercises/basic-bmi/_codes/python/response/bmi.py
285
4.1875
4
# BMI = weight/height² weight = 60 height = 1.65 result = '' bmi = weight / height ** 2 if bmi < 18.5: result = 'Underweight' elif bmi <= 24.9: result = 'Normal weight' elif bmi <= 29.9: result = 'Overweight' else: result = 'Obesity' print(f'BMI: {bmi}\nResult: {result}')
false
b5baca210b64490ab2c2f36ff5e160b74741dd75
MomoeYoshida/cp1404practicals
/prac_05/hex_colours.py
625
4.25
4
""" Create a program that allows you to look up hexadecimal colour codes. """ # Don't worry about matching the case COLOUR_CODES = {"aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "antiquewhite1": "#ffefdb", "cyan1": "#00ffff", "darkgoldenrod3": "#cd950c", "aquamarine1": "#7fffd4", "deeppink1": "#ff1493", "gold1": "#ffd700", "gray": "#bebebe", "pale": "#db7093"} colour_name = input("Enter a colour name: ").lower() while colour_name != "": print("The code for \"{}\": {}".format(colour_name, COLOUR_CODES.get(colour_name))) colour_name = input("Enter a colour name: ").lower()
true
09b9b885c2b61134421aad0b6224f1d2ccb27f54
TrystanDames/Python
/Crash Course/chap06/TryItYourself_Page163.py
1,313
4.25
4
#6-4 language_means = { 'for': 'This is to allow us to create a loop', '.pop': 'This allows us to delete something at the end of a list', 'del': 'This allows us to delete something specific', 'sum()': 'This allows us to sum up all the values in a variable', 'print()': 'This allows us to see the info we put into our program', 'backslash(n)': 'This creates a new line where this is placed', 'backslash(t)': 'This makes an indent for where this is placed', 'get()': 'This fetches something within the variable.' } print("\nThe following words and what they mean in python:") for language in language_means.values(): for means in language_means.keys(): print(f"\n{means}: {language}") #6-5 rivers = { 'nile': 'egypt', 'sepik': 'new guinea', 'mississippi': 'united states' } for river in rivers.keys(): for country in rivers.values(): print(f"\nThe {river} river runs through the county of {country}") #6-6 favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } take_poll = {'jen','sarah', 'edward', 'phil', 'trystan', 'jaden', 'vusi'} for poll in take_poll: if poll in favorite_languages: print(f"\nThank you {poll.title()} for taking the poll we really appreciate it.") else: print(f"\nWe are inviting you {poll.title()} to come and take our poll.")
true
04e090efd2337c753ca5d9d64aae9b85270313d2
baburajk/python
/practice/mergesort.py
1,343
4.375
4
#!/usr/local/bin/python3 import argparse class MergeSort: """ Merge sort example """ def mergesort(self,unsortedlist): if len(unsortedlist) < 2: return unsortedlist #Step:1 Divide list in half midindex = int(len(unsortedlist) / 2) unsortedleft = unsortedlist[:midindex] unsortedright = unsortedlist[midindex:] print ("Recursion", unsortedleft, unsortedright) #Step:2 Sort each half sortedleft = self.mergesort(unsortedleft) print ("Sorted Left" , sortedleft) sortedright = self.mergesort(unsortedright) print ("Sorted Right" , sortedright) #Step:3 Merge each halves sortedlist = [] while len(sortedlist) < len(unsortedlist): #unsortedleft's first element comes next if it's less than #Unsorted rights first element or if unsortedright is empty print ("Inside loop", sortedleft, sortedright) if sortedleft and ((not sortedright) or sortedleft[0] < sortedright[0]): sortedlist.append(sortedleft.pop(0)) else: sortedlist.append(sortedright.pop(0)) print ("Sorted list", sortedlist, sortedleft,sortedright) return sortedlist #mergesort def main(): cli = argparse.ArgumentParser() cli.add_argument("--list",nargs="*",type=int,default=[1,2,3,4]) args = cli.parse_args() msort = MergeSort() msort.mergesort(args.list) if __name__ == "__main__": main() #MergeSort
true
8ed12fbd48c437b2baf749207976fb08a2d5004a
suzytoussaint98/tp-Geometrie2D
/dossier_code/Polygon.py
814
4.15625
4
class Polygon: """ A class used to represent a Polygon Attributes ---------- x_list : list horizontal coordinates of Polygon points y_list : list vertical coordinates of Polygon points Methods ------- add_point(point) Add the provided point to the polygon draw() Draw the polygon """ def __init__(self): self.x_list = [] self.y_list = [] def add_point(self, point): """ Add a point to the Polygon Parameters ---------- point : Point The point to add to the Polygon """ self.x_list.append(point.x) self.y_list.append(point.y) def draw(self): """ Draw the polygon """ plt.plot(self.x_list, self.y_list)
true
b72973deca28929df927b32123d96310d85888f2
Sudoka/CSE-231
/10/turtle_example.py
1,240
4.1875
4
# lkd: 04/10. # a couple of functions to illustrate turtle graphics # these functions do not perform error checking. # call them with reasonable arguments, or suffer the consequences. import turtle def drawSquare(pen, size = 50, fillcolor=""): """draw a square of given size using pen; fill it if fillcolor is provided""" pen.pencolor("black") # square will be outlined in black if fillcolor: pen.fillcolor(fillcolor) # set the fill color and pen.fill(True) # begin filling #draw the square pen.down() for i in range(4): pen.forward(size) pen.left(90) pen.fill(False) # end filling def drawCircles(pen, size = 50, num = 6): """draw num circles with given radius using pen""" colorlst = ["#FF0000", "#FFCC00", "#CC0066", "#996666", "#9900CC",\ "#6600FF", "#33FFFF", "#330099", "#003300", "#000099"] rotation = 360/float(num) pen.down() # be sure the pen is down for i in range(num): # draw circles with colors from colorlst pen.pencolor(colorlst[i%len(colorlst)]) pen.circle(size) pen.left(rotation)
true
28f9fab3e39f901aa33dab1b59a11f80193058cb
pankaj-lewagon/mltoolbox
/mltoolbox/clean_data.py
534
4.15625
4
import string def remove_punctuation(text): for punctuation in string.punctuation: text = text.replace(punctuation, '') return text def lowercase(text): text = text.lower() return text def remove_num(text): num_remove = ''.join(word for word in text if not word.isdigit()) return num_remove if __name__ == '__main__': print remove_num("121212 Pankaj 121212") print remove_punctuation("12121?????2 Pank2!!!aj 121212????") print lowercase("12121?????2 Pank2!!!aj XXXXXXXXX121212????")
true
5e53ab4f41caab7253868ca8b0b46d897ca04b95
Kamonphet/BasicPython
/PythonOOP/basic07.py
2,479
4.21875
4
# Inheritance การสืบทอดคุณสมบัติ => การสร้างสิ่งใหม่ขึ้นด้วยการสืบทอดหรือรับเอา # คุณสมบัติบางอย่างมากจากสิ่งเดิมที่มีอยู่แล้วโดยการสร้างเพิ่มเิมจากสิ่งที่มีอยู่แล้ว # แบ่งเป็น superclass และ subclass # superclass # super() => เรียกใช้งานคุณสมบัติในsuperclass # class Employee: class Employee: #class variable _minSalary = 12000 _maxSalary = 50000 def __init__(self,name,salary,department): # instance variable self._name = name #protected self.__salary = salary self.__department = department # protected medthod def _showdata(self): print("complete attribute") print("name = {}".format(self._name)) print("salary = ",self.__salary) print("Department = ",self.__department) def _getIncome(self) : return self.__salary*12 #แปลง obj เป็น str def __str__(self) : return ("EmployeeName = {} , Department = {} , SalaryPerYear = {}".format(self._name,self.__department,self._getIncome())) # subclass # class name(Employee): class Accounting(Employee): __departmentName = "แผนกบัญชี" def __init__(self,name,salary): super().__init__(name,salary,self.__departmentName) class Programmer(Employee): __departmentName = "แผนกพัฒนาระบบ" def __init__(self,name,salary): super().__init__(name,salary,self.__departmentName) # super()._showdata() class sale(Employee): __departmentName = "แผนกขาย" def __init__(self,name,salary): super().__init__(name,salary,self.__departmentName) # สร้างวัตถุ obj1 = Employee("phet",50000,"Teacher") obj2 = Employee("Flim",100000,"Bussines") obj3 = Employee("Family",150000,"House") account = Accounting('phet',40000) programmer = Programmer('flim',60000) Sale = sale('love',1000) #เรียกใช้ # print(Employee._maxSalary) # print(account._minSalary) # account._showdata() # print("Income = {}".format(account._getIncome())) # print(account.__str__())
false
b5b2a7a6f7fff4329242694370b2166d497df502
Kamonphet/BasicPython
/54Exception.py
2,740
4.1875
4
# Exception การจัดการข้อผิดพลาด # การที่โปรแกรมของเรานั้นผิดพลาดแล้วเราต้องหาวิธีในการแก้ปัญหาเพื่อให้แสดงออกมาให้ผู้ใช้รู้ว่าผิดพลาดอย่างไร # try exect ''' try: คำสั่งรันโปรแกรมปกติ except: คำสั่งที่ทำงานตอนโปรแกรมมีข้อผิดพลาด ''' try: number1 = int(input("enter number 1 :")) number2 = int(input("enter number 2 :")) result = number1/number2 print(result) except ValueError: print("ต้องป้อนตัวเลขเท่านั้นถึงจะหารได้") except ZeroDivisionError: print("ห้ามหารด้วยเลข 0") except TypeError: print("ชนิดข้อมูลไม่ถูกต้อง") # exection หลาย ๆ เหตุการณ์ / \ # valueError => ค่าผิดพลาด | # ZeroDivision => ผิดพลาดที่เลข 0 | # TypeError => ชนิดข้อมูลไม่ตรงกัน | # ลดรูป exection # except Exception as e: # print(e) # else : #มาสามารถใส่ else ได้สำหรับถ้าไม่มีช้อผิดพลาด # print("จบโปรแกรม") # finally คล้าย else แต่จะทำงานได้ทั้งตอนผิดพลาดและไม่พิดพลาดของโปรแกรม finally: print("ทำงานต่อไป...") # ทำงานร่วมกับloop while while True: try: name=input("ป้อนชื่อผู้ใช้โปรแกรม :") if name == "phet" : print("มีชื่อนี้ในระบบแล้ว") number1 = int(input("enter number 1 :")) number2 = int(input("enter number 2 :")) if number1 == 0 and number2 == 0: break if number1 < 0 or number2 < 0: raise Exception("ไม่สามารถป้อนค่าติดลบได้") result = number1/number2 print(result) except Exception as e: print(e) finally: print("ทำงานต่อไป...") # raise กำหนดข้อผิดพลาดเอง ต้องเขียนภายใต้ try
false
4620aedfda4e5c810faf6ef0cb614239b608dd5c
ankit0777/LinkedListSolvedQuestions
/Delete Middle of Linked List.py
562
4.1875
4
# Given a singly linked list, delete middle of the linked list. For example, if given linked list is 1->2->3->4->5 then linked list should be modified to 1->2->4->5. def deleteMid(head): ''' head: head of given linkedList return: head of resultant llist ''' temp1=head temp2=head temp3=head while(temp2 and temp2.next): temp1=temp1.next temp2=temp2.next.next while(temp3.next != temp1): temp3=temp3.next temp3.next=temp1.next temp1.next=None return head #code here
true
c6f4b1723e8a2794d5dd8ef057bfef1822819ae8
texaygames/py_basics
/SelfRechner.py
1,063
4.125
4
def calculate(): ope = input(''' Please type in the math operation you would like to complete: + for addition - for subtraction * for multiplication / for division ''') num_1 = int(input("Please Type in your first number: ")) num_2 = int(input("Please Type in your second number: ")) if ope == "+": print("{} + {} = ".format(num_1, num_2)) print(num_1 + num_2) elif ope == "-": print("{} - {} = ".formate(num_1, num_2)) print(num_1 - num_2) elif ope == "*": print("{} * {} = ".formate(num_1, num_2)) print(num_1 * num_2) elif ope == "/": print("{} / {} = ".formate(num_1, num_2)) print(num_1 / num_2) else: print("You have not typed in a valid number") again() def again(): calc_again = input("Möchtest du noch einmal rechnen? [J/N]") if calc_again.upper() == "J": calculate() elif calc_again.upper() == "N": print("Bis Balt! :)") else: again() calculate()
false
df1af634cd9044bbc31c5b281832aa96f2ec2471
skinder/Algos
/PythonAlgos/Done/power_of_2.py
1,025
4.125
4
''' https://leetcode.com/problems/power-of-two/ Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: true Explanation: 20 = 1 Example 2: Input: 16 Output: true Explanation: 24 = 16 Example 3: Input: 218 Output: false ''' class Solution(object): def isPowerOfTwo(self, n): if n <= 0: return False x = str(bin(n))[2:] if x.count("1") > 1: return False else: return True def isPowerOfFour(self, num): if num > 0: binary = str(bin(num))[2:] if binary.count('1') == 1: if binary.count('0') % 2 == 0: return True return False def isPowerOfThree(self, n): if n <= 0: return False while n != 1: if n % 3 != 0: return False n = n / 3 return True a = Solution() print a.isPowerOfTwo(16) print a.isPowerOfFour(16) print a.isPowerOfThree(9)
true
a7f8495913cc7cef65a82ea1cd791c4ab359e3c0
Szoul/Automate-The-Boring-Stuff
/Chapter 2/NumberGuessingGame.py
2,633
4.15625
4
#create a game where you have to guess a number; it has to be in betweeen 2 #random numbers; the Programm should give you a hint whether it is lower or # higher than the inserted number; if the correct number is typed in, show the # number of tries before completion of the game #Bonuspunkte: Hinweis falls die Zahl "viel größer/kleiner" ist (über 100,30,... entfernt) #Zielzahl ist zwischen -999 und 999 import random import os while True: goal_number = random.randint(-999,999) lower_end = random.randint(-1000,1000) upper_end = random.randint(-1000,1000) player_try_counter = 0 while lower_end >= goal_number: lower_end = random.randint(-1000,1000) while upper_end <= goal_number: upper_end = random.randint(-1000,1000) print("Welcome to Guessing the Number") print("The number you are looking for is in between " + str(lower_end) + " and " + str(upper_end)) while True: print ("Type in your guess") player_guess = input() try: int(player_guess) #also goes to except if "player_guess" is a float - why? except ValueError: print ("Please enter an Integer") print ("") continue # if not (float(player_guess)).is_integer(): # dont need this because of upper problem # print("Please enter an Integer") # continue player_guess = int(player_guess) player_try_counter += 1 if player_guess < goal_number: if player_guess + 100 < goal_number: print("Your number is way too low") elif player_guess + 30 < goal_number: print("Your number is too low") else: print("Your number is a just a bit too low") if player_guess > goal_number: if player_guess -100 > goal_number: print("Your number is way too high") elif player_guess - 30 > goal_number: print("Your number is too high") else: print("Your number is just a bit too high") if player_guess == goal_number: print("Congratulations! You found the right number!") print("It took you " + str(player_try_counter) + " tries to complete the game") break continue if not input("If you want to restart type in 'restart'. Otherwise press Enter to exit") == 'restart': break os._exit(0) # hwo to exit shell with this command? - os._exit(0) did reopen new shell?
true
104e756b9b40a138154e1c2f95b532c717253cec
Szoul/Automate-The-Boring-Stuff
/Chapter 10/selective_copy.py
1,808
4.125
4
#! python 3.8.3 # selective_copy.py - copys files of a certain suffix from the original folder(and its subfolders) to another directory # TODO # Loop # walk through a directory-tree with os.walk # regex to select files with the named suffix # shutil.copy() files to new directory # optional: make it a function that recieves the original and the new directiory, as well as the suffix as an argument def copy_suffixfiles_to_folder (original_directory, goal_directory, suffix): import os, shutil, re from pathlib import Path regex = re.compile(rf"(.*?)\.{suffix}$") for foldername, subfoldername, filename in os.walk(original_directory): # filename is a list of filenames in current folder, if current folder is empty it will return an empty list for files in filename: match = regex.search(files) if match != None: filename_to_move = match.group() foldername = foldername.replace("\\","/") #convert forward slashes to backwards slashes in order to use with the Path module, because Windows path system is just perfect file_to_move_path = Path(f"{foldername}/{files}") # print (file_to_move_path) # print (goal_directory) shutil.copy(file_to_move_path, goal_directory) print (f"copying <{files}> to goal directory") from pathlib import Path suffix = "txt" original_directory = Path("C:/Users/Acer PC/Desktop/Python/Automate-The-Boring-Stuff/Chapter 10/dir1") goal_directory = Path ("C:/Users/Acer PC/Desktop/Python/Automate-The-Boring-Stuff/Chapter 10/dir2/selective_copy_goal_dir") copy_suffixfiles_to_folder(original_directory, goal_directory, suffix)
true
9ad347bc8ccfdb7dce8a630dfe66fea8d327b9a2
Szoul/Automate-The-Boring-Stuff
/Chapter 5/dictionary_test2_what_happens_if_2keys_are_the_same.py
591
4.15625
4
dict1 = {"key1":"value1", "key1":"value2"} dict2 = {1:1,1:2} for x in range(0): print (dict1) print (dict1.get("key1")) print (dict2) print (dict2.get(1)) list1 = list(dict1.items()) print (list1) if "value1" in dict1.values(): print ("value1") else: print ("not value 1") #Python doesnt support duplicate keys in a dictionary #it seems like the two keys of the same name and its value is overwritte by the second one # Workaround: use a single key and as a value make a list of all the items belonging there #for example: dict1 = {"key1":["value1","value2"]}
true
867028725b2664b74ad3d17d802640928dbd1642
Szoul/Automate-The-Boring-Stuff
/Chapter 7/Regex_Version_of_strip().py
1,448
4.5
4
#! python 3.8.3 #Regex_Version_of_strip().py: imitate the strip() function including a regex ''' Project description: Write a function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second argument to the function will be removed from the string. ''' # strip([text], [characters to be removed]) > if no 2nd argument, remove whitespace #regex to detect whitespace(\s) #replace (regex.sub([substitute],[text])) (substitute = "replace with nothing") def regex_strip (text, remove_text="\s*"): import re start_regex = re.compile(rf"^{remove_text}") end_regex = re.compile(rf"{remove_text}$") text = start_regex.sub("", text) text = end_regex.sub("", text) return text test_text = "\n\nEine Kugel läuft um die Ecke und fällt um. " #regex_strip(text, remove_text) seems to work the same way as text.strip(remove_text) print ("..." + test_text + "\n_______________________________________________") print ("__" + test_text.strip("\n\nEine") + "__") print ("\n\n") print ("__" + regex_strip(test_text, "\n\nEine") + "__") print ("\n_______________________________________________\n") print ("__" + test_text.strip() + "__") print ("\n\n") print ("__" + regex_strip(test_text) + "__")
true
bd7c2ae7710ea045235c97557a0b59128677f464
GraphicalDot/Assignments
/assignment_1_nov_2014.py
2,970
4.21875
4
#!/usr/bin/env python def Upto_you(): """ Write the most fancier 10 if, else statements, Its upto you """ pass def sort_list(): """ 1.Prepare a list of all alphabets 2.Prepare a list by shuffling them and joining them without spaces 3.From this list which will have 20 elements, prepare a list of dictionaries with key as 1 to 20 and values as the above mentioned randomly joined alphabets. 4.sort this list in descending order according to the value Hint: Output is like [{1: 'afmeniyhqvkdxrlocswgjpbtu'}, {2: jdtprombhueifnygskvclwxqa'}, ....so on] """ pass def another_sort_list(): """ From the update of sort_list() Step2: Update every dictionary present in the list by removing last three elements from each value Hint [{1: 'afmeniyhqvkdxrlocswgjp'}, {2: jdtprombhueifnygskvclw'}, ....so on] {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17, 'p': 16, 's': 19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26} Then sum the values according to the above mentioned dictionary The above mentioned dictionary is just for your reference, dont copy that and make your own code Hint: Output is like [{1: 'afmeniyhqvkdxrlocswgjpbtu', "sum": "282"}, {2: jdtprombhueifnygskvclw', "sum": "283"}, ....so on] """ new_dict = dict() #Preparing the list like this {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7 and so on [new_dict.update({element[1]:element[0]})for element in zip(range(1,27), map(chr,range(ord("a"),ord("z")+1)))] h = lambda x : sum([new_dict[element] for element in x ]) [element.update({"sum": h(element.values()[0])}) for element in shivam_dict] return shivam_dict def lambda__(): """ should returns a output of a list which will not have prime numbers upto 1000 """ pass def and_or(): """ returns a list which will not have any number divisible by [18, 19, 21, 99, 45] Original list will have 1, 10000 """ pass def exception_handling(): """ Handle exception After handling this exception raise your own excpetion which should only print the error messege as the output """ pass def open_file(file_path): """ Print the contents of the file ying on file_path Now opena new file in your home directory, Write something in that file and then mv that file into this current directory Hint: os or subprocess module """ def convert_string_to_list(string): """ Convert this string into a list string = "HEY_MAN_WHAT_the_fuck_is_going_on" output = ["Hey", "man", "what", "the", "fuck", "is"m "going", "on"] The convert this list into string = "hey man what the fuck is going on"" Sonvert this string into string = "hey man, everything is great" Everything what you have done shall be done in one line with the help of list comprehensions """ pass if __name__ == "__main__":
true
2672f5d4e0a83ccdc7630078ce8a7ffca18723e0
MamvotaTake/Python-Projects
/NATO-alphabet-start/main.py
1,011
4.125
4
# student_dict = { # "student": ["Angela", "James", "Lily"], # "score": [56, 76, 98] # } # # #Looping through dictionaries: # for (key, value) in student_dict.items(): # #Access key and value # pass # student_data_frame = pandas.DataFrame(student_dict) # # #Loop through rows of a data frame # for (index, row) in student_data_frame.iterrows(): # #Access index and row # #Access row.student or row.score # pass # # # Keyword Method with iterrows() # # {new_key:new_value for (index, row) in df.iterrows()} import pandas data = pandas.read_csv("nato_phonetic_alphabet.csv") phonetic_dict = {row.letter: row.code for (index, row) in data.iterrows()} print(phonetic_dict) def generate_phonetic(): user_word = input("Enter word: ").upper() try: output = [phonetic_dict[letter] for letter in user_word] except KeyError: print("Sorry, Only letters in the alphabet please") generate_phonetic() else: print(output) generate_phonetic()
false
ac4556965380d09b8ec0bd9aa2bdb84b71054ace
hermanoaraujo/python
/Matriz/matriz-transposta.py
605
4.5
4
''' Uma matriz transposta é a matriz que se obtém da troca de linhas por colunas de uma dada matriz. Assim, dada uma matriz C de ordem m x n, a matriz transposta dela será representada por Ct de ordem n x m onde cada elemento de Ct [i,j] = C [j,i]. ''' a=[] lin=2 col=3 #leitura da matriz for i in range(lin): linha=[] for j in range(col): n=int(input('digite numero: ')) linha.append(n) a.append(linha) #Gerando a matriz transposta at=[] for i in range(col): linha=[] for j in range(lin): linha.append(a[j][i]) at.append(linha) print(a) print(at)
false
24cfab559337edd63565b7c1c0e874447fdc2f1f
hermanoaraujo/python
/Funcoes/calculo-media-vetor.py
1,061
4.28125
4
''' Escreva um programa que leia N números inteiros (máximo 20) e armazene em um vetor X. Calcule a média dos elementos do vetor e informe quantos elementos estão abaixo da média do conjunto. Crie uma função que faça a leitura dos elementos de um vetor; uma função que retorne a média dos elementos de um vetor; e, finalmente, outra função que receba um vetor e um número (float), e retorne quantos elementos do vetor estão abaixo desse número. ''' def media(vetor): tam = len(vetor) soma = 0 for i in range(tam): soma += vetor[i] media = soma/tam return media def lerVetor(n): vetor = [] for i in range(n): n = int(input("Digite o numero "+str(i)+" : ")) vetor.append(n) return vetor def abaixoMed(vetor,media): tam = len(vetor) abaixo = [] for i in range(tam): if (vetor[i]<media): abaixo.append(vetor[i]) return abaixo vetor = lerVetor(3) media = media(vetor) print("Meu vetor é: ",vetor) print("A media do Vetor é: ",media) print("Abaixo da media é: ",abaixoMed(vetor,media))
false
1651097f34f267c20ee394a62c01491d86cadb68
hermanoaraujo/python
/Arquivos/ler-arq-string.py
514
4.3125
4
''' Escreva um programa que leia do teclado o nome de um arquivo texto e uma string, abra o arquivo e inclua no final dele a string lida. José Hermano ''' #Ler o nome do arquivo nome_arq = input("Digite o nome do arquivo: ") #Ler uma string string = str(input("Digite um texto: ")) #Abre o arquivo com a opção 'a' de adição arquivo = open(nome_arq,'a') #Adiciona a string no final do arquivo arquivo.write(string+"\n") #fecha o arquivo arquivo.close() print(string+" adicionado no final do arquivo: "+nome_arq)
false
6e6e3868a8d8a24df89f650839e1cfe70f3061a9
joaocarlos-git/cursopython
/calc_exercicio3.py
2,080
4.40625
4
# Crie uma calculadora com quatro operações, div, sub, som, mult, que pergunte ao usuario #qual operação ele deseja fazer e peça os numeros que serão calculados, em seguida #mostre o resultado da operação na tela, sendo que as funções utilizadas no programa #estejam em um módulo separado do arquivo principal. import matematico continuar = "" while True: continuar = input("\nDeseja calcular? S/N: ") if continuar.lower() == "n" or continuar != "s": break else: try: operacao = input("Qual operação deseja fazer? Digite\n1 para soma\n2 para subtraçao" "\n3 para multiplicaçao\n4 para divisão\n") if operacao == "1": num1 = int(input("Digite um numero: ")) num2 = int(input("Digite o segundo numero: ")) print("Seu resultado é: " + str(matematico.soma(num1,num2))) print("") elif operacao == "2": num1 = int(input("Digite um numero: ")) num2 = int(input("Digite o segundo numero: ")) print("Seu resultado e: " + str(matematico.sub(num1,num2))) print("") elif operacao == "3": num1 = int(input("Digite um numero: ")) num2 = int(input("Digite o segundo numero: ")) print("Seu resultado e: " + str(matematico.mult(num1,num2))) print("") elif operacao == "4": num1 = int(input("Digite um numero: ")) num2 = int(input("Digite o segundo numero: ")) print("Seu resultado e: " + str(matematico.div(num1,num2))) print("") else: print("\nVocê digitou uma opção inválida, tente novamente.\n") except: print("\nOcorreu algum erro, verifique a sua operação, como por exemplo, \nse houve tentativa" " de divisão por zero, pois não é possível dividir por zero. ") print("\nObrigado por usar a calculadora de João Carlos!")
false
a17ee9f753f0e9284365c3169dd2c7d0dfe9ef57
anandaug30/Python_Code_Snippet
/basic/recursive_fibonacci_number.py
1,818
4.53125
5
from functools import lru_cache def recursive_fibonacci_number(n): """" basic Fibonacci number function""" if n == 1 or n == 2: return 1 elif n > 2: return recursive_fibonacci_number(n - 1) + recursive_fibonacci_number(n - 2) fibonacci_cache = {} def recursive_fibonacci_number_cache(n): """ implementing memoization explicitly if we have cached the value, then return it 0 """ if n in fibonacci_cache: return fibonacci_cache[n] # compute the Nth term if n == 1 or n == 2: value = 1 elif n > 2: value = recursive_fibonacci_number_cache(n - 1) + recursive_fibonacci_number(n - 2) # Cache the value and return it fibonacci_cache[n] = value return value @lru_cache(maxsize=1000) def recursive_fibonacci_number_lru(n): """Implement memorization using LRU""" if type(n) != int: raise TypeError("n must be a integer, provided {}".format(n)) if n < 1: raise TypeError("n must be a positive integer") if n == 1 or n == 2: return 1 elif n > 2: return recursive_fibonacci_number_lru(n - 1) + recursive_fibonacci_number_lru(n - 2) """ # using basic Fibonacci number for number in range(1, 39): #print(number, ";", recursive_fibonacci_number_cache(number)) print(recursive_fibonacci_number(number+1)/recursive_fibonacci_number(number)) # using explict memo for number in range(1, 39): print(number, ";", recursive_fibonacci_number_cache(number)) print(recursive_fibonacci_number_cache(number+1)/recursive_fibonacci_number_cache(number)) """ # using functool lru_cache for number in range(1, 500): print(number, ";", recursive_fibonacci_number_lru(number)) # print(recursive_fibonacci_number_lru(number+1)/recursive_fibonacci_number_lru(number))
false
b28af486761cee99d68879c0f78539af878d10a6
muffinsofgreg/mitx
/6.2/yieldall_iter.py
377
4.25
4
def powerset(items): """ Returns all the subsets of this set. This is a generator. """ if len(items) <= 0: yield [] else: for item in powerset(items[1:]): yield [items[0]] + item yield item items = ["bucket", "driver", "mouse", "hatchet", "gourd", "bottle"] new = powerset(items) for item in new: print(item)
true
434e0e8d87fe692e98afa6d1f2b29a8eac0be885
ssquirrel0911/Python-Projects
/SamanthaSquirrelAssignment20-11-13-2018PatientChargesFunction.py
2,753
4.34375
4
#Samantha Squirrel #samantha.squirrel001@albright.edu #Assignment 20 Chapter 10 Programming Exercise 6; Patient Charges import time from SamanthaSquirrelAssignment20PatientClass import Patient from SamanthaSquirrelAssignment20ProcedureClass import Procedure def main(): patient = makePatientList() procedure = makeProcedureList() def makePatientList(): #Creates empty list patientChart = [] #Adds 3 Patient objects to the list #User will input data for all 3 patients for count in range(1, 4): #Get patient data print("Patient " + str(count) + ":") patientFullName = input("Enter the patient's full name: ") patientFullAddress = input("Enter the patient's full address: ") patientPhoneNumber = int(input("Enter patient's phone number: ")) patientEmergencyContact = input("Enter patients emerhency contact with name/number: ") print() #Creates a new Patient object in memory #Assigns to patient variable patient = Patient(fullName, fullAddress, phoneNumber, emergencyContact) #Adds objects to the list patientChart.append(patient) #returns list return patientChart def makeProcedureList(patient, ): #Creates empty list procedureChart = [] #Adds the Procedures to the list #User will input for all 3 patients and procedures for count in range(1, 4): #Get procedure data print("Procedure " + str(count) + ":") procedureProcedureName = input("Enter the name of procedure: ") procedureDateOfProcedure = input("Enter the patient's procedure date: ") procedurePractitioner = input("Enter the patient's practitioner: ") procedureCharge = float(input("Enter the cost of the procedure: $ ")) #creates a new Procedure object in memory #Assigns procedure variable procedure = Procedure(procedureName, dateOfProcedure, practitioner, charge) #Adds objects to the list procedureChart.append(procedure) #returns list return procedureChart #The display list function accepts a list containing all the objects as an argument #and displays stored data def displayList(patientChart, procedureChart): for item in patientChart: print(item.getFullName()) print(item.getFullAddress()) print(item.getPhoneNumber()) print(item.getEmergencyContact()) print() for items in procedureChart: print(items.getProcedureName()) print(items.getDateOfProcedureName()) print(items.getPractitioner()) print(items.getCharge()) print() main() time.sleep(3)
true
8408e30c79142ea2f4b46dccc695f89bfc1c05a1
ssquirrel0911/Python-Projects
/SamanthaSquirrelLabAssignment9-18-2018.py
2,678
4.21875
4
#Samantha Squirrel #samantha.squirrel001@albright.edu import time #Lab assignments Programming Exercises #Execise 1 dayOfWeek = int(input("Input a number in the range of 1 through 7:", )) #User should put in a number in the range of 1 through 7 if dayOfWeek == 1: print("Monday") elif dayOfWeek == 2: print("Tuesday") elif dayOfWeek == 3: print("Wednesday") elif dayOfWeek == 4: print("Thursday") elif dayOfWeek == 5: print("Friday") elif dayOfWeek == 6: print("Saturday") elif dayOfWeek == 7: print("Sunday") else: print("The number you input cannot be recogonized " \ "because there are only 7 days in a week.") #Exercise 2 lengthOfRectangle1 = float(input("What is the length of your first rectangle?", )) #User will put in the first rectangle length widthOfRectangle1 = float(input("What is the width of your first rectangle?", )) #User will put in the first rectangle width lengthOfRectangle2 = float(input("What is the length of your second rectangle?", )) #User will put in the second rectangle length widthOfRectangle2 = float(input("What is the width of your second rectangle?", )) #User will put in the second rectangle width areaOfRectangle1 = lengthOfRectangle1 * widthOfRectangle1 print("The area of your first rectangle is: ", areaOfRectangle1) areaOfRectangle2 = lengthOfRectangle2 * widthOfRectangle2 print("The area of your second rectangle is:", areaOfRectangle2) if areaOfRectangle1 > areaOfRectangle2: print("The area of your first rectangle is greater than your second rectangle.")#Will let user know the first rectangle area is bigger than the second elif areaOfRectangle2 > areaOfRectangle1: print("The area of your second rectangle is greater than your second rectangle.") #Will let user know the second rectangle area is bigger than the first elif areaOfRectangle1 == areaOfRectangle2: print("The area of both your rectangles are the same.") else: print("You did a succesful job with inputting your values.") #Positive feedback for the user #Exercise 3 ageOfUser = int(input("What is your age?", )) #User will input their age if ageOfUser <= 1: print("You are an infant.") #Will let user know if they are an infant elif ageOfUser >= 1 or 1 <= 13: print("You are a child.") #Will let user know if they are a child elif ageOfUser >= 13 or 13 <= 20: print("You are a teenager.")#Will let user know if they are an teenager elif ageOfUser >= 20: print("You are an adult.")#Will let user know if they are an adult else ageOfUser <= 0: print("You can't be any age less than 0.") #Will let user know they're not born yet time.sleep(3)
true
7599c5fe94c1f9aea7b4ca2bc2627db2cb525344
ssquirrel0911/Python-Projects
/SamanthaSquirrelAssignment20-11-13-2018RetailFunction.py
1,714
4.375
4
#Samantha Squirrel #samantha.squirrel001@albright.edu #Assignment 20 Chapter 10 Lab Programming Exercise 5; Retail Item #RetailItem function import time from SamanthaSquirrelAssignment20RetailClass import RetailItem def main(): #Creates a list for retail item retailItem = makeList() #Displays data in a list print("This is the data that is entered: ") displayList(retailItem) #makeList function ets data from the user for 3 retail items #Function will return a a list of retail objects containing the data def makeList(): #Creates empty retailItemChart = [] #Adds 3 RetailItem objects to the list #User will input a data for all 3 retail items print("Enter data for 3 retail products.") for count in range(1, 4): #Get retail item data print("Item " + str(count) + ":") retailItemItem = input("Enter retail product: ") retailItemUnits = int(input("Enter the number of units brought: ")) retailItemPrice = float(input("Enter the item's price: ")) print() #Creates a new RetailItem object in memory #and assigns it to retailItem variable retailItem = RetailItem(retailItemItem, retailItemUnits, retailItemPrice) #Adds objects to the list retailItemChart.append(retailItem) #Returns list return retailItemChart #The displayList function accepts a list containing the objects as an argument #and displays store data def displayList(retailItemChart): for item in retailItemChart: print(item.getItem()) print(item.getUnits()) print(item.getPrice()) print() main() time.sleep(3)
true
42f3ab7a52a8aeba636bfbe2c2500de45876eb3d
Coreyh2/game-assignment
/game assignment.py
1,727
4.21875
4
import time def displayIntro(): print ('You are trapped in a maze, each passageway has a set of doors') print ('you need to find a way out') print ('if you choose the wrong path') print ('you fall into a trap door, and can never come out.') print def chooseDoor(): door = '' while door != '1' and door != '2': print ('Which Door will you Pick? (1 or 2)') door = raw_input() return door def chooseDoor2(): door = '' while door != 'A' and door != 'B': print ('Which Door will you Pick? (A or B)') door = raw_input() return door def chooseDoor3(): door = '' while door != 'C' and door != 'D': print ('Which Door will you Pick? (D or C)') door = raw_input() return door def checkDoor(chooseDoor): print ('You approach the Door...') time.sleep(2) print ('The Exitment Growing...') time.sleep(2) print ('You Open The door and...') print time.sleep(2) def option1(): door = '1' if chooseDoor == str(door): print("You find a empty room") print("Please select one of the doors") chooseDoor2() doorA = raw_input() else: print("You Find $5,000 and more doors") print("Now please select door A or B") chooseDoor2() doorA = raw_input() if chooseDoor == str(doorA): print("You find $10,000 ") print("Please select another door") else: print("You find another empty room") print("Now please select another door") if __name__ == "__option1__": option1() option1() def main(): playAgain = 'yes' while playAgain == 'yes' or playAgain == 'y': displayIntro() doorNumber = chooseDoor() checkDoor(doorNumber) print ('Do you want to play again? (yes or no)') playAgain = raw_input() if __name__ == "__main__": main()
true
468151db2249c3d8f58b61b193444e167a61383a
amber21mizuno/SpeedLimit
/nguyenSpeedLimit.py
2,499
4.125
4
#File: nguyenSpeedLimit.py #Project: CSIS2101 - Assignment 3 (Final Draft) #Author: Jenny P. Nguyen #History: September 24, 2019 def nguyenSpeedLimit(): #The fine starts off at 0 because it hasn't been determined by the user's input fine = 0 #A greeting from the computer then it askes the 3 questions to determine the speeding fine print("Welcome, User!") print("\n") speedLimit = float(input("Please enter the Speed Limit: ")) print("\n") speedVh = float(input("Please enter the Speed of the Vehicle: ")) print("\n") cOrSZone = input("Construction or School Zone?: ") #With the boolean, this is used to define the fine cost based on (speedVh - speedLimit) if (speedVh-speedLimit) < 10 and (speedVh-speedLimit) >0: fine = 120.00 elif (speedVh-speedLimit) < 15 and (speedVh-speedLimit) >= 10: fine = 199.00 elif (speedVh-speedLimit) < 20 and (speedVh-speedLimit) >= 15: fine = 248.00 elif (speedVh-speedLimit) < 30 and (speedVh-speedLimit) >= 20: fine = 286.00 elif (speedVh-speedLimit) >=30: print("\n") print("Court Mandatory. See ya in court!") else: print("\n") print("You are driving within the speed limit. Thank you for driving safely!") #With the boolean, this is part of the fine whether or not it doubles based on the Construction or School zone if cOrSZone == "yes" or cOrSZone == "Yes" or cOrSZone == "Y": cOrSZone2 = fine * 2 print("\n") print("Your total fine is: ${0:0.2f}".format(cOrSZone2)) print("\n") elif cOrSZone == "no" or cOrSZone == "No" or cOrSZone == "N": cOrSZone2 = fine print("\n") print("Your total fine is: ${0:0.2f}".format(cOrSZone2)) print("\n") else: print("Your input is invalid.") #With the boolean, this prints out a message after their total fine if (speedVh-speedLimit) < 10 and (speedVh-speedLimit) >0: print("Slow Down!") elif (speedVh-speedLimit) < 15 and (speedVh-speedLimit) >= 10: print("Drive with caution!") elif (speedVh-speedLimit) < 20 and (speedVh-speedLimit) >= 15: print("You are over speeding!") else: if (speedVh-speedLimit) < 30 and (speedVh-speedLimit) >= 20: print("You are in Danger zone!") nguyenSpeedLimit()
true
46dd92e64d27983b4af810f8f785ee061f65b27d
kirankhandagale1/Python_training
/Excercise2/p2_5.py
222
4.21875
4
# Write a Python program to print alphabet pattern 'E' # used python 3.. for i in range(1, 6): for j in range(1, 6): if(i%2!=0): print("* ",end="") print("* ",end="") print()
false
02340c80ae7afa083e76b5a7024b13f33a2a2788
kirankhandagale1/Python_training
/Excercise2/p2_4.py
251
4.125
4
# Write the program to break the loop if user give n as input, if y continue a=0 while True: c=str(raw_input("Enter your choice 'n'= break, 'y'=continue ")) if(c=='n'): print(" break ") break elif(c=='y'): print(" continue ") continue
true
d9f5ce0ff23c64013e699dcc25defd6bf90df4ea
ChristianBalazs/DFESW3
/palindrome.py
588
4.25
4
#Exercise # A palindrome reads the same forwards and backwards e.g. otto or racecar. # ask a user to type in a string # get then length of the string # reverse the string by reading letter by letter # check the reversed string against the original string # if they are the same it is a palindrome #SOLUTION with Leon : theInput = input("Word here: ") numChars = len(theInput) - 1 varInvert ="" while numChars >= 0: varInvert = varInvert + theInput[numChars] numChars = numChars - 1 if varInvert == theInput: print("Pallindrome") else: print("No")
true
7508f2791e325932c47d606fb4b156f63663af48
paulacaicedo/LaboratorioLibreriasyColeccionesRemoto
/main/laboratory.py
1,323
4.125
4
""" Solución del laboratorio """ from custom_functions import temperature_methods nacional_list = [] hottest_tem_list = [] for i in range(3): departament = input("which is the departament?: ") departament_list = [] for i in range(12): temperature = int(input("Please give me the {} temperature: ".format(i + 1))) departament_list.append(temperature) print(departament_list) z = temperature_methods.desviacion_estandar(departament_list) print("La desviacion estandar es: ", z) x = temperature_methods.calculate_prom(departament_list) print("El promedio es: ", x) nacional_list.append(x) y = temperature_methods.hottest_temperature(departament_list) print("La temperatura mas caliente: ", y) print("Esta en el mes: ", temperature_methods.pos_item(departament_list)) hottest_tem_list.append(y) print( ) print("El promedio nacional es: ", temperature_methods.calculate_prom(nacional_list)) print("La temperatura del promedio del los 3 fue mas caliente: ",temperature_methods.hottest_temperature(nacional_list)) print("El promedio de la temperatura mas caliente es: ", temperature_methods.calculate_prom(hottest_tem_list)) print("La temperatura mas caliente en todo el año: ", temperature_methods.hottest_temperature(hottest_tem_list))
false
55c7f825475c3336e5776f98408259ca5aaef47f
CarterDennis98/LeapYearCalc
/LeapYear.py
2,785
4.3125
4
# This python program will tell you if a year a user enters is a leap year or not import datetime import tkinter as tk from random import randint # Function to check if a number can be cast to int def IsInt(x): try: int(x) return True except ValueError: return False # Function to check current year def GetYear(): # Get the current year from the system clock sysTime = datetime.datetime.now() currentYear = sysTime.year t1.delete(0, len(t1.get())) t1.insert(0, currentYear) # Function to get a random year def RandYear(): year = randint(0, 10000) t1.delete(0, len(t1.get())) t1.insert(0, year) # Function to clear fields def ClearFields(): t1.delete(0, len(t1.get())) lbl3.config(text = "") # Function to check if input is a leap year def IsLeap(): year = t1.get() if(IsInt(year)): year = int(year) # Check the user's year to make sure it's valid before checking if it's a leap year if(year >= 0): if(year % 4 == 0): if(year % 100 == 0): if(year % 400 == 0): lbl3.config(text = "YES", font = ("Bold", 20), fg = "green") else: lbl3.config(text = "NO", font = ("Bold", 20), fg = "red") else: lbl3.config(text = "YES", font = ("Bold", 20), fg = "green") else: lbl3.config(text = "NO", font = ("Bold", 20), fg = "red") else: lbl3.config(text = "Invalid Input", font = ("Bold", 20), fg = "red") else: lbl3.config(text = "Invalid Input", font = ("Bold", 20), fg = "red") # GUI window window = tk.Tk() window.title("Leap Year Calculator") window.geometry("400x250+10+10") window.resizable(width = False, height = False) # Label for year lbl1 = tk.Label(text = "Year:") lbl1.place(x = 50, y = 75) # Text box to enter the year t1 = tk.Entry(bd = 3) t1.place(x = 100, y = 75) # Button to use current year btn1 = tk.Button(text = "Use Current Year", command = GetYear) btn1.place(x = 250, y = 40) # Button for random year between 0 and 10,000 btn2 = tk.Button(text = "Random Year", command = RandYear) btn2.place(x = 260, y = 70) # Button to find result btn3 = tk.Button(text = "GO!", command = IsLeap) btn3.place(x = 285, y = 100) # Label for result lbl2 = tk.Label(text = "Is it a leap year?") lbl2.place(x = 50, y = 180) # Label for result lbl3 = tk.Label() lbl3.place(x = 150, y = 170) window.bind("<Return>", lambda event = None: btn3.invoke()) # Button to reset fields btn4 = tk.Button(text = "Reset", command = ClearFields) btn4.place(x = 145, y = 100) window.mainloop()
true
48127178ea2b10da71ddb3bdf66bf017cc5a8cc0
ayodejipy/calculator
/calculator.py
935
4.21875
4
''' Python Project: Magical calculator Author: Jegede Ayodeji Inspired by: The Complete Python 3 Course: Begineer to Advanced ''' import re print('Magical Calculator') print("Type 'quit' to exit application") previous = 0 run = True def performMath(): global run global previous equation = "" if previous == 0: equation = input('Enter Equation: ') else: equation = input(str(previous)) if equation == 'quit': print("Logging you out of our calculator!") run = False else: equation = re.sub('[a-zA-Z,.:()" "]','', equation) #use regex to filter user input & tell our program what kind of characters it should accept if previous == 0: previous = eval(equation) #built in function to handle complex mathematical operation from string else: previous = eval(str(previous) + equation) while run: performMath()
true
21f039ce1da546bc233099ab1bdbf7cbd1d4b803
feratur/effective-python-notes
/1_pythonic_thinking/07_enumerate_over_range.py
1,217
4.15625
4
# Item 7: Prefer enumerate Over range from random import randint random_bits = 0 for i in range(32): if randint(0, 1): random_bits |= 1 << i print(bin(random_bits)) # Often, you’ll want to iterate over a list and also know the # index of the current item in the list flavor_list = ['vanilla', 'chocolate', 'pecan', 'strawberry'] for i in range(len(flavor_list)): flavor = flavor_list[i] print(f'{i + 1}: {flavor}') # enumerate wraps any iterator with a lazy generator # enumerate yields pairs of the loop index and the # next value from the given iterator for i, flavor in enumerate(flavor_list): print(f'{i + 1}: {flavor}') # can make this even shorter by specifying the number # from which enumerate should begin counting (1 in this case) # as the second parameter for i, flavor in enumerate(flavor_list, 1): print(f'{i}: {flavor}') # ✦ enumerate provides concise syntax for looping over an iterator and # getting the index of each item from the iterator as you go. # ✦ Prefer enumerate instead of looping over a range and indexing into a sequence. # ✦ You can supply a second parameter to enumerate to specify the number # from which to begin counting (zero is the default).
true
4c2dbdbd53ea06834589f0b75960c90c02b6eb63
MyrinNaidoo12/ComSci
/CSC1015F/Assignmet1/triangle.py
388
4.28125
4
#Program to calculate area #Myrin Naidoo # NDXMYR001 import math a = eval(input("Enter the length of the first side: ")) b = eval(input("Enter the length of the second side: ")) c = eval(input("Enter the length of the third side: ")) s = (a+b+c)/2 area = math.sqrt(s*(s-a)*(s-b)*(s-c)) print("The area of the triangle with sides of length",a,"and",b,"and",c,"is",area , end =".")
false
05eee5ff43902fb33a2c18984252888ebfc1945e
AnjalBam/IWassign-data-types-functions-python
/data_types/9_exchange_fist_last_char.py
277
4.28125
4
""" 9. Write a Python program to change a given string to a new string where the first and last chars have been exchanged. """ sample_str = 'Anjal Bam' def exchange_first_last_chars(word): return word[-1] + word[1:-1] + word[0] print(exchange_first_last_chars(sample_str))
true
b9fef56ae2bbd4516deb5acbf403efe711f97418
AnjalBam/IWassign-data-types-functions-python
/data_types/14_create_html_strings.py
263
4.34375
4
""" 14. Write a Python function to create the HTML string with tags around the word(s). """ sample_str = 'I love programming Python.' sample_tag = 'i' def add_tags(tag, content): return f"<{tag}>{content}</{tag}>" print(add_tags(sample_tag, sample_str))
true
ad8b944d699587929154d0d46589785ee18e2790
AnjalBam/IWassign-data-types-functions-python
/functions/10_even_numbers_from_list.py
381
4.125
4
""" 10. Write a Python program to print the even numbers from a given list. Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9] Expected Result : [2, 4, 6, 8] """ sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] def print_even_numbers(lst): even_list = [] for item in lst: if item % 2 == 0: even_list.append(item) print(even_list) print_even_numbers(sample_list)
true
b34ddc7947e34af54e383a9c62c2ea92afc04f78
AnjalBam/IWassign-data-types-functions-python
/functions/17_if_str_starts_with_char_lambda.py
282
4.1875
4
""" 17. Write a Python program to find if a given string starts with a given character using Lambda. """ sample_str = 'coding' check_if_starts = lambda char: True if char == sample_str[0] else False print(check_if_starts('c')) # True print() print(check_if_starts('d')) # False
true
004a21509f172e5487e2c87f6f130bca6aaf497e
AnjalBam/IWassign-data-types-functions-python
/functions/5_factorial_of_num.py
332
4.34375
4
""" 5. Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument. """ def fact(num): if num > 0: product = 1 for i in range(1, num + 1): product *= i return product else: return None print(fact(5))
true
6336b5856e28ae348b84025d9a6929434b1ff950
AnjalBam/IWassign-data-types-functions-python
/functions/14_sort_dict_lambda.py
259
4.28125
4
""" 14. Write a Python program to sort a list of dictionaries using Lambda. """ name_marks = [ {'name': 'Anjal', 'age': 20}, {'name': 'Rajesh', 'age': 16}, {'name': 'Aman', 'age': 15} ] name_marks.sort(key=lambda x:x['age']) print(name_marks)
false
388fd74deb0e8acd739d09ed4e3db43ee1c27b82
AnjalBam/IWassign-data-types-functions-python
/data_types/23_check_if_e,pty_list.py
275
4.1875
4
""" 23. Write a program to check if the list is empty or not. """ sample_list = [1, 3, 5, 6, 7] # sample_list = [] def check_if_empty(list): if len(list) == 0: return 'Empty List!' else: return 'List Not Empty!' print(check_if_empty(sample_list))
true
d0cf40b3c6253de5c2a6f64d744e527717cc40a3
edwintcloud/cs1.3_exercises
/hash_func.py
383
4.25
4
def hash_str(string): """hash_str uses the djb2 algorithm to compute the hash value of a string http://www.cse.yorku.ca/~oz/hash.html""" hash = 5381 for char in string[1:]: # (hash << 5) + hash is equivalent to hash * 33 hash = (hash << 5) + hash + ord(char) return hash # test result = hash_str("test") print(result) print(hash_str("estt"))
true
714db9bc430a1ae767791440941679d9b96ddc80
ingridl-santos/PLP
/Codebench/lista1/paranteses_balanceado.py
1,296
4.15625
4
#!/usr/bin/python3 """ Uma sequência de parênteses e colchetes é considerada bem-formada caso os parenteses e colchetes correspondentes são fechados na ordem inversa à que foram abertos. Por exemplo: A sequencia "(()())" é bem-formada, pois todos os paresenteses e colchetes são fechados na ordem inversa que foram abertos. Por outro lado, a sequencia ")()(" não é bem formada. Entrada Cada linha da entrada será um caso de teste. Cada caso de teste conterá uma sequência de parênteses, sem espaços. A entrada termina com uma linha contendo a sequência de caracteres '###'. Esse caso não deve ser processado. Saída Para cada caso de entrada, imprima uma linha contendo a palavra SIM ou a palavra NAO, indicando se a sequência está balanceada. Restrições Não use pilha, nem recursão. Entrada: (()()) ()) (()) )( ### Saída: SIM NAO SIM NAO """ entrada = input() while(entrada != '###'): aberto = 0 fechado = 0 for i in (entrada): if i == '(': aberto += 1 if i == ')': fechado += 1 if (aberto > 0): aberto -= 1 fechado -= 1 if aberto == 0 and fechado == 0: print('SIM') else: print('NAO') entrada = input()
false
0c5823b89d67b231091186cbb6c425cdf7b5e7af
ingridl-santos/PLP
/Codebench/lista4/head_tail.py
1,775
4.5
4
#!/usr/bin/python3 """ Faça uma função head(L) que retorna a cabeça da lista L e uma função tail(L) que retorna a cauda da lista L A cabeça da lista é o primeiro elemento da lista. A função hd não precisa funcionar com uma lista vazia. Exemplos: head([1, 2, 3]) deve retornar 1; head([1] deve retornar 1; head([[1,2,3], [4, [5, 6]]]) deve retornar [1, 2, 3] head([]) tem comportamento indefinido. A cauda é uma lista que contém todos os elementos de L, exceto o primeiro. Note que uma lista vazia tem uma cauda vazia. """ import sys def head(L): return L[0] # remova esta linha e insira seu codigo def tail(L): return L[1:] # remova esta linha e insira seu codigo ############################## # Nao modifique o programa daqui para baixo casos = [dict(e=[1, 2, 3, 4], h=1, t=[2,3,4]), dict(e=[[1], [2, 3, 4]], h=[1], t=[[2,3,4]]), dict(e=[[1, 2], 3, 4], h=[1,2], t=[3,4]), dict(e=[[1, 2], [3], [4]], h=[1,2], t=[[3],[4]]), dict(e=[[[1], 2, 3], 3, 4, 5], h=[[1],2,3], t=[3,4,5]), dict(e=[1], h=1, t=[]), dict(e=[[1, 2]], h=[1,2], t=[]), dict(e=[[], 2, 3], h=[], t=[2,3]), dict(e=[[], []], h=[], t=[[]]), dict(e=[[]], h=[], t=[])] for num in range(len(casos)): entrada = casos[num]['e'] h_esperado = casos[num]['h'] t_esperado = casos[num]['t'] saida_h = head(entrada) == h_esperado saida_t = tail(entrada) == t_esperado if saida_h and saida_t: print("Caso #%d: ok!" % num) else: print("Caso #%d: erro" % num) print(" Etrada:", entrada) print(" Saida esperada:") print(" head:", h_esperado) print(" tail:", t_esperado) print(" Saida obtida:") print(" head:", saida_h) print(" tail:", saida_t)
false
3d2aa8178602d6d8cc8ba9d2ddbd38fd06db83d0
ingridl-santos/PLP
/Codebench/lista1/expecto_patronum.py
1,292
4.1875
4
#!/usr/bin/python3 """ No universo do livro Harry Potter, o Expecto Patronum é um feitiço que cria um guardião composto de energia positiva, na forma de um animal prateado, único para cada bruxo. O patrono do personagem principal é um cervo. Escreva um programa que lê uma string representando o nome de um animal e verifica se esse animal é um cervo. Entrada A entrada conterá uma única palavra com no máximo 80 caracteres. A entrada poderá conter letras maiúsculas e minúsculas. Saída 1. Se o patrono for cervo, exiba a mensagem cervo eh patrono do Harry Potter. 2. Caso contrário, exiba a mensagem <entrada> nao eh patrono do Harry Potter, substituindo a expressão <entrada> pela string fornecida como entrada. Entrada : cervo Saída : cervo eh patrono do Harry Potter Entrada : CERVO Saída : CERVO eh patrono do Harry Potter Entrada : asno Saída : asno nao eh patrono do Harry Potter """ def compara_string(str1, str2): for i in range(len(str2)): aux = str2.lower() if(len(str1) != len(str2)): return 1 for i in range(len(str2)): if(str1[i] != aux[i]): return 1 return 0 entrada = input() if(compara_string('cervo', entrada) == 0): print(entrada, 'eh patrono do Harry Potter') else: print(entrada, 'nao eh patrono do Harry Potter')
false
36a886e57528457e63b7c811808660498f3d1fae
asarfraaz/stylk
/arrange.py
725
4.3125
4
"""program to list of random numbers in assending order""" import random def rinput(): """takes a number and generates that no of random list of numbers""" num = int(raw_input('enter number:')) ln = random.sample(range(300,325),num) return ln, num def arrange(l, n): """Arranges highest number in the list at the end of the list""" i = 0; for i in range(0,n-1): if l[i]>l[i+1]: l[i], l[i+1] = l[i+1], l[i] ans = l return ans def main(): """This is main""" l, n = rinput() print 'the random generated list' print l ans = arrange(l, n) print 'the sorted list with largest number in end' print ans if __name__ == '__main__': main()
true
dbb0a138b681dffec4d7350c01cfe5e0a8199d10
asarfraaz/stylk
/user_name.py
641
4.40625
4
"""This is a doc string This program will take the user name and the surname. Then it will give the output on the proper formate and also write the user name in the upper case letters """ def get_input(): first=str(raw_input('Enter ur first name')) last=str(raw_input('Enter ur last name')) return str(first), str(last) def formated_output(first, last): print '-Name:', first.lower(), ',Surname:', last.lower() print '-', first.upper(), last.upper() print '-'*10, '-'*5 print '-', first.capitalize(), ',', last.capitalize() #main first,last=get_input() formated_output(first,last)
true
c5f21dcd39f9483891ec7de1a69c7ef51e5849c7
asarfraaz/stylk
/fibonacci.py
957
4.25
4
"""This is a doc string This program checks if a number is fibonacci number If not, then it will print the closest Fibonacci number to the input number """ def get_input(): """get the input number""" inp = int(raw_input('Enter the number')) return inp def chec_fib(n_n): """cal if the number is true or false""" a_a = 0 b_b = 1 c_c = a_a + b_b while c_c <= n_n: if c_c is n_n: print n_n, 'is a fibonacci number' return c_c a_a = b_b b_b = c_c c_c = a_a + b_b print n_n, 'is not a fibonacci number' d_diff = c_c - a_a x_x = n_n - d_diff y_y = c_c - n_n print d_diff, '-<', n_n, '>-', c_c if x_x > y_y: print c_c, 'is the closest Fibonacii number to', n_n else: print d_diff, 'is the closest Fibonacii number to', n_n if __name__ == '__main__': n_n = get_input() chec_fib(n_n)
false
ccea36072311ed10aad7705c0aa8bd490ea56a00
VenkatalakshmiS/python-cyberfrat
/cyberfrat day 5.py
1,434
4.125
4
l1=[1,2,3,4,5] print(l1) l1=[1,2,3,"Python"] print(l1) l1.append(34) print(l1) l1.insert(3,"Deepa") print(l1) l1.insert(2,"Venkat") print(l1) element="Deepa" print(type(element)) num=5 print(type(num)) l1.insert(3,element) print(l1) print(l1[2]) n1=10 n2=20 n1,n2=n2,n1 print(n1) print(n2) n1=10 n2=20 n3=30 n4=40 n1,n2,n3,n4=n4,n3,n2,n1 print(n1,n2,n3,n4) s1=set(l1) print(s1) l1=[1,2,3,4,5] print(l1.pop()) l1=[1,2,3,"Python"] print(l1.pop()) print(l1) l1=[34,12,78,"Python","deepa"] l1.remove(78) print(l1) val=l1[3] l1.remove(val) print(l1) l1=[34,12,78,"Python","deepa"] for element in l1: if element==78: l1.remove(element) print(l1) l1=[1,2,3,4,5] l2=l1 print(l1.pop()) print(l1) print(l2) l1=[1,2,3,4,5,6,7] #l2=l1.copy #print(l1) #print(l2) #l2=l1.copy() #print(l2) print(l1.pop()) l1=l2[0:2] print(l1) l2=['a','b','c'] l1.extend(l2) print(l1) l1.insert(0,l2) print(l1) l1=l1[0:-2] print(l1) alpha=['b','q','a','t'] alpha.sort() print(alpha) num=[345,7,32,7464,868] num.sort() print(num) #num.clear() #print(num) #del alpha #print(alpha) l1=[1,2,3,4,5,6,7,8] l2=[x for x in l1] print(l2) l2=[x for x in l1 if x%2!=0] print(l2) l2=[x if x%2!=0 else 'even' for x in l1] print(l2) num=[x for x in range(0,101)] print(num) l2=[x for x in num if x%2==0] print(l2)
false
8e67375ab245880493e84eed750a4595ad064dd9
ldbrierley/learn_python
/index.py
822
4.15625
4
import random def get_guess(): while True: try: guess = input("What is your guess: ") int(guess) return guess except: print("That did not work please type an number") the_random_number = random.randint(1,20) print("Welcome to the number guessing game.") print("Guess a number between 1 and 20 and I will tell you if it was to small or too big") number_of_guesses = 0 while True: guess = get_guess() number_of_guesses += 1 print("You have done " + str(number_of_guesses) + " Attempts") if guess == the_random_number: print("correct") break elif guess > the_random_number: print("You guess to high") else: print("You guess to low") score = 100 / number_of_guesses print("score is " + str(score))
true
49bc6b3d989fcf3bb371f93ceaf35539591a2fed
glenonmateus/ppe
/secao12/modulos_customizados.py
800
4.34375
4
""" Módulos Customizados Como módulos Python nada mais são do que arquivos Python, então TODOS os arquivos que criamos neste curso são módulos Python pronto para serem utilizados. # Importando um função específica do nosso módulo from funcoes_com_parametro import soma_impares print(soma_impares([1, 2, 3, 4, 5, 6, 7, 8, 9])) # Importando todo o módulo (temos acesso a todos os elementos do módulo) import funcoes_com_parametro as fcp # Estamos acessando e imprimindo uma variável contida no módulo print(fcp.lista) print(fcp.tupla) print(fcp.soma_impares(fcp.lista)) from map import cidades, c_para_f print(list(map(c_para_f, cidades))) """ import sys sys.path.append('../secao8') from funcoes_com_parametro import soma_impares print(soma_impares([1, 2, 3, 4, 5, 6, 7, 8, 9]))
false
0b8e96a55e86889471b16ad55ed395c901ebdb9c
glenonmateus/ppe
/secao11/debuggando_com_pdb.py
2,593
4.125
4
""" Debuggando com PDB PDB -> Python Debugger # OBS: A utilização do print() para debuggar código é uma prática ruim def dividir(a, b): print(f'a={a}, b={b}') try: return int(a) / int(b) except ValueError: return 'Valor Incorreto' except ZeroDivisionError: return 'Não é possível realizar um divisão por Zero' print(dividir(4, 7)) # Existem formas mais profissionais de se fazer esse 'debug', utilizando o # Debugger. Em Python, podemos fazer isso em diferentes IDEs, como o PyCharm # ou utilizando o PDB. # Exemplo from random import randrange def dividir(a, b): try: return int(a) / int(b) except ValueError: return 'Valor Incorreto' except ZeroDivisionError: return 'Não é possível realizar um divisão por Zero' print(dividir(randrange(0, 50), randrange(1, 50))) # Exemplo com o PDB # Para utilizar o PDB, precisamos importar a bibioteca pdb e então utilizar a função set_trace() OBS: A partir do Python 3.7, não é mais necessário importar a biblioteca pdb, pois o comando de debug foi incorporado como função built-in (integrada) chamada breakpoint() # Comandos básicos do PDB # l - listar onde estamos no código # n - próxima linha # p - imprime variável # c - continua a execução, finaliza a debugging import pdb nome = 'Angelina' sobrenome = 'Jolie' pdb.set_trace() nome_completo = nome + ' ' + sobrenome curso = 'Programação em Python: Essencial' final = nome_completo + ' faz o curso' + curso print(final) nome = 'Angelina' sobrenome = 'Jolie' import pdb; pdb.set_trace() nome_completo = nome + ' ' + sobrenome curso = 'Programação em Python: Essencial' final = nome_completo + ' faz o curso' + curso print(final) # Por que utilizar este formato? # O debug é utilizado durante o desenvolvimento. Costumamos realizar todos os imports de bibliotecas no início do arquivo. # Por isso, ao invés de colocarmos o import do pdb no início do arquivo, nós # colocamos somente onde vamos debuggar, e ao finalizar já fazemos a remoção. nome = 'Angelina' sobrenome = 'Jolie' breakpoint() nome_completo = nome + ' ' + sobrenome curso = 'Programação em Python: Essencial' final = nome_completo + ' faz o curso' + curso print(final) """ # OBS: cuidado com conflitos entre nomes de variáveis e os comandos do pdb # Como os nomes das variáveis são os mesmos do comando do pdb, devemos utilizar o comando p para imprimir # as variáveis. Ou seja, p nome_da_variável # Nada de colocar nomes não representativos em variáveis, sempre optar por nomes significativos
false
7795889ac49a50f9318a187dd7e97fd7f892cc40
glenonmateus/ppe
/secao7/ordered_dict.py
1,012
4.21875
4
""" Módulo Collections - Ordered Dict # Em um dicionário, a ordem de inserção dos elementos não é garantida. dicionario = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} print(dicionario) for chave, valor in dicionario.items(): print(f'chave={chave}:valor={valor}') OrderedDict -> É um dicionário, que nos garante a ordem de inserção dos elementos. # Fazendo import from collections import OrderedDict dicionario = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}) for chave, valor in dicionario.items(): print(f'chave={chave}:valor={valor}') """ from collections import OrderedDict # Entendendo a diferença entre Dict e OrderedDict # Dicionários comuns dict1 = {'a': 1, 'b': 2} dict2 = {'b': 2, 'a': 1} print(dict1 == dict2) # True/False?? -> True já que a ordem dos elementos # Não importa para o dicionário # Ordered Dict odict1 = OrderedDict(dict1) odict2 = OrderedDict(dict2) print(odict1 == odict2) # True/False? -> False já que a ordem dos elementos # importa para o OrderedDict
false
45874cd743f5c9ac41f651bbf3d97b448204c9fd
onuryarartr/trypython
/loop_problem4.py
860
4.40625
4
"""Her bir while döngüsünde kullanıcıdan bir sayı alın ve kullanıcının girdiği sayıları "toplam" isimli bir değişkene ekleyin. Kullanıcı "q" tuşuna bastığı zaman döngüyü sonlandırın ve ekrana "toplam değişkenini" bastırın. İpucu : while döngüsünü sonsuz koşulla başlatın ve kullanıcı q'ya basarsa döngüyü break ile sonlandırın.""" print("""************************************* Sayı Toplama Uygulaması ************************************* """) toplam = 0 liste = [] while True: sayı = input("Sayı Girin: ") if(sayı == "q") or (sayı == "Q"): print("\n{} sayılarının toplamı: {}".format(liste, toplam)) print("\nProgramı kullandığınız için teşekkürler...") break else: toplam += int(sayı) liste.append(int(sayı))
false
d3656e2165051158604ebf6df019795eed6f167e
onuryarartr/trypython
/loop_problem1.py
829
4.5625
5
"""Kullanıcıdan aldığınız bir sayının mükemmel olup olmadığını bulmaya çalışın. Bir sayının kendi hariç bölenlerinin toplamı kendine eşitse bu sayıya "mükemmel sayı" denir. Örnek olarak, 6 mükemmel bir sayıdır. (1 + 2 + 3 = 6)""" print("""************************************* Mükemmel Sayı Bulucu ************************************* """) sayı = int(input("Lütfen bir sayı girin:")) x = 1 toplam = 0 while (x < sayı): if(sayı % x == 0): toplam += x x += 1 if(toplam == sayı): print("\n{} bir mükemmel sayıdır.".format(sayı)) print("\nProgramı kullandığınız için teşekkürler...") else: print("\n{} bir mükemmel sayı değildir.".format(sayı)) print("\nProgramı kullandığınız için teşekkürler...")
false
9f355c1b4f24e8407009f6bb291968ef74902961
FlyingQuetzal/Moje_cwiczenia
/Ex 1/Employee.py
976
4.25
4
class Employee: number_of_objects = 0 def __init__(self, first_name, last_name, email, salary): self.first_name = first_name self.last_name = last_name self.email = email self.monthly_salary = salary Employee.number_of_objects += 1 def get_annual_salary(self): return self.monthly_salary * 12 def show_employee_information(self): full_name = f"{self.first_name} {self.last_name}" print(f"Pracownik: {full_name}, Adres email: " f"{self.email}, Wynagrodzenie miesieczne: " f"{self.monthly_salary}") employee_1 = Employee("Jan", "Kowalski", "jankowalski@wp.pl", 3000) employee_2 = Employee("Oliwia", "Nowak", "oliwianowak@gmail.com", 2800) print(employee_1.get_annual_salary()) employee_1.show_employee_information() print("-----------------") print(employee_2.get_annual_salary()) employee_2.show_employee_information() print(f"Liczba pracowników: {Employee.number_of_objects}")
false
daad457e49041ad1f324e56258b1e8ab608b72a3
PARASVARMA/100-days-of-code-challenge
/listfunction.py
613
4.40625
4
#list append function:- words = ["hello"] words.append("world") print(words[1]) #list len function:- nums = [1, 3, 5, 7, 9] print(len(nums)) #other len function example: letters = ["a", "b", "c"] letters.append("d") print(len(letters)) #list insert function:- words = ["python", "fun"] index = 1 words.insert(index, "is") print(words) #other insert function example:- nums = [9, 4, 3, 2, 1] nums.append(4) nums.insert(2, 11) print(len(nums)) #list index function:- letters = ['p', 'q', 'r', 's', 't'] print(letters.index('r')) print(letters.index('p')) print(letters.index('z'))
false
80dc8d0e92c5181f45cf8ae70ab75cf3ce441ce5
PARASVARMA/100-days-of-code-challenge
/metacharacter.py
840
4.1875
4
#Regular Expression:- import re pattern = r"spam" if re.match(pattern, "spamspamspam"): print("Match") else: print("No match") #function re.search and re.findall import re pattern = r"spam" if re.match(pattern, "eggspamsausagespam"): print("Match") else: print("No match") if re.search(pattern, "eggspamsausagespam"): print("Match") else: print("No match") print(re.findall(pattern, "eggspamsausagespam")) #Some methods like group,start,end and span import re pattern = r"pam" match = re.search(pattern, "eggspamsausage") if match: print(match.group()) print(match.start()) print(match.end()) print(match.span()) #Search and Replace: import re str = "My name is David. Hi David." pattern = r"David" newstr = re.sub(pattern, "Amy", str) print(newstr)
true
14e9d7459eb925fa64083c7aa74c7239b087425d
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/MzKhan/lesson03/slice_sequences.py
2,110
4.3125
4
''' Name: Muhammad Khan Date: 02/28/2019 Assignment03 ''' def exchange_first_last(seq): # The method swaps the first and the last item in the given sequence. # parm: sequence # return : sequence return seq[-1:]+seq[1:-1]+seq[:1] def remove_every_other(seq): # The method removes the every other item from the given sequence. # parm: sequence # return: sequence return seq[::2] def remove_first_last_four_and_between(seq): # The method removes the first 4 and the last 4 items from the sequence # and also every other item. # parm: sequence # return: sequence return seq[4:-4:2] def reverse_sequence(seq): # The method reverses the sequence. # parm: sequence # return: sequence return seq[::-1] def swap_third_third(seq): # The method re-orders the sequence as # The middle third, # The last third # The first third third = len(seq)//3 return seq[third:-third]+seq[-third:]+seq[:third] if __name__ =="__main__": # Test the methods above using "assert" statement. a_string = "this is a string" a_tuple = (2, 54, 13, 12, 5, 32) a_list = list(range(10)) 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,1,2,3,4,5,6,7,8,0] assert remove_every_other(a_string) == "ti sasrn" assert remove_every_other(a_tuple) == (2,13,5) assert remove_every_other(a_list) == [0,2,4,6,8] assert remove_first_last_four_and_between(a_string) == " sas" assert remove_first_last_four_and_between(a_tuple) == () assert remove_first_last_four_and_between(a_list) == [4] assert reverse_sequence(a_string) == "gnirts a si siht" assert reverse_sequence(a_tuple) == (32,5,12,13,54,2) assert reverse_sequence(a_list) == list(range(9,-1,-1)) assert swap_third_third(a_string) == "is a stringthis " assert swap_third_third(a_tuple) == (13,12,5,32,2,54) assert swap_third_third(a_list) == [3, 4, 5, 6, 7, 8, 9, 0, 1, 2] print("Tests Passed: ")
true
50556888317ba4b3502a2d915aca31803285b383
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/ian_letourneau/Lesson02/fizz_buzz.py
526
4.5
4
## Ian Letourneau ## 4/25/2018 ## A script to list numbers and replace all multiples of 3 and/or 5 with various strings def fizz_buzz(): """A function that prints numbers in range 1-100 inclusive. If number is divisible by 3, print "Fizz" If number is divisible by 5, print "Buzz" If number is divisible by both 3 and 5, print "FizzBuzz""" for num in range(1,101): if not num%3 and not num%5: print('FizzBuzz') elif not num%3: print('Fizz') elif not num%5: print('Buzz') else: print(num) fizz_buzz()
true
3e217c277829b2ec8e8b3fc9332c028f459308b8
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/luyao_xu/lesson04/dict_lab.py
2,070
4.28125
4
#!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 """ Basic ins and outs of python dictionaries and sets""" """Dictionaries 1""" # Create a dictionary containing “name”, “city”, and “cake” for “Chris” from “Seattle” who likes “Chocolate” diction = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} # Display the dictionary print(diction) # Delete the entry for “cake” dict.popitem(diction) # Display the dictionary print(diction) # Add an entry for “fruit” with “Mango” and display the dictionary diction['fruit'] = 'Mango' # Display the dictionary keys print(diction.keys()) # Display the dictionary values print(diction.values()) # Display whether or not “cake” is a key in the dictionary print('cake' in diction.keys()) # Display whether or not “Mango” is a value in the dictionary print('Mango' in diction.values()) diction = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} """Dictionaries 2""" # Using the dictionary from item 1 diction = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} item_copy = diction.copy() # Make a dictionary using the same keys but with the number of ‘t’s in each value as the value for i in item_copy: item_copy[i] = item_copy[i].lower().count('t') print(item_copy) """Sets 1""" # Create sets s2, s3 and s4 that contain numbers from zero through twenty, divisible by 2, 3 and 4 s2 = set(range(0, 20, 2)) s3 = set(range(0, 20, 3)) s4 = set(range(0, 20, 4)) # Display the sets. print(s2) print(s3) print(s4) # Display if s3 is a subset of s2 (False) print(s3.issubset(s2)) # Display if s4 is a subset of s2 (True) print(s4.issubset(s2)) """Sets 2""" # Create a set with the letters in ‘Python’ s_python = set('Python') # Add ‘i’ to the set s_python.update('i') # print(s_python) # Create a frozenset with the letters in ‘marathon’. fs_marathon = frozenset('marathon') # display the union of the two sets print(s_python.union(fs_marathon)) # display the intersection of the two sets print(s_python.intersection(fs_marathon))
true
a9ad11cbe33e74feff9bead270a32d07a76b87bf
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/Craig_Morton/lesson08/Circle_Test.py
2,900
4.15625
4
# ------------------------------------------------- # # Title: Lesson 8, pt 2/2 Circle Test # Dev: Craig Morton # Date: 9/24/2018 # Change Log: CraigM, 9/24/2018, Circle Test # ------------------------------------------------- # from math import pi from Circle import Circle import random import unittest class CircleTest(unittest.TestCase): """Circle unit tests""" def test_constructor(self): for i in range(100): c = Circle(i) self.assertEqual(c.radius, i) self.assertEqual(c.diameter, i * 2) def test_properties(self): for i in range(100): c = Circle(i) c.radius = c.radius + 1 self.assertEqual(c.radius, i + 1) self.assertEqual(c.diameter, c.radius * 2) new_diameter = c.diameter * 2 c.diameter = new_diameter self.assertEqual(c.radius, new_diameter / 2) self.assertEqual(c.diameter, new_diameter) def test_area(self): pi2 = pi * 2 for i in range(100): c = Circle(i) area = pi2 * i self.assertEqual(c.area, area) def test_from_diameter(self): for i in range(100): c = Circle.from_diameter(i) self.assertEqual(c.radius, i / 2) self.assertEqual(c.diameter, i) def test_equal(self): for i in range(100): c1 = Circle(i) c2 = Circle(i) c3 = Circle(i + 1) self.assertEqual(c1, c2) self.assertNotEqual(c1, c3) def test_repr(self): for i in range(100): c1 = Circle(i) repr_c1 = repr(c1) c2 = eval(repr_c1) self.assertEqual(c1, c2) def test_addition(self): for i in range(100): # Addition c1 = Circle(i) c2 = Circle(i * 2) self.assertEqual(c2, c1 + c1) c1 += c1 self.assertEqual(c2, c1) def test_multiply(self): for i in range(100): # Addition c1 = Circle(i) c2 = Circle(i * 2) self.assertEqual(c2, c1 * 2) self.assertEqual(c2, 2 * c1) c1 *= 2 self.assertEqual(c2, c1) def test_less_than(self): for i in range(100): c1 = Circle(i) c2 = Circle(i + 1) self.assertTrue(c1 < c2) self.assertFalse(c2 < c1) self.assertFalse(c1 < c1) def test_sort(self): circle_list = [Circle(random.randint(0, 10000)) for i in range(100)] circle_list_s1 = sorted(circle_list) circle_list_s2 = sorted(circle_list, key=Circle.sort_key) self.assertEqual(circle_list_s1, circle_list_s2) for i in range(99): self.assertTrue(circle_list_s1[i] < circle_list_s1[i + 1]) if __name__ == "__main__": unittest.main()
false
7972d961bb6ea21126da9b9d34b4bcbc2b6eafe5
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/jeanruggiero/Lesson02/series.py
1,374
4.3125
4
#!/usr/bin/env python3 # This script contains functions that compute sequences. def fibonacci(n): """This function returns the nth value in the fibonacci series (starting with zero index).""" if n <= 1: return n else: # Call fibonacci function recursively to determine nth value return fibonacci(n-2) + fibonacci(n-1) def lucas(n): """This function returns the nth value in the lucas series (starting with zero index).""" if n == 0: return 2 elif n == 1: return 1 else: # Call lucas function recursively to determine nth value return lucas(n-2) + lucas(n-1) def sum_series(n,x=0,y=1): """This function returns the nth value (starting with index zero) in of an additive series with first two numbers x and y.""" if n == 0: return x elif n == 1: return y else: # Call sum_series function recursively to determine nth value return sum_series(n-2,x,y) + sum_series(n-1,x,y) # Assert statements to test functions assert fibonacci(10) == 55 # Tests fibonacci function against known value assert lucas(7) == 29 # Tests lucas function against known value assert sum_series(20) == fibonacci(20) # Tests sum_series against fibonacci assert sum_series(13,2,1) == lucas(13) # Tests sum_series against lucas
true
51f7ba0382267d53359368ef900f184162adb104
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/Sean_Tasaki/Lesson2/fibonacci.py
1,721
4.15625
4
def fibonacci(n): """Return the nth value in the fibonacci sequence (starting with zero index. """ if n == 1: return 1 if n == 0: return 0 if n < 0: print("Invalid data") else: return fibonacci(n - 2) + fibonacci(n - 1) def lucas(n): """Return the nth value in the Lucas numbers series (starting with zero index. """ if n == 1: return 1 if n == 0: return 2 if n < 0: print("Invalid data") else: return lucas(n - 2) + lucas(n - 1) def sum_series(n, index0 = 0, index1 = 1): """Return the nth value in a series. The default parameter values set to calculate fobonacci series. Calling with optional arguments index0 = 2 and index1 = 1 will calculate lucas series. """ # Calculates fibonacci series if (index0 == 0 and index1 == 1): if n == 1: return 1 if n == 0: return 0 if n < 0: print("Invalid data") else: return fibonacci(n - 2) + fibonacci(n - 1) # Calculates lucas series elif (index0 == 2 and index1 == 1): if n == 1: return 1 if n == 0: return 2 if n < 0: print("Invalid data") else: return lucas(n - 2) + lucas(n - 1) # Test the fibonacci function. assert fibonacci(2) == 1 assert fibonacci(6) == 8 assert fibonacci(7) == 13 # Test the lucas function assert lucas(2) == 3 assert lucas(6) == 18 assert lucas(7) == 29 # Test sum_series with default parameters assert sum_series(2) == 1 assert sum_series(6) == 8 assert sum_series(7) == 13 # Test sum_series as a Fibonacci sequence assert sum_series(2, 0, 1) == 1 assert sum_series(6, 0, 1) == 8 assert sum_series(7, 0, 1) == 13 # Test sum_series as a Lucas sequence assert sum_series(2, 2, 1) == 3 assert sum_series(6, 2, 1) == 18 assert sum_series(7, 2, 1) == 29
true
1b6639eee8509e007e7ab19233840a6b5b89e2ed
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/AlyssaHong/Lesson08/test_circle.py
1,698
4.46875
4
""" Author: Alyssa Hong Date: 12/18/2018 Update: Lesson8 Assignments > Test circle.py """ #!/usr/bin/env python3 import unittest from circle import Circle class TestCircle(unittest.TestCase): def test_radiusr(self): c = Circle(4) self.assertEqual(c.radius, 4) self.assertEqual(c.diameter, 8) def test_diamter(self): c = Circle(4) c.diameter = 2 self.assertEqual(c.diameter, 2) self.assertEqual(c.radius,1) def test_area(self): c = Circle(2) self.assertEqual(c.area, '12.56637') with self.assertRaises(AttributeError): c.area = 42 def test_from_diameter(self): c = Circle.from_diameter(8) self.assertEqual(c.radius, 4) self.assertEqual(c.diameter, 8) def test_str(self): c = Circle(4) self.assertEqual(str(c), "Circle with radius: 4.0") def test_repr(self): c = Circle(4) self.assertEqual(repr(c), 'Circle(4)') def test_add(self): c1 = Circle(2) c2 = Circle(4) c3 = c1 + c2 self.assertEqual(c3.radius, 6) def test_multi(self): c1 = Circle(2) c2 = Circle(4) with self.assertRaises(TypeError): c3 = c2 * 3 del c3 def test_comparsion(self): c1 = Circle(1) c2 = Circle(2) c3 = Circle(2) c4 = Circle(3) self.assertEqual(c1 < c2, True) self.assertEqual(c2 > c1, True) self.assertEqual(c2 == c3, True) self.assertEqual(c4 < c3, False) self.assertEqual(c1 != c4, True) self.assertEqual(c3 == c4, False) if __name__ == "__main__": unittest.main()
false
2a7485d2ad5be0891741db58a4de485ebfbed977
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/luyao_xu/lesson03/slicing_lab.py
2,180
4.53125
5
"""Get the basics of sequence slicing down""" def exchange_first_last(seq): """ Exchange the first item and the last item of a sequence :param seq: the sequence :return: The first and last item in a sequence exchanged """ if len(seq) <= 1: return seq return seq[-1:] + seq[1:-1] + seq[:1] def every_other_removed(seq): """ Remove every other item in a sequence :param seq: the sequence :return: Every other item removed in a sequence """ return seq[::2] def every_other_4removed(seq): """ Removed first4 and last 4 items, and then every other item in between of the sequence :param seq: The :return: """ return seq[4:-4:2] def reverse_items(seq): """ Elements reverse :param seq: the sequence :return: Reverse elements """ return seq[::-1] def order_third(seq): """ with the middle third, then last third, then the first third in the new order :param seq: The sequence :return: new order of sequence: middle third, last third, first third. """ one_third = len(seq) // 3 return seq[one_third:one_third * 2] + seq[one_third * 2:] + seq[:one_third] if __name__ == '__main__': a_string = "Say hello to the world" a_tuple = (1, 2, 3, 4, 5, 6, 7, 8) empty = '' one_el = 'H' assert exchange_first_last(a_string) == "day hello to the worlS" assert exchange_first_last(a_tuple) == (8, 2, 3, 4, 5, 6, 7, 1) assert exchange_first_last(empty) == '' assert exchange_first_last(one_el) == 'H' assert every_other_removed(a_string) == "Syhlot h ol" assert every_other_removed(a_tuple) == (1, 3, 5, 7) assert every_other_removed(empty) == '' assert every_other_removed(one_el) == 'H' assert reverse_items(a_string) == "dlrow eht ot olleh yaS" assert reverse_items(empty) == '' assert reverse_items(one_el) == 'H' assert reverse_items(a_tuple) == (8, 7, 6, 5, 4, 3, 2, 1) assert order_third(a_string) == "lo to the worldSay hel" assert order_third(empty) == '' assert order_third(one_el) == 'H' assert order_third(a_tuple) == (3, 4, 5, 6, 7, 8, 1, 2)
true
06b140475dd7b1978ee8670dbf806c357bd6edeb
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/stefan_lund/Lesson_5/a_new_file.py
2,267
4.1875
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:# joke = fun(first_try[0]) except NameError: # fun(first_try['spam']) ==> NameError: name 's' is not defined in except_test.py print("\nWhoops! there is no joke for: spam") else: # 'Spam, Spam, Spam, Spam, Beautiful Spam' will only print if ther's no except, # but there is a NameError so joke = fun(first_try[1]) is never called joke = fun(first_try[1]) # Here is a try/except block. Add an else that prints not_joke try: not_joke = fun(first_try[2]) # fun(first_try[2]) returns a string except SyntaxError: # no SyntaxError occurs so continue to else print('Run Away!') else: # not_joke holds the string, print it print(not_joke) # What did that do? You can think of else in this context, as well as in # loops as meaning: "else if nothing went wrong" # (no breaks in loops, no exceptions in try blocks) # Figure out what the exception is, catch it and in that same block # # try calling the more_fun function with the 2nd language in the list, # again assigning it to more_joke. # # If there are no exceptions, call the more_fun function with the last # language in the list # Finally, while still in the try/except block and regardless of whether # there were any exceptions, call the function last_fun with no # parameters. (pun intended) langs = ['java', 'c', 'python'] try: more_joke = more_fun(langs[0]) # more_fun(langs[n]) returns nothing except IndexError: pass # print("\nWhoops! index 5 is way out of index in the list [1, 2, 3]\n") finally: # since above IndexError occurred, to continue using the same try - except block # finally:, what is executed disregarding whatever else happend has to be used more_joke = more_fun(langs[1]) # more_fun(langs[n]) returns nothing last_fun()
true
ee3f09ef1c237bbd8fdb39b8e1f79c30aaa9448b
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/patchcarrier/Lesson08/index_slicing.py
1,127
4.375
4
#!/usr/bin/env python3 """ examples / test code for __getindex__ Doesn't really do anything, but you can see what happens with different indexing. """ import operator class IndexTest: def __getitem__(self, index): # print("In getindex, indexes is:", index) if isinstance(index, slice): print("it's a single slice:", index) elif isinstance(index, tuple): print("it's a multi-dimensional slice:", index) else: try: ind = operator.index(index) # this converts arbitrary objects to an int. print("it's an index: ", ind) except TypeError: # not a simple index raise print("It's a simple index") if __name__ == "__main__": it = IndexTest() print("calling with simple index") it[4] print("calling with single slice") it[3:4] print("calling with two slices") it[3:4, 7:8] print("calling with full slice") it[:] print("Calling with slice and int") it[3:4,1] print("calling with an invalid index") it["this"]
true
e913a2da6a229aa2db444a24952c226f828a7107
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/srepking/Lesson03/list_lab.py
2,340
4.21875
4
#Start Series 1 fruits = ['Apples', 'Pears', 'Oranges', 'Peaches'] print(fruits) response = input('What other fruit would you like? > ') fruits += [response] print(fruits) response = input('\n''Which number fruit would you like? > ''\n') print('\n'"Nice Choice! You chose {number}, which corresponds to the {fruit}"'\n'.format( number=response, fruit=fruits[int(response)-1])) # Add another to the beginning using '+' fruits=['tomato']+fruits print('\n''We added tomatoes to the beginning of the list') print(fruits) # Add another to the beginning using 'insert' fruits.insert(0, 'kiwi') print('\n''We added kiwis to the beginning of the list') print (fruits) # Display all the fruits that begin with P, using a for loop new_list = [] for i in fruits: if i[0].lower() == 'p': new_list += [i] print('\n''These are the fruits that start with the letter P ') print(new_list) # Start Series 2 print('\n''This is the fruit list we have so far starting Series 2.''\n') print(fruits) # Remove the last fruit del fruits[-1:] print('\n''Now we remove the last fruit') print(fruits) # Now we will ask a user which fruit to remove. First double the fruit list. fruits2 = fruits*2 print('\n''We Double our fruit list') print(fruits2) response = input('\n''Which fruit would you like to remove?') for i in fruits2: try: del fruits2[fruits2.index(response)] except ValueError as error: break print('\n''These are the fruits left in your basket') print (fruits2) # Start of Series 3 new_list = fruits[:] for i in fruits: while True: response = input("Do you like {fruit}? yes or no > ".format(fruit=i.lower())) if response == 'no' or response == 'yes': break if response == 'no': del new_list[new_list.index(i)] print(new_list) # Start of Series 4 print('\n''This is the start of Series 4') print('\n''This is our list of fruits starting Series 4') print(fruits) # Create a copy of fruit list and spell fruits backwards new_list = [] for i in fruits: spell = [str(i[::-1])] new_list += spell print('\n''This is our fruit list with fruits spelled backwards') print(new_list) # Delete the last item of the original list del fruits[-1:] print('\n''This is the original fruit list with the last item deleted') print(fruits)
true
55ecf62e2e117efc682c349ab31e36eaf47c60a4
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/SLammertink/Lesson03/mailroom_1.py
2,878
4.21875
4
#! /usr/bin/env python3 # Author: SLammertink # UW Self Paced Lesson 03 # Mailroom part 1 # Initiate the lists used don_list= [75, 25346.25, 125, 25, 200.50] # list with the donations name_list = ['Sukhmani Travers', 'Sebastien Mayo', 'Aryan Davila', 'Zayan Langley', 'Charlotte Bates'] #list with the donor names count_list = [1, 2, 1, 3, 2] # list with a count of the donations given choices_list = ['Sending a Thank You', 'Creating a Report', 'quit'] # list from where user can chose # The Functions used: def name_in_list(): #Checks whether is name is in the name list if not it adds it input_name = input("Please enter the donor's name: ") if input_name not in name_list: print('') print("That name is not in the donor list, will add it now.") # notify the user that the name will be added to the list print('') name_list.append(input_name) print('') print('The donor {} has been added to the list!'.format(input_name)) # Notifty the user that the donot has been added print('') # add zero to the new user in the count_list count_list.append(0) don_list.append(0) elif input_name in name_list: print('') input_don = float(input("How much is the donation: ")) print('') print("Sending email ----->") # pretending to send the email print("Thank you {} for your generous donation!".format(input_name)) # format the email message print('') for i, name in enumerate(name_list): if name == input_name: don_list[i] = (don_list[i] + input_don) count_list[i] = (count_list[i] + 1) return(don_list, count_list) # Creating a report function: def report(): print("{:^30}{:5}{:^20}{:5}{:^30}{:5}{:^20}{:5}".format('Name', '|', 'Donation','|', 'Number of gifts','|', 'Average gift', '|')) print("{:-<116}".format('')) print(' ') for i, j, k in zip(name_list, don_list, count_list): print("{:35}${:^25.2f}{:^35}${:^20.2f}".format(i, j,k, (j / k))) # ask the user to choose from three options: def choices(): # Function that prints the choices as long as it is True while True: print('') print("Please make a choice: ") print('') for i, j in enumerate(choices_list): print(i + 1, j) choice = input("Please chose an option, to see the list of donors type 'list': ") if choice == 'list': print('') print('Here are the donors already in the list: ') print('') print(name_list) print('') elif choice == "1": print('') name_in_list() elif choice == "2": print('') report() elif choice == "3": break # the program starts here if __name__ == '__main__': choices()
true
219f019bceedae48b8e7544d7381b35428038ce8
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/eldonab/lesson08/circle.py
1,895
4.40625
4
#!/usr/bin/python import math class Circle: """create a circle class that represents a simple circle""" def __init__(self, radius): self.radius = radius @property def diameter(self): return self.radius * 2 @diameter.setter def diameter(self, value): self.radius = value/2 @property def area(self): return math.pi * self.radius ** 2 @classmethod def from_diameter(cls, diameter): # needs to return Circle(radius) radius = diameter/2 return cls(radius) def __repr__(self): return f"Circle({self.radius})" def __str__(self): return f"Circle with radius: {float(self.radius)}" def __add__(self, other): return Circle(self.radius + other.radius) def __mul__(self, other): #circle(5) * 3 return Circle(self.radius * other) def __lt__(self, other): return self.radius < other.radius def __eq__(self, other): return self.radius == other.radius def __gt__(self, other): self.radius > other.radius def __ne__(self, other): return self.radius != other.radius def __rmul__(self, other): return Circle(other * self.radius) def __iadd__(self, other): return Circle(self.radius + other.radius) def __imul__(self, other): return Circle(self.radius * other) class Sphere(Circle): """Create a simple sphere as a subclass of Circle class""" def __init__(self, radius): super().__init__(radius) def __str__(self): return f"Sphere with a radius: {float(self.radius)}" def __repr__(self): return f"Sphere({self.radius})" @property def volume(self): return 4/3*math.pi*(self.radius**3) @property def area(self): return 4*math.pi*(self.radius**2)
false
a90f0bfe69a0a49448f0780183e6d69fb72111f2
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/paul_jurek/lesson02/fizz_buzz.py
531
4.40625
4
"""module to run the fiz_buz excercise Goal: 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.""" def run_fizz_buzz(): for i in range (1,101): if (i%3==0) & (i%5==0): print('FizzBuzz') elif i%3==0: print('Fizz') elif i%5==0: print('Buzz') else: print(i) run_fizz_buzz()
true
c002c563d71788c97a82e058eb25f1d5a1867c0d
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/JeffBennett/Lesson03/slicing_lab.py
1,955
4.15625
4
""" 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 between. with the elements reversed (just with slicing). with the middle third, then last third, then the first third in the new order. """ def exchange_first_last(seq): """exchange first and last elements of a sequence of length >= 2.""" return seq[-1] + seq[1:-1] + seq[0] def remove_every_other(seq): """remove every other element of a sequence of length >= 2.""" return seq[::2] def remove_first_last_4_and_every_other(seq): """remove first and last 4 items and every other item in between of a sequence of length >=9.""" return seq[4:-4:2] def reversal(seq): """reverse elements of a sequence of length >=1.""" return seq[::-1] def permute_thirds(seq): """present middle third, last third, then first third of a sequence of length >=3. If length not divisible by three, new middle receives excess.""" return seq[len(seq)//3:] + seq[:len(seq)//3] if __name__ == "__main__": assert exchange_first_last('ab') == 'ba' assert exchange_first_last('abc') == 'cba' assert exchange_first_last('abcdef') == 'fbcdea' assert remove_every_other('abc') == 'ac' assert remove_every_other('abcdef') == 'ace' assert remove_first_last_4_and_every_other('012345678') == '4' assert remove_first_last_4_and_every_other('0123456789') == '4' assert remove_first_last_4_and_every_other('0123456789abcd') == '468' assert reversal('a') == 'a' assert reversal('ab') == 'ba' assert reversal('abc') == 'cba' assert permute_thirds('abc') == 'bca' assert permute_thirds('0123456789abcdef') == '56789abcdef01234' assert permute_thirds('0123456789abcdefg') == '56789abcdefg01234' print("tests passed")
true
46359441026ad23ecaf018142bf339814bcf7e80
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/NatalieRodriguez/Lesson08/Circle.py
2,719
4.625
5
#Natalie Rodriguez # Lesson 08: Circle # May 12, 2018 ''' Goal: 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 there are equal (follows from above) be able to put them in a list and sort them You will use: properties a classmethod a define a bunch of “special methods” General Instructions: For each step, write a couple of unit tests that test the new features. Run these tests (and they will fail the first time) Add the code required for your tests to pass. ''' #imports import math class Circle: def __init__(self, in_radius=1): self._radius = in_radius def __str__(self): return "Circle with radius: "+str(self.radius) def __repr__(self): return "Circle("+str(self.radius)+")" def __add__(self, other): return Circle(self.radius+other.radius) def __iadd__(self, other): self.radius += other.radius return self def __imul__(self, scalar): self.radius *= scalar return self def __sub__(self, other): return Circle(self.radius-other.radius) def __mul__(self, scalar): return Circle(self.radius*scalar) def __rmul__(self, scalar): return Circle(self.radius*scalar) def __pow__(self, power): return Circle(self.radius**power) def __truediv__(self, scalar): return Circle(self.radius/scalar) def __lt__(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 __le__(self, other): return self.radius <= other.radius def __eq__(self, other): return self.radius == other.radius def __len__(self): return round(self.circumference) @classmethod def from_diameter(cls, in_diameter): return cls(in_diameter / 2) @property def radius(self): return self._radius @radius.setter def radius(self, value): self._radius = value @property def diameter(self): return 2 * self._radius @diameter.setter def diameter(self, value): self._radius = value / 2 @property def area(self): return math.pi*(self._radius**2) @property def circumference(self): return 2*math.pi*self._radius
true
a4bda7040bf21690f3df4379d971f5d39f1f0fa7
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/etwum/lesson02/fizz_buzz.py
778
4.1875
4
#assigns the initial value of 1 to x x = 1 #loops while x is less than 101 while(x < 101): #checks if the remainder of dividing x by 3 and 5 is equal to zero if x % 3 == 0 and x % 5 == 0: print("FizzBuzz") #moves to this statement if the first statement doesnt pass #checks if dividing x by only 3 has a remainder of zero elif x % 3 == 0: print("Fizz") #moves to this statement if the second statement doesnt pass #checks if dividing x by only 5 has a remainder of zero elif x % 5 == 0: print("Buzz") #moves to this statement if the third statement doesnt pass #just prints the value of x else: print(x) #adds one to the current value of x x+=1
true
b5c4d5fb3f1018e0bf7bf09e60e1ad0bee14f7e8
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/ador_yano/Lesson02/DrawGrids.py
2,380
4.71875
5
# DrawGrids.py implements the Lesson 2 assignment from UWPCE Python Programming intro = '''UWPCE Python Programming: Lesson 2 Assignment Three functions to print grid three ways 1. print_grid(): display on screen a simple 2 x 2 grid 2. print_grid1(n): display on screen a scalable 2 x 2 grid based on the size specified by the argument "n" 3. print_grid2(a,b): diplay on screen a grid specified by "a" rows & "a" columns of "b" size ''' print(intro) def print_grid(): for i in range(2): # draw 2 rows of 2 columns for i in range(2): # draw top line print("+", "- " * 4, end="") print("+") for i in range(4): # draw row for i in range(2): # draw columns print("|", " " * 4, end="") print("|") for i in range(2): # draw bottom line print("+", "- " * 4, end="") print("+") def print_grid1(n): scale = n//2 # convert n to scale defined by assignment for i in range(2): # draw 2 rows of 2 columns for i in range(2): # draw top line print("+", "- " * scale, end="") # size side per scale print("+") for i in range(scale): # draw row per scale for i in range(2): # draw columns print("|", " " * scale, end="") print("|") for i in range(2): # draw bottom line print("+", "- " * scale, end="") # size side per scale print("+") def print_grid2(a,b): rows = a columns = a scale = b # grid box size for i in range(rows): # draw rows for i in range(columns): # draw top line across number of columns print("+", "- " * scale, end="") # draw column per scale print("+") for i in range(scale): # draw row per scale for i in range(columns): # draw column per scale print("|", " " * scale, end="") print("|") for i in range(columns): # draw bottom line across number of columns print("+", "- " * scale, end="") # draw column per scale print("+")
true
3065b20a415680f3e9e1021dbaa957fccd1d1ddf
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/RoyC/Lesson03/list_lab.py
2,716
4.375
4
#!/usr/bin/env python3 # Lesson 03, Series lab # Series 1 print("\nSERIES 1\n") # Print out initial list of fruit fruits = ["Apples", "Pears", "Oranges", "Peaches"] print(fruits) # Prompt for another fruit and append it to the end of list, then print fruits.append(input("\nPlease enter a fruit to add -> ")) print(fruits) # Prompt for index of fruit to display and display it (make them enter a number in range) index = 0 while index < 1 or index > len(fruits): index = int(input("\nEnter index of fruit (between 1 and " + str(len(fruits)) + ") to display -> ")) print("Fruit number {} is {}".format(index, fruits[index-1])) # Using two different methods, add another fruit to beginning fruits = ["Bananas"] + fruits print("....\n", fruits) fruits.insert(0, "Kumquats") print("....\n", fruits) # Iterate through the list and display all fruits that start with 'P' print("....") for fruit in fruits: if fruit[0] == "P" or fruit[0] == "p": print(fruit) # Series 2 print("\nSERIES 2\n") # Make a copy of the list for use in Series 2, since instructions for Series 3 say to use list from Series 1 fruits2 = fruits[:] # Print the list of fruits print(fruits2) # Remove last fruit from list and print again fruits2.pop() print(fruits2) # Double the fruit list (for BONUS!) and display again fruits2 *= 2 print(fruits2) # Prompt for fruit to delete (prompt until a match is found) fruit_to_delete = "" while fruit_to_delete not in fruits2: fruit_to_delete = input("\nEnter fruit to delete -> ") # Delete all occurrences of the entered fruit while fruit_to_delete in fruits2: fruits2.remove(fruit_to_delete) # Display the list to show fruit was removed print(fruits2) # Series 3 # Start with ending list from Series 1, display it to start print("\nSERIES 3\n") # Again make a copy of the list for use in Series 3, since instructions for Series 4 say to use list from Series 1 fruits3 = fruits[:] print(fruits3) # make a copy of the list to iterate fruits_copy = fruits3[:] for fruit in fruits_copy: while True: response = input("Do you like " + fruit.lower() + " (yes or no)? ") if response == "yes": break elif response == "no": fruits3.remove(fruit) break # Display new list with fruit they hate removed print(fruits3) # Series 4 print("\nSERIES 4\n") # Make a new copy of the list for manipulation in this series fruits4 = fruits[:] # Iterate the copy list and reverse the letters in each fruit for i, fruit in enumerate(fruits4): fruits4[i] = fruit[::-1] # Remove last fruit on original list fruits.pop() # Display both lists print("Original:", fruits) print("Copy: ", fruits4)
true
8ed6c73fda1278c856fc4f9dc4fa8a9e70309d96
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/prgrover/lesson02/series.py
2,122
4.40625
4
def fibonacci(n): """ This function uses recursion to calculate a Fibonacci Series. Args: n: Calculate up to the nth value of the Fibonacci Series. Returns: The nth value in the Fibonacci Series. """ if n <= 1: return n else: return (fibonacci(n-1) + fibonacci(n-2)) def lucas(n): """ This function uses recursion to calculate a Lucas Number series. Args: n: Calculate up to the nth value of the Lucas Number series. Returns: The nth value in the Lucas Number series. """ if n == 0: return 2 if n == 1: return 1 else: return (lucas(n-1) + lucas(n-2)) def sum_series(n, y=0, z=1): """ Generalized function that calculates a number series based on the provided parameters. Calling this function with no optional parameters will produce numbers from the fibonacci series. Calling it with the optional arguments 2 and 1 will produce values from the lucas numbers. Other values for the optional parameters will produce other series. Args: n: Required. Calculate up the nth value of numeric series. y: Optional. The first value of the series to be produced. Default value is 0. z: Optional. The second value of the series to be produced. Default valie is 1. Returns: The nth value of the Lucas Number series. """ if n == 0: return y elif n == 1: return z else: return (sum_series(n-1, y, z) + sum_series(n-2, y, z)) """ fibonacci(n) tests Known values of the Fibonacci Numbers series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 """ assert fibonacci(0) == 0 assert fibonacci(8) == 21 """ lucas(n) tests Known values of the Lucas Numbers series: 2, 1, 3, 4, 7, 11, 18, 29, 47, 76 """ assert lucas(2) == 3 assert lucas(9) == 76 """ sum_series(n,,z) tests The provided paramters should correctly match either the fibonacci or lucas series calculated values """ assert sum_series(0) == fibonacci(0) assert sum_series(8) == fibonacci(8) assert sum_series(9, 0, 1) == fibonacci(9) assert sum_series(6, 2, 1) == lucas(6)
true
eaec4f4b31dd241cfe17fe26ddbf0e5943e9c32d
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/MzKhan/lesson08/circle.py
2,837
4.34375
4
""" Name: Muhammad Khan Date: 04/01/2019 Assignment08 """ import math as m class Circle: """The initializer or the constructor for the Circle Class""" def __init__(self , radius): """Instance attributes are initalized here""" if radius < 0: raise TypeError("Invalid radius < 0") self.radius = radius @property def diameter(self): """Return the diameter of a circle""" return 2*self.radius @diameter.setter def diameter(self, diameter): """Set the radius""" self.radius = diameter / 2 @property def area(self): """ Area property--it can't be changed. Raises an AttributeError exception""" return m.pi*self.radius**2 @classmethod def from_diameter(cls, diameter): """Alternative constructor""" return cls(diameter / 2) def __repr__(self): """Recreate the object and return it for the developer""" return "Circle({})".format(self.radius) def __str__(self): """Return a nicely printable string for the user""" return "Circle with radius: {}".format(self.radius) def __add__(self,other): """Add two circles.""" return Circle(self.radius + other.radius) def __mul__(self,num): """Multiply a circle by a number""" return Circle(self.radius * num) def __rmul__(self,num): """Multiples radius of circle by an int but sequence reversed""" return Circle(self.radius*num) def __lt__(self, other): """Return true if the left circle is less than the right circle""" return self.radius < other.radius def __eq__(self, other): """Return true if both circles are equal""" return self.radius == other.radius ######### #Optional ######### #Augmented assignmnet operators. def __iadd__(self, other): """Augmented Addition """ return Circle(self.radius + other.radius) def __imul__(self,num): """Augmented Multiplication""" return Circle(self.radius*num) # With a similiar apprach, other augmented operaters can be defined as well. if __name__ == "__main__": c = Circle(4) print("Diameter = ",c.diameter) print("change diameter...") c.diameter = 100 print("Diameter = ",c.diameter) print("Alternative Constructor") c = Circle.from_diameter(16) print("diameter = ",c.diameter) print("radius = ", c.radius) c1 = Circle(2) c2 = Circle(4) c3 = Circle(6) print(c1+c2) print(repr(c3)) print("Unsorted Circles: ") circles=[Circle(6), Circle(7), Circle(8), Circle(4), Circle(0), Circle(2), Circle(3), Circle(5), Circle(9), Circle(1)] print(circles) print("Sorted Circles: ") circles.sort() print(circles)
true
26ae3b8dcd0f43ad92b2c81b8dcaf0ac28f07bf3
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/AlyssaHong/Lesson03_1/slicing.py
1,976
4.375
4
""" Author: Alyssa Hong Date: 10/22/2018 Update: 10/24/2018 Lesson3 Assignments > Slicing Lab Exercise """ #Get the basics of sequence slicing downself. #Test items: a_string = "this is a string" a_tuple = (2, 54, 13, 12, 5, 32) #1 with the first and last items exchanged. def exchange_first_last(seq): a_new_sequence = seq[-1:] + seq[1:-1] + seq[:1] print("result #1:", a_new_sequence) return a_new_sequence assert exchange_first_last(a_string) == "ghis is a strint" assert exchange_first_last(a_tuple) == (32, 54, 13, 12, 5, 2) #2 with every other item removed. def every_other_item_remove(seq): a_new_sequence = seq[::2] print("result #2:", a_new_sequence) return a_new_sequence assert every_other_item_remove(a_string) == "ti sasrn" assert every_other_item_remove(a_tuple) == (2, 13, 5) #3 with the first 4 and the last 4 items removed, and then every other item # in between. def select_item_and_remove(seq): a_new_sequence = seq[4:-4] print("result #3:", a_new_sequence) return a_new_sequence assert select_item_and_remove(a_string) == " is a st" assert select_item_and_remove(a_tuple) == () #4 with the elements reversed (just with slicing). def elements_reverse(seq): a_new_sequence = seq[::-1] print("result #4:", a_new_sequence) return a_new_sequence assert elements_reverse(a_string) == "gnirts a si siht" assert elements_reverse(a_tuple) == (32, 5, 12, 13, 54, 2) #5 with the middle third, then last third, then the first third in the new order. def each_third_reorder(seq): dividend = len(seq) quotient = int(dividend/3) middle_third = seq[quotient:quotient+quotient] last_third = seq[quotient+quotient:dividend] first_third = seq[:quotient] a_new_sequence = middle_third + last_third + first_third print("result #5:", a_new_sequence) return a_new_sequence assert each_third_reorder(a_string) == "is a stringthis " assert each_third_reorder(a_tuple) == (13, 12, 5, 32, 2, 54)
true
6ddb09156fa8433a5d321d97988ce7dc4e503c29
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/dominic_martin/lesson03/mailroom.py
2,432
4.15625
4
#!usr/bin/env Python dnd = {'Ted Bayer': 500, 'Panfila Alvarez': 700, 'JR Reid': 330, 'Simon Laplace': 440, 'Jennifer Meyers': 800} a = int(input("What would you like to do?\nSend a Thank You? - (1)\nCreate a Report? - (2)\nQuit? - (3)\nEnter your response:")) def choices(a): ''' This function presents the user with choices.''' global dnd if a == 1: thanks(a) if a == 2: genReport(a) if a == 3: quitAll(a) def thanks(a): ''' This function gives the option to enter a name already on the list, or enter a new name. If the user enters a new name, another function is called. If a current name is entered, a function is called. If the user wants to see a list of names, a list is printed.''' global dnd b = str(input("Who would you like to send a thanks to?\n" "Type 'list' or enter a name:")) if b in dnd.items(): print() print(b) donamt(b) if b == 'list': print() for x in dnd.keys(): print(x) else: newDonor(b) def newDonor(b): ''' If a new name is entered, the dictionary is updated with the name and a default donation of $0.''' print() dnd.update({b:0}) newDonat = 0 for name, donat in dnd.items(): if donat == newDonat: print(name) print() donamt(b) a == None def donamt(b): ''' This function allows the user to enter a donation amount for either a new or current name. The function updates the current donation amount for the name.''' global dnd print() d = int(input("Enter a donation amount:")) print() e = int(dnd[b]) + d dnd.update({b:e}) for name, donat in dnd.items(): if b == name: print(b + " has donated: " + str(e)) tyemail(b) def tyemail(b): ''' This function sends a thank you message to the previously chosen name.''' global dnd print() for name, donat in dnd.items(): if b == name: print(name + ", thank you so much for your donation. It's going to a wonderful cause to help lessen the greenhouse emissions from our production plant. Thanks again and Happy Holidays!") a == None def genReport(a): ''' This function generates a report that shows a list of names and their associated donations.''' global dnd print() width1 = 27 p = ('Name:', 'Amount:') print(f'{p[0]:{width1}}{p[1]:{width1}}') for name, donat in dnd.items(): print(f'{name:{width1}}{"$"+str(donat):{width1}}') def quitAll(a): ''' This function quits the program.''' print() print("Thanks for using The Mailroom Application! Goodbye!") choices(a)
true
50fdc496d710ffe6b97ce06f69d04cd80fa0b459
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/Dustin_L/lesson02/grid_printer.py
1,491
4.3125
4
#!/usr/bin/env python3 def print_row(n, sz, bottom): """Print a single row Print a single row of n cells of size sz. The bottom line of the row is only printed if 'bottom' is True. Args: n (int): number of cells sz (int): size of each cell bottom (bool): include bottom line if True """ if n < 0 or sz < 0: return # Top and bottom line definition tb = ('+ ' + ('- ' * sz)) * n + '+' + '\n' # Inner line definition inner = ('| ' + (' ' * 2 * sz)) * n + '|' + '\n' row = tb + (sz * inner) if bottom: row += tb print(row, end='') def print_fixed_grid(): """Print a 2 x 2 cell grid where length = width = 0""" tmb = '+ - - - - + - - - - +\n' bars = '| | |\n' print(tmb + (4 * bars) + tmb + (4 * bars) + tmb) def print_grid(d): """Print a 2 x 2 cell grid where length = width = d Args: d (int): length and width of grid """ if d < 0: return print_row(2, int(d / 2), False) print_row(2, int(d / 2), True) print() def print_grid2(n, sz): """Print a n x n cell grid where each cell is of size sz. Args: n (int): grid dimensions sz (int): size of each cell """ if n < 0 or sz < 0: return for i in range(n): print_row(n, sz, True if (i == n - 1) else False) print() if __name__ == '__main__': print_fixed_grid() print_grid(4) print_grid2(5, 1)
true
16aa103b823cbc17e57443c6338b8989ce3ee1f3
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/jvirtue/lesson04/triagram.py
2,675
4.34375
4
#Lesson 4 Assignment 2 #Triagrams #Jason Virtue 02/15/2019 #UW Self Paced Python Course import random source = "sherlock_holmes.txt" def read_infile(source= source): with open(source, "r") as infile: book = infile.read() return book def format_book(book): book = book.replace("\n", " ") book = book.replace("\\", " ") words = book.split(" ") while "" in words: words.remove("") for i in range(len(words)): while " " in words[i]: words[i] = words[i].replace(" ", "") while "\\" in words[i]: words[i] = words[i].replace("\\", "") while "\\\'" in words[i]: words[i] = words[i].replace("\\\'", "'") return words def make_dictionary(lst): dic = {} for i in range(len(lst)- 2): two_words = lst[i] + " " + lst[i + 1] value = lst[i+2] if two_words not in dic: dic[two_words] = [value,] else: dic[two_words].append(value) return dic def make_sentence(dic): sentence = [] while True: if len(sentence) == 0: two_words = random.choice(list(dic.keys())) two_word_lst = two_words.split(" ") if "." in two_words: continue else: two_word_lst[0] = two_word_lst[0].capitalize() word = random.choice(dic[two_words]) new_two_word = two_word_lst[1] + " " + word if new_two_word in dic: sentence.append(two_word_lst[0]) sentence.append(two_word_lst[1]) sentence.append(word) else: two_word_lst = sentence[-2:] two_words = " ".join(two_word_lst) word = random.choice(dic[two_words]) new_two_word = two_word_lst[1] + " " + word if new_two_word in dic: sentence.append(word) if "." in sentence[-1]: break return " ".join(sentence) def make_paragraph(dic): paragraph = [] while len(paragraph) < 5: para = make_sentence(dic) paragraph.append(para) return " ".join(paragraph) def create_literature(dic, paras = 4): entire_book = [] while len(entire_book) < paras: para = make_paragraph(dic) entire_book.append(para) return "\n\n".join(entire_book) if __name__ == "__main__": book = read_infile() words = format_book(book) dic = make_dictionary(words) paras = int(input("How many paragraphs would you like your 'book' to have?: ")) new_book = create_literature(dic, paras) print("\nPresto here is your new book as follows: ") print() print(new_book)
false
8f778c22a309b79bda9e63871edcde3234e2c8cc
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/christopher_gantt/lesson02/series.py
1,317
4.1875
4
def fibonacci(n): '''Returns the nth value in the fibonacci series''' fibonacci_list = [0,1] for number in range(1, n): fibonacci_list.append(fibonacci_list[number]+fibonacci_list[number-1]) return fibonacci_list[n-1] def lucas(n): '''Returns the nth value in the lucas series''' lucas_list = [2,1] for number in range(1,n): lucas_list.append(lucas_list[number]+lucas_list[number-1]) return lucas_list[n-1] def sum_series(n, first_number = 0, second_number = 1): '''Returns the nth value in a sum series, where you can dictate the first and second numbers of the series''' sum_list = [first_number, second_number] for number in range(1,n): sum_list.append(sum_list[number]+sum_list[number-1]) return sum_list[n-1] if __name__ == '__main__': '''Testing the three functions for accuracy''' #Testing the fibonacci function assert fibonacci(3) == 1 assert fibonacci(7) == 8 assert fibonacci(12) == 89 #Testing the lucas fuction assert lucas(3) == 3 assert lucas(7) == 18 assert lucas(12) == 199 #Testing the sum_series function assert sum_series(3) == 1 assert sum_series(3) == fibonacci(3) assert sum_series(5,2,1) == lucas(5) assert sum_series(5,7,3) == 23
true
110beb3aa0d6592fcf3af181c9cd21adf10ac2ce
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/TinaB/lesson03/SlicingLab.py
1,864
4.375
4
""" Slicing Lab Assignment """ def exchange_first_last(seq): """function to switch first and last elements""" new_seq = seq[-1:] + seq[1:-1] + seq[:1] return new_seq def every_other(seq): """print everyother element""" if isinstance(seq, tuple): print(seq[::2]) return tuple(seq[::2]) elif isinstance(seq, str): print(seq[::2]) return str(seq[::2]) print(seq[::2]) return seq[::2] def four_in_to_four_out(seq): """function to start four elements in print every other till four elements from end""" print(seq[4:-4:2]) return seq[4:-4:2] def reverse_seq(seq): """print series reversed""" print(seq[::-1]) return seq[::-1] def switch_thirds(seq): """print first third, second third and third third in new order""" new_seq = seq if isinstance(seq, tuple): list(new_seq) third_length = int((len(seq) // 3)) #switched = new_seq[2*third_length:] + \ #new_seq[:third_length] + new_seq[third_length:2*third_length] switched = seq[third_length:] + seq[:third_length] #if isinstance(seq, tuple): #tuple(switched) print(switched) return switched if __name__ == '__main__': """ Tests""" a_string = "this is a string" a_tuple = (2, 54, 13, 12, 5, 32) assert exchange_first_last(a_string) == "ghis is a strint" assert exchange_first_last(a_tuple) == (32, 54, 13, 12, 5, 2) assert every_other(a_string) == "ti sasrn" assert every_other(a_tuple) == (2, 13, 5) assert four_in_to_four_out(a_string) == ' sas' assert four_in_to_four_out(a_tuple) == () assert reverse_seq(a_string) == "gnirts a si siht" assert reverse_seq(a_tuple) == (32, 5, 12, 13, 54, 2) assert switch_thirds(a_string) == "is a stringthis " assert switch_thirds(a_tuple) == (13, 12, 5, 32, 2, 54)
false
a8e0826f88ca36166d003d8b382bd5f05b8df82c
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/yixingxu/lesson04/trigram.py
1,548
4.28125
4
#!/usr/bin/env python3 import os import random # read in a file and convert the words into list def readin_words(file_name = "sherlock_small.txt"): with open(file_name, "r") as rf: # readin file and replace all the non words with space content = rf.read().replace('\n', ' ').replace('.','').replace(',','').replace('(',' ').replace(')', ' ').replace('--',' ') # convert the content into list of words return content.lower().split() # create a trigram dict according to the words list generated from the input file def create_trigram_dict(words_list): trigram_dict = {} for i in range(len(words_list)-2): two_words_key=words_list[i] +' '+ words_list[i+1] third_word_value = words_list[i+2] trigram_dict.setdefault(two_words_key,[]).append(third_word_value) return trigram_dict def create_new_content(trigram_dict, content_length = 100): # initiate from a random key in trigram_dict new_content = random.choice(list(trigram_dict)).split() # create a new words list, the number of words are set to content_length for i in range(content_length): new_key = new_content[i]+' '+ new_content[i+1] if new_key in trigram_dict: new_word = random.choice(trigram_dict[new_key]) new_content.append(new_word) else: break print( ' '.join(new_content)) if __name__ == "__main__": words_list = readin_words() trigram_dict = create_trigram_dict(words_list) create_new_content(trigram_dict)
true
923da0d9b0d993dd45664cc815fb36718818fcf8
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/AndyKwok/lesson04/trigrams.py
1,815
4.21875
4
# Description: Trigram Exercise # Author: Andy Kwok # Last Updated: 07/22/2018 # ChangeLog: # v1.0 - Initialization import random import re # Read contents from file f = open('sherlock_mid.txt') read_data = f.read() f.close() # Split words into a string by , . - ; ( ) " ' ! and space split_data = re.split('[,|\.|\-|\;|(\|)|\"|\'|!|\s]+',read_data) # Remove '' caused by re.split if split_data[-1] == '': del split_data[-1] # Generating dictionary word_index = {} for counter, word in enumerate(split_data): if counter != (len(split_data)-2): next_word = word + ' ' + split_data[counter+1] # Check if key already exist existing_value = word_index.get(next_word, ["Key_Do_not_Exists"]) if existing_value == ["Key_Do_not_Exists"]: # Adding new key and value word_index.update({next_word: [split_data[counter+2]]}) else: # Adding new value to existing key word_index[next_word].append(split_data[counter+2]) else: break # Seek user to intial word input starter_word = input("Please provide two words to develop a trigram sequence> ") trigrams_list = starter_word.split(' ') while trigrams_list != None: # Set key and find key value search_word = trigrams_list[-2] + ' ' + trigrams_list[-1] word_found = word_index.get(search_word) if word_found != None: # Adding value to list for found key word_insert = random.choice(word_found) trigrams_list += [word_insert] else: # Break from the loop when there is no matched key break # Joining all words into a story story = " ".join(trigrams_list) print(story) # Reference ''' for show in word_index: print(show, word_index[show]) print(word_insert) print(trigrams_list) '''
false
2f5a1155eb3af1ad4426419033181c57b4aec6d3
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/Matt_Hudgins/Lesson03/list_lab.py
2,635
4.34375
4
#!/usr/bin/env python3 ''' File Name: list_lab.py Author: Matt Hudgins Date created: 5/5/18 Date last modified: 5/5/18 Python Version 3.6.4 ''' # Series 1 print("Starting Series 1!") # Fruit List fruit = ["Apples", "Pears", "Oranges", "Peaches"] print(fruit) # User will add a new fruit new_fruit = input("What fruit would you like to add?") fruit.append(new_fruit) print("This is the new list", fruit) # User will pick a number pick_a_number = int(input("Pick a number between 1-4:")) print(pick_a_number, fruit[pick_a_number - 1]) # User will add a fruit to the beginning of the list add_a_fruit = input("What fruit would you like to add to the beginning of the list?") fruit = [add_a_fruit] + fruit print(fruit) # User will insert fruit into list at the beginning insert_a_fruit = input("What fruit would you like to add to the beginning?") fruit.insert(0, insert_a_fruit) print("Updated List:", fruit) # Searching for fruits that start with the letter P for n in fruit: if n.startswith("P"): print("Here's all of the fruit that start with the letter P:", n) # Series 2 print("Starting Series 2!") # This prints and updated list for the user print("This is the most upto date list:", fruit) # This removes the last furit from the list del fruit[6] print("This is an updated list with the last fruit removed:", fruit) # User deletes a fruit from the list new_fruit = input("Which fruit would you like to delete?") if new_fruit in fruit: fruit.remove(new_fruit) print(new_fruit, "has been deleted from the list") print("This is the new list:", fruit) # Series 3 print("Staring Series 3!") fruit = ["Apples", "Pears", "Oranges", "Peaches"] fruit_list = ["Apples", "Pears", "Oranges", "Peaches"] print("Please answer the following questions with yes or no") for i in fruit_list: x = input(f"Do you like {i.lower()} ?") while (x != "yes") and (x != "no"): x = input("Invalid input please enter a yes or no:") if x == "no": fruit.remove(i) if x == "yes": print("I like this fruit too!") print("This is an updated list with only the fruits you like:", fruit) # Series 4 print("Alright lets start Series 4!") fruit = ["Apples", "Pears", "Oranges", "Peaches"] fruit_reserve = list(range(len(fruit))) for i in range(len(fruit)): fruit_reserve = [fruit[i][::-1]] print("Original List:", fruit) print("Reversed Order:", fruit_reserve) del fruit[-1] print("This is a list of the last fruit deleted:", fruit) fruit.insert(3,"Peaches") print("This is the original list:", fruit) Print ("This is the end of the list-lab exercise!")
true
b2fb5ae1da042302eef4e8b3697032d139328ce8
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/matiasli/lesson02/fizzbuzz.py
647
4.375
4
# fizzbuzz # 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. # to run, in the terminal, load ipython, import fizzbuzz, then call fizzbuzz.fizzBuzz() def fizzBuzz(): for i1 in range(100): if ( (i1+1)%15 == 0): print("FizzBuzz") elif ( (i1+1)%3 == 0): print("Fizz") elif ( (i1+1)%5 == 0): print("Buzz") else: print(i1+1)
true
5c314a314f8b38c1372548af76c3d1cfbb08b351
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/RoyC/Lesson03/strformat_lab.py
1,607
4.46875
4
#!/usr/bin/env python3 # Lesson 03, String formatting lab # Task One in_tuple = ( 2, 123.4567, 10000, 12345.67) print("file_{:03d}: {:.2f}, {:.2e}, {:.2e}".format(*in_tuple)) # Task Two print(f"file_{in_tuple[0]:03}: {in_tuple[1]:.2f}, {in_tuple[2]:.2e}, {in_tuple[3]:.2e}") # Task Three def formatter(in_tuple): """ Return formatted string with the integer values in the given tuple """ out_string = "The {:d} numbers are " + ("{:d},"*len(in_tuple)) # print out formatted string, minus last extranneous comma return out_string.format(len(in_tuple), *in_tuple)[:-1] print(formatter((1, 4, 2, 11, 9))) print(formatter((5, 1, 0))) print(formatter((3, 6, 9, 12, 15, 18))) # Task Four it = ( 4, 30, 2017, 2, 27) print(f"{it[3]:02} {it[4]:02} {it[2]:04} {it[0]:02} {it[1]:02}") # Task Five the_list = ['oranges', 1.3, 'lemons', 1.1] print(f"The weight of an {the_list[0][:-1]} is {the_list[1]} and the weight of a {the_list[2][:-1]} is {the_list[3]}") print(f"The weight of an {the_list[0][:-1].upper()} is {1.2*the_list[1]} and the weight of a {the_list[2][:-1].upper()} is {1.2*the_list[3]}") # Task Six def get_row(name, age, cost): """ Return a column formatted row of data for display """ return "{:<12}{:>4d}{:>10.2f}".format(name, age, cost) print("{:<12}{:>4}{:>10}".format("Name", "Age", "Cost")) print(get_row("Roy", 29, 999.99)) print(get_row("Terri", 59, 1122.50)) print(get_row("Kirby", 12, 555.25)) print(get_row("Amanda", 33, 1944.32)) print(get_row("Erin", 19, 800.21)) ten_nums = (range(995, 1005)) print(("{:<5d}"*10).format(*ten_nums))
false
3665d00ec6b524f1bec2c9d0a3ccd60329d95be3
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/cindywaldron/lesson3/list_lab.py
1,877
4.5625
5
#!/usr/bin/env python3 a_list = [ "Apples", "Pears", "Oranges", "Peaches"] print(a_list) # ask user to enter a fruit response = input("Enter a fruit name > ") #display user's input print("You entered: " + response) print(response + " is added to end of list") # add the input to end of the list a_list.append(response) # display the list print(a_list) # ask user to enter a number num = int(input("Enter a number > ")) #display the item print(a_list[num-1]) # Enter another fruit response = input("Enter another fruit name > ") a_list2 = [response] print(response + " is added to front of list. New list ==>") # add the fruit to front of the list print(a_list2 + a_list) # enter another fruit response = input("Enter another fruit name > ") # insert an item to front of the list a_list.insert(0, response) print("Inserted " + response + " to front of list.") #display the list print(a_list) # print fruit name starts with 'P' for item in a_list: if 'P' in item: print(item) # Series 2 print("Series 2: Display the list ==>") print(a_list) # remove the last fruit a_list.pop() print("Removed last item on list, new list ==> ") print(a_list) # ask for a fruit to delete response = input("Enter a fruit to delete > ") a_list.remove(response) print(" Removed " + response + ", new list ==> ") print(a_list) #Series 3 print("Series 3: Display the list ==>") print(a_list) response = 'maybe' for i in a_list[:]: response = input("Do you like " + i.lower() + "? ") while response != 'yes' and response != 'no': response = input("Do you like " + i.lower() + "? ") if response == 'no': a_list.remove(i) print(a_list) #Series 4 another_list = [x[::-1] for x in a_list][::-1] print("Delete last item from original list, new list ==>") a_list.pop() print(a_list) print("Reversed the letters in each fruit, new list ==>") print(another_list)
true
3f8e1b8a5567f21657151c2fe8d7a2652e6a6422
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/njschafi/Lesson03/list_lab.py
1,245
4.1875
4
#!/usr/bin/env python3 # NEIMA SCHAFI, LESSON 3 Assignment - list_lab #SERIES 1 fruit = ['Apples', 'Pears', 'Oranges', 'Peaches'] print(fruit) response = input("Please enter another fruit: ") fruit.append(response.title()) print(fruit) response2 = int(input("Please enter a number above zero: ")) print(fruit[response2-1]) fruit = ['Lemon'] + fruit print(fruit) fruit.insert(0, 'Banana') print(fruit) for item in fruit: if item[0][0] == 'P': print(item) #SERIES 2 print(fruit) fruit = fruit[:-1] print(fruit) response3 = input("Please enter a fruit to delete: ") if response3.title() in fruit: fruit.remove(response3.title()) print(fruit) #SERIES 3 fruit = ['Apples', 'Pears', 'Oranges', 'Peaches'] fruit2 = ['Apples', 'Pears', 'Oranges', 'Peaches'] for n in fruit: response4 = input("Do you like {}? ".format(n.lower())) while not response4.lower() in ['yes', 'no']: response4 = input('Please enter yes or no:\n') if response4.lower() == 'no': fruit2.remove(n) fruit = fruit2 print(fruit) #SERIES 4 fruit = ['Apples', 'Pears', 'Oranges', 'Peaches'] fruit2 = [] for item in fruit: fruit2.append(item[::-1]) fruit = fruit[:-1] print(fruit) print(fruit2)
false
b5e083e33cf2b7ba7a0d47d1f589757af6b1685b
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/SLammertink/Lesson03/strformat_lab.py
2,257
4.5
4
#! /usr/bin/env python3 # UW Self paced Lesson 03 string lambda # Task 1 ''' Write a format string that will take the following four element tuple: ( 2, 123.4567, 10000, 12345.67) and produce: 'file_002 : 123.46, 1.00e+04, 1.23e+04' ''' StrList = (2, 123.4567, 10000, 12345.67) def Task1(): print(f"file_{StrList[0]:03d} : {StrList[1]:.2f}, {StrList[2]:.2e}, {StrList[3]:.2e}") # task 2 '''Using your results from Task One, repeat the exercise, but this time using an alternate type of format string (hint: think about alternative ways to use .format() (keywords anyone?), and also consider f-strings if you’ve not used them already). ''' def Task2(): print("file_{0:03d} : {1:.2f}, {2:.2e}, {3:.2e}".format(StrList[0], StrList[1], StrList[2], StrList[3])) print("file_%03d : %.2f, %.2e, %.2e" % StrList) # Task 3 ''' Rewrite: "the 3 numbers are: {:d}, {:d}, {:d}".format(1,2,3) to take an arbitrary number of values.''' def formatter(in_tuple): formatter_string = "the " + str(len(in_tuple)) + " numbers are " + ", ".join(["{}"]*len(in_tuple)).format(*in_tuple) print(formatter_string) # Task 4 '''Given a 5 element tuple: ( 4, 30, 2017, 2, 27) use string formating to print: '02 27 2017 04 30' ''' five_tuple = ( 4, 30, 2017, 2, 27) def TaskFour(five_tuple): reformat = "{0:02d} {1:d} {2:d} {3:02d} {4:d}" print(reformat.format(five_tuple[3], five_tuple[4], five_tuple[2], five_tuple[0], five_tuple[1])) # Task 5 print(f'The weight of an {str(fruit_list[0])[:-1]} is {fruit_list[1]} and the weight of a {str(fruit_list[2])[:-1]} is {fruit_list[3]}') # Now see if you can change the f-string so that it displays the names of the fruit in upper case, and the weight 20% higher print(f'The weight of an {str(fruit_list[0])[:-1].upper()} is {fruit_list[1] * 1.2} and the weight of a {str(fruit_list[2].upper())[:-1]} is {fruit_list[3] * 1.2}') # Task 6 # Write some Python code to print a table of several rows, each with a name, an age and a cost. Make sure some of the costs are in the hundreds and thousands to test your alignment specifiers. rows = [('Name', 'Age', 'Cost'),('Seb', 50, 200),('Kim', 47, 5000), ('Mike', 25, 375.25)] for row in rows: print("{:^10}{:^10}{:^10}".format(*row))
true
651789601f0720d6062045e557e226ee50fccf2d
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/ador_yano/Lesson02/Series.py
2,197
4.34375
4
# Series.py: implements Fibonacci Series Exercise for Lesson 2 Assignment intro = '''UWPCE Python Programming: Lesson 2 Assignment Fibonacci Series Exercise: fibonnaci and lucas functions to return nth value of each series, generalized series function with three parameters 1. fib(n) - series starts with 0 and 1, returns nth value from zero index 2. lucas(n) - series starts with 2 and 1, returns nth value from zero index 3. sum_series(n, a, b) - optional arguments a and b default to 0 and 1, can be set to other values returns nth value ''' print(intro) def fib(n): """ Return nth value in Fibonacci series """ if n < 0: # check for negative numbers print("Invalid argument") elif n == 0: # first value (zero index) in Fibonacci is 0 return 0 elif n == 1: # second value in Fibonacci is 1 return 1 else: return fib(n-2) + fib(n-1) # nth value is the sum of the previous two values in the series def lucas(n): """ Return nth value in Lucas series """ if n < 0: # check for negative numbers print("Invalid argument") elif n == 0: # first value (zero index) in Lucas is 2 return 2 elif n == 1: # second value in Lucas is 1 return 1 else: return lucas(n-2) + lucas(n-1) # nth value is the sum of the previous two values in the series def sum_series(n,a=0,b=1): """ Return nth value in generalized series seeded by a and b parameters """ if n < 0: # check for negative numbers print("Invalid argument") elif n == 0: # first value (zero index) set by a parameter return a elif n == 1: return b # second value set by b parameters else: return sum_series(n-2,a,b) + sum_series(n-1,a,b) # nth value is the sum of the previous two values in the series def tests(): assert fib(9) == 34 assert lucas(9) == 76 assert sum_series(9) == 34 assert sum_series(9,2,1) == 76 assert sum_series(5,3,8) == 49
true