blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
2be6e85839802e5365e65ee47d09f914d388f198
rajdharmkar/Python2.7
/methodoverloading1.py
606
4.25
4
class Human: def sayHello(self, name=None): if name is not None: print 'Hello ' + name else: print 'Hello ' # Create instance obj = Human() # Call the method obj.sayHello() # Call the method with a parameter obj.sayHello('Rambo') #obj.sayHello('Run', 'Lola');TypeError takes at most 2 args given 3 args #obj.sayHello('Run', 'Lola', "Run"); TypeError takes at most 2 args given 4 args '''Output: Hello Hello Rambo To clarify method overloading, we can now call the method sayHello() in two ways: obj.sayHello() obj.sayHello('Rambo')'''
true
825180decbe595ad5ec6b84511f97661ae28a121
NANGSENGKHAN/cp1404practicals
/prac02/exceptions_demo.py
1,046
4.53125
5
try: numerator = int(input("Enter the numerator: ")) denominator = int(input("Enter the denominator: ")) while denominator == 0: print("Denominator cannot be zero") denominator = int(input("Enter the denominator: ")) fraction = numerator / denominator print(fraction) except ValueError: print("Numerator and denominator must be valid numbers!") except ZeroDivisionError: print("Cannot divide by zero!") print("Finished.") """1.When will a ValueError occur? A ValueError occur when a built-in operation or function receives an argument that has the right type but am inappropriate value, and the situation is not described by a more precise exception such as IndexError. 2.When will a ZeroDivision occur? ZeroDivision occur when attempting to divide a number by zero. 3.Could you change the code to avoid the possibility of a ZeroDivisionError? If you could figure out the answer to question 3, then make this change now. Changing the code to avoid ZeroDivisionError. """
true
9ac5ec423256abc74722ccf876114310e87aad6b
emanchas/Python
/Python/exam1IST140_Ed Manchas.py
1,160
4.21875
4
print ('This program converts fahrenheit to celsius \n') user_temp = int(input('Please input a temperature in Fahrenheit:')) while user_temp < 0: print ('Error! Temperature must be greater than 0 degrees!') user_temp = int(input('Please input a temperature in Fahrenheit:')) print ('') print ('Fahrenheit \t Celsius') for user_temp in range (0, user_temp+1, 5): Cel = (5/9) * user_temp - 17.8 print (user_temp, '\t', '\t', format (Cel, '.2f')) print ('') answer = input ('Input new temperature...Y/N? \n') while answer == 'Y' or answer == 'y': user_temp = int(input('Please input a temperature in Fahrenheit:')) while user_temp < 0: print ('Error! Temperature must be greater than 0 degrees!') user_temp = int(input('Please input a temperature in Fahrenheit:')) print ('') print ('Fahrenheit \t Celsius') for user_temp in range (0, user_temp+1, 5): Cel = (5/9) * user_temp - 17.8 print (user_temp, '\t', '\t', format (Cel, '.2f')) print ('') answer = input ('Input new temperature...Y/N? \n') print ('') print ('Thank you for using this program ^_^')
true
fb80c96b9ea3a455cc9e5fe3daac41c59e64672b
EQ4/amplify
/src/amplify/utils.py
643
4.46875
4
import re def natural_sort(string): ''' This function is meant to be used as a value for the key-argument in sorting functions like sorted(). It makes sure that strings like '2 foo' gets sorted before '11 foo', by treating the digits as the value they represent. ''' # Split the string into a list of text and digits, preserving the relative # order of the digits. components = re.split(r'(\d+)', string) # If a part consists of just digits, convert it into an integer. Otherwise # we'll just keep the part as it is. return [(int(part) if part.isdigit() else part) for part in components]
true
599ff97346be71193c24c5818e5f2daf99cd6e04
cfascina/python-learning
/exercices/built-in-functions/lambda-expression/main.py
764
4.5625
5
# Lambda expressions are anonymous functions that you will use only once. # The following square() function will be converted into a lambda expression, # step by step. # Step 1: # def square(number): # result = number ** 2 # return result # Step 2: # def square(number): # return number ** 2 # Step 3: # def square(number): return number ** 2 # Step 4 (lambda expression): # lambda number: number ** 2" numbers = [1, 2, 3, 4, 5] print("Results w/ lambda expression:") for number in map(lambda number: number ** 2, numbers): print(number) # This code does exactly the same thing as the following, but we don't need to # declare the function square(), since we will only use it once: # for number in map(square, numbers): # print(number)
true
ee4f50efcfb983282db6c7a1bedf8116508ebf55
MDCGP105-1718/portfolio-Ellemelmarta
/Python/ex11.py
780
4.1875
4
from random import randint x = int(randint (1,100)) #make user guess a number with input guess = int(input("Guess a number between 1 - 100: ")) num_guesses = 1 #tell them higher or lower while guess != x: if guess > x and guess != x: print ("wrong, too high") guess = int(input("Guess again: ")) num_guesses += 1 #if statement to make sure the guess isnt equal to input and is higher than it to then tell the user if guess < x and guess != x: print ("wrong, too low") guess = int(input("Guess again: ")) num_guesses += 1 #if statement to make sure the guess isnt equal to input and is lower than it to then tell the user else: print (f"Congratulations you got it in {num_guesses} guesses. Number = {x}")
true
b59bf1444ea96d25bb3aa233600e298f41df21e9
ssavann/Python-Hangman-game
/Hangman.py
1,754
4.34375
4
#Build a hangman game import random import HangmanArt import HangmanWords #print ASCII art from "stages" print(HangmanArt.logo) end_of_game = False #List of words word_list = HangmanWords.word_list #Let the computer generate random word chosen_word = random.choice(word_list) #to count the number of letter in the word word_length = len(chosen_word) #set lives to equal 6 lives = 6 #for test only #print(f'Pssst, the solution is {chosen_word}.') #Create blanks display = [] for _ in range(word_length): display += "_" while not end_of_game: guess = input("Guess a letter: ").lower() #if user typed in the same letter before, we will let him know if guess in display: print(f"You've already guessed {guess}") #Check guessed letter for position in range(word_length): letter = chosen_word[position] # print(f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}") if letter == guess: display[position] = letter #get a track record of lives. If lives goes down to "zero", you lose. if guess not in chosen_word: print(f"You've guessed {guess}, that's not in the word. You lose a life.") lives -= 1 if lives == 0: end_of_game = True print("You lose!") print(f"{' '.join(display)}") if "_" not in display: end_of_game = True print("You win!") #print ASCII art from "stages" print(HangmanArt.stages[lives]) """ #A loop to guess each letter at every position for char in chosen_word: if char == guess: display.append(guess) else: display.append("_") print(display) """
true
77f22ce39b1fee400eaf29861a4a5eca82ebf9a4
LuiSteinkrug/Python-Design
/wheel.py
1,400
4.21875
4
import turtle turtle.penup() def drawCircle(tcolor, pen_color, scolor, radius, mv): turtle.pencolor(pen_color) # not filling but makes body of turtle this colo turtle.fillcolor(tcolor) # not filling but makes body of turtle this colo turtle.begin_fill() turtle.right(90) # Face South turtle.forward(radius) # Move one radius turtle.right(270) # Back to start heading turtle.pendown() # Put the pen back down turtle.circle(radius) # Draw a circle turtle.penup() # Pen up while we go home turtle.end_fill() # End fill. turtle.home() # Head back to the start pos def drawHexagon(side_length, pen_color): polygon = turtle.Turtle() polygon.pencolor(pen_color) num_sides = 6 angle = 360.0 / num_sides polygon.penup() # Pen up while we go home polygon.left(120) polygon.forward(side_length) polygon.right(120) polygon.pendown() # start drawing hexagon for i in range(num_sides): polygon.forward(side_length) polygon.right(angle) polygon.pencolor("white") polygon.fillcolor("white") polygon.penup() polygon.home() drawCircle("blue", "blue", "black", 200, 30) print (" 2 ") drawCircle("white", "white", "black", 150, 30) drawHexagon(200, "white") drawHexagon(150, "blue") turtle.exitonclick()
true
325f52227fcdd352295be2352731b33cedaf2ba4
urantialife/AI-Crash-Course
/Chapter 2/Functions/homework.py
715
4.1875
4
#Exercise for Functions: Homework Solution def distance(x1, y1, x2, y2): # we create a new function "distance" that takes coordinates of both points as arguments d = pow(pow(x1 - x2, 2) + pow(y1 - y2, 2), 0.5) # we calculate the distance between two points using the formula provided in the hint ("pow" function is power) return d # this line means that our function will return the distance we calculated before dist = distance(0, 0, 3, 4) # we call our function while inputting 4 required arguments, that are coordinates print(dist) # we display thr calculated distance
true
6993f804ebd81a8fac2c2c2dcc7ba5a96d37e62d
saifsafsf/Semester-1-Assignments
/Lab 11/Modules2.py
1,894
4.4375
4
def strength(password): '''Takes a password. Returns its strength out of 10.''' pass_strength = 0 # If length of password is Good. if 16 >= len(password) >= 8: pass_strength += 2 # If password has a special character if ('$' in password) or ('@' in password) or ('#' in password): pass_strength += 3 lower, upper, alpha, num = False, False, False, False # If a letter(lower or upper) or a number is found for a in password: if a.islower(): lower = True elif a.isupper(): upper = True elif a.isdigit(): num = True if a.isalpha(): alpha = True # In case of alphanumeric if num == True and alpha == True: pass_strength += 3 # In case of lowercse & uppercase if upper == True and lower == True: pass_strength += 2 return pass_strength def output(pass_strength, password): '''Takes password & its strength Returns Strength with appropriate comments.''' # If strength exceeds 8 if pass_strength > 8: # Storing password in a file file = open('passwords.txt', 'a') file.write(f'{password}\n') file.close() # Giving comments print(f'\nStrength: {pass_strength}/10.\nYour password is STRONG!\n') else: # Giving comments print(f'\nStrength: {pass_strength}/10.') print(f'\nYour password is weak.\nTry adding atleast 1 symbol, 1 lowercase & 1 uppercase letter.') print('\nAlso, make sure it\'s alphanumeric & has more than 8 characters but not more than 16.') print('\nNow, Try Again.\n')
true
ce44b33c8e5d4c26ec7f67d09fff55e8d4623d9c
saifsafsf/Semester-1-Assignments
/Lab 08/task 1.py
419
4.21875
4
math_exp = input('Enter a mathematical expression: ') # Taking Input while math_exp != 'Quit': math_exp = eval(math_exp) # Evaluating Input print(f'Result of the expression: {math_exp:.3}\n') print('Enter Quit to exit the program OR') # Taking input for next iteration math_exp = input('Enter another mathematical expression: ') print('Program exited successfully.') # Exiting message
true
7196fac0553a675a33fe3cc7816876f40fa2966e
saifsafsf/Semester-1-Assignments
/Lab 08/AscendSort.py
533
4.15625
4
def ascend_sort(input_list): '''ascend_sort([x]) Returns list sorted in ascending order.''' for i in range(1, len(input_list)): # To iterate len(list)-1 times for j in range((len(input_list))-i): if input_list[j] > input_list[j+1]: # Comparing two consecutive values interchange = input_list[j+1] input_list[j+1] = input_list[j] # Sorting consecutive values in ascending order input_list[j] = interchange return input_list
true
bdf165162078678430c7db868bb38f2894b27f63
saifsafsf/Semester-1-Assignments
/Assignment 3/Task 1.py
780
4.1875
4
import Maxim import Remove # Importing modules import Reverse nums = input('Enter a natural number: ') # Taking input if int(nums) > 0: largest_num = str() # Defining variable before using in line 9 while nums != '': max_num = Maxim.maxim(nums) # Using Maxim module largest_num = max_num + largest_num # Storing in descending order nums = Remove.remove_max(max_num, nums) # Removing the max_num for next iteration print(f'\nThe Largest Number possible: {int(largest_num)}') smallest_num = Reverse.reverse(int(largest_num)) # Reversing the largest number print(f'The Smallest Number possibe: {smallest_num}\n') else: # Natural Numbers only print('Invalid Input... Natural Numbers only.')
true
ba2c1f8c3440bbcc652276ea22c025fdc6fae4d6
ridinhome/Python_Fundamentals
/07_classes_objects_methods/07_01_car.py
862
4.4375
4
''' Write a class to model a car. The class should: 1. Set the attributes model, year, and max_speed in the __init__() method. 2. Have a method that increases the max_speed of the car by 5 when called. 3. Have a method that prints the details of the car. Create at least two different objects of this Car class and demonstrate changing the objects attributes. ''' class Car(): def __init__(self,model,year,max_speed): self.model = model self.year = year self.speed = max_speed def accelerate(self): self.speed += 5 def __str__(self): return(f"The {self.model} is from {self.year} and has a maximum speed of {self.speed}.") my_car1 = Car("BMW",2020,90) my_car2 = Car("Toyota",2019,70) print (my_car1) print (my_car2) my_car1.accelerate() print (my_car1) my_car2 = Car("Honda",2018,65) print (my_car2)
true
3ca0df53a0db382f61549d00923829d0dc3b00be
ridinhome/Python_Fundamentals
/08_file_io/08_01_words_analysis.py
1,565
4.4375
4
''' Write a script that reads in the words from the words.txt file and finds and prints: 1. The shortest word (if there is a tie, print all) 2. The longest word (if there is a tie, print all) 3. The total number of words in the file. ''' my_dict = {} shortest_list = [] longest_list = [] def shortestword(input_dict): '''Function to accept a dictionary, convert it to a tuple, sort it and then return the sorted list as well as the length of the longest and shortest words''' result_list = [] for key in input_dict: tuple_to_add = key,input_dict[key] result_list.append(tuple_to_add) new_list = sorted(result_list, key= lambda item:item[1]) short_length = new_list[0][1] list_length = len(new_list)-1 long_length = new_list[list_length][1] return new_list, short_length, long_length with open("words.txt","r") as fin: '''Opens the file, reads the words and then passes them to a dictionary after stripping out new line characters.''' for word in fin.readlines(): word = word.rstrip() my_dict[word] = [int(len(word))] sorted_list,shortest_length,longest_length = shortestword(my_dict) for key,value in sorted_list: '''Creates the list of the shortest words and the longest words.''' if value == shortest_length: shortest_list.append(key) elif value == longest_length: longest_list.append(key) print ("The shortest words are: ",shortest_list) print ("The longest words are:", longest_list) print (f"The total number of words are: {len(sorted_list)}")
true
b644aa4a1d7e9d74a773a5e2b4dc095fac236ee2
ridinhome/Python_Fundamentals
/03_more_datatypes/3_tuples/03_16_pairing_tuples.py
970
4.375
4
''' Write a script that takes in a list of numbers and: - sorts the numbers - stores the numbers in tuples of two in a list - prints each tuple If the user enters an odd numbered list, add the last item to a tuple with the number 0. Note: This lab might be challenging! Make sure to discuss it with your mentor or chat about it on our forum. ''' num_str = input ("Please enter a list of numbers:") split_list = num_str.split() num_list =[] tuple_list = [] for i in range (0,len(split_list)): num_list.append(int(split_list[i])) num_list.sort() if len(num_list) % 2 ==0: for i in range (0,len(num_list)-1,2): tuple_to_add = (num_list[i],num_list[i+1]) tuple_list.append(tuple_to_add) else: for i in range (0,len(num_list)-1,2): tuple_to_add = (num_list[i],num_list[i+1]) tuple_list.append(tuple_to_add) tuple_to_add = (num_list[len(num_list)-1],0) tuple_list.append(tuple_to_add) print (tuple_list)
true
916c20052c18261dd5ef30d421b0e17b0e92d443
ridinhome/Python_Fundamentals
/02_basic_datatypes/1_numbers/02_05_convert.py
568
4.375
4
''' Demonstrate how to: 1) Convert an int to a float 2) Convert a float to an int 3) Perform floor division using a float and an int. 4) Use two user inputted values to perform multiplication. Take note of what information is lost when some conversions take place. ''' value_a = 90 value_b = 11.0 value_a_float = float(value_a) print (value_a_float) value_b_float = int(value_b) print(value_b_float) value_c = value_a // value_b print(value_c) c = input("Enter a value") b = input("Enter another value") cd = float(c) * float(b) print(cd)
true
d4c0dbee1de20b3fae2f2ae80f74d105463d4c07
akhilkrishna57/misc
/python/cap.py
1,727
4.21875
4
# cap.py - Capitalize an English passage # This example illustrates the simplest application of state machine. # Scene: We want to make the first word capitalized of every sentence # in a passage. class State (object): def setMappedChar(self, c): self.c = c def getMappedChar(self): return self.c def setNextState(self, s): self.s = s def keepCurrentState(self): self.s = self def getNextState(self): return self.s class BeforeSentenceState (State): '''We are ahead of a passage or behind a full stop of a sentence but before the next one''' def transit(self, c): if c.isalpha(): self.setMappedChar(c.upper()) self.setNextState(InSentenceState()) else: self.setMappedChar(c) self.keepCurrentState() class InSentenceState (State): '''We are within a sentence''' def transit(self, c): if c == '.': self.setMappedChar(c) self.setNextState(BeforeSentenceState()) else: self.setMappedChar(c) self.keepCurrentState() class Capitalizer (object): def process(self, text): result = '' currentState = BeforeSentenceState() for c in text: currentState.transit(c) result += currentState.getMappedChar() currentState = currentState.getNextState() return result cap = Capitalizer() print cap.process("""apple device owners can run official apps for Google Maps, \ Google Search, Gmail, Google's Chrome browser, Google Drive and more. \ they can get Microsoft-written apps for its Bing search service, \ its SkyDrive cloud-storage service, its OneNote note-taking service and more. \ and they can get a host of Amazon's apps, including several apps for Amazon's \ online store and apps for Amazon's cloud-based video and music steaming services.""")
true
21ca29ba7a6e2a124a20291d11490a4eefabe4d3
jhanse9522/toolkitten
/Python_Hard_Way_W2/ex8.py
1,364
4.53125
5
formatter = "{} {} {} {} " # this is the equivalent of taking a data of type str and creating positions (and blueprints?) for different arguments that will later be passed in and storing it in a variable called #formatter print(formatter.format(1, 2, 3, 4)) #The first argument being passed in and printed is of data type int (1,2,3,4) and they go into the 4 positions set by the {} print(formatter.format("one", "two", "three", "four")) #The second argument being passed in and printed is of data type str ("one", "two"...) and they go into the 4 positions set by {} print(formatter.format(True, False, False, True)) #The third argument being passed in and printed is of data type Boolean (True, False, False, True) and they go in the 4 positions set by {} print(formatter.format(formatter, formatter, formatter, formatter)) #The fourth argument being passed in and printed is of data type var (pointing to a str with 4 {} so this will print 16 of them total) print(formatter.format( #The fifth argument being passed in is of data type str and there are 4 strings being passed in, 1 string per position or {} and will print a total of 4 distinct {} on same line :) "Small are your feet", "And long is the road", "Will measures more", "Just shut up and code!" )) #OK! I think I get what this is doing!
true
06efc287d6c51abc7851cbccbece718179a9e4a0
jhanse9522/toolkitten
/Python_Hard_Way_W2/ex16.py
1,368
4.3125
4
from sys import argv script, filename = argv print(f"We're going to erase {filename}.") print("If you don't want that, hit CTRL-C (>C).") print("If you do want that, hit RETURN.") #print statement doesn't ask for input. Only to hit the return key, which is what you would normally hit after entering user input. (or quit python--already built in--ctrl c) input("?") print("Opening the file...") target = open(filename, 'w') #calls open and passes in the parameter filename and write mode and stores the opened file in write mode in the variable "target". print("Truncating the file. Goodbye!") target.truncate() #erased my whole file (no parameters) which said "This is a test file" or something like that print("Now I'm going to ask you for three lines.") line1 = input("line 1: ") #stores user input under these variable names: line1, line2, line3. Uses prompt: line 1:, line 2:, line 3:: line2 = input("line 2: ") line3 = input("line 3: ") print("I'm going to write these to the file.") target.write(line1) #write to the file, pass in the parameter line1--writes line 1 to the file. target.write("\n") #write to the file, pass in the parameter new line, goes to next line target.write(line2) #...etc target.write("\n") target.write(line3) target.write("\n") print("And finally, we close it.") target.close() #closes opened file which is in write mode
true
0ba974b7a198bea2c267cb0a1d87c719c6bef25e
jhanse9522/toolkitten
/Python_Hard_Way_W2/ex15a.py
1,171
4.65625
5
filename = input("What's the name of the file you want to open?") txt = open(filename) #the open command takes a parameter, in this case we passed in filename, and it can be set to our own variable. Here, our own variable stores an open text file. Note to self: (filename) and not {filename} because filename is already a variable label created in line 3. print(f"Here's your file {filename}:") print(txt.read()) #call a function on an opened text file named "txt" and that function we call is "read". We call "read" on an opened file. It returns a file and accepts commands. ****You give a FILE a command using dot notation. close = txt.close print(close) print("Type the filename again:") file_again = input("> ") #sets user input received at prompt "> " equal to variable called "file_again" txt_again = open(file_again) #opens our sample txt file again and stores opened file in a variable called txt_again print(txt_again.read()) #reads the file now stored under txt_again and prints it out again. close = txt_again.close print(close) #********** This is an alternate version from the study drill. Using input only and not argv to open the file.
true
63043be9d8b39e5caf053a06bd8129a27f0c4ffe
BSR-AMR-RIVM/blaOXA-48-plasmids-Microbial-Genomics
/scripts/printLine.py
273
4.1875
4
# quick code to print the lines that starts with > import sys FILE = sys.argv[1] with open(FILE, 'r') as f: count = 0 for line in f: count =+ 1 if line.startswith(">"): newLine = line.split(' ') if len(newLine) < 3: print(newLine) print(count)
true
b48bbe647eedb43c9e4adaa726842cfed8c38fd0
Rythnyx/py_practice
/basics/reverseArray.py
1,125
4.46875
4
# The purpose of this excercise is to reverse a given list exList = [1,2,3,4,5,6,7,8,9,10,'a','b','c','d','e','f','g'] # The idea here is to simply return the list that we had but step through it backward before doing so. # This however will create a new list, what if we want to return it without creating a new one? def reverse_list(p_list): return p_list[::-1] # To make this work we need to keep track of indexes and step through the list ourselves # whilst flipping elements with each other def reverse_list_in_place(p_list): # indexes left = 0 right = len(p_list) -1 # When we pass the midpoint we have finished while left < right: # swap elements temp = p_list[left] p_list[left] = p_list[right] p_list[right] = temp # update indexes left += 1 right -= 1 return p_list #if __name__ == "__main__": print("This is the result of a new reversed list being returned:\n\t" + str(reverse_list(exList)) + "\n") print("This is the result of the same list being returned with inplace swapping:\n\t" + str(reverse_list_in_place(exList)))
true
787bb5e6c13463126b80c1144ae7a19274aab61b
ebonnecab/CS-2-Tweet-Generator
/regular-challenges/dictionary_words.py
1,176
4.125
4
#an algorithm that generates random sentences from words in a file #TO DO: refactor code to use randint import random import sys # number = sys.argv[:1] number = input('Enter number of words: ') #takes user input ''' removes line breaks, and appends the words from the file to the list, takes five words from the list object, stores them in an array, and joins the array into a sentence before outputting it''' def random_sentence(): words_list = [] #creates list object with open('/usr/share/dict/words') as file: #accessing word file text = file.read().split() for word in text: # words_list.append(word) # rand_num = random.randint(0, len(text)-1) # rand_word = words_list[rand_num] # words_list.append(word) word = word.strip() words_list.append(word) word_array = random.choices(words_list, k= int(number)) sentence = ' '.join(word_array) + '.' sentence = sentence.capitalize() return sentence if __name__ == '__main__': test = random_sentence() print(test)
true
151172bdb8289efb3e3494a7c96db79c0d07de4c
kushrami/PythonProgramms
/LoanCalculator.py
439
4.125
4
CostOfLoan = float(input("Please enter your cost of loan = ")) InterestRate = float(input("Please enter your loan interst rate = ")) NumberOfYears = float(input("Please enter Number of years you want a loan = ")) InterestRate = InterestRate / 100.0 MonthlyPayment = CostOfLoan * (InterestRate * (InterestRate + 1.0) * NumberOfYears) / ( (1.0 + InterestRate) * NumberOfYears - 1.0) print("Your Monthly Payment of loan is",MonthlyPayment)
true
d5c46b1068f3fa7d34ef2ef5151c1c0a825c88f5
derpmagician/holbertonschool-higher_level_programming
/0x0B-python-input_output/0-read_file.py
253
4.3125
4
#!/usr/bin/python3 """ Reads an utf-8 formated file line by line""" def read_file(filename=""): """Reads an UTF8 formated file line by line """ with open(filename, encoding='utf-8') as f: for line in f: print(line, end='')
true
8fc8ff320c25de0b3b15537fbbee03749721a9c1
Aliena28898/Programming_exercises
/CodeWars_exercises/Roman Numerals Decoder.py
1,816
4.28125
4
''' https://www.codewars.com/kata/roman-numerals-decoder Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered "MCMXC" (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered "MMVIII" (2000 = MM, 8 = VIII). The Roman numeral for 1666, "MDCLXVI", uses each letter in descending order. Example: solution('XXI') # should return 21 Courtesy of rosettacode.org ''' #SOLUTION: sol = 0 index = 0 def decode(roman, char, decimal): global sol global index if char in roman and decimal != 1: while index < len(roman) and roman[index] == char: sol = sol + decimal index += 1 if roman[index:].find(char) != -1: if char in "MCX": sol = sol + int(decimal * 0.9) else: sol = sol + int(decimal * 0.8) index = index + 2 else: while index < len(roman) and roman[index] == char: sol = sol + decimal index += 1 def solution(roman): global sol global index sol = 0 index = 0 decode(roman, 'M', 1000) decode(roman, 'D', 500) decode(roman, 'C', 100) decode(roman, 'L', 50) decode(roman, 'X', 10) decode(roman, 'V', 5) decode(roman, 'I', 1) return sol #SAMPLE TESTS: test.assert_equals(solution('XXI'), 21) test.assert_equals(solution('MCMXC'), 1990) test.assert_equals(solution('MMVIII'), 2008) test.assert_equals(solution('MDCLXVI'), 1666) test.assert_equals(solution('II'), 2)
true
24540c992ec687bd43c3b38674e1acef2f43dcb8
Aliena28898/Programming_exercises
/CodeWars_exercises/Reversed Sequence.py
298
4.25
4
''' Get the number n to return the reversed sequence from n to 1. Example : n=5 >> [5,4,3,2,1] ''' #SOLUTION: def reverse_seq(n): solution = [ ] for num in range(n, 0, -1): solution.append(num) return solution #TESTS: test.assert_equals(reverse_seq(5),[5,4,3,2,1])
true
51bff2c710aa809cc0cf3162502a7acae518bf60
AnaLuizaMendes/Unscramble-Computer-Science-Problems
/Task1.py
1,011
4.25
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 1: How many different telephone numbers are there in the records? Print a message: "There are <count> different telephone numbers in the records." """ # First create a set to hold all the unique numbers nums = set() def get_nums(list): # For loop in text, to go throw each row in the doc # Then, select the numbers in the first and second columns # If it is not in nums adds to it, if it is ignore and continue for row in list: for num in row[0], row[1]: nums.add(num) return nums get_nums(texts) get_nums(calls) # Get the len of nums to know how many unique numbers in the two documents count = len(nums) print(f"There are {count} different telephone numbers in the records.")
true
18ad26f5f5613336ece2a9affadceb7282ab0a75
aaishikasb/Hacktoberfest-2020
/cryptography system/Crypto_system.py
729
4.3125
4
def machine(): keys = "abcdefghijklmnopqrstuvwxyz !" values = keys[-1] + keys[0:-1] encrypt = dict(zip(keys, values)) decrypt = dict(zip(values, keys)) option = input( "Do you want to encrypt or decrypt, press e for encrypt and d for decrypt?") message = input("what is the message you wanna encrypt or decrypt?") if (option.lower() == 'e'): new_msg = ''.join([encrypt[i] for i in message]) # here we are changing the values of each alphabet according to the values associated with keys in dictionary! elif (option.lower() == 'd'): new_msg = ''.join([decrypt[i] for i in message]) else: print("Enter the valid option ( e or d )") return new_msg print(machine())
true
c0f8180687415dbc703433d7642329baedf9212f
MLHafizur/Unscramble-Computer-Science-Problems
/Task4.py
1,528
4.1875
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """ def get_telemarketers(record_list): text_num_list, caller_list, reciever_list = [], [], [] for record in record_list: caller, reciever = record[0].strip(), record[1].strip() if is_text(record): text_num_list.extend([caller, reciever]) elif is_call(record): caller_list.append(caller) reciever_list.append(reciever) else: raise Exception('Type of the record not recognized') telemarketer_set = (set(caller_list) - (set(reciever_list) | set(text_num_list))) return sorted(telemarketer_set) def is_text(record): return len(record) == 3 def is_call(record): return len(record) == 4 print('These numbers could be telemarketers:\n', get_telemarketers(texts + calls))
true
99abf35d29cc6488acc5a7d230abd99688ca45ea
JKinsler/Sorting_Algorithms_Test
/merge_sort3.py
1,508
4.15625
4
""" +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Merge sort Sorting array practice 6/9/20 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Sort an unsorted array in O(nlogn) time complexity Developer notes: this is my favorite way to organize the merge sort algorithm because I think it's easily readable. """ def merge_sort(arr): """ Divide a conquer sort method with O(nlog(n)) runtime """ # set the recursion base case if len(arr) < 2: return arr # divide the list mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) def merge(left, right): """ combine the two sorted lists into a single sorted list """ i_left = 0 i_right = 0 res = [] #interleave right and left into a list while i_left < len(left) and i_right < len(right): if left[i_left] < right[i_right]: res.append(left[i_left]) i_left += 1 else: res.append(right[i_right]) i_right += 1 # add remaining values from the left index while i_left < len(left): res.append(left[i_left]) i_left += 1 # add remaining values from the right index while i_right < len(right): res.append(right[i_right]) i_right += 1 return res if __name__ == '__main__': print(merge_sort([3, 1, 2])) print(merge_sort([])) print(merge_sort([8, 1, 35, 2, 16]))
true
e0c5fc3a55327871f16b450def694a6dd97a8e5f
JKinsler/Sorting_Algorithms_Test
/merge_sort2.py
1,353
4.15625
4
""" +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Merge sort Sorting array practice +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Sort an unsorted array in O(nlogn) time complexity """ def merge_sort(arr): """ decompose the array into arrays of length 1 recombine the arrays in a sorted manner, using the helper function Developer notes: This solution is not ideal because it uses 'pop(0)' in the helper function, which adds O(n) run time. """ if len(arr) < 2: print(f'returning arr: {arr}') return arr mid = len(arr)//2 lst1 = merge_sort(arr[:mid]) lst2 = merge_sort(arr[mid:]) return merge(lst1, lst2) def merge(lst1, lst2): """combine two sorted arrays into a single sorted array""" res = [] # add the lowest value to res while len(lst1) > 0 or len(lst2) > 0: # add the value of the remaining list if one list is empty if lst1 == []: res.append(lst2.pop(0)) elif lst2 == []: res.append(lst1.pop(0)) # append the lesser value to res elif lst1[0] < lst2[0]: res.append(lst1.pop(0)) else: res.append(lst2.pop(0)) return res if __name__ == '__main__': print(merge_sort([3, 1, 4]))
true
5a5c10e83e60d200ed4a722f8a018e43014d628d
Benedict-1/mypackage
/mypackage/sorting.py
1,561
4.34375
4
def bubble_sort(items): '''Return array of items, sorted in ascending order''' count = 0 for idx in range(len(items)-1): if items[idx] > items[idx + 1]: items[idx],items[idx + 1] = items[idx + 1],items[idx] count += 1 if count == 0: return items else: return bubble_sort(items) def merge(left, right): """Merge sort merging function.""" left_index, right_index = 0, 0 result = [] while left_index < len(left) and right_index < len(right): if left[left_index] < right[right_index]: result.append(left[left_index]) left_index += 1 else: result.append(right[right_index]) right_index += 1 result += left[left_index:] result += right[right_index:] return result def merge_sort(array): """Merge sort algorithm implementation.""" if len(array) <= 1: # base case return array # divide array in half and merge sort recursively half = len(array) // 2 left = merge_sort(array[:half]) right = merge_sort(array[half:]) return merge(left, right) def quick_sort(items): if len(items) <= 1: return items items = list(items) pivot = items[-1] new_list = [pivot] count = 0 for i in range(len(items)-1): if items[i]<pivot: new_list = [items[i]]+ new_list count+=1 else: new_list = new_list + [items[i]] return quick_sort(new_list[:count])+[pivot]+quick_sort(new_list[count+1:])
true
8242e2eb55ad59d6c17497e56df4cc150fc78a33
jpchato/data-structures-algorithms-portfolio
/python/array_shift.py
766
4.3125
4
''' Feature Tasks Write a function called insertShiftArray which takes in an array and the value to be added. Without utilizing any of the built-in methods available to your language, return an array with the new value added at the middle index. Example Input Output [2,4,6,8], 5 [2,4,5,6,8] [4,8,15,23,42], 16 [4,8,15,16,23,42] ''' import math def insert_shift_array(array, value): middle_index = math.ceil(len(array)/2) end_piece = array[middle_index:len(array)] start_piece = array[0:middle_index] start_piece.append(value) for item in end_piece: start_piece.append(item) print(start_piece) return start_piece if __name__ == "__main__": insert_shift_array([2,4,6,8], 5) insert_shift_array([4,8,15,23,42], 16)
true
82f361fc9231541a923a2c071e14c9b8e6780f88
cnagadya/bc_16_codelab
/Day_three/wordcount.py
599
4.1875
4
""" words function to determine the number of times a word occurs in a string""" def words(input_string): #dictionary template to display words as keys and occurances as values words_dict = {} #splitting string into list to enable iteration words_list = input_string.split() #iterate through the list to check for the words for word in words_list: #check if the word is a number if word.isdigit(): word = int(word) words_dict[word] = words_list.count(str(word)) print words_dict words("one fish two fish red fish blue fish") words('testing 1 2 testing')
true
3ba5adf3dfceea19a2d84aa3e983951341f10e92
elvisasante323/code-katas
/python_code/regex.py
515
4.4375
4
# Learning about regex import re # Search the string to see if it starts with 'The' and ends with 'Spain' text = 'The rain in Spain' expression = re.search('^The.*Spain$', text) if expression: print('We have a match!\n') else: print('There is no match!\n') # Find all lower case characters alphabetically between 'a' and 'm' expression = re.findall('[a-m]', text) print(expression, '\n') # Find all digit characters text = 'That will be 59 dollars' expression = re.findall('\d', text) print(expression)
true
215950378bbcd2f020be5ebfb49cd5c7b5a9aa07
cgisala/Capstone-Intro
/Lab1/Part2:_list_of_classes.py
432
4.21875
4
#Variable choice = 'y' #Initializes choice to y classes = [] #Declares an empty array #Loops until the user enters 'n' for no while(choice == 'y'): semesterClass = input("Enter a class you are taking this semester: ") classes.append(semesterClass) choice = input("Do you want to add more y or n: ") print('My classes for this semester:') #Prints the answer in each line for myClass in classes: print(myClass)
true
9e3b8d7aac17d3b5cef01341cc8452f9ac52cab6
zrjaa1/Berkeley-CS9H-Projects
/Project2A_Power Unit Converter/source_to_base.py
1,260
4.34375
4
# Function Name: source_to_base # Function Description: transfer the source unit into base unit. # Function Input # - source_unit: the unit of source, such as mile, cm. # - source_value: the value in source unit. # Function Output # - base_unit: the unit of base, such as m, kg, L # - base_value: the value in base unit. def source_to_base(source_unit, source_value): Distance = {'ft': 0.3048, 'cm': 0.01, 'mm': 0.001, 'mi': 1609.34, 'm': 1, 'yd': 0.9144, 'km': 1000, 'in': 0.0254}; Weight = {'lb': 0.453592, 'mg': 0.000001, 'kg': 1, 'oz': 0.0283495, 'g': 0.001}; Volume = {'floz': 0.0295735, 'qt': 0.946353, 'cup': 0.236588, 'mL': 0.001, 'L': 1, 'gal': 3.78541, 'pint': 0.473176}; if Distance.has_key(source_unit): base_unit = 'm' base_value = source_value * Distance[source_unit] print base_unit, base_value return base_unit, base_value elif Weight.has_key(source_unit): base_unit = 'kg' base_value = source_value * Weight[source_unit] print base_unit, base_value return base_unit, base_value elif Volume.has_key(source_unit): base_unit = 'L' base_value = source_value * Volume[source_unit] print base_unit, base_value return base_unit, base_value else: print 'Wrong source unit' source_to_base('lb',100)
true
3191972f08fb2d8e4a6292c5bdd59aabdcb51688
alfonso-torres/data_types-operators
/strings&casting.py
1,937
4.65625
5
# Strings and Casting # Let's have a look at some industry practices # single and double quotes examples greetings = 'hello world' single_quotes = 'single quotes \'WoW\'' double_quotes = "double quotes 'WoW'" # It is more easier to use print(greetings) print(single_quotes) print(double_quotes) # String slicing greetings = "Hello world!" # String # indexing in Python starts from 0 # H e l l o w o r l d ! # 0 1 2 3 4 5 6 7 8 9 10 11 # how can we find out the length of this statement/string print(len(greetings)) # We have a method called len() to find out the total length of the statement print(greetings[0:5]) # out puts Hello starting from 0 to 4 print(greetings[6:11]) # out puts world starting from 6 to 10 # reverse indexing starts with -1 print(greetings[-1]) # Let's have a look at some strings methods white_space = "Lot's of space at the end " # strip() helps us delete all white spaces print(len(white_space)) print(len((white_space.strip()))) Example_text = "here's Some texts with lot's of text" print(Example_text.count("text")) # counts the number of times the word is mentioned in the statement print(Example_text) print(Example_text.upper()) print(Example_text.lower()) print(Example_text.capitalize()) # capitalises first letter of the string print(Example_text.replace("with", ",")) # will replace the world "with" , in this case # Concatenation and Casting # We use the symbol `+` to concatenate First_name = "James" Last_name = "Bond" age = 99 # int # print(First_name + " " + Last_name) print(First_name + " " + Last_name + " " + str(age)) #print(Last_name) agee = "99" print(agee) print(type(agee)) print(int(agee)) print(type(int(agee))) x = "100" y = "-90" print(x + y) # 100-90 is printed print(int(x) + int(y)) # 10 is printed # F- String is an amazing magical formatting f print(f"Your Fist Name is {First_name} and Last Name is {Last_name} and you are {age} old")
true
38322c01d2c410b06440fae9ce02faf2c8e045c4
JamesPiggott/Python-Software-Engineering-Interview
/Sort/Insertionsort.py
880
4.1875
4
''' Insertionsort. This is the Python implementation of the Insertionsort sorting algorithm as it applies to an array of Integer values. Running time: ? Data movement: ? @author James Piggott. ''' import sys import timeit class Insertionsort(object): def __init__(self): print() def insertionsort(self, unsorted): for i in range(0, len(unsorted)): for j in range(unsorted[i], 0, -1): if unsorted[j] < unsorted[j - 1]: swap = unsorted[j - 1] unsorted[j - 1] = unsorted[j] unsorted[j] = swap def main(): unsorted = [7, 3, 8, 2, 1, 9, 4, 6, 5, 0] insert = Insertionsort() insert.insertionsort(unsorted) print(unsorted) if __name__ == "__main__": # print(timeit.timeit("main()", setup="from __main__ import Insertionsort")) main()
true
0c54a30b5564cf4fce07a4a22d90f2fee61fd27c
Caelifield/calculator-2
/calculator.py
1,170
4.21875
4
"""CLI application for a prefix-notation calculator.""" from arithmetic import (add, subtract, multiply, divide, square, cube, power, mod, ) # Replace this with your code def calculator(): while True: input_string = input('Enter string:') token = input_string.split(' ') oper = token[0] try: num1 = token[1] except: num1 = token[0] try: num2 = token[2] except: num2 = token[0] #token is a list if oper == 'q': quit() elif oper == "+": print(add(int(num1),int(num2))) elif oper == "-": print(subtract(int(num1),int(num2))) elif oper == "*": print(multiply(int(num1),int(num2))) elif oper == "/": print(divide(int(num1), int(num2))) elif oper == "square": print(square(int(num1))) elif oper == "cube": print(cube(int(num1))) elif oper == "pow": print(power(int(num1),int(num2))) elif oper == "mod": print(mod(int(num1),int(num2))) calculator()
true
204462c7d2e433cbb38fd5d0d1942cda5303b939
VIPULKAM/python-scripts-windows
/count_lines.py
759
4.21875
4
file_path='c:\\Python\\pledge.txt' def count_lines(handle): ''' This function returns the line count in the file. ''' offset = 0 for line in handle: if line: offset += 1 continue return offset def count_occurnace(handle, word): ''' This function returns the word count in a given file ''' count = 0 for line in handle: if word in line: count += 1 return word, count with open(file_path) as f: line_count = count_lines(f) print(f"Total number of lines in '{file_path}':={line_count}") with open(file_path) as f: word_count = count_occurnace(f, "is") count, word = word_count print(f"For word \"{count}\" number of occurances are '{word}'")
true
854838cba4d9a2f2abddfb86bccd1237e9140a4c
jofro9/algorithms
/assignment1/question3.py
2,458
4.1875
4
# Joe Froelicher # CSCI 3412 - Algorithms # Dr. Mazen al Borno # 9/8/2020 # Assignment 1 import math # Question 3 class UnitCircle: def __init__(self): self.TARGET_AREA_ = 3.14 self.RADIUS_ = 1. self.triangles_ = 4. self.iter = 0 ### member functions for use throughout code ### # gamma function for pythagorean long side of right triangle formed by splitting the isosceles in half def Gamma(self, alpha, beta): return math.sqrt( (alpha ** 2) + (beta ** 2) ) # distance from centroid to the side calculated by gamma def Altitude(self, gamma): return math.sqrt( (self.RADIUS_ ** 2) - ((gamma / 2.) ** 2) ) # area of all of the isosceles trianlges for the current iteration, # update the number of triangles for the next iteration def TriangleArea(self, alpha, beta): t_area = alpha * beta * self.triangles_ self.triangles_ *= 2 return t_area def PrintTriangle(self, alpha, beta, gamma, area, altitude): if self.iter == 0.: triangles = 0 else: triangles = self.triangles_ print( "\nIteration #" + str(self.iter) + "\n" + "___________________________________\n" "\nCurrent area: " + str(area) + "\nNumber of triangles: " + str(int(triangles / 2)) + "\nalpha: " + str(alpha) + "\nbeta: " + str(beta) + "\ngamma: " + str(gamma) + "\naltitude: " + str(altitude) ) self.iter += 1 # New unit Circle Object unit_circle = UnitCircle() ### init values (0th iteration) alpha = unit_circle.RADIUS_ * math.sqrt(2.) / 2. # straight distance to farthes inscribe geometry beta = unit_circle.RADIUS_ - alpha area = (2. * alpha) ** 2 gamma = 0. altitude = 0. unit_circle.PrintTriangle(alpha, beta, gamma, area, altitude) # 1st iteration, slightly different calculation than the rest t_area = unit_circle.TriangleArea(alpha, beta) area += t_area gamma = unit_circle.Gamma(alpha, beta) altitude = unit_circle.Altitude(gamma) unit_circle.PrintTriangle(alpha, beta, gamma, area, altitude) while (unit_circle.TARGET_AREA_ - area) > 0.001: beta = gamma / 2. alpha = unit_circle.RADIUS_ - altitude t_area = unit_circle.TriangleArea(alpha, beta) area += t_area gamma = unit_circle.Gamma(alpha, beta) altitude = unit_circle.Altitude(gamma) unit_circle.PrintTriangle(alpha, beta, gamma, area, altitude)
true
731beff49555f623448ce5cb13188586fa850201
tabish606/python
/comp_list.py
665
4.53125
5
#list comprehension #simple list example #creat a list of squares squares = [] for i in range(1,11): squares.append(i**2) print(squares) #using list comprehension squares1 = [] squares1 = [i**2 for i in range(1,11)] print(squares1) #NOTE : in list comprehension method the data is to be append in list is remeber and put in tha list with the loop conditons like above examples #example2 print negative numbers negative = [-i for i in range(1,11)] print(negative) #example 3 print first charcter of element names = ['tabish', 'ansari','bigde', 'nawab'] first_char = [name[0] for name in names] print(first_char)
true
0384000aaaedfd61cf915234cc419e4d9deff281
kadamsagar039/pythonPrograms
/pythonProgramming/bridgelabzNewProject/calender.py
653
4.15625
4
"""Calender Program This program is used to take month and year from user and print corresponding Calender Author: Sagar<kadamsagar039@gmail.com> Since: 31 DEC,2018 """ from ds_utilities.data_structure_util import Logic def calender_runner(): """ This method act as runner for calender_queue(month, year) :return: nothing """ logic_obj = Logic() try: month = int(input('Enter month: ')) except: print("Enter integer only ") try: year = int(input("Enter Year: ")) except: print("Enter integer only") logic_obj.calender(month, year) if __name__ == "__main__": calender_runner()
true
d389e3a7ad0bd05f8ec5f50d0c9b3d192859f41a
StudentDevs/examples
/week1/2.py
1,958
4.8125
5
""" Tutorials on sqlite (quickly grabbed off google, there may be better ones): https://stackabuse.com/a-sqlite-tutorial-with-python/ https://pynative.com/python-sqlite/ """ import sqlite3 def main(): print('Connecting') conn = sqlite3.connect(':memory:') # Configure the connection so we can use the result records as dictionaries. conn.row_factory = sqlite3.Row # Get a "cursor" for database operations. cur = conn.cursor() print('Creating table') sql = '''CREATE TABLE people ( id integer PRIMARY KEY, first_name text NOT NULL, last_name text NOT NULL)''' cur.execute(sql) print('Selecting all') cur.execute('SELECT * FROM people') for i in cur.fetchall(): print(dict(i)) print('Inserting') cur.execute('INSERT INTO people (id, first_name, last_name) VALUES (1, "joe", "aaa")') cur.execute('INSERT INTO people (id, first_name, last_name) VALUES (2, "jane", "bbb")') cur.execute('INSERT INTO people (id, first_name, last_name) VALUES (3, "marty", "ccc")') print('Selecting all') cur.execute('SELECT * FROM people') for i in cur.fetchall(): print(dict(i)) print('Selecting all and printing only specific columns') cur.execute('SELECT * FROM people') for i in cur.fetchall(): print('first: {} / last: {}'.format(i['first_name'], i['last_name'])) print('Selecting id 3') cur.execute('SELECT first_name, last_name FROM people WHERE id = 3') result = cur.fetchone() if result: print(dict(result)) else: print('No record found') print('Deleting id 3') cur.execute('DELETE FROM people WHERE id = 3') print('Selecting id 3') cur.execute('SELECT first_name, last_name FROM people WHERE id = 3') result = cur.fetchone() if result: print(dict(result)) else: print('No record found') if __name__ == '__main__': main()
true
a268b45504f17b58cdf3e5537a47f68ec6e9faa3
3NCRY9T3R/H4CKT0B3RF3ST
/Programs/Python/bellman_ford.py
1,438
4.1875
4
#This function utilizes Bellman-Ford's algorithm to find the shortest path from the chosen vertex to the others. def bellman_ford(matrix, nRows, nVertex): vertex = nVertex - 1 listDist = [] estimation = float("inf") for i in range(nRows): if (i == vertex): listDist.append(0) else: listDist.append(estimation) for i in range(nRows-1): for j in range(nRows): for k in range (nRows): if (matrix[j][k] != 0 and matrix[j][k] + listDist[j] < listDist[k]): listDist[k] = matrix[j][k] + listDist[j] return listDist # This function prints the distance from the inital vertex to the othersdef printBF(lista): def printBF(list): nDist = len(list) for i in range(nDist): print("The distance to the vertex " + str(i + 1) + " is: " + str(list[i])) #We start with the adjacency matrix of a weighted graph. adjacencyMatrix = [[0, 10, 5, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 3, 0, 8, 2, 0], [0, 0, 0, 0, 4, 4], [0, 0, 0, 0, 0, 6], [0, 0, 0, 0, 0, 0]] originVertex = 1 # Here you can chose the origin vertex (value >=1) nRows=len(adjacencyMatrix[0]) nColumns=len(adjacencyMatrix) #Here we get the shortest paths from the origin vertex utilizing Bellman-Ford's Algorithm finalBF = bellman_ford(adjacencyMatrix, nRows, originVertex) # Now we just print the distances from the chosen vertex to another. printBF(finalBF)
true
8b8177c2acb317808a8e4808293cdc8b690f230f
NirajPatel07/Algorithms-Python
/insertionSort.py
376
4.125
4
def insertionSort(list1): for i in range(1,len(list1)): curr=list1[i] pos=i while curr<=list1[pos-1] and pos>0: list1[pos]=list1[pos-1] pos-=1 list1[pos]=curr list1=list(map(int, input("Enter Elements:\n").split())) print("Before Sorting:\n",list1) insertionSort(list1) print("After Sorting:\n",list1)
true
2a575b03af1d4347b73917510fd275583fa674c3
GrandPa300/Coursera-RiceU-Python
/01_Rock-paper-scissors-lizard-Spock/Rock-paper-scissors-lizard-Spock.py
2,074
4.15625
4
# Mini Project 1 # Rock-paper-scissors-lizard-Spock # The key idea of this program is to equate the strings # "rock", "paper", "scissors", "lizard", "Spock" to numbers # as follows: # # 0 - rock # 1 - Spock # 2 - paper # 3 - lizard # 4 - scissors # helper functions import random def number_to_name(number): # fill in your code below if number == 0: name = "rock" elif number == 1: name = "Spock" elif number == 2: name = "paper" elif number == 3: name = "lizard" elif number == 4: name = "scissors" return name # convert number to a name using if/elfi/else #don't forget to return the reslut! def name_to_number(name): # fill in your code below if name == "rock": number = 0 elif name == "Spock": number = 1 elif name == "paper": number = 2 elif name == "lizard": number = 3 elif name == "scissors": number = 4 return number # convert number to a name using if/elfi/else #don't forget to return the reslut! def rpsls(name): # fill in your code below player_number = name_to_number(name) comp_number = random.randrange(4) print "Player chooses " + name print "Computer chooses " + number_to_name(comp_number) difference = (player_number - comp_number)%5 #print player_number #print comp_number #print difference print "==============" if difference > 2: print "Computer wins!" elif difference == 0: print "Player and Computer ties!" else: print "Player wins!" print "==============" print "" # convert name to player_number using name_to_number # compute random guess for comp_number using random.randrange() # compute difference of player_number and comp_number modulo five # use if/elif/else to determine winner # convert comp_number to name using number_to_name # print results # test your code rpsls("rock") rpsls("Spock") rpsls("paper") rpsls("lizard") rpsls("scissors")
true
66dca308dded21abc0509cd24802891564c63c0d
Taylorsuk/Game-of-Hangman
/hangman.py
2,950
4.125
4
import random import re # import the wordlist txtfile = open('word_list.txt', 'r') wordsToGuess = txtfile.readlines() allowedGuesses = 7 incorrectGuesses = [] correctGuesses = [] randomWord = random.choice(wordsToGuess).strip() guessWord = [] maskCharacter = '*' # we have a random word so we can now start the game print("Lets play a game of Hangman") for character in randomWord: guessWord.append(maskCharacter) print("The word you are trying to guess is {}".format(''.join(guessWord))) def findOccurrences(s, ch): return [i for i, letter in enumerate(s) if letter == ch] # while they still have guesses in the bank run this loop while allowedGuesses - len(incorrectGuesses) > 0: # get an input from the user letterGuess = input('\n\nGuess a letter: ').lower() # check that its a valid letter (and they actually entered something!) if not re.match("^[a-z]*$", letterGuess): print('You can only enter a character from the alphabet (a - z)') continue elif len(letterGuess) > 1 or len(letterGuess) == 0: print("You must enter a single character") print(letterGuess) continue # already tried the letter elif (letterGuess in correctGuesses) or (letterGuess in incorrectGuesses): print("You have already tried {}. Please enter your next guess: {}".format(letterGuess, ''.join(guessWord))) continue # letter is in the word # letterIndex = randomWord.find(letterGuess) letterIndices = findOccurrences(randomWord, letterGuess) # if letterIndex >= 0: if len(letterIndices) > 0: correctGuesses.append(letterGuess) print('awesome guess, "{}" is in the word.'.format(letterGuess)) for letterIndex in letterIndices: guessWord[letterIndex] = letterGuess # incorrect guess else: # push the incorrect guess to the incorrect guess list and incorrectGuesses.append(letterGuess) # calculate the guesses remaining remaining = allowedGuesses - len(incorrectGuesses) # notify the user print("Sorry, you lose a life, '{}' is not in the secret word, {} guesses remaining. \n\n Please enter your next guess: {}".format( letterGuess, remaining, ''.join(guessWord))) # check if that was their last life if remaining == 0: print('Sorry, you failed to guess the word: "{}", you lose, why not give it another go!'.format(randomWord)) break print('Incorrect guesses: "{}"'.format(incorrectGuesses)) # show current status print('Please enter your next guess: {}'.format(''.join(guessWord))) # let's see how many remaining stars there are: remainingStars = findOccurrences(guessWord, maskCharacter) # they have guessed all the letters Winner! # if len(correctGuesses) == len(randomWord): if len(remainingStars) == 0: print('Congratulations you win') break
true
78182f8b7eeed49d51da5ad194732dbee021ddf4
aiqingr/python-lesson
/pythonProject/python1/inputExample.py
319
4.21875
4
# num_input = input("Input a number") # print(num_input ** 2) # First two line will popup an error because the input function always return a string # This will be Method One # num_input_1 = input("input a number: ") # print(int(num_input_1) ** 2) num_input_2 = int(input("input a number: ")) print(num_input_2 ** 2)
true
41aed98b579dcc9e7621c9356685aacc33fcf7e9
fivaladez/Learning-Python
/EJ10_P2_Classes.py
981
4.28125
4
# EJ10_P2 Object Oriented - Classes # Create a class class exampleClass: eyes = "Blue" age = 22 # The first parameter MUST be self to refers to the object using this class def thisMethod(self): return "Hey this method worked" # This is called an Object # Assign the class to an a variable to the class exampleObject = exampleClass() # Calling methods from our Object # Members from our class print " ", exampleObject.eyes print " ", exampleObject.age print " ", exampleObject.thisMethod() class className: def createName(self, name): # Create a var called name and assign the parameter name # This is because the variable is inside a function self.name = name def displayName(self): return self.name def saying(self): print " Hello %s" % self.name first = className() second = className() first.createName("Ivan") print " ", first.displayName() first.saying() print " ", first.name
true
ebbdc407c8e93e02618d8aec68213b2229de61ec
fivaladez/Learning-Python
/EJ21_P2_Lambda.py
1,006
4.375
4
# EJ21_P2 Lambda expression - Anonymous functions # Write function to compute 3x+1 def f(x): return 3*x + 1 print f(2) # lambda input1, input2, ..., inputx: return expression in one line print lambda x: 3*x + 1 # With the above declaration we still can not use the function, # we need a name, so, we can do the next thing: def g(x): return 3*x + 1 print g(2) def full_name(fn, ln): return fn.strip().title()+" " + ln.strip().title() print full_name("Ivan ", "Valadez ") soccer_players = ["Leonel Messi", "Cristiano Ronaldo", "Ricardo Kaka"] print soccer_players # in sort method, take each of the spaces from a list (one by one) soccer_players.sort(key=lambda name: name.split(" ")[-1].lower()) print soccer_players # Function to create functions def build_quadratic_function(a, b, c): """Returns the function f(x) = ax^2 + bx + c""" return lambda x: a*x**2 + b*x + c # Option 1 f = build_quadratic_function(2, 3, -5) print f(0), f(1), f(2) # Option 2 print build_quadratic_function(2, 3, -5)(2)
true
99002d0f430011ee9f40ac32feac98b84b435544
fivaladez/Learning-Python
/EJ11_P2_SubClasses_SuperClasses.py
1,065
4.40625
4
# EJ11_P2 Object Oriented - subClasses and superClasses # SuperClass class parentClasss: var1 = "This is var1" var2 = "This is var2 in parentClass" # SubClass class childClass(parentClasss): # Overwrite this var in this class var2 = "This is var2 in childClass" myObject1 = parentClasss() print " ", myObject1.var1 # You can acces to upper layer class "parentClasss" myObject2 = childClass() print " ", myObject2.var1 print " ", myObject1.var2 print " ", myObject2.var2 # ================================================== # Multiple inhertance class mom: mom = "Im mom" class dad: dad = "Im dad" # child class inherit/hereda the elements of classes mom and dad class son(mom, dad): son = "Im son" myObject3 = son() print " ", myObject3.mom print " ", myObject3.dad print " ", myObject3.son # ================================================== # Constructor class new: def __init__(self): print " This is the contructor of class new: " # Automatically calls the constructor myObject4 = new()
true
3194e6d5a08128b1eb943b29f579bf3bf72b1d68
tanish522/python-coding-prac
/stack/stack_1.py
415
4.15625
4
# stack using deque from collections import deque stack = deque() # append() function to push element in the stack stack.append("1") stack.append("2") stack.append("3") print('Initial stack:') print(stack) # pop() fucntion to pop element print('\nElements poped from stack:') print(stack.pop()) print(stack.pop()) print(stack.pop()) print('\nStack after elements are poped:') print(stack)
true
2e1f82907b455f15ddaa77b4a3841c2dd61f6de5
ArsenArsen/claw
/claw/interpreter/commands/cmd_sass.py
1,764
4.125
4
""" Takes the given input and output directories and compiles all SASS files in the input into the output directory The command takes three parameters, namely target, directory, and glob: sass <source> <target> [style] The source parameter is relative to the claw resource directory The target parameter is where the compiled files will reside The style argument is the style of the output. It is assumed that the source is a directory unless it's found that it is a file See: https://sass.github.io/libsass-python/sass.html#sass.compile For example, to compile all sass files in scss and put them in static, as compacted css files: sass scss static compact To take index.scss and compile it into static/index.css: sass index.scss static/index.css """ from os.path import join, isfile, exists, dirname from os import makedirs from claw.errors import ClawParserError, check_deps check_deps("SASS compiler", "sass") import sass def claw_exec(claw, argv): # pylint: disable=missing-docstring if len(argv) != 3 and len(argv) != 4: raise ClawParserError("sass requires two or three arguments") src = join(claw.resource_dir, argv[1]) dst = join(claw.output_dir, argv[2]) style = "nested" if len(argv) == 3 else argv[3] if not exists(src): raise ClawParserError("sass source: no such file or directory") try: if isfile(src): makedirs(dirname(dst), exist_ok=True) with open(dst, 'w') as target: target.write(sass.compile(filename=src, output_style=style)) else: sass.compile(dirname=(src, dst), output_style=style) except sass.CompileError as error: raise ClawParserError("There was an error while compiling sass files:", error)
true
649df4c7b9f19ab38d3924cd2dc68f956b70f90b
iEuler/leetcode_learn
/q0282.py
1,461
4.28125
4
""" 282. Expression Add Operators https://leetcode.com/problems/expression-add-operators/ Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. Example 1: Input: num = "123", target = 6 Output: ["1+2+3", "1*2*3"] Example 2: Input: num = "232", target = 8 Output: ["2*3+2", "2+3*2"] Example 3: Input: num = "105", target = 5 Output: ["1*0+5","10-5"] Example 4: Input: num = "00", target = 0 Output: ["0+0", "0-0", "0*0"] Example 5: Input: num = "3456237490", target = 9191 Output: [] """ from typing import List class Solution: def addOperators(self, num: str, target: int) -> List[str]: def helper(s, k): if k == 0: if s[0] == '0' and len(s) > 1 and s[1] not in '+-*': return [] return [s] if eval(s) == target else [] ans = helper(s, k - 1) if s[k] != '0' or k == len(s)-1 or s[k+1] in '+-*': ans += helper(s[:k] + '+' + s[k:], k - 1)\ + helper(s[:k] + '-' + s[k:], k - 1)\ + helper(s[:k] + '*' + s[k:], k - 1) return ans if not num: return [] return helper(num, len(num)-1) num = "105" target = 5 num = "123" target = 6 num = "00" target = 0 num = "" target = 5 print(Solution().addOperators(num,target))
true
444ef66071c458cf92cfff248f813ab29608c91e
Prashant1099/Simple-Python-Programs
/Count the Number of Digits in a Number.py
318
4.15625
4
# The program takes the number and prints the number of digits in the number. n = int(input("\nEnter any Number = ")) count = 0 temp = n while (n>0): n //= 10 count += 1 print("-----------------------------------") print("Number of Digits in ",temp, " = ",count) print("-----------------------------------")
true
b8da10fe0d52d9d8ff08344c4bc8d3465b8f3e6d
atifahsan/project_euler
/p1.py
275
4.21875
4
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. numbers = [i for i in range(1, 1000) if not i % 3 or not i % 5] print(sum(numbers))
true
1179247685bb98e5de3d5de793ba677670d18e55
ananth-duggirala/Data-Structures-and-Algorithms
/Arrays and Strings/reverse_string.py
338
4.28125
4
""" Problem statement: Reverse a string. """ def reverseString(string): newString = "" n = len(string) for i in range(n): newString += string[n-1-i] return newString def main(): string = input("This program will reverse the entered string. \n\nEnter string: ") print(reverseString(string)) if __name__ == "__main__": main()
true
8af2e44e30d2e180e9b16f63c69d2d53d6a1594b
Suman196pokhrel/TkinterPractice
/more_examples/m7e_canvas_and_mouse_events.py
2,551
4.3125
4
""" Example showing for tkinter and ttk how to: -- Capture mouse clicks, releases and motion. -- Draw on a Canvas. Authors: David Mutchler and his colleagues at Rose-Hulman Institute of Technology. """ import tkinter from tkinter import ttk class PenData(object): def __init__(self): self.color = 'blue' self.mouse_position_x = None self.mouse_position_y = None self.is_dragging = False def main(): pen_data = PenData() root = tkinter.Tk() main_frame = ttk.Frame(root, padding=5) main_frame.grid() instructions = 'Click the left mouse button to make circles,\n' instructions = instructions + 'drag the left mouse button to draw' label = ttk.Label(main_frame, text=instructions) label.grid() # Make a tkinter.Canvas on a Frame. # Note that Canvas is a tkinter (NOT a ttk) class. canvas = tkinter.Canvas(main_frame, background='lightgray') canvas.grid() # Make callbacks for mouse events. canvas.bind('<Button-1>', lambda event: left_mouse_click(event)) canvas.bind('<B1-Motion>', lambda event: left_mouse_drag(event, pen_data)) canvas.bind('<B1-ButtonRelease>', lambda event: left_mouse_release(pen_data)) # @UnusedVariable # Make a button to change the color. button = ttk.Button(main_frame, text='Flip pen color') button.grid() button['command'] = lambda: flip_pen_color(pen_data) root.mainloop() def left_mouse_click(event): canvas = event.widget canvas.create_oval(event.x - 10, event.y - 10, event.x + 10, event.y + 10, fill='green', width=3) def left_mouse_drag(event, data): # data.mouse_position_x and _y keep track of the PREVIOUS mouse # position while we are dragging. canvas = event.widget if data.is_dragging: canvas.create_line(data.mouse_position_x, data.mouse_position_y, event.x, event.y, fill=data.color, width=5) else: data.is_dragging = True # Start dragging data.mouse_position_x = event.x data.mouse_position_y = event.y def left_mouse_release(data): data.is_dragging = False def flip_pen_color(data): if data.color == 'blue': data.color = 'red' else: data.color = 'blue' # ---------------------------------------------------------------------- # Calls main to start the ball rolling. # ---------------------------------------------------------------------- main()
true
d6577d3cba76440597da1653413a156453e16514
maainul/Python
/pay_using_try_catch.py
244
4.125
4
try: Hours=input('Enter Hours:') Rates=input('Enter Rates:') if int(Hours)>40: pay=40*int(Rates)+(int(Hours)-40)*(int(Rates)*1.5) print(pay) else: pay=int(Hours)*int(Rates) print(pay) except: print('Error,Please enter numeric input.')
true
dc54502a549f56b66637befa2cbf522f744357c0
maainul/Python
/Centimeter_to_feet_and_inch.py
265
4.125
4
cm=int(input("Enter the height in centimeters:")) inches=0.394*cm feet=0.0328*cm print("The length in inches",round(inches,2)) print("The length in feet",round(feet,2)) OUTPUT: Enter the height in centimeters:50 The length in inches 19.7 The length in feet 1.64
true
4719c9d94b43e37e25802ebdb2f92a8eaeb735a8
sudheer-sanagala/intro-python-coursera
/WK-03-Loops/while_loops.py
2,178
4.3125
4
# while loops x = 0 while x < 5: print("Not there yet, x =" + str(x)) x = x + 1 print("x = "+str(x)) #current = 1 def count_down(start_number): current = start_number while (current > 0): print(current) current -= 1 #current = current -1 print("Zero!") count_down(3) """ Print prime numbers A prime factor is a number that is prime and divides another without a remainder. """ def print_prime_factors(number): # Start with two, which is the first prime factor = 2 # Keep going until the factor is larger than the number while factor <= number: # Check if factor is a divisor of number if number % factor == 0: # If it is, print it and divide the original number print(factor) number = number / factor else: # If it's not, increment the factor by one factor = factor + 1 return "Done" print_prime_factors(100) """ The multiplication_table function prints the results of a number passed to it multiplied by 1 through 5. An additional requirement is that the result is not to exceed 25, which is done with the break statement. """ def multiplication_table(number): # Initialize the starting point of the multiplication table multiplier = 1 # Only want to loop through 5 while multiplier <= 5: result = number * multiplier # What is the additional condition to exit out of the loop? if result > 25 : break print(str(number) + "x" + str(multiplier) + "=" + str(result)) # Increment the variable for the loop multiplier += 1 multiplication_table(3) """ Print multiplication tables """ def multiplication_table(number,limit): # Initialize the starting point of the multiplication table multiplier = 1 # Only want to loop through 5 while multiplier <= limit: result = number * multiplier # What is the additional condition to exit out of the loop? #if result > 25 : # break print(str(number) + " x " + str(multiplier) + " = " + str(result)) # Increment the variable for the loop multiplier += 1 multiplication_table(3,10) # break statement i = 0 while True: print("Iteration number "+ str(i)) i = i + 1 if i == 10: break print("Final value :" +str(i))
true
dd0c19ae77a22d440a86212bb03966d240c56b91
Robbot/ibPython
/src/IbYL/Classes/Polymorphism.py
1,050
4.1875
4
''' Created on 16 Apr 2018 @author: Robert ''' class network: def cable(self): print('I am the cable') def router(self): print('I am the router') def switch(self): print('I am the switch') def wifi(self): print('I am wireless router, cable does not matter') class tokenRing(network): def cable(self): print('I am a token ring cable') def router(self): print('I am a token ring router') class ethernet(network): def cable(self): print('I am a ethernet cable') def router(self): print('I am a ethernet router') def main(): windows=tokenRing() mac=ethernet() #example of polimorphism - this is the same method cable but it takes data from different classes and gives different results windows.cable() mac.cable() # below it is even better implemented for obj in (windows, mac): obj.cable() obj.router() # obj.wifi is not definied in class windows or mac but it is taken from class network obj.wifi() main()
true
7999ace79084e36c7190d8a1bd42eca5daad30f6
leon-sleepinglion/daily-interview-pro
/014 Number of Ways to Climb Stairs/main.py
413
4.15625
4
''' If we look at the solution as a function f(n) where n = number of steps f(1) = 1 f(2) = 2 f(3) = 3 f(4) = 5 f(5) = 8 f(6) = 13 This is in fact a fibonacci sequence! Hence the solution can be implemented as a function that calculates the (n+2)th fibonacci number ''' def staircase(n): x = [0,1] for i in range(n): x.append(x[-1]+x[-2]) return x[-1] print(staircase(4)) # 5 print(staircase(5)) # 8
true
0493b5cd7e50e3b1acd3487d7f0db5c13e9c6e15
AT1924/Homework
/hw10/functional.py
1,772
4.15625
4
class InvalidInputException(Exception): def __str__(self): return "Invalid Input Given." def apply_all(f_list, n): """apply_all: [function], number -> [number] Purpose: applies each function in a list to a single number Consumes: a list of functions and a number Produces: a list of numbers where each number is the result of a function application Exceptions: InvalidInputException if any of the inputs are None Example: function_apply([lambda x: x+1, lambda x: x+2, lambda x: x+3], 4) --> [5,6,7] """ return map(lambda f: f(n), f_list) def compose(f_list, n): """compose: [function], number -> number Purpose: composes all of the functions in a list and applies this to a number Consumes: a list of functions and a number Produces: a number that is the result of composing all of the functions in the list and applying this to the number argument Exceptions: InvalidInputExceiption if any of the inputs are None Example: compose([lambda x: x+1, lambda x: x+2, lambda x: x+3], 4) --> 10 """ def comp2(f1, f2): return lambda x: f1(f2(x)) composed = reduce(comp2, f_list) composed = reduce(lambda x, y: lambda z: x(y(z)), f_list) return composed(n) def list_compose_steps(f_list, n): """list_compose_steps: [function], number -> [number] Purpose: shows all intermediate steps of compose starting with the input number n Consumes: a list of functions and a number Produces: a list of numbers that represent the intermediate steps of compose Exceptions: InvalidInputExceiption if any of the inputs are None Example: list_compose_steps([lambda x: x+1, lambda x: x+2, lambda x: x+3], 4) --> [4, 5, 7, 10] """ return []
true
33655816cfafa233b306d61f4534338cebeced0a
Lord-Gusarov/holbertonschool-higher_level_programming
/0x06-python-classes/1-square.py
514
4.21875
4
#!/usr/bin/python3 """ Task 1 Write a class Square that defines a square by >Private instance attribute: size >Instantiation with size (no type/value verification) >You are not allowed to import any module """ class Square: """ A class that defines a Square """ def __init__(self, size): """Initializes and instance of class Square takes the size and sets it for the new instance Args: size: size for the new instance """ self.__size = size
true
3f48b004bfa01617330bbcc06c11751187786c86
Lord-Gusarov/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-write_file.py
319
4.1875
4
#!/usr/bin/python3 """Task: Write to a file """ def write_file(filename="", text=""): """writes to a file, overtwiting it if it exist Args: filename (str): desire name of the output file text (str): what is to be written """ with open(filename, 'w') as f: return f.write(text)
true
f636dc47edfa679588c09af316acb7a9fc07db5e
Lord-Gusarov/holbertonschool-higher_level_programming
/0x06-python-classes/2-square.py
960
4.46875
4
#!/usr/bin/python3 """Task2 Write a class Square that defines a square by Private instance attribute: size Instantiation with optional size: def __init__(self, size=0): Size must be an integer, otherwise raise a TypeError exception with the message size must be an integer If size is less than 0, raise a ValueError exception with the message size must be >= 0 """ class Square: """Defines a Square class with an integer size equal or greater than zero """ def __init__(self, size=0): """Initializer, validates given size for correct type and fo correct value. If one of these is not correct, and exception is raised Args: size (int): must be an integer greater or equal to zero """ if type(size) is not int: raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") self.__size = size
true
e38e998dba656061bb5af65d2cd338e0bd30de8b
xinyifuyun/-Python-Programming-Entry-Classic
/chapter_three/02.py
310
4.21875
4
a = ("first", "second", "third") print("The first element of the tuple is %s" % a[0]) print("The second element of the tuple is %s" % a[1]) print("The third element of the tuple is %s" % a[2]) print("%d" % len(a)) print(a[len(a) - 1]) b = (a, "b's second element") print(b[1]) print(b[0][0]) print(b[0][2])
true
b050f7dcbcc0a529ec03ac638af6c04cac4e6026
Aneeka-A/Basic-Python-Projects
/addition_problems.py
1,561
4.5625
5
""" File: addition_problems.py ------------------------- This piece of code will create addition problems (with 2 digit numbers). New problems will continue to be displayed until the user gets 3 correct answes in a row. """ import random # Declaring the minimum and the maximum numbers that can appear in the question. MIN_NUM = 10 MAX_NUM = 99 # Declaring the number of times one has to give correct answers in a row to master the addition program. MASTER_ADD = 3 def main(): """ This program will produce random addition problems consisting of only two digit numbers that the user will have to answer. The program will have to keep producing problems until the user masters the addition problems, i.e., until the user answers 3 problems correctly in a row. """ correct_in_a_row = 0 while correct_in_a_row < 3: num_1 = random.randint(MIN_NUM, MAX_NUM) num_2 = random.randint(MIN_NUM, MAX_NUM) print("What is " + str(num_1) + " + " + str(num_2) + " ?") expected_ans = int(num_1) + int(num_2) expected_ans = int(expected_ans) inp_ans = input("Your answer: ") inp_ans = int(inp_ans) if inp_ans == expected_ans: correct_in_a_row += 1 print("Correct1 You've gotten {} correct in a row.".format(correct_in_a_row)) else: correct_in_a_row = 0 print("Incorrect. The expected answer is " + str(expected_ans)) print("Congratulations! You mastered addition.") if __name__ == '__main__': main()
true
d001674dd6a054da8536bdfb8565cb423a5e49e2
Onselius/mixed_projects
/factors.py
741
4.34375
4
#! /usr/bin/python3 # factors.py # Finding out all the factors for a number. import sys def check_args(): if len(sys.argv) != 2: print("Must enter a number") sys.exit() elif not sys.argv[1].isdigit(): print("Must enter a number") sys.exit() else: return True check_args() number = int(sys.argv[1]) factors = [str(1), str(number)] lower = 2 upper = number while lower < upper: if number % lower == 0: upper = int(number / lower) factors.append(str(lower)) factors.append(str(upper)) lower += 1 factors = list(set(factors)) factors.sort(key=int) if len(factors) == 2: print("%s is a prime!" % (number)) factors = ", ".join(factors) print(factors)
true
882145ab3ef396f1cf082b5a6e912dad48597167
chnandu/practice-problems
/string-problems/unique_chars.py
644
4.25
4
#!/usr/bin/python # Check if given string has all unique characters or not def check_uniqueness(str_): """Check if given string has all unique characters and return True :param str_: Given string :returns: True, if all characters are unique. Else, False. """ char_dict = {} for c in str_: if char_dict.get(c) is None: char_dict[c] = 1 else: print("Duplicate character: %s" % c) return False return True if __name__ == "__main__": inputs = ["abcdfhefef", "abcdefgh", "1234", "foo"] for i in inputs: print("%s --> %s" % (i, check_uniqueness(i)))
true
4327f65151e2054c6ece88b694faa02ec3449d09
Shaaban5/Hard-way-exercises-
/py files/ex9+10.py
897
4.15625
4
days = "Mon Tue Wed Thu Fri Sat Sun" months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\tso on" # \n print in new line & \t print tap print "Here are the days: ", days print "Here are the months: ", months print """ There's something going on here. With the three double- quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6. """ print "I am 6'2\" tall." # put \ before double qoute to tel python just print print 'I am 6\'2" tall.' # put \ before qoute to tel python just print print "I am 6'2\\ \" tall." # double backslash to tell python print it i need it in my txt tabby_cat = "\tI'm tabbed in." persian_cat = "I'm split\non a line." backslash_cat = "I'm \\ a \\ cat." fat_cat = """ I'll do a list: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass """ print tabby_cat print persian_cat print backslash_cat print fat_cat
true
44f95e83ddebe7cf08f73ca9c9e66e4307b1ae58
Shaaban5/Hard-way-exercises-
/py files/ex27+28.py
1,613
4.1875
4
print True and True # T print False and True # F print 1 == 1 and 2 == 1 # F print "test" == "test" # T print '\n' print 1 == 1 or 2 != 1 # T print True and 1 == 1 # T print False and 0 != 0 # F print True or 1 == 1 # T print '\n' print "test" == "testing" # F print 1 != 0 and 2 == 1 # F print "test" != "testing" # T print "test" == 1 # F print '\n' print not (True and False) # T print not (1 == 1 and 0 != 1) # F print not (10 == 1 or 1000 == 1000) # F print not (1 != 10 or 3 == 4) # F print '\n' print not ("testing" == "testing" and "Zed" == "Cool Guy") # T print 1 == 1 and not ("testing" == 1 or 1 == 0) # T print "chunky" == "bacon" and not (3 == 4 or 3 == 3) # F print 3 == 3 and not ("testing" == "testing" or "Python" == "Fun") # F print '\n' print 'test' <= "test" # T # QUOTE OR DOUBLE Q DOESNT AFFECT print 'test' <= 'testI' # T print 'test' <= 'test-ING' # T # CHECK SAME ORDER AND THEN COMPARE print 'test' <= 'ING-test' # F # order is important print '\n' print True and 'aaaaaaa' # 1st check right side if true check left side then return last one checked print False and 'aaaaaaa' # 1st check right side found false then return false without checked left side print 'aaaaaaa' and True ,'\t', 'aaaaaaa' and False # it hase to check the left side print '\n' print True or 1 # the oppist in 'or' 1st check right side if rtuen true and doesnt check left side print False or 1 # 1st check right side if false check left side and return last one checked print 1 or False,'\t',1 or True # doesnt have to check the left side print any and True , any and False
true
9fd35de9093f9f05025455b55fb72eb32d2f698d
AsmitaKhaitan/Coding_Challenge_2048
/2048_game.py
1,920
4.40625
4
#importing the Algorithm.py file where all the fuctions for the operatins are written import Algorithm import numpy as np #Driver code if __name__=='__main__': #calling start() function to initialize the board board= Algorithm.start() while(True): t = input("Enter the number (move) of your choice : ") #since 3 is for moving UP if(t=='3'): #calling the up function to carry out operation board,c= Algorithm.up(board) #calling function to get the current status of the game curr= Algorithm.state(board) print(curr) #if game is not over then add a random 2 or 4 if(curr == 'CONTINUE PLAYING, THE GAME IS NOT YET OVER!!!'): Algorithm.add_num(board) else : break #the same process like the above if condition is followed for down, left and right #since "4" is for moving down elif(t=='4'): board,c=Algorithm.down(board) curr= Algorithm.state(board) print(curr) if(curr == 'CONTINUE PLAYING, THE GAME IS NOT YET OVER!!!'): Algorithm.add_num(board) else : break #since "1" is for moving left elif(t=='1'): board,c=Algorithm.left(board) curr= Algorithm.state(board) print(curr) if(curr == 'CONTINUE PLAYING, THE GAME IS NOT YET OVER!!!'): Algorithm.add_num(board) else : break #since "2" is for moving right elif(t=='2'): board,c=Algorithm.right(board) curr= Algorithm.state(board) print(curr) if(curr == 'CONTINUE PLAYING, THE GAME IS NOT YET OVER!!!'): Algorithm.add_num(board) else : break else: print("Invalid choice of move, sorry!") #print the board after each move print(np.matrix(board))
true
1978e3ac3665e1c5b096ee01da1da17a967873cd
ckitay/practice
/MissingNumber.py
998
4.3125
4
# All numbers from 1 to n are present except one number x. Find x # https://www.educative.io/blog/crack-amazon-coding-interview-questions # n = expected_length # Test Case 1 , Expect = 6 from typing import List from unittest import TestCase class Test(TestCase): def test1(self): self.assertEqual(find_missing_number([3, 7, 1, 2, 8, 4, 5], 8), 6) def test2(self): self.assertEqual(find_missing_number([3, 1], 3), 2) def test3(self): self.assertEqual(find_missing_number([2], 2), 1) def find_missing_number(nums: List[int], expected_length: int) -> List[int]: # Find sum of all values in nums sum_nums = sum(nums) # Created expectedNums, starting with 1 and ending with expected_length # expected + 1 because there is exactly 1 number missing expected_nums = range(1, expected_length + 1) # Find sum of all expectedNums values sum_expected = sum(expected_nums) # Return Missing number return sum_expected - sum_nums
true
452b696d838bfd7d77b0c02ea9129f168d6b1786
SuproCodes/DSA_PYTHON_COURSE
/OOP.py
1,994
4.125
4
class Employee: def __init__(self, name): self.name = name def __repr__(self): return self.name john = Employee('John') print(john) # John #---------------------------- # Dog class class Dog: # Method of the class def bark(self): print("Ham-Ham") # Create a new instance charlie = Dog() # Call the method charlie.bark() # This will output "Ham-Ham" #----------------------------- class Car: "This is an empty class" pass # Class Instantiation ferrari = Car() #----------------------------- class my_class: class_variable = "I am a Class Variable!" x = my_class() y = my_class() print(x.class_variable) #I am a Class Variable! print(y.class_variable) #I am a Class Variable! #----------------------------- class Animal: def __init__(self, voice): self.voice = voice # When a class instance is created, the instance variable # 'voice' is created and set to the input value. cat = Animal('Meow') print(cat.voice) # Output: Meow dog = Animal('Woof') print(dog.voice) # Output: Woof #------------------------------- a = 1 print(type(a)) # <class 'int'> a = 1.1 print(type(a)) # <class 'float'> a = 'b' print(type(a)) # <class 'str'> a = None print(type(a)) # <class 'NoneType'> #------------------------------- # Defining a class class Animal: def __init__(self, name, number_of_legs): self.name = name self.number_of_legs = number_of_legs #----------------------------- class Employee: def __init__(self, name): self.name = name def print_name(self): print("Hi, I'm " + self.name) print(dir()) # ['Employee', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'new_employee'] print(dir(Employee)) # ['__doc__', '__init__', '__module__', 'print_name'] #--------------------------- #<class '__main__.CoolClass'> #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
true
f6e13f9d47f8524f63c175d086f49de917c678d4
vipin-s0106/DataStructureAndAlgorithm
/Linkedlist/reverse_linked_list.py
1,465
4.125
4
class Node: def __init__(self, data): self.data = data self.next = None class Linkedlist: def __init__(self): self.head = None def add(self, data): new_node = Node(data) if self.head is None: self.head = new_node else: temp = self.head while (temp.next != None): temp = temp.next temp.next = new_node def print_list(self): temp = self.head while (temp != None): print(temp.data, end=" ") temp = temp.next print("") def linkedlist_length(self): count = 0 temp = self.head while temp is not None: count += 1 temp = temp.next return count def reverse_linked_list(self): prev = None current = None fast = self.head while fast != None: current = fast fast = fast.next current.next = prev prev = current self.head = current def reverseLinkedList_recursion(self,prev,cur): if cur == None: return self.reverseLinkedList_recursion(cur,cur.next) if cur.next == None: self.head = cur cur.next = prev l = Linkedlist() l.add(1) l.add(2) l.add(3) l.add(4) l.add(6) l.print_list() l.reverse_linked_list() l.print_list() l.reverseLinkedList_recursion(None,l.head) l.print_list()
true
fd879e688bc00a100698b5f53fcf5731c22ebcd4
AlanAloha/Learning_MCB185
/Programs/completed/at_seq_done.py
694
4.1875
4
#!/usr/bin/env python3 import random #random.seed(1) # comment-out this line to change sequence each time # Write a program that stores random DNA sequence in a string # The sequence should be 30 nt long # On average, the sequence should be 60% AT # Calculate the actual AT fraction while generating the sequence # Report the length, AT fraction, and sequence seq = '' at_count = 0 for i in range(30): n = random.randint(1,10); print(n,end=' ') if 1<=n<=3: seq+='A' at_count+=1 elif 4<=n<=6: seq+='T' at_count+=1 elif 7<=n<=8: seq+='G' else: seq+='C' print('\n',len(seq), at_count/len(seq), seq) """ python3 at_seq.py 30 0.6666666666666666 ATTACCGTAATCTACTATTAAGTCACAACC """
true
01d632d6197fb44a76eadc59fba2ea73f48d3c70
jptheepic/Sudoku_Solver
/main.py
2,359
4.21875
4
#The goal of this project is to create a working sudoku solver #This solution will implement recustion to solve the board #This function takes in a 2D array and will print is as a sudoku board def print_board(board): for row in range(0,len(board)): for col in range(0,len(board)): #prints the boarder for the right side of the board if col ==0: print("|",end=' ') #Prints the boarder for the right side of the board if col ==8: endline = ' |\n' elif (col+1)%3 == 0: endline = "|" elif (row+1)%3 == 0: endline = "_" else: endline = " " if board[row][col] ==0: print(" ", end=endline) else: print(board[row][col], end=endline) #This function takes in a postion and a number and returns weather the placement is valid def valid(board, row, col,number): #Checks to see if that number shares a row for i in range(0,len(board)): if (board[row][i] == number and col != i): return False #checks to see if that number shars a col for j in range(0,len(board)) : if (board[j][col] == number and row != j): return False #This is the logic used to check if the nuber shares a box x = (col//3)*3 y = (row//3)*3 for i in range(y, y + 3): for j in range(x , x + 3): if (board[i][j] == number ): return False return True def find_empty(board): for row in range(len(board)): for col in range(len(board)): if board[row][col] == 0: return (row,col) return None def solve(board): empty_position = find_empty(board) #If no more empty positions return true if not empty_position: return True else: row, col = empty_position for num in range(1,10): if valid(board,row,col,num): board[row][col] = num if solve(board): return True board[row][col] = 0 return False if __name__ == '__main__': board =[ [7,8,0,4,0,0,1,2,0], [6,0,0,0,7,5,0,0,9], [0,0,0,6,0,1,0,7,8], [0,0,7,0,4,0,2,6,0], [0,0,1,0,5,0,9,3,0], [9,0,4,0,6,0,0,0,5], [0,7,0,3,0,0,0,1,2], [1,2,0,0,0,7,4,0,0], [0,4,9,2,0,6,0,0,7]] print('#'*8 + " Original Board " +'#'*8) print_board(board) print('#'*8 + " Sovled Board " +'#'*8) solve(board) print_board(board)
true
959f6649dcedb7c3521a54fcf325126b3a5cc4b9
Lamchungkei/Unit6-02
/yesterdays.py
830
4.3125
4
# Created by: Kay Lin # Created on: 28th-Nov-2017 # Created for: ICS3U # This program displays entering the day of the week then showing the order from enum import Enum # an enumerated type of the days of the week week = Enum('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday') # input print('Sunday(1), Monday(2), Tuesday(3), Wednesday(4), Thursday(5), Friday(6), Saturday(7)') input_day = raw_input('Enter your favorite day of the week: ') # process input_day = input_day.title() if input_day in week: counter = 1 for a_day in week: if input_day == str(a_day): print (str(counter) + ' is the number that corresponds to your favourite day of the week') else: counter = counter + 1 else: print('Please input valid day') print('\n')
true
854300cb49d11a58f9b72f1f3a59d4a12012cd9c
jb3/aoc-2019
/day-3/python/wire.py
1,486
4.15625
4
"""Structures relating to the wire and points on it.""" import typing from dataclasses import dataclass @dataclass class Point: """Class representing a point in 2D space.""" x: int y: int def right(self: "Point") -> "Point": """Return a new point 1 unit right of the point.""" return Point(self.x + 1, self.y) def left(self: "Point") -> "Point": """Return a new point 1 unit left of the point.""" return Point(self.x - 1, self.y) def up(self: "Point") -> "Point": """Return a new point 1 unit up from the point.""" return Point(self.x, self.y + 1) def down(self: "Point") -> "Point": """Return a new point 1 unit down from the point.""" return Point(self.x, self.y - 1) def __hash__(self: "Point") -> int: """Convert the Point to a form which Python can hash.""" return hash((self.x, self.y)) def manhattan_distance(self: "Point", other: "Point") -> int: """Calculate the manhattan distance between two points.""" return abs(self.x - other.x) + abs(self.y - other.y) class Wire: """Class reprensenting an electrical wire.""" def __init__(self: "Wire", points: typing.List[Point]) -> None: """Instantiate a new wire given a list of points.""" self.points = points def dist_to(self: "Wire", point: Point) -> int: """Calculate how far along the wire this point is.""" return self.points.index(point)
true
647d1d36759511e86ef6434c8a59daf7b345e888
AnushSomasundaram/Anush_Python_projects
/Anush_assignments/1st_sem/python/first assignment/area_of_triangle.py
221
4.15625
4
#Write a program to find the area of triangle given # base and height. def area_of_triangle(height,base): area = 0.5*height*base print("The area of the given trianle is ",area,"units.") area_of_triangle(1,6)
true
1c527311d782ceeec6e04e27d6f4b70e0532f9e4
AnushSomasundaram/Anush_Python_projects
/chap4_fuctions/lambda.py
458
4.25
4
#lambda functions are just inline functions but specified with the keyword lambda def function_1(x):return x**2 def function_2(x):return x**3 def function_3(x):return x**4 callbacks=[function_1,function_2,function_3] print("\n Named Functions") for function in callbacks: print("Result:",function(3)) callbacks=\ [lambda x:x**2,lambda x:x**3,lambda x:x**4] print("Anonymous Functions:") for function in callbacks: print("Result",function(3))
true
3b9a3df013329cc99b8ac392ca6d1f2c1bbcbcde
AnushSomasundaram/Anush_Python_projects
/compsci_with_python/chap2/largestword.py
310
4.125
4
length= int(input("Enter the number of elements in the list")) words=[] for i in range (0,length): print("Word no.",i,":-") words.append(str(input())) longest=0 for i in range (1,length): if len(words[i])>len(words[longest]): longest=i print("longest word is :-",words[longest])
true
cb7875e93bb7619218691f2beba46a87f691d96c
AnushSomasundaram/Anush_Python_projects
/Anush_assignments/1st_sem/python/first assignment/operations.py
598
4.125
4
"""Write a Python program that allows the user to enter two integer values, and displays the results when each of the following arithmetic operators are applied. For example, if the user enters the values 7 and 5, the output would be, 7+5=12 7-5=2 and so on.""" number1=int(input("Please enter the first integer:-")) number2=int(input("\nPlease enter the second integer:-")) sum=number1+number2 difference=number1-number2 print("\The sum of the two integers is",number1,"+",number2,"=",sum," .") print("\nThe difference between the two integers is",number1,"-",number2,"=",difference," .")
true
76d43d9bc8db00125fde1eb88ffb25d7546b43c8
MithilRocks/python-homeworks
/bitwise_homework/divisible_by_number.py
399
4.3125
4
# hw: wtp to check if a number is multiple of 64 def divisible_by_number(num): if num & 63 == 0: return True else: return False def main(): number = 128 if divisible_by_number(number): print("The number {} is divisble by 64".format(number)) else: print("The number {} is not divisble by 64".format(number)) if __name__ == "__main__": main()
true
0880f00fcc0cda49c2cbd4de54e5ed0969156f3b
MYadnyesh/Aatmanirbhar_program
/Week 1/add.py
512
4.15625
4
#Program 1:- Addition of 2 numbers def add(x,y): print("The addition is : ") return x+y while True: print(add(int(input("Enter 1st number: ")),int(input("Enter 2nd number: ")))) a=input("Do you want to continue (Press Y to continue)") if(a=='y' or a=='Y') is True: continue else: break #***********Output********** # Enter 1st number: 45 # Enter 2nd number: 55 # The addition is : # 100 # Do you want to continue (Press Y to continue)y # Enter 1st number:
true
b45735562a84f066be681ba592a610118e6da06c
MYadnyesh/Aatmanirbhar_program
/Week 1/primeIntr.py
633
4.1875
4
#Program 2 :- To print all the Prime numbers in an given interval lower = int(input("Enter a starting number")) upper = int(input("Enter a ending number ")) print("Prime numbers between", lower, "and", upper, "are:") for num in range(lower, upper + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) # ******OUTPUT****** # Enter a starting number100 # Enter a ending number 200 # Prime numbers between 100 and 200 are: # 101 # 103 # 107 # 109 # 113 # 127 # 131 # 137 # 139 # 149 # 151 # 157 # 163 # 167 # 173 # 179 # 181 # 191 # 193 # 197 # 199
true
a177115cde3a19cf9e2397aa844610b5a62ffb0c
CIS123Sp2020A/extendedpopupproceed-tricheli
/main.py
614
4.21875
4
#Tenisce Richelieu from tkinter import import tkinter.messagebox as box #The first step after imports is crate a window window = Tk() #This shows up at the top of the frame window.title('Message Box Example') #create the dialog for the window def dialog(): var = box. askyesno('Message Box', 'Proceed?') if var == 1: box.showinfo('Yes Box', 'Proceeding...') else: box.showwarning('No Box', 'Cancelling...') #creating a button btn = Button(window, text='Click', command= dialog) #have to pack the button btn.pack(padx = 150, pady = 50) #start the action and keep it going window.mainloop()
true
7ec6c5f2363d20cdd567aff4f9cc48718e77f895
silastsui/pyjunior
/strloops/backwards.py
551
4.15625
4
#!/usr/bin/python #backwards text = str(raw_input("Enter a phrase: ")) #solution1 (wat) print text[::-1] #solution2 (for x in range) reverse = "" a = len(text) for x in range(len(text)-1, -1,-1): reverse += text[x] print reverse #solution3 (for let in text) backwards = "" for let in text: backwards = let + backwards print backwards #solution4 (reverse) def reverse(text): if len(text) <= 1: return text return reverse(text[1:]) + text[0] print reverse(text) #solution5 reverse = "" for x in reversed(text): reverse += x print reverse
true
1802b34d83cbfb6b9026a99c6e30da00d950fa5c
strikingraghu/Python_Exercises
/Ex - 04 - Loops.py
2,676
4.125
4
""" In general, statements are executed sequentially. The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. Programming languages provide various control structures that allow for more complicated execution paths. Loop Type & Description WHILE LOOP Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body. FOR LOOP Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. NESTED LOOP You can use one or more loop inside any another while loop, for loop or do..while loop. """ # While Loop simple_count = 0 while simple_count < 10: simple_count += 1 print("Loop Executed =", simple_count) print("Good Bye!") print("--------------------------") another_count = 0 while another_count < 5: another_count += 1 print(another_count, "is the while loop's value") else: if another_count == 5: print("Ending while loop execution!") print("--------------------------") # Takes user's input user_input = int(input("Enter an integer value :")) total_value = 0 iterable_value = 1 while iterable_value <= user_input: total_value = total_value + iterable_value iterable_value += 1 print("Sum Value =", total_value) print("End of the execution") print("--------------------------") # For Loop sample_string = 'Bangalore' for each_letter in sample_string: print(each_letter) print("Printed every letter of the word :", sample_string) print("--------------------------") # For Loop (Includes Indexing) fruits = ['Mango', 'Apple', 'Pine', 'Orange', 'Papaya'] for each_fruit in fruits: print("Fruit Name =", each_fruit, "& it's Index value =", fruits.index(each_fruit)) print("Good Bye!") print("--------------------------") # For Loop (Is this a Prime number?) for num in range(10, 20): for i in range(2, num): if num % i == 0: j = num / i print('%d equals %d * %d' % (num, i, j)) break else: print(num, 'is a prime number') print("Good Bye!") print("--------------------------") # Nested Loop x = 2 while x <= 100: y = 2 while y <= x / y: if not x % y: break y += 1 if y > x / y: print(x, " is a prime number") x += 1 print("Done") print("--------------------------")
true
d5d43273000fb4a88b57e33c5fa7377264f2a707
strikingraghu/Python_Exercises
/Ex - 14 - File Handling.py
1,925
4.53125
5
""" In this article, you'll learn about Python file operations. More specifically, opening a file, reading from it, writing into it, closing it and various file methods. """ import os # Opening File file_open = open("c:/python_file.txt") print(file_open) # We can see the path of file, mode of operation and additional details! print("Class =", type(file_open)) # Reading Contents print("--------------------------") print(file_open.read()) print("--------------------------") # Write Operations print("--------------------------") write_some_data = open("c:/python_write_operation.txt", 'w') # New File write_some_data.write("Contents available in this file is been pushed via Python script!\n" "However, you can read contents without any fees\n" "By the way, are you from Bangalore city?") write_some_data.close() write_some_data = open("c:/python_write_operation.txt", 'r') print(write_some_data.read()) write_some_data.close() print("--------------------------") # Reading Specific Lines write_some_data = open("c:/python_write_operation.txt", 'r') print(write_some_data.read(65)) # Specifically displaying few characters write_some_data.close() # File Object Attributes print("Is file closed? =", write_some_data.closed) # Returns TRUE / FALSE print("What is the file name? =", write_some_data.name) # Returns Name print("Can we see the file buffer information? =", write_some_data.buffer) # Returns Buffer! print("What is the file encoding results? =", write_some_data.encoding) # Returns File Encoding Relevant Info print("--------------------------") # Python Files & Directory Management # Import OS Module (@Start of this script) print("Current Working Directory =", os.getcwd()) os.chdir("C:\\Users\\") print("Changing Directory Path = Done") print("After Changing Directory Path =", os.getcwd())
true
5fa07f44836ffb22fcd8a237bc1cf8e572c154ac
strikingraghu/Python_Exercises
/Ex - 08 - Tuples.py
2,146
4.28125
4
""" A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. Differences between tuples and lists are, the tuples cannot be changed unlike lists! Also, tuples use parentheses, whereas lists use square brackets. """ sample_tuple_01 = ('Ram', 3492, 'Suresh') sample_tuple_02 = (28839.23, 'Hemanth', 684.J, 'Bangalore') print() print(sample_tuple_01) print(sample_tuple_02) # Displaying ID print("sample_tuple_01 - ID =", id(sample_tuple_01)) print("sample_tuple_02 - ID =", id(sample_tuple_02)) # Equality Test tuple_001 = ('Ram', 3492, 'Suresh') print() print("ID - tuple_001 =", id(tuple_001)) tuple_002 = tuple_001 print("ID - tuple_002 =", id(tuple_001)) print("Both tuples are having same ID's, where assignment attaches name to an object!") print("Assigning from one reference to another, puts two name tags to an object.") print(tuple_001) print(tuple_002) print("--------------------------") # Generic Tuple Operations tuple_007 = ('Yogesh', 'Bangalore', 'Idly', 329091, 293.3772, 'Delhi', 291, 952, 'KKR', 'RCB', 'Virat') tuple_008 = (3881, 9486142938.4992, 37, 887452.27610020991, 3889, 583, 8331) print("Length =", len(tuple_007)) print("Get Index Value =", tuple_007.index('Bangalore')) print("Tuple's Size =", tuple_007.__sizeof__()) print("Tuple's Class Info =", tuple_007.__class__) print("Value (Virat) Contains Test =", tuple_007.__contains__('Virat')) print("Value (Dhoni) Contains Test =", tuple_007.__contains__('Dhoni')) print("Object's Attributes List =", tuple_007.__dir__()) print("--------------------------") # Few Tuple Operations print("Get Value (Index Value 10) =", tuple_007.__getitem__(10)) print("Another Way - Tuple's Length (__len__) =", tuple_007.__len__()) tiny_tuple = ('Chennai', 'Modi') print("After Adding 2 Elements - ID Changed =", id(tuple_007.__add__(tiny_tuple))) print("However, 'tuple_007' ID =", id(tuple_007)) print("Max Element =", max(tuple_008)) print("Min Element =", min(tuple_008)) print("All Elements Iterable? all() =", all(tuple_008)) print("--------------------------")
true
041fa7d58b4c8916abf660eb1bfa82ff8f1b0b6f
SaketSrivastav/epi-py
/trees/check_bst.py
1,156
4.1875
4
#! /usr/bin/python class Check_Bst(): def check_balanced(self, node): """ Input: A tree node Output: (+)ve number if BST is balanced, otherwise -1 Description: Start with root node and calculate the height of the left subtree and right subtree. If an absolute difference of heght of left and right subtree is 0 or 1 then we say the tree node at N is balanced otherwise its unbalanced. """ #Base Case if not node: return 0 # Check if left subtree is balanced left_height = self.check_balanced(node.left) if left_height == -1: return -1 # Check if right subtree is balanced right_height = self.check_balanced(node.right) if right_height == -1: return -1 # If both subtree are balanced if abs(left_height - right_height) > 1: return -1 # Return the height of node n return (1 + max(left_height, right_height)) def check_bst(self, my_bst): is_balanced = self, self.check_balanced(my_bst.get_root()) return is_balanced
true
454081e675b5dfb9a82293d3a79fa2ff90be90fc
rakibkuddus1109/pythonClass
/polymorphism.py
763
4.375
4
# polymorphism : Many ways to define the method # Method overloading # Method overriding # Method overloading: Considering relevant methods based upon no. of arguments that method has # even though the method names are same # Python doesn't support method overloading # class Operation: # def mul(self,a,b,c): # return (a+b)*(a-c) # def mul(self,a,b): # return a*b # # def mul(self,a,b,c): # # return (a+b)*(a-c) # obj = Operation() # print(obj.mul(4,5)) # Method overriding: Considering the child class method even though parent class method is present class First: def add(self,a,b): return a+b class Second(First): def add(self,a,b): return a*b obj = Second() print(obj.add(5,6))
true
99355f7b9957a8dcd2c176e4436969861e571a2b
rakibkuddus1109/pythonClass
/exception_handling.py
1,837
4.34375
4
# Exception Handling: Handling the exception or error # In-built exception : comes with programming language itself # User-defined exception : setting up our own defined exception # In-built exception: # a = [6,5.6,'Python',0,67] # for j in a: # print(1/j) # this would give in-built exception when 'Python' would come for division """ try: <statement> except: <statement> """ # try : those lines which may give an error, has to be written inside 'try' block # except : statements which should be executed after error occurance, comes under 'except' block # 'try' block should have minimum one 'except' block # import sys # importing to know the type of error # a = [6,5.6,'Python',0,67] # a = [6,5.6,'Python',0,67,(12,23)] # for j in a: # try: # print(1/j) # # except: # # print("Error has occured for",j,sys.exc_info()[0]) # except TypeError: # print("You have tried to divide with different type of data") # except ZeroDivisionError: # print("You are trying to divide by 0") # except: # print("Undefined error has occured!") # print("Execution is over.") # User-defined exception: class ValueSmallError(Exception): # Inherit "Exception" class to make it as an exception class pass class ValueLargeError(Exception): pass num1 = int(input("Enter num1 value:")) while True: try: num2 = int(input("Enter num2 value:")) if num2 < num1: raise ValueSmallError # to call exception class use "raise" elif num2 > num1: raise ValueLargeError else: print("Number guessed correctly!") break except ValueSmallError: print("Value entered is smaller, try again!") except ValueLargeError: print("Value entered is larger, try again!")
true