blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
c9dadcd37ac16013e6a9c23aa3afe411bacd400e
jhuang09/GWC-2018
/Data Science/attack.py
2,488
4.34375
4
# This project checks to see if your password is a strong one # It works with longer passwords, but not really short ones. # That's because since each letter is considered a word in the dictionary.txt file, # any password that contains just letters will be considered as a word/not a strong password. # To alleviate this, I've split it so that it will break the string into substrings of length 3, # because there are a lot of combinations of two letter words in the dictionary.txt as well. # doesn't work for "I", "am", etc. etc. # longer words should work def is_secure(password, word_list): # make a list of letters of word if (password in word_list): print(password) return False # char_list = list(password) if (len(password) < 3): if (not password in word_list): return True # iterate through letters in password # start with one letter and then keep incresing letters # to check if the substring of password is an actual word for i in range(3, len(password)): sub_pw = password[0:i] if(sub_pw in word_list): print("i=", i, "sub=", sub_pw) secure = is_secure(password[i:], word_list) # print(secure) if (not secure): return False if(i == len(password) - 1): return True # goes through each word in the dictionary and checks if it appears in the password # doesn't work too well because each letter counts as a word in the dictionary.txt # for word in word_list: # if (word in password): # index = password.find(word) #first index of word appearing # left_pw = password[0:index] # right_pw = password[index + len(word):] # security = [is_secure(left_pw, word_list), is_secure(right_pw, word_list)] # # only if both left and right sides are actual words, then return false # if (security[0] == False and security[1] == False): # return False return True # open and read in words from text file file = open("dictionary.txt", "r") text = file.read() file.close() # will automatically create a list of all the words split = text.split() # print(type(split)) # prompt user for input password = input("What's your password?\n").lower() secure = is_secure(password, split) # keep prompting user if the password is a word while (len(password) < 3 or not secure): #any(word in password for word in split) password = input("Password is a word! Enter a new one.\n").lower() secure = is_secure(password, split) print("Congratulations! Your password is very secure!")
true
32c4a398d4cc157611fb6827fce531ecbb82f431
GeraldShin/PythonSandbox
/OnlineCode.py
1,851
4.28125
4
#This will be snippets of useful code you find online that you can copy+paste when needed. #Emoji Package #I don't know when this will ever be helpful, but there is an Emoji package in Python. $ pip install emoji from emoji import emojize print(emojize(":thumbs_up:")) #thumbs up emoji, check notes for more. #List comprehensions #You could probably get better at these... here is an easy example for reference numbers = [1,2,3,4,5,6,7] evens = [x for x in numbers if x % 2 is 0] odds = [y for y in numbers if y not in evens] cities = ['London', 'Dublin', 'Oslo'] def visit(city): print("Welcome to "+city) for city in cities: visit(city) def split_lines(s): #split a string into pieces using a separator return s.split('\n') split_lines('50\n python\n snippets') language = "python" #reverse the order of the letters in a word reversed_language = language[::-1] print(reversed_language) def union(a,b): #find elements that exist in both lists return list(set(a + b)) union([1, 2, 3, 4, 5], [6, 2, 8, 1, 4]) def unique(list): #finds if all elements in a list are unique if len(list)==len(set(list)): print("All elements are unique") else: print("List has duplicates") unique([1,2,3,4,5]) # All elements are unique from collections import Counter #counts freq of appearance of elements list = [1, 2, 3, 2, 4, 3, 2, 3] count = Counter(list) print(count) # {2: 3, 3: 3, 1: 1, 4: 1} def most_frequent(list): #piggy-backing, finds most freq appearance of elements return max(set(list), key = list.count) numbers = [1, 2, 3, 2, 4, 3, 1, 3] most_frequent(numbers) # 3 def multiply(n): #mapping applies the function in the parens to the data element in the parens return n * n list = (1, 2, 3) result = map(multiply, list) print(list(result)) # {1, 4, 9}
true
9e304793cd98bac00cc967be51c1c3da49dd8639
Isaac-D-Dawson/Homework-Uploads
/PyCheckIO/ReverseEveryAscending.py
2,396
4.46875
4
# Create and return a new iterable that contains the same elements as the argument iterable items, but with the reversed order of the elements inside every maximal strictly ascending sublist. This function should not modify the contents of the original iterable. # Input: Iterable # Output: Iterable # Precondition: Iterable contains only ints # The mission was taken from Python CCPS 109 Fall 2018. It’s being taught for Ryerson Chang School of Continuing Education by Ilkka Kokkarinen def reverse_ascending(items): #stage one: sanity checker: if len(items) <= 2: #if there are two items in the list return(items) #don't make changes, it shouldn't matter. else: #otherwise, run the program normally. #allocate variables now that we know we need them. outval = [] #outpt variable midval = [[]] #the variable we perform all out operations in. h = 0 #What was the last number we looked at? for i in items: if i > h: #if I is more than the last thing we looked at, midval[-1].append(i) #it goes in the existing sublist else: #otherwise midval.append([i]) #it goes in a new sublist h = i #Here's the last thing we checked #print(midval) #Debug call #print(midval) #Debug call for i in midval: for j in reversed(i): #For each item in a reversed sublist outval.append(j) #Add it to the output #print(outval) #Debug call return(outval) # if __name__ == '__main__': # print("Example:") # print(reverse_ascending([1, 2, 3, 4, 5])) # # These "asserts" are used for self-checking and not for an auto-testing # assert list(reverse_ascending([1, 2, 3, 4, 5])) == [5, 4, 3, 2, 1] # assert list(reverse_ascending([5, 7, 10, 4, 2, 7, 8, 1, 3])) == [10, 7, 5, 4, 8, 7, 2, 3, 1] # assert list(reverse_ascending([5, 4, 3, 2, 1])) == [5, 4, 3, 2, 1] # assert list(reverse_ascending([])) == [] # assert list(reverse_ascending([1])) == [1] # assert list(reverse_ascending([1, 1])) == [1, 1] # assert list(reverse_ascending([1, 1, 2])) == [1, 2, 1] # print("Coding complete? Click 'Check' to earn cool rewards!")
true
b440d0252e9ed8a9bc3f84b569a31f819225302a
Isaac-D-Dawson/Homework-Uploads
/PyCheckIO/DateTimeConverter.py
1,685
4.5
4
# Computer date and time format consists only of numbers, for example: 21.05.2018 16:30 # Humans prefer to see something like this: 21 May 2018 year, 16 hours 30 minutes # Your task is simple - convert the input date and time from computer format into a "human" format. # example # Input: Date and time as a string # Output: The same date and time, but in a more readable format # Precondition: # 0 < date <= 31 # 0 < month <= 12 # 0 < year <= 3000 # 0 < hours < 24 # 0 < minutes < 60 def date_time(time: str) -> str: date = time.split(" ")[0] clock = time.split(" ")[1] months = "January,Febuary,March,April,May,June,July,August,Septermber,October,November,December".split(",") date = date.split(".") clock = clock.split(":") if int(clock[0]) == 1: hours = "hour" else: hours = "hours" if int(clock[1]) == 1: minutes = "minute" else: minutes = "minutes" outval = f"{int(date[0])} {months[int(date[1])-1]} {date[2]} year {int(clock[0])} {hours} {int(clock[1])} {minutes}" #print(outval)#Debug output return(outval) # if __name__ == '__main__': # print("Example:") # print(date_time('01.01.2000 00:00')) # #These "asserts" using only for self-checking and not necessary for auto-testing # assert date_time("01.01.2000 00:00") == "1 January 2000 year 0 hours 0 minutes", "Millenium" # assert date_time("09.05.1945 06:30") == "9 May 1945 year 6 hours 30 minutes", "Victory" # assert date_time("20.11.1990 03:55") == "20 November 1990 year 3 hours 55 minutes", "Somebody was born" # print("Coding complete? Click 'Check' to earn cool rewards!")
true
239f81592f5c85411d53ced66e13b7ec94218b97
Isaac-D-Dawson/Homework-Uploads
/PyCheckIO/MedianOfThree.py
1,536
4.375
4
# Given an iterable of ints , create and return a new iterable whose first two elements are the same as in items, after which each element equals the median of the three elements in the original list ending in that position. # Wait...You don't know what the "median" is? Go check out the separate "Median" mission on CheckiO. # Input: Iterable of ints. # Output: Iterable of ints. # The mission was taken from Python CCPS 109 Fall 2018. It’s being taught for Ryerson Chang School of Continuing Education by Ilkka Kokkarinen from typing import Iterable def median_three(els: Iterable[int]) -> Iterable[int]: if len(els) <= 2: #if there are two or less items in els return(els) #return it else: #otherwise outval = els[0:2] #set the output variable to be the first two items in els for i in range(2, len(els)): #Then, for every number other than the first two... outval.append(sorted([els[i-2], els[i-1], els[i]])[1]) #Get the median ending at that position. #print(outval) #Debug call return(outval) #Output the output variable # if __name__ == '__main__': # print("Example:") # print(list(median_three([1, 2, 3, 4, 5, 6, 7]))) # # These "asserts" are used for self-checking and not for an auto-testing # assert list(median_three([1, 2, 3, 4, 5, 6, 7])) == [1, 2, 2, 3, 4, 5, 6] # assert list(median_three([1])) == [1] # print("Coding complete? Click 'Check' to earn cool rewards!")
true
f4fc59d24310afd8a4fb778ad743d194cc0c1e2a
Isaac-D-Dawson/Homework-Uploads
/PyCheckIO/MorseDecoder.py
2,122
4.125
4
# Your task is to decrypt the secret message using the Morse code. # The message will consist of words with 3 spaces between them and 1 space between each letter of each word. # If the decrypted text starts with a letter then you'll have to print this letter in uppercase. # example # Input: The secret message. # Output: The decrypted text. # Precondition: # 0 < len(message) < 100 # The message will consists of numbers and English letters only. MORSE = {'.-': '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', '-----': '0', '.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5', '-....': '6', '--...': '7', '---..': '8', '----.': '9' } def morse_decoder(code): inval = code.split(" ")#get it as individual words) #We do the first word maually to ensure valid capitaliseation currentWord = inval[0].split(" ") outval = MORSE[currentWord[0]].upper() for i in currentWord[1:]: outval = f"{outval}{MORSE[i]}" #Now we decode the rest normally for i in inval[1:]: outval = f"{outval} " for j in i.split(" "): outval = f"{outval}{MORSE[j]}" print(outval)#Debug call return(outval) # if __name__ == '__main__': # print("Example:") # print(morse_decoder('... --- ...')) # #These "asserts" using only for self-checking and not necessary for auto-testing # assert morse_decoder("... --- -- . - . -..- -") == "Some text" # assert morse_decoder("..--- ----- .---- ---..") == "2018" # assert morse_decoder(".. - .-- .- ... .- --. --- --- -.. -.. .- -.--") == "It was a good day" # print("Coding complete? Click 'Check' to earn cool rewards!")
true
50deb4603696cf2de54543fdc813df491944525c
BerkeleyPlatte/competitiveCode
/weird_string_case.py
958
4.4375
4
#Write a function toWeirdCase (weirdcase in Ruby) that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd #indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character should be upper cased. #The passed in string will only consist of alphabetical characters and spaces(' '). Spaces will only be present if there are multiple words. Words will be separated by a #single space(' '). def to_weird_case(string): string_list = list(string) altered_list = [] for index, value in enumerate(string_list): if value.isalpha(): if index % 2 == 0: altered_list.append(value.upper()) else: altered_list.append(value.lower()) else: altered_list.append(value) return ''.join(altered_list) print(to_weird_case('This'))
true
89708757e3ec29b31feef559b24ff8b3a336c6e5
gab-umich/24pts
/fraction.py
1,979
4.1875
4
from math import gcd # START OF CLASS DEFINITION # EVERYTHING IS PUBLIC class Fraction: """A simple class that supports integers and four operations.""" numerator = 1 denominator = 1 # Do not modify the __init__ function at all! def __init__(self, nu, de): """Assign numerator and denominator, then simplify""" self.numerator = nu self.denominator = de self.simplify() # Do not modify the simplify function at all! def simplify(self): """_________Require: self.numerator is an int, self.denominator is an int, Modify: Simplify numerator and denominator, Effect: GCD(numerator, denominator) == 1""" try: if self.denominator == 0: raise ValueError("denominator is zero ") gcd_ = gcd(self.numerator, self.denominator) self.numerator /= gcd_ self.denominator /= gcd_ except ValueError as err: print(err) # Do not modify the print function at all! def print(self): print("{}/{}".format(self.numerator, self.denominator)) # END OF CLASS DEFINITION def add(frac1, frac2): """________Require: frac1 and frac2 are simplified Modify: nothing Effect: return frac1 added by frac2 and simplified""" def sub(frac1, frac2): """________Require: frac1 and frac2 are simplified Modify: nothing Effect: return frac2 subtracted from frac1 and simplified""" def mul(frac1, frac2): """________Require: frac1 and frac2 are simplified Modify: nothing Effect: return frac1 multiplied by frac2 and simplified""" def div(frac1, frac2): """________Require: frac1 and frac2 are simplified Modify: nothing Effect: return frac1 divided by frac2 simplified""" # this is tricky! What can go wrong in div??
true
1fb18bf77b33d4e911364ff771b8ea1bb11c20cc
Luoxsh6/CMEECourseWork
/Week2/code/tuple.py
980
4.5625
5
#!/usr/bin/env python """Practical of tuple with list comprehension""" __author__ = 'Xiaosheng Luo (xiaosheng.luo18@imperial.ac.uk)' __version__ = '0.0.1' birds = (('Passerculus sandwichensis', 'Savannah sparrow', 18.7), ('Delichon urbica', 'House martin', 19), ('Junco phaeonotus', 'Yellow-eyed junco', 19.5), ('Junco hyemalis', 'Dark-eyed junco', 19.6), ('Tachycineata bicolor', 'Tree swallow', 20.2), ) # Birds is a tuple of tuples of length three: latin name, common name, mass. # write a (short) script to print these on a separate line or output block by species # Hints: use the "print" command! You can use list comprehension! # ANNOTATE WHAT EVERY BLOCK OR IF NECESSARY, LINE IS DOING! # ALSO, PLEASE INCLUDE A DOCSTRING AT THE BEGINNING OF THIS FILE THAT # SAYS WHAT THE SCRIPT DOES AND WHO THE AUTHOR IS # use traditional loops for i in range(len(birds)): print(birds[i]) # use list comprehension [print(birds[i]) for i in range(len(birds))]
true
8e11531642b2dfb6460f5240499eba2c1fd7e8d9
YuvalSK/curexc
/cod.py
1,872
4.3125
4
import exrates import datetime import sys def inputdate(date_text): '''function that inputs a date, and verified if the date is in a vaild format, else return False ''' try: datetime.datetime.strptime(date_text, '%Y-%m-%d') return True except ValueError: return False def main(): '''main to test the program: inputs a date, and prints the list of currencies for which there is a date, in format requested ''' datetext = input("Greetings User! please enter a date:" ) #value vaildation using the function above, loop untill correct format, with mentioning problem while inputdate(datetext)== False: #printing error! sys.stderr.write("\Value Error! invalid input-choose an available date\n") datetext = input(" Let's give it another try! " + "\n" +" please enter a date:" + '\n' + " i.e. 'YYYY-MM-DD' stracture, an exsample for a vaild format is 2017-03-11" + '\n') inputdate(datetext) #using the date the user entered, to withdraw the dictionery from exrates file, get_exrate fuction and sorted by code. date_Rates = sorted(exrates.get_exrates(datetext)) #marging two dictionery, to get the name and code in one dictionery curlist = exrates.get_currencies() #the format requested format_list = '{name} ({code})' #creating the list, using the format above, while check every code in the updated code list Final_list = [format_list.format(name=curlist.get(code, "<unknonwn>"),code=code) for code in date_Rates] print('\nHere is a list of correncies available to ' + datetext + " : \n") #print the values of the list print('\n'.join(Final_list)) main()
true
1114c211c01850695d172cab82d0d544640e2f91
AdarshRise/Python-Nil-to-Hill
/1. Nil/6. Function.py
1,618
4.53125
5
# Creating Function # function are created using def def fun(): print(" function got created ") def fun2(x): print("value of x is :",x) # a bit complex use of function def fun3(x): x=x*x print("value of x*x is ",x) # above code will execute from here x=2 fun() fun2(x) fun3(x) print(x) # the value of x is unaffected by fun3() #-------------------------------------------------- # Variable present in the function call are called -: Actual parameters # Variable present in the function defintion are called -: Formal parameters #-------------------------------------------------- # passing parameter in functions def par(x,y): # function without default value of y print(" value of x ",x,"value of y ",y) def par2(x,y=10): # function with default value of y print(" value of x ",x," value of y ",y) # this will execute the code above x=3 y=4 par(x,y) # passing 2 parameter to a function without default value par2(x) # passing 1 parameter to a function with a default value par2(x,y) # passing 2 parameter to a function with a default value par2(y=50,x=90) # passing values in different order but with the names of Formal parameters # code below is invalid #----------------------- # def fun(x=10,y): # some code.... #----------------------- #------------------------------------------------------------ # there is No exact main funtion, but we can make one def main(): print(" all the exectue statements should go here ") if __name__="__main__": main() # the above code works as a sudo-main funtion in python, learn more about __name__
true
a9917be09fdd70e78780145231214f1bc833ef95
mpwesthuizen/eng57_python
/dictionairies/dictionairies.py
1,292
4.46875
4
# Dictionairies # definitions # a dictionary is a data structure, like a list, but organised with a key and not indexes # They are organised with key: 'value' pairs # for example 'zebra': "an african wild animal that looks like a horse but has stripes on its body." # this means you can search data using keys, rather than index. # syntax my_dictionary ={'key':'value'} print(type(my_dictionary)) # Defining a dictionary # looking at our stringy landlords we need more info.. like the houses they have and contact detail. stingy_dict = { 'name': 'giggs', 'phone_number' : '0745 678 910', 'property_type': 'flat' } # printing dictionary print(stingy_dict) print(type(stingy_dict)) # getting one value out print(stingy_dict['name']) print(stingy_dict['phone_number']) # re-assigning one value stingy_dict['name'] = "alfredo de medo" print(stingy_dict) # new key value pair stingy_dict['property_type'] = "house 2, Unit 29 Watson Rd" print(stingy_dict) stingy_dict['number_of_victims'] = 0 stingy_dict['number_of_victims'] += 1 print(stingy_dict) # Get all the values out # special dictionary methods # (methods are functions that belong to specific data types) # .keys() print(stingy_dict.keys()) # .values() print(stingy_dict.values()) # .items() print(stingy_dict.items())
true
c0901965ca658c1eb3a7c93624513527f4559564
Mayank-Chandra/LinkedList
/LinkedLIst.py
1,135
4.28125
4
class Node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.head=None def push(self,new_data): new_node=Node(new_data) new_node.next=self.head self.head=new_node def insertAfter(self,prev_node,new_data): if prev_node is None: print('The Given Previous node must be in LinkedList:') return new_node=Node(new_data) new_node.next=prev_node.next prev_node.next=new_node def append(self,new_data): new_node=Node(new_data) if self.head is None: self.head=new_node return last=self.head while(last.next): last=last.next last.next=new_node def printList(self): temp=self.head while(temp): print(temp.data) temp=temp.next if __name__=='__main__': list1=LinkedList() list1.append(6) list1.push(7) list1.push(1) list1.append(4) list1.insertAfter(list1.head.next,8) print("The Created List is:",list1.printList())
true
461085bffe23b8dd9873de328d4a859beb12e3ab
jcjc2019/edX-MIT6.00.1x-IntroToComputerScience-ProgrammingUsingPython
/Program2-ndigits.py
405
4.125
4
# below is the function to count the number of digits in a number def ndigits(x): # when x is more than 0 if x > 0: #change type to string, count the length of the string return len(str(int(x))) # when x is less than 0 elif x < 0: #get the absolute value, change type to string, and count the length return len(str(abs(x))) else: return 0
true
8952a219e349498121e00fc45c06c53b19e92b65
earl-grey-cucumber/Algorithm
/353-Design-Snake-Game/solution.py
1,815
4.1875
4
class SnakeGame(object): def __init__(self, width,height,food): """ Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]] """ self.width, self.height, self.food = width, height, food self.foodCount = 0 self.body = [0] self.directions = {'U': [-1, 0], 'L': [0, -1], 'R': [0, 1], 'D': [1, 0]} def move(self, direction): """ Moves the snake. @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down @return The game's score after the move. Return -1 if game over. Game over when snake crosses the screen boundary or bites its body. :type direction: str :rtype: int """ head = self.body[0] tail = self.body.pop() x = head / self.width y = head % self.width newx = x + self.directions[direction][0] newy = y + self.directions[direction][1] newHead = newx * self.width + newy if (newx < 0 or newx >= self.height or newy < 0 or newy >= self.width or newHead in self.body): return -1 self.body.insert(0, newHead) if (self.foodCount < len(self.food) and newx == self.food[self.foodCount][0] and newy == self.food[self.foodCount][1]): self.foodCount += 1 self.body.append(tail) return len(self.body) - 1 # Your SnakeGame object will be instantiated and called as such: # obj = SnakeGame(width, height, food) # param_1 = obj.move(direction)
true
0b4692180343e2d59f6eecc315b8886072b07dd9
Laxaria/LearningPyth3
/PracticePython/Fibonacci.py
987
4.5625
5
# Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. # Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number # of numbers in the sequence to generate. # (Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is # the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …) # http://www.practicepython.org/exercise/2014/04/30/13-fibonacci.html def Fib_Generator(userInput): fibList = [0, 1,1] userInput = int(userInput) if userInput == 0: print(fibList[0]) elif userInput == 1: print(fibList[0:2]) elif userInput == 2: print(fibList[0:3]) else: for _i in range(userInput-3): fibList.append(fibList[-1] + fibList[-2]) print(fibList) Fib_Generator(input("How many Fibonnaci numbers do you want to generate? Input: "))
true
6d288b804d2b5cc07008fd53cf4ff7352052e458
MelindaD589/Programming-Foundations-Fundamentals
/practice.py
448
4.125
4
# Chapter 1 print("Hello world!") # Chapter 2 # Exercise 1 name = input("Hi, what's your name? ") age = int(input("How old are you? ")) if (age < 13): print("You're too young to register", name) else: print("Feel free to join", name) # Exercise 2 print("Hello world!") print("Goodbye world!") # Exercise 3 # syntax error print("Hello world") # runtime error 10 * (2/0) # semantic error name = "Alice" print("Hello name")
true
fc7376086c6c59f67ab1009af30a49a5491079f1
debdutgoswami/python-beginners-makaut
/day-6/ascendingdescending.py
344
4.34375
4
dictionary = {"Name": "Debdut","Roll": "114", "Dept.": "CSE"} ascending = dict(sorted(dictionary.items(), key=lambda x: x[1])) descending = dict(sorted(dictionary.items(), key=lambda x: x[1], reverse=True)) print("the dictionary in ascending order of values is",ascending) print("the dictionary in descending order of values is",descending)
true
9b2e6ada5318d7eecc9797368fa73b53fef11943
MikeWooster/reformat-money
/reformat_money/arguments.py
1,405
4.125
4
class Argument: """Parses a python argument as string. All whitespace before and after the argument text itself is stripped off and saved for later reformatting. """ def __init__(self, original: str): original.lstrip() start = 0 end = len(original) - 1 while original[start].isspace(): start += 1 while original[end].isspace(): end -= 1 # End requires +1 when used in string slicing. end += 1 self._leading_whitespace = original[:start] self._trailing_whitespace = original[end:] self.set_text(original[start:end or None]) def get_leading_whitespace(self): return self._leading_whitespace def get_trailing_whitespace(self): return self._trailing_whitespace def set_text(self, text): self._text = text def get_text(self): return self._text def __str__(self): return f"{self.get_leading_whitespace()}{self.get_text()}{self.get_trailing_whitespace()}" def __repr__(self): return f"'{self}'" def __eq__(self, other): return ( isinstance(other, Argument) and self.get_leading_whitespace() == other.get_leading_whitespace() and self.get_text() == other.get_text() and self.get_trailing_whitespace() == other.get_trailing_whitespace() )
true
8b2aadc3171527ad7c2880ee3d5167cd0542ba85
edu-athensoft/ceit4101python
/stem1400_modules/module_4_function/func1_define/function_3.py
392
4.15625
4
""" function - without returned value - with returned value """ def showmenu(): print("egg") print("chicken") print("fries") print("coke") print("dessert") return "OK" # call it and lost returned value showmenu() print() print(showmenu()) print() # call it and keep returned value isdone = showmenu() print(isdone) print(isdone+" -2nd") print(isdone+" -3rd")
true
7a13ea84858a0824e09630477fe3861eb26571ae
edu-athensoft/ceit4101python
/stem1400_modules/module_12_oop/oop_06_instance/s5_add_attribute/instance_attribute_2.py
593
4.46875
4
""" Adding attributes to an object """ # defining a class class Cat: def __init__(self, name, age): self.name = name self.age = age # self.color does not exist. def sleep(self): print('sleep() is called') def eat(self): print('eat() is called') # def antimethod(self): # pass # main program tom = Cat("Tom",1) # print(tom.color) # AttributeError: 'Cat' object has no attribute 'color' tom.color = "Orange" print(tom.color) peter = Cat("Peter",1) print(peter.color) # AttributeError: 'Cat' object has no attribute 'color'
true
420933e86e4ecad7a1108f09fcbf2531af0ee7df
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_6_dictionary/dictionary_func_03_len.py
1,458
4.125
4
# len() # How len() works with tuples, lists and range? testList = [] print(testList, 'length is', len(testList)) testList = [1, 2, 3] print(testList, 'length is', len(testList)) testTuple = (1, 2, 3) print(testTuple, 'length is', len(testTuple)) testRange = range(1, 10) print('Length of', testRange, 'is', len(testRange)) # How len() works with strings and bytes? testString = '' print('Length of', testString, 'is', len(testString)) testString = 'Python' print('Length of', testString, 'is', len(testString)) # byte object testByte = b'Python' print('Length of', testByte, 'is', len(testByte)) testList = [1, 2, 3] # converting to bytes object testByte = bytes(testList) print('Length of', testByte, 'is', len(testByte)) # How len() works with dictionaries and sets? testSet = {1, 2, 3} print(testSet, 'length is', len(testSet)) # Empty Set testSet = set() print(testSet, 'length is', len(testSet)) testDict = {1: 'one', 2: 'two'} print(testDict, 'length is', len(testDict)) testDict = {} print(testDict, 'length is', len(testDict)) testSet = {1, 2} # frozenSet frozenTestSet = frozenset(testSet) print(frozenTestSet, 'length is', len(frozenTestSet)) # How len() works for custom objects? # skip class Session: def __init__(self, number=0): self.number = number def __len__(self): return self.number # default length is 0 s1 = Session() print(len(s1)) # giving custom length s2 = Session(6) print(len(s2))
true
abf7b2cfe1d7d7c171855ca4dad7e57f6fd6943d
edu-athensoft/ceit4101python
/evaluate/evaluate_3_project/python1_beginner/guessing_number/guessing_number_v1.py
1,689
4.25
4
""" Guessing number version 1.0 problems: 1. how to generate a random number/integer within a given range 2. how to validate the number and make it within your upper and lower bound 3. comparing your current number with the answer case #1: too small case #2: too big case #3: bingo 4. max 5 times failed for 5 times -> get "???" won within 5 times -> get "???" 5. difficulty problem fixed difficulty (version 1.0) adjustable difficulty (version 1.1) 6. the number of turns you may play (version 2) """ import random def generate_answer(): answer = random.randrange(1,101) return answer def set_difficulty(): chances = 5 return chances def get_valid_number(): x = None while True: myinput = input("enter a number (1-100):") # validate myinput if myinput.isdigit(): x = int(myinput) if x > 100 or x < 1: print("Warning: Please input a valid number!") else: # print("Your input is {}".format(x)) break else: print("Warning: Please input a valid number!") return x def compare(x, answer): flag = False if x > answer: print("Too big") elif x < answer: print("Too small") else: print("bingo") flag = True return flag # main program, main logic answer = generate_answer() print("answer =", answer) chances = set_difficulty() for i in range(chances): x = get_valid_number() if compare(x, answer): break else: print("You have {} chances left".format(chances - i - 1)) print()
true
5378ef0faa41bacd228ee02bc616d4fc74fd8bfb
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_6_dictionary/dictionary_func_04_sorted.py
1,380
4.375
4
# sorted() # sorted(iterable[, key][, reverse]) # sorted() Parameters # sorted() takes two three parameters: # # iterable - sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any iterator # reverse (Optional) - If true, the sorted list is reversed (or sorted in Descending order) # key (Optional) - function that serves as a key for the sort comparison # Return value from sorted() # sorted() method returns a sorted list from the given iterable. # Sort a given sequence: string, list and tuple # vowels list pyList = ['e', 'a', 'u', 'o', 'i'] print(sorted(pyList)) # string pyString = 'Python' print(sorted(pyString)) # vowels tuple pyTuple = ('e', 'a', 'u', 'o', 'i') print(sorted(pyTuple)) # Sort a given collection in descending order: set, dictionary and frozen set # set pySet = {'e', 'a', 'u', 'o', 'i'} print(sorted(pySet, reverse=True)) # dictionary pyDict = {'e': 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5} print(sorted(pyDict, reverse=True)) # frozen set pyFSet = frozenset(('e', 'a', 'u', 'o', 'i')) print(sorted(pyFSet, reverse=True)) # Sort the list using sorted() having a key function # take second element for sort def takeSecond(elem): return elem[1] # random list random = [(2, 2), (3, 4), (4, 1), (1, 3)] # sort list with key sortedList = sorted(random, key=takeSecond) # print list print('Sorted list:', sortedList)
true
4fbf6cc6d51892c9a80e5d4266be5ad184d5ff30
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_7_array/array_3_search.py
571
4.21875
4
""" Searching element in a Array """ import array # initializing array with array values # initializes array with signed integers arr = array.array('i', [1, 2, 3, 1, 2, 5]) # printing original array print("The new created array is : ", end="") for i in range(0, 6): print(arr[i], end=" ") print("\r") # using index() to print index of 1st occurrence of 2 print("The index of 1st occurrence of 2 is : ", end="") print(arr.index(2)) # using index() to print index of 1st occurrence of 1 print("The index of 1st occurrence of 1 is : ", end="") print(arr.index(1))
true
c1fe6f37a7e4522a78a2e1d2922bdb6102636941
edu-athensoft/ceit4101python
/stem1400_modules/module_10_gui/s04_widgets/s0401_label/label_7_justify.py
1,117
4.1875
4
""" Tkinter place a label widget justify=left|center(default)|right """ from tkinter import * root = Tk() root.title('Python GUI - Label justify') root.geometry("{}x{}+200+240".format(640, 480)) root.configure(bg='#ddddff') # create a label widget label1 = Label(root, text='Tkinter Label 1', height=3, width=28, font = "Helnetic 20 bold italic", bg='#72EFAA', fg='black', wraplength=180, justify='right') # show on screen label1.pack() # create a label widget label2 = Label(root, text='Tkinter Label 2', height=3, width=28, font = "Helnetic 20 bold italic", bg='#EF72AA', fg='black', wraplength=180, justify='left') # show on screen label2.pack() # create a label widget label3 = Label(root, text='Tkinter Label 3', height=3, width=28, font = "Helnetic 20 bold italic", bg='#EFAA72', fg='black', wraplength=180, justify='center') # show on screen label3.pack() root.mainloop()
true
845282c41034ea8dd5595f6d9f41bc9dff50bfee
edu-athensoft/ceit4101python
/stem1400_modules/module_9_datetime/s93_strptime/s3_strptime/datetime_17_strptime.py
420
4.1875
4
""" datetime module Python format datetime Python has strftime() and strptime() methods to handle this. The strptime() method creates a datetime object from a given string (representing date and time) """ from datetime import datetime date_string = "21 June, 2018" print("date_string =", date_string) date_object = datetime.strptime(date_string, "%d %B, %Y") print("date_object =", date_object, type(date_object))
true
7b97eec2bef56c7cdfc4577d5838ba2d7c1cd4b3
edu-athensoft/ceit4101python
/stem1471_projects/p00_file_csv_processor_2/csv_append_row.py
824
4.25
4
""" csv processor append a row In this example, we first define the data that we want to append to the CSV file, which is a list of values representing a new row of data. We then open the CSV file in append mode by specifying 'a' as the file mode. This allows us to append data to the end of the file rather than overwriting the entire file. Finally, we use the csv.writer object to write the new row of data to the CSV file using the writerow() method. Note that we also specify newline='' when opening the file to ensure that the correct line endings are used on all platforms. """ import csv # data to append to CSV file new_row = [6, 'Cathy', 'Saint Luc', 'G8'] # open CSV file in append mode with open('data/output.csv', mode='a', newline='') as file: writer = csv.writer(file) writer.writerow(new_row)
true
9ba6f0b0303c1287bfc28a289e4afe878b85cd34
edu-athensoft/ceit4101python
/stem1400_modules/module_12_oop/oop_09_inheritance/s10_super/demo1_super_single/super_init_2c.py
736
4.375
4
""" super and init child overrides init() of parent and use its own init() child has its own property: age parent has a property: name child cannot inherit parent's property due to overriding, properties defined in parent do not take effect to child. """ class Parent: def __init__(self, name): print('Parent __init__() called.') self.name = name class Child(Parent): def __init__(self, age): print('Child __init__() called.') self.age = age # main # c1 = Child() # TypeError: __init__() missing 1 required positional argument: 'age' c1 = Child(16) print(c1.age) # print(c1.name) # AttributeError: 'Child' object has no attribute 'name' # there is no such attribute defined in Child
true
ba671e89c9244cd5969667d0f9aca6bec71a825d
edu-athensoft/ceit4101python
/stem1400_modules/module_12_oop/oop_09_inheritance/s10_super/demo1_super_single/super_init_2e.py
672
4.21875
4
""" super and init child overrides init() of parent and use its own init() child has its own property: age parent has a property: name child inherit parent's property by super(), child init() must accept all parameters the order of parameter matters """ class Parent: def __init__(self, name): print('Parent __init__() called.') self.name = name class Child2(Parent): def __init__(self, age, name): print('Child __init__() called.') self.age = age super().__init__(name) # main # order of arguments do not match that of the declared parameters c2 = Child2('Jack', 18) print('age:',c2.age) print('name:',c2.name)
true
aaba8ca8136fbb564b3c3a6869e57ec0be0b0fbf
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_4_string/string_demo/string_1_capitalize.py
761
4.46875
4
""" string method - capitalize() string.capitalize() return a new string """ # case 1. capitalize a sentence str1 = "pyThOn is AWesome." result = str1.capitalize() print(f"old string: {str1}") print(f"new string: {result}") print() # case 2. capitalize two sentence str1 = "pyThOn is AWesome. pyThOn is AWesome." result = str1.capitalize() print(f"old string: {str1}") print(f"new string: {result}") print() # case 3. non-alphabetic first character str1 = "+ pyThOn is AWesome." result = str1.capitalize() print(f"old string: {str1}") print(f"new string: {result}") print() # case 4. whitespace as the first character str1 = " pyThOn is AWesome." result = str1.capitalize() print(f"old string: {str1}") print(f"new string: {result}") print()
true
e8beb53f159933978745cec0d453798992e3c514
edu-athensoft/ceit4101python
/stem1400_modules/module_12_oop/oop_11_classmember/s01_class_attribute/demo_4_add_property.py
482
4.25
4
""" adding properties by assignment """ class Tool: count = 0 def __init__(self, name): self.name = name Tool.count += 1 # test tool1 = Tool("hammer") print(f'{tool1.count} tool(s) is(are) created.') print() tool1.count = 99 print(f'The instance tool1 has extra property: count') print(f'{tool1.count} tools are created.') print() print(f'Now instance property has nothing to do with class property: count') print(f'{Tool.count} tools are created.')
true
c958faae61b8d8a3f1a85cba789bbf87d87a1388
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_7_array/array_2_add_2.py
347
4.34375
4
""" Python array Adding Elements to a Array append() extend() source: """ import array as arr numbers = arr.array('i', [1, 2, 3]) numbers.append(4) print(numbers) # Output: array('i', [1, 2, 3, 4]) # extend() appends iterable to the end of the array numbers.extend([5, 6, 7]) print(numbers) # Output: array('i', [1, 2, 3, 4, 5, 6, 7])
true
4a5ca15f00ebf97484032636a9bf7a10458bc914
edu-athensoft/ceit4101python
/stem1400_modules/module_10_gui/s04_widgets/s0401_label/label_1_create.py
342
4.3125
4
""" Tkinter place a label widget Label(parent_object, options,...) using pack() layout ref: #1 """ from tkinter import * root = Tk() root.title('Python GUI - Text Label') root.geometry("{}x{}+200+240".format(640, 480)) # create a label widget label1 = Label(root, text='Tkinter Label') # show on screen label1.pack() root.mainloop()
true
4543ea3f1dc6e723d7dfc265b3fe856dc787f186
edu-athensoft/ceit4101python
/stem1400_modules/module_14_regex/s3_re/regex_9_search.py
266
4.1875
4
""" regex """ import re mystr = "Python is fun" pattern = r'\APython' # check if 'Python' is at the beginning match = re.search(pattern, mystr) print(match, type(match)) if match: print("pattern found inside the string") else: print("pattern not found")
true
0d3f250ba8d881ab75e3f043e905ec3425424496
edu-athensoft/ceit4101python
/evaluate/evaluate_2_quiz/stem1401_python1/quiz313/q6.py
1,290
4.4375
4
""" Quiz 313 q6 A computer game company is developing a 3A-level role-playing game. The character you are controlling will receive equipment items of different tiers while adventuring in the big world. The system will display different background and text colors according to the level of the item to distinguish them. If the item is of the first tier, the system uses gray; if the item is of the second tier, the system uses green; if the item is of the tier level, the system uses blue; if the item is of the fourth tier, the system uses purple; if the item is of the fifth tier, the system uses gold(en). Please write a program to determine what color should be used to display the background and text of an item based on its tier when you pick up an item and know its tier number. Hint: Please save your code in the file naming as stem1401_quiz313_q6_yourname.py """ # tier numbers = 1, 2, 3, 4, 5 tier_num = int(input("Input a number of tier: ")) color = None if tier_num == 1: color = "gray" elif tier_num == 2: color = "green" elif tier_num == 3: color = "blue" elif tier_num == 4: color = "purple" elif tier_num == 5: color = "golden" else: print("Invalid input.") if color: print(f"The right color of tier number {tier_num} should be {color}.")
true
92d6114c1a38dc82151a67729905a625ef3f18ff
Mart1nDimtrov/Math-Adventures-with-Python
/01. Drawing Polygons with the Turtle Module/triangle.py
373
4.53125
5
# exerCise 1-3: tri anD tri again # Write a triangle() # function that will draw a triangle of a given “side length.” from turtle import * # encapsulate with a function def triangle(sidelength=100): # use a for loop for i in range(3): forward(sidelength) right(120) # set speed and shape shape('turtle') speed(0) # create a square triangle()
true
e8b911a5f1a2d7b8569d3636cc5bcc2b1d5382a1
BH909303/py4e
/ex6_1.py
490
4.1875
4
''' py4e, Chapter 6, Exercise 1: Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards. William Kerley, 21.02.20 ''' fruit = 'banana' index = len(fruit)-1 #set index to last letter of string while index >= 0: #print letters of words from last to first letter = fruit[index] print(letter) index = index - 1
true
ceedc4cf9059a26d9544f553148abac5a5d39d2a
AccentsAMillion/Python
/Ten Real World Applications/Python Basics/Functions and Conditionals/PrintReturnFunction.py
396
4.15625
4
# -*- coding: utf-8 -*- """ Created on Mon Mar 30 09:28:25 2020 @author: Chris """ #To create functions in python it starts with def function(): # Division (/) Function calculating the sum of myList taking in 3 parameters def mean(myList): print("Function mean started!") the_mean = sum(myList) / len(myList) return the_mean myMean = mean([0 ,3 ,4]) print (myMean + 10) print
true
cb12aca17df00ff174aa59c48f720b77c23e9026
andrei-chirilov/ICS3U-assignment-05b-Python
/reverse.py
406
4.1875
4
#!/usr/bin/env python3 # Created by: Andrei Chirilov # Created on: November 2019 # This program reverses a digit import math def main(): number = int(input("Enter a number: ")) result = "" if number == 0: print(0) exit(0) while number != 0: result += str(number % 10) number = math.floor(number / 10) print(result) if __name__ == "__main__": main()
true
9ca29631af7bc11b2128efe122862904346a05ec
oscarmrt/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/8-uppercase.py
241
4.28125
4
#!/usr/bin/python3 def uppercase(str): for characters in str: if ord(characters) >= 97 and ord(characters) <= 122: characters = chr(ord(characters) - 32) print('{:s}'.format(characters), end='') print('')
true
d03cc6651d511fefa6af2adea4aa722df253f99d
gauthamikuravi/Python_challenges
/Leetcode/shift_zeros.py
1,106
4.21875
4
####################################################### #Write a program to do the following:Given an array of random numbers, push all the zeros of a given array to the start of the array. # The order of all other elements should be same. #Example #1: Input: {1, 2, 0, 4, 3, 0, 5, 0} #Output: {0, 0, 0, 1, 2, 4, 3, 5} #Example #2:Input: {1, 2, 0, 0, 0, -1, 6} #Output: {0, 0, 0, 1, 2, -1, 6} #Example #3:Input: {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0} #Output: {0, 0, 0, 0, 1, 9, 8, 4, 2, 7, 6} ########################################### # ran the loop through reverse order # swap the elements in the same position until the first zero element was found class Solution: def shiftposition(self, nums): pos = len(nums) - 1 for i in reversed(range(len(nums))): el = nums[i] if el != 0: nums[pos], nums[i] = nums[i], nums[pos] pos -= 1 return (nums) if __name__ == '__main__': array = [1, 2, 0, 0, 0, -1, 6] sol = Solution() a = sol.shiftposition(array) print(a)
true
53a16f0432aa40c042ddb70f4bfc0b09a97227dc
sk1z0phr3n1k/Projects
/python projects/mbox.py
1,483
4.15625
4
# Author: Mark Griffiths # Course: CSC 121 # Assignment: Lab: Lists (Part 2) # Description: mbox module # The mbox format is a standards-based email file format # where many emails are put in a single file def get_mbox_username(line): """ Get mbox email username Parse username from the start of an email Parameters: line (str): line starting a new email in mbox format Returns: (str) email username """ words=line.split() email=words[1] # use the double split strategy pieces = email.split('@') return(pieces[0]) def get_mbox_domain(line): """ Get mbox email domain Parse domain from a new email in mbox format Parameters: line (str): line starting a new email in mbox format Returns: (str) email internet domain """ words=line.split() email=words[1] # double split strategy pieces = email.split('@') return(pieces[1]) def get_mbox_day(line): """ Get mbox email day of the week Parse the day of the week an email was sent from the start of an email Parameters: line (str): line starting a new email in mbox format Returns: (str) day of the week abbreviation """ words=line.split() return(words[2]) def get_mbox_minute(line): """ Get mbox email minute Parse the minute an email was sent from the start of an email Parameters: line (str): line starting a new email in mbox format Returns: (str) minute """ words=line.split() time=words[5] # double split strategy pieces = time.split(':') return(pieces[1])
true
320fba2a5627ea67e99b54abfae6315115e5c74b
Jamieleb/python
/challenges/prime_checker.py
685
4.34375
4
import math def is_prime(num): ''' Checks if the number given as an argument is prime. ''' #first checks that the number is not even, 1 or 0 (or negative). if num < 2 or num > 2 and not num % 2: return False #checks if all odd numbers up to the sqrt of num are a factor of num for x in range(3, int(math.sqrt(num))+1, 2): if not num % x: return False else: return True #if no numbers are a factor, returns True (that the number is prime) def prime_counter(num): ''' Function returns the number of primes that exist in the range up to and including the given number. ''' count = 0 for i in range(0,num+1): if is_prime(i): count += 1 return count
true
80ae08b7bf04d23b557a34f0dcd409c04b7e942a
2ptO/code-garage
/icake/q26.py
541
4.59375
5
# Write a function to reverse a string in-place # Python strings are immutable. So convert string # into list of characters and join them back after # reversing. def reverse_text(text): """ Reverse a string in place """ if not text: raise ValueError("Text is empty or None") start = 0 end = len(text) - 1 chars = list(text) while start <= end: t = chars[start] chars[start] = chars[end] chars[end] = t start += 1 end -= 1 return "".join(chars)
true
908b37ef23e23156396a33582721faa92f816ddc
Akshaypokley/PYCHAMP
/src/SetConcepts.py
2,816
4.25
4
"""Set A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.""" setex={'java','python',True,False,45,2.3} print(setex) """Access Items You cannot access items in a set by referring to an index, since sets are unordered the items has no index. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.""" for x in setex: print(x) #if we want to check print("java" in setex) """Change Items Once a set is created, you cannot change its items, but you can add new items. """ """Add Items To add one item to a set use the add() method. To add more than one item to a set use the update() method.""" setex.add("AKSHAY") setex.update(["JAVA45",897,65.3]) print(setex) #length of set print(len(setex)) # @We can remove item from set using remove and descard method setex.remove('AKSHAY') setex.discard(2.3) print(setex) #Remove the last item by using the pop() method: setex.pop() print(setex) #The clear() method empties the set: #The del keyword will delete the set completely: """Join Two Sets There are several ways to join two or more sets in Python. You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another:""" setex.clear() print(setex) #del setex #print(setex) set1={3.3,15,45,True,False,'Akshay'} set2={'Java', 'Pokley',True} set3=set1.union(set2) print(set3) set1.update(set2) print(set1) #It also make as constructor set23=set((47,87,'ajksh')) print(set23) print(set2.symmetric_difference(set23)) """Set Methods Python has a set of built-in methods that you can use on sets. Method Description add() Adds an element to the set clear() Removes all the elements from the set copy() Returns a copy of the set difference() Returns a set containing the difference between two or more sets difference_update() Removes the items in this set that are also included in another, specified set discard() Remove the specified item intersection() Returns a set, that is the intersection of two other sets intersection_update() Removes the items in this set that are not present in other, specified set(s) isdisjoint() Returns whether two sets have a intersection or not issubset() Returns whether another set contains this set or not issuperset() Returns whether this set contains another set or not pop() Removes an element from the set remove() Removes the specified element symmetric_difference() Returns a set with the symmetric differences of two sets symmetric_difference_update() inserts the symmetric differences from this set and another union() Return a set containing the union of sets update() Update the set with the union of this set and others"""
true
b7c9deb2e1fd40b3b79343e8afd5f1978ffcb0ae
ayoblvck/Startng-Backend
/Python task 1.py
225
4.5625
5
# a Python program to find the Area of a Circle using its radius import math radius = float(input('Please enter the radius of the circle: ')) area = math.pi * radius * radius print ("Area of the circle is:%.2f= " %area)
true
b6dd55f61795983858f76cbd06978865722c9850
isolis1210/HW2-Python
/calculator.py
1,487
4.5
4
def calculator(): #These lines take inputed values from the user and store them in variables number_1 = float(float(input('Please enter the first number: '))) number_2 = float(float(input('Please enter the second number: '))) operation = input('Please type in the math operation you would like to complete:+,-,*,/,//,** ') #These conditional statements apply the desired math function if operation == "+": print(number_1 + number_2) elif operation == '-': print(number_1 - number_2) elif operation == '*': print(number_1 * number_2) elif operation == '/': print(number_1 / number_2) elif operation == '//': print(number_1 // number_2) elif operation == '**': print(number_1 ** number_2) else: print('FALSE') #If the input for an operation is invalid, this message will appear print('You have not typed a valid operator, please run the program again.') input_output() '''The calculator function takes two numbers and the desired math operation to calculate a solution''' def input_output(): calc_again = input('Do you wish to exit? Please type Y for YES or N for NO. ') if calc_again.upper() == 'N': calculator() elif calc_again.upper() == 'Y': print('See you later.') else: input_output() calculator() ''' This function asks if the user wants to calculate another expression, if so it calls on the calculator function'''
true
32a429bae97a0678517dff15dbce80bbd25ee46a
NSNCareers/DataScience
/Dir_OOP/classVariables.py
1,374
4.3125
4
# Class variables are those shared by all instances of a class class Employee: raise_amount = 10.04 gmail = '@gmail.com' yahoo = '@yahoo.com' num_of_employees = 0 def __init__( self, fistName, lastName, gender, pay): self.first = fistName self.last = lastName self.gender = gender self.p = pay self.email = fistName + '.' + lastName + self.gmail Employee.num_of_employees += 1 def apply_raise(self): self.p = int(self.p + self.raise_amount) return self.p # print(Employee.num_of_employees) emp_1 = Employee('James','Hunter','Male',100000) emp_2 = Employee('Luvas','Gasper','Female',300000) print(emp_1.p) print(emp_1.apply_raise()) print(emp_2.email) # Shows you the class attributes and instance attributes print(Employee.__dict__) # This prints out the name space of Employee print(emp_1.__dict__) # This prints out the name space of emp_1 print(emp_2.__dict__) # This prints out the name space of emp_2 # change class variable using class instance empl_1 emp_1.raise_amount = 30 # change class variable using class its self Employee.raise_amount = 20 print(emp_1.raise_amount) print(Employee.raise_amount) print(emp_1.__dict__) # This prints out the name space of emp_1 print(emp_2.__dict__) # This prints out the name space of emp_2 #print(Employee.num_of_employees)
true
e69539f58ab8f159c826d552d852c08cd79a022f
Developirv/PythonLab1
/exercise-5.py
512
4.25
4
# DELIVERABLE LAB 03/05/2019 5/6 # exercise-05 Fibonacci sequence for first 50 terms # Write the code that: # 1. Calculates and prints the first 50 terms of the fibonacci sequence. f = 1 current = 1 former = 0 for term in range (50): if term == 0: print(f"term: {term} / number: 0") elif term == 1: print(f"term: {term} / number: 1") else: f = current + former print(f"term: {term} / number: {f}") former = current current = f # 2. Print each term and number as follows: # ^^
true
91bcd6886a825494f0013eb115ee3f8ac5871ec8
LialinMaxim/Toweya
/league_table.py
2,866
4.21875
4
""" The LeagueTable class tracks the score of each player in a league. After each game, the player records their score with the record_result function. The player's rank in the league is calculated using the following logic: * The player with the highest score is ranked first (rank 1). The player with the lowest score is ranked last. * If two players are tied on score, then the player who has played the fewest games is ranked higher. * If two players are tied on score and number of games played, then the player who was first in the list of players is ranked higher. Implement the player_rank function that returns the player at the given rank. For example: table = LeagueTable(['Mike', 'Chris', 'Arnold']) table.record_result('Mike', 2) table.record_result('Mike', 3) table.record_result('Arnold', 5) table.record_result('Chris', 5) print(table.player_rank(1)) All players have the same score.  However, Arnold and Chris have played fewer games than Mike, and as Chris is before Arnold in the list of players,  he is ranked first. Therefore, the code above should display "Chris". """ class LeagueTable: __empty_player = {'scores': 0, 'games': 0, 'last_game': None} __last_game = 0 def __init__(self, players: list): self.players = {p: dict(LeagueTable.__empty_player) for p in players} # dict() need to make a new objs def __srt__(self): return f'<LeagueTable obj: {self.players}>' def record_result(self, player: str, score: int): data_player = self.players.get(player) if data_player: data_player['scores'] += score data_player['games'] += 1 data_player['last_game'] = self.__get_last_game() def player_rank(self, rank=None): if rank and (rank > len(self.players) or rank < 0): return None ps = self.players # List of Tuples [(player name, scores, games, game order) ... ] table_rank = [(p, ps[p]['scores'], ps[p]['games'], ps[p]['last_game']) for p in ps] table_rank = sorted(table_rank, key=lambda p: (-p[1], p[2], p[3])) if rank: return table_rank[rank - 1] return table_rank def add_player(self): pass @classmethod def __get_last_game(cls, ): cls.__last_game += 1 return cls.__last_game if __name__ == '__main__': table = LeagueTable(['Mike', 'Chris', 'Arnold', 'Nike', 'Max']) table.record_result('Max', 2) table.record_result('Nike', 2) table.record_result('Mike', 2) table.record_result('Mike', 3) table.record_result('Arnold', 5) table.record_result('Chris', 5) print('The leader:', table.player_rank(1), ) from pprint import pprint print("\nRating of all players") pprint(table.player_rank()) print("\nPlayers") pprint(table.players)
true
91e32dc173b88a2cbdb441627633957137064961
kunaljha5/python_learn_101
/scripts/pyhton_list_operations_remove_pop_insert_append_sort.py
1,554
4.25
4
# https://www.hackerrank.com/challenges/python-lists/problem #Consider a list (list = []). You can perform the following commands: # insert i e: Insert integer at position. # print: Print the list. # remove e: Delete the first occurrence of integer. # append e: Insert integer at the end of the list. # sort: Sort the list. # pop: Pop the last element from the list. # reverse: Reverse the list. # #Initialize your list and read in the value of #followed by lines of commands where each command will be of the type # INPUT # 12 # insert 0 5 # insert 1 10 # insert 0 6 # print # remove 6 # append 9 # append 1 # sort # print # pop # reverse # prints listed above. Iterate through each command in order and perform the corresponding operation on your list. # OUTPUT # [6, 5, 10] # [1, 5, 9, 10] # [9, 5, 1] if __name__ == '__main__': N = int(input()) klist = [] for _ in range(N): action =input().split() # print(action) if action[0] == "insert": klist.insert(int(action[1]), int(action[2])) elif action[0] == "print": print(klist) elif action[0] == 'remove': klist.remove(int(action[1])) elif action[0] == 'append': klist.append(int(action[1])) elif action[0] == 'sort': klist.sort() elif action[0] == 'pop': klist.pop(-1) #print(klist) elif action[0] == 'reverse': klist.reverse() #print(klist) else: print("NA")
true
7d180da0bcf7f111d1d306897566ec129cd5ef0e
mebsahle/data-structure-and-algorithms
/sorting-algorithms/pancakeSort.py
882
4.125
4
# Python code of Pancake Sorting Algorithm def maxNum(arr, size): num = 0 for index in range(0, size+1): if arr[index] > arr[num] : num = index return num def flipArr(arr, index): begin = 0 while begin < index : temp = arr[begin] arr[begin] = arr[index] arr[index] = temp begin = begin + 1 index = index - 1 def pancakeSort(arr, size): for index in range(size-1, 0 ,-1): index1 = maxNum(arr, index) if index1 != index : flipArr(arr, index1) flipArr(arr, index) def main(): arr = [56, 47, 9, 46, 70, 9, 25, 36] size = len(arr) print("Unsorted Array: ", arr) pancakeSort(arr, size) print("Sorted Array: ", arr) if __name__ == "__main__": main()
true
0bb65cb9b5d9e6b30d70b2613cc224cb39c24d5e
balanalina/Formal-Languages-and-Compiler-Design
/Scanner/symbol_table/linked_list.py
1,973
4.21875
4
# class for a Node class Node: def __init__(self, val=None): self.val = val # holds the value of the node self.nextNode = None # holds the next node # implementation of a singly linked list class LinkedList: def __init__(self, head=None): self.headNode = head self.size = 0 # inserts a new node at the end of the list, returns the position on which it was inserted def insert(self, new_node): # make sure that the new node is not linked to other nodes new_node.nextNode = None self.size += 1 if self.headNode is None: self.headNode = new_node return 1 else: index = 1 current_node = self.headNode while current_node.nextNode is not None: current_node = current_node.nextNode index += 1 current_node.nextNode = new_node return index + 1 # searches for a value in the list and returns its position ( starting from 1), returns 0 if the value wasn't found def search(self, token): index = 1 current_node = self.headNode while current_node is not None: if current_node.val == token: return index else: current_node = current_node.nextNode index += 1 return 0 # returns true if the list is empty, false otherwise def is_empty(self): if self.headNode is None: return True return False # returns the number of nodes in the list def get_size(self): return self.size # returns the elements of the list as a string def pretty_print(self): current_node = self.headNode list_as_string = '' while current_node is not None: list_as_string = list_as_string + str(current_node.val) + " " current_node = current_node.nextNode return list_as_string
true
b63fd63b6a381fd59a4e1f0eb1fef04bdc7886d7
HurricaneSKC/Practice
/Ifelseproblem.py
535
4.28125
4
# Basic problem utilising if and elif statements # Take the users age input and determine what level of education the user should be in age = int(input("Enter your age: ")) # Handle under 5's if age < 5: print("Too young for school") # If the age is 5 Go to Kindergarten elif age == 5: print ("Go to Kindergarten") # Ages 6 through 17 goes to grades 1 through 12 elif age >= 6 and age<= 17: print ("go to grade {}".format(age-5)) # If age is greater then 17 say go to college elif age > 17: print ("Go to college")
true
56ff2ec0d608fe22ec4c4a8acf6d0f7789e61f91
HurricaneSKC/Practice
/FunctionEquation.py
614
4.1875
4
# Problem 10: Create an equation solver, functions # solve for x # x + 4 = 9 # x will always be the first value recieved and you will only deal with addition # Create a function that takes an input equation as a string to solve for x as above example def string_function(equation): # separate the function using the split operator x, add, num1, equals, num2 = equation.split() # convert the string into integers num1 = int(num1) num2 = int(num2) # solve equation x = num2 - num1 # return x return("x = {}" .format(x)) # Run function print(string_function(input("Input function: ")))
true
c3bd0685bcceacb2bee2ae1cc40bb24aff0cd71c
benjdj6/Hackerrank
/DataStructures/LinkedList/ReverseDoublyLinkedList.py
533
4.125
4
""" Reverse a doubly linked list head could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node return the head node of the updated list """ def Reverse(head): curr = head while curr: tmp = curr.prev curr.prev = curr.next curr.next = tmp if not curr.prev: break curr = curr.prev return curr
true
d2cb42f27bc8a03906e7f19d28a0bc75467053a3
Harshad06/Python_programs
/py-programs/args-kwargs.py
442
4.28125
4
# args/kwargs allows python functions to accept # arbitary/unspecified amount of arguments & keyword arguments. # Arguments def print_args(*args): print(f"These are my arguments : {args}") print_args([1,2,3],(20,30),{'key': 4}, 'abc') #--------------------------------------------------- # Keyword Arguments def print_kwargs(**kwargs): for key,value in kwargs.items(): print(key,value) print_kwargs(x="Hello", y="world")
true
1b504b774f87f662641549baee8860ea34fd6fa7
Harshad06/Python_programs
/useful-functions/accumulate.py
389
4.1875
4
""" accumulate() function > accumulate() belongs to “itertools” module > accumulate() returns a iterator containing the intermediate results. > The last number of the iterator returned is operation value of the list. """ import itertools import operator n = [1,2,3,5,10] print(list(itertools.accumulate(n, operator.add))) print(list(itertools.accumulate(n, operator.mul)))
true
e34ed0465a5fd22c905826be81eda95e1bba69d4
Harshad06/Python_programs
/PANDAS/joinsIdenticalData.py
740
4.21875
4
import pandas as pd df1 = pd.DataFrame([1,1], columns=['col_A'] ) #print("DataFrame #1: \n", df1) df2 = pd.DataFrame([1,1,1], columns=['col_A'] ) #print("DataFrame #2: \n", df2) df3 = pd.merge(df1, df2, on='col_A', how='inner') print("DataFrame after inner join: \n", df3) # Output: 2x3 --> 6 times it will be printed. [one-many operation] # It maybe any type of join ---> inner/outer/right/left ''' DataFrame after inner join: col_A 0 1 1 1 2 1 3 1 4 1 5 1 ''' # In case where any df data is "NaN" or "None", then value will be empty column- # df1 = pd.DataFrame([NaN, NaN], columns=['col_A'] ) ''' DataFrame after inner join: Empty DataFrame Columns: [col_A] Index: [] '''
true
6824c7f37caca3e464bfacb3da444a075808cf09
Harshad06/Python_programs
/string programs/longestString.py
454
4.59375
5
# Python3 code to demonstrate working of # Longest String in list # using loop # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks'] # printing original list print("The original list : " + str(test_list)) # Longest String in list using loop max_len = -1 for element in test_list: if len(element) > max_len: max_len = len(element) result = element # printing result print("Maximum length string is : " + result) print(len(result))
true
4360b4921820bf5519f4a23e9300e51cf5a667d8
Robbie-Wadud/-CS-4200-Project-3
/List Comprehension Finding Jones.py
483
4.21875
4
# -*- coding: utf-8 -*- """ Created on Wed Oct 7 20:22:17 2020 @author: Robbi """ print('Let\'s find the last name "Jones" within a list of tuples') #Creating the list (firstName, lastName) names = [('Robbie', 'Wadud'),('Matt', 'Jones'),('Lebron', 'James'),('Sarah', 'Jones'),('Serena', 'Williams'),('Ashley', 'Jones'),('Jessica', 'Jones')] #Creating the new Jones tuple jones = tuple(row for row in names if 'Jones' == row[1]) #Spacer print('') print(jones)
true
fdca2f44051851ad10fb9ac34b4edf16afe46cb7
sharmasourab93/JustPython
/tests/pytest/pytest_101/pytest_calculator_example/calculator.py
1,470
4.3125
4
""" Python: Pytest Pytest 101 Learning pytest with Examples Calculator Class's PyTest File test_calculator.py """ from numbers import Number from sys import exit class CalculatorError(Exception): """An Exception class for calculator.""" class Calculator: """A Terrible Calculator.""" def add(self, x, y): try: self._check_operand(x) self._check_operand(y) return x + y except TypeError: raise CalculatorError('Wrong') def subtract(self, x, y): return x - y def multiply(self, x, y): return x * y def _check_operand(self, operand): if not isinstance(operand, Number): raise CalculatorError(f'"{operand}" was not a number') if __name__ == '__main__': calculator = Calculator() operations = [ calculator.add, calculator.subtract, calculator.multiply ] print("Let's calculate!") while True: print("Pick an operation") for i in enumerate(operations, start=1): print(f"{i[0]}: {i[1].__name__}") print("q for quit") operation = input("Pick an operation:") if operation == 'q': exit() op = int(operation) a, b = input("What is a & b?").split() a, b = int(a), int(b) result = operations[op - 1] print(result(a, b))
true
1be1e0530d028553e0099989161dc24ebc3e1d41
sharmasourab93/JustPython
/decorators/decorator_example_4.py
612
4.3125
4
""" Python: Decorator Pattern In Python A Decorator Example 4 Using Decorators with Parameter Source: Geeksforgeeks.org """ def decorator_fun(func): print("Inside Decorator") def inner(*args): print("Inside inner Function") print("Decorated the Function") print("Printing args:", None if args is None else args) func() return inner @decorator_fun def func_to(): print("Inside actual function ") """ The code above is equivalent to: decorator_fun(func_to)() """ if __name__ == '__main__': func_to()
true
937df73a2265bef32d2ba32ca222c47c8db247b9
sharmasourab93/JustPython
/decorators/decorator_example_10.py
950
4.21875
4
""" Python: Decorator Pattern in Python A Decorator Example 10 Func tools & Wrappers Source: dev.to (https://dev.to/apcelent/python-decorator-tutorial-with-example-529f) """ from functools import wraps def wrapped_decorator(func): """Wrapped Decorator Docstring""" """ functools.wraps comes to our rescue in preventing the function from getting replaced. It takes the function used in the decorator and adds the functionality of copying over the function name, docstring, arguemnets etc. """ @wraps(func) def inner_function(*args, **kwargs): """Inner Function Docstring""" print(f"{func.__name__} was called") return func(*args, **kwargs) return inner_function @wrapped_decorator def foobar(x): """Foobar Docstring""" return x**2 if __name__ == '__main__': print(foobar.___name__) print(foobar.__doc__)
true
d5320085808347ab18124a1886072b5b9cfdbe0f
sharmasourab93/JustPython
/oop/oop_iter_vs_next.py
947
4.375
4
""" Python: iter Vs next in Python Class """ class PowTwo: """Class to implement an iterator of powers of two""" def __init__(self, max=0): self.max = max def __iter__(self): self.n = 0 return self def __next__(self): if self.n <= self.max: result = 2 ** self.n self.n += 1 return result else: raise StopIteration if __name__ == '__main__': numbers = PowTwo(3) i = iter(numbers) while True: try: print(next(i)) except StopIteration: print("Stop Iteration raised.") break # A simpler way to achieve this # would be to use a for loop as given below: print("Printing the same object value using for loop") for i in PowTwo(3): print(i) # The advantage of using iterators is that they save resources.
true
332349a979045aa438f80f293690460e34ba8e19
NicholasDowell/Matrix-Calculator
/Matrix.py
2,856
4.375
4
# This will be the fundamental matrix that is used for Matrix Operations # it stores a 2d grid of values # 11 # To DO: Restrict the methods so that they will not resize the matrix when they shouldnt # CONVENTION is [ROW][COLUMN] BE CAREFUL class Matrix: def __init__(self, rows, columns): self._data = [[0 for x in range(columns)] for y in range(rows)] self._height = rows self._width = columns # returns the matrix's height (number of rows) def get_height(self): return self._height def set_height(self, new_height): self._height = new_height # returns the matrix's width (number of columns) def get_width(self): return self._width # replaces a row in the matrix with the passed new row def replace_row(self, row_number, new_row): self._data[row_number] = [column for column in new_row] return # replaces a column in the matrix with the passed new column # Column_number represents the index of the column in the matrix that will be replaced. # column_index represents the current index in the new column (the value that is being placed into the matrix) # the passed column must have the same number of entries as the number of rows in the matrix def replace_column(self, column_number, new_column): # What do you do to replace a column? column_index = 0 for x in self._data: x[column_number] = new_column[column_index] column_index += 1 return # adds a new column on the rightmost side of the matrix. def add_column(self, new_column): self._width += 1 for x in range(self._height): self._data[x].append(new_column[x]) return # adds a new row to the bottom of the matrix def add_row(self, new_row): self._height += 1 self._data.append(new_row) # replaces a single number in the matrix def replace_value(self, new_value, row, column): self._data[row][column] = new_value def set_row(self, row_index, new_row): self._data[row_index] = new_row # returns a list containing all elements of one row of the matrix def get_row(self, row_index): return self._data[row_index] # returns a list containing all elements of one column of the matrix def get_column(self, column_index): column = [] for x in range(self._height): column.append(self._data[x][column_index]) return column # returns the value stored at one coordinate of the matrix def get_value(self, row, column): return self._data[row][column] def get_data(self): return self._data def set_width(self, new_width): self._width = new_width
true
971383f0baa1427023b3884f19d11c9d1f590055
AGKirby/InClassGit
/calc.py
1,014
4.1875
4
def calc(): # get user input try: num1 = int(input("Please enter the first number: ")) # get a number from the user num2 = int(input("Please enter the second number: ")) # get a number from the user except: # if the user did not enter an integer print("Invalid input: integer expected. Exiting program.") return result = 0 # calculate the results sum = num1 + num2 difference = num1 - num2 multiply = num1 * num2 try: divide = num1 / num2 except: #divide by zero error! divide = None #put the results in a list operation = ["Addition: ", "Subtraction: ", "Multiplication: ", "Division: "] resultsList = [sum, difference, multiply, divide] total = 0 # print the results and sum the list for i in range(len(resultsList)): print(operation[i] + str(resultsList[i])) total += resultsList[i] # print the sum of the list print("The sum of the list is " + str(total)) calc()
true
2a09f466b0eb647e577bf0835a4d55e4cbae1792
iambillal/inf1340_2015_asst1
/exercise2.py
1,212
4.46875
4
def name_that_shape(): """ For a given number of sides in a regular polygon, returns the shape name Inputs: user input 3-10 Expected Outputs: triangle, quadrilateral, pentagon, hexagon, heptagon, octagon, nonagon, decagon. Errors: 0,1,2, any number greater than 10 and any other string """ name_that_shape = raw_input("How many sides? ") if (name_that_shape == "3"): print("triangle") elif (name_that_shape == "4"): print("quadrilateral") elif (name_that_shape == "5"): print("pentagon") elif (name_that_shape == "6"): print("hexagon") elif (name_that_shape == "7"): print("heptagon") elif (name_that_shape == "8"): print("octagon") elif (name_that_shape == "9"): print("nonagon") elif (name_that_shape == "10"): print("decagon") else: print("Error") #name_that_shape() """ Test cases: How many sides? 3 triangle How many sides? 4 quadrilateral How many sides? 5 pentagon How many sides? 6 hexagon How many sides? 7 heptagon How many sides? 8 octagon How many sides? 9 nonagon How many sides? 10 decagon How many sides? 2 Error How many sides? 11 Error """
true
3674c62c670327d324a08a2bb13a6cc111b9b973
mischelay2001/WTCIS115
/PythonProjects/CIS115PythonProjects/Lab4Problem4.py
1,143
4.34375
4
__author__ = 'Michele' #How to test either a string or numeric #Initial age question and valid entry test age = int(input('Enter the child\'s age: ')) BooleanValidAge = age <= 200 #Is age entry valid while BooleanValidAge == False: print('Invalid entry. Please re-enter a valid age for the child.') age = int(input('Enter the child\'s age: ')) BooleanValidAge = age <= 200 #end valid age entry loop #Initial weight question and valid entry test weight = int(input('Enter the child\'s weight: ')) BooleanValidWeight = weight <= 1000 #Is the entry valid while BooleanValidWeight == False: print('Invalid entry. Please re-enter a valid weight for the child.') weight = int(input('Enter the child\'s weight: ')) BooleanValidWeight = weight <= 1000 #end valid weight entry loop BooleanAgeWeight = age < 8 or weight < 70 if BooleanAgeWeight == True: print('The child is required to ride in a booster seat according to North Carolina state law.') #There is extra sunlight else: print('The child is no longer required to ride in a booster seat according to North Carolina state law.')
true
2c330237b90116e7f55075a360f4290fe334d533
mischelay2001/WTCIS115
/PythonProjects/CIS115PythonProjects/Lab9Problem3.py
2,927
4.375
4
__author__ = 'Michele Johnson' # Write a program to play the rock-paper-scissors game. # A single player is playing against the computer. # In the main function, ask the user to choose rock, paper or scissors. # Then randomly pick a choice for the computer. # Pass the choices of the player and the computer to a find_winner function, # which determines and displays the outcome of the game. # Imported Modules import random def InfoToUser(): # Information to the user print('Welcome to Rock Paper Scissors!!!') print() print('This is a single player game against the computer.') print('The player will select a weapon from the list below.') print('The computer will then select a weapon.') print('The most powerful weapon WINS!!!') print() print(' Weapons List') print() print('Weapon Code Weapon') print('R Rock') print('P Paper') print('S Scissors') print() print() def GetPlayer1(): ##User enters input global Player1 Player1 = input('Player 1, please enter your weapon of choice from the list above: ') print() Player1 = Player1.upper() if Player1 != "R" and Player1 != "P" and Player1 != "S": print('The player did not enter a valid weapon from the list above.') else: if Player1 == "R": print("The Player's weapon of choice is Rock.") if Player1 == "P": print("The Player's weapon of choice is Paper.") if Player1 == "S": print("The Player's weapon of choice is Scissors.") def GetComputer(): # Randomly select either R, P, or S global Computer Computer = ["R", "P", "S"] Computer = random.choice(Computer) if Computer == "R": print("The Computer's weapon of choice is Rock.") elif Computer == "P": print("The Computer's weapon of choice is Paper.") elif Computer == "S": print("The Computer's weapon of choice is Scissors.") def DetermineWinner(Player1, Computer): if Player1 == Computer: print("It's a Tie!!!") elif Player1 == "R" and Computer == "S": print("Rock beats Scissors. Player 1 Wins!!!") elif Player1 == "S" and Computer == "P": print("Scissors beat Paper. Player 1 Wins!!!") elif Player1 == "P" and Computer == "R": print("Paper beats Rocks. Player 1 Wins!!!") elif Computer == "R" and Player1 == "S": print("Rock beats Scissors. The Computer Wins!!!") elif Computer == "S" and Player1 == "P": print("Scissors beat Paper. The Computer Wins!!!") else: print("Paper beats Rocks. The Computer Wins!!!") def main(): # Call Functions InfoToUser() GetPlayer1() GetComputer() print() DetermineWinner(Player1,Computer) main()
true
ba9e9753af0ce41ee2b220db1dc202677a8d73e7
mischelay2001/WTCIS115
/PythonProjects/CIS115PythonProjects/Lab5Problem1.py
1,570
4.25
4
__author__ = 'Michele' print('It is time to select your health plan for the year.') print('You will need to select from the table below:') print('') print('Health Plan Code Coverage Premium') print('E Employee Only $40') print('S Employee & Spouse $160') print('C Employee & Children $200') print('F Whole Family $250') print('') #User entry; 1st pass Choice = str(input('Please enter your health plan choice code from the table above: ')) Choice = Choice.upper() UserEntryValid = Choice == 'E' or Choice == 'S' or Choice == 'C' or Choice == 'F' #Test valid user entry while UserEntryValid == False: print('Your entry is invalid. Please select a valid code from the table above.') Choice = str(input('Please enter your health plan choice code from the table above: ')) Choice = Choice.upper() UserEntryValid = Choice == 'E' or Choice == 'S' or Choice == 'C' or Choice == 'F' #print(Choice) #print(UserEntryValid) #Begin program if Choice == 'E': print('You have selected the Employee Only health plan. Your premium is $40.') elif Choice == 'S': print('You have selected the Employee & Spouse health plan. Your premium is $160.') elif Choice == 'C': print('You have selected the Employee & Children health plan. Your premium is $200.') else: print('You have selected the Whole Family health plan. Your premium is $250.')
true
c3bec77407894ad0425a6c44b57733ff67beb1d7
EtienneBrJ/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/square.py
2,210
4.21875
4
#!/usr/bin/python3 """ Module Square """ from models.rectangle import Rectangle class Square(Rectangle): """ Square class inherits from Rectangle """ def __init__(self, size, x=0, y=0, id=None): """ Initialize an instance square from the class Rectangle. """ super().__init__(size, size, x, y, id) @property def size(self): """ Retrieves the size of the square. """ return self.width @size.setter def size(self, size): """ Sets the size of the Square. """ self.width = size self.height = size def update(self, *args, **kwargs): """ Public method: assigns an argument to each attribute """ if args and len(args) != 0: i = 0 for arg in args: if i == 0: if arg is None: self.__init__(self.size, self.x, self.y) else: self.id = arg elif i == 1: self.size = arg elif i == 2: self.x = arg elif i == 3: self.y = arg i += 1 elif kwargs and len(kwargs) != 0: for k, v in kwargs.items(): if k == 'id': if v is None: self.__init__(self.size, self.x, self.y) else: self.id = v elif k == 'size': self.width = v elif k == 'x': self.x = v elif k == 'y': self.y = v def to_dictionary(self): """ Public method: Returns the dictionary representation of a Rectangle """ return { "id": self.id, "size": self.size, "x": self.x, "y": self.y } def __str__(self): """ Return the print() and str() representation of the Square. """ return '[Square] ({}) {}/{} - {}'.format(self.id, self.x, self.y, self.width)
true
366b54996d3152ac7bee13e218f167480699acd8
rutujak24/crioTryout
/swapCase.py
707
4.4375
4
You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa. '''For Example: Www.HackerRank.com → wWW.hACKERrANK.COM Pythonist 2 → pYTHONIST 2 Input Format A single line containing a string . Constraints Output Format Print the modified string . Sample Input 0 HackerRank.com presents "Pythonist 2". Sample Output 0 hACKERrANK.COM PRESENTS "pYTHONIST 2". ''' def swap_case(s): a = "" for let in s: if let.isupper() == True: a+=(let.lower()) else: a+=(let.upper()) return a if __name__ == '__main__': s = input() result = swap_case(s) print(result)
true
b585acc6820a2a013d1dacf883fc961d618f78a3
mlarva/projecteuler
/Project1.py
743
4.1875
4
#If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. #Find the sum of all the multiples of 3 or 5 below 1000. def multipleFinder(min, max, *multiples): multiplesSet = set() if min >= max: print("Minimum is not smaller than maximum") return if min < 0 or max < 1: print("Cannot enter negative numbers") return for x in range(min,max): for y in multiples: if x % y == 0: multiplesSet.add(x) return multiplesSet def sumSet(setToSum): sum = 0 for x in setToSum: sum += x return sum multiplesSet = multipleFinder(1,1000, 3, 5) print(sumSet(multiplesSet))
true
b1953a6b8652ea8744c6ca9c935a7ec9d04ac4b6
MikeCullimore/project-euler
/project_euler_problem_0001.py
2,131
4.3125
4
""" project_euler_problem_0001.py Worked solution to problem 1 from Project Euler: https://projecteuler.net/problem=1 Problem title: Multiples of 3 and 5 Problem: if we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. Break the problem down further: 1) Find the largest multiple of 3: e.g. for 10, it is 9 = 3 x 3. 2) Likewise for 5: e.g. for 10, it is 5 = 1 x 5. 3) Factorise each sum e.g. 3 + 6 + 9 = 3*(1 + 2 + 3). 4) Use Gauss's trick for the sums 1 + 2 + ... + n = n*(n - 1)/2. 5) Multiply the sums by 3 or 5 as appropriate then add together. TODO: use example above as test case. TODO: input validation. """ import numpy as np def sum_gauss_trick(number): """Calculate the sum 1 + 2 + 3 + ... + number using Gauss's trick.""" sum = int(number*(number+1)/2) print('The sum of the natural numbers up to {} is {}.'.format(number, sum)) return sum def find_largest_multiplier(number, divisor): """Find the largest multiple of divisor below the given number. I.e. return largest multiplier such that multiplier*divisor < number. """ multiplier = int(np.floor((number - 1)/divisor)) print('The largest multiple of {} below {} is {} x {} = {}.'.format( divisor, number, multiplier, divisor, multiplier*divisor)) return multiplier def find_sum_multiples_3_or_5(upper): """Find the sum of all multiples of 3 or 5 below the given upper bound. E.g. if upper=10: multiples of 3 or 5 are 3, 5, 6 and 9; sum is 23. """ multiplier_3 = find_largest_multiplier(upper, 3) multiplier_5 = find_largest_multiplier(upper, 5) sum_3 = sum_gauss_trick(multiplier_3) sum_5 = sum_gauss_trick(multiplier_5) solution = 3*sum_3 + 5*sum_5 print('The sum of all multiples of 3 or 5 below {} is:'.format(upper)) print('3*{} + 5*{} = {}.'.format(upper, sum_3, sum_5, solution)) return solution def main(): # find_sum_multiples_3_or_5(10) find_sum_multiples_3_or_5(1000) if __name__ == '__main__': main()
true
256b3cf6e6919388e85f3e16fd025c4fc1c3b688
suspectpart/misc
/cellular_automaton/cellular_automaton.py
1,787
4.28125
4
#!/usr/bin/python ''' Implementation of the Elementary Cellular Automaton For an explanation of the Elementary Cellular Automaton, read here: http://mathworld.wolfram.com/ElementaryCellularAutomaton.html The script takes three parameters: - A generation zero as a starting pattern, e.g. 1 or 101 or 1110111 - A rule from 0 to 255 by which to evolve the generations - A maximum generation Sample usage: ./cellular_automaton.py 010 30 30 ./cellular_automaton.py 1110111 255 30 ''' import sys def rule(i): return "".join(reversed(list("{0:08b}".format(i)))) # 00111001 becomes [1,0,0,1,1,1,0,0], so that rule[1], rule[2].. work def cellular_automaton(generation_zero, rule, max_generations): generations = evolve_all(generation_zero, rule, max_generations) width = len(generations[-1]) for i, generation in enumerate(generations): padded_zeros = (width - len(generation)) / 2 padded_generation = "0" * padded_zeros + generation + "0" * padded_zeros print "".join(map(str, padded_generation)).replace("0", " ").replace("1", "X") def evolve_all(generation_zero, rule, max_generation): generations = [generation_zero] for i in range(max_generation): generations.append(evolve(generations[i], rule)) return generations def evolve(generation, rule): next_generation = "" generation = "00" + generation + "00" for i, cell in enumerate(generation[1:-1]): left_neighbour, right_neighbour = str(generation[i]), str(generation[i+2]) binary_value_of_cell = int(left_neighbour + cell + right_neighbour, 2) next_generation += rule[binary_value_of_cell] return next_generation if __name__ == "__main__": generation_zero = str(sys.argv[1]) r = rule(int(sys.argv[2])) max_generation = int(sys.argv[3]) cellular_automaton(generation_zero, r, max_generation)
true
86cf4cb652c0c62011f157bfd98259d7a092d005
anaruzz/holbertonschool-machine_learning
/math/0x06-multivariate_prob/0-mean_cov.py
564
4.125
4
#!/usr/bin/env python3 """ A function that calculates the mean and covariance of a data set """ import numpy as np def mean_cov(X): """ Returns mean of the data set and covariance matrix of the data set """ if type(X) is not np.ndarray or len(X.shape) != 2: raise TypeError("X must be a 2D numpy.ndarray") if X.shape[0] < 2: raise ValueError("X must contain multiple data points") n, d = X.shape mean = X.mean(axis=0, keepdims=True) xi = X - mean cov = np.matmul(xi.T, xi) / (n - 1) return mean, cov
true
3a904d372a32c4d10dbf04e2e0f8653bf6c0d995
anaruzz/holbertonschool-machine_learning
/math/0x00-linear_algebra/3-flip_me_over.py
398
4.15625
4
#!/usr/bin/env python3 """ Script that returns the transpose of a 2D matrix """ def matrix_transpose(matrix): """ function that returns the transpose of a 2D matrix, """ i = 0 new = [[0 for i in range(len(matrix))] for j in range(len(matrix[i]))] for i in range(len(matrix)): for j in range(len(matrix[i])): new[j][i] = matrix[i][j] return new
true
5ebd7f954d1ebf345d87d7cb8afa11bfbb9846a8
whatarthurcodes/Swedish-Test
/swedishtest.py
1,843
4.125
4
import sys import random import csv def swedishtest(): word_bank = select_module() lang = choose_lang() questions(word_bank, lang) def select_module(): file_found = False while file_found is False: try: module_choice = raw_input('Enter the file name. ex. module1.csv \n') module = open(module_choice) csv_f = csv.reader(module) file_found = True except Exception: print ("Cannot Find file ") + module_choice + ("\n") word_bank =[] for row in csv_f: word_bank.append(row) return word_bank def choose_lang(): lang = False while lang is False: lang = input('For Swedish to English enter 0 For English to Swedish enter 1 \n') if lang == 0 or lang == 1: return lang else: print ('Please enter 0 for English to Swedish or 1 for Swedish to English \n') lang = False def questions(word_bank, lang): answer = 'answer' quit = False number_of_words = len(word_bank) print number_of_words correct_answers = 0 number_of_questions =0 print ('\nTo quit, enter q or quit') if lang == 0: print ('The word is given in Swedish, please type in the English word \n') lang_answer = 1 if lang == 1: print ('The word is given in English, please type in the Swedish word \n') lang_answer = 0 while quit is False: rand = random.randint(0, number_of_words-1) question = word_bank[rand] answer = raw_input(question[lang] + '\n') if answer == 'q' or answer == 'quit': quit = True print "You got " + str(correct_answers) + " correct out of " + str(number_of_questions) elif question[lang_answer] == answer: print "Correct! \n" correct_answers = correct_answers + 1 number_of_questions = number_of_questions + 1 else: print "Wrong! The answer is: " + question[lang_answer] + "\n" number_of_questions = number_of_questions + 1 swedishtest()
true
28a5ceae1d0b29e00c0a7e657c5ea9f3ce3ab08f
mlawan/lpthw
/ex30/ex30.py
518
4.15625
4
people = 30 cars = 40 trucks = 40 if cars > people or trucks < cars: print("We should take the cars") elif cars< people: print("We should not take the cars") else: print(" We cant decide.") if trucks > cars and cars == trucks: print("Thats too much of trucks") elif trucks <cars: print("Maybe we could take the trucks") else: print(" We still can't decide") if cars == trucks and cars > people: print("Alrifht, lets jsut take the trucks") else: print("fine, lets stay home then.")
true
0a3c8d459722962a4cf49d524456b76d2069fc9a
python4kidsproblems/Operators
/comparison_operators.py
1,266
4.28125
4
# Comarison Operators Practice Problems # How to use this file: # Copy this to your python (.py) file, and write your code in the given space ################################### Q1 ################################### # Write a program that asks the user, # # "Are you older than 15? Answer True or Flase." # # Convert the user response to Bool and then check its type using the # # type function. # # See what happpens if the user does not repond with True or False, # # and replies with Yes or No instead. Will this program still work? # ########################################################################## # your code goes here ################################### Q2 ################################### # Write a Truth Detector program that gives the User two numbers to # # compare and tell which one is bigger. If the User answers correctly # # print True and if not print False. # # Hint: Notice that print(1==1) prints True and print(4<3) prints False. # ########################################################################## # your code goes here
true
fc09bc969303a4bddf367fc3748ffb53e20e7ba0
rsurpur20/ComputerScienceHonors
/Classwork/convertor.py
1,114
4.25
4
# convert dollars to other currencies import math import random # # dollars=float(input("Dollars to convert: \n $")) #gets the input of how many dollars, the user wants to convert # # yen=dollars*111.47 #the conversion # euro=dollars*.86 # peso=dollars*37.9 # yuan=dollars*6.87 # # print("$"+str(dollars) + " in yen is", str(yen)) #prints the result. a comma is # #the same as a plus in string cancatination. a comma will add a space, where a plus lets you munipulate the spacing # print("$"+str(dollars) + " in euros is", str(euro)) #prints the result. a comma is # print("$"+str(dollars) + " in pesos is", str(peso)) #prints the result. a comma is # print("$"+str(dollars) + " in yuan is", str(yuan)) #prints the result. a comma is # print(random.randrange(0,101,10)) #starts, end, step. so it starts and includes zero, # #ends with and doesn't include 101, and it is a multiple of 10 #this code is to get an input as theta and do the following: sin^2(theta)+cos^2(theta) theta=math.radians(float(input("pick a random number \n"))) # print(theta) print(float((math.sin(theta)**2)+(math.cos(theta)**2)))
true
111c5346ca6f32e8f25608a1d2cf2ea143056ed6
rsurpur20/ComputerScienceHonors
/minesweeper/minesweepergame.py
2,394
4.25
4
# https://snakify.org/en/lessons/two_dimensional_lists_arrays/ #Daniel helped me,and I understand import random widthinput=int(input("width?\n"))+2 #number or colomns heightinput=int(input("height ?\n"))+2 #number of rows bombsinput=int(input("number of bombs?\n"))#number of bombs width=[] height=[] # j=[] # # for x in range(len(j)): #len(j) gives you the number of rows # # print(*j[x]) #putting a * right before a list gets rid of synatx # # width=[0]*widthinput # height=[0]*heightinput # # print(width) # # print(height) # list=[width[]height[]] # for x in range(0, len(height)): # # print(width[x]) # # print()#print on new line # for x in range(0,len(width)): # print(width[x], end=' ') #prints on same line # print()#print on new line # index=[] # for every row in the height, make an empty row: for x in range(heightinput): #height +2 gives you number of rows width=[0]*(widthinput) index.append(width) # print(index) # print(*index[x]) area=heightinput*widthinput # for x in range(0,bombsinput): # position=random.randint(0,area) # print(position) i=1 while i<=bombsinput: x=random.randint(1,widthinput-2) y=random.randint(1,heightinput-2) index[y][x]="*" # print(y,x) i+=1 #adds one to the area around the bomb z=0 # print(bombsinput) # for z in range(bombsinput): if index[y+1][x]!="*": #right index[y+1][x]+=1 if index[y-1][x]!="*": #left index[y-1][x]+=1 if index[y][x+1]!="*":#down index[y][x+1]+=1 if index[y][x-1]!="*":#up index[y][x-1]+=1 #diagonals if index[y-1][x+1]!="*": index[y-1][x+1]+=1 if index[y+1][x-1]!="*": index[y+1][x-1]+=1 if index[y-1][x-1]!="*": index[y-1][x-1]+=1 if index[y+1][x+1]!="*": index[y+1][x+1]+=1 # index[y][x+2]=+1 # index[y][x-2]=+1 z+=1 for x in range(1,heightinput-1): #every row except the buffer rows for y in range(1,widthinput-1): #for every colomn except the buffer colomns # print(*index[y]) print(index[x][y], end=' ') print() # height.append(width) # j.append(width) #list j will have ten zeros # print(height) # print(width[x]) # gives you a ten by ten list of 100 zeros # # for i in range(height): # for j in range(width): # print(width[i][j], end=' ') # print()
true
bac4234eb3635e084517cab020e5b8761e77967f
joelstanner/codeeval
/python_solutions/HAPPY_NUMBERS/happy_numbers.py
1,485
4.3125
4
""" A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers. INPUT SAMPLE: The first argument is the pathname to a file which contains test data, one test case per line. Each line contains a positive integer. E.g. 7 22 OUTPUT SAMPLE: If the number is a happy number, print out 1. If not, print out 0. E.g 1 1 0 For the curious, here's why 7 is a happy number: 7->49->97->130->10->1. Here's why 22 is NOT a happy number: 22->8->64->52->29->85->89->145->42->20->4->16->37->58->89 ... """ import sys def parse_input(input_file): with open(input_file, mode="r") as file: for line in file: happiness(line.rstrip()) def happiness(num): """Return 1 if number is happy, 0 if not num is a string and is converted into single digit integers """ happys = [int(j) for j in num] last = 0 for digit in happys: last += digit ** 2 if last == 1: print(1) elif last == 89: # all unhappy numbers become 89 at some point print(0) return else: happiness(str(last)) if __name__ == '__main__': INPUT_FILE = sys.argv[1] parse_input(INPUT_FILE)
true
9668ba9aad876675efe26dc644d08c3f8cb049a1
joelstanner/codeeval
/python_solutions/NUMBER_PAIRS/NUMBER_PAIRS.py
2,563
4.3125
4
""" You are given a sorted array of positive integers and a number 'X'. Print out all pairs of numbers whose sum is equal to X. Print out only unique pairs and the pairs should be in ascending order INPUT SAMPLE: Your program should accept as its first argument a filename. This file will contain a comma separated list of sorted numbers and then the sum 'X', separated by semicolon. Ignore all empty lines. If no pair exists, print the string NULL e.g. 1,2,3,4,6;5 2,4,5,6,9,11,15;20 1,2,3,4;50 OUTPUT SAMPLE: Print out the pairs of numbers that equal to the sum X. The pairs should themselves be printed in sorted order i.e the first number of each pair should be in ascending order. E.g. 1,4;2,3 5,15;9,11 NULL """ from sys import argv def number_pairs(num_list, minuend): """Return a list of number pairs that sum to the minuend. This is accomplished by iterating a list of integers and subtracting the number from the minuend. If the difference from that operation is also in our list of numbers, then we have a pair. Remove the second number (diff) from the list so we don't duplicate. Args: num_list: A sorted list of integers. minuend: The number we are looking to find sums of in our num_list. Returns: A list of tuples that sum to the minuend. """ pairs = [] for subtrahend in num_list: diff = minuend - subtrahend if diff in num_list: pairs.append((subtrahend, diff)) num_list.remove(diff) return pairs def parse_line(line): """Returns a list of ints and a minuend integer. The line needs to be in the form '1,2,3,...;5' as described in the module docstring """ num_list, minuend = line.split(';') num_list = [int(num) for num in num_list.split(',')] minuend = int(minuend) return num_list, minuend def parse_output(output_list): """Return a string formed like so: '1,4;2,3'""" output = [] for pair in output_list: temp = ",".join([str(num) for num in pair]) output.append(temp) return ";".join(output) def main(input_file): """Iterate the lines of a text file and print the results.""" with open(input_file, 'r') as file: for line in file: num_list, minuend = parse_line(line) pairs = number_pairs(num_list, minuend) out_line = parse_output(pairs) if not out_line == '': print(out_line) else: print('NULL') if __name__ == '__main__': main(argv[1])
true
a73717e0842d17d44f275aeafba71950e88e5b55
joelstanner/codeeval
/python_solutions/PENULTIMATE_WORD/PENULTIMATE_WORD.py
583
4.4375
4
""" Write a program which finds the next-to-last word in a string. INPUT SAMPLE: Your program should accept as its first argument a path to a filename. Input example is the following: some line with text another line Each line has more than one word. OUTPUT SAMPLE: Print the next-to-last word in the following way: with another """ from sys import argv def penultimate(input_file): with open(input_file, 'r') as file: for line in file: words = line.rstrip().split() print(words[-2]) if __name__ == '__main__': penultimate(argv[1])
true
0dc79dcc5c3b026ad10e1328ed2ef84a12514fb1
joelstanner/codeeval
/python_solutions/UNIQUE_ELEMENTS/unique_elements.py
809
4.4375
4
""" You are given a sorted list of numbers with duplicates. Print out the sorted list with duplicates removed. INPUT SAMPLE: File containing a list of sorted integers, comma delimited, one per line. E.g. 1,1,1,2,2,3,3,4,4 2,3,4,5,5 OUTPUT SAMPLE: Print out the sorted list with duplicates removed, one per line. E.g. 1,2,3,4 2,3,4,5 """ from sys import argv INPUT_FILE = argv[1] def unique_elements(input_file): """Print out the sorted list with duplicates removed, one per line""" with open(input_file, mode="r") as file: for line in file: # Create a new, unique list that is a set from orig list. u_list = sorted(list(set([int(x) for x in line.split(',')]))) print(*u_list, sep=",") if __name__ == '__main__': unique_elements(INPUT_FILE)
true
3b9c14de993878342e89d659c501c39b27078042
joelstanner/codeeval
/python_solutions/SIMPLE_SORTING/SIMPLE_SORTING.py
873
4.53125
5
""" Write a program which sorts numbers. INPUT SAMPLE: Your program should accept as its first argument a path to a filename. Input example is the following 70.920 -38.797 14.354 99.323 90.374 7.581 -37.507 -3.263 40.079 27.999 65.213 -55.552 OUTPUT SAMPLE: Print sorted numbers in the following way. Please note, that you need to print the numbers till the 3rd digit after the dot including trailing zeros. -38.797 7.581 14.354 70.920 90.374 99.323 -55.552 -37.507 -3.263 27.999 40.079 65.213 """ from sys import argv def sorter(input_file): with open(input_file, 'r') as file: for line in file: line = line.rstrip() sort_list = sorted([float(x) for x in line.split()]) for item in sort_list: print("{:.3f}".format(item), end=" ") print() if __name__ == '__main__': sorter(argv[1])
true
66a16d29f30d44d93ca5f219d6d51752633364e2
jDavidZapata/Algorithms
/AlgorithmsInPython/stack.py
329
4.125
4
# Stack implementation in Python stack = [] # Add elements into stack stack.append('a') stack.append('b') stack.append('c') print('Stack') print(stack) # Popping elements from stack print('\nAfter popping an element from the stack:') print(stack.pop()) print(stack) print('\nStack after elements are poped:') print(stack)
true
b6a6ac69c4730e0f7ee4e2bf889271812d5f168d
ogrudko/leetcode_problems
/easy/count_prime.py
804
4.15625
4
''' Problem: Count the number of prime numbers less than a non-negative number, n. Example 1: Input: n = 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. Example 2: Input: n = 0 Output: 0 Example 3: Input: n = 1 Output: 0 Constraints: 0 <= n <= 5000000 ''' # Solution class Solution: def count_primes(self, n: int) -> int: is_prime = True primes_list = [] if n < 2: return len(primes_list) elif n == 2: return 1 for i in range (2, n + 1, 1): for j in range (1, i, 1): if i % j == 0 and j != 1: is_prime = False if is_prime == True: primes_list.append(i) is_prime = True return len(primes_list)
true
a7745492208033ac49f8d0285ff7c141eed19a70
gatherworkshops/programming
/_courses/tkinter2/assets/zip/pythonchallenges-solutions/eventsdemo.py
2,908
4.21875
4
import tkinter import random FRUIT_OPTIONS = ["Orange", "Apple", "Banana", "Pear", "Jalapeno"] window = tkinter.Tk() # prints "hello" in the developer console def say_hello(event): name = name_entry.get() if len(name) > 0: print("Hello, " + name + "!") else: print("Hello random stranger!") # adds a random fruit to the fruit list, # only allowing a maximum of 8 fruit def add_fruit(event): if fruit_list.size() >= 8: return random_index = random.randrange(0, len(FRUIT_OPTIONS)) random_fruit = FRUIT_OPTIONS[random_index] fruit_list.insert(tkinter.END, random_fruit) # deletes the selected fruit from the list, # if one is selected def delete_fruit(event): selected_fruit = fruit_list.curselection() fruit_list.delete(selected_fruit) # generates a smoothie recipe from the fruit # selection made by the user def generate_recipe(event): fruit_counter = {} # count the number of each type of fruit # using a dictionary chosen_fruit = fruit_list.get(0, tkinter.END) for fruit in chosen_fruit: if fruit in fruit_counter: fruit_counter[fruit] += 1 else : fruit_counter[fruit] = 1 # generate recipe text using the dictionary recipe_text = "Recipe:\n\n" for fruit_type in fruit_counter: recipe_line = str(fruit_counter[fruit_type]) + " x " + fruit_type + "\n" recipe_text += recipe_line # delete the old recipe if there was one recipe_display.delete("1.0", tkinter.END) # display the new recipe recipe_display.insert(tkinter.END, recipe_text) # name prompt name_prompt = tkinter.Label(window) name_prompt.config(text="What is your name?") name_prompt.grid(row=0, column=0) # name input name_entry = tkinter.Entry(window) name_entry.bind("<Return>", say_hello) name_entry.grid(row=1, column=0) # hello button hello_button = tkinter.Button(window) hello_button.config(text="Click Me!") hello_button.bind("<Button>", say_hello) hello_button.grid(row=2, column=0) # fruit list fruit_list = tkinter.Listbox(window) fruit_list.grid(row=0, column=1, columnspan=2, sticky="nesw") # add fruit button add_fruit_button = tkinter.Button(window) add_fruit_button.config(text="Add Random Fruit") add_fruit_button.bind("<Button>", add_fruit) add_fruit_button.grid(row=1, column=1, sticky="ew") # delete fruit button delete_fruit_button = tkinter.Button(window) delete_fruit_button.config(text="Delete Fruit") delete_fruit_button.bind("<Button>", delete_fruit) delete_fruit_button.grid(row=1, column=2, sticky="ew") # recipe button create_recipe_button = tkinter.Button(window) create_recipe_button.config(text="Generate Recipe") create_recipe_button.bind("<Button>", generate_recipe) create_recipe_button.grid(row=1, column=3) # recipe display recipe_display = tkinter.Text(window) recipe_display.grid(row=0, column=3) window.mainloop()
true
d6eb76e86a7c77ce7f875289e87562990ed2bd58
karramsos/CipherPython
/caesarCipher.py
1,799
4.46875
4
#!/usr/bin/env python3 # The Caesar Cipher # Note that first you will need to download the pyperclip.py module and # place this file in the same directory (that is, folder) as the caesarCipher.py file. # http://inventwithpython.com/hacking (BSD Licensed) # Sukhvinder Singh | karramsos@gmail.com | @karramsos import pyperclip # the string to be encrypted/decrypted message = 'This is my secret message.' # the encryption/decryption key key = 13 # tells the program to encrypt or decrypt mode = 'encrypt' # set to 'encrypt' or 'decrypt' # every possible symbol that can be encrypted LETTERS = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~' # stores the encrypted/decrypted form of the message translated = '' # capitalize the string in message #message = message.upper() # run the encryption/decryption code on each symbol in the message string for symbol in message: if symbol in LETTERS: # get the encrypted/decrypted number for this symbol num = LETTERS.find(symbol) # get the numbor of the symbol if mode == 'encrypt': num += key elif mode == 'decrypt': num -= key # handle the wrap-around if num is larger than the length of # LETTERS or less than 0 if num >= len(LETTERS): num -= len(LETTERS) elif num < 0: num += len(LETTERS) # add encrypted /decrypted number's symbol at the end of translated translated = translated + LETTERS[num] else: # just add the symbol without encrypting/decrypting translated += symbol # print the encrypted/decrypted string to the screen print(translated) # copy the encrypted/decrypted string to the clipboard pyperclip.copy(translated)
true
2ea42b749ee8320df5a7eda34a07e3bc683101b3
40168316/PythonTicketApplication
/TicketApplication.py
2,257
4.375
4
TICKET_PRICE = 10 SERVICE_CHARGE = 2 tickets_remaining = 100 # Create a function that calculates the cost of tickets def calculate_cost_of_tickets(num_tickets): # Add the service charge return (num_tickets * TICKET_PRICE) + SERVICE_CHARGE # Run this code continuously until we run out of tickets while tickets_remaining >= 1: # Output how many tickets are remaining using the tickets_remaining variable print("There are {} tickets remaining.".format(tickets_remaining)) # Gather the user's name and assign it to a new variable name = input("What is your name? ") # Prompt the user by name and ask how many tickets they would like num_tickets = input("How many tickets would you like, {}? ".format(name)) # ADD A TRY EXCEPT AS USER CAN ENTER A STRING HERE try: # Convert num_tickets to int num_tickets = int(num_tickets) # Raise a value error if the request is for more tickets than available if num_tickets > tickets_remaining: raise ValueError("There are only {} tickets remaining".format(tickets_remaining)) except ValueError as err: # Deal with error print("Issue with input. {}. Please try again!".format(err)) else: # Calculate the price (number of tickets multiplied by the price) and assign it to a variable amount_due = calculate_cost_of_tickets(num_tickets) # Output the price to the screen print("The total due is ${}".format(amount_due)) # Prompt user if they want to proceed. Y/N? should_proceed = input("Do you want to proceed? Y/N ") # If they want to proceed if should_proceed.lower() == "y": # print out to the screen "SOLD!" to confirm purchase # TODO: Gather credit card information and process it. print("SOLD!") # and then decrement the tickets remaining by the number of tickets purchased tickets_remaining -= num_tickets # Otherwise.... else: # Thank them by name print("Thank you anyways, {}!".format(name)) # Notify user that the tickets are sold out print("Sorry the tickets are all sold out!!! :(")
true
b49ea3e976180eecf26802fe0a6a198ce6e914fb
aabidshaikh86/Python
/Day3 B32.py
1,119
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[2]: fullname = 'abid sheikh' print(fullname ) # In[ ]: # Req: correct the name format above by using the string method. # In[3]: print(fullname.title()) # Titlecase ---> first Letter of the word will be capital # In[ ]: # In[ ]: # Req: I want all the name to be in capital. # In[4]: print(fullname.upper()) ### Uppercase # In[ ]: # In[ ]: # Req: I want all the name to be in smallcase.. # In[5]: print(fullname.lower()) ### Lowercase # In[ ]: # In[ ]: *** Introduction to f strings in python.*** # In[ ]: # In[ ]: firstname = 'abid' lastname = 'sheikh' # In[ ]: # Req: get me a fullname. # In[ ]: General syntax of a f string f" custom string {placeholder1} {placeholder2} ......{nplaceholder}" ----> refercing point of the above variable created. # In[16]: x = f"{firstname} {lastname}" print(x) # In[17]: print(x.title()) # In[ ]: # In[ ]: req : i want to appreciate Abid for sending the practice file URL daily on time. # In[18]: print(f"keep up the goodwork, {x.title()}") # In[ ]:
true
626aea1dbd007cc33e1c79e6fa7a35848f313cc5
aabidshaikh86/Python
/Day7 B32.py
1,888
4.375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: list Continuation : # In[ ]: # In[1]: cars = ['benz','toyota','maruti','audi','bnw'] # In[ ]: ## Organising the list datatype # In[ ]: req : i want to organise the data in the alphabetical order !!! A to Z # In[ ]: Two different approcahes : 1. Temp approch -------> sorted 2. Permanent approch -------> sort # In[ ]: ## In the sorted (temp) approach we will be having the orginal order of the list!! ## In the sort (permanenet) approch we will not be having the original order back!! # In[8]: print(sorted(cars)) ## Temp approach # In[10]: print(cars) ## Original Approch # In[11]: cars.sort() ## permanent approach print(cars) # In[12]: print(cars) # In[ ]: *** Interview : what is the diff bet sorted and Sort?? *** # In[ ]: # In[ ]: get_ipython().set_next_input('Req: i want to print the list in the reverse order');get_ipython().run_line_magic('pinfo', 'order') # In[13]: print(cars) # In[14]: cars.reverse() ## Reverse Order print(cars) # In[ ]: ## How do you count the no of Elements in a list?? ## # In[15]: len(cars) ## Count method # In[ ]: ## introduction to slicing of the lists:: # In[17]: students = ['mohini','rachana','uma','swapna','vidhya','naveena'] # In[18]: print(students) # In[19]: type(students) # In[ ]: ## General syntex of slicing: -------FORMULA----------- var[startvalue:stopvalue:step count] ------> this is the formula. Note : Last value is always exclusive..!! # In[28]: print(students[0:1]) # In[29]: print(students[0:2]) # In[36]: print(students[4:6]) ## Last value is always exclusive and it will not be considered!! # In[38]: print(students[0:6:2]) ## Alternare name of the students..!! # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]:
true
8d778b4cf8872d0c928d6a55933fcdfa86d0847d
Jasmine582/guess_number
/main.py
468
4.125
4
import random random_number = random.randrange(100) correct_guess = False while not correct_guess: user_input = input("Guess a number between 0 and 100:") try: number = int(user_input) if number == random_number: correct_guess = True elif number > random_number: print("You guessed too high") elif number < random_number: print("You guessed too low") except: print("Not a number!") print("You guessed the right number!")
true
f8390e1a672802dd30b581fb71a50b1a2d3fbcd5
kristopher-merolla/Dojo-Week-3
/python_stack/python_fundamentals/type_list.py
1,418
4.46875
4
# Write a program that takes a list and prints a message for each element in the list, based on that element's data type. # Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the array contains. If it contains only one type, print that type, otherwise, print 'mixed'. # Here are a couple of test cases (l,m,n below) # #input l = ['magical unicorns',19,'hello',98.98,'world'] # #output # "The array you entered is of mixed type" # "String: magical unicorns hello world" # "Sum: 117.98" # # input m = [2,3,1,7,4,12] # #output # "The array you entered is of integer type" # "Sum: 29" # # input n = ['magical','unicorns'] # #output # "The array you entered is of string type" # "String: magical unicorns" # ------------------------------------------------- k = l mySum = 0 myStr = "" for i in range (0,len(k)): if (type(k[i]) is str): myStr += k[i] myStr += " " elif (type(k[i]) is int): mySum += k[i] elif (type(k[i]) is float): mySum += k[i] if (myStr!="" and mySum!=0): print "The array you entered is of mixed type" print myStr print mySum elif (myStr=="" and mySum!=0): print "The array is of integer type" print mySum else: print "The array is of string type" print myStr
true
3caf05cc3eb9cee2e9e0d7ad2ef9882a32a8668d
niteeshmittal/Training
/python/basic/Directory.py
1,490
4.125
4
#Directory try: fo = open("phonenum.txt") #print("phonenum.txt exists. We are good to go.") except IOError as e: if (e.args[1] == "No such file or directory"): #print("File doesn't exists. Creating a phonenum.txt.") fo = open("phonenum.txt", "w") finally: fo.close() opt = input("1 for store and 2 for read: ") print(f"You chose {opt}") #if (opt == '1'): # name = input("Enter you name: ") # print(f"You entered {name}") # fo = open("phonenum.txt", "a") # #fo.write("\n" + name) # fo.write(name + "\n") # fo.close() #elif (opt == '2'): # print("You chose to read and display the file.") # fo = open("phonenum.txt") # str = fo.read() # print(str) # fo.close() #else: # print("Functionality under development.") namelist = [] if (opt == '1'): while (opt == '1'): name = input("Enter your name: "); print(f"You entered {name}"); namelist.append(name); opt = input("1 to coninue saving more names\n2 to display the current list\n3 to display file content: "); print(namelist); fo = open("phonenum.txt", "a"); for i in namelist: fo.write(i + "\n"); fo.close(); if (opt == '2'): print();print("You chose to display the current list of names given by user.\nCurrent list: {0}".format(namelist)); opt = input("3 to display file content: "); if (opt == '3'): print();print("You chose to read and display the file."); fo = open("phonenum.txt"); str = fo.readlines(); #print(str); for x in str: print(x.strip()); fo.close(); else: print("You chose to exit.");
true
3dde22d71aab3f343ef9f0aa6707e7b6a9220a61
rjcmarkelz/python_the_hard_way
/functional_python/chp1_1.py
1,619
4.15625
4
# chapter 1 of functional python book def sum(seq): if len(seq) == 0: return 0 return seq[0] + sum(seq[1:]) sum([1, 2, 3, 4, 1]) sum([1]) # recursive def until(n, filter_func, v): if v == n: return [] if filter_func(v): return [v] + until(n, filter_func, v+1) else: return until(n, filter_func, v+1) # now use lambda for one line functions mult_3_5 = lambda x: x % 3 == 0 or x % 5 == 0 mult_3_5(3) mult_3_5(5) # combine until(10, lambda x: x % 3 == 0 or x % 5 == 0, 0) # nested generator expression sum(n for n in range(1, 10) if n % 3 == 0 or n % 5 == 0) # object creation # plus operator is both commutative and associative 1 + 2 + 3 + 4 # can also be # fold values left to right # create intermediate values 3 and 6 ((1 + 2) + 3) + 4 # fold values right to left # intermediate objects 7 and 9 are created 1 + (2 + (3 + 4)) # slight advantage working left to right import timeit timeit.timeit("((([] + [1]) + [2]) + [3]) + [4]") timeit.timeit("[] + ([1] + ([2] + ([3] + [4])))") #### # Important functional design that + has no hidden side effects #### # stack of turtles # CPUs are generally procedural not functional or OO # three main layers of abstraction # 1) applications will be functions all the way down until # we hit the objects # 2) Underlying Python runtime environment that supports functional # programming is objects- all the way down- until we hit turtles # 3) The libraries that support python are a turtle on which python stands # # The OS and hardware form thier own stack of turtles # Nearing the end.
true