blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
32825ec6823749ec084a80d18865a23f05851a6e
Tetyana-I/first-python-syntax-exercises
/words.py
469
4.5
4
def print_upper_words(words, must_start_with): """Print each word (on a separate line uppercase) from words-list that starts with any letter in must_start_with set """ for word in words: if (word[0] in must_start_with) or (word[0].upper() in must_start_with): print(word.upper()) # this should print "HELLO", "HEY", "YO", and "YES" print_upper_words(["hello", "hey", "goodbye", "yo", "yes"], must_start_with={"H", "y"})
true
8f38be0f4bc6445f279cf523fbb830dbc8482e94
robpalbrah/RedditDailyProgrammer
/easy/dp_293_easy.py
1,713
4.15625
4
""" [2016-11-21] Challenge #293 [Easy] Defusing the bomb https://tinyurl.com/dp-293-easy """ # Status: Done # allowed_wires = {cut_wire_color : [allowed_wire_color, ...], ...} allowed_wires = {None : ['white', 'black', 'purple', 'red', 'green', 'orange'], 'white' : ['purple', 'red', 'green', 'orange'], 'black' : ['black', 'purple' 'red'], 'purple' : ['black', 'red'], 'red' : ['green'], 'green' : ['white', 'orange'], 'orange' : ['black', 'red']} def cut_wire(wire, previous_wire = None): """ Given wire and previous_wire determines whether or not you allowed to cut it. Returns True on success, False othervise. """ if wire in allowed_wires[previous_wire]: return True else: return False def process_input(input_list): """ Determines whether or not you allowed to cut an ordered sequence of wires. Returns True on success, False otherwise. """ previous_wire = current_wire = None for wire in input_list: previous_wire = current_wire current_wire = wire if not cut_wire(current_wire, previous_wire): return False return True def print_bomb_state(input_list): """ Determines whether or not you allowed to cut an ordered sequence of wires. Prints "Bomb defused" on success, "Boom" otherwise. """ if process_input(input_list): print("Bomb defused") else: print("Boom") if __name__ == '__main__': input_1 = ['white', 'red', 'green', 'white'] input_2 = ['white', 'orange', 'green', 'white'] print_bomb_state(input_1) print_bomb_state(input_2)
true
31adb720c1fca5d66db953e58fb4e409cded43f2
RobertHostler/Python-Data-Structures
/StacksAndQueues/QueueFromStacks.py
1,100
4.15625
4
from Stacks import Stack class QueueFromStacks(): # This is a queue implemented using a stack. This is a # common interview question or puzzle, and I thought I # would attempt it myself. def __init__(self, N): self.N = N self.stack1 = Stack(N) self.stack2 = Stack(N) def __str__(self): return str(self.stack1) + "\n" + str(self.stack2) def isEmpty(self): return self.stack1.isEmpty() and self.stack2.isEmpty() def isFull(self): return self.stack1.isFull() and self.stack2.isFull() def enqueue(self, value): if self.isFull(): print("The queue is full.") elif self.isEmpty(): self.stack1.push(value) else: while not self.stack1.isEmpty(): temporary = self.stack1.pop() self.stack2.push(temporary) self.stack1.push(value) while not self.stack2.isEmpty(): temporary = self.stack2.pop() self.stack1.push(temporary) def dequeue(self): return self.stack1.pop()
true
5c7774fab73738e6e625f2eb9e90fc7433f6e2e3
pzhao5/CSSI_Python_Day_4
/for_split.py
595
4.46875
4
my_string = raw_input("Type something: ") # upper() method on string would capitalize the string. # print "{} {}".format("", "") is the way to format a string. # Unlike JS, Python does not support ++, thus you should use += 1 instead print "Print words in upper case" index = 0 for word in my_string.split(): # return individual words in a string. Split it by white space print "{} {}".format(index, word.upper()) # capitalize the words index += 1 print "Print each letter upper case" index = 0 for letter in my_string: print "{} {}".format(index, letter.upper()) index += 1
true
2c18b87f54a76008e1e255b08b7491922f905e0d
danielzyla/Python_intermediate
/11.py
1,223
4.125
4
##choice =''' ## ##choose on from the list: ##'load data' -\t\t 1 ##'export data' -\t\t 2 ##'analyze & predict' -\t 3 ## ##''' ## ##optlisted={'1':'load data', '2':'export data', '3':'analyze & predict'} ## ##choicenr=input(choice) ## ##while choicenr: ## if not choicenr.isdigit(): ## print('it is not number') ## choicenr=input(choice) ## continue ## else: ## if choicenr in optlisted: ## print(optlisted[choicenr]) ## break ## else: ## print('Incorrect number') ## choicenr=input(choice) ## continue options = ['load data', 'export data', 'analyze & predict'] choice = 'x' def DisplayOptions(optlist): for opt in optlist: print('%d - '%(optlist.index(opt)+1)+opt) return input() while choice: choice=DisplayOptions(options) if choice: try: choice_num=int(choice) if choice_num >0 and choice_num <=3: print(options[choice_num-1]) else: print('incorrect choice') except ValueError: print('a number must be entered') continue else: input('press enter to end')
true
ed553ef5a29820c3f52f2b19dfc0867eda49a5d5
Vagacoder/Python_for_everyone
/P4EO_source/ch11/sec05/permutations.py
1,002
4.34375
4
## # This program computes permutations of a string. # def main() : for string in permutations("eat") : print(string) ## Gets all permutations of a given word. # @param word the string to permute # @return a list of all permutations # def permutations(word) : result = [] # The empty string has a single permutation: itself. if len(word) == 0 : result.append(word) return result else : # Loop through all character positions. for i in range(len(word)) : # Form a shorter word by removing the ith character. shorter = word[ : i] + word[i + 1 :] # Generate all permutations of the simpler word. shorterPermutations = permutations(shorter) # Add the removed character to the front of each permutation # of the simpler word. for string in shorterPermutations : result.append(word[i] + string) # Return all permutations. return result # Start the program. main()
true
50e1100ebc2bf59007e20c74181dd9720813a924
Vagacoder/Python_for_everyone
/P4EO_source/ch06/how_to_1/scores.py
1,106
4.21875
4
## # This program computes a final score for a series of quiz scores: the sum after dropping # the two lowest scores. The program uses a list. # def main() : scores = readFloats() if len(scores) > 1 : removeMinimum(scores) removeMinimum(scores) total = sum(scores) print("Final score:", total) else : print("At least two scores are required.") ## Reads a sequence of floating-point numbers. # @return a list containing the numbers # def readFloats() : # Create an empty list. values = [] # Read the input values into a list. print("Please enter values, Q to quit:") userInput = input("") while userInput.upper() != "Q" : values.append(float(userInput)) userInput = input("") return values ## Removes the minimum value from a list. # @param values a list of size >= 1 # def removeMinimum(values) : smallestPosition = 0 for i in range(1, len(values)) : if values[i] < values[smallestPosition] : smallestPosition = i values.pop(smallestPosition) # Start the program. main()
true
5a87579b0e1cc3816dc15f3dd5726a622c0b815d
Vagacoder/Python_for_everyone
/Ch11/P11_16.py
2,652
4.125
4
## P11.16 # revise evaluator.py by adding operations of % and ^ (power) def main() : expr = input("Enter an expression: ") tokens = tokenize(expr) value = expression(tokens) print(expr + "=" + str(value)) ## Breaks a string into tokens. # @param inputLine a string consisting of digits and symbols # @return a list of numbers (made from the digits of the input) and symbols # def tokenize(inputLine) : result = [] i = 0 while i < len(inputLine) : if inputLine[i].isdigit() : j = i + 1 while j < len(inputLine) and inputLine[j].isdigit() : j = j + 1 result.append(int(inputLine[i : j])) i = j else : result.append(inputLine[i]) i = i + 1 return result ## Evaluates the expression. # @param tokens the list of tokens to process # @return the value of the expression # def expression(tokens) : value = term(tokens) done = False while not done and len(tokens) > 0 : next = tokens[0] if next == "+" or next == "-" : tokens.pop(0) # Discard "+" or "-" value2 = term(tokens) if next == "+" : value = value + value2 else : value = value - value2 else : done = True return value ## Evaluates the next term found in the expression. Add "%" # @param tokens the list of tokens to process # @return the value of the term # def term(tokens) : value = power(tokens) done = False while not done and len(tokens) > 0 : next = tokens[0] if next == "*" or next == "/" or next == "%": tokens.pop(0) value2 = factor(tokens) if next == "*" : value = value * value2 elif next == "/" : value = value / value2 else: value = value % value2 else : done = True return value ## power function # power is higher than * or /, but lower than () def power(tokens): value = factor(tokens) done = False while not done and len(tokens) > 0 : next = tokens[0] if next == "^": tokens.pop(0) value2 = factor(tokens) value = value ** value2 else : done = True return value ## Evaluates the next factor found in the expression. # @param tokens the list of tokens to process # @return the value of the factor # def factor(tokens) : next = tokens.pop(0) if next == "(" : value = expression(tokens) tokens.pop(0) # Discard ")" else : value = next return value # Start the program. main()
true
a48ba5b2bef7306a04b613e4764a5172c9f12b27
Vagacoder/Python_for_everyone
/P4EO_source/ch11/sec03/palindromes2.py
1,688
4.34375
4
## # This program uses recursion to determine if a string is a palindrome. # def main() : sentence1 = "Madam, I'm Adam!" print(sentence1) print("Palindrome:", isPalindrome(sentence1)) sentence2 = "Sir, I'm Eve!" print(sentence2) print("Palindrome:", isPalindrome(sentence2)) ## Tests whether a text is a palindrome. # @param text a string that is being checked # @return True if text is a palindrome, False otherwise # def isPalindrome(text) : return substringIsPalindrome(text, 0, len(text) - 1) ## Recursively tests whether a substring is a palindrome. # @param text a string that is being checked # @param start the index of the first character of the substring # @param end the index of the last character of the substring # @return True if the substring is a palindrome # def substringIsPalindrome(text, start, end) : # Separate case for substrings of length 0 and 1. if start >= end : return True else : # Get first and last characters, converted to lowercase. first = text[start].lower() last = text[end].lower() if first.isalpha() and last.isalpha() : if first == last : # Test substring that doesn’t contain the matching letters. return substringIsPalindrome(text, start + 1, end - 1) else : return False elif not last.isalpha() : # Test substring that doesn’t contain the last character. return substringIsPalindrome(text, start, end - 1) else : # Test substring that doesn’t contain the first character. return substringIsPalindrome(text, start + 1, end) # Start the program. main()
true
c8779a53a5928f26a9bde553ca810f751c1ac65f
Vagacoder/Python_for_everyone
/P4EO_source/ch06/sec04/reverse.py
1,079
4.40625
4
## # This program reads, scales and reverses a sequence of numbers. # def main() : numbers = readFloats(5) multiply(numbers, 10) printReversed(numbers) ## Reads a sequence of floating-point numbers. # @param numberOfInputs the number of inputs to read # @return a list containing the input values # def readFloats(numberOfInputs) : print("Enter", numberOfInputs, "numbers:") inputs = [] for i in range(numberOfInputs) : value = float(input("")) inputs.append(value) return inputs ## Multiplies all elements of a list by a factor. # @param values a list of numbers # @param factor the value with which element is multiplied # def multiply(values, factor) : for i in range(len(values)) : values[i] = values[i] * factor ## Prints a list in reverse order. # @param values a list of numbers # def printReversed(values) : # Traverse the list in reverse order, starting with the last element i = len(values) - 1 while i >= 0 : print(values[i], end=" ") i = i - 1 print() # Start the program. main()
true
b834f91ed9708136aa32f8d2b8a6a3fb9add2ea3
Vagacoder/Python_for_everyone
/Function3.py
981
4.21875
4
## Ch05 R5.2h # calculate the weekday of date def weekDay(year, month, day): d = day print(d) m = shiftMonth(month) print(m) c = year // 100 if month == 1 or month == 2: y = year%100 -1 else: y = year%100 if y < 0: y += 100 c += -1 print('y',y) print('c',c) w = ( d + int(2.6*m -0.2) + y + int(y/4) + int(c/4) - 2*c )%7 print(int(2.6*m -0.2)) print(int(y/4)) print(int(c/4)) print(w) while w < 0: w += 7 if w == 0 : weekday = 'Sunday' elif w == 1 : weekday = 'Monday' elif w == 2 : weekday = 'Tuesday' elif w == 3 : weekday = 'Wedsday' elif w == 4 : weekday = 'Thursday' elif w == 5 : weekday = 'Friday' elif w == 6 : weekday = 'Saturday' return weekday def shiftMonth(month): if month >= 3 and month <=12: month += -2 elif month >= 1 and month <= 2 : month += 10 return month print(weekDay(2015, 2, 19))
false
1feb20bdb6281f6323f50c84278816dc128e218d
Vagacoder/Python_for_everyone
/P4EO_source/ch08/sec01/spellcheck.py
1,152
4.46875
4
## # This program checks which words in a file are not present in a list of # correctly spelled words. # # Import the split function from the regular expression module. from re import split def main() : # Read the word list and the document. correctlySpelledWords = readWords("words") documentWords = readWords("alice30.txt") # Print all words that are in the document but not the word list. misspellings = documentWords.difference(correctlySpelledWords) for word in sorted(misspellings) : print(word) ## Reads all words from a file. # @param filename the name of the file # @return a set with all lowercased words in the file. Here, a word is a # sequence of upper- and lowercase letters # def readWords(filename) : wordSet = set() inputFile = open(filename, "r") for line in inputFile : line = line.strip() # Use any character other than a-z or A-Z as word delimiters. parts = split("[^a-zA-Z]+", line) for word in parts : if len(word) > 0 : wordSet.add(word.lower()) inputFile.close() return wordSet # Start the program. main()
true
eea9344b03ebe54c9727d8ec1539e001fe3db9e0
Vagacoder/Python_for_everyone
/Ch12/insertionsort.py
474
4.4375
4
## # The insertionSort function sorts a list, using the insertion sort algorithm. # # Sorts a list, using insertion sort. # @param values the list to sort # def insertionSort(values): for i in range(1, len(values)): next = values[i] # Move all larger elements up. j = i while j > 0 and values[j - 1] > next: values[j] = values[j - 1] j = j - 1 # Insert the element values[j] = next
true
6a18e1cc99ec66f2dd69949cb9c472dd6dcc19de
Vagacoder/Python_for_everyone
/Ch12/P12_1.py
751
4.1875
4
# -*- coding: utf-8 -*- ## P12.1 # selection sort for descending order from random import randint def selectionSortDes(values) : for i in range(len(values)) : maxPos = maximumPosition(values, i) temp = values[maxPos] # swap the two elements values[maxPos] = values[i] values[i] = temp ## Finds the largest element in a tail range of the list. def maximumPosition(values, start) : maxPos = start for i in range(start + 1, len(values)) : if values[i] < values[maxPos] : maxPos = i return maxPos def main(): n = 20 values = [] for i in range(n) : values.append(randint(1, 100)) print(values) selectionSortDes(values) print(values) main()
true
40828a4f4b94cff92a03e7c273ac262e8d894744
Vagacoder/Python_for_everyone
/P4EO_source/ch12/sec06/linearsearch.py
448
4.28125
4
## # This module implements a function for executing linear searches in a list. # ## Finds a value in a list, using the linear search algorithm. # @param values the list to search # @param target the value to find # @return the index at which the target occurs, or -1 if it does not occur in the list # def linearSearch(values, target) : for i in range(len(values)) : if values[i] == target : return i return -1
true
fce8841d3f60fd63bcf052baafc1ebc3705a264e
Vagacoder/Python_for_everyone
/P4EO_source/ch04/sec01/doubleinv.py
505
4.15625
4
## # This program computes the time required to double an investment. # # Create constant variables. RATE = 5.0 INITIAL_BALANCE = 10000.0 TARGET = 2 * INITIAL_BALANCE # Initialize variables used with the loop. balance = INITIAL_BALANCE year = 0 # Count the years required for the investment to double. while balance < TARGET : year = year + 1 interest = balance * RATE / 100 balance = balance + interest # Print the results. print("The investment doubled after", year, "years.")
true
b23d88c162bcb6ff327a45f577e7e39ea17a1b59
anand14327sagar/Python_Learning
/Tuples.py
230
4.125
4
mytuple = (10,10,20,30,40,50) #to count the number of elements print(mytuple.count(10)) #the output will be 2 #to find the index # mytuple.index(50) #the output will be 5. since the index number at 50 is 5.
true
9e1af1f511a41856d2c0e75384f63f8d1d1ae4e0
reddyprasade/Turtle_Graphics_In_Python3
/Circles.py
863
4.25
4
# Python program to user input pattern # using Turtle Programming import turtle #Outside_In import turtle import time import random print ("This program draws shapes based on the number you enter in a uniform pattern.") num_str = input("Enter the side number of the shape you want to draw: ") if num_str.isdigit(): squares = int(num_str) angle = 180 - 180*(squares-2)/squares turtle.up x = 0 y = 0 turtle.setpos(x, y) numshapes = 8 for x in range(numshapes): turtle.color(random.random(), random.random(), random.random()) x += 5 y += 5 turtle.forward(x) turtle.left(y) for i in range(squares): turtle.begin_fill() turtle.down() turtle.forward(40) turtle.left(angle) turtle.forward(40) print (turtle.pos()) turtle.up() turtle.end_fill() time.sleep(11) turtle.bye()
true
8a6f6d7cb6db08dd01f59a56144cc532804f6928
ncommella/automate-boring
/exercises/hello.py
319
4.1875
4
print('Hi, what\'s your name?') userName = input() #displays length of userName print('What\'s up, ' + userName + '? The length of your name is ' + str(len(userName))) #asks for age print('What is your age?') userAge = input() print('In one year, you will be ' + str(int(userAge)+ 1) + ' years old.')
true
a51b1ddb7223ca8b07590ba82e2b2842f7c51d18
DustyHatz/CS50projects
/python/caesar.py
1,392
4.40625
4
# This program will creat a "Caesar Cipher" # User must enter a key (positive integer) and a message to encrypt from cs50 import get_string from sys import argv, exit # Check for exacctly one command line argument and make sure it is a positive integer. If not, exit. if len(argv) == 2 and argv[1].isdigit(): # Convert command line argument to an integer key = int(argv[1]) # Check to make sure the key is a positive integer. If not, exit. if key > 0: # Promt user for original message message = get_string("Message: ") # Create empty string for ciphertext ciphertext = "" # Iterate over the entire original message for i in range(len(message)): char = message[i] # Keep puncuation the same if not char.isalpha(): ciphertext += char # Shift uppercase and lowercase letters by amount of the key elif char.isupper(): ciphertext += chr((ord(char) + key - 65) % 26 + 65) else: ciphertext += chr((ord(char) + key - 97) % 26 + 97) # Print the original message and the encrypted message print("plaintext: " + message) print("ciphertext: " + ciphertext) else: print("Usage: python caesar.py k\n") exit(1) else: print("Usage: python caesar.py k\n") exit(1)
true
9225eeccba5923ace5e1b5189926fe1342fa5dbd
godwinreigh/web-dev-things
/programming projects/python projects/tkinter practice/4. Creating Input Fields.py
588
4.34375
4
from tkinter import * root=Tk() #creating entry widget for input fields #we can change the size of it using the width= and function #we can also change the color using bg and fg #we can also change the border width using borderwidth= function e = Entry(root, width=50, bg='Blue', fg='White', borderwidth = 5) e.pack() #to make the text always be there e.insert(0, "Enter your name: ") def myClick(): hello = "Hello " + e.get() myLabel= Label(root,text=hello) myLabel.pack() myButton = Button(root, text="Enter Your Name!", command =myClick) myButton.pack() root.mainloop()
true
891ec9eb9e870d6a0e6b5ce3b09f2e07a32fb035
godwinreigh/web-dev-things
/programming projects/python projects/tkinter practice/2. Positioning with tkinter's grud system.py
340
4.25
4
#grid system is like a grid think of your program as a grid from tkinter import * root = Tk() #creating a label myLabel1 = Label(root, text='Hello World') myLabel2 = Label(root, text='My name is John Elder') #shoving it onto the screen #this were using grid system myLabel1.grid(row=0, column= 0) myLabel2.grid(row=1, column= 5) root.mainloop()
true
e96eab67caa80b14babe7375ddf669d06bbd0465
godwinreigh/web-dev-things
/programming projects/python projects/tutorials(fundamentals)/14.Buildingbettercalculator.py
475
4.40625
4
numA = float(input("Please enter a number ")) operator = input("Please print an operator ") numB = float(input("Please enter the another number ")) if operator == "+": print(numA + numB) elif operator == "-": print(numA + numB) elif operator == "*": print(numA * numB) elif operator == "/": print(numA / numB) else: print("INVALID") #put float so that num1 won't be a string as a result #It will immediately convert whatever the user inputs into float
true
b03ef6a6f955644c5f3ff28075c0b33c0be05b9e
godwinreigh/web-dev-things
/programming projects/python projects/tutorials2/15. Dictionnaries.py
1,506
4.21875
4
#they are really good for: #super organized data (mini databases) #fast as hell (constant time) #sorted dictionary from collections import OrderedDict groceries = {'bananas': 5, 'oranges': 3 } print(groceries['bananas']) #to avoid syntax error that is because the element is not in the list we can use get, but it will result to none #it is like safety check print(groceries.get('starberry')) contacts = { 'James':{'phone':'123-4567','email':'web@com'}, 'Jane':{'phone':'987-6543','email':'web2@com'''}, } print(contacts['James']) # if we want to count words here sentence = "I like the name Aaron, because the name Aaron is the best." word_counts = { 'I': 1, 'like': 1, 'the' : 3 } #I is keys # 1 is value word_counts['the'] = + 1 #to change the value print(word_counts) #casting dictionary to list #the result will be all of the elements contain in dictionary print(word_counts.items()) #the result will be the only the keys of dictionary print(word_counts.keys()) #the result will be the only the value of dictionary print(word_counts.values()) #to delete something from dictionary word_counts.pop('I') print(word_counts) #to remove arbituary element word_counts.popitem() print(word_counts) #to add something in dictionary word_counts['Aaron'] = 2 #<to add the element 2 times print(word_counts) #to wipe entire dictionary #word_counts.clear() #print(word_counts) #to sort the list print(sorted(list(word_counts.values())))
true
17fb36ba7be775e159d675b035f7c8ac920785af
JBustos22/Physics-and-Mathematical-Programs
/root-finding/roots.py
1,529
4.4375
4
#! /usr/bin/env python """ This program uses Newton's method to calculate the roots of a polynomial which has been entered by the user. It asks for a polynomial function, its derivative, and the plotting range. It then plots it, and asks the user for a value. Once a value is entered, the root closest to that value is evaluated. Jorge Bustos Mar 4, 2019 """ from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt def Newton(f,dfdx,x,xL,e): #function defining the Newton method while np.abs(x-xL) > e: xL = x x = xL- f(xL)/dfdx(xL) return x fx=raw_input("Enter a Polynomial: ") #turns the polynomial inputs into usable functions def f(x): return eval(fx) dfx = raw_input("Enter its derivative: ") def df(x): return eval(dfx) a = int(raw_input("Enter the lower bound of your interval: ")) b = int(raw_input("Enter the upper bound of your interval: ")) x = np.linspace(a,b,1000) plt.plot(x,f(x)) plt.xlabel("x") plt.ylabel("f(x)") plt.show() x_i = 0 def isFloat(s): #functions that checks if it's a float try: float(s) return True except ValueError: return False while x_i != "q" : x_i = raw_input("Enter the starting value for root finding (q for quit): ") if isFloat(x_i): #checking for float print("The root of your polynomial is: ",Newton(f,df,float(x_i),1e4,1e-10)) plt.plot(x,f(x)) plt.xlabel("x") plt.ylabel("f(x)") plt.show() elif(x_i != "q"): #anything other than q or float print("invalid entry") print("Goodbye!")
true
3f7efff67d6ccd7cc349131237d356e34908635d
JBustos22/Physics-and-Mathematical-Programs
/plots and data/fractal.py
753
4.28125
4
#! /usr/bin/env python """ This program plots a fractal pattern using matplotlib Jorge Bustos Feb 12, 2019 """ from __future__ import division,print_function import matplotlib.pyplot as plt import numpy as np import math as m plt.scatter(-1,0,c="b",s=.1) plt.scatter(0,m.sqrt(3),c="b",s=.1) plt.scatter(1,0,c="b",s=10) x = 0 y = 0 r = 0 iterations = 200000 #how many points to plot for i in range (0,iterations,1): plt.scatter(-1*x,-1*y,c="b",s=.1) r = np.random.randint(3) #chooses a number from 0 to 2 randomly if r == 0: #for vertex (-1,0) x = (x + 1)/2 y = (y - 0)/2 elif r == 1: #for vertex (0,sqrt(3)) x = (x - 0)/2 y = (y - m.sqrt(3))/2 else: #for vertex(1,0) x = (x - 1)/2 y = (y - 0)/2 plt.savefig("fractal.png") plt.show()
false
43def0189ddebca9e6d900604d692c9a9d2e1a36
JBustos22/Physics-and-Mathematical-Programs
/computational integrals/hyperspheres.py
779
4.21875
4
#! /usr/bin/env python """ This program uses the numerical monte carlo integration function from the numint module. It calculates the volume of an unit sphere for dimensions 0, through 12, and creates a plot of hypervolume vs dimension. Jorge Bustos Mar 4, 2019 """ from __future__ import division, print_function import numint as ni import numpy as np #import matplotlib.pyplot as plt def f(x): return x[0]**2 + x[1]**2 + x[2]**2 N = 100 dim = 10 limit = [] print(0) d = np.linspace(0,12,13) I = [0] for k in range(1,13,1): dim = k limit += [[0,1]] I +=[ni.montecarlo(f,dim,limit,N)] print(I[k]) # plt.plot(d,I) # plt.xlabel("Dimension") # plt.ylabel("Hypervolume") # plt.title("Hypervolumes of an Unit Sphere vs. Dimension") # plt.savefig("hyperspheres.png") # plt.show()
true
6f42fe89b6be6ebf1d26bced38b9b523400b1903
ASamiAhmed/PythonPrograms
/sets.py
965
4.15625
4
variables = {'a','b','c','d','c'} print(variables) # remove the repeated variables variables.add('z') print(variables) # to add a new letter b = frozenset('asdsafadgwas') print(b) # frozenset conversion print({1,2,3,4} & {3,4,5,6}) # & is sign of intersection print({1,2,3} | {2,3,4}) # | is sign of union print({1,2,3} - {2,3,4}) # - is sign of difference print({1,2,3,4} ^ {2,3,5}) # ^ is sign of symmetric difference print({1,2} >= {1,2,3}) # >= is sign of superset check print({1,2} <= {1,2,3}) # >= is sign of subset check print( 2 in {1,2,3}) # in is for existance check print(4 in {1,2,3}) # in is for existance check s = {1,2,3} s.add(4) # add function is to add something print(s) s.discard(2) # to remove/delete print(s) s.remove(1) # to remove/delete print(s) s.update({1,2}) # to update set print(s) print(len(s))
false
ae9b70d3d0a73ca6f696a681d3e82c4969b99716
ASamiAhmed/PythonPrograms
/feet_inch_cm.py
278
4.28125
4
''' Write a Python program to convert height (in feet and inches) to centimetres. ''' number = int(input("Enter number: ")) feet = number*30.48 print("The number you entered in centimeter is",feet) inch = number*2.54 print("The number you entered in centimeter is",inch)
true
e9a31c7404309047d598f507aed85fbf0630ac40
tgandrews/Project-Euler
/Problem 6/Difference between sum of square and square of sum.py
654
4.21875
4
# Difference between sum of square and square of sum # (1^2 + 2^2) - (1 + 2)^2 import time; def Sum(maxVal): resultSquares = 0; resultSum = 0; i = 0; while i <= maxVal: resultSquares += (i * i); resultSum += i; i = i + 1; print 'Sum: ' + str(resultSum); print 'Sum of squares: ' + str(resultSquares); resultSumSquared = resultSum * resultSum; result = resultSumSquared - resultSquares; return result; print 'Working on first 100 natural numbers' start = time.time(); result = Sum(100); end = time.time(); print 'Result: ' + str(result); print 'Took: ' + str(end - start) + ' seconds';
true
6ac88a30fc498f0ae5505bf7813c82f52d631676
yiming1012/MyLeetCode
/LeetCode/贪心算法/455. 分发饼干.py
1,723
4.15625
4
""" 455. 分发饼干 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。 对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。   示例 1: 输入: g = [1,2,3], s = [1,1] 输出: 1 解释: 你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。 虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。 所以你应该输出1。 示例 2: 输入: g = [1,2], s = [1,2,3] 输出: 2 解释: 你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。 你拥有的饼干数量和尺寸都足以让所有孩子满足。 所以你应该输出2.   提示: 1 <= g.length <= 3 * 104 0 <= s.length <= 3 * 104 1 <= g[i], s[j] <= 231 - 1 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/assign-cookies 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: g.sort() s.sort() m, n = len(g), len(s) i, j = 0, 0 while i < m and j < n: if g[i] <= s[j]: i += 1 j += 1 return i if __name__ == '__main__': g = [1, 2, 3] s = [1, 2] print(Solution().findContentChildren(g, s))
false
34c52fae8d33c2f0390b13e2d1adaa3089805f5c
yiming1012/MyLeetCode
/LeetCode/树(Binary Tree)/199. Binary Tree Right Side View.py
2,027
4.21875
4
''' Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example: Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 <--- 通过次数26,604提交次数41,423 ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None import collections class Solution: def rightSideView(self, root: TreeNode) -> List[int]: ''' 执行用时 :36 ms, 在所有 Python3 提交中击败了80.96%的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了14.29%的用户 :param root: :return: ''' if not root: return [] queue = collections.deque() queue.append(root) res = [root.val] while queue: stack = [] while queue: node = queue.popleft() if node.left: stack.append(node.left) if node.right: stack.append(node.right) if stack: queue = collections.deque(stack) res.append(stack[-1].val) else: break return res def rightSideView(self, root): if not root: return [] level = [root] result = [] while level: next_level = [] result.append(level[-1].val) for node in level: if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) level = next_level return result
true
c9f5377545185d4cdca2bcfb228ddc43cd6b65b4
yiming1012/MyLeetCode
/LeetCode/哈希表(hash table)/1338. 数组大小减半.py
1,712
4.25
4
""" 1338. 数组大小减半 给你一个整数数组 arr。你可以从中选出一个整数集合,并删除这些整数在数组中的每次出现。 返回 至少 能删除数组中的一半整数的整数集合的最小大小。   示例 1: 输入:arr = [3,3,3,3,5,5,5,2,2,7] 输出:2 解释:选择 {3,7} 使得结果数组为 [5,5,5,2,2]、长度为 5(原数组长度的一半)。 大小为 2 的可行集合有 {3,5},{3,2},{5,2}。 选择 {2,7} 是不可行的,它的结果数组为 [3,3,3,3,5,5,5],新数组长度大于原数组的二分之一。 示例 2: 输入:arr = [7,7,7,7,7,7] 输出:1 解释:我们只能选择集合 {7},结果数组为空。 示例 3: 输入:arr = [1,9] 输出:1 示例 4: 输入:arr = [1000,1000,3,7] 输出:1 示例 5: 输入:arr = [1,2,3,4,5,6,7,8,9,10] 输出:5   提示: 1 <= arr.length <= 10^5 arr.length 为偶数 1 <= arr[i] <= 10^5 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/reduce-array-size-to-the-half 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from collections import Counter from typing import List class Solution: def minSetSize(self, arr: List[int]) -> int: """ 思路: 1. 统计词频,按词频逆序排序 @param arr: @return: """ n = len(arr) cnt = [(k, v) for k, v in Counter(arr).items()] cnt.sort(key=lambda x: x[1], reverse=True) # print(cnt) res = 0 cursum = 0 for k, v in cnt: cursum += v res += 1 if cursum * 2 >= n: return res
false
fedbe2bccf489f778cba98d6ebc58fa8915e9ab3
yiming1012/MyLeetCode
/LeetCode/贪心算法/452. 用最少数量的箭引爆气球.py
2,714
4.125
4
""" 在二维空间中有许多球形的气球。对于每个气球,提供的输入是水平方向上,气球直径的开始和结束坐标。由于它是水平的,所以y坐标并不重要,因此只要知道开始和结束的x坐标就足够了。开始坐标总是小于结束坐标。平面内最多存在104个气球。 一支弓箭可以沿着x轴从不同点完全垂直地射出。在坐标x处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstart,xend, 且满足  xstart ≤ x ≤ xend,则该气球会被引爆。可以射出的弓箭的数量没有限制。 弓箭一旦被射出之后,可以无限地前进。我们想找到使得所有气球全部被引爆,所需的弓箭的最小数量。 Example: 输入: [[10,16], [2,8], [1,6], [7,12]] 输出: 2 解释: 对于该样例,我们可以在x = 6(射爆[2,8],[1,6]两个气球)和 x = 11(射爆另外两个气球)。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solution: def findMinArrowShots(self, points: List[List[int]]) -> int: """ 思路:贪心算法 1. 按照起点从小到大排序,如果新的区间的起点ll小于当前区间的终点r,就缩小区间r = min(r, rr),令r等于当前区间和新区间终点的最小值 2. 如果新区间的起点ll大于当前区间的终点,则需要新的箭,res+1,同时设置新的区间的终点r @param points: @return: """ if not points: return 0 points.sort() res = 1 l, r = points[0] for i in range(1, len(points)): ll, rr = points[i] if ll > r: res += 1 r = rr else: r = min(r, rr) return res def findMinArrowShots2(self, points: List[List[int]]) -> int: """ 思路:贪心算法 1. 与思路1类似,该方法对每个区间的右端点排序,判断下一个区间的左端点是否大于当前区间的右端点 @param points: @return: """ if not points: return 0 points.sort(key=lambda x: x[1]) res = 1 l, r = points[0] for i in range(1, len(points)): ll, rr = points[i] if ll > r: res += 1 r = rr return res if __name__ == '__main__': points = [[10, 16], [2, 8], [1, 6], [7, 12]] print(Solution().findMinArrowShots(points))
false
7b53844e39454329c18574049ece774d5acc34f8
yiming1012/MyLeetCode
/LeetCode/设计/341. 扁平化嵌套列表迭代器.py
2,015
4.5
4
""" 341. 扁平化嵌套列表迭代器 给你一个嵌套的整型列表。请你设计一个迭代器,使其能够遍历这个整型列表中的所有整数。 列表中的每一项或者为一个整数,或者是另一个列表。其中列表的元素也可能是整数或是其他列表。   示例 1: 输入: [[1,1],2,[1,1]] 输出: [1,1,2,1,1] 解释: 通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,1,2,1,1]。 示例 2: 输入: [1,[4,[6]]] 输出: [1,4,6] 解释: 通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,4,6]。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/flatten-nested-list-iterator 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ class NestedInteger: def isInteger(self) -> bool: """ @return True if this NestedInteger holds a single integer, rather than a nested list. """ def getInteger(self) -> int: """ @return the single integer that this NestedInteger holds, if it holds a single integer Return None if this NestedInteger holds a nested list """ def getList(self) -> []: """ @return the nested list that this NestedInteger holds, if it holds a nested list Return None if this NestedInteger holds a single integer """ class NestedIterator: def __init__(self, nestedList: [NestedInteger]): self.stack = nestedList[::-1] def next(self) -> int: return self.stack.pop().getInteger() def hasNext(self) -> bool: while self.stack: top = self.stack[-1] if top.isInteger(): return True self.stack = self.stack[:-1] + top.getList()[::-1] return False
false
1c42c564af105d39f03b5d3a96775179d4a39582
yiming1012/MyLeetCode
/LeetCode/栈/单调栈(Monotone Stack)/496. 下一个更大元素 I.py
2,435
4.1875
4
""" 给定两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。 nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。   示例 1: 输入: nums1 = [4,1,2], nums2 = [1,3,4,2]. 输出: [-1,3,-1] 解释: 对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。 对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。 对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。 示例 2: 输入: nums1 = [2,4], nums2 = [1,2,3,4]. 输出: [3,-1] 解释:   对于 num1 中的数字 2 ,第二个数组中的下一个较大数字是 3 。 对于 num1 中的数字 4 ,第二个数组中没有下一个更大的数字,因此输出 -1 。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/next-greater-element-i 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: """ 思路:暴力法 时间复杂度:O(N*N) """ res = [] for num in nums1: index = nums2.index(num) for i in range(index + 1, len(nums2)): if nums2[i] > num: res.append(nums2[i]) break else: res.append(-1) return res def nextGreaterElement2(self, nums1: List[int], nums2: List[int]) -> List[int]: """ 思路: """ dic = {} stack = [] for i, num in enumerate(nums2): while stack and num > nums2[stack[-1]]: index = stack.pop() dic[nums2[index]] = num stack.append(i) return [dic.get(x, -1) for x in nums1] if __name__ == '__main__': nums1 = [4, 1, 2] nums2 = [1, 3, 4, 2] Solution().nextGreaterElement(nums1,nums2) Solution().nextGreaterElement2(nums1,nums2) if __name__ == '__main__': nums1 = [4, 1, 2] nums2 = [1, 3, 4, 2] print(Solution().nextGreaterElement(nums1, nums2))
false
47f28239360c82afb9e16dac6fec9557b2217310
yiming1012/MyLeetCode
/LeetCode/数学/1185. 一周中的第几天.py
1,328
4.1875
4
""" 1185. 一周中的第几天 给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。 输入为三个整数:day、month 和 year,分别表示日、月、年。 您返回的结果必须是这几个值中的一个 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}。 示例 1: 输入:day = 31, month = 8, year = 2019 输出:"Saturday" 示例 2: 输入:day = 18, month = 7, year = 1999 输出:"Sunday" 示例 3: 输入:day = 15, month = 8, year = 1993 输出:"Sunday" 提示: 给出的日期一定是在 1971 到 2100 年之间的有效日期。 """ class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: """ 吉姆拉尔森公式 @param day: @param month: @param year: @return: """ if month <= 2: d, m, y = day, month + 12, year - 1 else: d, m, y = day, month, year W = (d + 2 * m + 3 * (m + 1) // 5 + y + y // 4 - y // 100 + y // 400 + 1) % 7 week_day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] return week_day[W] if __name__ == '__main__': day = 31 month = 8 year = 2019 print(Solution().dayOfTheWeek(day, month, year))
false
6da0cb332487b42897331ba993693676ef3937f0
yiming1012/MyLeetCode
/LeetCode/树(Binary Tree)/114. 二叉树展开为链表.py
1,503
4.15625
4
""" 给定一个二叉树,原地将它展开为一个单链表。   例如,给定二叉树 1 / \ 2 5 / \ \ 3 4 6 将其展开为: 1 \ 2 \ 3 \ 4 \ 5 \ 6 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # 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: nex = None def flatten(self, root: TreeNode) -> None: """ 思路: 1. 记录中间变量 """ if root: self.flatten(root.right) self.flatten(root.left) print(root.val) root.right = self.nex root.left = None self.nex = root def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ if not root: return root def dfs(root): if root: arr.append(root) dfs(root.left) dfs(root.right) arr = [] dummy = root dfs(root) for i in range(len(arr) - 1): arr[i].left = None arr[i].right = arr[i + 1] return dummy
false
ca4e9d27433326261734046a3976e098e1704cba
yiming1012/MyLeetCode
/LeetCode/数学/面试题 16.11. 跳水板.py
1,571
4.1875
4
""" 你正在使用一堆木板建造跳水板。有两种类型的木板,其中长度较短的木板长度为shorter,长度较长的木板长度为longer。你必须正好使用k块木板。编写一个方法,生成跳水板所有可能的长度。 返回的长度需要从小到大排列。 示例: 输入: shorter = 1 longer = 2 k = 3 输出: {3,4,5,6} 提示: 0 < shorter <= longer 0 <= k <= 100000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/diving-board-lcci 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solution: def divingBoard1(self, shorter: int, longer: int, k: int) -> List[int]: """ 思路:数学公式length= longer * i + (k - i) * shorter 或者等差数列:range(shorter * k, longer * k + 1, longer - shorter) """ if k == 0: return [] if shorter == longer: return [k * shorter] res = [] for i in range(k + 1): res.append(longer * i + (k - i) * shorter) return res def divingBoard2(self, shorter: int, longer: int, k: int) -> List[int]: if k == 0: return [] if shorter == longer: return [k * shorter] return list(range(shorter * k, longer * k + 1, longer - shorter)) if __name__ == '__main__': shorter, longer = 2, 5 k = 5 print(Solution().divingBoard1(shorter, longer, k)) print(Solution().divingBoard2(shorter, longer, k))
false
cb3e2ddcbf9b58bd603b6ce23151e7df6b41cee0
yiming1012/MyLeetCode
/LeetCode/1184. Distance Between Bus Stops.py
2,425
4.34375
4
''' A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n. The bus goes along both directions i.e. clockwise and counterclockwise. Return the shortest distance between the given start and destination stops.   Example 1: Input: distance = [1,2,3,4], start = 0, destination = 1 Output: 1 Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.   Example 2: Input: distance = [1,2,3,4], start = 0, destination = 2 Output: 3 Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.   Example 3: Input: distance = [1,2,3,4], start = 0, destination = 3 Output: 4 Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.   Constraints: 1 <= n <= 10^4 distance.length == n 0 <= start, destination < n 0 <= distance[i] <= 10^4 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/distance-between-bus-stops 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' from typing import List class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: ''' 执行用时 :76 ms, 在所有 Python3 提交中击败了22.02%的用户 内存消耗 :14.5 MB, 在所有 Python3 提交中击败了10.00%的用户 :param distance: :param start: :param destination: :return: ''' if destination<start: start,destination=destination,start return min(sum(distance[start:destination]),sum(distance)-sum(distance[start:destination])) def distanceBetweenBusStops2(self, distance: List[int], start: int, destination: int) -> int: ''' 执行用时 :44 ms, 在所有 Python3 提交中击败了90%的用户 内存消耗 :14.5 MB, 在所有 Python3 提交中击败了10.00%的用户 优化思路:尽量将前一步运算出来的结果通过变量存起来,不要在用一次sum等函数 :param distance: :param start: :param destination: :return: ''' if start > destination: start, destination = destination, start forward = sum(distance[start:destination]) backward = sum(distance) - forward return min(forward, backward)
true
67f7d37b82e337c1c94ffc26c02464236cf14e21
yiming1012/MyLeetCode
/LeetCode/回溯法/5635. 构建字典序最大的可行序列.py
2,763
4.125
4
""" 5635. 构建字典序最大的可行序列 给你一个整数 n ,请你找到满足下面条件的一个序列: 整数 1 在序列中只出现一次。 2 到 n 之间每个整数都恰好出现两次。 对于每个 2 到 n 之间的整数 i ,两个 i 之间出现的距离恰好为 i 。 序列里面两个数 a[i] 和 a[j] 之间的 距离 ,我们定义为它们下标绝对值之差 |j - i| 。 请你返回满足上述条件中 字典序最大 的序列。题目保证在给定限制条件下,一定存在解。 一个序列 a 被认为比序列 b (两者长度相同)字典序更大的条件是: a 和 b 中第一个不一样的数字处,a 序列的数字比 b 序列的数字大。比方说,[0,1,9,0] 比 [0,1,5,6] 字典序更大,因为第一个不同的位置是第三个数字,且 9 比 5 大。   示例 1: 输入:n = 3 输出:[3,1,2,3,2] 解释:[2,3,2,1,3] 也是一个可行的序列,但是 [3,1,2,3,2] 是字典序最大的序列。 示例 2: 输入:n = 5 输出:[5,3,1,4,3,5,2,4,2]   提示: 1 <= n <= 20 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/construct-the-lexicographically-largest-valid-sequence 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solution: def constructDistancedSequence(self, n: int) -> List[int]: """ 思路:回溯法 类似数独 @param n: @return: """ m = 2 * n - 1 self.arr = [0] * m visited = set() # 找到了就返回True def backtrack(cur): if len(visited) == n: return True if self.arr[cur] != 0: if backtrack(cur + 1): return True for i in range(n, 0, -1): if i == 1 and i not in visited and self.arr[cur] == 0: self.arr[cur] = i visited.add(i) if backtrack(cur + 1): return True visited.remove(i) self.arr[cur] = 0 elif i not in visited and self.arr[cur] == 0 and cur + i < m and self.arr[cur + i] == 0: self.arr[cur] = i self.arr[cur + i] = i visited.add(i) if backtrack(cur + 1): return True visited.remove(i) self.arr[cur] = 0 self.arr[cur + i] = 0 return False backtrack(0) return self.arr if __name__ == '__main__': n = 3 print(Solution().constructDistancedSequence(n))
false
92dc91b390fde40f52df760b6f242e120cd7ae1b
yiming1012/MyLeetCode
/LeetCode/位运算/461. 汉明距离.py
1,058
4.4375
4
""" 两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。 给出两个整数 x 和 y,计算它们之间的汉明距离。 注意: 0 ≤ x, y < 231. 示例: 输入: x = 1, y = 4 输出: 2 解释: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ 上面的箭头指出了对应二进制位不同的位置。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/hamming-distance 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution: def hammingDistance(self, x: int, y: int) -> int: """ 思路:位运算 1. 判断二进制位是否相同,可用异或运算 2. 异或规则:相同为0,相异为1 @param x: @param y: @return: """ res = 0 ans = x ^ y while ans: ans &= ans - 1 res += 1 return res if __name__ == '__main__': x, y = 1, 4 print(Solution().hammingDistance(x, y))
false
bfbf594cc9c4e32065223bb06fee7b6f529cd945
yiming1012/MyLeetCode
/LeetCode/树(Binary Tree)/1367. 二叉树中的列表.py
2,164
4.125
4
""" 1367. 二叉树中的列表 给你一棵以 root 为根的二叉树和一个 head 为第一个节点的链表。 如果在二叉树中,存在一条一直向下的路径,且每个点的数值恰好一一对应以 head 为首的链表中每个节点的值,那么请你返回 True ,否则返回 False 。 一直向下的路径的意思是:从树中某个节点开始,一直连续向下的路径。 示例 1: 输入:head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] 输出:true 解释:树中蓝色的节点构成了与链表对应的子路径。 示例 2: 输入:head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] 输出:true 示例 3: 输入:head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] 输出:false 解释:二叉树中不存在一一对应链表的路径。 提示: 二叉树和链表中的每个节点的值都满足 1 <= node.val <= 100 。 链表包含的节点数目在 1 到 100 之间。 二叉树包含的节点数目在 1 到 2500 之间。 """ # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # 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 isSubPath(self, head: ListNode, root: TreeNode) -> bool: flag = False def dfs(root): if not root: return nonlocal flag if root.val == head.val: if find(head, root): flag = True return dfs(root.left) dfs(root.right) if flag: return def find(head, root): if not head: return True if not root: return False if head.val == root.val: return find(head.next, root.left) or find(head.next, root.right) else: return False dfs(root) return flag
false
47d8e7ca10710cc2e5f3124c9ce0397ee87dd9fd
yiming1012/MyLeetCode
/LeetCode/840. Magic Squares In Grid.py
1,990
4.28125
4
''' A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum. Given an grid of integers, how many 3 x 3 "magic square" subgrids are there?  (Each subgrid is contiguous).   Example 1: Input: [[4,3,8,4], [9,5,1,9], [2,7,6,2]] Output: 1 Explanation: The following subgrid is a 3 x 3 magic square: 438 951 276 while this one is not: 384 519 762 In total, there is only one magic square inside the given grid. Note: 1 <= grid.length <= 10 1 <= grid[0].length <= 10 0 <= grid[i][j] <= 15 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/magic-squares-in-grid 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' from typing import List class Solution: def numMagicSquaresInside(self, grid: List[List[int]]) -> int: ''' 执行用时 :64 ms, 在所有 Python3 提交中击败了14.46%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了6.67%的用户 :param grid: :return: ''' if len(grid)<3 or len(grid[0])<3: return 0 row = len(grid) col =len(grid[0]) count = 0 array = [i for i in range(1,10)] for i in range(row-2): for j in range(col-2): arr =[] # print(i,j) arr.extend(grid[i][j:j+3]) arr.extend(grid[i+1][j:j+3]) arr.extend(grid[i+2][j:j+3]) arr.sort() # print(arr) # print(sum(grid[i][j:j+3])) if arr!=array or grid[i+1][j+1]!=5 or sum(grid[i][j:j+3])!=15 or sum(grid[i+1][j:j+3])!=15 or sum(grid[i+2][j:j+3])!=15 or grid[i][j]+grid[i+1][j]+grid[i+2][j]!=15 or grid[i][j]+grid[i+1][j+1]+grid[i+2][j+2]!=15: continue else: count+=1 return count
true
b9446b52ab01cd26faaa1b6a36ec555800178aef
yiming1012/MyLeetCode
/LeetCode/树(Binary Tree)/889. 根据前序和后序遍历构造二叉树.py
1,727
4.125
4
""" 889. 根据前序和后序遍历构造二叉树 返回与给定的前序和后序遍历匹配的任何二叉树。  pre 和 post 遍历中的值是不同的正整数。   示例: 输入:pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1] 输出:[1,2,3,4,5,6,7]   提示: 1 <= pre.length == post.length <= 30 pre[] 和 post[] 都是 1, 2, ..., pre.length 的排列 每个输入保证至少有一个答案。如果有多个答案,可以返回其中一个。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode: def dfs(pre, post): if len(pre) == 1: return TreeNode(pre[0]) root = TreeNode(pre[0]) left = pre[1] right = post[-2] # 判断是否只剩一颗子树 if left == right: # 只有一棵子树 root.left = dfs(pre[1:], post[:-1]) else: # 存在左右子树 # 分别找到左右子树的根节点 prel = pre.index(right) postl = post.index(left) root.left = dfs(pre[1:prel], post[:postl + 1]) root.right = dfs(pre[prel:], post[postl + 1:-1]) return root return dfs(pre, post)
false
3b89c920a23fe0a68e3743068091a6969eeb910c
yiming1012/MyLeetCode
/LeetCode/会员题/243. 最短单词距离.py
1,403
4.125
4
""" 243. 最短单词距离 给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。 示例: 假设 words = ["practice", "makes", "perfect", "coding", "makes"] 输入: word1 = “coding”, word2 = “practice” 输出: 3 输入: word1 = "makes", word2 = "coding" 输出: 1 注意: 你可以假设 word1 不等于 word2, 并且 word1 和 word2 都在列表里。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/shortest-word-distance 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solution: def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: """ 思路:双指针 @param wordsDict: @param word1: @param word2: @return: """ i1 = i2 = -1 res = float('inf') for i, word in enumerate(wordsDict): if word == word1: i1 = i if word == word2: i2 = i if i1 != -1 and i2 != -1: res = min(res, abs(i1 - i2)) return res if __name__ == '__main__': wordsDict = ["practice", "makes", "perfect", "coding", "makes"] word1 = "coding" word2 = "practice" print(Solution().shortestDistance(wordsDict, word1, word2))
false
9e6dcce6dedd93812e378a54f53748beb5487972
yiming1012/MyLeetCode
/LeetCode/数组/1267. 统计参与通信的服务器.py
1,962
4.125
4
""" 1267. 统计参与通信的服务器 这里有一幅服务器分布图,服务器的位置标识在 m * n 的整数矩阵网格 grid 中,1 表示单元格上有服务器,0 表示没有。 如果两台服务器位于同一行或者同一列,我们就认为它们之间可以进行通信。 请你统计并返回能够与至少一台其他服务器进行通信的服务器的数量。   示例 1: 输入:grid = [[1,0],[0,1]] 输出:0 解释:没有一台服务器能与其他服务器进行通信。 示例 2: 输入:grid = [[1,0],[1,1]] 输出:3 解释:所有这些服务器都至少可以与一台别的服务器进行通信。 示例 3: 输入:grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]] 输出:4 解释:第一行的两台服务器互相通信,第三列的两台服务器互相通信,但右下角的服务器无法与其他服务器通信。   提示: m == grid.length n == grid[i].length 1 <= m <= 250 1 <= n <= 250 grid[i][j] == 0 or 1 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/count-servers-that-communicate 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solution: def countServers(self, grid: List[List[int]]) -> int: """ 思路:判断每行每列是否存在超过两台服务器 @param grid: @return: """ m, n = len(grid), len(grid[0]) row = [0] * m col = [0] * n for i in range(m): row[i] = sum(grid[i]) for i in range(n): col[i] = sum([grid[k][i] for k in range(m)]) res = 0 for i in range(m): for j in range(n): if grid[i][j] == 1 and (row[i] > 1 or col[j] > 1): res += 1 return res if __name__ == '__main__': grid = [[1, 0], [0, 1]] print(Solution().countServers(grid))
false
c2bc4d78568aadf371ab4830a2e9e08080135591
yiming1012/MyLeetCode
/LeetCode/并查集/547. 朋友圈.py
2,204
4.21875
4
""" 班上有 N 名学生。其中有些人是朋友,有些则不是。他们的友谊具有是传递性。如果已知 A 是 B 的朋友,B 是 C 的朋友,那么我们可以认为 A 也是 C 的朋友。所谓的朋友圈,是指所有朋友的集合。 给定一个 N * N 的矩阵 M,表示班级中学生之间的朋友关系。如果M[i][j] = 1,表示已知第 i 个和 j 个学生互为朋友关系,否则为不知道。你必须输出所有学生中的已知的朋友圈总数。 示例 1: 输入: [[1,1,0], [1,1,0], [0,0,1]] 输出: 2 说明:已知学生0和学生1互为朋友,他们在一个朋友圈。 第2个学生自己在一个朋友圈。所以返回2。 示例 2: 输入: [[1,1,0], [1,1,1], [0,1,1]] 输出: 1 说明:已知学生0和学生1互为朋友,学生1和学生2互为朋友,所以学生0和学生2也是朋友,所以他们三个在一个朋友圈,返回1。 注意: N 在[1,200]的范围内。 对于所有学生,有M[i][i] = 1。 如果有M[i][j] = 1,则有M[j][i] = 1。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/friend-circles 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solution: def findCircleNum(self, M: List[List[int]]) -> int: """ 思路:并查集 1. 首先让每个个体的父节点指向自己,朋友圈个数为N 2. 朋友圈存在连通性,每个个体指向一个根节点 3. 如果两个人可以联通,N-=1 """ res = n = len(M) parent = {i: i for i in range(n)} def union_find(x): if x != parent[x]: parent[x] = union_find(parent[x]) return parent[x] for i in range(n): for j in range(i): if M[i][j]: a = union_find(parent[i]) b = union_find(parent[j]) if a != b: parent[a] = b res -= 1 return res if __name__ == '__main__': M = [[1, 1, 0], [1, 1, 0], [0, 0, 1]] print(Solution().findCircleNum(M))
false
3d9a4fa16551d9863e59c4f1b1e980c4b2943ae9
yiming1012/MyLeetCode
/LeetCode/树(Binary Tree)/653. 两数之和 IV - 输入 BST.py
1,757
4.15625
4
""" 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。 案例 1: 输入: 5 / \ 3 6 / \ \ 2 4 7 Target = 9 输出: True   案例 2: 输入: 5 / \ 3 6 / \ \ 2 4 7 Target = 28 输出: False 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum-iv-input-is-a-bst 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def findTarget1(self, root: TreeNode, k: int) -> bool: """ 思路:回溯+剪枝 """ def recur(root, k, hashset): if not root: return False target = k - root.val if target in hashset: return True else: hashset.add(root.val) return recur(root.left, k, hashset) or recur(root.right, k, hashset) hashset = set() return recur(root, k, hashset) def findTarget2(self, root: TreeNode, k: int) -> bool: """ 思路:通过flag来标记是否已找到 """ if not root: return [] dic = set() flag = False def inorder(root): if root: inorder(root.left) if k - root.val in dic: nonlocal flag flag = True return dic.add(root.val) inorder(root.right) inorder(root) return flag
false
313d594302ee78ed6154d46cc8fa80c25493c2c6
Kristianmartinw/8-30-reference
/number.py
695
4.25
4
# Integers, no decimal print(3) print(int()) print(int(3)) print(int(3.0)) # Type casted (conversion from one type to another) # Floating Point Number, has decimal print(4.0) print(float()) print(float(4.0)) print(float(4)) # Type casted (conversion from one type to another) # Type casting to string print(str(7.0) + ' and ' + str(17)) # print(7.0 + ' and ' + 7) Will result in TypeError print(1+1) print(2-1) print(2*2) print(4/2) # Division always results in a float print(10 % 3) # Modulo returns the remaining number print(10//3) # Integer Division returns the amount of times a number fits in divison print(2**4) # Exponent multiplies number 1 by itself number 2 amount of times
true
27fcf9b9c7d1fc17e56c38c757362da24ffef957
shermanbell/CTI110
/M6HW2_Bell.py
2,373
4.21875
4
#Sherman_Bell #CTI_110 #M6HW2_Random Number Guessing Game #9_Nov_2017 # Write a program that does the following # Gernerate a random number in the range of 1 through 100. ( We'll call this "secret number") # Ask the user to guess what the secret number is # If the user's guess the higher thatn the secret number, the program shold tell the user "Too hig, try again" # If the user's guess is lower than the secret number, the program should tell the user " Too low, try again" # If the user guesses the number correctly, the program should congratulate the use! Writer whatever message you think is appropriate for the case. # The program should then ask the user Play again? (y for yes) and (n for no). # If the user enters"y", then the program should generate a new random number and start the game over again. #You shold, at the minimum, use a main() function # you might use two methods structure the program, for example main() and play_ game() # Exta Credit # Have the game keep track of the number of guesse the user makes,. When they guess correctly, tell the user how many guesses they used. # You might also decide that user only gets X number of guesses per game, and the game ends in a loss if they use all guesses before they guess the number. # You will need to test for yourself and decide what a far value for X wold be import random def genRandomNumber(): randomNumber = random.randint( 1, 100 ) return randomNumber def askUserForNumber( message = "Guess the number: "): userNumber = int( input( message) ) return userNumber def checkUserNumber( userNumber, randomNumber ) : if userNumber < randomNumber: return "Too Low , you have" elif userNumber > randomNumber : return " Too High" else: return " Congratulations you did it" def main () : userCongratulated = False letsStart = True while userCongratulated or letsStart: randomNumber = generateRandomNumber () userNumber = askUserForNumber () message = checkUserNumber ( userNumber , randomNumber ) while message != " Congratulations you did it": print( message ) userNumber = askUserForNumber( " Try again") message = checkUserNumber( userNumber, randNumber ) print( message ) userCongratulated = True main()
true
76fb1e4b9fdeccb59405863d1f8f3d7cc1cf0193
akudalek/short
/4/4.py
2,164
4.28125
4
""" Я предположил, что если задание из модуля “Цикл while”, то в коде напрашивается использование этого оператора. Как мне видится, для того чтобы выводить данные о кол-ве месяцев в бесконечном цикле. Если это так, напомнить ученику об этом и попросить дополнить код. В целом код рабочий, но можно в качестве предисловия к патерннам программирования расказать про философию Python: - Простое лучше сложного - Читаемость имеет значение и т.д. """ user_input = input("Введите, пожалуйста, номер месяца: ") month = int(user_input) # Обработчик ошибок print('Вы ввели', month) # проверку валидности данных делать сразу if month not in range(1, 13): # Люблю эту конструкцию :) print('Такого месяца нет') exit(0) # можно использовать list, slice или dict для хранения # кол-ва дней в месяце # и для получения необходимого рез-та по индексу "№мес-1" months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] print(f"Дней = {months[month - 1]}") # Просто люблю f строки :) """ В коде ошибка при подсчете стоимости аренды жилья d += exp - ed exp *= 1.03 строчки надо поменять местами Я бы предложил бы еще посмотреть вариант ниже Для меня он меньше и более понятный (О великий, Гвидо ван Россум!) 4 строк против 9 """ ed, exp, d = 10000, 12000, 0 for i in range(10): d += exp * pow(1.03, i) - ed print(f'Студенту надо попросить{round(d, 2)}рублей.') # Просто люблю f строки :)
false
05543281d6fad233f401393a66d0c1dcd63eddb6
afl0w/pythonNotes
/Activity-E.py
319
4.40625
4
#user input for the lengths of three sides of a triangle. print("Enter the lengths of the three triangle sides: ") x = int(input("x: ")) y = int(input("y: ")) z = int(input("z: ")) #if else statement if x == y == z: print("This is a Equilateral triangle") else: print("This is not a Equilateral triangle")
true
a9212b9cb5d30f782628cb570ef646c199ddbbe9
JunctionChao/python_trick
/ContextManger/3_属性私有化.py
964
4.5
4
""" python 通过下划线的命名规范来控制属性的访问 _单下划线开头:弱“内部使用”标识,如:from M import *,将不导入所有以下划线开头的对象,包括包、模块、成员 __双下划线开头双下划线结尾__:指那些包含在用户无法控制的命名空间中的“魔术”对象或属性,如类成员的__name__ 、__doc__、__init__、__import__、__file__、等。推荐永远不要将这样的命名方式应用于自己的变量或函数 __双下划线开头:模块内的成员,表示私有成员,外部无法直接调用 单下划线结尾_:只是为了避免与python关键字的命名冲突 """ class A: def __init__(self, x): self.__x = x if __name__ == '__main__': a = A(3) # print(a.__x) # AttributeError: 'A' object has no attribute '__x' # 其实系统内部进行了命名重整,可以在属性名前加下划线和类名称 _class print(a._A__x) # 3
false
a2262ddc8021d0e5b0669bac14cd3385627b49a6
nikhilchowdarykanneganti/python_by_example_-NICHOLA-LACEY-
/the basics/c6.py
329
4.34375
4
#Challenge6 '''Ask how many slices of pizza the user started with and ask how many slices they have eaten. Work out how many slices they have left and display the answer in a user- friendly format.''' print('you are left with',int(input('How many slices of pizza have you ordered\n'))-int(input('How many slices u ate\n')),'.')
true
76b7e9ec61e55aa043ca62db1871d7adb6e8534b
SuyogKhanal5/PythonNotes
/reg_expressions_three.py
945
4.40625
4
import re print(re.search(r'cat|dog','The cat is here')) # Use the pipe operator to see if you have cat or dog print(re.findall(r'.at', 'The cat in the hat sat')) # . is the wild card operator, so use it if you dont know one of the letters print(re.findall(r'...at', 'The cat in the hat went splat')) print(re.findall(r'^\d', '1 is a number' )) # ^ is used to see if the string starts with something print(re.findall(r'\d$', 'The number is 2' )) # $ is used to see if the string ends with something phrase = 'There are 3 numbers 34 inside 5 this sentence' pattern = r'[^\d]' # Use [^ID] to exclude something based on one of your identifiers print(re.findall(pattern, phrase)) pattern = r'[^\d]+' # The + makes it all print on one line print(re.findall(pattern, phrase)) text = 'Only find the hypen-words in this sentence, but you do not know how long-ish each one is' pattern = r'[\w]+-[\w]+' re.findall(pattern, text)
true
048daa5772e37fb3b19814ef57797a323707cdc6
Simran-kshatriya/Basic
/PythonBasics2.py
534
4.15625
4
if 5 > 3: print(" 5 is grater than 3") num = 0 if num > 0: print("This is a positive number") elif num == 0: print("Number is zero") else: print("This is a negative number") num1 = [1, 2, 3, 4, 5] sum = 0 for val in num1: sum +=val print("Total is ", sum) languages = ["Python", "Java","Ruby","PHP"] for val in languages: print(val) else: print("No Languages left ") print("Enter a number:") num2 = int(input()) sum1 = 0 i = 1 while i < num2: sum1 = sum1 +i i = i + 1 print("Total is :", sum1)
true
56fd69c6c693926b9161939ac1e8b69a2cf85cc2
JaeGyu/PythonEx_1
/20161221_1.py
1,048
4.25
4
#_*_ coding: UTF-8 _*_ import csv def read_data(): file = open('data.csv') reader = csv.reader(file) rows = [row[1:] for row in reader][1:] file.close() print(rows) return [float(row[0]) for row in rows],[float(row[1]) for row in rows] def read_data2(): with open("data.csv") as file: reader = csv.reader(file) rows = [row[1:] for row in reader][1:] print("출력 합니다.") print(rows) def read_data3(): with open("data.csv") as file: reader = csv.reader(file) '''for row in reader: continue print(row)''' rows = [row[1:] for row in reader][1:] print("rows :: ") print(rows) def list_test(): list = [[1,2],[3,4],[5,6]] print("before :: ",list) print([row for row in list]) print([row[1:] for row in list]) print(list[1:][1:]) def main(): print("main 입니다.") #print(read_data()) #print(read_data2()) #read_data3() list_test() if __name__ == '__main__': main()
false
614c48c004a052e42dcdd0f9d35fb7a49842f37d
sarahcenteno/chatServer
/server.py
2,768
4.125
4
#!/usr/bin/env python import socket host = '' port = 5713 # Creates TCP socket serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverSocket.bind((host, port)) # server connects to given host and port serverSocket.listen(2) # server listens for incoming TCP requests print("Server started") print("Waiting for client request...") conn, addr = serverSocket.accept() # server will accept new request print("Connection from: " + str(addr)) # prints connected IP address while True: # loops until Thank you. message and then breaks and ends program message = conn.recv(1024).decode() # decode message received from client print("From Client: " + str(message)) # prints message from client # if client sends any of the following messages, the server will send back # an encoded pre-determined message to the client and prints what it will # be sending to the client if message == "What is your name?": conn.send("My name is Sarah Centeno.".encode()) print("Sending: My name is Sarah Centeno.") elif message == "What course is this project for?": conn.send("This project is for CNT4704, Fall 2019.".encode()) print("Sending: This project is for CNT4704, Fall 2019.") elif message == "How many programming assignments do we have?": conn.send("I think there are two.".encode()) print("Sending: I think there are two.") elif message == "Do you think the second part is more challenging?": conn.send("Of course, the first part (socket programming) has been done for you.".encode()) print("Sending: Of course, the first part (socket programming) has been done for you.") elif message == "How do you know to respond to these questions?": conn.send("You programmed me, didn't you?".encode()) print("Sending: You programmed me, didn't you?") elif message == "Can I ask you a personal question?": conn.send("I don't think you'd like the answer.".encode()) print("Sending: I don't think you'd like the answer.") elif message == "Can you answer an arbitrary question?": conn.send("Yes, I can, but I won't".encode()) print("Sending: Yes, I can, but I won't.") elif message == "Thank you.": conn.send("You are welcome. Have a nice day!".encode()) print("Sending: You are welcome. Have a nice day!") print("Closing connection now...") break else: conn.send("I do not understand your question. Please re-enter your question.".encode()) print("Sending: I do not understand your question. Please re-enter your question.") if not message: # if message was not received, then it will break away from program break conn.close() # closes the connection
true
573535f4084cee4bed4787ccabf7a2d4de6d75e7
linshiu/python
/data_structures_algorithms/problem_solving_data_structures_algorithms/chap02_analysis/anagram.py
1,883
4.25
4
# -*- coding: utf-8 -*- """ Problem Solving with Data Structures and Algorithms, Brad Miller Chapter 2 - Analysis Anagram IDE: Spyder, Python 3 A good example problem for showing algorithms with different orders of magnitude is the classic anagram detection problem for strings. One string is an anagram of another if the second is simply a rearrangement of the first. For example, 'heart' and 'earth' are anagrams. The strings 'python' and 'typhon' are anagrams as well. For the sake of simplicity, we will assume that the two strings in question are of equal length and that they are made up of symbols from the set of 26 lowercase alphabetic characters. Our goal is to write a boolean function that will take two strings and return whether they are anagrams (Miller) """ #%% My Solution import matplotlib.pyplot as plt import random import time def getFrequency(word): """ Get frequency of letter in word Args: word (string): string of word Returns: dic: {key: letter from alphabet, value: count in word} """ alphabet = [chr(i) for i in range(97,97+26)] freqDic = {key: value for (key, value) in zip(alphabet,[0]*len(alphabet))} for letter in word: freqDic[letter]+=1 return freqDic def checkAnagram(word1,word2): """ Check if two words are anagrams Args: word1 (string): first word word2 (string): second word Returns: boolean: True if anagrams, False otherwise """ alphabet = [chr(i) for i in range(97,97+26)] if len(word1)!=len(word2): return False word1Dic = getFrequency(word1) word2Dic = getFrequency(word2) for letter in alphabet: if word1Dic[letter] != word2Dic[letter]: return False return True #%% test print(checkAnagram('apple','pleap'))
true
414e0568c3840e44c3b1b2fd7728c613f1a26c1d
linshiu/python
/data_structures_algorithms/problem_solving_data_structures_algorithms/chap04_recursion/reverseList.py
776
4.125
4
# -*- coding: utf-8 -*- """ Problem Solving with Algorithms and Data Structures, Brad Miller Chapter 4: Recursion IDE: Spyder, Python 3 Reverse a list """ #%% Function ################################################################# def reverseList(ls): """ Reverse a list base: Args: ls (list): list to reverse Regturns: list: reversed list """ if len(ls) <= 1: return ls else: return reverseList(ls[1:]) + [ls[0]] #%% Testl ################################################################# def test(): testList = [0,1,2,3,4] rev = reverseList(testList) testList.reverse() assert rev == testList print("Test: Success") if __name__ == "__main__": test()
true
39d9a59d7e31ec327248ca7d8675066ffbacb494
linshiu/python
/data_structures_algorithms/problem_solving_data_structures_algorithms/chap05_searching_sorting/bubbleSort.py
2,739
4.15625
4
# -*- coding: utf-8 -*- """ Problem Solving with Algorithms and Data Structures, Brad Miller Chapter 5: Searching and Sorting IDE: Spyder, Python 3 Bubble Sort """ import timeit import matplotlib.pyplot as plt import numpy.random as nprnd import numpy as np #%% Function ################################################################# def bubbleSort(ls): """ Sort a list using bubble sort Make passes through the list until list is sorted. During each pass, make comparisons between consecutive items and excahnge if out of order, so that items "bubble up" to the top of the list. So for the next pass, one fewer comparison (last) has to be made compared to the previous pass because sorted values are at the top. Stop until n-1 passes are done, or no exchanges were made during a pass Args: ls (list): list to sort Returns: None: modifies the list """ n = len(ls) i = 0 swap = True # passes (up to n-1) and whenever no swaps made in an iteration while i < n-1 and swap: swap = False # reset swaps # comparisons (up to n-1 for pass 0, n-2 for pass 1.. etc) for j in range(n-1-i): # swaps if ls[j] > ls[j+1]: ls[j], ls[j+1] = ls[j+1], ls[j] swap = True i+=1 #%% Testl ################################################################# def test(): """ Test if functions are working properly by using assertions Args: None Returns: None: will print Test: Success if everything ok, otherwise assertion error """ testList1 = [54,26,93,17,77,31,44,55,20] testList2 = [54,26,93,17,77,31,44,55,20] bubbleSort(testList1) testList2.sort() assert testList1 == testList2 print("Test: Success") if __name__ == "__main__": test() func= [bubbleSort] times = {f.__name__: [] for f in func} for f in times: for n in range(5): size = 5**(n+1) item = nprnd.randint(size*3, size = size) testList = nprnd.randint(low=0, high = size, size = size) t = timeit.Timer("{f}(testList)".format(f=f), "from __main__ import {f}, testList".format(f=f)) times[f].append((size, t.timeit(number=1000))) x,y = zip(*times[f]) plt.plot(x,y,'.-', c=np.random.rand(3,1)) plt.legend([f.__name__ for f in func], loc='upper left') plt.ylabel('miliseconds') plt.xlabel('size') plt.show()
true
fced4355855688f19276d43d5b11bbaca98ade02
linshiu/python
/think_python/10_03_cum_sum.py
456
4.25
4
def cum_sum(t): ''' Write a function that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i + 1 elements from the original list. For example, the cumulative sum of [1, 2, 3] is [1, 3, 6].''' total = 0 cum_list = [] for i in t: total += i cum_list.append(total) return cum_list print cum_sum([1,2,3])
true
243b8db5be415551b8664270bfa8e96e124a4c2f
Seariell/basics-of-python
/hw4/task_1.py
1,170
4.28125
4
# homework lesson: 4, task: 1 """ Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. В расчете необходимо использовать формулу: (выработка в часах*ставка в час) + премия. Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами. """ from sys import argv def salary(hours: float, rate: float) -> tuple: """ Расчет зарплаты :param hours: flat :param rate: float :return: tuple """ result = hours * rate premium = result * 0.1 return result, premium try: my_hours = float(argv[1]) my_rate = float(argv[2]) my_salary, my_premium = salary(my_hours, my_rate) print(f'Ваша зарплата составила: {my_salary + my_premium} руб. Включая премию в размере {my_premium} руб.') except ValueError: print('Ошибка: неверный формат')
false
0e108d3f3cd9b3038653d6465363728ffc73f2ae
PrasamsaNeelam/CSPP1
/cspp1-practice/m9/Odd Tuples Exercise/odd_tuples.py
439
4.28125
4
#Exercise : Odd Tuples ''' Author: Prasamsa Date: 8 august 2018 ''' def odd_tuples(a_tup): ''' aTup: a tuple returns: tuple, every other element of aTup. ''' return a_tup[::2] def main(): '''input a tuple''' data = input() data = data.split() a_tup = () l_len = len(data) for j in range(l_len): a_tup += (data[j],) print(odd_tuples(a_tup)) if __name__ == "__main__": main()
false
a90a75e5f3b0efcf58f5c990ed4fd55f21849599
PrasamsaNeelam/CSPP1
/cspp1-practice/cspp1-assignments/m6/p2/special_char.py
399
4.15625
4
''' Author: Prasamsa Date: 4 august 2018 ''' def main(): ''' Read string from the input, store it in variable str_input. ''' str_input = input() char_input = '' for char_input in str_input: if char_input in('!', '@', '#', '$', '%', '^', '&', '*'): str_input = str_input.replace(char_input, " ") print(str_input) if __name__ == "__main__": main()
true
0c7c2f31713898a2ec1381e38c662fcb3ad74b34
davidgoldcode/cs-guided-project-problem-solving
/src/demonstration_09.py
1,071
4.25
4
""" Challenge #9: Given a string, write a function that returns the "middle" character of the word. If the word has an odd length, return the single middle character. If the word has an even length, return the middle two characters. Examples: - get_middle("test") -> "es" - get_middle("testing") -> "t" - get_middle("middle") -> "dd" - get_middle("A") -> "A" """ def is_even(n: int) -> bool: # use the % modulo operator to determine if even or odd return n % 2 == 0 def get_middle(input_str): # Your code here # how do we determine lenght of string is even or odd # figure out how to get char or chars # return the single middle char if the lenght of string is odd # return 2 middle chars if length is even length = len(input_str) midpoint = length//2 if length <= 2: return input_str elif is_even(length): return input_str[midpoint - 1:midpoint + 1] else: return input_str[midpoint] print(get_middle("test")) print(get_middle("testing")) print(get_middle("middle")) print(get_middle("A"))
true
693558f4371fc3aa9d3deff7e0aa8aaefe389b24
natkam/adventofcode
/2017/aoc_05_jumps_1.py
2,014
4.46875
4
""" The message includes a list of the offsets for each jump. Jumps are relative: -1 moves to the previous instruction, and 2 skips the next one. Start at the first instruction in the list. The goal is to follow the jumps until one leads outside the list. In addition, these instructions are a little strange; after each jump, the offset of that instruction increases by 1. So, if you come across an offset of 3, you would move three instructions forward, but change it to a 4 for the next time it is encountered. For example, consider the following list of jump offsets: 0 3 0 1 -3 Positive jumps ("forward") move downward; negative jumps move upward. For legibility in this example, these offset values will be written all on one line, with the current instruction marked in parentheses. The following steps would be taken before an exit is found: (0) 3 0 1 -3 - before we have taken any steps. (1) 3 0 1 -3 - jump with offset 0 (that is, don't jump at all). Fortunately, the instruction is then incremented to 1. 2 (3) 0 1 -3 - step forward because of the instruction we just modified. The first instruction is incremented again, now to 2. 2 4 0 1 (-3) - jump all the way to the end; leave a 4 behind. 2 (4) 0 1 -2 - go back to where we just were; increment -3 to -2. 2 5 0 1 -2 - jump 4 steps forward, escaping the maze. In this example, the exit is reached in 5 steps. How many steps does it take to reach the exit? """ with open('05_input.txt', 'r') as f: data = f.read() offsets = [int(offset) for offset in data.splitlines()] def jump(offsets): position = 0 jump_count = 0 while True: try: jump_len = offsets[position] offsets[position] += 1 position += jump_len jump_count += 1 if position < 0: raise IndexError except IndexError as e: return jump_count print(jump(offsets))
true
b9eb9cc86ccd65bba04bfce054c8238362992270
natkam/adventofcode
/2017/aoc_02_checksum1.py
1,908
4.3125
4
""" The spreadsheet consists of rows of apparently-random numbers. To make sure the recovery process is on the right track, they need you to calculate the spreadsheet's checksum. For each row, determine the difference between the largest value and the smallest value; the checksum is the sum of all of these differences. For example, given the following spreadsheet: 5 1 9 5 7 5 3 2 4 6 8 The first row's largest and smallest values are 9 and 1, and their difference is 8. The second row's largest and smallest values are 7 and 3, and their difference is 4. The third row's difference is 6. In this example, the spreadsheet's checksum would be 8 + 4 + 6 = 18. What is the checksum for the spreadsheet in your puzzle input? """ def calculate_checksum(spreadsheet): int_array = make_int_array(spreadsheet) checksum = 0 for row in int_array: row.sort() checksum += row[-1] - row[0] return checksum def make_int_array(spreadsheet): rows = spreadsheet.splitlines() str_array = [] for row in rows: int_list_from_row = [int(item) for item in row.split()] str_array.append(int_list_from_row) return str_array def test_calculate_checksum(test_spreadsheet, expected_checksum): actual_checksum = calculate_checksum(test_spreadsheet) assert actual_checksum == expected_checksum, "actual_checksum = " + str(actual_checksum) test_spreadsheet1 = '5 1 9 5\n' + '7 5 3\n' + '2 4 6 8' test_calculate_checksum(test_spreadsheet1, 18) test_spreadsheet2 = '5 5 5 5\n' + '7\n' + '-1 1' test_calculate_checksum(test_spreadsheet2, 2) # Note that I/O methods such as readline() or readlines() leave whitespaces # (\t, \n) in the returned strings, so they are not satisfactory for spliting # the input into rows. with open('02_input.txt', 'r') as file_in: input_spreadsheet = file_in.read() print(calculate_checksum(input_spreadsheet))
true
ff451d9981296e73a3c71ed09a8605cb4b6dd9ed
fox-flex/lb7_2sem_op
/example/point_1.py
1,494
4.34375
4
from math import pi, sin, cos, radians class Point: 'Represents a point in two-dimensional geometric coordinates' def __init__(self, x=0, y=0): '''Initialize the position of a new point. The x and y coordinates can be specified. If they are not, the point defaults to the origin.''' self.move(x, y) def __str__(self): return '({0}, {1})'.format(self.x, self.y) def __eq__(self, other): if isinstance(other, self.__class__): return (self.x == other.x) and (self.y == other.y) else: return NotImplemented # False def __ne__(self, other): if isinstance(other, self.__class__): return (self.x != other.x) or (self.y != other.y) else: return NotImplemented # False def move(self, x, y): "Move the point to a new location in 2D space." self.x = float(x) self.y = float(y) def rotate(self, beta, other_point): 'Rotate point around other point' dx = self.x - other_point.get_xposition() dy = self.y - other_point.get_yposition() xpoint3 = dx * cos(beta) - dx * sin(beta) ypoint3 = dy * cos(beta) + dy * sin(beta) xpoint3 = xpoint3 + other_point.get_xposition() ypoint3 = ypoint3 + other_point.get_yposition() return self.move(xpoint3, ypoint3) def get_xposition(self): return self.x def get_yposition(self): return self.y
true
022aa7c9028a366b991567693d5be0c0ae2ed08d
DarinZhang/lpthw
/ex31/ex31.py
1,346
4.15625
4
# -*- coding: utf-8 -*- def break_words(sentence): words = sentence.split(' ') return words #sentence = "You are beautiful!" #print break_words(sentence) #print type(break_words(sentence)) print "You enter a dark room with two doors. Do you go through door #1 or door #2?" door = raw_input("> ") if door == "1": print "There's a giant bear here eating a cheese cake. What do you do?" print "1. Take the cake." print "2. Scream at the bear." bear = raw_input("> ") if bear == "1": print "The bear eats your face off. Good job!" elif bear == "2": print "The bear eats your legs off. Good job!" else: print "Well, enter the safe behavior do you think." behavior = raw_input("> ") if "run away" in behavior: print "Good job! That is right to run away!" else: print "Well, doing %s is probably better. Bear run away." % bear elif door == "2": print "You stare into the endless abyss at Cthulhu's retina." print "1. Blueberries." print "2. Yellow jacket clothespins." print "3. Understanding revolvers yelling melodies." insanity = raw_input("> ") if insanity == "1" or insanity == "2": print "Your body survives powered by a mind of jello. Good job!" else: print "The insanity rots your eyes into a pool of muck. Good job!" else: print "You stumble around and fall on a knife and die. Good job!"
true
acb041f6f6ef7016b60015882784cbb91bf4f5bf
sruthy-github/sruthy-python-files
/flow control/maximum 3 numbers.py
235
4.25
4
num1=int(input("Enter number1")) num2=int(input("Enter number2")) num3=int(input("Enter number3")) if(num1<num2,num3): print(num1,"is highest") elif(num2<num1,num3): print(num2,"is highest") else: print(num3,"is highest")
false
a458570e869d9d8d3205053ea2587d07089afaca
jddelia/think-python
/Section15/rect_in_circle.py
671
4.5
4
# This program creates a circle with OOP. from math import sqrt class Point: def __init__(self, x, y): self.x = x self.y = y class Circle: def __init__(self, center, radius): self.center = center self.radius = radius class Rectangle: def __init__(self, corner, height, width): self.corner = corner self.height = height self.width = width center_1 = Point(150, 100) circle_1 = Circle(center_1, 75) corner_1 = Point(100, 100) rect_1 = Rectangle(corner_1, 25, 50) def rect_in_circle(rect, circle): distance = sqrt(abs(corner_1.x - circle.center.x)**2 + abs(corner_1.y - circle.center.y)**2)
true
fe9b543b362b50a9491d74451d7fae5b27939e92
seunjeong/pykds
/pykids/class_2.py
2,518
4.3125
4
################################################################################ # More on String ################################################################################ my_name = 'Seongeun' my_age = 46 # Two different ways of print things print ('My name is: ' + my_name) print ('My name is {}'.format (my_name)) # With age print ('My name is {}, and my age is {}'.format (my_name, my_age)) ################################################################################ # List # - definition: A list is a data structure in Python that is ordered sequence of elements. Each element (or value) that is inside of a list is called an item. ################################################################################ #=============================================================================== # Initiating list #=============================================================================== num_list = [1,2,3] # number mixed_list = [1,'a', 'b', 2] # Play with a shopping list shopping_list = ['banana', 'yogurt', 'milk', 'meat', 'peach', 'chips', 'chocolate', 'tomato', 'toothpaste'] for i in range (len(shopping_list)): print (i) # i is called index print (shopping_list [i]) # empty list a_list = [] # add to the empty list a_list.append (1) print ('Now a_list is {}'.format(a_list)) # add more a_list.append ('a') print ('Now a_list is {}'.format(a_list)) #=============================================================================== # Create a longer list and print its item. #=============================================================================== # Adding more long_list = [] items = range (10) for i in items: long_list.append (i) # by now, long_list is full of 10 values. # now let's see it for this_item in long_list: print (this_item) ################################################################################ # Dictionary # - defintion: Dictionaries are Python’s data structure, and a dictionary consists of a collection of key-value pairs. ################################################################################ # Declare a dictionary avengers = {'movie_name': 'Iron Man', 'year':2008} print ('Release year of Iron Man: {}'.format (avengers['year'])) ################################################################################ # "for" loop ################################################################################ for name, year in avengers.items(): #print (name) print ('{}; {}'.format(name, year))
true
cc1a90064133b00c617934fb421fa56f010b4b45
longroad41377/variables
/divmod.py
441
4.125
4
try: number1 = int(input("Enter number 1: ")) number2 = int(input("Enter number 2: ")) div = number1 // number2 mod = number1 % number2 print("The integer result of the division is {}".format(div)) print("The remainder of the division is {}".format(mod)) except ValueError: print("The numbers need to be integers") except ZeroDivisionError: print("The second number cannot be 0")
true
3b4d595cb330cf983825957c1ac535cef82c7668
HakiimJ/python-bootcamp
/pre-session/basic_calculations.py
767
4.21875
4
pi = 3.14 # global constant #advanced way to set globals is given here: https://www.programiz.com/python-programming/variables-constants-literals def area_circle(radius): area = pi * radius * radius return area def volume_sphere(radius): return 0 def volume_cylinder(radius, height): area = area_circle (radius) volume = area * height return volume, area #---------------------------------- # now we call the above functions #ask the user (exercise) print('Radius?') radius = float(input()) area = area_circle (radius) print(area, 'is the area in square meters') print('Height?') height = float(input()) vol, ar = volume_cylinder (radius, height) print(vol, 'is the volume in cubic meters') print(area, 'is the area of the top of the cylinder')
true
596c2e7245265d4977774f9e6b6c11c0b3736612
VLevski/Programming0-1
/week3/4-Problems-Construction/int_functions.py
1,310
4.1875
4
def reverse_int(n): reverse_numbers = [] reverse_number = 0 while n != 0: reverse_numbers += [n % 10] n //= 10 for number in reverse_numbers: reverse_number = reverse_number * 10 + number return reverse_number def sum_digits(n): numbers = [] sum_numbers = 0 while n != 0: numbers += [n % 10] n //= 10 for number in numbers: sum_numbers += number return sum_numbers def product_digits(n): numbers = [] product_numbers = 1 while n != 0: numbers += [n % 10] n //= 10 for number in numbers: product_numbers *= number return product_numbers def digits(n, operand): numbers = [] sum_numbers = 0 product_numbers = 1 while n != 0: numbers += [n % 10] n //= 10 if operand: for number in numbers: sum_numbers += number return sum_numbers else: for number in numbers: product_numbers *= number return product_numbers if __name__ == "__main__": n = input("Enter a number: ") n = int(n) print("Reverset number is:", reverse_int(n)) print("Sum of number's digits is:", digits(n, 1)) print("Product of number's digits is:", digits(n, 0))
false
023519deca4c47c8d426dc5cad7ebf464cc4a4de
VLevski/Programming0-1
/week1/3-And-Or-Not-In-Problems/simple_answers.py
1,215
4.125
4
say = input("Say what you have to say: ") answer = "@" if "hello" in say: answer = answer + "H" if "how are you?" in say: answer = answer + "h" if "feelings" in say: answer = answer + "F" if "age" in say: answer = answer + "A" H = "Hello there, good stranger! " h = "I am fine, thanks for asking! How are you? " F = "Because I'm a machine I have no feelings " A = "I've no age - only current time-stamp " # Truth table: # H h F A #--------------------------------- # 0 0 0 0 # 0 0 0 1 # 0 0 1 0 # 0 0 1 1 # 0 1 0 0 # 0 1 0 1 # 0 1 1 0 # 0 1 1 1 # 1 0 0 0 # 1 0 0 1 # 1 0 1 0 # 1 0 1 1 # 1 1 0 0 # 1 1 0 1 # 1 1 1 0 # 1 1 1 1 if answer == "@HhFA": print(H + h + F + A) elif answer == "@HhF": print(H + h + F) elif answer == "@HhA": print (H + h + A) elif answer == "@Hh": print(H + h) elif answer == "@HFA": print(H + F + A) elif answer == "@HF": print(H + F) elif answer == "@HA": print(H + A) elif answer == "@H": print(H) elif answer == "@hFA": print(h + F + A) elif answer == "@hF": print(h + F) elif answer == "@hA": print(h + A) elif answer == "@h": print(h) elif answer == "@FA": print(F + A) elif answer == "@F": print(F) elif answer == "@A": print(A) else: print("What you meen?")
false
93c6d65644d19659bb0b118235ab632eeb8d1d2b
salehsami/100-Days-of-Python
/Day 3 - Control Flow and Logical Operators/Roller_Coaster_Ticket.py
717
4.15625
4
# Roller coaster Ticket print("WWelcome to the RollerCoaster") height = int(input("Enter your height in cm: ")) bill = 0 if height >= 120: print("You can ride the Roller Coaster") age = int(input("What is your age: ")) if age < 12: print("Your Ticket will be $5") bill += 5 elif 12 <= age <= 18: print("Your Ticket will be $7") bill += 7 else: print("Your Ticket will be $12") bill += 12 photos = input("You want photos yes or no: ") if photos == "yes": print("photos ticket will be $3") bill += 3 print(f"Your total Ticket is ${bill} ") else: print("You can't ride the Roller Coaster")
true
cd83e291a5f957ea7f201ae33d6f269f14644135
salehsami/100-Days-of-Python
/Day 10 - Beginner - Functions with Outputs/output_functions.py
254
4.21875
4
first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") def format_name(f_name, l_name): first = f_name.title() last = l_name.title() return f"{first} {last}" print(format_name(first_name, last_name))
true
47759d97ecce73c812888b02765a374685273cb8
GauravPadawe/1-Player-Rock-Paper-Scissors
/Game.py
2,642
4.28125
4
import sys # Importing required packages import random import time def game(user, choice): # Defining a function which will accept 2 inputs from user as (user, choice) choice = str(input(user + ", What's your choice?: ")) # Choice will accept value Rock/ Paper/ Scissors opt = ["Rock", "Paper", "Scissors"] # opt is a list of values bot = random.choice(opt) # bot will contain random values from opt time.sleep(1) # Delayed output by 1 second if choice == "Rock" and bot == "Scissors": # If else statements nested within print (user + ", you WON !! as bot chose scissors") elif choice == "Rock" and bot == "Paper": print (user + ", you LOSE !! as bot chose paper") elif choice == "Paper" and bot == "Scissors": print (user + ", you LOSE !! as bot chose scissors") elif choice == "Paper" and bot == "Rock": print (user + ", you WON !! as bot chose rock") elif choice == "Scissors" and bot == "Paper": print (user + ", you WON !! as bot chose paper") elif choice == "Scissors" and bot == "Rock": print (user + ", you LOSE !! as bot chose rock") elif choice == bot: print ("It's a TIE !!") elif choice not in opt: # if choice of user is not in opt then return invalid input print ("Oh NO !! Invalid input. Choose only from <Rock/Paper/Scissors>") def start(): # Defining a function start to make game little more interactive while True: user = str(input("What's your name?: ")) # User's name will be contained here choice = "" # Passing choice empty print (game(user, choice)) # game() will run in this block while True: # While loop so user will be propted to play again x = input(user + " , Do you want to play again ? Type Y/N: ") # Accepting value from user as Yes/No if x == "Y": # if value is Y restart the game with same user print (game(user, choice)) elif x == "N": # if value is N then exit the game print ("Goodbye " + user) sys.exit() else: # if user passes value other than Y/N prompt him with Invalid Input print ("Invalid Input") print (start()) # Run the Game # CODED BY - GAURAV PADAWE
true
d449b9cc2aeedf6e3c4c05402012ac58bf68ef5a
sduffy826/FinchBot
/testMath.py
1,012
4.15625
4
import math def conversionTest(): degrees = input("Enter degrees: ") print("{degrees:d} converted to radians is {radians:.2f}".format(degrees=degrees,radians=math.radians(degrees))) radians = input("Enter radians: ") print("{radians:.2f} converted to degrees is: {degrees:.2f}".format(radians=radians,degrees=math.degrees(radians))) lastLocationX = 0 lastLocationY = 0 targetLocationX = 72 targetLocationY = 6 currentAngleInRadians = math.radians(45.0) velocityPerSecond = 2.0 numberOfSeconds = 0.0 secondInterval = .01 secondsToTravel = 1.0 while True: numberOfSeconds += secondInterval currentPositionX = velocityPerSecond * numberOfSeconds * math.cos(currentAngleInRadians) + lastLocationX currentPositionY = velocityPerSecond * numberOfSeconds * math.sin(currentAngleInRadians) + lastLocationY print("{seconds:.2f} seconds x: {x:.2f} y: {y:.2f}".format(seconds=numberOfSeconds,x=currentPositionX,y=currentPositionY)) if (round(abs(numberOfSeconds-secondsToTravel),2) == 0): break
true
f1d629382312813dde2c6855af4f63bf21c4dcb7
YesimOguz/calculate-bill-python
/calculateBill.py
687
4.15625
4
# this is a program to calculate the total amount to be paid by customer in a restourant # get the price of the meal # ask the user to chose the type of tip to give(18%,20%,25%) # base on the tip calculate the total bill meal_cost = int(input('please enter the price of the meal: ' )) percentage_of_tip = input("""what tip percentage would you prefer a. 18% b. 20% c. 25% """ ) #meal_cost=2000(if we dont get it from user) if percentage_of_tip == 'a': tip = 0.18*meal_cost elif percentage_of_tip == 'b': tip = 0.2*meal_cost elif percentage_of_tip == 'c': tip = 0.25*meal_cost total_bill = meal_cost + tip print(f'the total cost of meal is {total_bill}')
true
34cb6e42eaf5504075f29b9e93eb09bdb89e9800
deShodhan/Algos
/w2pa5.py
868
4.3125
4
# Accept a string as input. Select a substring made up of three consecutive characters in the input string such that there are an equal number of characters to # the left and right of this substring. If the input string is of even length, make the string of odd length as below: • If the last character is a period ( . ), # then remove it • If the last character is not a period, then add a period ( . ) to the end of the string Print this substring as output. You can assume that all # input strings will be in lower case and will have a length of at least four. n=str(input()) if len(n)%2 is 0: print('even') if n[len(n)-1] == '.': n=n.replace(n[len(n)-1],'') print(n) c=int(len(n)/2) print(n[c-1:c+2]) else: n=n+'.' print(n) c=int(len(n)/2) print(n[c-1:c+2]) else: print('odd') c=int(len(n)/2) print(n[c-1:c+2])
true
d21eca2dcc25ea7d6fb521c53d3358ebef57e9c4
carlosgomes1/python-tests
/world-1/17-cateto-and-hypotenuse.py
391
4.46875
4
# Make a program that reads the length of the opposite cateto and the adjacent catheter of a # right triangle. Calculate and show the length of the hypotenuse. from math import hypot opposite = float(input('Length of opposite cateto: ')) adjacent = float(input('Length of adjacent cateto: ')) hypotenuse = hypot(opposite, adjacent) print(f'The hypotenuse will measure {hypotenuse:.2f}')
true
13e6bf1cafdc689897f61716751c132d5625cbe0
carlosgomes1/python-tests
/world-1/05-predecessor-and-successor.py
256
4.4375
4
# Make a program that receives an integer and shows on the screen its predecessor and successor. number = int(input('Enter an integer: ')) print( f'The number entered was {number}. The predecessor is {number - 1} and the successor is {number + 1}.')
true
9e71556d9191490662374993741a4b111715c9c9
carlosgomes1/python-tests
/world-1/19-sorting-item.py
494
4.1875
4
# A teacher wants to draw one of his four students to erase the board. # Make a program that helps him by reading the students' names and writing on the screen # the name of the chosen one. from random import choice student1 = input('First student: ') student2 = input('Second student: ') student3 = input('Third student: ') student4 = input('Fourth student: ') studentList = [student1, student2, student3, student4] chosen = choice(studentList) print(f'The student chosen was {chosen}')
true
1634bb33fbde3d6e7186019a6a09ed7c8b3afcc5
monchhichizzq/Leetcode
/Reverse_Integer.py
1,516
4.25
4
''' Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1] ([−214783648, 214783647]). For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. ''' class Solution: def reverse(self, x): ''' Reverse the input integer :param x: input integer :return: reversed integer ''' num = 0 # return the absolute value of a number a = abs(x) while(a!=0): # 123 # a = 123 # num = 0 # First iteration # a = 12 # num = 3 # second iteration # a = 1 # num = 32 # Third iteration # a = 0 # num = 321 # 除余运算 temp = a % 10 num = num * 10 + temp # a = int(a/10) # or a = a // 10 if x > 0 and num < 2147483647: print(num) elif x < 0 and num <= 2147483647: print(-num) else: print(0) if __name__ == '__main__': x_1 = 32111 x_2 = -2213 x_3 = 0 output = Solution() output.reverse(x_1) output.reverse(x_2) output.reverse(x_3)
true
781b64fb1675bdb0a9455b12881ebd0e7445a33e
sgouda0412/regex_101
/example/012_matching_one_or_more_repetitions.py
373
4.21875
4
""" Task You have a test string S. Your task is to write a regex that will match S using the following conditions: S should begin with 1 or more digits. After that, S should have 1 or more uppercase letters. S should end with 1 or more lowercase letters. """ import re Regex_Pattern = r'^[\d]+[A-Z]+[a-z]+$' print(str(bool(re.search(Regex_Pattern, input()))).lower())
true
6770521cbf59e985dc41341e5d05bd9760a66f82
sgouda0412/regex_101
/example/011_matching_zero_or_more_repetitions.py
375
4.1875
4
""" Task You have a test string S. Your task is to write a regex that will match S using the following conditions: S should begin with 2 or more digits. After that, S should have 0 or more lowercase letters. S should end with 0 or more uppercase letters """ import re Regex_Pattern = r'^[\d]{2,}[a-z]*[A-Z]*$' print(str(bool(re.search(Regex_Pattern, input()))).lower())
true
e15dc6d20c691a643fb184992e45bb6d3f55aac1
dustyujanin/Python_course
/lesson6/lesson6_4.py
1,166
4.125
4
class car: def __init__(self, speed, color, name, is_police): self.name = name self.speed = speed self.color = color self.is_police = is_police print(f"New {self.color} {self.name} is born!") def go(self): print(f"{self.color} car {self.name} is going") def show_speed(self): print(f"{self.color} car {self.name} speed is {self.speed}") def stop(self): self.speed = 0 print(f"{self.name} is stopped") def turn(self,direction): self.direction = direction print(f"{self.color} car {self.name} turn {self.direction}") class TownCar(car): def show_speed(self): if self.speed > 60: print(f"{self.name} -Over speed!") class WorkCar(car): def show_speed(self): if self.speed > 40: print(f"{self.name} - Over speed!") class SportCar(car): pass class PoliceCar(car): pass TCar = TownCar(70, 'red', 'ford focus', False) WCar = WorkCar(50, 'blue', 'nissan', False) PCar = PoliceCar(150,'black','Ford Mustang',True) TCar.go() TCar.turn("left") TCar.show_speed() TCar.stop() WCar.show_speed() PCar.show_speed()
false
0f79fabfc085fe7aae85f66fb216ff8d8591c90a
nikhilrane1992/Python_Basic_Exercise
/angle_betn_clock_hands.py
844
4.3125
4
# Find the anfle between the two clock hands # First find the hour degree and minute degree for hour angle from 12 hour_degree = (360 / 12.0) hr_minutes_degree = (360 / 12 / 60.0) # hour degree = 30 and hr minutes degree 0.5. # Find minute angle from 12 minutes_degree = 360 / 60.0 # minute degree is 6 # Now find the angle by using following formula. print "{} - {} - {}".format(hour_degree, hr_minutes_degree, minutes_degree) def clockangles(hour, minute): ans = abs(( hour * hour_degree + minute * hr_minutes_degree ) - (minute * minutes_degree)) # for no negative angle return min(360 - ans, ans) hour, minute = input("Enter hour and minute comma seperated: ") hour, minute = int(hour), int(minute) print "Angle Between {} hour and {} minute is {}".format( hour, minute, int(clockangles(hour, minute)))
true
5749e068940ab140b24525d99e32e927ff7476a0
nikhilrane1992/Python_Basic_Exercise
/conversion.py
585
4.59375
5
# Convert kilometers to mile # To take kilometers from the user km = input("Enter value in kilometers: ") # conversion factor for km to mile conv_fac = 0.621371 # calculate miles miles = km * conv_fac print '{:.3f} kilometers is equal to {:.3f} miles'.format(km, miles) # Python Program to convert temperature in celsius to fahrenheit # change this value for a different result celsius = input("Enter value in celsius: ") # calculate fahrenheit fahrenheit = (celsius * 1.8) + 32 print '{:.1f} degree Celsius is equal to {:.1f} degree Fahrenheit'.format( celsius, fahrenheit)
true
f656676ddc417498eca99aa1b687bac6391fa630
shubhamyedage/pycharm-codebase
/Test/apps/test_date_time/test_date_2.py
611
4.25
4
""" This module converts string to given date format. Date-Time Formats http://strftime.org/ """ from datetime import datetime, date s1 = "2008-08" s2 = "2017-08" v1 = datetime.strptime(s1, "%Y-%m") # print(v1) # print(v1.year) v1_date = str(v1.date()) # print(datetime.strptime(v1_date, "%Y-%m-%d").date()) v2 = datetime.strptime(s2, "%Y-%m").date().strftime("%Y-%m") print(v2) v3 = datetime.now() print(v3) def get_year(d): return d.year # y1 = get_year(v2) y2 = get_year(v3) # print(y1 == y2) s = "feb-15" v3 = datetime.strptime(s, "%b-%y") # print("v3 : {v3}".format(v3=v3)) # print(v3.month)
false
500fbe4ebe78bc2cd8cf8dc4b49639ba9bd746d3
Robzabel/AutomateTheBoringStuffScripts
/14.Data_Structures.py
1,324
4.46875
4
cats = { 'name': 'fenty', 'age': 6, 'colour': 'black'} # this creates a dictionary of information on the cat allCats = [] #this creates a blank dictionary that can hold all data about all cats in the variable called allCats allCats.append(cats) allCats.append({ 'name': 'Pooka', 'age': 3, 'colour': 'grey'})#Adding data to the variable allCats allCats.append({ 'name': 'Sweaty', 'age': 4, 'colour': 'blue'}) allCats.append({ 'name': 'John', 'age': 5, 'colour': 'orange'}) print(allCats) #this prints the data structure all cats #a simple tic tac toe board game import pprint theBoard = {'top-L':' ', 'top-M': ' ', 'top-R': ' ', \ 'mid-L':' ', 'mid-M': ' ', 'mid-R': ' ', \ 'low-L':' ', 'low-M': ' ', 'low-R': ' ',}#this creates the board as a data structure pprint.pprint(theBoard) #write a function that outputs the board in a nice display def printBoard(board): print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R']) print('-----') print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R']) print('-----') print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R']) printBoard(theBoard)# this prints the board as you can see you have the makings of a tic tak toe game #some examples of using the type function print(type(42)) print(type('hello')) print(type(theBoard))
false
51010381f36511069c0e670f5d2a2a283ed40364
KOdunga/Python_Introduction
/PycharmProjects/untitled1/maxnumber.py
389
4.25
4
# Create a function that requests for three integers then get the maximum number def getnumbers(): list = [] x = 1 while x<4: num = input("Enter a number: ") list.append(num) x+=1 getmaxnum(list) def getmaxnum(list): print(max(list)) y=1 while y != 0: getnumbers() y = int(input("To exit enter 0, press other numbers to continue: \t"))
true
b1b3198703fb3708a2fc277f0b9b4c99c68774b5
dave5801/data-structures
/sorting/sortings.py
2,316
4.21875
4
"""Class for sorting algorithms.""" ''' class Sortings(object): """A general class for sorting algorithms.""" def __init__(self, sort_list=None): """Take in empty list.""" if sort_list is None: self.sort_list = [] else: self.sort_list = sort_list def bubble_sort(self): """Bubble sort.""" for i in range(len(self.sort_list) - 1): for j in range(len(self.sort_list) - 1): if self.sort_list[j] > self.sort_list[j + 1]: temp = self.sort_list[j] self.sort_list[j] = self.sort_list[j + 1] self.sort_list[j + 1] = temp def insert_sort(self): """Insertion sort.""" for i in range(len(self.sort_list)): k = self.sort_list[i] j = i while j > 0 and k < self.sort_list[j-1]: self.sort_list[j] = self.sort_list[j-1] j -= 1 self.sort_list[j] = k def merge_sort(self, arr): """Merge Sort.""" if len(arr) <=1: return arr mid = len(arr)//2 left = arr[mid:] right = arr[:mid] left = self.merge_sort(left) right = self.merge_sort(right) output = [] while left and right: if right[0] < left[0]: output.append(right[0]) right.pop(0) elif left[0] < right[0]: output.append(left[0]) left.pop(0) return output + left + right def quick_sort(self, arr): """Quick sort.""" if len(arr) <= 1: return arr pivot = arr[0] left = [] right = [] for i in arr[1:]: if i < pivot: left.append(i) elif i > pivot: right.append(i) left = self.quick_sort(left) right = self.quick_sort(right) return left + [pivot] + right def radix_sort(self, arr): x = len(str(max(arr))) str_list = ['%0*d' % (x, i) for i in arr] print(str_list) ''' if __name__ == '__main__': s = Sortings([]) arr = [5, 102, 48, 10, 2, 500] t = s.radix_sort(arr) print(t) #tl = s.insert_sort() #print(s.sort_list)
false
3fcfbb9610c0aa54f8d8290b35d587e731f111bc
kevinjdonohue/LearnPythonTheHardWay
/ex7.py
878
4.40625
4
"""Exercise 7.""" # prints out a string print("Mary had a little lamb.") # prints out a formatted string with a placeholder -- inside we call format # and pass in the value to be placed in the formatted string placeholder print("Its fleece was white as {}.".format('snow')) # prints out a string print("And everywhere that Mary went.") # prints out 10 period strings print("." * 10) # assigns a single (character) string to each variable end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" # prints out the first 6 variables # plus assigns an empty space as the end character of the string # to create space between the first and second words print(end1 + end2 + end3 + end4 + end5 + end6, end=' ') # prints out the remaining 6 variables print(end7 + end8 + end9 + end10 + end11 + end12)
true
a4f32612138904fc26b35cc88768253b840c10f6
cgsmendes/aulas
/exerc_M_ou_F.py
205
4.125
4
letra = str(input("Digite M ou F: ")) if letra is 'm' or letra is 'M': print(letra, "É Masculino") elif letra is 'f' or letra is 'F': print(letra, "É FEMININO") else: print("SEXO INVÁLIDO")
false
dbace8d9d68e4dcc983acac20ac2dfc3e2ae1fe0
kushalkarki1/pythonclass-march1
/firstclass.py
388
4.1875
4
# if <condition>: # code # if 7 > 10: # print("This is if statement") # else: # print("This is else statement") # num = int(input("Enter any number: ")) # if num > 0: # print("This is positive number.") # else: # print("This is negative number.") num = int(input("Enter any num: ")) rem = num % 2 if rem == 0: print("Even number") else: print("Odd number")
true