blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
208a814d1ffce74cd1bd7eaedb39395b76ddba70
huangichen97/SC101-projects
/SC101 - Github/Class&Object (Campy, Mouse Event)/draw_line.py
1,837
4.125
4
""" File: draw_line Name:Ethan Huang ------------------------- TODO: This program opens a canvas and draws circles and lines in the following steps: First, it detect if the click is a "first click" or a "second click". If first click, the program will draw a hollow circle by SIZE. If second click, the it will create a line from the circle to the new click, and also delete the circle and then start a new round. """ from campy.graphics.gobjects import GOval, GLine from campy.graphics.gwindow import GWindow from campy.gui.events.mouse import onmouseclicked SIZE = 10 is_first = True circle_x = 0 circle_y = 0 circle = 0 window = GWindow() def main(): """ This program creates lines on an instance of GWindow class. There is a circle indicating the user’s first click. A line appears at the condition where the circle disappears as the user clicks on the canvas for the second time. """ onmouseclicked(draw) def draw(mouse): global is_first, circle, circle_x, circle_y if is_first is True: # The click is a first click(1st, 3th, 5th, etc.) # Should draw a circle on the mouse click circle = GOval(SIZE, SIZE, x=mouse.x-SIZE/2, y=mouse.y-SIZE/2) window.add(circle) is_first = False # To make the next click a second click circle_x = mouse.x - SIZE / 2 circle_y = mouse.y - SIZE / 2 else: # The click is a second click(2nd, 4th, 6th, etc.) # Should draw a line from the circle(created by the first click) to the new click window.remove(circle) the_line = GLine(circle_x, circle_y, mouse.x, mouse.y) window.add(the_line) is_first = True # To make the next click a first click again if __name__ == "__main__": main()
true
45b1b9758b34f9ce252ff72bb3334c2e3f60e3aa
huangichen97/SC101-projects
/SC101 - Github/Weather_Master/weather_master.py
2,050
4.25
4
""" File: weather_master.py ----------------------- This program will implement a console program that asks weather data from user to compute the average, highest, lowest, cold days among the inputs. """ EXIT = -1 def main(): """ This program asks weather data from user to compute the average, highest, lowest, cold days among the inputs. """ print('stanCode "Weather Master 4.0"!') data = int(input('Next Temperature: (or ' + str(EXIT) + ' to quit)? ')) if data == EXIT: # No temperatures were entered. print('No temperatures were entered.') else: # The first data was entered. highest = data # The highest temperature. lowest = data # The lowest temperature. sum_temperature = data # The SUM of the temperatures. amount_of_data = 1 # Pieces of data users input. average = float(sum_temperature / amount_of_data) # The average temperature. if data < 16: # Check whether the first data is a cold day. cold_day = 1 else: cold_day = 0 while True: # The program will keep the loop until users input "EXIT". data = int(input('Next Temperature: (or ' + str(EXIT) + ' to quit)? ')) if data == EXIT: # The user exited from the program. break else: if data > highest: highest = data if data < lowest: lowest = data if data < 16: cold_day += 1 sum_temperature += data amount_of_data += 1 average = float(sum_temperature / amount_of_data) print('Highest temperature = ' + str(highest)) print('Lowest temperature = ' + str(lowest)) print('Average = ' + str(average)) print(str(cold_day) + ' cold day(s)') ###### DO NOT EDIT CODE BELOW THIS LINE ###### if __name__ == "__main__": main()
true
9b5bf68a2f25bfdb2a276fbaa481d28859a9acdf
dhyani21/Hackerrank-30-days-of-code
/Day 25: Running Time and Complexity.py
576
4.1875
4
''' Task A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Given a number, n, determine and print whether it is Prime or Not prime. ''' for _ in range(int(input())): num = int(input()) if(num == 1): print("Not prime") else: if(num % 2 == 0 and num > 2): print("Not prime") else: for i in range(3, int(num**(1/2))+1, 2): if num % i == 0: print("Not prime") break else: print("Prime")
true
fe6db5c4e41116d07e7d1c2990fe6ec5fd59d29f
Cathryne/Python
/ex12.py
581
4.34375
4
# Exercise 12: Prompting People # http://learnpythonthehardway.org/book/ex12.html # request input from user # shorter alternative to ex11 with extra print "" height = float(raw_input("How tall are you (in m)? ")) weight = int(raw_input("How many kilograms do you weigh? ")) print "So, you're %r m tall and %d kg heavy." % (height, weight) # shorter without "BMI" helper variable in ex11: calculate directly after print, even without string formatting print "That makes your BMI round about:", round(weight / ( height * height ), 1) # round(x, n) rounds x to n decimal places
true
e8b2fd46e39711a75e83f590a86ffa5433116a1e
Cathryne/Python
/ex38sd6c.py
2,251
4.6875
5
# Exercise 38: Doing Things To Lists # http://learnpythonthehardway.org/book/ex38.html # Study Drill 6: other examples of lists and what do do with them # comparing word lists # quote examples for testing # Hamlet = "To be, or not to be, that is the question." # https://en.wikipedia.org/wiki/To_be,_or_not_to_be#Text # Crusoe = "Thus fear of danger is ten thousand times more terrifying than danger itself." # https://www.goodreads.com/quotes/318230-thus-fear-of-danger-is-ten-thousand-times-more-terrifying # functionalised listing of character name & quote words into list def make_list(character, quote): import string quote_list = [character] word_list = quote.translate(None, string.punctuation) word_list = word_list.split(' ') print "\tOK, so %s said: " % character, word_list for i in range(len(word_list)): last_word = word_list.pop() quote_list.append(last_word) i =+ 1 # print quote_list return quote_list print "\tLet's play a literature game! You are going to tell me 2 famous quotes and I'm going to tell you, which words they have in common." character1 = str(raw_input("\tWho shall the 1st quote be from? ")) quote1 = str(raw_input("\tAnd what did they say? ")) quote1_list = make_list(character1, quote1) character2 = str(raw_input("\tNow, who shall the 2nd quote be from? ")) quote2 = str(raw_input("\tAnd the 2nd one? ")) quote2_list = make_list(character2, quote2) # determine longer quote & assign if len(quote1_list) <= len(quote2_list): reticent = character1 fewer_words = quote1 shorter_list = quote1_list verbose = character2 more_words = quote2 longer_list = quote2_list else: reticent = character2 fewer_words = quote2 shorter_list = quote2_list verbose = character1 more_words = quote1 longer_list = quote1_list print "\tIn other words, %s was reticent in saying:" % reticent, fewer_words print "\tWhile %s was verbose:" % verbose, more_words # compare quote lists & convert result to new list plagiates = set(quote1_list).intersection(quote2_list) plagiates = list(plagiates) # check if plagiates exist & display if len(plagiates) != 0: print "\tHa! Either %s or %s plagiarised the words from the other:" % (character1, character2), plagiates else: print "\tNo plagiate words found!"
true
88e7900015a7c199e6e605beb15189e211af78d0
Cathryne/Python
/ex03.py
1,550
4.21875
4
# Exercise 3: Numbers and Math # http://learnpythonthehardway.org/book/ex3.html # general advice: leave space around all numbers & operators in mathematical operations, to distinguish from other code & esp. negative numbers print "I will now count my chickens:" print "Hens", 25 + 30 / 6 # , comma forces calculation result into same line print "Roosters", 100 - 25 * 3 % 4 print "Now I will count the eggs:" print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 # result of mathematical operation is printed directly; "qoutes" only for strings # order PEMDAS (Parentheses, Exponents, Multiplication, Division, Addition & Subtraction) # modulo operator % returns remainder after division print "Is it true that 3 + 2 < 5 - 7 ?" print 3 + 2 < 5 - 7 # Boolean statement returns True or False print "What is 3 + 2 ?", 3 + 2 print "What is 5 - 7 ?", 5 - 7 print "Oh, that's why it's False." print "How about some more." print "Is it greater?", 5 > -2 print "Is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2 # Study Drill 5: Rewrite to use floating point numbers so it's more accurate (hint: 20.0 is floating point). # appending decimal point & 0 to each number # Also works with only relevant ones? print "And now the calculations again with floating points." print "Hens", 25 + 30 / 6.0 # no effect, because 30 can already be completely divided by 6 print "Roosters", 100 - 25 * 3 % 4.0 # no effect because remainder of 75 / 3 = 72 is the integer 3 print "Eggs:", 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4.0 + 6 # effect, because 1 / 4.0 = 0.25
true
71d9d2c25a82558c813523cd9c7a935ffcbf5d78
Cathryne/Python
/ex19sd3.py
1,477
4.21875
4
# Exercise 19: Functions and Variables # http://learnpythonthehardway.org/book/ex19.html # Study Drill 3: Write at least one more function of your own design, and run it 10 different ways. def milkshake(milk_to_blend, fruit_to_blend, suggar_to_blend): """ Calculates serving size and prints out ingredient amounts for milkshake. """ servings = int(raw_input("Oh yeah, I forgot! For how many servings shall all this be? ")) milk_to_serve = servings * milk_to_blend fruit_to_serve = servings * fruit_to_blend suggar_to_serve = servings * suggar_to_blend print "You'll need %d g fruit, %d mL milk and %d g of suggar. Will it blend?!" % (fruit_to_serve, milk_to_serve, suggar_to_serve) milk = 200 fruit = 50 suggar = 10 print "\nLet's make a milkshake! I know this recipe: Blend %d mL milk, %d g fruit and %d g suggar in a blender. However, you should adjust something..." % (milk, fruit, suggar) # get recipe modifiers from user; can be negative fruitiness = float(raw_input("... Like the fruitiness! How many % more or less do you want? ")) sweetness = float(raw_input("Same for the sweetness: ")) print "\n\nResults calculated in function call:" milkshake(milk, fruit * (1 + (fruitiness / 100)), suggar * (1 + (sweetness / 100))) print "\n\nResults calculated via helper variables:" milk_to_blend = milk fruit_to_blend = fruit * (1 + (fruitiness / 100)) suggar_to_blend = suggar * (1 + (sweetness / 100)) milkshake(milk_to_blend, fruit_to_blend, suggar_to_blend)
true
42f65b2819021a0201c2ce3ee82ba39318beb466
RahulSundar/DL-From-Scratch
/MLP.py
1,821
4.1875
4
import numpy as np #import matplotlib.pyplot as plt '''This is a code to implement a MLP using just numpy to model XOR logic gate.Through this code, one can hope to completely unbox how a MLP model is setup.''' # Model Parameters '''This should consist of the no. of input, output, hidden layer units. Also, no.of inputs and outputs. ''' N_HiddenLayers = 1 Total_layers = 3 N_training = 4 Ni_units = 2 Nh_units = 2 No_units = 1 #Training dataset '''Here we also define training examples.''' #input arrays x = np.zeros((N_training, Ni_units)) x[:,0] = [0,1,0,1] x[:,1] = [0,1,1,0] # Target Values target = np.zeros((N_training, No_units)) target[:,0] = [0,0,1,1] #hidden layer h = np.zeros((N_training,Nh_units)) #Output layer y = np.zeros((N_training, No_units)) #Weights and biases '''No. of weight matrices/biases a Total_layers - 1 = 2''' W1 = np.ones((Nh_units, Ni_units))/2 W2 = np.ones((No_units, Nh_units))/2 b1 = -np.ones((Nh_units, 1))*0.5 b2 = -np.ones((No_units, 1)) #Activation function: def sigmoid(z): return 1/(1+np.exp(-z)) def binary_threshold(z): return np.where(z>0, 1,0) #Model: MLP (Simplest FFNN) '''The model is set up as sequential matrix multiplications''' '''Activation applied only on hidden layers as of now. Input layer's activation function is identity.''' '''pre activation for input layer''' z1 = np.matmul(x,np.transpose(W1)) + np.matmul(np.ones((N_training,1)), np.transpose(b1)) '''Activation for hidden layer''' h = np.where(z1 >0, 1, 0) '''Pre - activation of output layer ''' z2 =np.matmul(x,np.transpose(W2)) + np.matmul(np.ones((N_training,1)), np.transpose(b2)) '''Activation for output layer''' y = np.where(z1 >0, 1, 0) #Loss Function '''Here, we shall be using mean squared error loss as the loss function''' J = np.sum((y-target)**2)/N_training print(J)
true
c2b21f2737be09db89a51add64f1d86907b28c00
arsenijevicn/Python_HeadFirst
/chapter4/vsearch.py
243
4.15625
4
def search4vowels(): """Displays any vowels found in asked-for word""" vowels = set('aeiou') word = input("Upisite rec: ") found = vowels.intersection(set(word)) for vowels in found: print(vowels) search4vowels()
true
4dcb541a4c110aee3f795e990b3f096f5d00014d
AyushGupta22/RandomNumGenerator
/test.py
749
4.25
4
from rand import random #Testing our random function by giving min , max limit and getting output as list and then compute percentage of higher number for reference print('Enter min limit') min = int(input()) print('Enter max limit') max = int(input()) while max <= min: print('Wrong max limit\nEnter Again: ') max = int(input()) print('Want to generate more than one number input Y') ch = input() n = 1 if ch == 'Y' or ch == 'y': print("input number of random no. you want to generate") n = int(input()) res = random(min,max,n) print('random numbers are :- ',res,sep='\n',end='\n') greater = [x for x in res if x > min+((max-min)/2)] print('percentage of higher numbers out of n =',n,' is ',len(greater)/n*100)
true
5a0f54795e5b2777ebe9b2e9fdbdb07ee7db5e33
adilarrazolo83/lesson_two_handson
/main.py
714
4.28125
4
# Part 1. Create a program that will concatenate string variables together to form your birthday. day = "12" month = "October" year = "1983" my_birthday = month + " " + day + "," + year print(my_birthday) # Part 2. Concatenate the variables first, second, third, and fourth and set this concatenation to the variable final: this is a test first = "happy" second = "birthday" third = "to" fourth = "you" final = first + " " + second + " " + third + " " + fourth print(final.upper()) # Part 3. age = 15 if age >= 10: print("Not permitted") elif age >= 15: print("Permitted with a parent") elif age >= 18: print("Permitted with anyone over 18") else: print("Permitted to attend alone")
true
96dd3709ac413db258d3ab38be0bd957b51c117a
ktgnair/Python
/day_2.py
602
4.3125
4
#Datatypes #String #Anything inside a "" is considered as string print("Hello"[1]) #Here we can find at position 1 which character is present in word Hello print("1234" + "5678") #Doing this "1234" + "5678" will print just the concatenation of the two strings print("Hello World") #Integer print(1234 + 5678) #For Integer just type the number. Here + means it will add the numbers #Usually we will write a large number like 10000000 in real world as 1,00,00,000 for human readable format, that can be done in python using _ print(1_00_00_000 + 2) #Float print(3.1456) #Boolean True False
true
b3b3a3063b53e18e792d25c07f74d7a4d8441905
ktgnair/Python
/day_10.py
1,362
4.34375
4
# Functions with Outputs. # In a normal function if we do the below then we will get an error as result is not defined # def new_function(): # result = 3*2 # new_function() # print(result) # But using 'return' keyword in the below code we are able to store the output of a function i.e Functions with Outputs def my_function(): result = 3 * 2 return result output = my_function() print(output) # String title() # The title() function in python is used to convert the first character in each word to Uppercase and remaining characters to Lowercase in the string and returns a new string. def format(f_name, l_name): first_name = f_name.title() last_name = l_name.title() return f"{first_name} {last_name}" name = format("kt","GOUtHAM") print(name) # Alternative way print(format("kt","GOUtHAM")) # Multiple return values # 'return' keyword tells the computer that the function is over and need to move further # eg: The below code # def format(f_name, l_name): # if f_name == "" or l_name == "": # return "The input is invalid" # first_name = f_name.title() # last_name = l_name.title() # return f"{first_name} {last_name}" # name = format(input("Enter the first name"), input("Enter the last name")) # print(name) # The above code will stop if the input is empty and will not run beyond the if statement.
true
addc5679ff65e1454f5168d63ba1a72d098fbbe8
ktgnair/Python
/day_8-2.py
1,059
4.28125
4
# Prime Number Checker # You need to write a function that checks whether if the number passed into it is a prime number or not. # e.g. 2 is a prime number because it's only divisible by 1 and 2. # But 4 is not a prime number because you can divide it by 1, 2 or 4 user_input = int(input("Enter the number of your choice ")) def prime_checker(number): count = 0 for n in range(1,number+1): if(number % n == 0): count += 1 print(count) if(count == 2): # The count should be 2 because a number is prime if its divisible either by 1 or by the number itself. So only 2 time that condition occurs. print(count) print("It's a prime number") else: print("It's not a prime number") prime_checker(number=user_input) # Alternative Way # def prime_checker(number): # is_Prime = True # for n in range(2,number): # if(number % n == 0): # is_Prime = False # if is_Prime: # print("It's a prime number") # else: # print("It's not a prime number")
true
70ef560b7cc262f805a8b18c0fa269444276b665
ktgnair/Python
/day_5-5.py
1,685
4.1875
4
# Password Generator Project import random letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] print("Welcome to the Password Generator Program ") total_letters = int(input("How many letters would you like in your Password?\n")) total_numbers = int(input("How many numbers would you like in your Password?\n")) total_symbols = int(input("How many symbols would you like in your Password?\n")) password1 = random.sample(letters,total_letters) #Will return a random sample of the mentioned length - total_letters password2 = random.sample(numbers,total_numbers) password3 = random.sample(symbols,total_symbols) final_password = password1 + password2 + password3 #By doing this we will get the password but it will of fixed order letters + numbers + symbols final_password_new = random.sample(final_password, len(final_password)) #By doing this step we are again finding the random list out of the above final_password(means it will give output in unknow format, which will make the password tough to crack) final_password_string = "" #Empty string to concatenate the string inside the for loop for i in final_password_new: # Take one value from the list and concatenate it in the empty string, and finally we will have the whole list in one single string. final_password_string += i print(f"Your Password is: {final_password_string}")
true
9d2c5436378129d0f27f90a77aea9dd6249bab94
ktgnair/Python
/day_4-4.py
1,247
4.71875
5
# Treasure Map # Write a program which will mark a spot with an X. # You need to add a variable called map.This map contains a nested list. # When map is printed this is what the nested list looks like: # ['⬜️', '⬜️', '⬜️'],['⬜️', '⬜️', '⬜️'],['⬜️', '⬜️', '⬜️'] # Format the three rows into a square, like this: # ['⬜️', '⬜️', '⬜️'] # ['⬜️', '⬜️', '⬜️'] # ['⬜️', '⬜️', '⬜️'] # Write a program that allows you to mark a square on the map using a two-digit system. # The first digit is the vertical column number and the second digit is the horizontal row number. e.g.:23 # ['⬜️', '⬜️', '⬜️'] # ['⬜️', '⬜️', '⬜️'] # ['⬜️', 'X', '⬜️'] # For the below image in the list just go to https://emojipedia.org/empty-page/ and copy that emoji and paste it in the code row1 = ["🗌", "🗌", "🗌"] row2 = ["🗌", "🗌", "🗌"] row3 = ["🗌", "🗌", "🗌"] treasure_map = [row1, row2, row3] print(f"{row1}\n{row2}\n{row3}") position = input("Where do you want to put the treasure? ") column_no = int(position[0]) row_no = int(position[1]) treasure_map[row_no - 1][column_no - 1] = "❌" # print(treasure_map) print(f"{row1}\n{row2}\n{row3}")
true
27e08761ba250ff3ddf19c454df05fdf0acade2d
Alexanderdude/PythonInvestments
/finance_calculators.py
2,651
4.28125
4
import math # Imports the math module print("\n" + "Choose either 'investment' or 'bond' from the menu below to proceed: " + "\n" + "\n" + "investment \t - to calculate the amount of interest you'll earn on interest" + "\n" + "bond \t \t - to calculate the amount you'll have to pay on a home loan") # Displays text for the user sType = input("\n" + "Please enter your answer here: ") # Gets the users input sType = sType.upper() # Makes the input all in capital letters print("\n") if sType == "INVESTMENT" : # If the user entered investment rOriginal = float(input("\n" + "Please enter the amount of money you are depositing: ")) # User input rInRate = float(input("\n" + "Please enter the interest rate: ")) # User input iYears = int(input("\n" + "Please enter the amount of years the money will be deposited: ")) # User input sInType = input("\n" + "Will it be compound or simple interest?: ") # User input sInType = sInType.upper() # Makes the input all in capital letters if sInType == "SIMPLE" : # If user typed simple rTotal = rOriginal * (1 + ((rInRate / 100) * iYears)) print("\n \n" + "Wow, you will start off with R" + str(rOriginal) + " and after " + str(iYears) + " years you will get a total of R" + str(rTotal) + ". That is a R" + str(rTotal - rOriginal) + " increase!" ) elif sInType == "COMPOUND" : # If user typed compound rTotal = rOriginal * ((1 + (rInRate / 100))) ** iYears # Compound interest formulae print("\n \n" + "Wow, you will start off with R" + str(rOriginal) + " and after " + str(iYears) + " years you will get a total of R" + str(rTotal) + ". That is a R" + str(rTotal - rOriginal) + " increase!" ) else : print("\n \n" + "Please select either 'simple' or 'compound' ") # Error message elif sType == "BOND" : rVal = float(input("\n" + "Please enter the value of your house: ")) # User input rInRate = float(input("\n" + "Please enter the interest rate: ")) # User input iMonth = int(input("\n" + "Please enter the number of months you want to take to repay the bond: ")) # User input rTotal = (((rInRate / 100) / 12) * rVal)/(1 - ((1 + ((rInRate / 100) / 12)) ** (-iMonth))) # bond interest formulae print("\n \n" + "You will have to pay R" + str(rTotal) + " each month for a total of " + str(iMonth) + " months.") else : print("\n \n" + "Please select either 'bond' or 'interest' ") # Error message
true
c26242104a494b3a38fb578e1d437cc6853dd2ae
Jlemien/Beginner-Python-Projects
/Guess My Number.py
893
4.4375
4
7"""Overview: The computer randomly generates a number. The user inputs a number, and the computer will tell you if you are too high, or too low. Then you will get to keep guessing until you guess the number. What you will be Using: Random, Integers, Input/Output, Print, While (Loop), If/Elif/Else""" from random import randint number = randint(0,10000000) print("You need to guess what number I'm thinking of.") guess = int(input("What number would you like to guess? ")) while 1 == 1: if guess == number: print("Hooray! You guessed it right!") break elif guess < number: print("The number you guessed is too small.") guess = int(input("Guess again. What number would you like to guess? ")) elif guess > number: print("The number you guessed is too big.") guess = int(input("Guess again. What number would you like to guess? "))
true
a956f3b23892c56326cddaccf4b14b75e660706b
DKojen/HackerRank-Solutions
/Python/Text_wrap.py
552
4.15625
4
#https://www.hackerrank.com/challenges/text-wrap/problem #You are given a string and width . #Your task is to wrap the string into a paragraph of width . import textwrap string = 'ABCDEFGHIJKLIMNOQRSTUVWXYZ' max_width = 4 def wrap(string, max_width): return textwrap.fill(string,max_width) if __name__ == '__main__': result = wrap(string, max_width) print(result) #or without using textwrap: def wrap(string, max_width): return "\n".join([string[i:i+max_width] for i in range(0, len(string), max_width)])
true
275a568b7ccd4adb102c768fd74f8b8e78a04515
nickborovik/stepik_python_advanced
/lesson1_3.py
1,237
4.21875
4
# functions """ def function_name(argument1, argument2): return argument1 + argument2 x = function_name(2, 8) y = function_name(x, 21) print(y) print(type(function_name)) print(id(function_name)) """ """ def list_sum(lst): result = 0 for element in lst: result += element return result def sum(a, b): return a + b y = sum(14, 29) z = list_sum([1, 2, 3]) print(y) print(z) """ # stack in python """ def g(): print("I am function g") def f(): print("I am function f") g() print("I am function f") print("I am outside of any function") f() print("I am outside of any function") """ # task 1 - write program # my code """ def closest_mod_5(x): x = int(x) while x % 5: x += 1 return x """ # my optimized code """ def closest_mod_5(x): return (x + 4) // 5 * 5 y = int(input()) print(closest_mod_5(y)) """ # fibonacci """ def fib(x): if x == 0 or x == 1: return 1 else: return fib(x - 1) + fib(x - 2) y = fib(5) print(y) """ # task 2 - write program """ def C(n, k): if k == 0: return 1 elif n < k: return 0 else: return C(n - 1, k) + C(n - 1, k - 1) n, k = map(int, input().split()) print(C(n, k)) """
true
f85cb21075e1320782d29d9f0b0063d95df2bc23
shreyas710/Third-Year-Programs-Computer-Engineering-SPPU
/Python & R programming/prac5.py
474
4.21875
4
#Title: Create lambda function which will return true when no is even: import mypackage.demo mypackage.demo.my_fun() value=lambda no:no%2==0 no=input("Enter the no which you want to check : ") print(value(int(no))) #title:filter function to obtain or print even no or print even no num_list=[1,2,3,4,5] x=list(filter(lambda num:(num%2==0),num_list)) print(x) #Title:create a map function to multiply no an group by 5 x=list(map(lambda num:(num*5),num_list)) print(x)
true
f7c25f4592050bcb9df83d514d2f8df110c5d449
w-dayrit/learn-python3-the-hard-way
/ex21.py
1,595
4.15625
4
def add(a, b): print(f"ADDING {a} + {b}") return a + b def subtract(a, b): print(f"SUBTRACTING {a} - {b}") return a - b def multiply(a, b): print(f"MULTIPLYING {a} * {b}") return a * b def divide(a, b): print(f"DIVIDING {a} / {b}") return a / b print("Let's do some math with just functions!") age = add(30, 5) height = subtract(78, 4) weight = multiply(90, 2) iq = divide(100, 2) print(f"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}") # A puzzle for the extra credit, type it in anyway. print("Here is a puzzle.") what = add(age, subtract(height, multiply(weight, divide(iq,2)))) print("That becomes: ", what, "Can you do it by hand?") # Study Drills # 1. If you aren’t really sure what return does, try writing a few of your own functions and have them return some values. You can return anything that you can put to the right of an =. # 2. At the end of the script is a puzzle. I’m taking the return value of one function and using it as the argument of another function. I’m doing this in a chain so that I’m kind of creating a formula using the functions. It looks really weird, but if you run the script, you can see the results. What you should do is try to figure out the normal formula that would recreate this same set of operations. # 3. Once you have the formula worked out for the puzzle, get in there and see what happens when you modify the parts of the functions. Try to change it on purpose to make another value. # 4. Do the inverse. Write a simple formula and use the functions in the same way to calculate it
true
e3cd5279375fc9b78d13676b76b98b76768f38a7
umaralam/python
/method_overriding.py
426
4.53125
5
#!/usr/bin/python3 ##Extending or modifying the method defined in the base class i.e. method_overriding. In this example is the call to constructor method## class Animal: def __init__(self): print("Animal Constructor") self.age = 1 class Mammal(Animal): def __init__(self): print("Mammal Constructor") self.weight = 2 super().__init__() def eat(self): print("eats") m = Mammal() print(m.age) print(m.weight)
true
019b266b1aa9f3ce7251acb5959f93f175df1d9d
umaralam/python
/getter_setter_property.py
1,555
4.3125
4
#!/usr/bin/python3 class Product: def __init__(self, price): ##No data validation in place## # self.price = price ##Letting setter to set the price so that the validation is performed on the input## # self.set_price(price) ##Since using decorator for property object our constructor will get modified as## self.price = price ##price getter## # def get_price(self): # return self.__price ##price setter # def set_price(self, value): # if value < 0: # raise ValueError("Price can not be negative.") # self.__price = value ##setting property for getter and setter of product price## # price = property(get_price, set_price) ##With the above property implementation get_price and set_price is still directly accessible from outside. To avoid that we need to define ##property in a better way using decorator object rather than making getter and setter private using "__"## @property def price(self): return self.__price @price.setter def price(self, value): if value < 0: raise ValueError("Price can not be negative.") self.__price = value ##Passed negative value. Python accepts it without validation## product = Product(10) ##Directly accessing the price field to get the product price## #print(product.price) ##getting price by calling getter since price field is no longer accessible directly## #print(product.get_price()) ##Instead of calling getter and setter we can call the property object to get and set the price like a regular field access## #product.price = -1 print(product.price)
true
ad6fd41bd59eed17e8d504fcb6fdfa9d7da7f7c7
ArsathParves/P4E
/python assingments/rduper.py
326
4.15625
4
#fname = input("Enter file name: ") #fh = open(fname) #inp=fh.read() #ufh=inp.upper() #sfh=ufh.rstrip() #print(sfh) ## Read a file and print them the characters in CAPS and strip /n from right of the lines fname = input("Enter file name: ") fh = open(fname) for lx in fh: ly=lx.rstrip() print(ly.upper())
true
8a9f103b3ff3222d1b2b207c30fed67fee1c1450
ArsathParves/P4E
/python assingments/ex7-2.py
872
4.25
4
# 7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form: # X-DSPAM-Confidence: 0.8475(eg) # Count these lines and extract the floating point values from each of the lines and compute the average of those # values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution. # Use the file name mbox-short.txt as the file name fname = input("Enter file name: ") count=0 sum=0.0 average=0.0 fh = open(fname) for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue pos = line.find('0') num=line[pos:pos+6] fnum=float(num) count=count+1 sum=sum+fnum average=sum/count print(fnum) #print('Total lines:',count) #print('Total sum:',sum) print('Average spam confidence:',average)
true
32836815b3d948376d26030dff4fe454c654b591
nortonhelton1/classcode
/classes_and_objects (1)/classes_and_objects/customer-and-address.py
1,103
4.4375
4
class Customer: def __init__(self, name): self.name = name self.addresses = [] # array to represent addresses class Address: def __init__(self, street, city, state, zip_code): self.street = street self.city = city self.state = state self.zip_code = zip_code customer = Customer("John Doe") print(customer.addresses) address = Address("1200 Richmond", "Houston", "TX", "77989") another_address = Address("345 Harvin", "Houston", "TX", "77867") # how to add address to a customer customer.addresses.append(address) customer.addresses.append(another_address) # display customer and addresses print(customer.name) for address in customer.addresses: print(address.street) print(address.state) #print(customer.addresses) #customer.street = "1200 Richmond Ave" #customer.city = "Houston" #customer.state = "TX" #customer.zip_code = "77890" #Post #Comment #A single Post can have many comments #Comment can belong to a Post Walmart - Paper - Shirts - Shoes HEB - Meat - Chicken Fiesta - Fish - Vegetables
true
05acb84502e7e62ea9da1088ee08c1c945652c71
dylantzx/HackerRank
/30 Days Of Code/DictionariesAndMaps.py
635
4.125
4
############################# Question ########################### # https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem ################################################################## # Enter your code here. Read input from STDIN. Print output to STDOUT count = int(input()) list_of_queries = [input().split() for i in range(count)] phonebook = {name:number for name,number in list_of_queries} while True: try: check_name = input() if check_name in phonebook: print(f"{check_name}={phonebook[check_name]}") else: print("Not found") except: break
true
c1f1c50534463aea935f74526059a3760f2bbfc7
abbasjam/abbas_repo
/python/dev-ops/python/pythan-class/string14.py
212
4.15625
4
print ("String Manipulations") print ("-------------------") x=input("Enter the String:") print ("Given String is:",x) if x.endswith('.txt'): print ("Yes!!!!!!!text file") else: print ("Not textfile")
true
5864a1d2a032b9379e2ce6118c2e77598116c81a
abbasjam/abbas_repo
/python/dev-ops/python/pythan-class/string7.py
234
4.15625
4
print ("String Manipulations") print ("-------------------") x=input("Enter the String:") print ("Given String is:",x) if x.isspace(): print ("String Contains only spaces ") else: print ("one or more chars are not spaces")
true
6ffce6b6ba40bad4d70bd8dc847cfcabc9dfdcbd
chapman-cs510-2017f/cw-03-sharonjetkynan
/sequences.py
610
4.4375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def fibonacci(n): """ object: fibonacci(n) returns the first n Fibonacci numbers in a list input: n- the number used to calculate the fibonacci list return: retList- the fibonacci list """ if type(n) != int: print(n) print(":input not an integer") return False if n <= 0: print(str(n)+"not a postive integer") return False f1=1 f2=1 retList=[] for i in range (0,n): retList.append(f1) fn=f1+f2 f1=f2 f2=fn return retList
true
f671a071f6f111ea4f63e2b6aea4dd8e1844d056
KyleHu14/python-alarm-clock
/main.py
1,704
4.28125
4
import time import datetime def print_title() -> None: # Prints the title / welcome string when you open the app print('#' * 26) print('#' + '{:^24s}'.format("Alarm Clock App") + '#') print('#' * 26) print() def take_input() -> str: # Takes the input from the user and checks if the input is correct print('Enter Time in the Following Format : [Hours:Minutes:Seconds]') print('Example (5 hours, 5 minutes, 60 seconds) : 5:5:60\n') user_input_time = input('Enter Time: ') while not _check_input(user_input_time): print('[ERROR] : Incorrect input detected, please re-enter the time.') user_input_time = input('Enter Time : ') print() return user_input_time def _check_input(input_time : str) -> bool: # When given a string, checks if the input fulfills the int:int:int format if input_time.count(':') >= 4: return False if input_time.isalpha(): return False if ':' in input_time: for x in input_time.split(':'): if x.isalpha(): return False return True def convert_time(input_time : str) -> int: # Converts the input time in the format hour:min:sec and converts it to seconds hours = int(input_time.split(':')[0]) minute = int(input_time.split(':')[1]) sec = int(input_time.split(':')[2]) return (hours * 60 * 60) + (minute * 60) + sec def countdown(secs : int) -> None: while secs > 0: print(datetime.timedelta(seconds=secs), end='\r') time.sleep(1) secs -= 1 def main() -> None: print_title() final_time = convert_time(take_input()) countdown(final_time) main()
true
97e49ed0257e6f87dd9dd55ccaa7034b2f50ca9f
foleymd/boring-stuff
/more_about_strings/advanced_str_syntax.py
1,051
4.1875
4
#escape characters #quotation print('I can\'t go to the store.') print("That is Alice's cat.") print('That isn\'t Alice\'s "cat."') print("Hello, \"cat\".") print('''Hello, you aren't a "cat."''') #tab print('Hello, \t cat.') #newline print('Hello, \n cat.') print('Hello there!\nHow are you?\nI\'m fine!') #backslash print('Hello, \\ cat.') #raw string (doesn't do escape characters) print(r'Hello there!\nHow are you?\nI\'m fine!') #triple quotes for multiline strings print('''Dear Alice, Eve's cat has been arrested for catnapping, cat burglary, and extortion. Sincerely, Bob''') print("""Dear Alice, Eve's cat has been arrested for catnapping, cat burglary, and extortion. Sincerely, Bob""") spam = """Dear Alice, Eve's cat has been arrested for catnapping, cat burglary, and extortion. Sincerely, Bob""" print(spam) #it keeps the new lines when it stores the variables #strings uses indexes and slices and in/not in hello = 'hello world' print(hello[2]) print(hello[1:3]) print('world' in hello) #True print('World' in hello) #False
true
7939df2c4af30d7527ab8919d69ba5055f43f7ce
vishwaka07/phython-test
/tuples.py
1,048
4.46875
4
# tuples is also a data structure, can store any type of data # most important tuple is immutable # u cannot update data inside the tuple # no append, no remove, no pop, no insert example = ( '1','2','3') #when to use : days , month #tuples are faster than lists #methods that can be used in tuples : count,index, len function,slicing #tuple with one element num = (1,) print(type(num)) # tuple without parenthesis "()" guitar = 'yamaha','base' print(type(guitar)) #tuple unpacking guitarist = ('hello1','hello2','hello3') name1,name2,name3 = (guitarist) print(name1) #list inside the tuple #function returning two values means its gives output in tuple #so we have to store data in two variable def func(int1,int2): add = int1 + int2 multiply = int1*int2 return add,multiply add, multiply = func(2,3) print(add) print(multiply) # tuple can be use with range as num = tuple(range(1,11)) print(num) #convert tuple into list nums = list((1,2,3,4,5,6)) print(nums) #convert tuple into str nums1=str((1,2,3,4,5,6)) print(nums1)
true
0b15fd9864c222c904eef1e7515b5dd125e05022
Randheerrrk/Algo-and-DS
/Leetcode/515.py
1,209
4.1875
4
''' Find Largest Value in Each Tree Row ------------------------------------ Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed). Input: root = [1,3,2,5,3,null,9] Output: [1,3,9] Input: root = [1,2,3] Output: [1,3] Input: root = [1] Output: [1] Input: root = [1,null,2] Output: [1,2] Input: root = [] Output: [] ''' # Python Solution # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def largestValues(self, root: TreeNode) -> List[int]: if(root==None) : return [] result = [] def bfs(root: TreeNode) : q = [root] nonlocal result while q : s = len(q) levelMax = -math.inf for i in range(s) : temp = q.pop(0) levelMax = max(temp.val, levelMax) if(temp.left) : q.append(temp.left) if(temp.right) : q.append(temp.right) result.append(levelMax) bfs(root) return result
true
e6eada3e5ad01097e132123a75d6c2b3a134d977
shulme801/Python101
/squares.py
451
4.21875
4
squares = [value**2 for value in range(1,11)] print(squares) # for value in range(1, 11): # # square = value ** 2 # # squares.append(square) # squares.append(value**2) # print(f"Here's the squares of the first 10 integers {squares}") odd_numbers = list(range(1,20,2)) print(f"Here's the odd numbers from 1 through 20 {odd_numbers}") cubes = [value**3 for value in range(1,21)] print(f"\nHere's the cubes of the 1st 20 integers: {cubes}\n")
true
0b9e29c79c892215611b5cdb3e64ee2210d6f2a3
shulme801/Python101
/UdemyPythonCertCourse/Dunder_Examples.py
1,017
4.3125
4
# https://www.geeksforgeeks.org/customize-your-python-class-with-magic-or-dunder-methods/?ref=rp # declare our own string class class String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) def __add__(self, other): return self.string + other # Driver Code print ("This file's __name__ is %s" %__name__) if __name__ == '__main__': # object creation string1 = String('Hello') # print object location print(string1) #concatenate String object and a string print(string1 + " world!") class Employee: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return self.name + " age is " + str(self.age) def __len__(self): return len(self.name) # John = Employee("John Doe", 47) # print(John) # print(len(John))
true
9bd76fe2cca59bd95d2a5237d8bf34a13ed13c60
lawtonsclass/s21-code-from-class
/csci1/lec14/initials.py
742
4.21875
4
import turtle # imports the turtle library import math turtle.shape("turtle") # make the turtle look like a turtle turtle.up() turtle.backward(150) turtle.right(90) turtle.down() # put the turtle down so that we can draw again turtle.forward(200) # draw first line of L turtle.left(90) turtle.forward(125) # space between letters turtle.up() turtle.forward(40) turtle.down() turtle.left(90) turtle.forward(200) # calcuate the weird angle in the N angle = math.atan(125/200) angle = math.degrees(angle) turtle.right(180-angle) # calculate the weird length for the middle line of the N length = 125 / math.sin(math.radians(angle)) turtle.forward(length) turtle.left(180-angle) turtle.forward(200)
true
f14f7efaf33491f9758099e639e1adf4fbc55c50
lawtonsclass/s21-code-from-class
/csci1/lec19/random_squares.py
1,136
4.21875
4
import turtle import random turtle.shape('turtle') turtle.speed('fastest') colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] i = 1 while i <= 50: # draw a square with a random side length and a random color random_index = random.randint(0, len(colors) - 1) turtle.fillcolor(colors[random_index]) turtle.up() # pick the turtle up # pick a random starting x & y coordinate starting_x = random.randint(-300, 300) starting_y = random.randint(-300, 300) # move the turtle there turtle.goto(starting_x, starting_y) # put the turtle back down turtle.down() # pick a random side length for our square square_side_length = random.randint(50, 200) # actually draw the square turtle.begin_fill() # fill in (with the fillcolor) the following shape turtle.forward(square_side_length) turtle.left(90) turtle.forward(square_side_length) turtle.left(90) turtle.forward(square_side_length) turtle.left(90) turtle.forward(square_side_length) turtle.end_fill() # I'm done drawing, please fill in my shape Mr. Turtle i = i + 1 # advance i
true
0d613768179d34123018a637a31ce1327587c5fc
lawtonsclass/s21-code-from-class
/csci1/lec30/recursion.py
961
4.1875
4
def fact(n): # base case if n == 1: return 1 else: # recursive case! x = fact(n - 1) # <-- this is the "recursive call" # the answer is n * (n-1)! return n * x print(fact(5)) def pow(n, m): if m == 0: # base case return 1 else: # recursive case return n * pow(n, m-1) print(pow(2.5, 5)) def sum_divide_and_conquer(L): if len(L) == 0: # base case 1 return 0 elif len(L) == 1: # base case 2 return L[0] else: # recursive case # first, divide the list L into two halves midpoint = len(L) // 2 first_half = L[:midpoint] second_half = L[midpoint:] # let's recursively "conquer" the two halves! first_half_sum = sum_divide_and_conquer(first_half) second_half_sum = sum_divide_and_conquer(second_half) # final answer is the sum of both halves return first_half_sum + second_half_sum print(sum_divide_and_conquer([8, 6, 7, 5, 3, 0, 9, 2]))
true
919bc6acd1abd0d772c86c501de1aa4e9395d103
Nihadkp/MCA
/Semester-01/Python-Programming-Lab/Course-Outcome-1-(CO1)/02-Leap-Year/Leap_year.py
300
4.375
4
# purpose - to find leap years of future year from current year startYear = 2021 print("Enter any future year") endYear = int(input()) print("List of leap years:") for year in range(startYear, endYear): if (0 == year % 4) and (0 != year % 100) or (0 == year % 400): print(year)
true
1407338619c9f08438e00a72f20ee2a1796ffaa2
Nihadkp/MCA
/Semester-01/Python-Programming-Lab/Course-Outcome-1-(CO1)/20-Remove-even-numbers-form-a-list-of-integers/Removing_Even_numbers_in_LIST.py
419
4.1875
4
# purpose- removing even numbers in list numberList = [] even_numberList = [] n = int(input("Enter the number of elements ")) print("\n") for i in range(0, n): print("Enter the element ", i + 1, ":") item = int(input()) numberList.append(item) print(" List is ", numberList) even_numberList = [x for x in numberList if x % 2 != 0] print("\n") print("List after removing even numbers\n ", even_numberList)
true
31dabba934c1b70d75263ef9bf71549651baa464
Nihadkp/MCA
/Semester-01/Python-Programming-Lab/Course-Outcome-1-(CO1)/03-List-Comprehensions/List_Operations.py
1,445
4.125
4
# purpose - program to perform some list operations list1 = [] list2 = [] print("Select operation.") print("1.Check Length of two list's are Equal") print("2.Check sum of two list's are Equal") print("3.whether any value occur in both ") print("4.Display Lists") while True: choice = input("Enter any choice ") if choice in ('1', '2', '3', '4'): list1Len = int(input("Enter the number of elements in list 1 : ")) for i in range(0, list1Len): print("Enter the element ", i + 1, ":") item1 = int(input()) list1.append(item1) list2Len = int(input("Enter the number of elements in list 2 : ")) for j in range(0, list2Len): print("Enter the element ", j + 1, ":") item2 = int(input()) list2.append(item2) if choice == '1': if len(list1) == len(list2): print(" Length are Equal") else: print(" Length are Not Equal") if choice == '2': if sum(list1) == sum(list2): print(" Sums are Equal") else: print(" Sums are Not Equal") if choice == '3': list3 = [x for x in list1 if x in list2] print("Common elements in both list's are \n", list3) if choice == '4': print("List 1 is :\n", list1, " List 2 is :\n", list2)
true
7c9d95660844b66ff9becf9f656ed9f16f78ed79
mengeziml/sorepy
/sorepy/sorting.py
2,472
4.625
5
def bubble_sort(items): """Return array of items, sorted in ascending order. Args: items (array): list or array-like object containing numerical values. Returns: array: sorted in ascending order. Examples: >>> bubble_sort([6,2,5,9,1,3]) [1, 2, 3, 5, 6, 9] """ n = items.copy() for i in range(len(n)): for j in range(len(n)-1-i): if n[j] > n[j+1]: n[j], n[j+1] = n[j+1], n[j] return n def merge(A, B): """Returns a single merged array of two arrays. Args: A (array): list or array-like object containing numerical values. B (array): list or array-like object containing numerical values. Returns: array: unsorted. Examples: >>> merge([6,2,5],[9,1,3]) [6, 2, 5, 9, 1, 3] """ temp_list = [] while len(A) > 0 and len(B) > 0: if A[0] < B[0]: temp_list.append(A[0]) A.pop(0) else: temp_list.append(B[0]) B.pop(0) if len(A) == 0: temp_list = temp_list + B if len(B) == 0: temp_list = temp_list + A return temp_list def merge_sort(items): """Splits array into two sorted equal halves and uses merge(A,B) to sort items. Args: items (array): list or array-like object containing numerical values. Returns: array: sorted in ascending order. Examples: >>> merge_sort([6,2,5,9,1,3]) [1, 2, 3, 5, 6, 9] """ len_i = len(items) if len_i == 1: return items mid_point = int(len_i / 2) i1 = merge_sort(items[:mid_point]) i2 = merge_sort(items[mid_point:]) return merge(i1, i2) def quick_sort(items): """Return array of items, sorted in ascending order. Args: items (array): list or array-like object containing numerical values. Returns: array: sorted in ascending order. Examples: >>> quick_sort([6,2,5,9,1,3]) [1, 2, 3, 5, 6, 9] """ p=items[-1] l=[] r=[] for i in range(len(items)): if items[i]< p: l.append(items[i]) if len(l)>1 and len(l)>=len(items)//2: l=quick_sort(l) elif items[i]>p: r.append(items[i]) if len(r)>1 and len(r)>=len(items)//2: r=quick_sort(r) items=l+[p]+r return items
true
4663b089240b5f113c3c49e7918204417dff77f7
BenWarwick-Champion/CodeChallenges
/splitStrings.py
581
4.125
4
# Complete the solution so that it splits the string into pairs of two characters. # If the string contains an odd number of characters then it should replace # the missing second character of the final pair with an underscore ('_'). # Example: # solution('abc') # should return ['ab', 'c_'] # solution('abcdef') # should return ['ab', 'cd', 'ef'] # My Solution def solution(s): if (len(s) % 2) != 0: s += '_' return [s[i:i+2] for i in range (0, len(s), 2)] # Best Solution import re def solution(s): return re.findall(".{2}", s + "_")
true
992ad23ed86e3c42cebb5d4130acaba5dca70eda
ktsmpng/CleverProgrammerProjects
/yo.py
447
4.28125
4
# print from 1 to 100 # if number is divisble by 3 -- fizz # if number is divisble by 5 -- buzz # if divisible by both -- fizzbuzz # 2 # fizz # 3 def fizzbuzz(start_num, stop_num): print('_________________') for number in range(start_num, stop_num + 1): if number % 3 == 0 and number % 5 == 0: print("fizzbuzz") elif number % 3 == 0: print("fizz") elif number % 5 == 0: print("buzz") else: print(number) fizzbuzz(1,300)
true
661171d9cc55d2b4c5ef7bbfe5c02f9cc5760c43
Topperz/pygame
/5.first.pygame.py
2,986
4.65625
5
""" Show how to use a sprite backed by a graphic. Sample Python/Pygame Programs Simpson College Computer Science http://programarcadegames.com/ http://simpson.edu/computer-science/ Explanation video: http://youtu.be/vRB_983kUMc """ import pygame import time import math # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) PI = 3.141592653 pygame.init() # Set the width and height of the screen [width, height] size = (700, 500) screen = pygame.display.set_mode(size) pygame.display.set_caption("My Game") # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() # -------- Main Program Loop ----------- while not done: # --- Main event loop for event in pygame.event.get(): if event.type == pygame.QUIT: done = True # --- Game logic should go here # --- Drawing code should go here # First, clear the screen to white. Don't put other drawing commands # above this, or they will be erased with this command. screen.fill(WHITE) pygame.draw.rect(screen, RED, [100, 100, 100, 100]) pygame.draw.line(screen, GREEN, [0, 0], [100, 100], 5) pygame.draw.line(screen, GREEN, [200, 100], [300, 0], 5) pygame.draw.line(screen, GREEN, [100, 200], [0, 300], 5) pygame.draw.line(screen, GREEN, [200, 200], [300, 300], 5) # Draw on the screen several lines from (0,10) to (100,110) # 5 pixels wide using a for loop for y_offset in range(0, 100, 10): pygame.draw.line(screen,RED,[0,10+y_offset],[100,110+y_offset],5) #pygame.display.flip() #time.sleep(1) #for i in range(200): # # radians_x = i / 20 # radians_y = i / 6 # # x = int( 75 * math.sin(radians_x)) + 200 # y = int( 75 * math.cos(radians_y)) + 200 # # pygame.draw.line(screen, BLACK, [x,y], [x+5,y], 5) #pygame.display.flip() #time.sleep(0.1) # Draw an arc as part of an ellipse. Use radians to determine what # angle to draw. #pygame.draw.arc(screen, GREEN, [100,100,250,200], PI, PI/2, 2) #pygame.draw.arc(screen, BLACK, [100,100,250,200], 0, PI/2, 2) #pygame.draw.arc(screen, RED, [100,100,250,200],3*PI/2, 2*PI, 2) #pygame.draw.arc(screen, BLUE, [100,100,250,200], PI, 3*PI/2, 2) pygame.draw.arc(screen, BLACK, [20, 220, 250, 200], 0, PI/2, 2) pygame.draw.arc(screen, GREEN, [20, 220, 250, 200], PI/2 , PI, 2) pygame.draw.arc(screen, BLUE, [20, 220, 250, 200], PI, PI * 1.5, 2) pygame.draw.arc(screen, RED, [20, 220, 250, 200], PI * 1.5 , PI * 2, 2) # --- Go ahead and update the screen with what we've drawn. pygame.display.flip() # --- Limit to 60 frames per second clock.tick(60) # Close the window and quit. # If you forget this line, the program will 'hang' # on exit if running from IDLE. pygame.quit()
true
39984a91ad8bc8209dca055467c40ad7560a898e
applecool/Python-exercises
/key_value.py
594
4.125
4
# Write a function that reads the words in words.txt and stores # them as keys in a dictionary. It doesn't matter what the values # are. # # I used the python's in-built function random to generate random values # One can use uuid to generate random strings which can also be used to # pair the keys i.e., in this case the words in the .txt file import random output = dict() #creates an empty dictionary words = open('words.txt') line = words.readline() def key_value(): for line in words: word = line.strip() output[word] = random.random() return output print key_value()
true
d3210816dac9893a01061a6687f17b13304c3289
subreena10/dictinoary
/existnotexistdict.py
249
4.46875
4
dict={"name":"Rajiu","marks":56} # program to print 'exist' if the entered key already exist and print 'not exist' if entered key is not already exists. user=input("Enter ur name: ") if user in dict: print("exist") else: print("not exists")
true
090de8d31c4ea6ce5b30220d8e3f7679d8328db3
adreher1/Assignment-1
/Assignment 1.py
1,418
4.125
4
''' Rose Williams rosew@binghamton.edu Section #B1 Assignment #1 Ava Dreher ''' ''' ANALYSIS RESTATEMENT: Ask a user how many people are in a room and output the total number of introductions if each person introduces themselves to every other person once OUTPUT to monitor: introductions (int) - when each person introduces themselves to every other person once INPUT from keyboard: person_count (int) GIVEN: HALF (int) - 2 FORMULA: (person_count * (person_count - 1)) / HALF ''' # CONSTANTS HALF = 2 # This program outputs the total number of introductions possible if each # person in a room introduces themselves to every other person in the room # once, given the number of people in the room def main(): # Explain purpose of program to user print("How many introductions will occur if everyone " + "\n" + "introduces themseves to every other person?") # Ask user for number of people in room person_count_str= input('number of people in room:') # Convert str data to int person_count = int(person_count_str) # Use the formula to compute the result introductions = (person_count * (person_count - 1)) / HALF introductions = str(introductions) # Display labeled and formatted introduction count print('There are '+ introductions + ' introductions') if __name__ == '__main__': main()
true
29a9472bf05258a090423ef24cc0c64311a6272b
acc-cosc-1336/cosc-1336-spring-2018-Miguelh1997
/src/midterm/main_exam.py
561
4.40625
4
#write import statement for reverse string function from exam import reverse_string ''' 10 points Write a main function to .... Loop as long as user types y. Prompt user for a string (assume user will always give you good data). Pass the string to the reverse string function and display the reversed string ''' def main(): n = 'Y' while n == 'Y': string1 = input('Please input a string: ') new = reverse_string(string1) print(new) n = input("Press 'y' to enter another string... ") n = n.upper()
true
f16f06d76cb51cff2e10bc64d9310890e041231b
abalidoth/dsp
/python/q8_parsing.py
673
4.3125
4
# The football.csv file contains the results from the English Premier League. # The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program to read the file, # then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals. import pandas as pd footy = pd.read_csv(football.csv) footy["Diff"]=[abs(x-y) for x,y in zip(footy.Goals, footy["Goals Allowed"])] whichsmallest = footy.Diff[footy.Diff==min(footy.Diff)].index[0] print(footy.Team[whichsmallest])
true
645e285a751310786073fefba08294bf7850b051
40309/variables
/assignment_improvement_exercise_py.py
402
4.28125
4
#john bain #variable improvement exercise #05-09-12 import math radius = float(input("Please enter the radius of the circle: ")) circumference = int(2* math.pi * radius) circumference = round(circumference,2) area = math.pi * radius**2 area = round(area,2) print("The circumference of this circle is {0}.".format(circumference)) print("The area of this circle is {0}.".format(area))
true
73760296f75889f8eaba190a9bc38c2d03555c95
40309/variables
/Development Exercise 3.py
342
4.1875
4
#Tony K. #16/09/2014 #Development Exercise 3 height = float(input("Please enter your height in inches: ")) weight = float(input("Please enter your height in stones: ")) centimeter = height* 2.54 kilogramm = weight * (1/0.157473) print("You are {0} cenimeters tall and you weigh {1} kilogramm".format(centimeter,kilogramm))
true
5e20c1fde5e1ebd93f22d718ac78f699f31a387c
lloydieG1/Booking-Manager-TKinter
/data.py
1,013
4.1875
4
import sqlite3 from sqlite3 import Error def CreateConnection(db_file): ''' create a database connection to a SQLite database and check for errors :param db_file: database file :return: Connection object or None ''' #Conn starts as 'None' so that if connection fails, 'None' is returned conn = None try: #attempts to connect to given database conn = sqlite3.connect(db_file) #prints version if connection is successful print("Connection Successful\nSQL Version =", sqlite3.version) except Error as e: #prints the error if one occurs print("Error1 = " + str(e)) return conn def get(): db = "test.db" conn = CreateConnection(db) if conn == None: print('Connection failed') #SQL command to insert data sql = '''SELECT * FROM bookings_table;''' #Creates cursor c = conn.cursor() #Executes SQL command using user input results = c.execute(sql).fetchall() return results
true
f5c41d06bb1137f0d1aac5b0f1dbedc9604cc91b
NickNganga/pyhtontake2
/task3.py
547
4.125
4
def list_ends(a_list): return (a_list[0], a_list[len(a_list)-1]) # number of elements num = int(input("Enter number of elements : ")) # Below line read inputs from user using map() function put = list(map(int,input("\nEnter the numbers : ").strip().split()))[:num] # Below Line calls the function created above. put1 = list_ends(put) #Outputs the values under indices '0' & '-1' (the last one in the list). print("\nList is - ", put) #Outputs the values under indices '0' & '-1' (the last one in the list). print("\nNew List is - ", put1)
true
80282dbf6abf81960e5714850eb1455cd147009a
kgomathisankari/PythonWorkspace
/function_and_class_programs/palindrome_calling_function_prgram.py
561
4.25
4
user_input = input("Enter your name : ") def reverseString(user_input) : reverse_string = "" for i in range (len(user_input) - 1, -1 , -1) : reverse_string = reverse_string + user_input[i] return reverse_string def isPalindrome(user_input) : palindrome = "What you have entered is a Palindrome" not_palindrome = "What you have entered is not Palindrome" reverseString(user_input) if reverseString(user_input) == user_input : return palindrome else: return not_palindrome print(isPalindrome(user_input))
true
b61cc6e6fbac22a3444fd6827d4cbf84cc554924
kgomathisankari/PythonWorkspace
/for_loop_programs/modified_odd_and_even_program.py
503
4.3125
4
even_count = 0 odd_count = 0 getting_input = int(input("How many numbers do you want to enter? ")) for i in range (getting_input) : getting_input_2 = int(input("Enter the number : ")) even = getting_input_2 % 2 if even == 0 : even_count = even_count + getting_input_2 elif even != 0 : odd_count = odd_count + getting_input_2 print ("The Sum of Even numbers that you have entered is : ", even_count) print ("The Sum of Odd numbers that you have entered is : ", odd_count)
true
f4ad192198588faed881318cbee95bed57fbbdd2
kgomathisankari/PythonWorkspace
/for_loop_programs/largest_smallest_program.py
421
4.21875
4
no_count = int(input("How many numbers do you want to enter? ")) list = [] for i in range (no_count) : num = int(input("Enter the number : ")) list.append(num) largest = list[0] smallest = list[1] for j in list : if largest < j : largest = j elif smallest > j : smallest = j print("The largest number you entered is : " , largest) print("The smallest number you entered is : " , smallest)
true
fe9366843f9bdeac7a0687b6bb2abb26357007aa
vTNT/python-box
/test/func_doc.py
290
4.4375
4
#!/usr/bin/env python # -*- coding:utf-8 -*- def printmax(x, y): '''print the max of two numbers. the two values must be integers.''' x = int(x) y = int(y) if x > y: print x, 'is max' else: print y, 'is max' printmax(3, 5) #print printmax.__doc__
true
d331f247e1ad6183997de06a8323dd27f56794ad
vTNT/python-box
/app/Tklinter2.py
932
4.21875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- from Tkinter import * class LabelDemo( Frame ): """Demonstrate Labels""" def __init__( self ): """Create three Labels and pack them""" Frame.__init__( self ) # initializes Frame instance # frame fills all available space self.pack( expand = YES, fill = BOTH ) self.master.title( "Labels" ) self.Label1 = Label( self, text = "Label with text" ) # resize frame to accommodate Label self.Label1.pack() self.Label2 = Label( self, text = "Labels with text and a bitmap" ) # insert Label against left side of frame self.Label2.pack( side = LEFT ) # using default bitmap image as label self.Label3 = Label( self, bitmap = "warning" ) self.Label3.pack( side = LEFT ) def main(): LabelDemo().mainloop() # starts event loop if __name__ == "__main__": main()
true
658a3ba9560615ba04aebaa444e09e91f763c668
dscheiber/CodeAcademyChallenge
/binaryconversion.py
2,185
4.46875
4
# 3. Convert a decimal number into binary # Write a function in Python that accepts a decimal number and returns the equivalent binary number. # To make this simple, the decimal number will always be less than 1,024, # so the binary number returned will always be less than ten digits long. ##author note: ok, so i hardly understand binary besides the crash course i received in calculating binary vs IP address for ##properly establishing VPC subnets. with that said, i checked my work against a calculator and it's all good. ##i didn't need to make it simple and did not limit it to <1024. ## simple ask for number w input validation. def getNumber(): number = 0 numberValidation = None while numberValidation == None: number = input('Choose a number to be converted to binary. \n') try: number = int(number) if number >= 0: #and number <= 1024: ##removed bc i didn't need numberValidation = True else: print('Not a valid input.') except: print('Not a valid input.') return number ## determines the number of digits necessary for the final value. builds a list of n^2 multiples such that it can be used ## for determining the actual digits later on def digitDetermination(number): digit = 2 binaryLength = [0] while number >= digit: #print(number, digit) binaryLength.append(digit) digit += digit binaryLength.reverse() return binaryLength ## starting from the "left most digit", calculates the digit by determining the remainder of current number and n^2 multiple def calculateBinaryValues(number, binaryLength): binaryList = [] for value in binaryLength: remainder = number - value if remainder >= 0 and number != 0: binaryList.append('1') number = remainder else: binaryList.append('0') return binaryList def mainLoop(): value = getNumber() testDigits = digitDetermination(value) binaryValues = calculateBinaryValues(value, testDigits) binaryString = ''.join(binaryValues) return binaryString print(mainLoop())
true
206bfc1fc295e7803c04d70a69ee8445ad308201
yellowb/ml-sample
/py3_cookbook/_1_data_structure/deduplicate_and_maintain_order.py
979
4.125
4
""" Sample for removing duplicated elements in list and maintain original order """ import types names = ['tom', 'ken', 'tim', 'mary', 'ken', 'ben', 'berry', 'mary'] # Use `set()` for easy deduplicate, but changes the order print(set(names)) # Another approach: use loop with a customized hash function def dedupe(items, hash_func=None): deduped_items = [] seen_keys = set() for e in items: if hash_func is not None and isinstance(hash_func, types.FunctionType): key = hash_func(e) else: key = e if key not in seen_keys: seen_keys.add(key) deduped_items.append(e) return deduped_items print(dedupe(names)) # No customized hash function, use the elements' default hash function directly print(dedupe(names, lambda e: e[0])) # Think them as duplicated if the 1st char is the same print(dedupe(names, lambda e: e[-2:-1])) # Think them as duplicated if the last 2 chars are the same
true
892801363f4edc79ed1ed9ce38f9bdbd483ab02d
wjaneal/ICS3U
/WN/Python/VectorField.py
1,295
4.34375
4
#Vector Field Program #Copyleft 2013, William Neal #Uses Python Visual Module to Display a Vector Field #as determined by an equation in spherical coordinates #Import the required modules for math and graphics: import math from visual import * #Set a scale factor to determine the time interval for each calculation: Scale = 0.001 #Calculates and returns the magnitude of a gravitational field #Given G, the Gravitational constant, M and r def GravitationalField(G, M, r): return G*M/(r*r) def r(x,y,z): return sqrt(x**2+y**2+z**2) '''#Set up conversion from spherical coordinates to cartesian coordinates def Spherical_to_Cartesian(r, theta, phi): x = r*sin(phi)*cos(theta) y = r*sin(phi)*sin(theta) z = r*cos(phi) return (x,y,z) ''' #Draw points to show where the fly has been: P = points(pos = [(0.000001,0,0)], size = 1, color = color.red) #Draw a vector to show where the fly is: Field = [arrow(pos = (0.000001,0,0), axis = (0,0,1), shaftwidth = 0.1, length = 1)] #Draw a sphere to represent the surface on which the fly flies: ball = sphere(pos=(0,0,0), radius=1, opacity = 0.4) for x in range(-10,10): for y in range(-10,10): for z in range(-10,10): Field.append(arrow(pos=(x,y,z), axis = (0,0,1),shaftwidth = 0.1,length = GravitationalField(1,100,0.0011+r(x,y,z))))
true
ae30d9d7532905ac7e32a7b728a9a42c24c55db8
shripadtheneo/codility
/value_part_array/same_val_part_arr.py
910
4.1875
4
""" Assume the input is an array of numbers 0 and 1. Here, a "Same Value Part Array" means a part of an array in which successive numbers are the same. For example, "11", "00" and "111" are all "Same Value Part Arrays" but "01" and "10" are not. Given Above, implement a program to return the longest "Same Value Part Array" for any array input. e.g. "011011100" """ def long_same_part_arr(sequence): longest = (0, 0) curr = (0, 0) first, last = 0, 0 for i in range(1, len(sequence)): if sequence[i] == sequence[i - 1]: last = i curr = first, last else: first, last = i, i if curr[1] - curr[0] > longest[1] - longest[0]: longest = curr return sequence[longest[0]:longest[1] + 1] if __name__ == '__main__': print "Please input the array: " sequence = raw_input() print (long_same_part_arr(sequence))
true
12f98922c3aaeaed6e05d773976ac18892897b27
aishwarya-narayanan/Python
/Python/Turtle Graphics/turtleGraphicsAssignment.py
812
4.34375
4
import turtle # This program draws import turtle # Named constants START_X = -200 START_Y = 0 radius = 35 angle = 170 ANIMATION_SPEED = 0 #Move the turtle to its initial position. turtle.hideturtle() turtle.penup() turtle.goto(START_X, START_Y) turtle.pendown() # Set the animation speed. turtle.speed(ANIMATION_SPEED) # Draw 36 lines, with the turtle tilted by 170 degrees after each line is drawn. for x in range(18): turtle.pensize(2) turtle.color ("red") turtle.forward(500) turtle.color ("blue") turtle.circle(radius) turtle.color ("red") turtle.left(angle) for x in range(18): turtle.pensize(2) turtle.color ("green") turtle.forward(500) turtle.color ("magenta") turtle.circle(radius) turtle.color ("green") turtle.left(angle)
true
a035fc1998182c99f9b9d3f6a007f023584f532e
LeviMollison/Python
/PracticingElementTree.py
2,682
4.4375
4
# Levi Mollison # Learning how to properly use the XML Tree module try: from lxml import etree print("running with lxml.etree") except ImportError: try: # Python 2.5, this is the python we currently are running import xml.etree.cElementTree as etree print("running with cElementTree on Python 2.5+") except ImportError: try: # Python 2.5 import xml.etree.ElementTree as etree print("running with ElementTree on Python 2.5+") except ImportError: try: # normal cElementTree install import cElementTree as etree print("running with cElementTree") except ImportError: try: # normal ElementTree install import elementtree.ElementTree as etree print("running with ElementTree") except ImportError: print("Failed to import ElementTree from any known place") # Let's begin by making our own element root = etree.Element("root") # Can append children to elements as you would ITEMS to a LIST root.append( etree.Element("OneChild") ) # but an easier way to create children is to use a subele factory them. This is done with the subelement list which returns the desired child # it looks like this: child = etree.SubElement(parent, child tag name) child2 = etree.SubElement(root, "Child2") child3 = etree.SubElement(root, "Child3") # Now that the elements are created, you can pretty print the xml doc you made # print (etree.tostring( root) ) # elements are organized as closely to lists as possible. so many list functions work on xml trees child = root[0] # print child.tag # print len(root) # in order to go through the tree like a list, you need to turn it into a list children = list(root) #for element in children: # print element.tag # You can also insert elements at certain places that you wish using root.insert root.insert(0, etree.Element("Child0")) start = root[:1] end = root[-1:] """ print start[0].tag print end[0]. """ # There is more than just tags, there is also attribute manipulation # attributes are stored like dictionaries in elements, and are used the same way root = etree.Element("root", interesting="Totally") print etree.tostring(root) # can also set them in an already created element root.set("hello","huhu") # get searches the element for the desired attribute value # print root.get("hello") # can order , sort and search for attributes exactly like keys # print sorted(root.keys()) # Accessing text root.text = "TEXT" # print root.text # Playing with XPath needs
true
6fea835bad3e56232e2c9dfd965f8834fe1b7ceb
topuchi13/Res_cmb
/res.py
952
4.125
4
try: file = open ("./list.csv", "r") except FileNotFoundError: print ("*** The file containing available resistor list doesn't exist ***") list = file.read().split('\n') try: target = int(input("\nPlease input the target resistance: ")) except ValueError: print("*** Wrong Value Entered!!! Please enter only one integer, describing the resistor value ***") # def combiner(): # if target in list: # return "You already have that kind of resistor dummy" # for a in range(len(list)): # for b in range(len(list)): # for c in range(len(list)): # if list[a]+list[b]+list[c] == target: # print( "resistor 1: " + list[a] + "resistor 2: " + list[b] + "resistor 3: " + list[c]) # if list[a]+list[b] == target: # return "resistor 1: " + list[a] + "resistor 2: " + list[b] # return "no possible combinations were found" # print (combiner())
true
224cebe24edb6007f91782c94bfbcc61210a2604
kzd0039/Software_Process_Integration
/Assignment/makeChange.py
1,261
4.15625
4
from decimal import Decimal def makeChange(amount = None): """ Create two lists: money: store the amount of the bill To perform exact calculations, multiply all the amount of bills by 1000, which should be [20,10,5,1,0.25,0.1,0.05,0.1] at first, then all the calculations and comparisons are done among integers. result: empty list used to store the output """ money, result = [20000, 10000, 5000, 1000, 250, 100, 50, 10], [] #If there is no input or the input is string or the input is out of range[0,100), return empty list if amount == None or type(amount) == str or amount <0 or amount >= 100: return result # Multiply the amount by 1000, and keep the integer part(keep the digits till thousands places) amount = int(Decimal(str(amount)) * 1000) # Scan the money list, calculate the number of bills one by one and append the result to the output list for x in money: result.append(amount // x) amount = amount % x #If amount is no less than 5(thousands places is no less than 5), add one penny, else do nothing if amount >= 5: result[-1] += 1 #return result to universe return result
true
3adbd132cc9b8ebefb006fd7868a41ff1d9c485c
BadAlgorithm/juniorPythonCourse1
/BitNBites_JuniorPython/Lesson3/trafficLightProgram.py
1,292
4.3125
4
# %%%----------------Standard task------------------%%% lightColour = input("Light colour: ") if lightColour == "green": print("go!") elif lightColour == "orange": print("slow down") elif lightColour == "red": print("stop") else: print("Invalid colour (must be; red, orange or green)") # %%%----------------Extension task------------------%%% # Logical operators userColour = input("Light colour: ") lightColour = userColour.upper() if lightColour == "GREEN" or lightColour == "G": print("go!") elif lightColour == "ORANGE" or lightColour == "O": distance = input("Are you near or far away from the lights? ") distanceUpper = distance.upper() if distanceUpper == "NEAR" or distanceUpper == "N": print("Keep going") elif distanceUpper == "FAR" or distanceUpper == "F": print("Prepare to stop") else: print("Stop...") # String indexing userColour = input("Light colour: ") lightColour = userColour.upper() if lightColour[0] == "G": print("go!") elif lightColour[0] == "O": distance = input("Are you near or far away from the lights? ") distanceUpper = distance.upper() if distanceUpper[0] == "N": print("Keep going") elif distanceUpper[0] == "F": print("Prepare to stop") else: print("Stop...")
true
a47d166561f94e27e1759b83b6c9a62e585de59e
KevinKnott/Coding-Review
/Month 02/Week 01/Day 02/d.py
2,222
4.1875
4
# Binary Tree Zigzag Level Order Traversal: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ # Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between). # Definition for a binary tree node. from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # My first thought on this problem is actually to create the levels in a bfs and pass a empty node to represent a break # or to count the number of nodes added and just flip flop if you add left right or right left of node class Solution: def zigzagLevelOrder(self, root: TreeNode): if not root: return result = [] q = deque() q.appendleft((root, 1)) while q: nodesLeft = len(q) temp = deque() for _ in range(nodesLeft): node, level = q.pop() if level % 2 == 1: temp.append(node.val) else: temp.appendleft(node.val) if node.left: q.appendleft((node.left, level + 1)) if node.right: q.appendleft((node.right, level + 1)) result.append(temp) return result # My first thought to change the order of how we append the nodes to the queue actually fails because I wasn't using the level that I am using now # so it would switch but on the third round or so it would mess up. To fix this I just took advantage of the deque for appending to my list # Now is this an optimal solution? I believe it would be while it is o(N) and o(N+W) where W is the widest width I suppose that you could also do this # with a dfs but honestly it would be convoluted and normally a level order or moving out from a fixed point is the main purpose of a BFS # Score Card # Did I need hints? N # Did you finish within 30 min? 20 # Was the solution optimal? This is optimal # Were there any bugs? See my first blurb after my code # 5 5 5 3 = 4.5
true
ecd2a22e759163ce69be192752e81a19f023f98e
KevinKnott/Coding-Review
/Month 03/Week 01/Day 02/a.py
1,059
4.125
4
# Invert Binary Tree: https://leetcode.com/problems/invert-binary-tree/ # Given the root of a binary tree, invert the tree, and return its root. # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # This problem seems simple enough you go down the tree with a dfs and at every node # you point the children to the opposite side class Solution: def invertTree(self, root: TreeNode) -> TreeNode: def dfs(node): if node: # Swap sides node.left, node.right = node.right, node.left # Traverse down dfs(node.left) dfs(node.right) dfs(root) return root # The above solution is very simple but it runs in O(N) time and O(1) space as we are simply editing in place # Score Card # Did I need hints? N # Did you finish within 30 min?5 # Was the solution optimal? Yeah # Were there any bugs? None # 5 5 5 5 = 5
true
7f886aacfb48d99bcfe6374cc0c819a24d90bc02
KevinKnott/Coding-Review
/Month 02/Week 03/Day 05/a.py
2,835
4.34375
4
# Convert Binary Search Tree to Sorted Doubly Linked List: https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/ # Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place. # You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element. # We want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list. # Definition for a Node. class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right # For this problem we will have to do a simple dfs and then as we go down we should store the node that we are push the current node to the next # This is because as we go down the tree to the left we will get the prev node right then as we come back up that node should point # to the next node # Also the first time we reach the very end to the left we need to set it to the head and at the end point it to the last and vice versa to make it # a circle class Solution: def treeToDoublyList(self, root: 'Node') -> 'Node': if root is None: return self.first = None self.last = None # This is a basic in order traversal def dfs(node): if node is not None: # Traverse left side dfs(node.left) # If there is a node # Check if we have a last node so we can point it to the next node if self.last is not None: self.last.right = node node.left = self.last # One you have updated the pointer check if we need to update first else: self.first = node self.last = node dfs(node.right) # Run through the automation dfs(root) # Point first to last and vice versa self.first.left = self.last self.last.right = self.first return self.first # The above works pretty well as it is a simple dfs with an in order traversal # At the the only tricky part is figuring out when we need to update when we have the first node # This will run in o(N) Time and space as we have to put every node on the stack and visit it # Score Card # Did I need hints? N # Did you finish within 30 min? 15N (45 or so) # Was the solution optimal? See above # Were there any bugs? Nope # 5 5 5 5 = 5
true
1d8e25cdf7d3725c40c4f4f156fb1e13d375ed2b
KevinKnott/Coding-Review
/Month 03/Week 03/Day 03/b.py
1,363
4.25
4
# Symmetric Tree: https://leetcode.com/problems/symmetric-tree/ # Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # In this problem will take the tree and at every point make sure if we swap the left and the right # that they both return the reccurnce relationship that they are equal (the left and right being swapped) class Solution: def isSymmetric(self, root): if root is None: return def swapSides(node1, node2): if node1 and node2: return node1.val == node2.val and swapSides(node1.left, node2.right) and swapSides(node1.right, node2.left) if node1 and not node2: return False if node2 and not node1: return False return True return swapSides(root, root) # This works and is basically making sure you understand how exactly you can move through trees with a recurrence # Our code runs in O(N) as it will have to visit every node # Score Card # Did I need hints? Y # Did you finish within 30 min? 5 # Was the solution optimal? Y # Were there any bugs? N # 5 5 5 5 = 5
true
53b49618af403a3a0d416f3297e7e2a9ca9db70f
KevinKnott/Coding-Review
/Month 03/Week 02/Day 06/a.py
2,135
4.15625
4
# Merge k Sorted Lists: https://leetcode.com/problems/merge-k-sorted-lists/ # You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. # Merge all the linked-lists into one sorted linked-list and return it. # This problem can be broken down into two steps one merging two separate linked lists together # this is easy as it is the same as the merge sort method and secondly updating the n lists # until you only have one the easy way to do this is to use extra space and return a new list # from every merge you do and then keep iterating until there is only one list left and return it. # However the optimal solution is to actually update these in place by overwritting the A array # every time and iterating log(n) times # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeTwo(self, A, B): dummy = ListNode() cur = dummy while A and B: if A.val <= B.val: cur.next = A A = A.next else: cur.next = B B = B.next cur = cur.next if A: cur.next = A if B: cur.next = B return dummy.next def mergeKLists(self, lists): if lists is None or len(lists) == 0: return None while len(lists) > 1: temp = [] for i in range(1, len(lists), 2): temp.append(self.mergeTwo(lists[i-1], lists[i])) if len(lists) % 2 == 1: temp.append(lists[-1]) lists = temp return lists[0] # The above is pretty optimal it runs in O(nlogn) time and uses o(N) space you could slightly improve by just updating # the lists in real time but it would be more complicated and would give you O(1) space # Score Card # Did I need hints? N # Did you finish within 30 min? 15 # Was the solution optimal? Almost just need to improve space but I have limited time today # Were there any bugs? No bugs # 5 5 5 5 = 5
true
ea7d70f36d68d9f544b31b6e0419d643aed7826e
VEGANATO/Learned-How-to-Create-Lists-Code-Academy-
/script.py
606
4.1875
4
# I am a student trying to organize subjects and grades using Python. I am organizing the subjects and scores. print("This Year's Subjects and Grades: ") subjects = ["physics", "calculus", "poetry", "history"] grades = [98, 97, 85, 88] subjects.append("computer science") grades.append(100) gradebook = list(zip(grades, subjects)) gradebook.append(("visual arts", 93)) print(gradebook) last_semester_gradebook = [("politics", 80), ("latin", 96), ("dance", 97), ("architecture", 65)] full_gradebook = gradebook + last_semester_gradebook print("Last Year's Subjects and Grades: ") print(full_gradebook)
true
2fdd7901f6ff2b80df39194d6c47e81d2e9cf9c8
dilayercelik/Learn-Python3-Codecademy-Course
/8. Dictionaries/Project-Scrabble.py
1,800
4.25
4
#Module: Using Dictionaries - Project "Scrabble" letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10] #Question 1 Create a dictionary regrouping the two lists "letters" and "points", with elements of "letters" as keys and elements of "points" as values of the dictionary letter_to_points = {letter:point for letter, point in zip(letters, points)} print(letter_to_points) #Question 2 Add a key:value pair to letter_to_points letter_to_points[" "] = 0 print(letter_to_points) #Question 3-4-5-6 Create a function to compute the score of any word def score_word(word): point_total = 0 for letter in word: if letter in letter_to_points: point_total += letter_to_points[letter] else: point_total += 0 return point_total #example with word "LIFE" print(score_word("LIFE")) #Question 7-8 brownie_points = score_word("BROWNIE") print(brownie_points) #Question 9 player_to_words = {"player1": ["BLUE", "TENNIS", "EXIT"], "wordNerd": ["EARTH", "EYES", "MACHINE"], "Lexi Con": ["ERASER", "BELLY", "HUSKY"], "Prof Reader": ["ZAP", "COMA", "PERIOD"]} print(player_to_words) #Question 10 player_to_points = {} #Question 11-12-13-14 for player, words in player_to_words.items(): player_points = 0 for word in words: player_points += score_word(word) player_to_points[player] = player_points print(player_to_points) #Question 15 - BONUS def play_word(player, word): for value in player_to_words.values(): value.append(word) play_word('player1', 'STUPID') print(player_to_words) ## Bonus 2 for letter in letters: letters.append(letter.lower()) print(letters)
true
69c588b6f00b5cb6ce9ab31141b6f9d0e8639854
HaydnLogan/GitHubRepo
/algorithms/max_number.py
547
4.21875
4
# Algorithms HW1 # Find max number from 3 values, entered manually from a keyboard. # using built in functions # 0(1) no loops def maximum(a, b, c): list = [a, b, c] # return max(list) return max(a, b, c) # not using built in functions def find_max(a, b, c): if a > b and a > c: return a if b > a and b > c: return b return c x = int(input('number 1: ')) y = int(input('number 2: ')) z = int(input('number 3: ')) print(f'Maximum Number is', maximum(x, y, z)) print(f'Max number is', find_max(x, y, z))
true
b3fd7bfe7bf698d287bb30ce2d5e161120f83f2e
HaydnLogan/GitHubRepo
/algorithms/lesson_2/anagrams.py
1,004
4.21875
4
""" Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. """ def is_anagram(s1, s2): if len(s1) != len(s2): return False return sorted(s1) == sorted(s2) # Ture False def is_anagram2(ss1, ss2): if len(ss1) != len(ss2): return False count = {} # dictionary with all the characters for letter in ss1: if letter in count: count[letter] += 1 else: count[letter] = 1 for letter in ss2: if letter in count: count[letter] -= 1 else: count[letter] = 1 for i in count: if count[i] != 0: return False return True str1 = "abcccd" str2 = "abccdc" print(f'Anagrm 1:"', is_anagram(str1, str2)) print(f'Anagrm 2:"', is_anagram2(str1, str2))
true
a98f95088d163de04f30c58ce03e8ee770ec4a63
meagann/ICS4U1c-2018-19
/Working/Classes Practice/practice_point.py
1,302
4.375
4
""" ------------------------------------------------------------------------------- Name: practice_point.py Purpose: Author: James. M Created: 21/03/2019 ------------------------------------------------------------------------------ """ import math class Point(object): def __init__(self, x, y): """ Create an instance of a Point :param x: x coordinate value :param y: y coordinate value """ self.x = x self.y = y def get_distance(self, other_point): """ Compute the distance between the current object and another point :param other_point: Point object to find the distance to :return: float """ distance_x = other_point.x - self.x distance_y = other_point.y - self.y distance = math.sqrt(distance_x**2 + distance_y**2) # distance = math.sqrt((other_point.x - self.x)**2 + (other_point.y - self.y)**2) # distance = (distance_x**2 + distance_y**2)**0.5 return distance def main(): """ Program demonstrating the creation of point instances and calling class methods """ point1 = Point(3, 4) point2 = Point(4, 7) print("The distance between the points is", round(point1.get_distance(point2), 2)) main()
true
5b494b06748c5e2a319d8bcaf82668c02c7cd5cc
amdslancelot/stupidcancode
/questions/group_shifted_strings.py
1,672
4.15625
4
""" Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: "abc" -> "bcd" -> ... -> "xyz" Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], Return: [ ["abc","bcd","xyz"], ["az","ba"], ["acef"], ["a","z"] ] Note: For the return value, each inner list's elements must follow the lexicographic order. """ class Solution(object): ''' 1. Use Tuple to display the distance of each char to first char 2. map(sorted, {}) ''' def groupStrings(self, strings): """ :type strings: List[str] :rtype: List[List[str]] """ r = {} for x in strings: t = tuple((ord(c)-ord(x[0]))%26 for c in x) if t in r: r[t].append(x) else: r[t] = [x] return map(sorted, r.values()) s = Solution() r = s.groupStrings(["az","yx"]) print "ans:", r ''' ["fpbnsbrkbcyzdmmmoisaa" "cpjtwqcdwbldwwrryuclcngw" "a" "fnuqwejouqzrif" "js" "qcpr" "zghmdiaqmfelr" "iedda" "l" "dgwlvcyubde" "lpt" "qzq" "zkddvitlk" "xbogegswmad" "mkndeyrh" "llofdjckor" "lebzshcb" "firomjjlidqpsdeqyn" "dclpiqbypjpfafukqmjnjg" "lbpabjpcmkyivbtgdwhzlxa" "wmalmuanxvjtgmerohskwil" "yxgkdlwtkekavapflheieb" "oraxvssurmzybmnzhw" "ohecvkfe" "kknecibjnq" "wuxnoibr" "gkxpnpbfvjm" "lwpphufxw" "sbs" "txb" "ilbqahdzgij" "i" "zvuur" "yfglchzpledkq" "eqdf" "nw" "aiplrzejplumda" "d" "huoybvhibgqibbwwdzhqhslb" "rbnzendwnoklpyyyauemm"] '''
true
eacc496766f745c8df335d462d8846427f04d229
jtambe/Python
/ArrayOfPairs.py
503
4.3125
4
# this function checks if all elements in array are paired # it uses bitwise XOR logic def IsArrayOfPairs(arr): var = arr checker = 0 for i in range(len(arr)): checker ^= ord(arr[i]) if checker == 0: print("All pairs") else: print("At least one odd entry") def main(): arr = ['A','A','B','B','N','N','M','M',] IsArrayOfPairs(arr) arr = ['A', 'A', 'B', 'B', 'N', 'N', 'M', 'X', ] IsArrayOfPairs(arr) if __name__ == '__main__': main()
true
f0968a9c1fbc572a482ba161d0c19d2d846d8f41
greece57/Reinforcement-Learning
/cardgame/player.py
2,346
4.25
4
""" Abstract Player """ class Player(): """ This class should not be initialized. Inherit from this to create an AI """ def __init__(self, name): """ Initialize Variables """ self.name = name self.cards = [] #inGame self.last_enemy_move = -1 self.points = 0 #afterGame self.last_game = 0.0 #overAll self.won_games = 0 self.lost_games = 0 self.tied_games = 0 self._init() def init_for_game(self, total_cards, points): """ Initialize Player for a new Game """ self.cards = total_cards self.points = points def enemy_played(self, move): """ save enemys move """ self.last_enemy_move = move def won_round(self): """ Called by the Game to inform about round Outcome You played a higher card then the other player. """ self.points += 1 self._won_round() def lost_round(self): """ Called by the Game to inform about negative round Outcome You played a lower card then the other player.""" self._lost_round() def tie_round(self): """ Called by the Game to inform about equal round Outcome. Both players played the same card """ self._tie_round() def perform_move(self): """ Called by the Game to ask for the next Move of the Player """ move = self._choose_move() self.cards.remove(move) return move def won_game(self): """ Called by the Game to inform about positive Game Outcome """ self.won_games += 1 self.last_game = 1 self._game_over() def lost_game(self): """ Called by the Game to inform about negative Game Outcome """ self.lost_games += 1 self.last_game = -1 self._game_over() def tie_game(self): """ Called by the Game to inform about equal Game Outcome """ self.tied_games += 1 self.last_game = 0 self._game_over() ### TO BE IMPLEMENTED ### def _init(self): pass def _choose_move(self): pass def _won_round(self): pass def _lost_round(self): pass def _tie_round(self): pass def _game_over(self): pass def finalize(self): pass
true
b8414a54bb25b12fed98ebd497433d10eae8c591
tjnovak58/cti110
/M6T1_Novak.py
473
4.6875
5
# CTI-110 # M6T1 - Kilometer Converter # Timothy Novak # 11/09/17 # # This program prompts the user to enter a distance in kilometers. # It then converts the distance from kilomters to miles. # conversion_factor = 0.6214 def main(): kilometers = float(input('Enter the distance traveled in kilometers:')) show_miles(kilometers) def show_miles(km): miles = km * conversion_factor print('Distance traveled in miles = ', miles) main()
true
1bc7f7295f1c8ad8d8f3cf278a976cedcef64895
tjnovak58/cti110
/M2HW1_DistanceTraveled_TimothyNovak.py
581
4.34375
4
# CTI-110 # M2HW1 - Distance Traveled # Timothy Novak # 09/10/17 # # Define the speed the car is traveling. speed = 70 # Calculate the distance traveled after 6 hours, 10 hours, and 15 hours. distanceAfter6 = speed * 6 distanceAfter10 = speed * 10 distanceAfter15 = speed * 15 # Display the distance traveled after 6 hours, 10 hours, and 15 hours. print('The number of miles traveled after 6 hours is ', distanceAfter6) print('The number of miles traveled after 10 hours is ', distanceAfter10) print('The number of miles traveled after 15 hours is ', distanceAfter15)
true
75e0f2685f912d3fa048ef83ecdfd0eb11dca378
NiamhOF/python-practicals
/practical-13/p13p5.py
1,073
4.46875
4
''' Practical 13, Exercise 5 Program to illustrate scoping in Python Define the function f of x: print in the function f define x as x times 5 define y as 200 define a as the string I'm in a function define b as 4 to the power of x print the values of x, y, z, a and b return x define values for x, y, z, a and b print the values of x, y, z, a and b before the function define z as the function f(x) print the values of x, y, z, a and b after this ''' def f(x): '''Function that adds 1 to its argument and prints it out''' print ('In function f:') x *= 5 y = 200 a = "I'm in a function" b = 4 ** x print ('a is', a) print ('x is', x) print ('y is', y) print ('z is', z) print ('b is', b) return x x, y, z, a, b = 5, 10, 15, 'Hello', 'Bye' print ('Before function f:') print ('a is', a) print ('x is', x) print ('y is', y) print ('z is', z) print ('b is', b) z = f(x) print ('After function f:') print ('a is', a) print ('x is', x) print ('y is', y) print ('z is', z) print ('b is', b)
true
5e11d2d9c14c56b9ad0686eff5b6754b7989b50d
NiamhOF/python-practicals
/practical-9/p9p2.py
685
4.21875
4
''' Practical 9, Exercise 2 Ask user for a number Ensure number is positive while number is positive for all integers in the range of numbers up to and including the chosen number add each of these integers print the total of these integers ask the user to enter a number again If the number is less than zero, tell the user and stop the program ''' num = int (input ('Enter a positive integer: ')) add = 0 while num > 0: for i in range (0, num + 1, 1): add += i print ('The sum of the integers up to', num, 'is', add) add = 0 num = int (input ('Enter a positive integer: ')) if num < 0: print ('Number is less than zero')
true
29856ffe797d9b60da6735c46773a9d005f7d59d
NiamhOF/python-practicals
/practical-9/p9p5.py
1,958
4.125
4
''' Practical 9, Exercise 5 Ask user for number of possible toppings Ask user for numer of toppings on standard pizza Get the number of the possible toppings minus the number of toppings on a pizza Tell the user if either number is less than 0 or if the difference is less than zero else: calculate factorial of all possible toppings if toppings is equal to 0, factorial is 1 else: define factn as 1 for all numbers between 1 and number get factn = factn * each number if toppings on a standard pizza is equal to 0, factorial is 1 else: define factk as 1 for all numbers between 1 and number get factk = factk * each number get the factorial of the difference between the two if the difference is equal to 1 factj is 1 else: define factj as 1 for all numbers between 1 and number get factj = factj * each number get facti by multiplying factk and factj Print the possible numbers of combinations which is factn/facti ''' top = int (input ('Enter the number of possible toppings: ')) top_stand = int (input ('Enter the number of toppings offered on standard pizza: ')) diff = top - top_stand if top < 0 or top_stand < 0: print ('Number entered was less than 0') elif diff < 0: print ('Number of possible toppings must be greater than the number of toppings offered on a standard pizza') else: if top == 1 or top == 0: factn = 1 else: factn = 1 for i in range (1, top + 1): factn *= i if top_stand == 1 or top_stand == 0: factk = 1 else: factk = 1 for j in range (1, top_stand + 1): factk *= j if diff == 1 or diff == 0: factj = 1 else: factj = 1 for k in range (1, diff + 1): factj *= k facti=factk * factj print ('The number of possible combinations is:', (factn//facti))
true
22cf0ac6f1532d8bce0c66d1f95201a092b3680a
NiamhOF/python-practicals
/practical-9/p9p4.py
849
4.1875
4
''' Practical 9, Exercise 4 Ask user for a number while the number is greater than or equal to 0 if the number is 0, the factorial is 1 if the number is 1, the factorial is 1 if the number is greater than 1: define fact as 1 for all numbers i of the integers from 1 to number fact is fact times i tell the user the factorial ask for another number if the number is less than 0, tell the user ''' num = int (input ('Enter a positive integer: ')) while num >= 0: if num == 0: fact = 1 elif num == 1: fact = 1 else: fact = 1 i = 1 while i <= num: fact *= i i += 1 print ('The factorial of', num, 'is', fact) num = int (input ('Enter a positive integer: ')) if num < 0: print ('Number entered was less than 0')
true
7b698768332c8b9d5a78dd1baee6b3e0c0f65ac9
NiamhOF/python-practicals
/practical-2/p2p4.py
630
4.34375
4
#Practical 2, exercise 4 #Note: index starts at 0 #Note: going beyond the available letters in elephant will return an error animal='elephant' a=animal[0] b=animal[1] c=animal[2] d=animal[3] e=animal[4] f=animal[5] g=animal[6] h=animal[7] print ("The first letter of elephant is: " + a) print ("The second letter of elephant is: " + b) print ("The third letter of elephant is: " + c) print ("The fourth letter of elephant is: " + d) print ("The fifth letter of elephant is: " + e) print ("The sixth letter of elephant is: " + f) print ("The seventh letter of elephant is: " + g) print ("The eight letter of elephant is: " + h)
true
63f49c0b8878c2cf5871e726c2115a10acfc51c9
NiamhOF/python-practicals
/practical-18/p18p5-2.py
1,500
4.125
4
''' Practical 18, Exercise 5 alternate Define a function hasNoPrefix that takes two parameters index and s: if index is equal to zero return true else if the index position - 1 is a period return False else: return True Define a function is XYZ that takes the parameter s: assign containsXYZ the value false if the length of the string is greater than 2: for all values of i in the range 0 to length of string -2: if the first position of i is x and the second position of i is y and the third position of i is z: if passing i and the string through hasNoPrefix is true: containsXYZ is assigned the value true break once this has been shown to be true return containsXYZ if the above is not true Ask user to input a string print the function isXYZ with the parameter word ''' def hasNoPrefix(index, s): '''takes an index and a string and checks for a period''' if index == 0: return True elif s[index - 1] == '.': return False else: return True def isXYZ (s): '''takes string and checks if xyz is in it''' containsXYZ = False if len (s) > 2: for i in range (0, len(s) - 2): if s [i] == 'x' and s [i + 1] == 'y' and s[i + 2] == 'z': if hasNoPrefix(i, s): containsXYZ = True break return containsXYZ word = input ('Enter a string: ') print (isXYZ(word))
true
eb7d25ee8fd40c35ab061dde337f1b185b01607f
edwardmoradian/Python-Basics
/List Processing Part 1.py
290
4.1875
4
# Repetition and Lists Numbers = [8,6,7,5,3,0,9] # Using a for loop with my list of numbers for n in Numbers: print(n,"",end="") print() # Another example, list processing total = 0 for n in Numbers: Total = n + Total print ("Your total is", Total)
true
4b600ba28bb297ca75b0880b746510576afcc4d6
edwardmoradian/Python-Basics
/Read Lines from a File.py
645
4.21875
4
# read lines from a file # steps for dealing with files # 1. Open the file (r,w,a) # 2. Process the file # 3. Close the file ASAP. # open the file f = open("words.txt", "r") # process it, remember that the print function adds a newline character - two different ways to remove newline character line1 = f.readline() # read the first line print(line1, end="") # show it to you line2 = f.readline() # read the second line print(line2, end="") # show it to you line3 = f.readline() # read the thid line line3 = line3.rstrip("/n") print(line3) # show it to you # close it f.close()
true
cbb70013b4ff8ee5d2218244d58d67180aa4d2d1
edwardmoradian/Python-Basics
/List Methods and Functions.py
1,735
4.59375
5
# Let's look at some useful functions and methods for dealing with lists # Methods: append, remove, sort, reverse, insert, index # Access objects with dot operator # Built-in functions: del, min, max # Append = add items to an existing list at the end of the list # takes the item you want added as an argument a = [8,6,7] print(a) a.append(4) # add a 4 to the end of the list a.append(3) print(a) # Index = Takes an value you want to search for in the list as an argument # If it's found , returns the index where it's found. If it's not found, it will raise an exception. index = a.index(6) print(index) index = a.index(-1) print(index) # Insert = Another way to grow your list, but this let's you specify where the new item goes. # moves everyone over one space to make room. print(a) a.insert(1,12) print(a) # Sort = Arranges the values in the list in ascending order. a.sort() print(a) # Remove = the first way we can remove something from a list # Take a copy of the value you want to remove from the list as it's argument # Removes the first copy it finds starting at element 0 a.remove(7) print(a) # Reverse = puts the list in reverse order a.reverse() print(a) # Del = a built-in function that can be used to remove items in a list by index del(a[3]) print(a) # Min = a built-in function that takes a list as an argument and returns the smallest value in the list smallest = min(a) print("The smallest value in the list is", smallest) # Max = a built-in function that takes a list as an argument and returns the biggest value in the list biggest = max(a) print("The biggest value in the list is", biggest)
true
dc1d00f4d881c456baff43f1a54cb24bd34392f1
Sandip-Dhakal/Python_class_files
/class7.py
824
4.1875
4
# String formating using % operator and format method # name='Sam' # age=20 # height=5.7 # txt='Name:\t'+name+"\nAge:\t"+str(age)+"\nHeight:\t"+str(height) # print(txt) # txt="Name: %s Age: %d Height: %f"%(name,age,height) # print(txt) # num=2.54 # txt="Numbers in different decimal places %f,%.1f,%.2f,%.3f"%(num,num,num,num) # print(txt) # #format method # txt="My name is {}".format('Sam') # print(txt) # txt="My name is {name} {cast}".format(name='Sam', cast='Dhakal') # print(txt) # txt="Name: {0} Age: {1} Height: {2}".format(name,age,height) # print(txt) pi= 3.1415 radius = float(input("Enter a radius: ")) area = pi*radius**2 print("Area of circle with radius %.2f is %.2f"%(radius,area)) name = input("Enter your name: ") age = input("Enter your age: ") print('Your name is {} and age is {}'.format(name,age))
true
d72fb44e0d0b9d0e7fbcb16a11cb76fd9b66f605
dragonsarebest/Portfolio
/Code/5October2020.py
1,535
4.3125
4
class ListNode(object): def __init__(self, x): self.val = x self.next = None # Function to print the list def printList(self): node = self output = '' while node != None: output += str(node.val) output += " " node = node.next print(output) # Iterative Solution def reverseIteratively(self, head): # Implement this. previousNode = None node = self while(node != None): temp = node node = node.next temp.next = previousNode previousNode = temp # Recursive Solution def reverseRecursively(self, head): if(currentNode.next): #if not the tail self.reverseRecursively(head.next) #pass along next node #ex: head = 4, next = 3 head.next.next = head #3's next now = 4 head.next = None #4's next now = none # Test Program # Initialize the test list: testHead = ListNode(4) node1 = ListNode(3) testHead.next = node1 node2 = ListNode(2) node1.next = node2 node3 = ListNode(1) node2.next = node3 testTail = ListNode(0) node3.next = testTail print("Initial list: ") testHead.printList() # 4 3 2 1 0 #testHead.reverseIteratively(testHead) testHead.reverseRecursively(testHead) print("List after reversal: ") testTail.printList() # 0 1 2 3 4
true
8d532130ed4482209e92f343cb947eafdd639357
francisrod01/udacity_python_foundations
/03-Use-classes/Turtle-Mini_project/drawing_a_flower.py
660
4.25
4
#!~/envs/udacity-python-env import turtle def draw_flower(some_turtle): for i in range(1, 3): some_turtle.forward(100) some_turtle.right(60) some_turtle.forward(100) some_turtle.right(120) def draw_art(): window = turtle.Screen() window.bgcolor("grey") # Create the turtle Brad - Draws a square brad = turtle.Turtle() brad.shape("turtle") brad.speed(20) brad.color("yellow") # Put draw of square in loop to draw a flower for i in range(0, 36): draw_flower(brad) brad.right(10) brad.setheading(270) brad.forward(400) window.exitonclick() draw_art()
true
e8b187cf82b994c099b135796eb251459f17b1e9
Aryank47/PythonProgramming
/sanfoundary.py
377
4.125
4
# sanfoundary program to add element to a list n=int(input("Enter the no of elements to be read:")) a=[] for i in range(0,n): y=int(input("Enter the elements: ")) a.append(y) print(a) # sanfoundary program to print the multiplication table of the input number res=sum(a)/n print(res) n=int(input("Enter the number: ")) for i in range(1,11): print(n,"*",i,"=",n*i)
true
747991d9889ebfa7f627f7a54e706e8d7ba1eaa3
AbhishekBabuji/Coding
/Leetcode/balaned_paranthesis.py
1,832
4.1875
4
""" The following contains a class and methods to check for a valid patanthesis """ import unittest class ValidParanthesis: """ The following class contains a static method to check for valid paranthesis """ def check_paran(self, input_paran): """ Args: input_paran(str): The string for which one must check if it is valid paranthesis Returns: Boolean (True or False): True of the paranthesis id valid, False otherwise """ openbrace_set = set(('(', '{', '[')) matching_paran_set = set((('(', ')'), ('{', '}'), ('[', ']'))) stack = [] for brace in input_paran: if brace in openbrace_set: stack.append(brace) else: if stack: openbrace = stack.pop() closedbrace = brace if tuple((openbrace, closedbrace)) in matching_paran_set: continue else: return False else: return False return not stack class Test(unittest.TestCase): """ The class contains test cases to check for valid paranthesis """ def test1(self): """ '()[]{}]' False """ example1 = ValidParanthesis() self.assertEqual(example1.check_paran('()[]{}]'), False) def test2(self): """ '{}[' False """ example2 = ValidParanthesis() self.assertEqual(example2.check_paran('()[]{}'), True) def test3(self): """ '(' False """ example3 = ValidParanthesis() self.assertEqual(example3.check_paran('('), False) if __name__ == '__main__': unittest.main()
true
4e914e273e91739c55e8f9f95532e2dcfa778e3d
ioqv/CSE
/Edgar lopez Hangman.py
1,198
4.28125
4
""" A general guide for Hangman 1.Make a word bank - 10 items 2.Pick a random item from the list 3.Hide the word (use *)4.Reveal letters already guessed 5.Create the win condition """ import string import random guesses_left = 10 list_word = ["School", "House", "Computer", "Dog", "Cat", "Eat", "Hospital", "supreme", "pencil","truck", "Soccer"] random_word = random.choice(list_word) letters_guessed = [] ranged_word = len(random_word) print(random_word) guess = "" correct = list(random_word) guess = "" while guess != "quit": output = [] for letter in random_word: if letter in letters_guessed: output.append(letter) else: output.append("*") print(" ".join(list(output))) guess = input("Guess a letter: ") letters_guessed.append(guess) print(letters_guessed) if guess not in random_word: guesses_left -= 1 print(guesses_left) if output == correct: print ("You win") exit(0) if guesses_left == 0: print("you loose") Guesses = input("Guesses a letter:") print("These are your letter %s" % letters_guessed) lower = Guesses.lower() letters_guessed.append(lower)
true