blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
e24920a841c579ae46d74a759d9148c858222ea4
johnson365/python
/Design Pattern/Observer.py
1,986
4.1875
4
"""Implementation of Observer pattern""" from abc import ABCMeta, abstractmethod class Subject: """The abstract class of Subject put all Observer object in a collection!""" def __init__(self): self.observers = [] def attachObserver(self, observer): """add a observer into observer collection""" self.observers.append(observer) def removeObserver(self, observer): """remove a observer from observer collection""" self.observers.remove(observer) def notify(self): """notify all observers when state changed""" for ob in self.observers: ob.updateState() class Observer: """The abstract class of Observer""" __metaclass__ = ABCMeta @abstractmethod def updateState(self):pass class ConcreteSubject(Subject): """The concrete class of subject""" def __init__(self): Subject.__init__(self) self.__subjectState = None def getSubjectState(self): return self.__subjectState def setSubjectState(self, state): self.__subjectState = state class ConcreteObserver(Observer): """ The concrete class of Observer""" def __init__(self, subject, name): self.__subject = subject self.__name = name self.__state = None def getSubject(self): return self.__subject def setSubject(self, subject): self.__subject = subject def updateState(self): """update state by subject`s state""" self.__state = self.__subject.getSubjectState() print "Observer%s `s new state is %s" % (self.__name, self.__state) if __name__ == '__main__': s = ConcreteSubject() x = ConcreteObserver(s, 'x') y = ConcreteObserver(s, 'Y') z = ConcreteObserver(s, 'z') s.attachObserver(x) s.attachObserver(y) s.attachObserver(z) s.setSubjectState("ABC") s.notify()
true
d37eec249f9eae3f11d1eff5939199c62054ffaf
JSheldon3488/Daily_Coding_Problems
/Chapter6_Trees/6.3_Evaluate_Arithmetic_Tree.py
2,033
4.15625
4
""" Date: 7/7/20 6.3: Evaluate Arithmetic Tree """ class Node(): """ Node class used for making trees """ def __init__(self, val, left = None, right = None): self.val = val self.left = left self.right = right ''' Problem Statement: Suppose an arithmetic expression is given as a binary tree. each leaf is an integer and each internal node is one of +,-,*,/. Given the root of such a tree, write a function to evaluate it. Example: * + + 3 2 4 5 Should return 45. (3+2) * (4+5) in-order: [3, +, 2, *, 4, +, 5] pre-order: [*, +, 3, 2, +, 4, 5] ''' ''' My Solution ''' def evaluate(root: Node) -> int: # Base Case: if isinstance(root.val, int): return root.val # Recursive Case: elif root.val == '*': return evaluate(root.left) * evaluate(root.right) elif root.val == '+': return evaluate(root.left) + evaluate(root.right) elif root.val == '-': return evaluate(root.left) - evaluate(root.right) else: try: return evaluate(root.left)/evaluate(root.right) except ZeroDivisionError: return ZeroDivisionError ''' Book Solution ''' """ Same solution that I came up with. Note this is O(n) time and O(h) space complexity """ ''' Test Cases ''' def main(): assert evaluate(Node('*', left=Node('+', Node(3), Node(2)), right=Node('+', Node(4), Node(5)))) == 45 assert evaluate(Node('*', left=Node('+', Node(3), Node(2)), right=Node('+', Node(4), Node(5)))) != 35 assert evaluate(Node('*', left=Node('-', Node(3), Node(2)), right=Node('-', Node(4), Node(5)))) == -1 assert evaluate(Node('/', left=Node('+', Node(3), Node(2)), right=Node('-', Node(5), Node(5)))) == ZeroDivisionError if __name__ == '__main__': main() ''' Lessons Learned: * '''
true
4ec43707554a617f2211609ec94ab0fbc756e70f
JSheldon3488/Daily_Coding_Problems
/Chapter4_Stacks_and_Queues/Stack.py
1,565
4.21875
4
class Stack: """ A basic Stack class following "last in, first out" principle. Supports methods push, pop, peek, and size. The stack is initialized as empty. Attributes: Size: Keeps track of the size of the stack """ def __init__(self): """ Initializes the stack to an empty list with size 0 """ self.stack = [] self.size = 0 def __str__(self): """ Returns String representation of the stack. Top of stack is first element printed""" s = "Stack( " for i in range(self.size -1, -1, -1): s += str(self.stack[i]) if i != 0: s += " --> " s += " )" return s def push(self,data): """ Pushes 'data' onto the top of the stack (the back of the list) :param data: data to be pushed onto the stack """ self.stack.append(data) self.size += 1 def pop(self): """ Returns and removes the 'data' from the top of the stack :return: data from the top of the stack """ if self.size == 0: raise ValueError("The Stack is Empty") self.size -= 1 return self.stack.pop() def peek(self): """ Returns the 'data' from the top of the stack but does not remove the data. :return: 'data from the top of the stack """ if self.size == 0: raise ValueError("The Stack is Empty") return self.stack[-1]
true
ef6fa04462315f367b3d91186bbf2f3ed48fb559
JSheldon3488/Daily_Coding_Problems
/Chapter8_Tries/8.2_PrefixMapSum.py
2,066
4.25
4
""" Date: 7/26/20 8.2: Create PrefixMapSum Class """ ''' Problem Statement: Implement a PrefixMapSum class with the following methods: def insert(key: str, value: int) Set a given key's value in the map. If the key already exists overwrite the value. def sum(prefix: str) Return the sum of all values of keys that begin with a given prefix. Example: mapsum.insert("columnar", 3) assert mapsum.sum("col") == 3 mapsum.insert("column", 2) assert mapsum.sum("col") == 5 ''' from Trie import Trie, ENDS_HERE from collections import defaultdict ''' My Solution ''' class PrefixMapSum: def __init__(self): self._trie = Trie() self.values = defaultdict(int) def insert(self, key: str, value: int): self._trie.insert(key) self.values[key] = value def sum(self, prefix: sum): # Get all possible words with prefix words = self.complete_words(prefix, self._trie.find(prefix)) # Sum values from values dictionary for all possible words return sum(self.values[word] for word in words) def complete_words(self, prefix, prefix_dict: dict): words = [] for key, next_level in prefix_dict.items(): if key == ENDS_HERE: words.append(prefix) else: words.extend(self.complete_words(prefix + key, next_level)) return words ''' Book Solution ''' ''' Test Cases ''' def main(): mapsum = PrefixMapSum() mapsum.insert("columnar", 3) assert mapsum.sum("col") == 3 mapsum.insert("column", 2) assert mapsum.sum("col") == 5 if __name__ == '__main__': main() ''' Lessons Learned: * Using key.startswith(prefix) would allow us to do this without even using a trie and would make insertions fast but would do poorly with summation because it will check every single key in the dictionary * '''
true
608ed5c38e186df1ef955933bf6c77a3aa340ef1
ARON97/Desktop_CRUD
/backend.py
1,676
4.28125
4
import sqlite3 class Database: # constructor def __init__(self, db): self.conn = sqlite3.connect(db) self.cur = self.conn.cursor() self.cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer)") self.conn.commit() def insert(self, title, author, year, isbn): # The id is an autoincrement value so we will pass in null self.cur.execute("INSERT INTO book VALUES (NULL, ?, ?, ?, ?)", (title, author, year, isbn)) self.conn.commit() def view(self): # The id is an autoincrement value so we will pass in null self.cur.execute("SELECT * FROM book") rows = self.cur.fetchall() return rows # All search. The user will enter in a title or auther or isbn or year def search(self, title = "", author = "", year = "", isbn = ""): self.cur.execute("SELECT * FROM book WHERE title=? OR author=? OR year=? OR isbn=?", (title, author, year, isbn)) rows = self.cur.fetchall() return rows # Delete a record by selecting a record from the listbox def delete(self, id): self.cur.execute("DELETE FROM book WHERE id = ?", (id,)) # Note enter comma after id self.conn.commit() # Update a record by selecting a record from the listbox and display the record in the widget def update(self, id, title, author, year, isbn): self.cur.execute("UPDATE book SET title = ?, author = ?, year = ?, isbn = ? WHERE id = ?", (title, author, year, isbn, id)) self.conn.commit() # destructor def __del__(self): self.conn.close() #insert("The Earth", "John Doe", 1997, 225555852) #delete(3) # update(4, "The moon", "John Smith", 1917, 985557) # print(view()) # print(search(author="Aron Payle"))
true
5990428dbea6421d99b43c21c6c83c55f2617a59
matthewmuccio/Assessment1
/q1/run.py
1,969
4.28125
4
#!/usr/bin/env python3 import random # Helper function that gets the number of zeroes in the given list. def get_num_zeroes(x): num = 0 for i in x: if i == 0: num += 1 return num # Moves all the 0s in the list to the end while maintaining the order of the non-zero elements. def move_zeroes(x): length = len(x) # Length of the given list. num_zeroes = get_num_zeroes(x) # Gets the number of zeroes that must be moved. count = 0 # Counts the number of zeroes that have been moved to the end of the list. i = length - 1 # current index i is initially set to the last element's index. # Iterating through the list backward. while i >= 0: # If the current element is 0 and it is not in the correct place (at end of list). if x[i] == 0 and i <= length - num_zeroes: # Swap adjacent elements until the current element (0) is at end of list. while i < length - 1: temp = x[i] x[i] = x[i + 1] x[i + 1] = temp i += 1 # If the current index is at the last element's index, # we successfully moved the 0. if i == length - 1: count += 1 i -= 1 # If we have moved all zeroes to the end of the list we're done, break out of the loop. if count == num_zeroes: break return x # Returns the same list that was passed in as an argument (#in-place). # My alternate implementation of the function using list comprehensions (not in-place). #def move_zeroes(x): # return [not_zero for not_zero in x if not_zero != 0] + [zero for zero in x if zero == 0] # Tests if __name__ == "__main__": # Given test case. x = [0, 0, 1, 0, 3, 12] print("Given list:") print(x) print("Result:") print(move_zeroes(x)) print() # Random test case. lst = [0, 0] # Loads two zeroes into the list for simpler testing. for i in range(9): # Loads eight more random integers into the list. rand_num = random.randint(0, 25) lst.append(rand_num) print("Given list:") print(lst) print("Result:") print(move_zeroes(lst))
true
95ba120923b093a6af9636f643f12719e0dee77e
angelinka/programming4DA
/week5/lab5DatastrTuple.py
588
4.4375
4
#Program creates a tuple that stores the months of the year, from that tuple create #another tuple with just the summer months (May, June, July), print out the #summer months one at a time. #Author: Angelina B months = ("January", "February", "March", "April", "May", "June", "july", "August", "September", "October", "November", "December" ) # Slicing months to get 3 summer months in another tuple summerMonths = months[4:7] for month in summerMonths: print (month)
true
2bcf78b22555bc9db039525d2afb2fecae2fcce6
caoxiang104/algorithm
/data_structure/Linked_List/Singly_Linked_List.py
2,847
4.1875
4
# coding=utf-8 # 实现带哨兵的单链表 class LinkedList(object): class Node(object): def __init__(self, value, next_node): super(LinkedList.Node, self).__init__() self.value = value self.next = next_node def __str__(self): super(LinkedList.Node, self).__str__() return str(self.value) def __init__(self, *arg): super(LinkedList, self).__init__() self.nil = LinkedList.Node(None, None) self.nil.next = self.nil self.length = 0 for value in arg: self.append(value) def append(self, value): temp_node = self.nil node = LinkedList.Node(value, temp_node) while temp_node.next is not self.nil: temp_node = temp_node.next temp_node.next = node self.length += 1 return self.length def prepend(self, value): temp_node = self.nil node = LinkedList.Node(value, temp_node.next) temp_node.next = node self.length += 1 return self.length def insert(self, index, value): cur_node = self.nil cur_pos = 0 if index > self.size(): raise IndexError("Can't insert value beyond the list") while cur_pos < index: cur_node = cur_node.next cur_pos += 1 node = LinkedList.Node(value, cur_node.next) cur_node.next = node self.length += 1 return self.length def delete(self, value): cur_node = self.nil.next temp_node = self.nil while cur_node is not self.nil: if cur_node.value == value: break else: cur_node = cur_node.next temp_node = temp_node.next if cur_node is not self.nil: temp_node.next = cur_node.next self.length -= 1 return cur_node.value def search(self, value): cur_node = self.nil.next while cur_node is not self.nil and cur_node.value != value: cur_node = cur_node.next return cur_node.value def size(self): return self.length def __str__(self): super(LinkedList, self).__str__() cur_node = self.nil.next link_ = [] while cur_node is not self.nil: link_.append(str(cur_node)) cur_node = cur_node.next return '[' + ",".join(link_) + ']' def main(): link_ = LinkedList(2, 3, 5) print(link_) for i in range(10): link_.append(i) print(link_) link_ = LinkedList(1, 2, 3) for i in range(10): link_.prepend(i) print(link_) print(link_.size()) link_.insert(2, 100) print(link_) link_.delete(2) print(link_) print(link_.search(100)) if __name__ == '__main__': main()
true
62540e1e6192619838f134c1499907cbf03cf019
XuQiao/codestudy
/python/pythonSimple/list_comprehension.py
309
4.1875
4
listone = [2,3,4] listtwo = [2*i for i in listone if i>3] print (listtwo) def powersum(power, *args): '''Return the sum of each arguments raised to specified power''' total = 0 for i in args: total = total + pow(i,power) return total print (powersum(1,23,34)) print (powersum(2,10))
true
80fd1179076556a77d87ebe6aae78c2edd03ddf5
jhobaugh/password_generator
/password_generator.py
822
4.1875
4
# import random, define a base string for password, name, and characters in password import random password = "" name = "" chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789!#$%&" # while loop to ensure a password is outputted while password == "": # limit input limit = int(input("Thanks for using python password generator!\n" "How many characters would you like in your password? (minimum of 6): ")) # name input name = (input("What would you like to name the password?: ")) # character limiter if limit < 6: print("The minimum password length is 6") else: # character selector for c in range(limit): password += random.choice(chars) # print statement print(name + "\n" + password)
true
49a2f2e2c4b0da26013b635c66045373ad9e2654
xchmiao/Leetcode
/Tree/145. Binary Tree Postorder Traversal.py
2,366
4.15625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None ## Solution-1 ''' 1.1 Create an empty stack 2.1 Do following while root is not NULL a) Push root's right child and then root to stack. b) Set root as root's left child. 2.2 Pop an item from stack and set it as root. a) If the popped item has a right child and the right child is at top of stack, then remove the right child from stack, push the root back and set root as root's right child. b) Else print root's data and set root as NULL. 2.3 Repeat steps 2.1 and 2.2 while stack is not empty. ''' class Solution(object): def peekStack(self, stack): if len(stack) > 0: return stack[-1] else: return None def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] else: result = [] stack_nodes = [] node = root while True: while node: if node.right: stack_nodes.append(node.right) stack_nodes.append(node) node = node.left node = stack_nodes.pop() top_node = self.peekStack(stack_nodes) if (node.right == top_node) and (node.right is not None): stack_nodes.pop() stack_nodes.append(node) node = node.right else: result.append(node.val) node = None if len(stack_nodes) == 0: break return result ## Solution-2 class Solution(object): def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if root is None: return [] stack, output = [root, ], [] while stack: root = stack.pop() output.append(root.val) if root.left is not None: stack.append(root.left) if root.right is not None: stack.append(root.right) return output[::-1]
true
ec8e857911afcc4b2e7c74377913639f5a4b964c
zheguang/fun-problems
/longest_common_sequence.py
1,503
4.21875
4
#!/usr/bin/env python # Longest common sequence # Given two strings, the task is to find the longest common sequence of letters among them. # The letters do not have to be next to each other in the original string. # E.g. C D E F G A B # D E G B R T Z # output: D E G B # # It is interesting to compare this problem to longest increasing sequence. # The subproblem search space is different. # In longest increasing sequence, the search space is the LIS[i:-1] for all i. # But for longest common sequence, the search space is similat to the edit distance # i.e. LCS[0:-1]. # To determine the proper search space, it is important to know what the final optimal # answer might be from. memo = {} def longest_common_sequence(xs, ys): if (tuple(xs), tuple(ys)) in memo: lcs = memo[(tuple(xs), tuple(ys))] else: # can't use xs == [] comparison because string xs and list xs is different in python. if len(xs) == 0 or len(ys) == 0: lcs = [] else: lcs = max([ longest_common_sequence(xs[:-1], ys), longest_common_sequence(xs, ys[:-1]), longest_common_sequence(xs[:-1], ys[:-1]) + [xs[-1]] if xs[-1] == ys[-1] else [] ], key=lambda xs: len(xs)) memo[(tuple(xs), tuple(ys))] = lcs return lcs def main(): xs = 'helloworld' ys = 'foobarbusdust' lcs = longest_common_sequence(xs, ys) print(lcs) if __name__ == '__main__': main()
true
a2da9360fd828ab92db4f8f4b7d13c25327309e4
ruslanfun/Python_learning-
/if_elif3.py
360
4.25
4
# Ask the user to enter a number between 10 and 20 (inclusive). # If they enter a number within this range, display the message “Thank you”, # otherwise display the message “Incorrect answer” number = int(input("enter a number between 10 and 20: ")) if number >= 10 and number <= 20: print('thank you') else: print('incorrect answer')
true
1223e8cd384e5be4bf36329a22e85c3b538522b7
Priya-Mentorship/Python4Everybody
/arrays/adding.py
427
4.1875
4
import array as arr numbers = arr.array('i', [1, 2, 3, 5, 7, 10]) # changing first element numbers[0] = 34 print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10]) # changing 3rd to 5th element numbers[2:5] = arr.array('i', [4, 6, 8]) print(numbers) # Output: array('i', [0, 2, 4, 6, 8, 10]) numbers.append(6) numbers.insert(5,0) numbers2 = arr.array('i', [10,20,20]) numbers.extend(numbers2) print(numbers)
true
8f6d3c5ab8ca31a8aaba3fb47e7234f0fa0c95c6
onuratmaca/Data-Analysis-w-Python-2020
/compliment.py
583
4.6875
5
#!/usr/bin/env python3 """ Exercise 2 (compliment) Fill in the stub solution to make the program work as follows. The program should ask the user for an input, and the print an answer as the examples below show. What country are you from? Sweden I have heard that Sweden is a beautiful country. What country are you from? Chile I have heard that Chile is a beautiful country. """ def main(): # Enter you solution here country = input("What country are you from? ") print(f"I have heard that {country} is a beautiful country.") if __name__ == "__main__": main()
true
bb24c91663b4d3b52360a20fe35942c92daf7904
erarpit/python_practise_code
/secondprogram.py
324
4.125
4
print('A program for print list function') list = [ 2,4,5,5,5,6,'hello','ratio' ] print(list) print(list[4]) list.remove('hello') print(list) list.append('my') print(list) print(list[3:8]) newlist = list.copy() print(newlist) print(newlist.count(6)) print(newlist) list.index('my') print("printlist:",list)
true
9573ba807776f8906f1da9e66a0f5c9ec2d6979f
blackviking27/Projects
/text_based_adventure.py
2,162
4.25
4
# text based adventure game print("Welcome to text adventure") print("You can move in two directions left and right and explore the rooms") print("but you cannot go beyond the rooms since it is not safe for you as of now") print("r or right to go in right direction") print("l or left to go in left direction") room=[1,2,3,4,5,6] a = room[0] #initial room number i=1 while i>0: try: def room(n): #defining each room with its own proprties print("You are in room number",n) if n==1: print("This a magical room full of magic") elif n==2: print("This room is full of nightmares all around the world") elif n==3: print("This room belongs to the wisest man on the planet") elif n==4: print("This room belongs to the strongest man on the planet") elif n==5: print("This room belongs to someone unknown for centuries") elif n==6: print("This room is out of bounds for people") def left(): l=globals()['a']-1 if l>=1: room(l) else: print("There is no room in that direction") def right(): r =globals()['a']+1 if r<=6: room(r) else : print("There is no room in that direction") def main(): dir = input("Which direction you want to move") if dir == 'right' or dir == 'r': right() elif dir == 'left' or dir == 'l': left() else: print("Enter a valid direction") main() q=input("If you want to quit you can enter q or exit if not then press enter") if q == 'q' or q == "exit": break except Exception as e: pass i+=1 print("Thank you for playing the game") print("Hope to see you again")
true
e3e5eeb60adb1ad74935c816db64847c71e7bf98
khadley312/NW-Idrive
/Exercise Files/Ch2/variables_start.py
564
4.3125
4
# # Example file for variables # # Declare a variable and initialize it f=0 print(f) # # re-declaring the variable works f="abc" print(f) # # ERROR: variables of different types cannot be combined print("this is a string" + str(123)) # Global vs. local variables in functions def someFunction(): global f #this makes the f variable in this function global to outside of the function f="def" print(f) someFunction() print(f) del f #this deletes that global variable causing the next line to create an error in the code since f is deleted print(f)
true
2e003018aa4a1511f5cb3a1e18202e5c2e47b0b5
marsbarmania/ghub_py
/codingbat/Logic-1/near_ten.py
464
4.125
4
# -*- coding: utf-8 -*- # Given a non-negative number "num", # return True if num is within 2 of a multiple of 10. # Note: (a % b) is the remainder of dividing a by b, # so (7 % 5) is 2. def near_ten(num): remainder = num while remainder > 10: remainder %= 10 # print "remainder: ",remainder return True if remainder <= 2 or remainder >= 8 else False print near_ten(12) # True print near_ten(17) # False print near_ten(19) # True print near_ten(29)
true
155580584152bc4acf0d52f76e7ee6491b4739dc
ananyapoc/CPSC230
/CPSC230/APochiraju_2/newvolume.py
459
4.3125
4
#this is to calculate the volume of a cylinder import math #asking the user for inputs r=int(input("give me a length for the radius of the cylinder")) #stating conditions for radius if(r==0): print("please do not give zero") elif(r!=0): h=int(input("give me a length for the height of the cylinder")) #stating conditions for height if(h==0): print("please do not give zero") elif(h!=0): print((r*r)*h*math.pi) #calculating the volume using pi
true
39d4e818838bb596e46ed641193a64392a3f25e0
barbmarques/HackerRank-Python-Practice
/Basic_Python_Challenges.py
1,285
4.4375
4
# Print Hello, World! print("Hello, World!") # Given an integer,n, perform the following conditional actions: -- If n is odd, print Weird -- If n is even and in the inclusive range of 2 to 5, print Not Weird -- If n is even and in the inclusive range of 6 to 20, print Weird -- If n is even and greater than 20, print Not Weird if n%2 == 1: print('Weird') elif n >= 2 and n <= 5: print('Not Weird') elif n >= 6 and n <=20: print('Weird') else: print('Not Weird') # The provided code stub reads two integers from STDIN, a and. # Add code to print three lines where: # 1. The first line contains the sum of the two numbers. # 2. The second line contains the difference of the two numbers # 3. The third line contains the product of the two numbers print(a + b) print(a - b) print(a * b) # The provided code stub reads two integers, a and b, from STDIN. # Add logic to print two lines. The first line should contain the result of integer division a//b # The second line should contain the result of float division, a/b # No rounding or formatting is necessary. print(a//b) print(a/b) # The provided code stub reads an integer, n, from STDIN. # For all non-negative integers i<n, print i squared. i = 0 while i < n: print(i ** 2) i += 1
true
08d1d54fb84923904a94599150c528974fe86b3c
adid1d4/timer
/timer.py
1,114
4.15625
4
''' what should it do? it should decrease the seconds on the same line after the seconds go to 0, it should decrease a minute and get 59 on the seconds after this the iteration should repeat itself for the seconds when the minutes get to 0, the hour should decrease by 1, the minutes to 59, seconds to 59 and the iteration for the seconds should repeat itself. ''' import time import os import sys print "Working here, take another computer." print "It will show how to terminate after the time is done" print "I mean If I don't come by the timer eta" h = 2 m = 1 s = 5 # if the time given is negative or not wanted if s > 59 or m>59 or m<0 or s<0 or h<0: print "error. Please type the correct time." sys.exit(0) # the main idea while h>-1: print str(h)+':'+str(m)+':'+str(s) os.system('clear') if -1<s: s = s-1 time.sleep(1) if s==-1: m = m-1 if m == -1: h = h-1 if h==0 and s==0: m = 0 s - 59 m=59 s=59 s = 59
true
6a3afca3067a704a06be3892fdc773b16054bc69
njounkengdaizem/eliteprogrammerclub
/capitalize.py
962
4.34375
4
# write a simple program that takes a sentence as input, # returns the capitalized for of the sentence. ############################################################# result = "" # an empty string to hold the resulting string sentence = input("Enter a word: ") # gets inputs from the user sentence = sentence.capitalize() sentence_list = sentence.split('.') list = [] for word in sentence_list: list.append(word.strip()) # takes out every whitespace between splited sentence sentence = list for word in sentence: # here goes the magic result += word[0].upper() + word[1:] + '. ' # converts the first letter of the split string to uppercase print(result[:]) # then concatenates the remaining letters and adds a # full stop and empty space between the words.
true
7d2ca4711e013e5493e0532ad89d5c10380d73c3
mikestrain/PythonGA
/firstPythonScript.py
349
4.28125
4
print("this should be printed out") #this is a comment # print("The number of students is "+str(number_of_students)) # print(3**3) number_of_students = 6 number_of_classes = 10 total = number_of_students + number_of_classes print('number of students + number of classes = ' + str(total)) print('number of students + number of classes =', total)
true
725e62fb19f409922b89b8cbfc94669976130255
17c23039/The-Unbeatable-Game
/main.py
2,939
4.375
4
from time import sleep import random score = int(0) print("Rock Paper Scissors, Python edition! This project is to see how complicated and advanced I can make a RPS game.") sleep(3) print("When it is your turn, you will have three options. [R]ock, [P]aper and [S]cissors! For a loss you will lose a point, a tie it will stay the same, and a win will add a point.") sleep(5) print("Let's begin.") while score < 5 : rpschoice = input("Rock, paper, or scissors? R/P/S. ") sleep(1) print("Rock,") sleep(1) print("Paper,") sleep(1) print("Scissors,") sleep(1) print("Shoot!") sleep(1) aichoice = random.randint(1, 1) if aichoice == 1 : print("Rock!") sleep(1) if rpschoice == "R" : print("Tie!") print(f"Your score is {score}.") elif rpschoice == "r" : print("Tie!") print(f"Your score is {score}.") elif rpschoice == "P" : print("You win!") score = score + 1 print(f"Your score is {score}.") elif rpschoice == "p" : print("You win!") score = score + 1 print(f"Your score is {score}.") elif rpschoice == "S" : print("I win!") score = score - 1 print(f"Your score is {score}.") elif rpschoice == "s" : print("I win!") score = score - 1 print(f"Your score is {score}.") else : print("Invalid option!") elif aichoice == 2 : print("Paper!") sleep(1) if rpschoice == "R" : print("I win!") score = score - 1 print(f"Your score is {score}.") elif rpschoice == "r" : print("I win!") score = score - 1 print(f"Your score is {score}.") elif rpschoice == "P" : print("Tie!") print(f"Your score is {score}.") elif rpschoice == "p" : print("Tie!") print(f"Your score is {score}.") elif rpschoice == "S" : print("You win!") score = score + 1 print(f"Your score is {score}.") elif rpschoice == "s" : print("You win!") score = score + 1 print(f"Your score is {score}.") else : print("Invalid option!") elif aichoice == 3 : print("Scissors!") sleep(1) if rpschoice == "R" : print("You win!") score = score + 1 print(f"Your score is {score}.") elif rpschoice == "r" : print("You win!") score = score + 1 print(f"Your score is {score}.") elif rpschoice == "P" : print("I win!") score = score - 1 print(f"Your score is {score}.") elif rpschoice == "p" : print("I win!") score = score - 1 print(f"Your score is {score}.") elif rpschoice == "S" : print("Tie!") print(f"Your score is {score}.") elif rpschoice == "s" : print("Tie!") print(f"Your score is {score}.") sleep(3) print("You have reached 5 points! Congrats, you win!") sleep(3) print("Oh? You stayed?") sleep(1) print("Right, let's move on.") sleep(1) import coinflip
true
7250d2b24e69dce512edb4f99cb2710e770c1d80
buggy213/ML-120_Materials
/Unit-035/traditional_five_starter.py
2,620
4.1875
4
import random import sys # We will be using the following encoding for rock, paper, scissors, lizard, and Spock: # Rock = 0 # Paper = 1 # Scissors = 2 # Lizard = 3 # Spock = 4 # # Fill in the below method with the rules of the game. # determineWinner is a structure called a method. The code in the method will run every time it is called. def determineWinner(userInput, computerInput): if(userInput == 0): if(computerInput == 0): print("Rock against rock! It's a tie!") elif(computerInput == 1): print("Paper beats rock! You lose!") elif(computerInput == 2): print("Rock beats scissors! You win!") # TODO: finish this if statement elif(userInput == 1): if(computerInput == 0): print("Paper beats rock! You win!") elif(computerInput == 1): print("Paper against paper! It's a tie!") elif(computerInput == 2): print("Scissors beats paper! You lose!") # TODO: finish this if statement elif(userInput == 2): if(computerInput == 0): print("Rock beats scissors! You lose!") elif(computerInput == 1): print("Scissors beats paper! You win!") elif(computerInput == 2): print("Scissors against scissors! You win!") # TODO: finish this if statement #TODO: add cases for userInput == 3, 4 #The main part of our program. Everything below here will run when we press the play button. playing = True while(playing): # Step 1: Get the user input userInput = int(input("\nEnter rock (0), paper (1), scissors (2), lizard (3), or Spock(4)\n")) # Step 2: Making sure that the user inputted a correct value if(userInput < 0 or userInput > 4): print("Please input 0, 1, 2, 3, or 4.") continue # Step 3: TODO: Finish the statement below, using a method from Python's random API. computerInput should be between 0 and 2. computerInput = random.randint(0, 4) # Step 4: Printing out the computer's choice of rock, paper, or scissors if(computerInput == 0): print("Computer chose rock.") elif(computerInput == 1): print("Computer chose paper.") elif(computerInput == 2): print("Computer chose scissors.") elif(computerInput == 3): print("Computer chose lizard.") elif(computerInput == 4): print("Computer chose Spock.") else: print("Invalid input from computer: " + computerInput) continue # Step 5: Calling the determineWinner method here determineWinner(userInput, computerInput) # Step 6: Seeing if the user would like to play the game again playAgain = input("\nPlay again? [y or n]\n") if(playAgain == "n"): playing = False
true
ac65076020ab2a9aa50ee4ea7f31679a90cdf949
The-SS/parallel_python_test
/parallel_py_test.py
2,517
4.25
4
# Author: # Sleiman Safaoui # Github: # The-SS # Email: # snsafaoui@gmail.com # sleiman.safaoui@utdallas.edu # # Demonstrates how to use the multiprocessing.Process python function to run several instances of a function in parallel # The script runs the same number of instance of the function in series and parallel and compare the execution time # Note: Running a small number of instance will not demonstrate the advantages of parallel processing # from __future__ import print_function import multiprocessing as mp import time def function1(num1, num2): # function to run multiple instances of sum1 = 0 if num1 < num2: for i in range(num2 - num1): sum1 += 1 elif num2 < num1: for i in range(num1 - num2): sum1 += 1 else: sum1 = 0 print('returning: ', sum1) return sum1 def run_parallel_instances(number_of_instances_to_run): ''' runs several instances of function1 in parallel ''' cpu_count = mp.cpu_count() # get number of CPUs available print(cpu_count, ' available. Will use all of them') start_time = time.time() # for timing all_events = [] for count in range(1, number_of_instances_to_run): event = mp.Process(target=function1, args=(1, (count * count) ** 3)) # start a process for each function (target takes function name and args is the arguments to pass) event.start() # start the function but don't wait for it to finish all_events.append(event) # store handle for the process for e in all_events: e.join() # join the parallel threads end_time = time.time() print('Ran ', number_of_instances_to_run, 'parallel instances') print('Finished Parallel processes in: ', end_time - start_time) return end_time - start_time def run_sequential_instances(number_of_instances_to_run): ''' runs several instances of function1 sequentially ''' start_time = time.time() for count in range(1, number_of_instances_to_run): function1(1, (count * count) ** 3) end_time = time.time() print('Ran ', number_of_instances_to_run, 'sequential instances') print('Finished Sequential processes in: ', end_time - start_time) return end_time - start_time if __name__ == "__main__": number_of_instances_to_run = 20 s_time = run_sequential_instances(number_of_instances_to_run) p_time = run_parallel_instances(number_of_instances_to_run) print('Sequential time: ', s_time) print('Parallel time: ', p_time)
true
cef145f7edee15add71fd819ba64d39c7cb2f052
paulyun/python
/Schoolwork/Python/In Class Projects/3.10.2016/InClassActivity_3.10.2016.py
390
4.1875
4
#In class Activity for 3/10/2016 totalTime = int(input ("Enter a time in seconds")) resultMinutes = int(totalTime / 60) #this function divides the users totaltime by 60 to get the minute value resultSeconds = totalTime % 60 #this function gets the remainder value of the totaltime divided by 60 to get the remaining seconds value print (resultMinutes,"Minutes", resultSeconds,"Seconds")
true
27e0fcf49ea15c5bccf24a5858c85809fe5f022e
paulyun/python
/Schoolwork/Python/In Class Projects/5.17.2016/Palindrome.py
268
4.21875
4
def isPalindrome(): word = input("Please enter a word to see if it is Palindrome") reverse = "" for letter in range(len(word)-1, -1, -1): #range(start, stop, sequence) reverse+=word[letter] return reverse == word print(isPalindrome())
true
1ac8cbf4abb9d670f1e38bb7cfb706f0f8326308
Saksham-Bhardwaj/Password-Validation
/ValidationModule.py
1,105
4.25
4
#regex module import re #function to validate each password input def checkPass(str): if(len(str)<6 or len(str)>12): print(str + " Failure password must be 6-12 characters.\n") return if not re.search("[a-z]", str): print(str + " Failure password must contain at least one letter from a-z \n") return if not re.search("[A-Z]", str): print(str + " Failure password must contain at least one letter from A-Z \n") return if not re.search("[0-9]", str): print(str + " Failure password must contain at least one number 0-9 \n") return if not re.search("[*$_#=@]", str): print(str + " Failure password must contain at least one letter from *$_#=@! \n") return if re.search("[%!)(]", str): print(str + " Failure password cannot contain %!)( \n") return print(str+" Success\n") return #main function if __name__ == '__main__': password = input("Enter Password: ") arr = password.split(',') print("\n") for i in arr: checkPass(i)
true
2505d32f0cea8d1d6813edfcf2d87973e8524b77
IMDCGP105-1819/text-adventure-Barker678
/Player.py
1,132
4.25
4
class Player(object): #we create a Player class that affects the inventory of the player, the players name and given direction to the player. def __init__ (self): self.Player = Player self.Name = "" #empty - for the players name self.inventory = [] #we define the inventory/we need it for the items def getname (self): return self.Name def setname (self, newname): #the name of the player will be the same in the whole game self.Name = newname def givedirections (self): #the directions of the game print ("Type the direction you want to walk.") print ("north") print("south") print ("east") print ("west") # when we go to a certain place, we add a item to the inventory def addItem (self, itemtoadd): # check to see if player already has item if itemtoadd in self.inventory: print ("There is nothing else in this room that can help.") else: # add item to player inventory self.inventory.append(itemtoadd) print(self.inventory)
true
112ead1004333cd0b246109dd25103e7e579820b
SpadinaRoad/Python_by_Examples
/Example_114/Example_114.py
1,019
4.15625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_114 # $ python3 Example_114.py # $ python3 Example_114.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 114 Using the Books.csv file, ask the user to enter a starting year and an end year. Display all books released between those two years. """ import csv print(__doc__) start_year = int(input('Enter the start year : ')) print(f'The input for the start year : {start_year}') print() end_year = int(input('Enter the end year : ')) print(f'The input for the end year : {end_year}') print() filename = "Books.csv" with open(filename, 'r') as fo: reader = csv.reader(fo, delimiter=',') for line in reader : try : year = int(line[2]) if year in range(start_year, end_year) : print(f'"{line[0]}" by {line[1]} published in {line[2]}') except : pass print()
true
67e75bf152ecf46e74dfd00fcdfc7fa44523f85c
SpadinaRoad/Python_by_Examples
/Example_035/Example_035.py
599
4.125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_035 # $ python3 Example_035.py # $ python3 Example_035.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 035 Ask the user to enter their name and then display their name three times. """ print(__doc__) name = '' while name != 'x' : name = input('Enter your name : ') print() print(f'The input for your name : {name}.') if name != 'x' : print(name * 3) print()
true
af64d3f5ecf4e84e40a4d58eeaf5112f12bf5595
SpadinaRoad/Python_by_Examples
/Example_058/Example_058.py
1,125
4.5
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_058 # $ python3 Example_058.py # $ python3 Example_058.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 058 Make a maths quiz that asks five questions by randomly generating two whole numbers to make the question (e.g. [num1] + [num2]). Ask the user to enter the answer. If they get it right add a point to their score. At the end of the quiz, tell them how many they got correct out of five. """ import random print(__doc__) score = 0 count = 0 while count < 5 : num_1 = random.randint(0,20) num_2 = random.randint(0,20) sum = num_1 + num_2 answer = int(input(f'What is the sum of {num_1} and {num_2}? ')) print(f'The input for the answer is {answer}.') print(f'The sum of {num_1} and {num_2} is {sum}.') if answer == sum : print(f'Your answer is correct.') score += 1 else : print('Wrong answer.') count += 1 print() print(f'Your score is {score} out of 5.')
true
17110747677a3be407ce36d3a27a5d415d7d9432
SpadinaRoad/Python_by_Examples
/Example_022/Example_022.py
870
4.5
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_022 # $ python3 Example_022.py # $ python3 Example_022.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 022 Ask the user to enter their first name and surname in lower case. Change the case to title case and join them together. Display the finished result. """ print(__doc__) fname = '' while fname != 'x' : fname = input('What is your first name? ') if fname != 'x' : lname = input('What is your last name? ') print() print(f'Input for first name : {fname}') print(f'Input for last name : {lname}') fname = fname.title() lname = lname.title() print(f'Your full name : {fname} {lname}.') print()
true
7603e32d8a1590523d33d29d2e331968e6881de0
SpadinaRoad/Python_by_Examples
/Example_121/Example_121.py
2,486
4.84375
5
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_121 # $ python3 Example_121.py # $ python3 Example_121.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 121 Create a program that will allow the user to easily manage a list of names. You should display a menu that will allow them to add a name to the list, change a name in the list, delete a name from the list or view all the names in the list. There should also be a menu option to allow the user to end the program. If they select an option that is not relevant, then it should display a suitable message. After they have made a selection to either add a name, change a name, delete a name or view all the names, they should see the menu again without having to restart the program. The program should be made as easy to use as possible. """ print(__doc__) def menu() : print('Main Menu') print('----------') print('A. List names') print('B. Add a name') print('C. Change a name') print('D. Delete a name') print('X. Exit') print() return input('Enter menu item : ') def list_names() : print('List of Names.') count = 1 for i in names_list : print(f'{count} : {i}') count += 1 def add_name() : new_name = input('Enter a new name: ') print(f'The input for a name : {new_name}') names_list.append(new_name) def change_name() : list_names() index = int(input(f'Enter the number for the name to change: ')) print(f'The input for the index: {index}') new_name = input('Enter the new name: ') print(f'The input for a name : {new_name}') print() names_list[index - 1] = (new_name) list_names() def delete_name() : list_names() index = int(input(f'Enter the number for the name to change: ')) print(f'The input for the index: {index}') del names_list[index - 1] names_list = [] choice = '' while choice != 'x' : choice = menu().lower() print(f'The input for the choice: {choice}') print() if choice == 'a' : list_names() elif choice == 'b' : add_name() elif choice == 'c' : change_name() elif choice == 'd' : delete_name() elif choice == 'x' : pass else : print('Please enter one of A, B, C, D or X.') print()
true
949e7b0d24b836761e0b5f326349dadd404c91c5
SpadinaRoad/Python_by_Examples
/Example_120/Example_120.py
2,377
4.59375
5
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_120 # $ python3 Example_120.py # $ python3 Example_120.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 120 Display the following menu to the user: 1) Addition 2) Subtraction Enter 1 or 2 : If they enter a 1, it should run a subprogram that will generate two random numbers between 5 and 20, and ask the user to add them together. Work out the correct answer and return both the user’s answer and the correct answer. If they entered 2 as their selection on the menu, it should run a subprogram that will generate one number between 25 and 50 and another number between 1 and 25 and ask them to work out num1 minus num2. This way they will not have to worry about negative answers. Return both the user’s answer and the correct answer. Create another subprogram that will check if the user’s answer matches the actual answer. If it does, display “Correct”, otherwise display a message that will say “Incorrect, the answer is” and display the real answer. If they do not select a relevant option on the first menu you should display a suitable message. """ import random print(__doc__) def addition() : a = random.randint(5, 20) b = random.randint(5, 20) value = a + b answer = int(input(f'What is {a} plus {b} : ')) print(f'The input for the answer: {answer}') print() return (value, answer) def subtraction() : a = random.randint(25, 50) b = random.randint(1, 25) value = a - b answer = int(input(f'What is {a} less {b} : ')) print(f'The input for the answer: {answer}') print() return(value, answer) def check_answer(a: 'numbers') : if a[0] == a[1] : print('Correct.') else : print('Incorrect.') def main() : print('1) Addition') print('2) Subtraction') choice = int(input('Enter 1 or 2 : ')) print() print(f'The input for choice : {choice}') print() if choice not in range(1, 2) : print('You choice cannot be processed.') print() return if choice == 1 : to_check = addition() elif choice == 2 : to_check = subtraction() check_answer(to_check) print() main()
true
89696d06bfc3e0760c8fa983b4bdffa34a54a6a7
SpadinaRoad/Python_by_Examples
/Example_087/Example_087.py
628
4.71875
5
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_087 # $ python3 Example_087.py # $ python3 Example_087.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 087 Ask the user to type in a word and then display it backwards on separate lines. For instance, if they type in “Hello” it should display as shown below: o l l e H """ print(__doc__) a_word = input('Enter a word : ') print(f'Input for a word : {a_word}') print() for i in range(len(a_word), 0, -1) : print(a_word[i - 1])
true
59d41de6a817138dd30562aab81ef9e878ced7f1
SpadinaRoad/Python_by_Examples
/Example_008/Example_008.py
768
4.34375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_008 # $ python3 Example_008.py # $ python3 Example_008.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 008 Ask for the total price of the bill, then ask how many diners there are. Divide the total bill by the number of diners and show how much each person must pay. """ print(__doc__) total = input('What is the total amount of the bill : ') diners = input('How many diners are there : ') average = int(total) / int(diners) print('') print(f'The total amount of the bill is {int(total):.2f}') print(f'The number of diners is {diners}') print(f'The cost per diner is {average:.2f}')
true
b674a22cbac308660674199958dda064260eeb78
SpadinaRoad/Python_by_Examples
/Example_118/Example_118.py
781
4.4375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_118 # $ python3 Example_118.py # $ python3 Example_118.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 118 Define a subprogram that will ask the user to enter a number and save it as the variable “num”. Define another subprogram that will use “num” and count from 1 to that number. """ print(__doc__) def get_num() : a_num = int(input('Enter a number : ')) print(f'The input for a number : {a_num}') print() return a_num def display_nums(a : 'number') : for i in range(1, a + 1) : print(i) print() a_num = get_num() display_nums(a_num)
true
4cdf1d1b109601376c4046cd58fc940ba8a67ac0
SpadinaRoad/Python_by_Examples
/Example_073/Example_073.py
1,079
4.4375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_073 # $ python3 Example_073.py # $ python3 Example_073.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 073 Ask the user to enter four of their favourite foods and store them in a dictionary so that they are indexed with numbers starting from 1. Display the dictionary in full, showing the index number and the item. Ask them which they want to get rid of and remove it from the list. Sort the remaining data and display the dictionary. """ print(__doc__) food_dict = dict() for i in range(1, 5) : food_choice = input('Enter a favourite food: ') food_dict[i] = food_choice print() print(f'Input for food : {food_choice}') print() print(f'Here is the dictionary: {food_dict}') to_remove = int(input('What item do you want to remove? Enter the number: ')) print(f'Input for number to remove: {to_remove}') print() del food_dict[to_remove] print(sorted(food_dict.values()))
true
122071acd8cdcdb643aeb24d40edeb5bf00e5f72
SpadinaRoad/Python_by_Examples
/Example_005/Example_005.py
792
4.40625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_005 # $ python3 Example_005.py # $ python3 Example_005.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 005 Ask the user to enter three numbers. Add together the first two numbers and then multiply this total by the third. Display the answer as The answer is [answer]. """ print(__doc__) num_1 = input('Enter a number : ') num_2 = input('Enter a number : ') num_3 = input('Enter a number : ') answer = (int(num_1) + int(num_2)) * int(num_3) print('') print(f'The first number is : {num_1}') print(f'The second number is : {num_2}') print(f'The third number is : {num_3}') print(f'The answer is {answer}')
true
7acfe740b3794bfb3667c2012f8cad14ee51e14a
SpadinaRoad/Python_by_Examples
/Example_054/Example_054.py
1,300
4.3125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_054 # $ python3 Example_054.py # $ python3 Example_054.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 054 Randomly choose either heads or tails (“h” or “t”). Ask the user to make their choice. If their choice is the same as the randomly selected value, display the message “You win”, otherwise display “Bad luck”. At the end, tell the user if the computer selected heads or tails. """ import random print(__doc__) your_choice = '' comp_wins = 0 my_wins = 0 h_t_dict = { 'h' : 'heads', 't' : 'tails'} while your_choice != 'x' : heads_or_tails = random.choice(['h', 't']) your_choice = input('Choose heads or tails (h/t) : ') your_choice = your_choice.lower() if your_choice != 'x' : print() if heads_or_tails == your_choice : print('You win.') my_wins += 1 else : print('Bad luck') comp_wins += 1 print(f'You chose : {h_t_dict[your_choice]}') print(f'The computer chose : {h_t_dict[heads_or_tails]}') print(f'The score: Computer {comp_wins} Me {my_wins}') print()
true
862410ffce316943c47de2b0ab155f6549182f71
SpadinaRoad/Python_by_Examples
/Example_033/Example_033.py
1,029
4.5
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_033 # $ python3 Example_033.py # $ python3 Example_033.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 033 Ask the user to enter two numbers. Use whole number division to divide the first number by the second and also work out the remainder and display the answer in a user-friendly way (e.g. if they enter 7 and 2 display “7 divided by 2 is 3 with 1 remaining”). """ print(__doc__) int_a = '' while int_a != 'x' : int_a = input('Enter an integer : ') if int_a != 'x' : int_a = int(int_a) int_b = input('Enter a second integer : ') int_b = int(int_b) print() print(f'The input for number 1 : {int_a}.') print(f'The input for number 2 : {int_b}.') print(f'{int_a} divided by {int_b} is {int_a // int_b} with {int_a % int_b} remaining.') print()
true
9f61ce54a78450b8cd1151a94c177b3330e6b1f1
SpadinaRoad/Python_by_Examples
/Example_117/Example_117.py
2,151
4.4375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_117 # $ python3 Example_117.py # $ python3 Example_117.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 117 Create a simple maths quiz that will ask the user for their name and then generate two random questions. Store their name, the questions they were asked, their answers and their final score in a .csv file. Whenever the program is run it should add to the .csv file and not overwrite anything. """ import csv import random print(__doc__) #Start data. print('The Great Math Quiz') print('') name = input('What is your name? ') print(f'The input for name: {name}') print() #Saving to csv file filename = 'MathQuiz.csv' with open(filename, 'a') as fo: fo.write('The Great Math Quiz\n') fo.write(f'User: {name}\n') fo.write('\n') #First math question. operand_a = random.randint(1, 100) operand_b = random.randint(1, 100) correct_answer = operand_a + operand_b line_1 = f'Enter the addition of {operand_a} and {operand_b} : ' answer = int(input(line_1)) line_2 = f'Your answer is {answer}. ' if answer == correct_answer : line_2 += 'It is correct.' score = 1 else : line_2 += 'It is not correct.' score = 0 print(line_2) with open(filename, 'a') as fo : fo.write('The first question: \n') fo.write(f'{line_1}\n') fo.write(f'{line_2}\n') fo.write(f'\n') print() #Second math question. operand_a = random.randint(1, 100) operand_b = random.randint(1, 100) correct_answer = operand_a + operand_b line_1 = f'Enter the addition of {operand_a} and {operand_b} : ' answer = int(input(line_1)) line_2 = f'Your answer is {answer}. ' if answer == correct_answer : line_2 += 'It is correct.' score += 1 else : line_2 += 'It is not correct.' score += 0 print(line_2) with open(filename, 'a') as fo : fo.write('The first question: \n') fo.write(f'{line_1}\n') fo.write(f'{line_2}\n') fo.write(f'\n') fo.write(f'Correct answers: {score} out of 2 ({score/2:.2%}).') print()
true
b5e95bb07b2cb89f23c172c8af483b6bf595fa36
ooladuwa/cs-problemSets
/Week 1/07-SchoolYearsAndGroups.py
2,132
4.34375
4
Imagine a school that children attend for years. In each year, there are a certain number of groups started, marked with the letters. So if years = 7 and groups = 4For the first year, the groups are 1a, 1b, 1c, 1d, and for the last year, the groups are 7a, 7b, 7c, 7d. Write a function that returns the groups in the school by year (as a string), separated with a comma and space in the form of "1a, 1b, 1c, 1d, 2a, 2b (....) 6d, 7a, 7b, 7c, 7d". Examples: csSchoolYearsAndGroups(years = 7, groups = 4) ➞ "1a, 1b, 1c, 1d, 2a, 2b, 2c, 2d, 3a, 3b, 3c, 3d, 4a, 4b, 4c, 4d, 5a, 5b, 5c, 5d, 6a, 6b, 6c, 6d, 7a, 7b, 7c, 7d" Notes: 1 <= years <= 10 1 <= groups <=26 """ Understand: - There are a given number of years notated by y - for each year, there are a number of groups notated by a letter corresponding to the letter of the alphabet - 1 - each year/group combination is notated by yearNumbergroupLetter - in order to iterate through years and/or groups, integer must be converted to string Plan: - create groupLetters list indentical to alphabet # groupLetters = ["a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z] - create yearsList list from 1-10 # yearsList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - create empty list to hold groups by year # yearsByGroup = [] - slice groupLetters list from left identical to the number of groups # groupLetters[0:groups] - slice yearList at integer corresponding to years # yearList[0:years] - for each year/index, iterate through groupLetters and attach all letters to year individually attach one element from groupLetters and append it to new list # for year in yearsList and letter in groupLetters yearsByGroup += f{year}{letter} """ def csSchoolYearsAndGroups(years, groups): groupLetters = "abcdefghijklmnopqrstuvwxyz" yearList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] yearsByGroup = [] for year in yearList[:years]: for letter in groupLetters[:groups]: yearGroup = (f"{year}{letter}") yearsByGroup.append(yearGroup) continue continue return ", ".join(yearsByGroup)
true
56c7032089bdb28b37620aa15a03faf782e67f26
ooladuwa/cs-problemSets
/Week 3/033-insertValueIntoSortedLinkedList.py
2,081
4.3125
4
# Singly-linked lists are already defined with this interface: # class ListNode(object): # def __init__(self, x): # self.value = x # self.next = None # """ - create function to insert a node - create new link node with value provided - set up a current variable pointing to the head of the list and set a ref to the current node - while current.next < value - traverse to the next node - set new nodes pointer to current nodes next - set current nodes pointer to new node """ def insertValueIntoSortedLinkedList(l, value): new_node = ListNode(value) current = l # edge case if l is empty if l == None: return new_node # edge case if value is less than initial current value ie. first node if new_node.value < l.value: new_node.next = current return new_node # middle cases while current.next is not None: if current.next.value > new_node.value: new_node.next = current.next current.next = new_node return l current = current.next # edge case if value to be replaced comes after last element current.next = new_node return l """ Note: Your solution should have O(n) time complexity, where n is the number of elements in l, since this is what you will be asked to accomplish in an interview. You have a singly linked list l, which is sorted in strictly increasing order, and an integer value. Add value to the list l, preserving its original sorting. Note: in examples below and tests preview linked lists are presented as arrays just for simplicity of visualization: in real data you will be given a head node l of the linked list Example For l = [1, 3, 4, 6] and value = 5, the output should be insertValueIntoSortedLinkedList(l, value) = [1, 3, 4, 5, 6]; For l = [1, 3, 4, 6] and value = 10, the output should be insertValueIntoSortedLinkedList(l, value) = [1, 3, 4, 6, 10]; For l = [1, 3, 4, 6] and value = 0, the output should be insertValueIntoSortedLinkedList(l, value) = [0, 1, 3, 4, 6]. """
true
b900777c43b0910d9329b4a3e492e0da64aaf625
ooladuwa/cs-problemSets
/Week 2/027-WordPattern.py
1,640
4.21875
4
""" Given a pattern and a string a, find if a follows the same pattern. Here, to "follow" means a full match, such that there is a one-to-one correspondence between a letter in pattern and a non-empty word in a. Example 1: Input: pattern = "abba" a = "lambda school school lambda" Output: true Example 2: Input: pattern = "abba" a = "lambda school school coding" Output: false Example 3: Input: pattern = "aaaa" a = "lambda school school lambda" Output: false Example 4: Input: pattern = "abba" a = "lambda lambda lambda lambda" Output: false Notes: pattern contains only lower-case English letters. a contains only lower-case English letters and spaces ' '. a does not contain any leading or trailing spaces. All the words in a are separated by a single space. """ """ Understand: - take in a pattern and a string - determine if string follows same structure as pattern """ def csWordPattern(pattern, a): comp = {} a = a.split() # print(a) if len(pattern) != len(a): return False if len(a) < 2 or len(pattern) < 2: return True for i in range(len(a)): if pattern[i] not in comp: if a[i] in comp.values(): return False comp[pattern[i]] = a[i] # print("first loop") # print(comp) else: print(comp[pattern[i]]) print(a[i]) if comp[pattern[i]] != a[i]: return False # if comp[pattern[i]] == a[i]: # continue # if : # return False return True
true
690ffbac5d76e55e2ce80ff075bc81f97defbbd8
Deepakat43/luminartechnolab
/variabl length argument method/varargmethd.py
460
4.15625
4
def add(num1,num2): return num1+num2 res=add(10,20) print(res) #here 2 argumnts present #what if there are 3,4,5 etc arguments present #so we use ****variable length argument method**** def add(*args): print(args) add(10) add(10,20) add(10,20,30,40,50) #using this frmat we get argmnts in a (tuple) frmat #fr getting sum frm tupe frmat : def add(*args): res=0 for num in args: res+=num return res print(add(10,20,30,40,50))
true
afb2f7f9f469e96b342930d31461d9b9fa259171
jpierrevilleres/python-math
/square_root.py
1,291
4.28125
4
import math #imports math module to be able to use math.sqrt and abs function #Part 1 defining my_sqrt function def my_sqrt(a): #Python code taken from Section 7.5 x = a / 2 #takes as an argument and uses it to initialize value of x while True: #uses while loop as mentioned in Section 7.5 y = ( x + a / x ) / 2.0 if y == x: break x = y return x #returns an estimated square root value #Part 2 defining test_sqrt function def test_sqrt(): print("a \t mysqrt(a) \tmath.sqrt(a) \tdiff \n" + "- \t --------- \t ------------ \t----" ) #header for the table a = 1.0 #initializes the value of a to 1 while a < 26: #uses while loop to print a value from 1 to 25 #prints the values returned by my_sqrt for each value of a. #prints the values from math.sqrt for each value of a. #prints the absolute values of the differences between my_sqrt and math.sqrt for each value of a. print ('%(a)d %(my_sqrt(a)).11f %(math.sqrt(a)).11f %(diff).11g' % {"a": a, "my_sqrt(a)":my_sqrt(a), "math.sqrt(a)":math.sqrt(a), "diff":abs(my_sqrt(a) - math.sqrt(a))}) #computed data values for the table a = a + 1 #increments the value of a by 1 for the while loop to work
true
633b1ea1c5d61c406e9745dfe351f15cdf2b8bfd
markymauro13/CSIT104_05FA19
/Exam-Review-11-6-19/exam2_review3.py
490
4.3125
4
x = "Computational Concepts 1" y = "MSU" # What are the results of the following expressions? # a. How many ‘o’ in string x? # b. How can you find the substring “Concepts” in x? # c. How can you check if y starts with “M”? # d. How can you replace “MSU” in y with “Montclair State University”? #a print(x.count('o')) #b print(x.find("Concepts")) #c print(y.startswith('M')) #d print(y.replace("MSU", "Montclair State University"))
true
2a499ffe9355bb49ff0ca6ff45b8648a1841af15
markymauro13/CSIT104_05FA19
/Assignment3/1_calculateLengthAndExchange.py
443
4.25
4
x = str(input("Enter a string: ")) # ask for input from user if(len(x)>0): print("The length of string is: " + str(len(x))) # print the length of the string print("The resulted string is: " + str(x[-1]) + str(x[1:len(x) - 1]) + str(x[0])) # print the result of the modified string else: print("Try again, enter a valid string.") # need this because an error would happen if i didnt enter a string and just hit enter
true
c9cece85db973eedfc69fb0d9e8592935d21232e
markymauro13/CSIT104_05FA19
/Exam-Review-11-6-19/exam2_review6.py
445
4.1875
4
#6 for i in range(1,7): # controls the numbers of rows for j in range(1,i+1): # controls the numbers on those lines print(j, end = '') print() print("------") i = 1 while i <= 6: for j in range(1, i+1): print(j, end = '') print() i+=1 print("------") i = 6 while i >= 1: # reversed for j in range(1, i+1): print(j, end = '') print() i-=1
true
548c422e96d13360a458557f1e0e2a465bf3f782
AastikM/Hacktoberfest2020-9
/Python_Solutions/Q24_factorial(recursion).py
451
4.3125
4
#Function for calulating the factorial def factorial(x): if x == 1 or x== 0 : #base/terimination condition return 1 elif(x < 0) : print("Sorry, factorial does not exist for negative numbers") else: return (x * factorial(x-1)) #Recursive Call for function factorial # main num = int(input("Enter a Number :")) # To take input from the user (should be > = 0) print("Factorial of", num, "is", factorial(num))
true
2d1c82316be30bb1a893f9d6c58b4678137e6814
AastikM/Hacktoberfest2020-9
/Python_Solutions/Q2BinaryDecimal.py
521
4.53125
5
# Python program to convert binary to decimal #Function to convert binary to decimal def binaryToDecimal(n): num=n; decimal=0; #Initializing base value to 1, i.e 2^0 base = 1; temp = num; while temp: last_digit=temp%10; temp//= 10; decimal += last_digit * base; base *= 2; return decimal; #Driver program to test above function if __name__=="__main__": num=int(input("Enter binary number: ")) print("Number in Decimal form: ",binaryToDecimal(num))
true
bf8e19eae13001826a645bdb92e1897927875d54
davinpchandra/ITP_Assignments
/AssignmentPage46
1,747
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 19 10:11:08 2019 @author: davinpc """ # 3-4 GuestList guest_list = ["Steve Jobs","Robert Downey Jr","Will Smith"] for guest in guest_list: print("Dear " + guest + ", please come to my dinner.") print(" ") # 3-5 ChangingGuestList print(guest_list[0] + " can't come to the dinner.") guest_list[0] = "Emilia Clarke" for guest in guest_list: print("Dear " + guest + ", please come to my dinner.") print(" ") # 3-6 MoreGuests print("Dear Guests, we have found a bigger dinner table.") guest_list.insert(0, "Dwayne Johnson") guest_list.insert(2, "Gordon Ramsay") guest_list.append("Walt Disney") for guest in guest_list: print("Dear " + guest + ", please come to my dinner.") print(" ") # 3-7 ShrinkingGuestList print("Dear Guests, we can only invite two people to dinner.") popped_guest1 = guest_list.pop() print("Dear " + popped_guest1 + ", we're sorry we can't invite you to dinner.") popped_guest2 = guest_list.pop() print("Dear " + popped_guest2 + ", we're sorry we can't invite you to dinner.") popped_guest3 = guest_list.pop() print("Dear " + popped_guest3 + ", we're sorry we can't invite you to dinner.") popped_guest4 = guest_list.pop() print("Dear " + popped_guest4 + ", we're sorry we can't invite you to dinner.") for guest in guest_list: print("Dear " + guest + ", you are still invited to the dinner.") del guest_list[1] del guest_list[0] print(guest_list) print(" ") # 3-8 SeeingTheWorld places = ["USA","Greece","Dubai","Switzerland","Germany"] print(places) print(sorted(places)) print(places) print (sorted(places,reverse=True)) print(places) places.reverse() print(places) places.reverse() print(places) places.sort() print(places) places.sort(reverse=True) print(places)
true
bfbc32395535b56de1c2749b04614343afb18789
Dencion/practicepython.org-Exercises
/Exercise11.py
688
4.28125
4
def checkPrime(userNum): ''' Checks if the users entered number is a prime number or not ''' oneToNum = []#Creates a list starting from 1 - userNum divisorList = []#Empty list to be filled with divisors form userNum i = 1 while i <= userNum: oneToNum.append(i) i += 1 for number in oneToNum: if userNum % number == 0: divisorList.append(number) #Check if list is prime if divisorList[0] == 1 and divisorList[1] == userNum: print("Number is prime") else: print("Number is composite") userNum = int(input("Please choose a number to check for primality:")) checkPrime(userNum)
true
92411f12036363a6056c85f71df242dbb9a119de
KenjaminButton/runestone_thinkcspy
/6_functions/exercises/6.13.3.exercise.py
629
4.25
4
# 6.13.3 Exercise: # Write a non-fruitful function drawPoly(someturtle, somesides, somesize) # which makes a turtle draw a regular polygon. When called with # drawPoly(tess, 8, 50), it will draw a shape like this: import turtle # Initializing turtle window = turtle.Screen() window.bgcolor("lightgreen") # Changing colors and pensize for turtle kendrick = turtle.Turtle() kendrick.color("hotpink") kendrick.pensize(3) def drawPoly(someturtle, somesides, somesize): for i in range(somesides): kendrick.forward(somesize) kendrick.left(360/somesides) drawPoly(kendrick, 8, 50) window.exitonclick()
true
a9fae446d7e342cc7e4ffc014d00f42993877f62
KenjaminButton/runestone_thinkcspy
/14_web_applications/14.5.py
1,922
4.375
4
# Writing Web Applications with Flask ''' In this section, you will learn how to write web applications using a Python framework called Flask. Here is an example of a Flask web application: The application begins by importing the Flask framework on line 1. Lines 6-11 define a function hello() that serves up a simple web page containing the date and time. The call to app.run() on Line 14 starts a small web server. The run() method does not return; it executes an infinite loop that waits for incoming requests from web browsers. When a web browser sends a request to the Flask web server, the server invokes the hello() function and returns the HTML code generated by the function to the web browser, which displays the result. To see this in action, copy the code above into a text editor and save it as flaskhello.py (or whatever name you like). Then, download the Flask framework and install it on your computer. In many cases, you can accomplish this using the pip command included with your Python distribution: sudo pip3 install flask Next, execute your flaskhello.py program from the command line: pip flaskhello.py You should see a message similar to the following appear on the console: * Serving Flask app "sample" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 244-727-575 * Running on http://localhost:5000/ (Press CTRL+C to quit) ''' from flask import Flask from datetime import datetime app = Flask(__name__) @app.route('/') def hello(): return """<html><body> <h1>Hello, world!</h1> The time is {0}.</body></html>""".format( str(datetime.now())) # Launch the Flask dev server app.run(host="localhost", debug=True) # favicon.ico unavailable
true
9ad02888fbdeb4a86afc10d8be138e173475e075
KenjaminButton/runestone_thinkcspy
/10_lists/10.12.cloning_lists.py
603
4.34375
4
# 10.12 Cloning Lists ''' If we want to modify a list and also keep a copy of the original, we need to be able to make a copy of the list itself, not just the reference. This process is sometimes called cloning, to avoid the ambiguity of the word copy. The easiest way to clone a list is to use the slice operator. Taking any slice of a creates a new list. In this case the slice happens to consist of the whole list. ''' a = [81, 82, 83] b = a[:] # make a clone using slice print(a == b) # <<< True print(a is b) # <<< False b[0] = 5 print(a) # <<< [81, 82, 83] print(b) # <<< [5, 82, 83]
true
1ee694e9e288b104b3f6054b511fb9768e71a535
KenjaminButton/runestone_thinkcspy
/9_strings/9.9.strings_are_immutable.py
899
4.34375
4
# 9.9 Strings Are Immutable ''' One final thing that makes strings different from some other Python collection types is that you are not allowed to modify the individual characters in the collection. It is tempting to use the [] operator on the left side of an assignment, with the intention of changing a character in a string. For example, in the following code, we would like to change the first letter of greeting. ''' greeting = "Hello, world!" # greeting[0] = 'J' # <<< ERROR! print(greeting) ''' Instead of producing the output Jello, world!, this code produces the runtime error TypeError: 'str' object does not support item assignment. Strings are immutable, which means you cannot change an existing string. The best you can do is create a new string that is a variation on the original. ''' print("\n") greeting = "Hello, world!" newgreeting = "J" + greeting[1:] print(newgreeting)
true
9435b6fa5b480be9729ec52eaa5b87f7207401e5
KenjaminButton/runestone_thinkcspy
/10_lists/10.17.lists_and_loops.py
1,006
4.46875
4
# 10.17 Lists and Loops ''' ''' fruits = ["apple", "orange", "banana", "cherry"] for afruit in fruits: # by item print(afruit) ''' In this example, each time through the loop, the variable position is used as an index into the list, printing the position-eth element. Note that we used len as the upper bound on the range so that we can iterate correctly no matter how many items are in the list. ''' print("\nNew Example:") fruits = ["apple", "orange", "banana", "cherry"] for position in range(len(fruits)): # by index print(fruits[position]) ''' Any sequence expression can be used in a for loop. For example, the range function returns a sequence of integers. This example prints all the multiples of 3 between 0 and 19. ''' print("\nNew Example:") for number in range(20): if number % 3 == 0: print(number) ''' ''' print("\nNew Example:") numbers = [1, 2, 3, 4, 5] print(numbers) for i in range(len(numbers)): numbers[i] = numbers[i] ** 2 print(numbers)
true
d7c00c2393c1b3df29c77d606ccd92e456f5a5d9
KenjaminButton/runestone_thinkcspy
/11_files/exercises/11.9.4.py
2,501
4.25
4
''' Interpret the data file labdata.txt such that each line contains a an x,y coordinate pair. Write a function called plotRegression that reads the data from this file and uses a turtle to plot those points and a best fit line according to the following formulas: 𝑦=𝑦¯+𝑚(𝑥−𝑥¯) 𝑚=∑𝑥𝑖𝑦𝑖−𝑛𝑥¯𝑦¯∑𝑥2𝑖−𝑛𝑥¯2 where 𝑥¯ is the mean of the x-values, 𝑦¯ is the mean of the y- values and 𝑛 is the number of points. If you are not familiar with the mathematical ∑ it is the sum operation. For example ∑𝑥𝑖 means to add up all the x values. Your program should analyze the points and correctly scale the window using setworldcoordinates so that that each point can be plotted. Then you should draw the best fit line, in a different color, through the points. ''' from turtle import Turtle, Screen def plotRegression(data): x_list, y_list = [int(i[0]) for i in data], [int(i[1]) for i in data] x_list, y_list = [float(i) for i in x_list], [float(i) for i in y_list] x_sum, y_sum = sum(x_list), sum(y_list) x_bar, y_bar = x_sum / len(x_list), y_sum / len(y_list) x_list_square = [i ** 2 for i in x_list] x_list_square_sum = sum(x_list_square) xy_list = [x_list[i] * y_list[i] for i in range(len(x_list))] xy_list_sum = sum(xy_list) m = (xy_list_sum - len(x_list) * x_bar * y_bar) / (x_list_square_sum - len(x_list) * x_bar ** 2) # best y y_best = [(y_bar + m * (x_list[i] - x_bar)) for i in range(len(x_list))] # plot points turtle = Turtle() for i in range(len(x_list)): turtle.penup() turtle.setposition(x_list[i], y_list[i]) turtle.stamp() # plot best y turtle.penup() turtle.setposition(0, 0) turtle.color('blue') for i in range(len(x_list)): turtle.setposition(x_list[i], y_best[i]) turtle.pendown() return (min(x_list), min(y_list), max(x_list), max(y_list)) screen = Screen() screen.bgcolor('pink') f = open("labdata.txt", "r") plot_data = [] for aline in f: x, y = aline.split() plot_data.append((x, y)) # This next line should be something like: # screen.setworldcoordinates(*plotRegression(plot_data)) # but setworldcoordinates() is so tricky to work with # that I'm going to leave it at: print(*plotRegression(plot_data)) # and suggest you trace a rectangle with the return # values to get an idea what's going to happen to # your coordinate system screen.exitonclick()
true
af4d0611190081213e50361f1913ee68f694257e
KenjaminButton/runestone_thinkcspy
/2_simple_python_data/2.7.operators_and_operands.py
1,457
4.53125
5
# Operators and Operands print("\n----------------------------") print(2 + 3) # <<< 5 print(2 - 3) # <<< -1 print(2 * 3) # <<< 6 print(2 ** 3) # <<< 8 print(3 ** 2) # <<< 9 print("\n----------------------------") minutes = 645 hours = minutes / 60 print(hours) # <<< 10.75 print("\n----------------------------") print(7 / 4) # <<< 1.75 print(7 // 4) # <<< 1 minutes = 645 hours = minutes // 60 print(hours) # <<< 10 print("\nThis is the integer division operator:") # This is the integer division operator quotient = 7 // 3 print(quotient) # <<< 2 remainder = 7 % 3 print(remainder) # <<< 1 print("\nTime Example:") total_seconds = 7684 hours = total_seconds // 3600 # 1 hour holds 3600 seconds seconds_remaining = total_seconds % 3600 # Modulo returns the remainder minutes = seconds_remaining // 60 # Integer division operator seconds_finally_remaining = seconds_remaining % 60 print("\ntotal_seconds:") print(total_seconds) print("hours:") print(hours) print("minutes:") print(minutes) print("seconds") print(seconds_finally_remaining) print("\nChecking answer:") print((3600*2) + (8 * 60) + 4 ) print("\ndata-7-1: What value is printed when the following statement executes?") print(18 / 4) # Answer: <<< 4.5 print("\ndata-7-2: What value is printed when the following statement executes?") print(18 // 4) # Answer: <<< 4 print("\ndata-7-3: What value is printed when the following statement executes?") print(18 % 4) # Answer: <<< 2
true
aec94d7f54cc24921ab10dabc07957947fa8f212
KenjaminButton/runestone_thinkcspy
/4_python_turtle_graphics/4.1.hello_little_turtles.py
1,538
4.84375
5
# 4.1 Hello Little Turtles ''' There are many modules in Python that provide very powerful features that we can use in our own programs. Some of these can send email or fetch web pages. Others allow us to perform complex mathematical calculations. In this chapter we will introduce a module that allows us to create a data object called a turtle that can be used to draw pictures. Turtle graphics, as it is known, is based on a very simple metaphor. Imagine that you have a turtle that understands English. You can tell your turtle to do simple commands such as go forward and turn right. As the turtle moves around, if its tail is down touching the ground, it will draw a line (leave a trail behind) as it moves. If you tell your turtle to lift up its tail it can still move around but will not leave a trail. As you will see, you can make some pretty amazing drawings with this simple capability. ''' # Note ''' The turtles are fun, but the real purpose of the chapter is to teach ourselves a little more Python and to develop our theme of computational thinking, or thinking like a computer scientist. Most of the Python covered here will be explored in more depth later. ''' import turtle wn = turtle.Screen() # creates a graphic window alex = turtle.Turtle() # Create a turtle named Alex. alex.color("green") alex.pensize(5) alex.forward(150) # Tell alex to move foward 150 units alex.left(90) # Turn by 90 degrees alex.forward(150) # Tell alex to move forward 150 units wn.exitonclick() # wait for a user click on the canvas
true
dbd691354cf51c9b8c5ec66617d41ad250ca51cd
KenjaminButton/runestone_thinkcspy
/12_dictionaries/exercises/12.7.1.exercise.py
1,064
4.25
4
''' Write a program that allows the user to enter a string. It then prints a table of the letters of the alphabet in alphabetical order which occur in the string together with the number of times each letter occurs. Case should be ignored. A sample run of the program might look this this: Please enter a sentence: ThiS is String with Upper and lower case Letters. a 2 c 1 d 1 e 5 g 1 h 2 i 4 l 2 n 2 o 1 p 2 r 4 s 5 t 5 u 1 w 2 ''' def letterCountSort(text): alphabet = 'abcdefghijklmnopqrstuvwxyz' text = text.lower() # Empty dictionary letter_count = {} for char in text: if char in alphabet: if char in letter_count: letter_count[char] = letter_count[char] + 1 else: letter_count[char] = 1 # Below will return a counted dictionary # return letter_count # Sorting the alphabet of the dictionary printed. keys = letter_count.keys() for char in sorted(keys): print(char, letter_count[char]) letterCountSort("How are you?")
true
90e719b77b8664dd93f4b8a09b9fd822f5d64a5d
KenjaminButton/runestone_thinkcspy
/2_simple_python_data/2.8.input.py
887
4.25
4
# Input n = input("Please enter your name: ") print("\nHello", n) print("\n--------------------------") string_seconds = input("Please input the number of seconds you wish to convert: ") total_seconds = int(string_seconds) hours = total_seconds // 3600 seconds_still_remaining = total_seconds % 3600 minutes = seconds_still_remaining // 60 seconds_finally_remaining = seconds_still_remaining % 60 print("hours = {}, minutes = {}, seconds = {}".format(hours, minutes, seconds_finally_remaining)) print("\n--------------------------") # data-8-1: What is printed when the following statements execute? n = input("Please enter your age: ") # user types in 18 print ( type(n) ) # <<< class 'str' print("\n--------------------------") # data-8-2: Click on all of the variables of type `int` in the code below # data-8-3: Click on all of the variables of type `str` in the code below
true
36755b3f1801a8ed276545370b54deaa06eeda2d
KenjaminButton/runestone_thinkcspy
/17_classes_and_objects_basics/exercises/17.11.2.exercise.py
553
4.125
4
''' Add a method reflect_x to Point which returns a new Point, one which is the reflection of the point about the x-axis. For example, Point(3, 5).reflect_x() is (3, -5) ''' import math class Point: def __init__(self, initX, initY): self.x = initX self.y = initY def reflect_x(self): return self.x * -1, self.y print("\nExample 1:") print(Point(3, 5).reflect_x()) # <<< (-3, 5) print("\nExample 2:") print(Point(-5, 10).reflect_x()) # <<< (5, 10) print("\nExample 3:") print(Point(0, 0).reflect_x()) # <<< (0, 0)
true
a7e1aa3372a75ce887a35011f0669cf329db940d
KenjaminButton/runestone_thinkcspy
/4_python_turtle_graphics/4.11_13_exercise.py
709
4.3125
4
''' # 13 A sprite is a simple spider shaped thing with n legs coming out from a center point. The angle between each leg is 360 / n degrees. Write a program to draw a sprite where the number of legs is provided by the user. ''' number_of_legs = input("input a number of legs (choose between 0 and 360): ") number_of_legs_int = int(number_of_legs) if number_of_legs_int == 0: print("\tZero doesn't draw anything. Please try again.") import turtle window = turtle.Screen() ken = turtle.Turtle() window.bgcolor("lightblue") ken.color("pink") ken.pensize(4) for i in range(number_of_legs_int + 1): ken.forward(100) ken.backward(100) ken.left(360 / number_of_legs_int) window.exitonclick()
true
36a370c8100c4b59b269f1eec97f1f6f9966c02b
KenjaminButton/runestone_thinkcspy
/6_functions/exercises/6.13.11.exercise.py
602
4.5
4
# Extend the star function to draw an n pointed star. # (Hint: n must be an odd number greater or equal to 3). # n pointed star import turtle # Initializing turtle window = turtle.Screen() window.bgcolor("lightgreen") # Changing colors and pensize for turtle kendrick = turtle.Turtle() kendrick.color("hotpink") kendrick.pensize(2) def draw_N_Star(kendrick, n): # Formula for n star is left(180 - 180/n) # In order to close the star, use an odd number. for i in range(n): kendrick.forward(100) kendrick.left(180 - 180/n) draw_N_Star(kendrick, 8) window.exitonclick()
true
f70d6eb25a2ea7a650c3309478a51c881c8eeb37
KenjaminButton/runestone_thinkcspy
/6_functions/exercises/6.13.6.exercise.py
662
4.34375
4
# Write a non-fruitful function drawEquitriangle(someturtle, somesize) which # calls drawPoly from the previous question to have its turtle draw a # equilateral triangle. import turtle # Initializing turtle window = turtle.Screen() window.bgcolor("lightgreen") # Changing colors and pensize for turtle kendrick = turtle.Turtle() kendrick.color("hotpink") kendrick.pensize(3) def drawPoly(someturtle, somesides, somesize): # kendrick.penup() # kendrick.backward(somesize / 2) # kendrick.pendown() for i in range(3): kendrick.forward(somesize) kendrick.left(360 / somesides) drawPoly(kendrick, 3, 100) window.exitonclick()
true
327dac896917535638efe1b3cca6bf3fb5727d11
KenjaminButton/runestone_thinkcspy
/11_files/exercises/11.9.3.py
477
4.15625
4
''' Using the text file studentdata.txt (shown in exercise 1) write a program that calculates the minimum and maximum score for each student. Print out their name as well. ''' def min_and_max(): f = open('studentdata.txt', 'r') for i in f: items = i.split() # print(items[1:]) minimum = float(min(items[1:])) maximum = float(max(items[1:])) print("Name: %s, Min: %.2f, Max: %.2f" % (items[0], minimum, maximum)) min_and_max()
true
95f96088c1d431c2ef6a1d6d8b1864c4a27c0b20
eoinpayne/Python
/Lab2circle.py
277
4.15625
4
from math import pi r = 12 area = pi * r ** 2 circumference = 2*pi*r #circumference = 2*pi*r... ca calculate on the fly or define the sum up here. print ("The area of a circle with radius", r, "is", area) print ("The circumference of a circle with radius" , r, "is", 2*pi*r)
true
1c13bb45f9fe5ef9b7eedd2d4e02575119566751
eoinpayne/Python
/Lab2average.py
1,297
4.40625
4
__author__ = 'D15123620' #(1 point) Write a program average.py that calculates and prints the average of three #numbers. Test it with 3, 5 and 6. Does it make a difference if you treat the input strings as #float or int? what about if you print the output result as float or an int? '''def what_is_average (num_1, num_2, num_3): ###original way of doing it required that i enter in how many numbers there were average = ((num_1 + num_2 + num_3)/3) ### to be averaged return average ''' def what_is_average (num_1, num_2, num_3): numbers_to_average = [num_1, num_2, num_3]## this line sets list of numbers to be averaged to_divide_by = len(numbers_to_average) ##this line counts the amount of items in list above average = ((num_1 + num_2 + num_3)/to_divide_by) ## this line divides list by the variable that counted the list return average def main(): num_1 = float(input("Enter number 1: ")) num_2 = float(input("Enter number 2: ")) num_3 = float(input("Enter number 3: ")) average = what_is_average(num_1, num_2, num_3) print("%.2f" % average) main() ''' numstoAvg = [num1, num2, num3] ## array / list =len(mnumbstoAvg) ##this counts how many in the list. this result can then be used to calculate as the dividing number. '''
true
45b5235a525b2007c4124fd16fb894f7f10f9c0f
ivyostosh/algorithm
/data_structure/queue.py
1,921
4.5
4
# Queue Implementation (https://www.educative.io/blog/8-python-data-structures """ We can use append() and pop() to implement a queue, but this is inefficient as lists must shift elements one by one. Instead, the best practice is to use a deque from collections module. Deques (double-ended queue) allow you to access both sides of the queue through popleft() and popright() Important methods to remember: queue.append(), queue.appendleft(), queue.pop(), queue.popleft() """ ######################################################################## print("===============Create a deque===============") from collections import deque # Initialize a deque # Option 1: Empty deque q = deque() # Option 2: deque with values q = deque(['a', 'b', 'c']) print(q) ######################################################################## print("\n===============Add to a deque===============") # Add element to the right end of deque: using append() q.append('d') q.append('e') q.append('f') print("\nAdd to a queue using append()") print(q) # Add element to the left end of deque: using appendleft() q.appendleft(1) q.appendleft(2) print("\nAdd to a queue using appendleft()") print(q) print("\nNote deque can hold different types of elememt as shown above") ######################################################################## print("\n===============Delete from a deque===============") # Delete element from the right end of deque: using pop() q.pop() q.pop() print("\nDelete from the right end of the queue using pop()") print(q) # Delete element from the left end of deque: using popleft() q.popleft() print("\nDelete from the left end of the queue using popleft()") print(q) ######################################################################## # Common queue interview questions in Python """ Reverse first k elements of a queue Implement a queue using a linked list Implement a stack using a queue """
true
b0debf7de24d42f2106213afda16edb349e0c4dd
bikegirl/NLP-Nitro
/Word.py
878
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Word class holds the properties of a word: token, part_of_speech, and frequency. Has a method for computing complexity """ import math class Word: def __init__(self, word, part_of_speech, frequency = 0): self.__word = word self.__part_of_speech = part_of_speech self.__frequency = frequency def set_frequency(self, frequency): self.__frequency = frequency # Get word def get_word(self): return self.__word def get_part_of_speech(self): return self.__part_of_speech def get_frequency(self): return self.__frequency def compute_complexity_score(self): """ Word complexity = exp(-frequency) Return: complexity(float) """ return math.exp(-self.__frequency)
true
c9af8dd04b7a7cbac9ac159c22379174525ebc9a
suriyaaws2020/Python
/Create/NewfolderPython/python_101.py
807
4.34375
4
#variable declaration X=2, Y=-3, Z=0.4 #above declares the variables under respective variable type# #example X=2 is an integar, Z=0.4 is an float type# #print function is used to print the value# print(type(x)) #the above prints the value of X as 2. Output will be 2 #below command shows how to assign values into a variable and also determines the variable type of y P=type(y) #here the output will be an integar print(p) #== operator checks whether the values are same. comparative operator X==Y print(X==Y) #the output will be true or false #below command gets the input from user and store in the variable a and b respectively a=input("Enter the 1st number") b=input("Enter the 2nd number") #below command make the sum of above two values received c=a+b #below command prints the value of sum print(c)
true
5d41a7c7404af46e3d985142f487373e60a3f206
usn1485/TipCalculator
/TipCalculator.py
2,422
4.3125
4
#Import the required Modules import math import os #Take user input for bill amount. bill=float(input("Enter the bill Amount:")) # Write function to calculate tip. def tipCalculator(bill,percent): # convert the percent input to whole number if it is given as 0.15 if(percent<1): tipPercent=percent*100 tip = bill*( tipPercent / 100 ) else: tip = bill*( percent / 100 ) return tip # Verify if bill amount is Positive else throw error if(bill>0): #Take user input for tip Percent percent=float(input("Enter the tip Percent:")) # Verify if Percentage is Positive else throw error if(percent>0): # Calculate Tip for the given Bill Amount. tip = tipCalculator(bill,percent) #Check if user want to split the tip amount. splitBool=(input("Do you want to split the tip? y/n?").strip().upper()) #Verify if user wants to split and then split the tip amount. if splitBool=="Y": # Take user input for no of people they want to split tip between. noOfppl=int(input("Enter the No. of ppl you want to split the tip in:")) #If no of people are more than 1 then do the calculation to divide tip equally. if(noOfppl>1): FinalTip= round(( tip/noOfppl),2) print(f"tip Split for {noOfppl} people is ${FinalTip}cents each.") #If user changes mind and decides not to split. elif (noOfppl==1): print(f"tip for this table is ${round(tip,2)}cents.") # if user enters 0 or something else. else : print("tip should be paid by 1 or more people. Please check the input.") # If user doesn't want to split the tip amount, calculate the tip for per table elif splitBool=="N": print(f"tip for this table is ${round(tip,2)}cents") #If user enters Other than Y/ N characters, print warning. else: print("Please Enter Y or N characters only.") #if user enters Negative or 0 Percent value, print warning else: print("Percent must be positive") #If user enters the bill amount 0 or negative, print warning else: print("The bill amount must be greater than zero")
true
d684aacc8759a7a4eb3b3e039e4813934624d407
campjordan/Python-Projects
/Numbers/pi.py
1,243
4.28125
4
''' Find PI to the Nth Digit - Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program will go. ''' def arctan(x, one=1000000): """ Calculate arctan(1/x) arctan(1/x) = 1/x - 1/3*x**3 + 1/5*x**5 - ... (x >= 1) This calculates it in fixed point, using the value for one passed in """ power = one // x # the +/- 1/x**n part of the term total = power # the total so far x_squared = x * x # precalculate x**2 divisor = 1 # the 1,3,5,7 part of the divisor while 1: power = - power // x_squared divisor += 2 delta = power // divisor if delta == 0: break total += delta return total # Calculate pi def pi(one): return 4*(12*arctan(18, one) + 8*arctan(57, one) - 5*arctan(239, one)) pi = str(pi(10000000000000000000000000000000000000000000000000000000000000000)) pi = pi[:1] + "." + pi[1:] # adds the decimal point def get_pi(digit): if digit <=0 or digit > 64: print "Your number must be greater than 0 and no more than 64." get_pi() else: print pi[:digit + 1] get_pi(int(raw_input("How many digits of pi would you like?")))
true
c2d9a1ac9c8ce3a8f2c63b1fa8768ffc5400f68f
rulesrmnt/python
/calc.py
350
4.34375
4
print (2+3) #addition print (2*3) #multiplication print (2-3) # substraction print (2/3) #float division print (2//3) #integer division print (3%2) # Module, gives remainder print (2%2) print(round(2/3,2)) #round function print (2**5) # exponent i.e. 2 to the power 5 print (2**5**2) # associative rule i.e exponents are calculated from right to left
true
4355be5058d5d5a3858c4cee03ea4a219a35293b
jwarlop/UCSD
/Extension/Cert_DM_Adv_Analytics/2018Win_Py4Info/Homework/A06/URL_reader.py
1,267
4.125
4
# Assignment 6 # Network Programming # John M Warlop # Python 3.x # Due 3/4/2018 from urllib.request import urlopen url = input("type url(ex: www.ibm.com): ") url = "http://"+url try: res=urlopen(url) except: print("Could not open "+url) size=0 Chunk = 512 flag = False while True: chunk = res.read(Chunk) size += len(chunk) if not chunk: break if size >= 3000: if not flag: print(chunk[0:440]) flag = True if size < 3000: print(chunk) print("Size is: "+str(size)) ''' http://constitutionus.com 1. Rename the socket1.py to URL_reader.py 2. Modify URL_reader.py to use urllib, size is still 512 3. Add code to prompt for any URL 4. Add error checking(try/except) 5. Count number of chars received and stop showing any text when 3000 chars seen 6. Continue to receive all of document, print the total number of char Deliverable: Two files 1) URL_reader.py and png of successful running of program Location of test file: https://www.usconstitution.net/const.txt import urllib.request req = urllib.request.Request('http://constitutionus.com/') response = urllib.request.urlopen(req) thePage = response.read() print(thePage) pageLength = len(thePage) print("The length of page is: "+str(pageLength)) '''
true
72611838082c1243f1fb63fab711af4c832459ab
vijayramalingom/SYSC-1005-Introduction-to-Software-Development-
/math_quiz_v3.py
1,776
4.25
4
""" Version 3 of a math quiz program. Adapted from a programming problem by Jeff Elkner. dlb Dept. of Systems and Computer Engineering, Carleton U. Initial release: October 21, 2014 (SYSC 1005) Revised: November 4, 2015 (SYSC 1005) The user is prompted to enter a command ("T" or "Q"). If the user types "Q", the program finishes. If the user types "T", 10 addition problems are presented, then the user is prompted to enter another command. This continues until "Q" is entered. """ import random def ask_questions(): """ (None) -> int Ask 10 addition problems with random integer operands between 1 and 10. Return the number of questions that were answered correctly. """ ok = 0 # Number of correct answers so far for question in range(1, 11): num1 = random.randint(1, 10) num2 = random.randint(1, 10) correct_result = num1 + num2 prompt = ("Question " + str(question) + ". What's " + str(num1) + " plus " + str(num2) + "? ") answer = int(input(prompt)) if answer == correct_result: print("That's right -- well done.") ok += 1 else: print("No, I'm afraid the answer is", correct_result) return ok if __name__ == "__main__": done = False while not done: command = input("Take the quiz or Quit (T, Q): ") if command == 'T': correct = ask_questions() print("I asked you 10 questions.", end = " ") print("You got", correct, "of them right.") elif command == 'Q': done = True else: # The user typed a command other than Q or T print(command, "is not a recognized command")
true
512746e85cd9cc1c4b18b29fd05a103e4a915db1
dtingg/Fall2018-PY210A
/students/C_Farris/session03/list_lab.py
1,272
4.25
4
#!/usr/bin/env Python3 """ Date: November 11, 2018 Created by: Carol Farris Title: list Lab Goal: learn list functions """ def displayPfruits(myFruit): for x in myFruit: if x.lower().startswith('p'): print(x) else: print(x + " doesn't start with p") def addUsingInsert(myFruit): myFruit.insert(0, 'Pineapple') print(myFruit) def addToBeginningOfList(myFruit): singleList = ['Mango'] myFruit = singleList + myFruit print(myFruit) addUsingInsert(myFruit) print(myFruit) return myFruit def askforAFruit(): newFruit = input("Please enter a different fruit ==>") newFruit.strip() # strip any whitespace myFruit.append(newFruit) print(myFruit) def askForANumber(): fruitNumb = 100 fruitLength = len(myFruit) - 1 textInput = "Please select an integer from 0-{} ==>".format(fruitLength) while not fruitNumb <= fruitLength: fruitNumb = int(input(textInput)) gotThatFruit = myFruit[fruitNumb] print(fruitNumb, gotThatFruit) if __name__ == '__main__': myFruit = ['Apples', 'Pears', 'Oranges', 'Peaches'] print(myFruit) askforAFruit() askForANumber() addToBeginningOfList(myFruit) displayPfruits(addToBeginningOfList(myFruit))
true
8ce538d1282639c0040cc9101cf9ca1750192fcf
dtingg/Fall2018-PY210A
/students/ZidanLuo/session02/printGrid.py
602
4.125
4
import sys def print_grid(x,y): count = 1 #count all the possible number of lines lines = (y + 1) * x + 1 plus = "+" minus = "-" shu = "|" empty = " " #draw the horizontal and vertical lines Horizontal = (plus + y * minus) * x +plus Vertical = (shu + y * empty) * x + shu #Use while loop to loop through all the possible lines while count <= lines : if (count % (y + 1)) == 1: print (Horizontal) else: print (Vertical) count += 1 #Take arguments in Command Lines print_grid(int(sys.argv[1]),int(sys.argv[2]));
true
3ea0e0bef450bd1adf0135bbc54775a7aade1fb4
dtingg/Fall2018-PY210A
/students/ericstreit/session03/list_lab.py
2,511
4.15625
4
#Lesson03 #String Exercises ## # #!/usr/bin/env python3 #define variables mylist = ["Apples", "Pears", "Oranges", "Peaches"] #define function def myfunc(n): """Update the DocString""" pass #series 1 print("The list currently contains: ", mylist) additem = input("Pleaes enter another item: ") mylist.append(additem) print("The list currently now contains: ", mylist) l = len(mylist) listitem = int(input("Enter a list item from 1 to {} and I will show it to you: ".format(l))) print(mylist[(listitem-1)]) print() pause = input("OK, let's add Kiwis to the list!") newlist = ["Kiwis"] mylist = newlist + mylist print(mylist) pause = input("Now adding Mangos to the beginning of the list!") mylist.insert(0,"Mangos") print(mylist) pause = input("Now displaying all items that begin with the letter 'P'") for i in mylist: if i[0] == "P": print(i) pause = input("Press any key to continue to series 2 exercise") #series 2 print() print() print("The list currently contains items: ",mylist) print("Removing the last item, {}, from the list ".format(mylist[-1])) mylist.pop() print("The list now contains: ",mylist) toremove = input("Please enter an item you would you like to remove : ") mylist.remove(toremove) print("The list now contains: ",mylist) #series 3 #there is a bug in this section - if an item is removed then it skips the following item #I suspect because it changes the index value print("OK, let's move on to series 3!") print() copy_listXXXXXXXX = mylist print(id(mylist)) print("here is the copied list") print(copy_listXXXXXXXX) print(id(copy_listXXXXXXXX)) for i in copy_listXXXXXXXX: choice = input("Do you like {}?: (y/n)".format(i)) if choice == "y": continue elif choice == "n": mylist.remove(i) print("Removing {} from the list!".format(i)) #bug if 'n' is selected it skips the next item in the list, even if I use a copy of the list.. else: while choice != "y" or "n": choice = input("Hm, I don't understand '{}' please enter 'y' or 'n' ".format(choice)) break print(mylist) #series 4 #start print("Let's start series 4!") print("The list currently contains: ", mylist) l = len(mylist) newlist = [] for i in mylist: newlist.append(i[::-1]) print("The original list is {} minus the last item.".format(mylist[0:l-1])) print("The original list items spelled backwards is {}: ".format(newlist)) pause = input("Press any key to exit") #for testing if __name__=="__main__": pass
true
ab2aed6b36ee8a39a05d108704db93cad76a1311
dtingg/Fall2018-PY210A
/students/ZackConnaughton/session03/list_lab.py
709
4.15625
4
#!/usr/bin/env python def series1(): """ Shows what can be done with a simple list of fruitsself. """ fruits = ['Apples', 'Pears', 'Oranges', 'Peaches'] print(fruits) response = input('Input another Fruit: ') fruits.append(response) print(fruits) fruit_number = input('Enter the number fruit you want to see (from 1 ' 'to ' + str(len(fruits)) + '):') print(fruits[int(fruit_number) - 1]) fruits = ['Plum'] + fruits print(fruits) fruits.insert(0, 'Banana') print(fruits) p_fruits = [] for f in fruits: if f[0] == 'P': p_fruits.append(f) print(p_fruits) if __name__ == '__main__': series1()
true
e07217f51ac1b0401635329a3ae81a54495135a7
dtingg/Fall2018-PY210A
/students/DiannaTingg/Session05/comprehensions_lab.py
2,453
4.4375
4
# Lesson 05 Exercise: Comprehensions Lab # Count Even Numbers # Using a list comprehension, return the number of even integers in the given list. def count_evens(l): return len([i for i in l if i % 2 == 0]) assert count_evens([2, 1, 2, 3, 4]) == 3 assert count_evens([2, 2, 0]) == 3 assert count_evens([1, 3, 5]) == 0 # Revisiting the Dictionary and Set Lab food_prefs = {"name": "Chris", "city": "Seattle", "cake": "chocolate", "fruit": "mango", "salad": "greek", "pasta": "lasagna"} # Print dictionary using a string format method print("{name} is from {city} and he likes {cake} cake, {fruit} fruit, {salad} salad, and {pasta} pasta." .format(**food_prefs)) # Using a list comprehension, build a dictionary of numbers from zero to fifteen and the hexadecimal equivalent (string) # the hex() function gives you the hexidecimal representation of a number as a string def hex_dictionary(): my_dict = dict([(i, hex(i)) for i in range(16)]) return my_dict print(hex_dictionary()) # Make another hex dictionary, but use a one line dictionary comprehension def better_hex_dictionary(): return {key: hex(key) for key in range(16)} print(better_hex_dictionary()) # Using the food_prefs dictionary: Make a dictionary using the same keys but with the number of ‘a’s in each value. def a_values_dict(original_dict): return {key: value.count("a") for key, value in original_dict.items()} print(a_values_dict(food_prefs)) # Create sets s2, s3 and s4 that contain numbers from zero through twenty, divisible 2, 3 and 4. s2 = set(i for i in range(21) if i % 2 == 0) s3 = set(i for i in range(21) if i % 3 == 0) s4 = set(i for i in range(21) if i % 4 == 0) print("s2:", s2) print("s3:", s3) print("s4:", s4) # Create a sequence that holds all the divisors you might want – could be any number of divisors. # Loop through that sequence to build the sets up. You will end up with a list of sets – one set for each divisor. def make_sets(divisor_list): sets = [] for x in divisor_list: subset = set(i for i in range(21) if i % x == 0) sets.append(subset) return sets print(make_sets([2, 3, 4, 5])) # Extra credit: do it all as a one-liner by nesting a set comprehension inside a list comprehension. def make_better_sets(divisor_list): return [set(i for i in range(21) if i % number == 0) for number in divisor_list] print(make_better_sets([2, 3, 4, 5]))
true
29c93f8ba7065b60a30ea4264f4678eb90e8301a
dtingg/Fall2018-PY210A
/students/ZachCooper/session01/break_me.py
1,139
4.125
4
#!/usr/bin/env python # I tried a couple of error exceptions that I commonly ran into during my Foundations class # Example of ZeroValueError def divide_things(num1, num2): try: print(num1 / num2) except ZeroDivisionError: print("Ummm...You totally can't divide by 0") raise ZeroDivisionError divide_things(12, 0) # Example of ValueError try: num = float(input("Enter a number: ")) except ValueError: print("That was not a number!!") else: print("Your number is:") # Example of FileError try: fakefile = open('fake.txt', 'r') fakefile.read() except FileNotFoundError: print("Sorry your file doesn't exist...") except Exception as e: print(e) print("Unknown error, sorry!") # Example of KeyError seahawks_dict = {'Russell Wilson': 'Quarterback', 'Doug Baldwin': 'Wide Receiver', 'Pete Carrol': 'Coach', 'BobbyWagner': 'Linebacker'} def seahawks_exception(): try: print(seahawks_dict[1]) print(seahawks_dict[2]) print(seahawks_dict[4]) except KeyError: print("That is not a key in the Seahawks Dictionary!") seahawks_exception()
true
f3348cba2eaaa6e973b8a28497d0cd5d942389a4
dtingg/Fall2018-PY210A
/students/HABTAMU/session04/dict_lab.py
2,076
4.125
4
#!/usr/bin/env python3 """Dictionaries 1""" # Create a dictionary containing “name”, “city”, and “cake” for “Chris” from “Seattle” who likes “Chocolate” # (so the keys should be: “name”, etc, and values: “Chris”, etc.) my_dict = {"name": "Chris","city": "Seattle","cake": "Chocolate"} # Display the dictionary. print("{name} is from {city}, and likes {cake} cake.".format(**my_dict)) # Delete the entry for “cake”. my_dict.popitem() del my_dict["cake"] print(my_dict) # Add an entry for “fruit” with “Mango” and display the dictionary. dict = my_dict my_dict['fruit'] = 'Mango' print(my_dict) # Display whether or not “cake” is a key in the dictionary (i.e. False) (now). print('cake' in my_dict) # Display whether or not “Mango” is a value in the dictionary (i.e. True). print('Mango' in my_dict.values()) # Dictionaries 2 # Using the dictionary from item 1: # Make a dictionary using the same keys but with the number of ‘t’s in each value as the value(consider upper and lower case?). d = {} for k, v in my_dict.items(): d[k] = v.count('t') print(d) # Sets # Create sets s2, s3 and s4 that contain numbers from zero through twenty, divisible by 2, 3 and 4. s2 = set() s3 = set() s4 = set() for i in range(21): if not i % 2: s2.add(i) if not i % 3: s3.add(i) if not i % 4: s4.add(i) print(s2) print(s3) print(s4) # Display the sets. # Display if s3 is a subset of s2(False) print(s3.issubset(s2)) # and if s4 is a subset of s2 (True). s4.issubset(s2) # Sets 2 # Create a set with the letters in ‘Python’ and add ‘i’ to the set. s1 = set('Python') s1.add('i') s1 print(s1) # Create a frozenset with the letters in ‘marathon’. f = frozenset('marathon') # display the union and intersection of the two sets. x = s1.union(f) y = f.union(s1) print("union", x) print("union with", y) z = s1.intersection(f) zz = f.intersection(s1) print("intersection", z) print("intersection with", zz)
true
b74f0019166cd600f9a17433f5b1807b7f94548b
dtingg/Fall2018-PY210A
/students/DiannaTingg/Session04/get_languages.py
2,111
4.40625
4
# Lesson 04 Exercise: File Exercise # File reading and parsing # Write a program that takes a student list and returns a list of all the programming languages used # Keep track of how many students specified each language # It has a header line and the rest of the lines are: Last, First: Nicknames, languages def get_lines(my_file): """ Returns formatted lines using a text file :param my_file: a text file :return: list of lines with endings stripped, commas replaced with empty strings, and header removed """ with open(my_file, "r") as infile: lines = infile.readlines() strip_lines = [l.strip() for l in lines] words = [l.replace(",", "") for l in strip_lines] del words[0] return words def stuff_after_colon(lines): """ Returns a list of split lines :param lines: list of formatted lines that contain a colon :return: list of lines with only the text after the colon """ stuff = [] for x in lines: try: langs = x.split(": ")[1] stuff.append(langs) except IndexError: pass return stuff def print_dictionary(my_dict): """ Prints the dictionary contents using a formatted string :param my_dict: dictionary with language as the key and number of students as the value :return: an alphabetized, formatted list of computer languages and number of students """ print("Computer Languages Used by Students") for key in sorted(my_dict.keys()): print("{}: {}".format(key.capitalize(), my_dict[key])) def get_languages(filename): languages = {} strip_lines = get_lines(filename) stuff = stuff_after_colon(strip_lines) for lines in stuff: for item in lines.split(): if item == "nothing" or item[0].isupper(): continue else: if item in languages: languages[item] += 1 else: languages[item] = 1 print_dictionary(languages) if __name__ == "__main__": get_languages("students.txt")
true
63a2168eeeddcc102e648ea5130a40d888569a7d
dtingg/Fall2018-PY210A
/students/JonSerpas/session02/series.py
1,395
4.25
4
def fibonacci(n): #first create our list with starting integers fiblist = [0,1] #appends to the end list of integers the sum of the previous two integers #this will loop until the length of the list is n long #finally we return the n value of the list while len(fiblist) < n: fiblist.append(sum(fiblist[-2:])) return fiblist[n-1] print(fibonacci(7)) print(fibonacci(9)) print(fibonacci(5)) def lucas(n): #first create our list with starting integers lucaslist = [2,1] #appends to the end list of integers the sum of the previous two integers #this will loop until the length of the list is n long #finally we return the n value of the list while len(lucaslist) < n: lucaslist.append(sum(lucaslist[-2:])) return lucaslist[n-1] print(lucas(7)) print(lucas(9)) print(lucas(5)) def sum_series(n, x=0, y=1): #first create our list with starting integers sum_list = [x , y] #appends to the end list of integers the sum of the previous two integers #this will loop until the length of the list is n long #finally we return the n value of the list while len(sum_list) < n: sum_list.append(sum(sum_list[-2:])) return sum_list[n-1] print(sum_series(7)) print(sum_series(9,2,1)) print(sum_series(5,6,4)) #here we write our unit tests. #no Assertion Errors mean the code is working as expected assert fibonacci(7) == 8 assert lucas(7) == 18 assert sum_series(5,6,4) == 24
true
e571de78c6e4fd094bcf760e2f2f522ff53958aa
dtingg/Fall2018-PY210A
/students/Adolphe_N/session03/slicing.py
1,307
4.5
4
#! python3 a_string = 'this is a string' a_tuple = (2,54,13,12,5,32) name = 'Seattle' ''' prints the list with the last item first and first item last ''' def exchange_first_last(): #this will exchange the first and last character of the string print(a_string) print ('{}{}{}'.format(a_string[-1], a_string[1:-1], a_string[0])) print(a_tuple) print ('({}, {}, {}, {}, {}, {})'.format(a_tuple[-1], a_tuple[1],a_tuple[2], a_tuple[3],a_tuple[4], a_tuple[0])) ''' first and last 4 items removed along with every other item ''' def remove(n): len_str = len(n) print (a_string) print (n[4:(len_str-4):2]) ''' prints the reversed list ''' def reverse(n): len_str = len(n) print(a_string) print (n[::-1]) ''' prints the last third of the list first, then the first third then the middle third ''' def new_order(n): len_str = len(n) third = (len_str // 3) print(a_string) print("{}, {}, {}".format(n[(third)::], n[0:third], n[third:(third)])) print("{}, {}, {}".format(n[(third * 2)::], n[0:third], n[third:(third*2)])) if __name__ == '__main__': exchange_first_last() remove(a_string) reverse(a_string) new_order(name)
true
8dc90534107673e7574626c9816423f8c72bf4f2
Miriam-Hein/pands-problem-sheet
/es.py
710
4.125
4
# es.py # This program reads in a text file and outputs the number of e's it contains. # Author: Miriam Heinlein # Import library (System-specific parameters and functions) import sys # Function to read letter e in the file from an arugment in the command line def readText(): with open(sys.argv[1], "r") as f: #sys.argv reads the textfile from the command line whereby argv [1] refers to file names passed as argument to the function in index 1 text = f.read() # store content of the file in a variable totalEs = text.count('e') #counts the e's in the textfile and stores them in the variable totalEs # Display the number of e's counted print(totalEs) # Calling function readText()
true
12b5743215371715e3fb8437c64f2c76ebb68cef
michaelkmpoon/Pandhi_Ayush_-_Poon_Michael_Assignment1_CTA200H
/question_1/find_replace.py
962
4.15625
4
#!/usr/bin/env python3 import os def find_replace(find: str, replace: str): # type check, only strings allowed as input os.makedirs(replace) # make directory called replace in working directory for file_name in os.listdir("."): if file_name.endswith(".txt"): file = open(file_name, "r") for line in file: # for every line if find in line: file.close() # close file and reopen to read from first line file = open(file_name, "r") transfer = file.read() transfer = transfer.replace(find, replace) new_file = open(".\\" + replace + "\\" + file_name, "w+") new_file.write(transfer) new_file.close() break file.close() find = input("Enter the word to find: ") replace = input("Enter the word to replace: ") find_replace(find, replace)
true
8a2eb6e733d29afad05b36566efd71406ca57fbc
pankajnimgade/Python_Test101
/Function_Installation_and_Conditionals/code_with_branches_1_.py
1,574
4.25
4
phone_balance = 9 bank_balance = 100000000 if phone_balance < 10: phone_balance += 10 bank_balance -= 10 print("Phone Balance: " + str(phone_balance)) print("Bank Balance: " + str(bank_balance)) weight_in_kg = 55 height_in_m = 1.2 if 18.5 <= weight_in_kg/(height_in_m**2) < 25: print("BMI is considered 'normal'.") number = 10 if number % 2 == 0: print("{} is even.".format(number)) else: print("{} is odd.".format(number)) def garden_calendar(season): if season == "spring": print("Current season is {}. time to plant the garden!".format(season)) elif season == "summer": print("Current season is {}. time to water the garden!".format(season)) elif season == "autumn" or season == "fall": print("Current season is {}. time to harvest the garden!".format(season)) elif season == "winter": print("Current season is {}. time to stay indoors and drink tea!".format(season)) else : print("Don't recognize the season.") garden_calendar("winter") print("\n\n") #Third Example #change the age to experiment with the pricing age = 35 #set the age limits for bus fares free_up_to_age = 4 child_up_to_age = 18 senior_from_age = 65 #set bus fares concession_ticket = 1.25 adult_ticket = 2.50 #ticket price logic if age <= free_up_to_age: ticket_price = 0 elif age <= child_up_to_age: ticket_price = concession_ticket elif age >= senior_from_age: ticket_price = concession_ticket else: ticket_price = adult_ticket message = "Somebody who is {} years old will pay ${} to ride the bus.".format(age,ticket_price) print(message)
true
9b5ad1db488ceb425f57abc3cac88fefa8d581c5
Prathamdoshi/UC-Berkeley-Data-Analytics-Bootcamp-Module-Exercises
/Python/Netflix.py
1,405
4.125
4
instructions =""" # Netflix lookup Finding the info to some of netlfix's most popular videos ## Instructions * Prompt the user for what video they are looking for. * Search through the `netflix_ratings.csv` to find the user's video. * If the CSV contains the user's video then print out the title, what it is rated and the current user ratings. * For example "Pup Star is rated G with a rating of 82" * If the CSV does not contain the user's video then print out a message telling them that their video could not be found. """ # Modules import os import csv # Prompt user for video lookup video = input("What show or movie are you looking for? ") # Set path for file cwd = os.getcwd() csvpath = os.path.join(cwd, "Python/data/netflix_ratings.csv") # Bonus # ------------------------------------------ # Set variable to check if we found the video # Try: Zootopia; Gossip Girl found = False # Open the CSV with open(csvpath, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") # Loop through looking for the video for row in csvreader: if row[0].lower() == video.lower(): print(row[0]+ " is rated "+ row[1] + " with a rating of " + row[6]) found = True break # If the video is never found, alert the user if found == False: print("Sorry about this, we don't seem to have what you are looking for!")
true
8507cee32a92b1d19214e08ac731be5a10bc8bb4
daviddwlee84/LeetCode
/Python3/LinkedList/MergeTwoSortedLists/Better021.py
892
4.125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from ..ListNodeModule import ListNode class Solution: def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ # Declare a temporary head, because we aren't sure l1 or l2 is None or Head tempHead = node = ListNode(0) while l1 and l2: if l1.val < l2.val: node.next = l1 l1 = l1.next else: node.next = l2 l2 = l2.next node = node.next if not l1: # If l1 is empty, then connect the rest of l2 to node node.next = l2 else: # Vice versa node.next = l1 return tempHead.next
true
009fb7f3db4c51738566e83de7ae32ecd2e813f6
daviddwlee84/LeetCode
/Python3/LinkedList/InsertionSortList/Naive147.py
1,124
4.1875
4
from ..ListNodeModule import ListNode class Solution: def insertionSortList(self, head: ListNode) -> ListNode: if not head or not head.next: return head fakeRoot = ListNode(-1) current = fakeRoot.next = head while current and current.next: if current.val <= current.next.val: # already sorted current = current.next else: # delete current.next and save as temp temp = current.next current.next = current.next.next # iterate from the start to find the position to insert previous = fakeRoot while previous.next.val <= temp.val: previous = previous.next # insert after previous node temp.next = previous.next previous.next = temp return fakeRoot.next # Runtime: 200 ms, faster than 67.41% of Python3 online submissions for Insertion Sort List. # Memory Usage: 14.7 MB, less than 100.00% of Python3 online submissions for Insertion Sort List.
true
df797407e5c699b19a92585715a093d50f867c99
Kiddiflame/For_Assignment_5
/Documents/Forritun/max_int.py
590
4.59375
5
#1. Initialize with git init #2. input a number #3. if number is larger than 0, it becomes max-int #4. if number is greater than 0, user can input another number #5. repeat step 3 and 4 until negative number is given #6. if negative number is given, print largest number num_int = int(input("Input a number: "))# Do not change this line max_int = 0 if num_int > 0: max_int = num_int while num_int > 0: num_int = int(input("Input a number: ")) if num_int > max_int: max_int = num_int print("The maximum is", max_int) # Do not change this line
true
d5deb525066d1bd891b52c84f63f4033bdcedae8
andrew-yt-wong/ITP115
/ITP 115 .py/Labs/ITP115_L8_1_Wong_Andrew.py
1,568
4.28125
4
# Andrew Wong, awong827@usc.edu # ITP 115, Spring 2020 # Lab 8-1 # Wants to continue function that checks whether the user is going to continue def wantsToContinue(): # Loop until a valid response is given validResponse = False while not validResponse: # Retrieve the response and capitalize it response = input("Do you want to continue (y/n)? ").upper() # Check whether we continue or not, if it is invalid we will loop if response == "Y": validResponse = True return True elif response == "N": validResponse = True return False # Converts a given temperature given the type of conversion and temp def temperatureConverter(conversionType, inputTemperature): # Check which type of conversion if any and return the value if conversionType == 1: return (inputTemperature - 32) * 5 / 9 elif conversionType == 2: return (inputTemperature * 9 / 5) + 32 else: print("Invalid conversion code") return 0 # Main Function that calls the other two functions def main(): # Continue while the user wants to cont = True while cont: print("Welcome to the Temperature Converter 1.0") conversionType = int(input("Enter 1 for F->C, or 2 for C->F: ")) inputTemperature = int(input("Enter input temperature: ")) convertedTemp = temperatureConverter(conversionType, inputTemperature) print("The converted temperature is", convertedTemp) cont = wantsToContinue() print("") main()
true