blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
5ceff881fad153efd3b9ce95dfd6b77c7b9f55fa
cheung1/python
/help.py
441
4.15625
4
#1.write the triangle print code # notice: when you just define, it cannot execute #2.define a function def printTriangle(): 'this is the help document ' print ' * ' print ' * * ' print '* * *' #3.invoke the function #notice:only can via the invoke to use the function # invoke the function: write the function name,then add a pair of bracket printTriangle() #notice:define only once,but can invoke infite times printTriangle()
true
520ac63216a371940b7c98b2a152bd67b73c1bff
abhisjai/python-snippets
/Exercise Files/Ch2/functions_start.py
1,780
4.78125
5
# # Example file for working with functions # # define a basic function def func1(): print("I am a function") # func1() # Braces means to execute a function # value on console was any print command inside the function # If there was any return value, it was not assigned to any variable # print(func1()) # Execute a function and print its value # While executing it also prints any Print statements to console # It also prints return value = None as there was no return value from inside the function # print(func1) # Function does not executes at all # It only prints function defination which means functions are objects that can be passed around # function that takes arguments def func2 (argv1, argv2): print(argv1, " ", argv2) # func2(10, 20) # print(func2(10, 20)) # function that returns a value def cube(x): return x*x*x # cube(3) # This does not print any value. Return value is not assigned to any variable. # print(cube(3)) # function with default value for an argument def power(num, x=1): result = 1 for i in range(x): #Multiple number by itself for result = result * num return result # print(power(2)) # # In case of missing parameters, function used default assigned value of x # print(power(2, 3)) # # Even if x was assigned a value, you can override it when calling a function # print(power(x=5, num=2)) # # order of arguments does not matter if you absolutely define them #function with variable number of arguments def multi_add(*argv): result = 0 for x in argv: result = result + x return result print(multi_add(5, 10, 25, 5)) print(multi_add(1, 2, 3, 4, 5)) # You can combine variable argument list with formal parameters # Keep in mind, varibale argument list is last parameter
true
4239a7ae04f3adc3b0546b9e18d03d7dbd90946c
abhisjai/python-snippets
/Misc Code/python-tuples.py
1,180
4.28125
4
# Task # # Given an integer n and n space-separated integers as input, create a tuple t, of those n integers. Then compute and print the result of # Note: hash() is one of the functions in the __builtins__ module, so it need not be imported. # Input Format # The first line contains an integer, n, denoting the number of elements in the tuple. # The second line contains space-separated integers describing the elements in tuple . # Source: https://www.hackerrank.com/challenges/python-tuples/problem n = int(input()) # Map: map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) # Syntax: map(fun, iter) # Parameters : # fun : It is a function to which map passes each element of given iterable. # iter : It is a iterable which is to be mapped. # a single value that denotes how many numbers should be passed to a list n = int(input()) # print(f"Input from console {n}") # Convert all inputs from console and type cast them into int. integer_list = tuple(map(int, input().split())) # print(integer_list[0]) print(hash(integer_list)) # This is a random string
true
708d5102fb648b48abd4dd3886f5bb923cf2b856
varunmalik123/Python-Data-Analysis
/write_columns.py
930
4.53125
5
def write_columns(data,fname): """ The purpose of this function is to take a list of numbers and perform two calculations on it. The function will generate a csv file with three columns containing the original data and the result from the first to calculations respectively :param data(list with elements being either floats or ints): Input data :param fname(str): File name of output csv """ assert isinstance(data, list) assert isinstance(fname, str) assert (len(data) > 0) for elements in data: assert isinstance(elements, (int, float)) import csv fname = fname + ".csv" with open(fname, "w") as out: big_big = [] for no in data: temp_list = [] temp_list.append('{0:.2f}'.format(no)) temp_list.append(" " + '{0:.2f}'.format((no**2))) temp_list.append(" " + '{0:.2f}'.format(((no + no**2)/3))) big_big.append(temp_list) writer = csv.writer(out) writer.writerows(big_big)
true
d8df82383460b7c1730b7d2af1623a797fb35e5e
ra3738/Latext
/hasConsSpace.py
1,261
4.15625
4
#Checks if current index is a space, returns boolean def isThisASpace(str, index): if (str[index] == " "): return True else: return False #Checks if current index and next index are spaces, returns boolean #If at second last index, returns false def hasConsSpaces(str, index): if (index + 1 < len(str)): if (isThisASpace(str, index) and isThisASpace(str, index+1)): return True else: return False else: return False #Counts no. of consecutive spaces, returns int def howManySpaces(str, index): length = len(str) index = index n = 0 while (index < length): if (isThisASpace(str,index)): n = n + 1 index = index + 1 else: return n return n #replaces spaces number of indices after and including index with strToReplaceWith #Returns string def replaceSpaces(strToReplace, index, strToReplaceWith, spaces): strList = list(strToReplace) while (not(spaces== 0)): strList[index] = strToReplaceWith index = index + 1 spaces = spaces - 1 return "".join(strList) testString = " m m " i = 0 while (i < len(testString)): if (hasConsSpaces(testString, i)): j = howManySpaces(testString, i) print(j) testString = replaceSpaces(testString, i, "", j) i = i + j - 1 else: i = i + 1 print(testString) #comment
true
3060d4c3f53a1a2a35e9c41f79cf6c5c8b08402f
JadedCoder712/Character-Distribution
/testing123.py
2,877
4.21875
4
""" distribution.py Author: Kyle Postans Credit: Kyle Postans, Mr. Dennison Assignment: Write and submit a Python program (distribution.py) that computes and displays the distribution of characters in a given sample of text. Output of your program should look like this: Please enter a string of text (the bigger the better): The rain in Spain stays mainly in the plain. The distribution of characters in "The rain in Spain stays mainly in the plain." is: iiiiii nnnnnn aaaaa sss ttt ee hh ll pp yy m r Notice about this example: * The text: 'The rain ... plain' is provided by the user as input to your program. * Uppercase characters are converted to lowercase * Spaces and punctuation marks are ignored completely. * Characters that are more common appear first in the list. * Where the same number of characters occur, the lines are ordered alphabetically. For example, in the printout above, the letters e, h, l, p and y both occur twice in the text and they are listed in the output in alphabetical order. * Letters that do not occur in the text are not listed in the output at all. """ """What I want to do is make a list of uppercase and lowercase lists. Then make a thing that takes the list of upper/lowercase letters and creates a variable for each letter with the number of times it shows up. Then create a list of those variables (which have numbers of letters in the sentence attached to them). Sort them by amount. """ sentence = input("Please enter a string of text (the bigger the better): ") print('The distribution of characters in "{0}" is: '.format(sentence)) import string from operator import itemgetter, attrgetter, methodcaller bignumber=len(sentence) #unnecessary numbers=range(1, int(bignumber)) #unnecessary sentencelist=list(sentence) #turns the sentence into a list of letters megalist= string.ascii_lowercase #makes a list of lowercase letters finallist=[] #creates final list in order to put tuples into sentence1=[x.lower() for x in sentencelist] #makes all letters lowercase #The Actual Program: #creating the list of tuples by putting each letter with the times they appear in the sentence: for letter in megalist: number=sentence1.count(letter) if number is not int(0): variables=(number, letter) finallist.append(variables) #sorting the tuple list into reverse alphabetical order, then leaving those properties in place while puttiing it order of appearance AND alphabetical order: finallist1=sorted(finallist, key=itemgetter(0,1)) #finallist2=sorted(finallist1, key=itemgetter(0)) #finallistreversed=list(reversed(finallist1)) #print(finallistreversed) finallistreversed = list(finallist1) #creating the actual list of letters by multiplying the letters in the tuples by the amount of times they appear: for x,c in finallistreversed: if x is not int(0): print(x*c)
true
0cc275639d9847d73865c59c944c271b99605bb7
RohitPr/PythonProjects
/07. Banker Roulette/7.Banker_Roulette.py
502
4.34375
4
""" You are going to write a program which will select a random name from a list of names. The person selected will have to pay for everybody's food bill. Important: You are not allowed to use the choice() function. """ import random names_string = 'Angela, Ben, Jenny, Michael, Chloe' names = names_string.split(", ") names_list = list(names) names_length = len(names_list) result = random.randint(0, names_length - 1) person_who_will_pay = names_list[result] print(person_who_will_pay)
true
b504f63cabe4ac1ad9f493410378566fda23f66b
CihanKeles/ACM114_Sec2
/Week6/nested_for_exp.py
614
4.1875
4
num_students = int(input('How many students do you have? ')) num_test_scores = int(input('How many test scores per student? ')) for student in range(num_students): total = 0.0 print('Student number', student + 1) print('-----------------') for test_num in range(num_test_scores): print('Test number', test_num + 1, end='') score = float(input(': ')) # Add the score to the accumulator. total += score average = total / num_test_scores print('The average for student number', student + 1, \ 'is:', format(average, '.1f')) print()
true
799fcd9e6c1b9ad2b4f8bd37dcb14989a808bb59
CihanKeles/ACM114_Sec2
/Week14/ACM114_Quiz_Week13_solution.py
864
4.125
4
import random # The main function. def main(): # Initialize an empty dictionary. number_dict = dict() # Repeat 100 times. for i in range(100): # Generate a random number between 1 and 9. random_number = random.randint(1, 9) # Establish or increment the number in the dictionary. if random_number not in number_dict: number_dict[random_number] = 1 else: number_dict[random_number] += 1 # Display the results. print('Number\tFrequency') print('------ ---------') # The "sorted" function produces a sorted version of # the list of key-value pairs from the "items" method. for number, frequency in sorted(number_dict.items()): print(number, frequency, sep='\t') # Call the main function. main()
true
b0b91399237afcfe69a0b2c78428f139f658950f
tanngo1605/ProblemSet1
/problem5/solution.py
583
4.1875
4
#This is a really cool example of using closures to store data. # We must look at the signature type of cons to retrieve its first and last elements. cons takes in a and b, and returns a new anonymous function, which itself takes in f, and calls f with a and b. So the input to car and cdr is that anonymous function, which is pair. To get a and b back, we must feed it yet another function, one that takes # in two parameters and returns the first (if car) or last (if cdr) one. def car (pair) return pair(lambda a, b:a) def cdr(pair) return pair(lambda a,b: b)
true
bf772445c70ed744a38609bb35aa045d5d5e29ec
sujanay/python-interview-questions
/tree.py
2,011
4.125
4
from __future__ import print_function # Binary Tree Node class TreeNode: def __init__(self, v, l=None, r=None): self.value = v self.left = l self.right = r # insert data to the tree def tree_insert(root, x): attr = 'left' if x < root.value else 'right' side = getattr(root, attr) if not side: setattr(root, attr, TreeNode(x)) else: tree_insert(side, x) # preorder traversal through the tree def print_tree_preorder(root): if root is None: return print(root.value, end=' - ') print_tree_preorder(root.left) print_tree_preorder(root.right) # inorder traversal through the tree def print_tree_inorder(root): if root is None: return print_tree_inorder(root.left) print(root.value, end=' - ') print_tree_inorder(root.right) # postorder traversal through the tree def print_tree_postorder(root): if root is None: return print_tree_postorder(root.left) print_tree_postorder(root.right) print(root.value, end = ' - ') if __name__ == '__main__': # Tree Structure root = TreeNode(7) # 7 tree_insert(root, 4) # / \ tree_insert(root, 5) # 4 8 tree_insert(root, 8) # / \ \ tree_insert(root, 9) # 2 5 9 tree_insert(root, 2) # \ tree_insert(root, 3) # 3 print("Inorder traversal") # Inorder(left, root, right) print_tree_inorder(root) # outputs: 2 - 3 - 4 - 5 - 7 - 8 - 9 - print("\n\nPreorder traversal") # Preorder(root, left, right) print_tree_preorder(root) # outputs: 7 - 4 - 2 - 3 - 5 - 8 - 9 - print("\n\nPostorder traversal") # Postorder(left, right, root) print_tree_postorder(root) # outputs: 3 - 2 - 5 - 4 - 9 - 8 - 7 -
true
2e615d7d4fc73f1a5540ec12938b87b2f769b5b9
sujanay/python-interview-questions
/python/Algorithms/IsAnagram.py
515
4.4375
4
"""check if the two string are anagrams of each other""" """ Method-1: This method utilizes the fact that the anagram strings, when sorted, will be equal when testing using string equality operator """ def Is_Anagram(str1, str2): if len(str1) != len(str2): return False str1_sorted, str2_sorted = sorted(str1), sorted(str2) return str1_sorted == str2_sorted print(Is_Anagram('hello', 'billion')) print(Is_Anagram('mary', 'yarm')) print(Is_Anagram('table', 'balet'))
true
b3554ace99a9f2df79f386fafd19464937d7d4e6
tapczan666/sql
/homework_03.py
504
4.21875
4
# homework assignment No2 - continued import sqlite3 with sqlite3.connect("cars.db") as connection: c = connection.cursor() # find all car models in the inventory c.execute("SELECT * FROM inventory") inventory = c.fetchall() for car in inventory: print(car[0], car[1]) print(car[2]) # find all order dated for a given model c.execute("SELECT order_date FROM orders WHERE make = ? AND model = ? ORDER BY order_date", (car[0], car[1])) dates = c.fetchall() for d in dates: print(d)
true
3468722bd044822a7f85464074bc0a6cdae623bb
prydej/WordCount
/Tracker.py
712
4.1875
4
""" Author: Julian Pryde Name: Essay Tracker Purpose: To count the number of words over two letters in a string Dat: 22MAR16 Input: A String Output: An integer containing the number of words over 2 letters in input """ import sys # Read String from file essay_handle = open(sys.argv[1]) essay = essay_handle.read() essay_handle.close() # Remove all punctuation essay = essay.translate(None, "\'[](){}:,`-_.!@#$%^&*?\";\\/+=|") # Tokenize string on spaces split_essay = essay.split() # Iterate through through each word, add to count if over >= 3 letters count = 0 for butterfly in split_essay: if butterfly.len > 2: count += 1 # Print number of words to cmd line print("Words over 2 letters: ", count)
true
6199c577d8e6bef67694d770bded9339a9293ac4
AzwadRafique/Azwad
/Whacky sentences.py
602
4.3125
4
import random adj = input("Insert an adjective ") noun = input("Insert a noun ") verb = input("Insert a verb ending with 'ing' ") if verb.count('ing') == 0: verb = False while verb == False: verb = input("Please insert a verb ending with 'ing' ") sentences = [f"Our house has {adj} furniture and there is a {verb} {noun}", f"The school canteen has {adj} pizzas and a {verb} {noun}", f"The {adj} {noun} is {verb} ", f"He described the {noun} to be {adj} looking while he was {verb}"] sentence = random.choice(sentences) print(sentence)
true
d2b105a85201dc8c909dc6c53854c9dfbe04252e
AzwadRafique/Azwad
/Emailsv.py
1,536
4.21875
4
while 1 == 1: number_emails = { 'manha@gmail.com': '12345', 'jack@gmail.com': '124567' } login_or_sign_in = input('login or sign in: ') if login_or_sign_in.upper() == 'LOGIN': email = input('what is your email: ') if email in number_emails: password = input('password: ') if password == number_emails.get(email): print("welcome") break else: print('wrong password') else: print('wrong email') elif login_or_sign_in.upper() == 'SIGN IN': new_account = input('name of account: ') if new_account in number_emails: print('Sorry this title has already been taken') if len(new_account) <= 9: print('Sorry the account name must contain a minimum of 10 characters') if new_account.count('@gmail.com') == 0: print("The account name must contain '@gmail.com'") new_password = input('password: ') if len(new_password) <= 5: print('Sorry the password must have a minimum of 5 characters') confirmation = input('please confirm the password') if new_password == confirmation: number_emails[new_account] = new_password print("you have successfully created a new account") break else: print("you have not confirmed your password please try again later") else: print('can you please repeat')
true
4d20a237a1b8b806e5eea64c7c635dff54b4e8c2
dimamik/AGH_Algorithms_and_data_structures
/PRACTISE/FOR EXAM/Wyklady/W2_QUEUE_STACK.py
2,898
4.15625
4
class Node(): def __init__(self,val=None,next=None): self.val=val self.next=next class stack_lists(): def __init__(self,size=0): first=Node() self.first=first self.size=size def pop(self): if self.size==0:return self.size-=1 tmp=self.first.next.next to_ret=self.first.next self.first.next=tmp return to_ret def push(self,Node_to_push): tmp=self.first.next Node_to_push.next=tmp self.first.next=Node_to_push self.size+=1 def print_stack(self): if self.size==0:print("The stack is empty") tmp=self.first.next while tmp!=None: print(tmp.val) tmp=tmp.next class QueueLists(): def __init__(self,first=None): self.first=first def push(self,Node_to_push): if Node_to_push==None: return None if self.first==None: Node_to_push.next=None self.first=Node_to_push else: self.first.next=Node_to_push def PrintQueueOnLists(self): """ Printing from the end """ tmp=self.first while tmp!=None: print(tmp.val) tmp=tmp.next def pop(self): if self.first==None or self.first.next==None: return None else: to_ret=self.first tmp=self.first.next self.first=tmp return to_ret.val """ Q=QueueLists() Q.push(Node(15)) Q.push(Node(25)) print(Q.pop()) Q.PrintQueueOnLists() """ """ S=stack_lists() K=Node(5) S.push(K) S.print_stack() S.pop() S.print_stack() """ class stack(): def __init__(self,size=10): tab=[None]*size self.tab=tab self.top=0 #Current to fill self.size=size def pop(self): self.top-=1 return self.tab[self.top] def push(self,element_to_push): self.tab[self.top]=element_to_push self.top+=1 def is_empty(self): return self.size==0 def print_stack(self): print(self.tab[:self.top]) class Queue(): def __init__(self,size_of_tab=10): self.size_of_tab=size_of_tab tab=[None]*size_of_tab self.tab=tab self.first=0 self.size=0 def is_empty(self): return size==0 def pop(self): self.size-=1 self.first+=1 return self.tab[self.first-1] def push(self,el_to_push): self.size+=1 tmp=self.first+self.size-1 self.tab[tmp]=el_to_push def print_queue(self): tab_tmp=[0]*self.size k=0 for i in range(self.first,self.first+self.size): tab_tmp[k]=self.tab[i] k+=1 print(tab_tmp) """ K=stack_lists() K.push(Node(6)) K.push(Node(6)) K.push(Node(6)) K.push(Node(49)) K.pop() K.pop() K.pop() K.pop() K.print_stack() """
true
4e9b9da28608efcd69df0f7706a82d16461dd7d2
JulieBoberg/Learn-Python-3-the-Hard-Way
/ex8.py
931
4.3125
4
# declare variable formatter and set it equal to a string with four sets of brackets. formatter = "{} {} {} {}" # prints the string in the variable formatter with the arguments in format in place of the brackets print(formatter.format(1, 2, 3, 4)) # prints the string in the variable formatter with the arguments in format in place of the brackets print(formatter.format("one", "two", "three", "four")) # prints the string in the variable formatter with the arguments in format in place of the brackets print(formatter.format(True, False, False, True)) # prints the string in the variable formatter and each bracket contains the entire string of formatter print(formatter.format(formatter, formatter, formatter, formatter)) # prints formatter with each bracket replaced by a string provided in format() print(formatter.format( "Try your", "Own text here", "Maybe a poem", "Or a song about fear" ))
true
5d32181fdadd2ab1ca9b672617a612e03216259e
JulieBoberg/Learn-Python-3-the-Hard-Way
/ex20.py
1,617
4.1875
4
from sys import argv script, input_file = argv # define function print_all that accepts parameter f(a file) def print_all(f): # read the file(f) and print it print(f.read()) # define function rewind which accepts parameter f def rewind(f): # find the (0) start of the file(f) f.seek(0) # define the function print_a_line that accepts line_count and a file(f) def print_a_line(line_count, f): # Goes to line specified in line_count and reads that line of the file, prints print(line_count, f.readline()) # variable current_file opens the input_file current_file = open(input_file) # prints a string that ends with a line break print("First let's print the whole file:\n") # calls function print_all with current_file as parameter. This opens, reads and prints the input_file print_all(current_file) # prints a string print("Now let's rewind, kind of like a tape.") # calls function rewind that opens the input_file and goes to start of file. rewind(current_file) # prints a string print("Let's print three lines:") # variable current_line is set to 1 current_line = 1 # calls print_a_line which takes the current_line and prints it from current_file print_a_line(current_line, current_file) # variable current_line is increased by 1 current_line = current_line + 1 # current_line += 1 # calls print_a_line again but current_line is increased by 1 print_a_line(current_line, current_file) # calls print_a_line again but current_line is increased by 1 current_line = current_line + 1 # current_line += 1 print_a_line(current_line, current_file)
true
795ba841a724b31cc3f2963b9bd15b9a4f5346fd
natalialovkis/MyFirstPythonProject_Math
/math_project1.py
2,321
4.3125
4
# -*- coding: utf-8 -*- # Math learning program import random import math import turtle print("Hello Dear User!") name = input("Please, enter your name: ") print() print("Hello %s! Let`s learn the Math!" % name) print() num_of_ex = 0 while True: try: num_of_ex = int(input("How many exercises are you going to solve? " "Enter a number from 1 to 10: ")) if 1 <= num_of_ex <= 10: break print("try again") except ValueError: print("That's not an int!") user_try = 0 while user_try < num_of_ex: first = random.randint(1, 11) # generate number between 1 and 100 second = random.randint(1, 11) action = random.randint(1, 4) # 1=+; 2=-; 3=*; if action == 1: answer = first + second try: user_in = int(input("What is result " "of %d + %d :" % (first, second))) if user_in == answer: print("Good!") else: print("Not right") except ValueError: print("That's not an int!") elif action == 2: answer = first - second try: user_in = int(input("What is result " "of %d - %d :" % (first, second))) if user_in == answer: print("Good!") else: print("Not right") except ValueError: print("That's not an int!") else: answer = first * second try: user_in = int(input("What is result " "of %d * %d :" % (first, second))) if user_in == answer: print("Good!") else: print("Not right") except ValueError: print("That's not an int!") user_try += 1 print() print("Good job! Bye!") print() input("Press enter to see a surprise.") radius = 100 petals = num_of_ex def draw_arc(b, r): c = 2*math.pi*r ca = c/(360/60) n = int(ca/3)+1 l = ca/n for i in range(n): b.fd(l) b.lt(360/(n*6)) def draw_petal(b, r): draw_arc(b, r) b.lt(180-60) draw_arc(b, r) b.rt(360/petals-30) bob = turtle.Turtle() for i in range(petals): draw_petal(bob, radius) bob.lt(360/4)
true
bb36efd1df3edf317fb9a8ba21309202e4582e33
TrilochanSati/exp
/daysInDob.py
832
4.3125
4
#Program to return days from birth of date. from datetime import date def daysInMonth(month:int,year:int)->int: months=[31,28,31,30,31,30,31,31,30,31,30,31] if(year%4==0 and month==2): return 29 else: month-=1 return months[month] def daysInDob(dobDay,dobMonth,dobYear)->int: today=date.today() totalDays=0 curDay=today.day curMonth=today.month curYear=today.year day=dobDay month=dobMonth year=dobYear while(day!=curDay or month!=curMonth or year!=curYear): dim=daysInMonth(month,year) if(day==dim): day=0 month+=1 totalDays+=1 day+=1 if(month>12): month=1 year+=1 print(day,month,year) return totalDays print("days",daysInDob(27,9,2018))
true
c829a7f379119a3e735a4a9b20de160faa4c3776
alzheimeer/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/3-say_my_name.py
543
4.40625
4
#!/usr/bin/python3 def say_my_name(first_name, last_name=""): """ Args: first_name (str): the first name last_name (str, optional): the last name Raises: TypeError: if the first_name or last_name are not strings """ if first_name is None or type(first_name) is not str: raise TypeError('first_name must be a string') if last_name is None or type(last_name) is not str: raise TypeError('last_name must be a string') print("My name is {:s} {:s}".format(first_name, last_name))
true
d65d22f6a7e69c886203c873e3870359b74f2eed
chenjiahui1991/LeetCode
/P0225.py
1,053
4.1875
4
class MyStack: def __init__(self): """ Initialize your data structure here. """ self.line = [] def push(self, x): """ Push element x onto stack. :type x: int :rtype: void """ self.line.append(0) for i in range(len(self.line) - 1, 0 , -1): self.line[i] = self.line[i - 1] self.line[0] = x def pop(self): """ Removes the element on top of the stack and returns that element. :rtype: int """ return self.line.pop(0) def top(self): """ Get the top element. :rtype: int """ return self.line[0] def empty(self): """ Returns whether the stack is empty. :rtype: bool """ return len(self.line) == 0 # Your MyStack object will be instantiated and called as such: obj = MyStack() obj.push(1) obj.push(2) print(obj.top()) print(obj.pop()) print(obj.empty()) # param_3 = obj.top() # param_4 = obj.empty()
true
e51c78c3e21eb1c6a1624bd113fa1d94ab353293
Abishekthp/Simple_Assignments
/Assigmnet_1/11Factor_and_largest_factor_of_a_Number.py
247
4.25
4
#FIND THE FACTORS OF A NUMBER AND PRINT THE LARGEST FACTOR n=int(input('Enter the number:')) l=0 print('Factors are:') for i in range(1,n): if(n%i==0): print(i) if(i>l): l=i print('largest factor:',l)
true
9db36b88191861353321686f4209406196385ae1
HolyCoffee00/python_books
/python_books/py_crash/chaper_7/greeter.py
267
4.21875
4
name = input("Please tell me your name: ") print("Hello, " + name.title() + "!") prompt = "If you tell us who you are i will personalize the message: " prompt += "\nWhat is your firtst name: " name = input(prompt) print("Hello, " + name.title() + "!")
true
f58ad48501d9a0a3bf2d2fcb239a1e2ca6ad9870
neilkazimierzsheridan/sqlite3
/sq2.py
1,070
4.1875
4
#sqlite part 2 import sqlite3 conn = sqlite3.connect('customer2.db') c = conn.cursor() #create the cursor instance #c.execute(" SELECT rowid, * FROM customers") #rowid to get autogenerated primary key, this is element 0 now ## USING THE WHERE CLAUSE SEARCHING #c.execute(" SELECT rowid, * FROM customers WHERE last_name = 'Baker'") #using the WHERE clause to search for something specific in field e.g. last_name # if e.g. age could do WHERE age >= 21 etc # WHERE last_name LIKE 'B%' for all the ones beginning B #c.execute(" SELECT rowid, * FROM customers WHERE last_name LIKE 'M%'") c.execute(" SELECT rowid, * FROM customers WHERE email LIKE '%google.com'") items = c.fetchall() print("\n", "Displaying records from database:") for item in items: print("\n" + "ID: " + str(item[0]) + "\n" + "Name :"+ item[1] + " " + item[2] + "\n" + "Email: " + item[3]) # display them with the primary key conn.commit() # Datatypes are NULL, INTEGER, REAL, TEXT, BLOB // BLOB stored as is e.g. image, audio etc. conn.close()
true
644335a0226c0b9a54aeb7b689e8452e0705466a
ddib-ccde/pyforneteng2020
/week1/exercise2.py
1,106
4.1875
4
# Print an empty line print(f"") # Ask user for an IP address and store as string ipaddr = input("Please enter an IP address: ") # Split the IP address into four parts and store in a list ipaddr_split = ipaddr.split(".") # Print an empty line print(f"") # Print the header with centered text (^) and width 15 print(f"{'Octet1':^15}{'Octet2':^15}{'Octet3':^15}{'Octet4':^15}") print("-" * 60) # Print each octet of the IP address using list slicing print(f"{ipaddr_split[0]:^15}{ipaddr_split[1]:^15}{ipaddr_split[2]:^15}{ipaddr_split[3]:^15}") # Print IP in binary using builtin bin() function # The ipaddr_split variable is a string, need to convert to integer with builtin function int() print( f"{bin(int(ipaddr_split[0])):^15}" f"{bin(int(ipaddr_split[1])):^15}" f"{bin(int(ipaddr_split[2])):^15}" f"{bin(int(ipaddr_split[3])):^15}" ) # Print the IP in hex format using builtin function hex() print( f"{hex(int(ipaddr_split[0])):^15}" f"{hex(int(ipaddr_split[1])):^15}" f"{hex(int(ipaddr_split[2])):^15}" f"{hex(int(ipaddr_split[3])):^15}" ) print("-" * 60)
true
1d9174ea48f7685df67ab36c817ab72f1c1f0f7e
GAURAV-GAMBHIR/pythoncode
/3.A2.py
238
4.21875
4
a=(12,14,14,11,87,43,78) print("smallest element is",min(a)) print("largest element is",max(a)) finding product of all element in tuple result=1 for x in a: result=result*x print("product of all element in tuple is: ",result)
true
c6df819a465084cbaf0ad8de72c2e554a3898a37
Bishwajit05/DS-Algos-Python
/Recursion/CoinChangeProblemRecursion.py
1,649
4.25
4
# Implement coin change problem # Author: Pradeep K. Pant, ppant@cpan.org # Given a target amount n and a list (array) of distinct coin values, what's the fewest coins needed to make the # change amount. # 1+1+1+1+1+1+1+1+1+1 # 5 + 1+1+1+1+1 # 5+5 # 10 # With 1 coin being the minimum amount. # Solution strategy: # This is a classic problem to show the value of dynamic programming. We'll show a basic recursive example and show # why it's actually not the best way to solve this problem. # Implement fibonacci_iterative() def coin_change_recursion(target,coins): ''' INPUT: Target change amount and list of coin values OUTPUT: Minimum coins needed to make change Note, this solution is not optimized. ''' # Default to target value min_coins = target # Check to see if we have a single coin match (BASE CASE) if target in coins: return 1 else: # for every coin value that is <= than target (Using list comprehension for i in [c for c in coins if c <= target]: # Recursive Call (add a count coin and subtract from the target) num_coins = 1 + coin_change_recursion(target - i, coins) # Reset Minimum if we have a new minimum (new num_coins less than min_coins) if num_coins < min_coins: min_coins = num_coins return min_coins # Test print (coin_change_recursion(8,[1,5])) # 4 # Note # The problem with this approach is that it is very inefficient! It can take many, # many recursive calls to finish this problem and its also inaccurate for non # standard coin values (coin values that are not 1,5,10, etc.)
true
cd49cf9074247537a3d29e2ba4d9ad0dea5634c2
Bishwajit05/DS-Algos-Python
/LinkedLists/DoublyLinkedListImple.py
733
4.34375
4
# Doubly Linked List class implementation # Author: Pradeep K. Pant, ppant@cpan.org # Implement basic skeleton for a doubly Linked List # Initialize linked list class class DoublyLinkedListNode(object): def __init__(self,value): self.value = value self.prev_node = None self.next_node = None # Test # Added node a = DoublyLinkedListNode(1) b = DoublyLinkedListNode(2) c = DoublyLinkedListNode(3) # Set the pointers # setting b after a (a before b) b.prev_node = a a.next_node = b # Setting c after a b.next_node = c c.prev_node = b print (a.value) print (b.value) print (c.value) # Print using class print (a.next_node.value) print (b.next_node.value) print (b.prev_node.value) print (c.prev_node.value)
true
a75396b7a5bbd99390cb90c02857f63c0fc99df4
Bishwajit05/DS-Algos-Python
/Sorting/InsertionSortImple.py
938
4.21875
4
# Insertion Sort Implementation # Author: Pradeep K. Pant, https://pradeeppant.com # Insertion sort always maintains a sorted sub list in the lower portion of the list # Each new item is then "inserted" back into the previous sublist such that the # sorted sub list is one item larger # Complexity O(n2) square # Reference material: http://interactivepython.org/runestone/static/pythonds/SortSearch/TheSelectionSort.html def insertion_sort(arr): # For every index in array for i in range(1,len(arr)): # Set current values and position currentvalue = arr[i] position = i # Sorted Sublist while position>0 and arr[position-1]>currentvalue: arr[position]=arr[position-1] position = position-1 arr[position]=currentvalue # Test arr = [2,7,1,8,5,9,11,35,25] insertion_sort(arr) print (arr) #[1, 2, 5, 7, 8, 11, 25, 35]
true
4ce6d7ff07ffd9a199d96f8c522a4c043c1e9043
erien/algorithms
/mergeSort/python/main.py
2,430
4.34375
4
"""Example implementation of the merge sort algorithm""" TO_SORT = "../../toSort.txt" SORTED = "../../sorted.txt" def read_table_from_file(path: str) -> list: """Reads table from a file and creates appropriate table... I mean list! Args: path: Path to the file Returns: Read table """ with open(path, "r") as file: # Omit first two lines (they're comments) file.readline() file.readline() # Omit the line with amount, we don't need that file.readline() # Now read the rest of the numbers tab = [] for line in file.readlines(): tab.append(int(line)) return tab def _merge(tab: list, start: int, end: int): """Merges tables Args: tab: Table to merge start: start of the chunk to merge end: end of the chunk (not included) to merge """ half = (end + start) // 2 left = start right = half buffer = [] while (left < half) and (right < end): if tab[left] < tab[right]: buffer.append(tab[left]) left += 1 else: buffer.append(tab[right]) right += 1 while left < half: buffer.append(tab[left]) left += 1 while right < end: buffer.append(tab[right]) right += 1 i = 0 while start < end: tab[start] = buffer[i] start += 1 i += 1 def _merge_sort(tab: list, start: int, end: int): """Performs merge sort, what did you expect? The range is [start; end) Args: tab: Table to sort start: start of the chunk to sort end: end of the chunk (not included) to sort """ if end - start < 2: return half = (end + start) // 2 _merge_sort(tab, start, half) _merge_sort(tab, half, end) _merge(tab, start, end) def merge_sort(tab: list): """Sortes the table using merge sort algorithm Args: tab: tab to be sorted """ _merge_sort(tab, 0, len(tab)) def main(): """Guees where the whole fun starts? [: Reads table to be sorted and sorted performs the merge sort algorithm and checks if table was sorted """ to_sort = read_table_from_file(TO_SORT) sorted_table = read_table_from_file(SORTED) merge_sort(to_sort) assert to_sort == sorted_table print("Table was sorted correctly!") return 0 main()
true
d3d57dbcde978689fb4122a9266b9ea44a4674c7
mapatelian/holbertonschool-higher_level_programming
/0x0B-python-input_output/3-write_file.py
323
4.25
4
#!/usr/bin/python3 def write_file(filename="", text=""): """Writes a string to a text file Args: filename (str): name of the file text (str): string to be input """ with open(filename, 'w', encoding='utf-8') as filie: characters = filie.write(text) return characters
true
ec92ebb83400693ea92230c152ec34b490eb1703
mapatelian/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
475
4.28125
4
#!/usr/bin/python3 def add_integer(a, b=98): """Function that adds two integers. Args: a (int): first integer b (int): second integer Return: sum of the arguments """ if isinstance(a, int) is False and isinstance(a, float) is False: raise TypeError("a must be an integer") if isinstance(b, float) is False and isinstance(b, int) is False: raise TypeError("b must be an integer") return int(a) + int(b)
true
acf85c1dae18cff881547f333fd36114a70e6601
mapatelian/holbertonschool-higher_level_programming
/0x0B-python-input_output/0-read_file.py
284
4.125
4
#!/usr/bin/python3 def read_file(filename=""): """Reads a text file in UTF-8, prints to stdout Args: filename (str): name of the file """ with open(filename, 'r', encoding='utf-8') as filie: for linie in filie: print(linie, end='')
true
202bade662bbd859d43c58c1ed371c2c1a0eaf85
mengnan1994/Surrender-to-Reality
/py/0073_set_matrix_zeroes.py
1,615
4.1875
4
""" Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. Example 1: Input: [ [1,1,1], [1,0,1], [1,1,1] ] Output: [ [1,0,1], [0,0,0], [1,0,1] ] Example 2: Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ] Follow up: A straight forward solution using O(mn) space is probably a bad idea. A simple improvement uses O(m + n) space, but still not the best solution. Could you devise a constant space solution? """ class Solution(object): def set_zeros(self, matrix: [[int]]) -> None: if not matrix or not matrix[0]: return self.matrix = matrix self.m, self.n = len(matrix), len(matrix[0]) self._mark() self._set_zero() def _mark(self): for i in range(self.m): for j in range(self.n): if self.matrix[i][j] == 0: for k in range(self.m): if self.matrix[k][j] != 0: self.matrix[k][j] = '#' for k in range(self.n): if self.matrix[i][k] != 0: self.matrix[i][k] = '#' def _set_zero(self): for i in range(self.m): for j in range(self.n): if self.matrix[i][j] == '#': self.matrix[i][j] = 0 def test(self): matrix = [ [0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5] ] self.set_zeros(matrix) print(matrix) Solution().test()
true
dbb8650adc7e732575c33a032004fce683831afa
mengnan1994/Surrender-to-Reality
/py/0646_maximum_length_of_pair_chain.py
1,531
4.28125
4
""" You are given n pairs of numbers. In every pair, the first number is always smaller than the second number. Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion. Given a set of pairs, find the length longest chain which can be formed. You needn't use up all the given pairs. You can select pairs in any order. Example 1: Input: [[1,2], [2,3], [3,4]] Output: 2 Explanation: The longest chain is [1,2] -> [3,4] Note: The number of given pairs will be in the range [1, 1000]. """ class Solution: """ 0252_meeting_room 0253_meeting_room 的简化版本 """ def find_longest_chain(self, pairs): def key(element): return element[1] pairs = sorted(pairs, key=key) print(pairs) memo_num_pairs = [None for _ in pairs] memo_max_end = [None for _ in pairs] memo_num_pairs[0], memo_max_end[0] = 1, pairs[0][1] for i in range(1, len(pairs), +1): if pairs[i][0] > memo_max_end[i - 1]: memo_num_pairs[i] = memo_num_pairs[i - 1] + 1 memo_max_end[i] = pairs[i][1] else: memo_num_pairs[i], memo_max_end[i] = memo_num_pairs[i - 1], memo_max_end[i - 1] print(memo_num_pairs) return memo_num_pairs[-1] def test(self): pairs = [[-10,-8],[8,9],[-5,0],[6,10],[-6,-4],[1,7],[9,10],[-4,7]] ans = self.find_longest_chain(pairs) print(ans) soln = Solution() soln.test()
true
6109e08e127c59aa0699d6b7d06e8f65fb1893d7
mengnan1994/Surrender-to-Reality
/py/0151_reverse_words_in_string.py
880
4.375
4
""" Given an input string, reverse the string word by word. Example: Input: "the sky is blue", Output: "blue is sky the". Note: A word is defined as a sequence of non-space characters. Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. You need to reduce multiple spaces between two words to a single space in the reversed string. Follow up: For C programmers, try to solve it in-place in O(1) space. """ class Solution(object): def reverse_words(self, string): word_list = string.split(' ') word_list = [word[::-1] for word in word_list] res = "" for word in word_list: if word: res += word + " " return res[:-1][::-1] def test(self): print(self.reverse_words("the sky is blue shit ")) Solution().test()
true
40042792515af1f36829f92aaa330ac6cb17555e
mengnan1994/Surrender-to-Reality
/py/0186_reverse_words_in_a_string_ii.py
1,254
4.25
4
""" Given an input string , reverse the string word by word. Example: Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"] Note: A word is defined as a sequence of non-space characters. The input string does not contain leading or trailing spaces. The words are always separated by a single space. Follow up: Could you do it in-place without allocating extra space? """ class Solution: def reverse_words(self, str): idx = 0 while idx < len(str): start = idx while idx < len(str) and str[idx] != " ": idx += 1 end = idx word = str[start : end] self._swapper(str, start, end) idx += 1 str_len = len(str) self._reverser(str, 0, len(str)) # str = str[::-1] def _reverser(self, str, start, end): for idx in range((end - start) // 2): str[start + idx], str[end - 1 - idx] = str[end - 1 - idx], str[start + idx] def test(self): str = ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] self.reverse_words(str) print(str) soln = Solution() soln.test()
true
2f49b448e55de701569925e9f71c956bd6e1dcdf
mengnan1994/Surrender-to-Reality
/py/0098_valid_binary_search_tree.py
1,395
4.1875
4
""" Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: 1. The left subtree of a node contains only nodes with keys less than the node's key. 2. The right subtree of a node contains only nodes with keys greater than the node's key. 3. Both the left and right subtrees must also be binary search trees. Example 1: Input: 2 / \ 1 3 Output: true Example 2: 5 / \ 1 4 / \ 3 6 Output: false Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value is 5 but its right child's value is 4. 1120 -> 1134 (ac) 99.73% """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def is_valid_bst(self, root: TreeNode): if not root: return True return self._dfs(root, -float("inf"), float("inf")) def _dfs(self, node : TreeNode, lower_bound, upper_bound): if not (node.val < upper_bound and node.val > lower_bound): return False valid = True if node.left: valid = valid and self._dfs(node.left, lower_bound, node.val) if not valid: return False if node.right: valid = valid and self._dfs(node.right, node.val, upper_bound) return valid
true
250013f9d8f1cb624ca63725487ec54ad7985317
WillHTam/reference
/bubble_sort.py
1,239
4.1875
4
# Bubble Sort # compare consecutive pairs of elements # swap elements in pairs such that smaller is first # at end of list, do so again. stop when no more swaps have been made def bubble_sort(L): """ inner for loop does the comparisons outer while loop is doing multiple passes until no more swaps """ swap = False # flag for indicating when finished while not swap: swap = True print(L) for i in range(1, len(L)): if L[i - 1] > L[i]: # if element is out of order, swap and set flag back to False swap = False temp = L[i] L[i] = L[i - 1] L[i - 1] = temp # worst case? O(len(L)) for going through the whole list in the inner loop # and through the whole list O(len(L)) for the while loop # results in O(n*2) complexity where n is len(L) # to do len(L) - 1 comparisons and len(L) - 1 passes def bubble_two(L): last_index = len(L) - 1 while last_index > 0: print(L) for i in range(last_index): if L[i] > L[i + 1]: L[i], L[i + 1] = L[i + 1], L[i] last_index -= 1 return L l = [1, 5, 3, 8, 4, 9, 6, 2] m = l[:] bubble_sort(l) print('~') bubble_two(m)
true
912f71e7813de37a3e70d91f41c6b8c57353d45b
Nihiru/Python
/Leetcode/maximum_subarray.py
522
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 4 17:34:37 2020 @author: nick """ def maximum_subarray(array): # setting the maximum sub array similar to max_sum = array[0] current_sum = max_sum for ele in array[1:]: current_sum = max(ele + current_sum, ele) # adding elements to the existing array and determining the greatest max_sum = max(current_sum, max_sum) # identifying the maximum between maximum_sum and pre-calculated current_sum return max_sum
true
00c305f72eb4ca256dd67b8596097b834fb7c910
sandesh-chhetry/basic-python-
/Python Assignment 4/session3_functional.py
2,584
4.25
4
""" ---------------------------------------------------------------------------------------------------------------------------------------------------- """ """ 1. Write a program to display all prime numbers from 1 to """ ##function to find prime number in a range def findPrimeNumber(initial,final): for i in range(initial,final): ## take value from 2 to i for j in range(2,i): ## check condition whether the number is divisible by other number except same number and 1 if (i%j) == 0: break else: ## if not divisible then print i print(i) ## print(j) print("find prime numbers?") initialVal = input("Insert initial value: ") finalVal = input("Insert final value: ") ##pass user input value to find the prime numbers findPrimeNumber(int(initialVal),int(finalVal)) """ ---------------------------------------------------------------------------------------------------------------------------------------------------- """ """ 2. Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.) """ ##function to check whether the given string is palindrome or not def isPalindrome(string): ##get reverse of the input string check = string[::-1] ##print(check) if(string == check): print(string+ " is palindrome.") else: print(string+ " is not palindrome.") string = input("type a string to check palindrome or not: ") ##pass string paramater to the given function isPalindrome("2552") isPalindrome(string) """ ---------------------------------------------------------------------------------------------------------------------------------------------------- """ """6. Create a dictionary that has a key value pair of letters and the number of occurrences of that letter in a string. Given a string “pineapple”. The result should be as: {“p”:3, “i”:1, “n”:1, “e”:2, “a”:1, “l”:1} Don’t worry about the order of occurrence of letters. """ ##function to count the letters and the number in their def countLetters(string): print("the letter with their numbers are: ") dictonary = {} for letter in string: dictonary[letter] = dictonary.get(letter, 0) + 1 print(dictonary) string = input("insert an string: ") ##pass input value throw parameter countLetters(string)
true
c29246c37d513184514a1319aec0688b4e3db1f2
sandesh-chhetry/basic-python-
/Python Assignment 1/listGetExample.py
421
4.15625
4
##Exercise 4. Consider a list of any arbitrary elements. Your code should print the length of the list ##and first and fourth element of the list. ##list which contain some element elements = ["1st position", "2nd position", "3rd position", "4th position", "5th position", "6th position"] print("Length of the given element is: " + str(len(elements))) print("fourth element of the list is : " + str(elements[4]))
true
181b5324ba8239fc341d0304edc0007e2e73fde9
wiselyc/python-hw
/swap.py
352
4.34375
4
def swap_last_item(input_list): """takes in a list and returns a new list that swapped the first and the last element""" input_list[0], input_list[-1] = input_list[-1], input_list[0] # gets the first and last element and makes the first element = the last and the last element = the first return input_list # returns the new list
true
62482eb26b465185c7301587a6667e2b8fa18603
phttrang/MITx-6.00.1x
/Problem_Sets_3/Problem_2.py
1,834
4.25
4
# Problem 2 - Printing Out the User's Guess # (10/10 points) # Next, implement the function getGuessedWord that takes in two parameters - a string, secretWord, and a list of letters, # lettersGuessed. This function returns a string that is comprised of letters and underscores, based on what letters in # lettersGuessed are in secretWord. This shouldn't be too different from isWordGuessed! # Example Usage: # >>> secretWord = 'apple' # >>> lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's'] # >>> print(getGuessedWord(secretWord, lettersGuessed)) # '_ pp_ e' # When inserting underscores into your string, it's a good idea to add at least a space after each one, so it's clear to the user # how many unguessed letters are left in the string (compare the readability of ____ with _ _ _ _ ). This is called usability - # it's very important, when programming, to consider the usability of your program. If users find your program difficult to # understand or operate, they won't use it! # For this problem, you are free to use spacing in any way you wish - our grader will only check that the letters and underscores # are in the proper order; it will not look at spacing. We do encourage you to think about usability when designing. # For this function, you may assume that all the letters in secretWord and lettersGuessed are lowercase. def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' result = [] for char in secretWord: if char in lettersGuessed: result.append(char) else: result.append("_ ") return " ".join(result)
true
2945e387eb1a73bd8610e69bf79b7d0ff0b9462b
qrzhang/Udacity_Data_Structure_Algorithms
/3.Search_Sorting/recursion.py
1,221
4.1875
4
"""Implement a function recursively to get the desired Fibonacci sequence value. Your code should have the same input/output as the iterative code in the instructions.""" def get_fib_seq(position): first = 0 second = 1 third = first + second seq = [first, second, third] if position < 1: return -1 elif position < 4: return seq[:position - 1] else: for i in range(3, position): first = second second = third third = first + second seq.append(third) i += 1 return seq def my_get_fib(position): first = 0 second = 1 third = first + second if position < 0: return -1 elif position == 0: return first elif position == 1: return second elif position == 2: return third else: for i in range(2, position): first = second second = third third = first + second return third def get_fib(position): if position == 0 or position == 1: return position return get_fib(position - 1) + get_fib(position - 2) # Test cases print(get_fib(9)) print(get_fib(11)) print(get_fib(0))
true
aa00145cfff0c3d87d1ebc57537143777a49c728
opeoje91/Election_Analysis
/CLASS/PyPoll_Console.py
1,634
4.4375
4
#The data we need to retrieve # Assign a variable for the file to load and the path. #file_to_load = 'Resources/election_results.csv' # Open the election results and read the file #with open(file_to_load) as election_data: # To do: perform analysis. #print(election_data) import csv import os # Assign a variable for the file to load and the path. #file_to_load = os.path.join("Resources", "election_results.csv") # Open the election results and read the file. #with open(file_to_load) as election_data: # Print the file object. #print(election_data) #create election analysis to write # Create a filename variable to a direct or indirect path to the file. file_to_save = os.path.join("analysis", "election_analysis.txt") # Using the open() function with the "w" mode we will write data to the file. #open(file_to_save, "w") # Using the with statement open the file as a text file. #outfile = open(file_to_save, "w") # Write some data to the file. #outfile.write("Hello World") # Close the file #outfile.close() # Using the with statement open the file as a text file. with open(file_to_save, "w") as txt_file: # Write some data to the file. #txt_file.write("Hello World") # Write three counties to the file. # txt_file.write("Arapahoe, Denver, Jefferson") #write each on new line use \n # Write three counties to the file. txt_file.write("Arapahoe\nDenver\nJefferson") #The total number of votes cast #A complete list of candidates who received votes #The percentage of votes each candidate won #The total number of votes each candidate won #The winner of the election based on popular vote
true
418c14a4ae1e95d39e400b389bf6d16c6575559f
ar012/python
/learning/sets.py
948
4.1875
4
num_set = {1, 2, 3, 4, 5} word_set = {"mango", "banana", "orange"} subjects = set(["math", "bangla", "english"]) print(1 in num_set) print("mango" not in word_set) print(subjects) print(set()) # duplicate elements nums = {1, 2, 3, 5, 1, 2, 6, 3, 10} print(nums) # To add a element to a set nums.add(9) print(nums) # To remove a element from a set nums.remove(6) print(nums) li = [1, 2, 3, 4, 5, 6, 7, 0, 7, 5] list = list(set(li)) print(list) # Set Operations print("\nSet Operations\n") a = {1, 2, 3, 4, 8} b = {5, 3, 7, 8, 10} # Union of sets set_union = a | b print("Union of a and b =", set_union) # Intersection of sets set_intersection = a & b print("Intersection of a and b =", set_intersection) # difference of sets set_diff = a - b print("Diff from a to b =", set_diff) set_diff2 = b - a print("Difference from b to a =", set_diff2) # symmetric difference # set_sym_diff = a ^ b # print(Sym_Diff from a to b =", set_sym_diff)
true
84d1c158dd321f99c38ce95c3825a457b21ca9e5
Charles-IV/python-scripts
/recursion/factorial.py
536
4.375
4
no = int(input("Enter number to work out factorial of: ")) def recursive_factorial(n, fact=1): # fact = 1 # number to add to fact *= n # does factorial calculation n -= 1 # prepare for next recursion #print("fact: {}, n = {}".format(fact, n)) - test for debugging if n > 1: # keep repeating until it gets too low fact = recursive_factorial(n, fact) # pass variable back to output correct value return fact # return to output or lower level of recursion to output print(recursive_factorial(no))
true
d142a70a335d662c1dcc443603f17e2cc3e4996a
MorgFost96/School-Projects
/PythonProgramming/5-16/objects.py
2,685
4.34375
4
#Morgan Foster #1021803 # Intro to Object Oriented Programming ( OOP ) # - OOP enables you to develop large scale software and GUI effectively # - A class defines the properties and behaviors for objects # - Objects are created from classes # Imports import math # --- # OOP # --- # - Use of objects to create programs # - Object is a software entity that contains both data and code # - The procedure ( codes ) that an object performs are called methods # - Encapsulation # - Combining of data and code into a single object # - An object typically hides its data ( data binding ) but allows outside code to access its methods # - Code reusability # -------------------------------------- # Differences between Procedural and OOP # -------------------------------------- # Procedural # - Separation of data and codes # - If change way of storing data from variables to list, must modify all functions to accept list # # OOP # - Data and codes all encapsulated in class # - Just change the data and methods in class and all objects will take care of themselves class IncorrectCircle: # Initializer or constructior # - Automatically called when object is instantiated def __init__( self, radius = 1 ): self.radius = radius # Self Parameter that refers to the object that invokes the method def getPerimeter( self ): return 2 * self.radius * math.pi # Can use name other than self # - Self is conventional def getArea( you ): return you.radius ** 2 * math.pi def setRadius( self, radius ): self.radius = radius class Circle: # Place .__ prevents direct access to the data member def __init__( self, radius = 1 ): self.__radius = radius # Getters or Accessors def getRadius( self ): return self.__radius def getPerimeter( self ): return 2 * self.__radius * math.pi def getArea( you ): return you.__radius ** 2 * math.pi # Setter or Mutator def setRadius( self, radius ): self.__radius = radius def test(): incorrect_circle = IncorrectCircle() # circle.radius is called a dot access print( "The area of the circle of radius", incorrect_circle.radius, "is", incorrect_circle.getArea() ) circle = Circle( 25 ) print( "The area of the circle of radius", circle.getRadius(), "is", circle.getArea() ) # # Direct access to data member incorrect_circle.radius = 100 # circle.radius = 100 won't work # Change the radius from 25 to 100 circle.setRadius( 100 ) print( incorrect_circle.radius ) print( circle.getRadius() ) test() # To Instantiate is to create an instance of an object
true
97ddb326c2af50e3f61ed34fbe097d61eed12ebd
h4l0anne/PongGame
/Pong.py
2,421
4.28125
4
# Simple Pong Game in Python import turtle wn = turtle.Screen() wn.title("Pong Game") wn.bgcolor("green") wn.setup(width=800, height=600) wn.tracer(0) # Paddle A paddle_left = turtle.Turtle() paddle_left.speed(0) # 0 for maximum possible speed paddle_left.shape("square") paddle_left.color("blue") paddle_left.shapesize(stretch_wid=5, stretch_len=1) paddle_left.penup() #Sets the current pen state to PENUP. Turtle will move around the screen, but will not draw when its pen state is PENUP paddle_left.goto(-350, 0) # Paddle B paddle_right = turtle.Turtle() paddle_right.speed(0) # 0 for maximum possible speed paddle_right.shape("square") paddle_right.color("blue") paddle_right.shapesize(stretch_wid=5, stretch_len=1) paddle_right.penup() paddle_right.goto(350, 0) # Ball ball = turtle.Turtle() ball.speed(50) ball.shape("circle") ball.color("red") ball.penup() ball.goto(0, 0) ball.dx = 0.2 # every time the ball moves, it moves by 2 pixels ball.dy = 0.2 # Function to move the paddle def paddle_left_up(): y = paddle_left.ycor() y += 20 paddle_left.sety(y) def paddle_left_down(): y = paddle_left.ycor() y -= 20 paddle_left.sety(y) def paddle_right_up(): y = paddle_right.ycor() y += 20 paddle_right.sety(y) def paddle_right_down(): y = paddle_right.ycor() y -= 20 paddle_right.sety(y) # Keyboard binding to listen for keyboard input wn.listen() wn.onkeypress(paddle_left_up, "w") wn.onkeypress(paddle_left_down, "s") wn.onkeypress(paddle_right_up, "Up") wn.onkeypress(paddle_right_down, "Down") # Main Game Loop while True: wn.update() # Move the ball ball.setx(ball.xcor() + ball.dx) ball.sety(ball.ycor() + ball.dy) # Border checking if ball.ycor() > 290: ball.sety(290) ball.dy *= -1 if ball.ycor() < -290: ball.sety(-290) ball.dy *= -1 if ball.xcor() > 390: ball.goto(0, 0) ball.dx *= -1 if ball.xcor() < -390: ball.goto(0, 0) ball.dx *= -1 # Paddle and ball collisions if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_right.ycor() + 40 and ball.ycor() > paddle_right.ycor() - 40): ball.setx(340) ball.dx *= -1 if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddle_left.ycor() + 40 and ball.ycor() > paddle_left.ycor() - 40): ball.setx(-340) ball.dx *= -1
true
2aea01ba888855ee4d4d7e024bad881d26d5e9fa
smartpramod/97
/PRo 97.py
449
4.21875
4
import random print("NUMBER GUESSING GAME") number=random.randint(1,9) chances=0 print("GUESS A NUMBER BETWEEN 1 AND 9") while(chances<5): Guess=int(input("Enter your number")) if Guess==number: print("Congrulation, YOU WON") break elif Guess<number: print("Your guess was too low ") else: print("Your guess was too high") chances=chances+1 if not chances<5: print("you loss")
true
bc3e55ea22cd1e7e3aa39a9b020d128df16dfa92
aalhsn/python
/conditions_task.py
1,279
4.3125
4
""" Output message, so the user know what is the code about and some instructions Condition_Task author: Abdullah Alhasan """ print(""" Welcome to Abdullah's Calculator! Please choose vaild numbers and an operator to be calculated... Calculation example: first number [operation] second number = results """) calc_results = 0 num1= input("Input first number: ") try: num1 = int(num1) except ValueError: print("Invaild values!") else: num2= input("Now, second number: ") try: num2 = int(num2) except ValueError: print("Invaild values!") else: op = input("""Please type in the operator symbol what is between the [..]: [ + ]: Addition [ - ]: Substraction [ x ]: Multiplying [ / ]: Division Type here: """) if op == "+": results = num1 + num2 print(""" {} {} {} = ... answer is {} """.format(num1,op,num2,results)) elif op == '-': results = num1 - num2 print(""" {} {} {} = ... answer is {} """.format(num1,op,num2,results)) elif op.lower() == "x": results = num1 * num2 print(""" {} {} {} = ... answer is {} """.format(num1,op,num2,results)) elif op == "/": results = num1 / num2 print(""" {} {} {} = ... answer is {} """.format(num1,op,num2,results)) else: print("Operator is invaild!")
true
e321759c85fa184f7fdb08811827a36faadc8317
mukesh-jogi/python_repo
/Sem-5/Collections/Set/set1.py
1,960
4.375
4
# Declaring Set set1 = {"Apple","Banana","Cherry","Mango","Pinapple"} print(set1) # Iterate through Set set1 = {"Apple","Banana","Cherry","Mango","Pinapple"} for item in set1: print(item) # Add item to set set1 = {"Apple","Banana","Cherry","Mango","Pinapple"} set1.add("NewFruit") for item in set1: print(item) # Add multiple items in a set set1 = {"Apple","Banana","Cherry","Mango","Pinapple"} set1.update(['Item1','Item2','Item3']) for item in set1: print(item) # Length of set set1 = {"Apple","Banana","Cherry","Mango","Pinapple"} print(len(set1)) # Remove item using remove method # If the item to remove does not exist, remove() will raise an error. set1 = {"Apple","Banana","Cherry","Mango","Pinapple"} set1.remove("Banana") print(set1) # Remove item item using discard method # If the item to remove does not exist, discard() will NOT raise an error. set1 = {"Apple","Banana","Cherry","Mango","Pinapple"} set1.discard("Bananas") print(set1) # Remove item using pop method set1 = {"Apple","Banana","Cherry","Mango","Pinapple"} set1.pop() print(set1) # Clear all items from set using clear() set1 = {"Apple","Banana","Cherry","Mango","Pinapple"} set1.clear() print(set1) # Delete set set1 = {"Apple","Banana","Cherry","Mango","Pinapple"} del set1 print(set1) # Merge sets using union method # Both union() and update() will exclude any duplicate items set1 = {"Apple","Banana","Cherry","Mango"} set2 = {"Mango","Pinapple"} set3 = set1.union(set2) print(set1) print(set2) print(set3) # Merge sets using update method # Both union() and update() will exclude any duplicate items set1 = {"Apple","Banana","Cherry","Mango"} set2 = {"Mango","Pinapple"} set1.update(set2) print(set1) print(set2) # Declaring set using set constructor set1 = set(('Banana','Mango')) print(set1) print(type(set1)) # Copy one set into another set set1 = set(('Banana','Mango')) set2 = set1.copy() set2.add("apple") set1.add("aaa") print(set1) print(set2)
true
a6885c761cbf2d54c530a8a114c7782dabb2631b
Karolina-Wardyla/Practice-Python
/list_less_than_ten/task3.py
400
4.15625
4
# Take a random list, ask the user for a number and return a list that contains only elements from the original list that are smaller than the number given by the user. random_list = [1, 2, 4, 7, 8, 9, 15, 24, 31] filtered_numbers = [] chosen_number = int(input("Please enter a number: ")) for x in random_list: if x < chosen_number: filtered_numbers.append(x) print(filtered_numbers)
true
3b6824ea991b59ccd05b3d42f872c5e8d1313d4a
Karolina-Wardyla/Practice-Python
/divisors/divisors.py
522
4.34375
4
# Create a program that asks the user for a number and then prints out a list of all the divisors of that number. # Divisor is a number that divides evenly into another number. # (For example, 13 is a divisor of 26 because 26 / 13 has no remainder.) chosen_number = int(input("Please enter a number: ")) possible_divisors = range(1, chosen_number // 2 + 1) divisors = [] for number in possible_divisors: if chosen_number % number == 0: divisors.append(number) divisors.append(chosen_number) print(divisors)
true
0a43c57a016eb641a07c8f0e2ed16080da2866b2
Aaron-Nazareth/Code-of-the-Future-NumPy-beginner-series
/6 - Basic operations on arrays.py
707
4.5
4
# Tutorial 6 # Importing relevant modules import numpy as np # We can create an array between numbers like we can do with lists and the 'range' command. # When using arrays, we use the 'arange' command. a = np.arange(0, 5) # Creates an array from 0 up to 5 - [0 1 2 3 4] print(a) # Basic math operations on arrays b = np.array([4, 6, 19, 23, 45]) print(b) # Addition print(a + b) # Subtraction print(b - a) # Square all the elements in a print(a**2) # NumPy actually has it's own functions built in print(np.square(a)) # Testing whether values in an array are less than a given value c = np.array([1, 2, 3, 4]) print(c < 2) # This prints an array of booleans showing whether values are less than 2.
true
9519d25c32ac136ff355e521e4bf36dc80eee71b
meghasundriyal/MCS311_Text_Analytics
/stemming.py
609
4.3125
4
#stemming is the morphological variants of same root word from nltk.tokenize import word_tokenize from nltk.stem import PorterStemmer ps = PorterStemmer() #words to be stemmed (list) stem_words = ["eat", "eats", "eating", "eaten", "eater", "received","receiving"] #find stem word for each of the word in the list for word in stem_words: print(word, " : ",ps.stem(word)) #stemming a sentence ''' 1. tokennize each word 2. find stem word or each word ''' file_content = open("input.txt").read() tokens = word_tokenize(file_content) for word in tokens: print(word ," : ", ps.stem(word))
true
9937cae75d06147093025d2482225550aace9f9a
Reena-Kumari20/code_war
/Reversed_Words.py
213
4.1875
4
# Complete the solution so that it reverses all of the words within the string passed def reverse_words(s): a=(' '.join(s.split(" ")[-1::-1])) return a string=["hell0 world!"] print(reverse_words(string))
true
8b99f60f51da55d805fcfdd13bf0e34bc71b8386
Reena-Kumari20/code_war
/sum_of_string.py
586
4.1875
4
'''Create a function that takes 2 positive integers in form of a string as an input, and outputs the sum (also as a string): Example: (Input1, Input2 -->Output) "4", "5" --> "9" "34", "5" --> "39" Notes: If either input is an empty string, consider it as zero.''' def sum_str(a, b): if a=="" and b=="": return str(0) elif a!="" and b=="": return a elif a=="" and b!="": return b else: sum=int(a)+int(b) x=str(sum) y=type(x) return x,y a=input("string_first:- ") b=input("string_second:- ") print(sum_str(a,b))
true
301a64567164a85abdef442a8672c985776a87e0
jreichardtaurora/hmwk_2_test
/HW2_Prob_1_JaredReichardt.py
1,398
4.3125
4
''' Created on Sep 13, 2019 @author: jared r CSC1700 section AM The purpose of this problem was to write a calculator that calculates the user's total shipping cost. It handles negative inputs properly, and prompts the user for their package weight, and what type of shipping they used. ''' def main(): print("Starting Fast Freight Shipping Company Shipping Calculator") weight = float(input("What was your total package weight (in pounds)? ")) while weight <= 0: weight = float(input("Error, please make sure your weight is a positive number: ")) ship = input("Did you use Expedited (E) or Regular (R) shipping? ") if ship == 'E': shipping = "Expedited" elif ship == 'R': shipping = "Regular" if ship == 'E': if weight <= 2: rate = 1.5 elif weight <= 6: rate = 3.0 elif weight < 10: rate = 4.0 else: rate = 4.75 elif ship == 'R': if weight <= 2: rate = 1.0 elif weight <= 6: rate = 2.0 elif weight <= 10: rate = 3.0 else: rate = 3.5 total = rate * weight print(f"Your total package weight was {weight} pounds.") print(f"Your Selected Shipping was {shipping}.") print("Your total shipping cost will be $" + format(total, '.2f')) main()
true
88b954e1465b806c15318999a4715c0e6c7d7cc4
renatocrobledo/probable-octo-spork
/codingame/src/norm_calculation.py
1,538
4.65625
5
''' You are given an integer matrix of size N * M (a matrix is a 2D array of numbers). A norm is a positive value meant to quantify the "size/length" of an element. In our case we want to compute the norm of a matrix. There exist several norms, used for different scenarios. Some of the most common matrix norms are : - The norm 1: for each column of the matrix, compute the sum of the absolute values of every element in that column. The norm 1 is the maximum of these sums. - The infinite norm: for each row of the matrix, compute the sum of the absolute values of every element in that row. The infinite norm is the maximum of these sums. - The max norm: compute the maximum of the absolute values of every element in the matrix. Given the matrix, print these three norms. Input N the number of rows M the number of columns Next N lines: the M values of each element in the row of the matrix Output A single line: N_1 N_INF N_MAX With : N_1 the norm 1 of the matrix N_INF the infinite norm of the matrix N_MAX the max norm of the matrix ''' # transpose 2D list in Python (swap rows and columns) n = int(input()) m = int(input()) l = [] whole_max = 0 rows = [] for i in range(n): row = list(map(lambda x: abs(int(x)),input().split())) _max = max(row) if _max > whole_max: whole_max = _max rows.append(sum(row)) l.append(row) cols = [] for t in list(zip(*l)): cols.append(sum(t)) norm_1 = max(cols) infinite_norm = max(rows) max_norm = whole_max print(f'{norm_1} {infinite_norm} {max_norm}')
true
88963ec18f118fca69d3e26b3b57db8c5a2736cc
kundan7kumar/Algorithm
/Hashing/basic.py
476
4.1875
4
# Python tuple can be the key but python list cannot a ={1:"USA",2:"UK",3:"INDIA"} print(a) print(a[1]) print(a[2]) print(a[3]) #print(a[4]) # key Error # The functionality of both dictionaries and defualtdict are almost same except for the fact that defualtdict never raises a KeyError. It provides a default value for the key that does not exists. from collections import defaultdict d=defaultdict() d["a"] =1 d["b"] = 2 print(d) print(d["a"]) print(d["b"]) print(d["c"])
true
43a8fae76b90437274501bafd949b39995401233
tongyaojun/corepython-tongyao
/chapter02/Test15.py
430
4.125
4
#!/usr/bin/python #sort input numbers userInput1 = int(input('Please input a number:')) userInput2 = int(input('Please input a number:')) userInput3 = int(input('Please input a number:')) def getBiggerNum(num1, num2): if num1 > num2: return num1 else : return num2 biggerNum = getBiggerNum(userInput1, userInput2) biggestNum = getBiggerNum(biggerNum, userInput3) print('The biggest num is:', biggestNum)
true
c328f75f3d0278660d4d544563b5d953af5b7041
jjti/euler
/Done/81.py
2,016
4.21875
4
def path_sum_two_ways(test_matrix=None): """ read in the input file, and find the sum of the minimum path from the top left position to the top right position Notes: 1. Looks like a dynamic programming problem. Ie, start bottom right and find the sum of the minimum path from the current square to the bottom right """ matrix = test_matrix if test_matrix is None: # import the downloaded matrix matrix = [] with open("81.input.txt") as matrix_file: for line in matrix_file: matrix.append([int(num) for num in line.split(",")]) # initialize distances at None min_path = [[None] * len(matrix)] * len(matrix) max_ind = len(matrix) - 1 # it's a square matrix for i in range(max_ind, -1, -1): # vertical for j in range(max_ind, -1, -1): # horizontal if i == max_ind and j == max_ind: # we're in the bottom right corner min_path[i][j] = matrix[i][j] elif j == max_ind and i < max_ind: # we're along the right side of the matrix # have to go down min_path[i][j] = matrix[i][j] + min_path[i + 1][j] elif j < max_ind and i == max_ind: # we're along the bottom of the matrix # have to go right min_path[i][j] = matrix[i][j] + min_path[i][j + 1] else: # we're not up against either side of the matrix # find the minimum route from this to the right or downwards min_path[i][j] = matrix[i][j] + min( [min_path[i + 1][j], min_path[i][j + 1]]) return min_path[0][0] assert path_sum_two_ways([[131, 673, 234, 103, 18], [201, 96, 342, 965, 150], [630, 803, 746, 422, 111], [537, 699, 497, 121, 956], [805, 732, 524, 37, 331]]) == 2427 print(path_sum_two_ways()) # output: 427337 in 0.056 seconds
true
b3cca4d969aa2be4ad517aad8d903ae2826da02d
jjti/euler
/Done/65.py
2,141
4.1875
4
import utils """ The square root of 2 can be written as an infinite continued fraction. The infinite continued fraction can be written, 2**0.5 = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a similar way, 23**0.5 = [4;(1,3,1,8)]. It turns out that the sequence of partial values of continued fractions for square roots provide the best rational approximations. Let us consider the convergents for 2**0.5. Hence the sequence of the first ten convergents for 2**0.5 are: 1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ... What is most surprising is that the important mathematical constant, e = [2; 1,2,1, 1,4,1, 1,6,1 , ... , 1,2k,1, ...]. The first ten terms in the sequence of convergents for e are: 2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ... The sum of digits in the numerator of the 10th convergent is 1+4+5+7=17. Find the sum of digits in the numerator of the 100th convergent of the continued fraction for e. """ def denom_seq(length=30): """ What is most surprising is that the important mathematical constant, e = [2; 1,2,1, 1,4,1, 1,6,1 , ... , 1,2k,1, ...]. make that seq ^ """ return [2 * (i / 3) if not i % 3 else 1 for i in range(2, length + 2)] assert denom_seq(9) == [1, 2, 1, 1, 4, 1, 1, 6, 1] def convergence_of_e(upper_limit=100): """ increment the fraction until we reach upper limit sum the digits in the numerator after incrementing target number of times Notes: 1. the multiplier here (in the denom_seq above), is like a multiplier for the numerator and denominator when calculating the next fraction 2. if p, q is the next numerator and denominator, and we have a, b and c, d as the n-1 and n fractions: p = a + multiplier(c) q = b + multiplier(d) 3. aannndddd the denominator has nothing to do with it... """ # a and b are last and current numerators a, b = 2, 3 for multiplier in denom_seq(upper_limit - 1)[1:]: a, b = b, a + multiplier * b return sum(utils.split(b)) assert convergence_of_e(10) == 17 # outputs 272 in 0.05 seconds print convergence_of_e(100)
true
d6a3a1abfac543f817434f9b903515db63993c02
jjti/euler
/Done/57.py
1,511
4.125
4
import utils """ It is possible to show that the square root of two can be expressed as an infinite continued fraction. 2 ** 1/2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213... By expanding this for the first four iterations, we get: 1 + 1/2 = 3/2 = 1.5 1 + 1/(2 + 1/2) = 7/5 = 1.4 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666... 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379... The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator. In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator? """ def SquareOfTwoGenerator(limit=1000): """ numerators = 3, 7, 17, 41, 99 denominators = 2, 5, 12, 29, 70 the next numerator is the current numerator + 2 times the last denominator the next denominator is the sum of the current numerator and denominator """ index, num, den = 0, 3, 2 while index < limit: """set the next numerator and denominator return whether the numerator has more digits than the denominator (see above)""" hit = len(utils.split(num)) > len(utils.split(den)) num, den = num + 2 * den, num + den index += 1 yield hit # now run thru the iterator and accumulate all the hits count = 0 for numerBiggerThanDenom in SquareOfTwoGenerator(): if numerBiggerThanDenom: count += 1 print(count)
true
4c28efd8124035ef404c5cdabf8279a25ffdead2
nasingfaund/Yeppp-Mirror
/codegen/common/Argument.py
1,926
4.4375
4
class Argument: """ Represents an argument to a function. Used to generate declarations and default implementations """ def __init__(self, arg_type, name, is_pointer, is_const): self.arg_type = arg_type self.name = name self.is_pointer = is_pointer self.is_const = is_const @property def arg_type(self): """ This is the type of the argument with no qualifiers, and if it is a pointer, it is the type pointed to e.g const Yep8s *x -> Yep8s """ return self.arg_type @property def full_arg_type(self): """ This is the type of the argument including qualifiers like const, pointers etc. """ ret = "" if self.is_const: ret += "const " ret += self.arg_type + " " if self.is_pointer: ret += "*YEP_RESTRICT " return ret @property def name(self): return self.name @property def is_pointer(self): return self.is_pointer @property def is_const(self): return self.is_const @property def declaration(self): """ Returns the declaration needed in a C function """ ret = "" if self.is_const: ret += "const " ret += self.arg_type + " " if self.is_pointer: ret += "*YEP_RESTRICT " ret += self.name return ret @property def size(self): """ Get the size of the argument, e.g Yep8s -> 8. This is needed to generate the right alignment checks """ ret = "" for c in self.arg_type: if c.isdigit(): ret += c return ret @property def data_type_letter(self): """ Returns s if signed, u if unsigned, f if floating-point """ return self.arg_type[-1]
true
7432e574d515aadac24d93b6aa1568d3add65fc6
johnpospisil/LearningPython
/try_except.py
873
4.21875
4
# A Try-Except block can help prevent crashes by # catching errors/exceptions # types of exceptions: https://docs.python.org/3/library/exceptions.html try: num = int(input("Enter an integer: ")) print(num) except ValueError as err: print("Error: " + str(err)) else: # runs if there are no errors print('No errors.') finally: # runs always, whether there is an exception or not print('Finally clause.') # make your own exceptions classes class ValueTooHighError(Exception): pass def test_value(x): if x > 100: raise ValueTooHighError('value is too high') print(test_value(200)) # exceptions can be raised at will too x = -5 if x < 0: raise Exception('exception: x should be positive') # assert statements - below, assert than x is gretaer than or equal to 0, raise an assert error if False assert (x >= 0), 'x is negative'
true
d78585044147f77090dc54494e1a3c24b36c5b37
johnpospisil/LearningPython
/while_loops.py
592
4.21875
4
# Use While Loops when you want to repeat an action until a certain condition is met i = 1 while i <= 10: print(i, end=' ') i += 1 print("\nDone with loop") # Guessing Game secret_word = "forge" guess = "" guess_count = 0 guess_limit = 3 out_of_guesses = False print("\nGUESSING GAME") while guess != secret_word and not(out_of_guesses): if guess_count < guess_limit: guess = input("Enter the secret word: ") guess_count += 1 else: out_of_guesses = True if out_of_guesses: print("Out of guesses. You lose.") else: print("You guessed it!")
true
9fc9df1a3b6028dffaae5efdfacc2b5577929ce2
lihaoyang411/My-projects
/Encryption-Bros-master/Main.py
1,947
4.15625
4
import sys typeChosen = 0 def choose(choice): while True: if choice.find(".") >= 0 or choice.find("-") >= 0: choice = input("You didn't type in a positive integer. Please try again: ") else: try: choice = int(choice) dummyNum = 2/choice if choice == 1 or choice == 2 or choice == 3: break else: choice = input("You didn't type a valid choice. Please try again: ") except ValueError: choice = input("You didn't type in a positive integer. Please try again: ") except ArithmeticError: choice = input("You didn't type in a positive integer. Please try again: ") print("") return choice def main(): morseCount = 0 pigCount = 0 imageCount = 0 while(1): choice = input("What would you like to do? Please select an option below:\n1. Edit a text file\n2. Edit an image\n3. Exit Program\n\nEnter your choice: ") choice = choose(choice) if choice == 1: choice = input("Would you like to encrypt a text file into Morse/Vig Cypher or Pig Latin/Hashing?\n1. Morse/Vig Cypher\n2. Pig Latin/Hashing\n\nEnter your choice: ") choice = choose(choice) if choice == 1: if morseCount == 0: import morse morseCount += 1 else: morse.main() else: if pigCount == 0: import piglatin pigCount += 1 else: piglatin.main() elif choice == 2: if imageCount == 0: import EncryptImage imageCount += 1 else: EncryptImage.main() else: print("Exiting program...\n") sys.exit() main()
true
23334bd9745a107a337460c8cd4a2b8dcfa6a52d
Shiliangwu/python_work
/hello_world.py
1,037
4.21875
4
# this is comment text # string operation examples message="hello python world" print(message) message="hello python crash course world!" print(message) message='this is a string' message2="this is also a string" print(message) print(message2) longString='I told my friend, "Python is my favorite language!"' print(longString) name="ada lovelace" print(name.title()) print(name.upper()) print(name.lower()) print(name.lower().upper()) fullString=message2+" AND "+longString print(fullString) print("hello,"+fullString.title()+"!") # tab print("Python") print("\tPython") print("Language:\n\tPython\n\t\tJavaScripy") # delete extra spaces. favorite_language=' Python with blanks ' print(favorite_language) print(favorite_language.rstrip()) print(favorite_language.lstrip()) print(favorite_language) message = "One of Python's strengths is its diverse community." print(message) message = 'One of Python"s strengths is its diverse community.' print(message) def yourchoice(): print("my choice") yourchoice()
true
bde6d52ed8e8578510e2e3ed47ca03fd13172c33
anindo78/Udacity_Python
/Lesson 3 Q2.py
698
4.15625
4
# Define a procedure, greatest, # that takes as input a list # of positive numbers, and # returns the greatest number # in that list. If the input # list is empty, the output # should be 0. def greatest(list_of_numbers): if len(list_of_numbers) == 0: return 0 else: maximum = list_of_numbers[0] if len(list_of_numbers) > 0: for i in list_of_numbers: maximum = max(maximum, i) return maximum print greatest([4,23,1]) #>>> 23 print greatest([]) #>>> 0 #More elegant solution def greatest(list_of_numbers): maximum = 0 for i in list_of_numbers: if i > maximum: maximum = i return maximum
true
0fc6e1ae13fecbc47013ddecc2b29ef71f13b8c6
hamsemare/sqlpractice
/291projectReview.py
2,985
4.28125
4
import sqlite3 connection = None cursor = None name= None # Connect to the database def connect(path): global connection, cursor connection=sqlite3.connect(path) cursor=connection.cursor() def quit(): exit(0) def findName(): global name studentName= input("Enter Student Name: ") if(studentName=="q" or studentName=="Q"): quit() cursor.execute(''' select * from students where studentName==? ''', (studentName,)) num=cursor.fetchall() for i in num: j=''.join(i) name= studentName if(num==[]): return True return False def login(): print("\n"*10) print("LOGIN") print("--"*5) print("\n") while True: check= findName() if(check): print("Name does not Exist!!!") l=input("Do you want to Create an Account, enter y if Yes: ") if(l=="q" or l=="Q"): return elif(l=="y" or l=="Y"): create() return else: print("\n") else: # Login print("Successful Login !!!") return def create(): global connection, cursor print("\n"*10) print("CREATE AN ACCOUNT") print("--"*10) print("\n") while True: check= findName() if(check): # Good create an account cursor.execute(''' insert into students values (?)''', (name,)) connection.commit() print("Account Created!!!!!") login() return else: print("Name is Taken!!!") l=input("Do you want to login, enter y if Yes: ") if(l=="q" or l=="Q"): return elif(l=="y" or l=="Y"): login() return else: print("\n") def vCourses(): global connection, cursor, name print("\n"*10) print("View Courses") print("--"*10) print("\n") cursor.execute(''' select courseName from Courses where studentName=(?)''', (name,)) aCourse=[] courses= cursor.fetchall() for i in courses: course=''.join(i) aCourse.append(course) print("COURSES") print("--"*10) if(len(aCourse)==0): print("NONE") else: for i,j in enumerate(aCourse): num=i+1 print("Course", num, ": "+ j) print("\n") def aCourses(): global connection, cursor, name print("\n"*10) print("Add Courses") print("--"*10) print("\n") courseName= input("Enter Course Name: ") if(courseName=="q" or courseName=="Q"): quit() else: cursor.execute(''' insert into courses values (?,?,?)''', (courseName, 3, name ) ) connection.commit() # Main client/User interface def main(): global connection, cursor path= "./291database.db" connect(path) print("Welcome:") print("--"*5) print("\n") print("To quit enter q. ") log= input("To Login enter l, or to Create an Account enter anything else: ") # Validate login or create account info if(log=="q" or log=="Q"): quit() elif(log=="l" or log=="L"): login() else: create() # Courses while True: print("To quit, enter 'q' or 'Q'") c= input("To view courses enter 'v' , enter anything else to add courses: ") if(c=="Q" or c=="q"): quit() if(c=="v" or c=="V"): vCourses() else: aCourses() main()
true
3f30bad898e7fbaa90495f3f609f6f6c3d43ba78
HunterOreair/Portflio
/RollDie.py
942
4.1875
4
#A simple python program that rolls die and returns the number that has been rolled. Made by Hunter Oreair. from random import randint # imports randint. duh. min = 1 #sets the minimum value on the dice that you can roll max = 6 #sets the maximum value def die(): # Creates a method called die rollDie = randint(min, max) # sets what number you rolled print("You rolled a", rollDie) # prints the number you rolled def rollAgain(): again = True while again: #while 'again' is True, do the following: die() # calls the die method. print("Would you like to roll again? y/n") #asks if you would like to roll again. ans = input() #takes your input if ans == "y": #if your input equals 'y' then run the while loop again again = True else: #anything will end the program again = False rollAgain() # calls rollAgain method, running the program.
true
464d00436d9c90def53af9f7b1717e16f1031b23
JerryCodes-dev/hacktoberfest
/1st Assignment.py
884
4.15625
4
# NAME : YUSUF JERRY MUSAGA # MATRIC NUMBER : BHU/19/04/05/0056 # program to find the sum of numbers between 1-100 in step 2 for a in range(1,100,2): print(a) num = 1 while num < 100: print(num) num += 2 # program to find all even numbers between 1-100 for b in range(2,100,2): print (b) numb = 2 while numb < 100: print(numb) numb += 2 # program to find the solution to this equation 2x + 3y + 1 x = float(input('Enter a number for x:')) y = float(input('Enter a number for y:')) c = 2*(x) + 3*(y) + 1 print(c) def equation(x,y): c = 2*(x) + 3*(y) + 1 return c # print in any value for x and y print(equation(2,3)) # average age of students in class age = float(input('Enter Age: ')) totalAge = age sum = 0 while age > 0: sum += age age -= 1 print('Sum of the ages:', sum) averageAge = sum / totalAge print('Average age is: ' , averageAge)
true
5cc890b202f98bb88b5d614c43745cf2b427b0e4
CoffeePlatypus/Python
/Class/class09/exercise1.py
893
4.6875
5
# # Code example demonstrating list comprehensions # # author: David Mathias # from os import listdir from random import randint from math import sqrt print # create a list of temps in deg F from list of temps in deg C # first we create a list of temps in deg C print('Create a list of deg F from a list of deg C temperatures:') print dC = [-40, 0, 10, 20, 30, 40, 100] dF = [1.8 * c + 32 for c in dC] print('dC: {}'.format(dC)) print('dF: {}'.format(dF)) print # in this version, we use a list comprehension to create the # list of degrees C -- a comprehension inside a comprehension print('Create a list of deg F from a list of degC temperatures.') print('deg C temps generated randomly by list comprehenstion') print('within the conversion list comprehension:') print dF = [int(1.8 * c + 32) for c in [randint(0, 100) for i in range(8)]] print('deg F for random deg C: {}'.format(dF)) print
true
7185ccd8e4a6913a24efb58ee17692112564b4d7
CoffeePlatypus/Python
/Class/class03/variables.py
804
4.125
4
# # Various examples related to the use of variables. # # author: David Mathias # x = 20 print type(x) print y = 20.0 print type(y) print s = "a" print type(s) print c = 'a' print type(c) print b = True print type(b) print print('8/11 = {}'.format(8/11)) print print('8.0/11 = {}'.format(8.0/11)) print print('float(8)/11 = {}'.format(float(8)/11)) print s = '12' print('int(s) = '.format(int(s))) print('int(s) + 10 = {}'.format(int(s) + 10)) # the next line would give an error # print('s + 10 = {}'.format(s+10)) print pi = 3.14159 print('int(pi) = {}'.format(int(pi))) print s1 = 'This is ' s2 = 'a test.' print 's1 = ' + s1 print 's2 = ' + s2 print('s1 + s2 = {}'.format(s1 + s2)) print s3 = s1 + s2 print('s3 = s1 + s2. s3 = ' + s3) print s = 'Spam ' print('s = Spam. s*4 = ' + s*4) print
true
3e8ea3989cf216ab53e9a493b07ea974dbe17091
rp927/Portfolio
/Python Scripts/string_finder.py
585
4.125
4
''' In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left. ''' def count_substring(string, sub_string): ls = [] o = 0 count = 0 l = len(sub_string) sub_ls = [sub_string] while l <= len(string): ls.append(string[o:l]) o += 1 l += 1 for _ in ls: if _ in sub_ls: count += 1 return count ''' Sample input: ABCDCDC CDC Sample output: 2 '''
true
0fa7471aa14fec407c4b491a338ffaf70f530183
lherrada/LeetCode
/stacks/problem1.py
741
4.28125
4
# Check for balanced parentheses in Python # Given an expression string, write a python program to find whether a given string has balanced parentheses or not. # # Examples: # # Input : {[]{()}} # Output : Balanced # # Input : [{}{}(] # Output : Unbalanced from stack import Stack H = {'{': '}', '[': ']', '(': ')'} def checkifbalanced(myinput): stack = Stack() for i in myinput: if i in H.keys(): stack.push(i) else: if len(stack) > 0 and H[stack.pop()] == i: continue else: return False return False if len(stack) > 0 else True myinput = '([[[{}]]](' if checkifbalanced(myinput): print("Balanced") else: print("Unbalanced")
true
4c4cbbf75cd598226f55a08b967597dde477e7a3
odemeniuk/twitch-challenges
/interview/test_palindrome.py
336
4.40625
4
# write a function that tells us if a string is a palindrome def is_palindrome(string): """ Compare original string with its reverse.""" # [::-1] reverses a string reverse = string[::-1] return string == reverse def test_is_palindrome(): assert is_palindrome('banana') is False assert is_palindrome('foof')
true
d8f9c69874ca0ab5da4dac704f88fedb77b1b30d
dragonRath/PythonBasics
/stringformatting.py
2,162
4.53125
5
#The following will illustrate the basic string formatting techniques used in python age = 24 #print("My age is " + str(age) + " years\n") print("My age is {0} years".format(age)) #{} Replacement brackets print("There are {0} days in {1}, {2}, {3}, {4}, {5}, {6} and {7}".format(31, "January", "March", "May", "July", "August", "October", "December")) print("""January: {2} Feburary: {0} March: {2} April: {1} May: {2} June: {1} July: {2} August: {2} Septemeber: {1} October: {2} November: {1} December: {2}""". format(28, 30, 31)) print("\nGrael Knight said: 'Hello'" + " Avi") print("\nMy age is %d years" %age) print("\nMy age is %d %s, %d %s" %(age, "years", 6, "months")) #%d is int, %s is string; this replacement stands for all the variables for i in range(1, 12): # ** means to the power of. %d = integer, %s = String, %f = Float print("Number %2d squared is %4d and cubed is %4d" %(i, i ** 2, i ** 3)) #The 2 or 4 before the %d is for allocating space. String formating. print ("Pi is approximately %12f" %(22 / 7)) #Default float precision print ("Pi is approximately %12.50f" %(22 / 7)) #50 decimal point precision print ("Pi is approximately %0.50f" %(22 / 7)) #50 decimal point precision without giving extra space to the float. for i in range(1, 12): #In {:}, the first no. is the replacement field whereas the second one is the width of the field. Don't put space between the colons. Gives an error. print("Number {0:2} squared is {1:4} and cubed is {2:4}".format(i, i ** 2, i ** 3)) #Don't put space between the colons. Gives an error. for i in range(1, 12): #The < symbol justifies the left hand side, ie, it starts from the left instead of allocation from the right. print("Number {0:2} squared is {1:<4} and cubed is {2:<4}".format(i, i ** 2, i ** 3)) print ("Pi is approximately {0:12.50}".format(22 / 7)) #Using replacement fields syntax print("January: {2}, Feburary: {0}, March: {2}, April: {1}, May: {2}, June: {1}, July: {2}, August: {2}, Septemeber: {1}, October: {2}, November: {1}, December: {2}".format(28, 30, 31)) for i in range(1, 12): print("No. {} squared is {} and cubed is {:4}".format(i, i ** 2, i ** 3))
true
c603d6ab0955cfc0100daa3a9c4c37cceb58876c
loweryk/CTI110
/p3Lab2a_lowerykasey.py
1,026
4.46875
4
#Using Turtle in Python #CTI-110 P3LAB2a_LoweryKasey import turtle #Allows us to use turtles wn = turtle.Screen() #Creates a playground for turtles alex = turtle.Turtle() #Creatles a turtle, assign to alex #commands from here to the last line can be replaced alex.hideturtle() #Hides the turtle in icon #For the loop that iterates 4 times to draws a square #Tell alex to draw a square alex.right(90) #Tell alex to move right by 90 units alex.forward(50) #Tell alex to move forward by 50 units alex.left(90) #Tell alex to move left by 90 units alex.forward(100) #Tell alex to move forward by 100 units alex.left(90) alex.forward(100) alex.left(90) alex.forward(100) alex.left(90) alex.forward(50) alex.forward(80) #Tells alex to draw a specific triangle alex.left(120) alex.forward(80) alex.left(120) alex.forward(80) alex.left(120) #ends commands wn.mainloop() #wait for user to close window
true
f643f39546ae35916bf1147df22e1bdfddfd4972
sheriaravind/Python-ICP4
/Source/Code/Num-Py -CP4.py
359
4.28125
4
import numpy as np no=np.random.randint(0,1000,(10,10)) # Creating the array of 10*10 size with random number using random.randint method print(no) min,max = no.min(axis=1),no.max(axis=1) # Finding the minimum and maximum in each row using min and max methods print("Minimum elements of 10 size Array is",min) print("Maximum elements of 10 size Array is",max)
true
3fb3edce524850dfdc618bc407b47c3f57d89978
TENorbert/Python_Learning
/learn_python.py
637
4.125
4
#!/usr/bin/python """ python """ ''' first_name = input("Enter a ur first name: ") last_name = input("Enter your last name: ") initial = input("Enter your initial: ") person = initial + " " + first_name + " " + last_name print("Ur name is %s" %person) print("Ur name is %s%s%s" %initial %first_name %last_name) ''' catNames = [] while True: print('Enter the name of cat ' + str(len(catNames) + 1) + '(or enter Nothing to stop.):') name = input() if name == '': break catNames = catNames + [name] ##Append indirectly using list concatenation print('The cat names are:') for name in catNames: print(' ' + name)
true
25b1a46a621054c7d04da0e02ce0acc6181c46eb
keithrpotempa/python-book1
/sets/cars.py
1,539
4.21875
4
# Create an empty set named showroom. showroom = set() # Add four of your favorite car model names to the set. showroom.update(["Car1", "Car2", "Car3", "Car4"]) # Print the length of your set. print("Showroom length", len(showroom)) # Pick one of the items in your show room and add it to the set again. showroom.update(["Car1"]) # Print your showroom. Notice how there's still only one instance of that model in there. print(showroom) # Using update(), add two more car models to your showroom with another set. showroom.update({"Car5", "Car6"}) print(showroom) # You've sold one of your cars. Remove it from the set with the discard() method. showroom.discard("Car1") print(showroom) # Now create another set of cars in a variable junkyard. Someone who owns a junkyard full of old cars has approached you about buying the entire inventory. In the new set, add some different cars, but also add a few that are the same as in the showroom set. junkyard = set() junkyard.update(["Car2", "Junk1", "Junk2", "Junk3"]) print(junkyard) # Use the intersection method to see which cars exist in both the showroom and that junkyard. print("Intersection", showroom.intersection(junkyard)) # Now you're ready to buy the cars in the junkyard. Use the union method to combine the junkyard into your showroom. new_showroom = showroom.union(junkyard) print(new_showroom) # Use the discard() method to remove any cars that you acquired from the junkyard that you do not want in your showroom. new_showroom.discard("Junk1") print(new_showroom)
true
d4a524ea19b19afd811e32a9f0c58916b4cabb8f
BrutalCoding/INFDEV01-1_0912652
/DEV_01_1___Assignment_4___Exercise_1.b/DEV_01_1___Assignment_4___Exercise_1.b/DEV_01_1___Assignment_4___Exercise_1.b.py
227
4.25
4
celcius = -273.15 #This is the default value to trigger the while loop here below while celcius <= -273.15: celcius = input("Enter Celcius to convert it to Kelvin:\n") print "Celcius:", celcius, "Kelvin = ", celcius+273.15
true
b0985c06edbb8bc0ff8d86e3f7b5772d204954a3
olivepeace/ASSIGNMENT-TO-DETERMINE-DAYOF-BIRTH
/ASSIGNMENT TO DETERMINE DAY OF BIRTH.py
1,960
4.375
4
""" NAME: NABUUMA OLIVIA PEACE COURSE:BSC BIOMEDICAL ENGINEERING REG NO: 16/U/8238/PS """ import calendar print("This Program is intended to determine the exact day of the week you were born") print(".....................................................") day = month = year = None #Next code ensures that only and only integers input while(day == None): try: day = int(input("PLEASE TYPE IN YOUR DAY OF YOUR BIRTH:")) while(day not in range(1, 32)): print("this is not a day") day = int(input("PLEASE TYPE IN YOUR DAY OF BIRTH:")) except: print("Please type in numbers only") print() while(month == None): try: month = int(input("PLEASE TYPE IN YOUR MONTH OF BIRTH:")) while(month not in range(1, 13)): print("Mr or Lady, months move from Jan, To December. thats twelve, not %d or whatever you've input" % month) month = int(input("PLEASE TYPE IN YOUR MONTH OF BIRTH AGAIN: ")) except: print("Please type in numbers only") print() while(year == None): try: year = int(input("PLEASE TYPE IN YOUR YEAR OF BIRTH: ")) while(year not in range(1000, 2500)): if(year >= 2500): print("No offense but by %d, you'll be dead, ALREADY. So please, type in " % year) year = int(input("PLEASE TYPE IN YOUR YEAR OF BIRTH ")) if(year < 1000): print("By then you were not born. Unless you are immortal") year = int(input("PLEASE TYPE IN YOUR YEAR OF BIRTH: ")) except: print("Please type in numbers only") print() #this outputs the day in form of numbers from 0 - 6 date = calendar.weekday(year, month, day) exact = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] print("You were born on ", exact[date]) input("press Enter to exit")
true
afad2695aa4dff1ce100cfaf65cbdcca9b6c37d4
RaazeshP96/Python_assignment1
/function12.py
305
4.3125
4
''' Write a Python program to create a function that takes one argument, and that argument will be multiplied with an unknown given number. ''' def multi(n): a = int(input("Enter the number:")) return f"The required result is { n * a }" n = int(input("Enter the integer:")) print(multi(n))
true
8c225b5b0ac4648cfa8e555b9aaf74312d89484f
RaazeshP96/Python_assignment1
/function16.py
237
4.25
4
''' Write a Python program to square and cube every number in a given list of integers using Lambda. ''' sq=lambda x:x*x cub=lambda x:x*x*x n=int(input("Enter the integer:")) print(f"Square -> {sq(n)}") print(f"Cube -> {cub(n)}")
true
d7a0eaf524bd36baf8ef17e6aab4147e32e61e9b
DeepuDevadas97/-t2021-2-1
/Problem-1.py
1,046
4.21875
4
class Calculator(): def __init__(self,a,b): self.a=a self.b=b def addition(self): return self.a+self.b def subtraction(self): return self.a-self.b def multiplication(self): return self.a*self.b def division(self): return self.a/self.b repeat = 1 while repeat != 0: print("_____________________CALCULATOR_______________________________") a=float(input("Enter 1st number : ")) b=float(input("Enter 2nd number : ")) obj=Calculator(a,b) operator = input("Enter type of operation [+] [-] [*] [/] : ") if operator == "+": print("Result : ",obj.addition()) elif operator == "-": print("Result : ",obj.subtraction()) elif operator == "*": print("Result : ",obj.multiplication()) elif operator == "/": print("Result : ",obj.division()) else: print("Invalid Operator !!")
true
22b5e71d891a902473213c464125bea0ca1526c6
kelpasa/Code_Wars_Python
/5 кю/RGB To Hex Conversion.py
971
4.21875
4
''' The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value. Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here. The following are examples of expected output values: rgb(255, 255, 255) # returns FFFFFF rgb(255, 255, 300) # returns FFFFFF rgb(0,0,0) # returns 000000 rgb(148, 0, 211) # returns 9400D3''' def rgb(*color): arr = [] for i in color: if i < 0: arr.append(hex(0).replace('0x','')) elif i > 255: arr.append(hex(255).replace('0x','')) else: arr.append(hex(i).replace('0x','')) res = [] for i in arr: if len(i) == 1: res.append('0'+i) else: res.append(i) return ''.join(res).upper()
true
efe2f3dd96140dfb7ca59d5a5571e6c031491273
kelpasa/Code_Wars_Python
/5 кю/Scramblies.py
430
4.15625
4
''' Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false. Notes: Only lower case letters will be used (a-z). No punctuation or digits will be included. Performance needs to be considered ''' def scramble(s1,s2): for letter in set(s2): if s1.count(letter) < s2.count(letter): return False return True
true
4d26fc6d60a59ad20aec5456cf32bc6588018139
kelpasa/Code_Wars_Python
/6 кю/String transformer.py
489
4.40625
4
''' Given a string, return a new string that has transformed based on the input: Change case of every character, ie. lower case to upper case, upper case to lower case. Reverse the order of words from the input. Note: You will have to handle multiple spaces, and leading/trailing spaces. For example: "Example Input" ==> "iNPUT eXAMPLE" You may assume the input only contain English alphabet and spaces. ''' def string_transformer(s): return ' '.join(s.swapcase().split(' ')[::-1])
true
a62713c957216d00edf4dbb925e5f561f94c4cf2
kelpasa/Code_Wars_Python
/6 кю/Sort sentence pseudo-alphabetically.py
1,238
4.3125
4
''' Given a standard english sentence passed in as a string, write a method that will return a sentence made up of the same words, but sorted by their first letter. However, the method of sorting has a twist to it: All words that begin with a lower case letter should be at the beginning of the sorted sentence, and sorted in ascending order. All words that begin with an upper case letter should come after that, and should be sorted in descending order. If a word appears multiple times in the sentence, it should be returned multiple times in the sorted sentence. Any punctuation must be discarded. Example For example, given the input string "Land of the Old Thirteen! Massachusetts land! land of Vermont and Connecticut!", your method should return "and land land of of the Vermont Thirteen Old Massachusetts Land Connecticut". Lower case letters are sorted a -> l -> l -> o -> o -> t and upper case letters are sorted V -> T -> O -> M -> L -> C.''' import re def pseudo_sort(st): st, upper, lower = re.sub(r'[^ \w]','',st).split(), [], [] for i in st: if i[0].islower(): lower.append(i) else: upper.append(i) return ' '.join(sorted(lower) + sorted(upper)[::-1])
true
4804ed7aa18e361bf99084a6d1f2390b18d8bb8a
kelpasa/Code_Wars_Python
/5 кю/Emirps.py
1,045
4.3125
4
''' If you reverse the word "emirp" you will have the word "prime". That idea is related with the purpose of this kata: we should select all the primes that when reversed are a different prime (so palindromic primes should be discarded). For example: 13, 17 are prime numbers and the reversed respectively are 31, 71 which are also primes, so 13 and 17 are "emirps". But primes 757, 787, 797 are palindromic primes, meaning that the reversed number is the same as the original, so they are not considered as "emirps" and should be discarded. ''' from math import log, ceil def makeSieveEmirp(n): sieve, setPrimes = [0]*n, set() for i in range(2, n): if not sieve[i]: setPrimes.add(i) for j in range(i**2, n, i): sieve[j] = 1 return { n for n in setPrimes if n != int(str(n)[::-1]) and int(str(n)[::-1]) in setPrimes } def find_emirp(n): setEmirp = makeSieveEmirp( 10**(int(ceil(log(n,10)))) ) crunchL = [p for p in setEmirp if p <= n] return [len(crunchL), max(crunchL), sum(crunchL)]
true
3f821ad7f3538a1066e56a6c8737932fcbda94b0
kelpasa/Code_Wars_Python
/6 кю/Parity bit - Error detecting code.py
1,118
4.21875
4
''' In telecomunications we use information coding to detect and prevent errors while sending data. A parity bit is a bit added to a string of binary code that indicates whether the number of 1-bits in the string is even or odd. Parity bits are used as the simplest form of error detecting code, and can detect a 1 bit error. In this case we are using even parity: the parity bit is set to 0 if the number of 1-bits is even, and is set to 1 if odd. We are using them for the transfer of ASCII characters in binary (7-bit strings): the parity is added to the end of the 7-bit string, forming the 8th bit. In this Kata you are to test for 1-bit errors and return a new string consisting of all of the correct ASCII caracters in 7 bit format (removing the parity bit), or "error" in place of ASCII characters in which errors were detected. ''' def parity_bit(binary): lst = [] for i in binary.split(): if (i.count('1') % 2 == 0 and i[-1] == '0') or (i.count('1') % 2 == 0 and i[-1] == '1'): lst.append(i[:-1]) else: lst.append('error') return ' '.join(lst)
true
ab10772302efd8e44c5b0d5a157587cbeea7ce62
kelpasa/Code_Wars_Python
/6 кю/Multiplication table.py
424
4.15625
4
''' our task, is to create NxN multiplication table, of size provided in parameter. for example, when given size is 3: 1 2 3 2 4 6 3 6 9 for given example, the return value should be: [[1,2,3],[2,4,6],[3,6,9]] ''' def multiplicationTable(n): table = [] for num in range(1, n+ 1): row = [] for colum in range(1, n + 1): row.append(num * colum) table.append(row) return table
true
9180bd22fb2a47c8276454dda65caa58fd5116ce
kelpasa/Code_Wars_Python
/6 кю/Matrix Trace.py
1,236
4.34375
4
''' Calculate the trace of a square matrix. A square matrix has n rows and n columns, where n is any integer > 0. The entries of the matrix can contain any number of integers. The function should return the calculated trace of the matrix, or nil/None if the array is empty or not square; you can otherwise assume the input will be valid (of the form described below). The trace of an n-by-n square matrix A is defined to be the sum of the elements on the main diagonal (the diagonal from the upper left to the lower right) of A. A matrix will be defined as an array of arrays, where the 1st entry represents the 1st row, the 2nd entry the 2nd row, and so on. For example, the following code... [[1, 2, 3], [4, 5, 6], [7, 8, 9]] represents the matrix |1 2 3| |4 5 6| |7 8 9| which has a trace of 1 + 5 + 9 = 15.''' from itertools import chain def trace(matrix): try: if matrix == []: return None elif len(list(chain(*matrix)))// len(matrix[0]) != len(matrix[0]): return None else: diagonal = [] for i in range(len(matrix)): diagonal.append(matrix[i][i]) return sum(diagonal) except ZeroDivisionError: return None
true