blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
457c8d01c473f8500d737b6e37d18403d2956cbc
Ccccarson/study_python
/basic/def_fanc.py
1,821
4.1875
4
# 在python中,定义一个函数要使用 def 语句,一次写出函数名、括号、货好种的参数和冒号 # 然后,在缩进块中编写函数体,函数的返回值用return语句返回 def my_abs(x): if x>0: return x else: return -x print(my_abs(-99)) def fibonacci(x): if x==0: return 0 if x<=2: return 1 else: return fibonacci(x-1)+fibonacci(x-2) print(fibonacci(5)) # 请注意,函数体内部的语句在执行时,一旦执行到return时,函数就执行完毕并将结果返回。 # 因此内部通过条件判断和循环可以实现非常复杂的逻辑 # 如果没有return语句,函数执行完毕后也会返回结果,只是结果为none # return None可以简写为return # 如果想要定义一个什么事也不做的空函数,可以用pass语句 def nop(): pass # 参数检查 修改一下my_abs的定义 # 数据类型检查可以用内置函数isinstance()实现 def my_abs1(x): if not isinstance(x,(int,float)): raise TypeError('bad operand type') if x>=0: return x else: return -x # 返回多个值 import math def move(x,y,step,angle=0): nx=x+step*math.cos(angle) ny=y-step*math.sin(angle) return nx,ny # import math语句表示导入math包,并允许后续代码引用math包里的sin、cos等函数 print(move(100,100,60,math.pi/6)) # 练习 定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程: # ax2 + bx + c = 0 # 的两个解。 def quadratic(a,b,c): if a==0: return "a is not 0" else: my_discriminant=b*b-4*a*c x1=(-b-math.sqrt(my_discriminant))/(2*a) x2=(-b+math.sqrt(my_discriminant))/(2*a) return x1,x2 print(quadratic(2, 3, 1)) print(quadratic(1, 3, -4))
false
728025a2f0e7574edd8f4d44f2bddc79a2ba87d2
iqbalanwar/python_tutorial
/3_data_structure_collections/1_list_and_tuples.py
1,948
4.5
4
''' Lists are mutable - Lists are an ordered collection Tuples are not mutable - Tuples are also an ordered collection - They were exactly the same, but can't be modified ''' def main(): game_one_list() game_two_list() game_tuple() x = ['-','X','X','-'] print(f"Before, the list x is {x}") # this will modify list x, so the value at the 0 index # will be the value popped, or '-' # NEW LIST: ['-','-','X','X'] x.insert(0, x.pop()) print(f" After, the list x is {x}") def game_one_list(): print("========== Game One List ==========") game = ['Rock', 'Paper', 'Scissors', 'Lizard', 'Spock'] i = game.index('Paper') print(f'{game[i]} is on index {i}') game.append('Computer') # adds an item to the end of the list game.insert(0, 'Shotgun') # inserts an item based on given index game.remove('Lizard') # removes an item based on the first matching value game.pop() # removes an item at the end of the list x = game.pop() # pop can also return the popped value # using pop and append together can simulate a stack game.pop(0); # pop also removes based on index print(f'{x} was popped') print_list(game) def game_two_list(): print("========== Game Two List ==========") game = ['Rock', 'Paper', 'Scissors', 'Lizard', 'Spock'] print(', '.join(game)) # Prints the list, with commas between print_list(game) # Prints the list as is print('The length of game is {}'.format(len(game))) def game_tuple(): print("========== Game Tuple ==========") game = ('Rock', 'Paper', 'Scissors', 'Lizard', 'Spock') print(', '.join(game)) # Prints the list, with commas between print_list(game) # Prints the list as is print('The length of game is {}'.format(len(game))) def print_list(o): for i in o: print(i, end=' ', flush=True) print() if __name__ == '__main__': main()
true
c588558203888ba2219a16b5b8acacd695cc2867
hexinyu1900/webauto
/day01/day5/07_parms_test.py
922
4.21875
4
""" 目标:parameterized插件应用 步骤: 1.导包 2.修饰测试函数 3.在测试函数中使用变量接收传递过来的值 语法: 1.单个参数:值为列表 2.多个参数:值为列表嵌套元组,如:[(1,2,3),(2,3,4)] """ import unittest from parameterized import parameterized # 定义测试类并继承 class Test01(unittest.TestCase): # # 单个参数使用方法 # @parameterized.expand(["1", "2", "3"]) # def test_add(self, num): # print("num:", num) # # 多个参数使用方法 写法1 # @parameterized.expand([(1, 2, 3), (3, 0, 3), (2, 1, 3)]) # def test_add_more(self, a, b, c): # print("{}+{}={}:".format(a, b, c)) # 写法2 data = [(1, 2, 3), (3, 0, 3), (2, 1, 3)] @parameterized.expand(data) def test_add_more(self, a, b, c): print("{}+{}={}:".format(a, b, c))
false
cf91f9a79fc5d254c651612de39fd6472bdd2225
hexinyu1900/webauto
/day7/test01_dict_json.py
832
4.34375
4
""" 目标:将python中的字典转为json字符串 操作: 1.导包 import json 2.调用dumps()方法 将字典转换为json字符串 注意: json中,还有一个方法dump()写入json,勿要选错 """ # 导包 import json """将字典转换为json字符串""" # 定义字典 data = {"name": "赞多", "age": 22} # 调用dumps进行转换json字符串 print("转换之前的数据类型:", type(data)) data2 = json.dumps(data) print("转换之前的数据类型:", type(data2)) """将字符串转为json""" # 定义字符串 string = '{"name":"力丸", "age":24}' # 注意错误写法,属性名必须使用双引号 # string = "{'name':'力丸', 'age':24}" print("转换之前:", type(string)) # 转换 string1 = json.loads(string) print("转换之后:", type(string1))
false
6ffefd7a634fde7fba5178bda6a3c9a07513cda2
irimina/python-exercises
/apendAndsort.py
309
4.15625
4
''' Task: Write a for-loop that iterates over start_list and .append()s each number squared (x ** 2) to square_list. Then sort square_list! ''' start_list = [5, 3, 1, 2, 4] square_list = [] # Your code here! for number in start_list: square_list.append(number**2) square_list.sort() print square_list
true
d851c1ca807d66353d7a188404a111ae9347ca84
JuliaJansen/-HabboHotel
/Python code/csv_reader.py
2,442
4.21875
4
# Reads the list of houses and water from a csv file named output.csv # and stores this in the same object-type of list. # # csv_reader(filename) # Amstelhaege - Heuristieken # Julia Jansen, Maarten Brijker, Maarten Hogeweij import csv from house import * def csv_reader(filename): """ Writes the values of a map to csv file named datetime_output.csv """ # open csv file, define fieldnames for houses, instantiate the reader csvfile = open(filename, 'r') fieldnames = ('one','two','three', 'four') reader = csv.DictReader(csvfile, fieldnames) # lists to contain houses and water houses = [] water = [] map_value = 0 houses_total = 0 pieces_of_water = 0 # number of rows in csv number_of_rows = len(list(csv.reader(open(filename)))) # get number of houses and pieces of water if number_of_rows < 30: houses_total = 20 pieces_of_water = number_of_rows - houses_total - 1 elif number_of_rows < 50: houses_total = 40 pieces_of_water = number_of_rows - houses_total - 1 else: houses_total = 60 pieces_of_water = number_of_rows - houses_total - 1 # total amount of objects on the map total_items = pieces_of_water + houses_total # finally, read in houses -> water -> value count_row = 0 for row in reader: # turn houses into house objects if count_row < houses_total: x_min = float(row['one']) y_min = float(row['two']) type_house = row['three'] distance = float(row['four']) new_house = House(x_min, y_min, type_house) new_house.updateDistance(distance) houses.append(new_house) # turn water into water objects elif count_row >= houses_total and count_row < total_items: x_min = float(row['one']) y_min = float(row['two']) x_max = float(row['three']) y_max = float(row['four']) new_water = Water(x_min, y_min, x_max, y_max) water.append(new_water) # read value of map elif count_row == total_items: map_value = float(row['one']) count_row += 1 # # return map and map value full_map = houses + water return (full_map, houses, water, map_value, houses_total, pieces_of_water)
true
55e8156bc16ef1325974b1979d60070fa8217591
gade008/estudos_python
/cursoemvideo/desafio0017.py
405
4.15625
4
from math import pow, sqrt, ceil ca = float(input('Digite o cateto adjacente do triângulo:')) co = float(input('Digite o cateto oposto:')) h = sqrt((pow(ca, 2) + pow(co, 2))) print(" ^") print(" | \ ") print(' | \ ') print(' | \ ') print(' | \ Hipotenusa: {}'.format(h)) print('CO:{} |____________\ '.format(co)) print(' CA:{}'.format(ca))
false
331e4169c939a145aad37067de34c66036165e04
sandykramb/PythonBasicConcepts
/Ascending_order.py
253
4.25
4
numero1 = int(input("Digite um numero inteiro:")) numero2 = int(input("Digite um numero inteiro:")) numero3 = int(input("Digite um numero inteiro:")) if numero1 < numero2 < numero3: print ("crescente") else: print ("não está em ordem crecesnte")
false
12f824c483ebfc1aba65a336c316fbeb3356dff7
1941012973/CWC
/quiz-1/question2.py
2,485
4.375
4
import random # reserved values for user USER_INPUT = "" USER_POINTS = 0 # reserved values for computer COMPUTER_INPUT = "" COMPUTER_POINTS = 0 # other reserved values STOP_GAME = False MAX_ROUNDS = 3 COMPLETED_ROUNDS = 0 ACCEPTED_INPUTS = ['R', 'P', 'S'] # loop till the number of rounds is 3 or user decides to quite while not STOP_GAME and COMPLETED_ROUNDS < MAX_ROUNDS: print("\nStarting Round!") # Ask user's initial input USER_INPUT = input("User's choice: ") # Make a random choice for computer input COMPUTER_INPUT = random.choice(ACCEPTED_INPUTS) # Validate input or ask them to enter correct again. while USER_INPUT not in ACCEPTED_INPUTS: print("Invalid Input. Please enter one of accepted inputs >", str(ACCEPTED_INPUTS)) USER_INPUT = input("User's choice: ") else: print( f"Input success! \n\nUser's input is \n{USER_INPUT}\n\nComputer's input is \n{COMPUTER_INPUT}\n") # validate and update points if USER_INPUT == 'R' and COMPUTER_INPUT == 'P': COMPUTER_POINTS += 1 print("Computer won this round.") elif USER_INPUT == 'P' and COMPUTER_INPUT == 'S': COMPUTER_POINTS += 1 print("Computer won this round.") elif USER_INPUT == 'S' and COMPUTER_INPUT == 'R': COMPUTER_POINTS += 1 print("Computer won this round.") elif USER_INPUT == 'R' and COMPUTER_INPUT == 'S': USER_POINTS += 1 print("User won this round.") elif USER_INPUT == 'P' and COMPUTER_INPUT == 'R': USER_POINTS += 1 print("User won this round.") elif USER_INPUT == 'S' and COMPUTER_INPUT == 'P': USER_POINTS += 1 print("User won this round.") else: USER_POINTS += 1 COMPUTER_POINTS += 1 print("Tie round!") # update rounds count and ask if users want to play more COMPLETED_ROUNDS += 1 if COMPLETED_ROUNDS < 3: STOP_GAME = False if input( "Would you play another game? Enter 'y' or 'n': ") == 'y' else True # display the game result print(f"\n{COMPLETED_ROUNDS} round(s) completed. Computer points are {COMPUTER_POINTS} and user points are {USER_POINTS}") if COMPUTER_POINTS == USER_POINTS: print("Game tied!") elif COMPUTER_POINTS > USER_POINTS: print("Computer won the game!") else: print("User won this game.!")
true
01995a8eec92fb99395ba57a7def0cf85458e627
abhinav-bapat/PythonPrac
/for_loop_example6.py
307
4.1875
4
""" Find out and print the vowels in a given word word = 'Milliways' vowels = ['a', 'e', 'i', 'o', 'u'] """ word = 'Milliways' vowels = ['a', 'e', 'i', 'o', 'u'] result=[] for x in word: if x in vowels: if x not in result: result.append(x) print(result)
true
3602779abf4c08403d3fab6016327915f1292a66
abhinav-bapat/PythonPrac
/code/day2/03_dictionary_examples/dictionary_example3.py
215
4.1875
4
""" Using keys and indexing, print the 'hello' from the following dictionary: d3 = {'k1':[{'nest_key':['this is deep',['hello']]}]} """ d3 = {'k1':[{'nest_key':['this is deep',['hello']]}]}
false
35184453606c23ec5579cd25a29e8be7dbc6cd3d
graemerenfrew/DesignPatternsInPython
/SingletonPattern/singleton_classic.py
592
4.15625
4
class Singleton(object): ans = None @staticmethod def instance(): ''' we do not instantiate instances of Singleton class we just use this static method to allow access''' if '_instance' not in Singleton.__dict__: Singleton._instance = Singleton() # this is how we ensure we only have one instance by doing reflection return Singleton._instance s1 = Singleton.instance() s2 = Singleton.instance() assert s1 is s2 s1.ans = 42 #hilarious I just fucking love python nerdy shit assert s2.ans == s1.ans print("assertions all passed")
true
4c0c0c19a1e2ddf5c9f947b53e035475ea978167
houjun/python_study
/a2.py
2,574
4.3125
4
def get_length(dna): """ (str) -> int Return the length of the DNA sequence dna. >>> get_length('ATCGAT') 6 >>> get_length('ATCG') 4 """ return len(dna) def is_longer(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna1 is longer than DNA sequence dna2. >>> is_longer('ATCG', 'AT') True >>> is_longer('ATCG', 'ATCGGA') False """ return get_length(dna1) > get_length(dna2) def count_nucleotides(dna, nucleotide): """ (str, str) -> int Return the number of occurrences of nucleotide in the DNA sequence dna. >>> count_nucleotides('ATCGGC', 'G') 2 >>> count_nucleotides('ATCTA', 'G') 0 """ return dna.count(nucleotide) def contains_sequence(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna2 occurs in the DNA sequence dna1. >>> contains_sequence('ATCGGC', 'GG') True >>> contains_sequence('ATCGGC', 'GT') False """ return dna2 in dna1 def is_valid_sequence(dna): """ (str) -> bool Return True if and only if the DNA sequence is valid (that is, it contains no characters other than 'A', 'T', 'C' and 'G'). >>> is_valid_sequence('AGCT') True >>> is_valid_sequence('AGCTB') False """ return dna.count('A') + dna.count('T') + dna.count('C') + dna.count('G') == get_length(dna) def insert_sequence(dna1, dna2, index): """ (str, str, int) -> str Return the DNA sequence obtained by inserting the second DNA sequence into the first DNA sequence at the given index. (You can assume that the index is valid.) >>> insert_sequence('CCGG', 'AT', 2) 'CCATGG' """ return dna1[:index] + dna2 + dna1[index:] def get_complement(nucleotide): """ (str) -> str The first parameter is a nucleotide ('A', 'T', 'C' or 'G'). Return the nucleotide's complement. >>> get_complement('A') T >>> is_valid_sequence('G') C """ if nucleotide == 'A': return 'T' elif nucleotide == 'T': return 'A' elif nucleotide == 'G': return 'C' elif nucleotide == 'C': return 'G' def get_complementary_sequence(dna): """ (str) -> str The parameter is a DNA sequence. Return the DNA sequence that is complementary the given DNA sequence. >>> get_complementary_sequence('AT') TA """ comp_dna = '' for nucleotide in dna: comp_dna += get_complement(nucleotide) return comp_dna
false
35aaf99d1f456b2dbb245924da2a9ebbb0683683
ankitsaini84/python
/files.py
614
4.21875
4
""" 1. Create a program that opens file.txt. Read each line of the file and prepend it with a line number. """ with open('file.txt', 'r') as r_file: for line in r_file: print(line.rstrip()) # rstrip removes all trailing whitespaces & newlines """ 2. Read the contents of animals.txt and produce a file named animals­sorted.txt that is sorted alphabetically. """ animals = [] with open('animals.txt', 'r') as ra_file: for animal in ra_file: animals.append(animal) was_file = open('sorted-animals.txt', 'w') animals.sort() for animal in animals: was_file.write(animal) was_file.close()
true
bdb8aa93aa1252198159eee3dc0214021ede2cab
Mohitgola0076/Day5_Internity
/File_and_Data_Hanldling.py
1,662
4.1875
4
''' Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Data handling is the process of ensuring that research data is stored, archived or disposed off in a safe and secure manner during and after the conclusion of a research project. Proper planning for data handling can also result in efficient and economical storage, retrieval, and disposal of data. ''' # Python print() to File Example : def main(): f= open("guru99.txt","w+") #f=open("guru99.txt","a+") for i in range(10): f.write("This is line %d\r\n" % (i+1)) f.close() #Open the file back and read the contents #f=open("guru99.txt", "r") # if f.mode == 'r': # contents =f.read() # print contents #or, readlines reads the individual line into a list #fl =f.readlines() #for x in fl: #print x if __name__== "__main__": main() # Python code to illustrate read() mode file = open("file.text", "r") print (file.read()) # Python code to create a file file = open('geek.txt','w') file.write("This is the write command") file.write("It allows us to write in a particular file") file.close() # Python code to illustrate append() mode file = open('geek.txt','a') file.write("This will add this line") file.close() # Python code to illustrate with() with open("file.txt") as file: data = file.read() # do something with data # Python code to illustrate split() function with open("file.text", "r") as file: data = file.readlines() for line in data: word = line.split() print (word)
true
75fbd42ced9297082c7796e677ddc01fbf3091ec
Hasibul-Alam/learning-python
/Python Basic/recursion.py
240
4.28125
4
#!/usr/bin/python3.9 def calc_factorial(x): if x == 1: return 1 else: return (x*calc_factorial(x-1)) grab = input('Enter a number to find its factorial:') b=int(grab) print ('Factorial of',b,'is:',calc_factorial(b))
true
3af98f0e1cdbf8c49ef05ca95243d11ce478b742
Hasibul-Alam/learning-python
/clever-programming/set.py
787
4.15625
4
list_of_numbers = [1, 2, 2, 3, 4, 5, 5, 5, 6, 6] no_duplicate_set = set(list_of_numbers) no_duplicate_list = list(no_duplicate_set) list_of_numbers = no_duplicate_list print(list_of_numbers) library_1 = {'Harry Potter', 'Hunger Games', 'Lord of the rings'} library_2 = {'Harry Potter', 'Romeo and Juliet'} # union_operation find common and uncommon elements of both sets union_operation = library_1.union(library_2) print('All book in the town:',union_operation) # intersection_operation find only common element in both sets intersection_operation = library_1.intersection(library_2) print('Books found in both library:',intersection_operation) # difference_operation find the uncommon element of the first set difference_operation = library_1.difference(library_2) print(difference_operation)
true
b68fdff33a610c7e4bb398d14a6c21cc13a9b558
dustinboswell/daily-coding-problem
/prob28.py
2,558
4.21875
4
''' Write an algorithm to justify text. Given a sequence of words and an integer line length k, return a list of strings which represents each line, fully justified. More specifically, you should have as many words as possible in each line. There should be at least one space between each word. Pad extra spaces when necessary so that each line has exactly length k. Spaces should be distributed as equally as possible, with the extra spaces, if any, distributed starting from the left. If you can only fit one word on a line, then you should pad the right-hand side with spaces. Each word is guaranteed not to be longer than k. For example, given the list of words ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"] and k = 16, you should return the following: ["the quick brown", # 1 extra space on the left "fox jumps over", # 2 extra spaces distributed evenly "the lazy dog"] # 4 extra spaces distributed evenly ''' def make_line(words, k): # special-case 1 word, to avoid divide-by-0 weirdness below if len(words) == 1: return word.ljust(k) spaces = k - sum(len(w) for w in words) spaces_per_word, num_extra = divmod(spaces, len(words)-1) line = '' for i, word in enumerate(words): line += word if i < len(words)-1: line += ' ' * (spaces_per_word + (1 if i < num_extra else 0)) return line def justify(words, k): assert words # otherwise, do we print a blank line or not? lines = [] # list of final strings to return line_words = [] # list of words for current line being built min_line_len = 0 # minimum characters required for current line for word in words: # optimistically append word, assuming there is space line_words.append(word) min_line_len += len(word) if len(line_words) > 1: min_line_len += 1 # preceeding space for new word # oops, line too long -- undo, print, start new line if min_line_len > k: line_words.pop() lines.append(make_line(line_words, k)) line_words = [word] min_line_len = len(word) lines.append(make_line(line_words, k)) return lines ''' For example, given the list of words and k = 16, you should return the following: ["the quick brown", # 1 extra space on the left "fox jumps over", # 2 extra spaces distributed evenly "the lazy dog"] # 4 extra spaces distributed evenly ''' print(justify(["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"], 16))
true
1006271f95ec1da9d57dd3afaaf1591cd27afaad
cryu1994/python_folder
/oop/products/index.py
666
4.1875
4
class bike(object): def __init__(self, price, max_speed, miles = 0): print "New bike" self.price = price self.max_speed = max_speed self.miles = miles def display(self): print "Price is:",self.price print "The max_speed is:",self.max_speed print "The total miles riden is:",self.miles return self def ride(self): print "Riding" self.miles += 10 return self def reverse(self): print "Reversing" if self.miles >= 5: self.miles -= 5 return self bike1 = bike(100,10).ride().ride().ride().reverse().display() bike2 = bike(200,20).ride().ride().ride().reverse().display() bike3 = bike(300,30).reverse().reverse().reverse().display()
true
0d351c6f2fce0c3a503bfaf4d0269c838eb3495f
Larrydek/Python-UNSAM
/11 - Recursión y regresión/factorial.py
371
4.28125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 26 21:17:55 2021 @author: Manjuanel """ #FACTORIAL # def factorial(n): # if n == 1: # return 1 # return n * factorial(n-1) #Otro factorial detallado: def factorial(n): if n == 1: r = 1 return r f = factorial(n-1) r = n * f return r factorial(3)
false
db602a5d6607720329fc4a7a7deac5cabd1f412f
Sahil12S/LeetCode
/Python/bubbleSort.py
453
4.15625
4
# Bubble Sort Algorithm def bubbleSort(data): for i in range(len(data) - 1, 0, -1): for j in range(i): if data[j] > data[j + 1]: temp = data[j] data[j] = data[j + 1] data[j + 1] = temp print("Current state: ", data) def main(): list1 = [6, 20, 8, 19, 56, 23, 87, 41, 49, 53] bubbleSort(list1) print("Result: ", list1) if __name__ == "__main__": main()
false
5e811a872eb8544f21e4e5b9405bb0e58f25197b
OrpingtonClose/daily
/python/rxpy/book/iterator.py
495
4.125
4
def iterate(iterator): print("Next") print(next(iterator)) print(next(iterator)) print("for loop") for i in iterator: print(i) class next_impl: def __init__(self): self.i = 0 def __iter__(self): return self def __next__(self): if self.i > 5: raise StopIteration self.i += 1 return self.i collection = list([1,2,3,4,5]) iterator = iter(collection) print("iterate(iterator)") iterate(iterator) print("iterate(next_impl())") iterate(next_impl())
false
62032db1055ce4b10a14cb5574db5fdf6f6b7e11
mvoecks/CU-MatrixMethods
/firstorder.py
2,656
4.34375
4
#This file generates random text based on an input text using a first order markov chain model #import necessary libraries import random import sys #define the probability transition matrix hashtable and the lastword variable lastWord = '' ptm = {} #This section populates the probability transition matrix by scanning every word of the document and updates #the entries of the corrisponding words in the hashtable so that its rows are all the words in the document #and their columns consist of all the words that follow that specific word #these lines get the next word from the text with open('sample.txt', 'r') as f: for line in f: for word in line.split(): #the word is first converted to lowercase and checked to see if it is actually a word word = word.lower() if word != '': #this first if statement will only return true once at the very start of the algorithm, #and just sets the first word of the document to the variable lastWord if lastWord == '': lastWord = word #For every subsequent word in the document the following code runs else: #if the previous word is not in the probability transition hashtable then add it #and make its only entry the word we are processing if not(lastWord in ptm): ptm[lastWord] = [word] #if the previous word exists in the probability transition hashtable then update its #columns to include the word we are currently processing else: ptm[lastWord].append(word) #set the variable lastWord to the word currently being processed so the next loop associates #the correct words lastWord = word #This section of the code generates the text by picking a random starting word, and then based of that random #starting word it picks the next word randomly from the previous words probabiliy transition hashtable #pick a random word from the hashtable start = random.choice(list(ptm)) #loop until the user specified number of words have been randomly generated for i in range(1, int(sys.argv[1])): #choose a random word to be printed next based of the previous word word = random.choice(ptm[start]) #reset the previous word to be the current word that was just picked start = word #print out the word set that was set aside for printing sys.stdout.write(word+' ') sys.stdout.flush() print()
true
9a42eba82f4fe4eb85c0430c76d05448e5a63b25
crobil/project
/range_extraction.py
1,524
4.5625
5
""" instruction A format for expressing an ordered list of integers is to use a comma separated list of either individual integers or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example ("12, 13, 15-17") Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format. Example: solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]) # returns "-6,-3-1,3-5,7-11,14,15,17-20" """ def solution(args): out = '' flag = False out += '%d' % args[0] for idx in range(1,len(args)): if args[idx] - args[idx-1] == 1: if flag == True and idx == len(args)-1: out += '%d' % args[idx] elif flag == False and idx == len(args)-1: out += ',%d' % args[idx] elif flag == True: continue elif args[idx] - args[idx+1] == -1: flag = True out += '-' else: out += ',%d' % args[idx] else: if flag == True: out += '%d,%d' % (args[idx-1], args[idx]) flag = False else: out += ',%d' % args[idx] flag = False return out
true
6c7f9df74e6defe4b9348e167da97b71d19047c4
crobil/project
/Simple_Encryption_#1_Alternating_Split.py
1,477
4.46875
4
""" For building the encrypted string: Take every 2nd char from the string, then the other chars, that are not every 2nd char, and concat them as new String. Do this n times! Examples: "This is a test!", 1 -> "hsi etTi sats!" "This is a test!", 2 -> "hsi etTi sats!" -> "s eT ashi tist!" Write two methods: def encrypt(text, n) def decrypt(encrypted_text, n) For both methods: If the input-string is null or empty return exactly this value! If n is <= 0 then return the input text. This kata is part of the Simple Encryption Series: Simple Encryption #1 - Alternating Split Simple Encryption #2 - Index-Difference Simple Encryption #3 - Turn The Bits Around Simple Encryption #4 - Qwerty Have fun coding it and please don't forget to vote and rank this kata! :-) """ def decrypt(encrypted_text, n): if n < 1: return encrypted_text res = '' res1 = '' res2 = '' res1 += encrypted_text[0:int(len(encrypted_text)/2)] res2 += encrypted_text[int(len(encrypted_text)/2):] for idx in range(len(encrypted_text)): if idx % 2 == 0: res += res2[int(idx / 2)] if idx % 2 == 1: res += res1[int(idx / 2)] return decrypt(res, n-1) def encrypt(text, n): if n < 1: return text res = '' for var in range(1,len(text),2): res += text[var] for var in range(0,len(text),2): res += text[var] return encrypt(res, n-1)
true
fcf5810c6153783f3133e1ec24260d6c9f3c8a1f
alyssonalvaran/activelearning-python-exercises
/scripts/exercise-08.py
788
4.40625
4
#!/usr/bin/env python # coding: utf-8 # ## Exercise 8 # #### dates-and-times # Ask the user to input a month, day, and year, and display it in the following format - `Jan 2, 2019 (Wed)`. # In[1]: import datetime # assuming that the user will enter valid inputs: month = int(input("Enter month (1 to 12): ")) day = int(input("Enter day (1 to 31): ")) year = int(input("Enter year (1 to 12): ")) dt = datetime.date(year, month, day) print("That is " + f"{dt:%A} {dt:%B} {dt.day}, {dt:%Y}") # Display the current time in the following format - `9:05 PM`. # In[ ]: today = datetime.datetime.today() print(f"{today.hour}:{today:%M} {today:%p}") # #### list-dir # Display the contents of the root directory. # In[ ]: import os for file in os.listdir("/"): print(file)
true
4210cf5ce1635d4dd0e938e6767cc030ce617349
alyssonalvaran/activelearning-python-exercises
/scripts/exercise-06.py
2,035
4.6875
5
#!/usr/bin/env python # coding: utf-8 # ## Exercise 6: Functions # #### days-in-month # Modify days-in-month of Exercise 3.1. Write a function called `num_days_in_month(month)` which will return the number of days given a month (1 to 12). The function should return -1 if the value passed is not between 1 to 12. Modify the code to make use of the function. # In[1]: def num_days_in_month(month): if month.isdigit() and 1 <= int(month) <= 12: month = int(month) else: return -1, "" days = 31 months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] if month == 2: days = 28 elif month in [4, 6, 9, 11]: days = 30 return days, months[month - 1] month = input("Enter month (1 to 12): ") days, str_month = num_days_in_month(month) if days != -1: print("There are {} days in {}.".format(days, str_month)) else: print("Please enter a number between 1 to 12.") # #### password-strength # Modify password-strength of Exercise 4. Write a function called `get_password_score(password)` which will return the password score. Modify the code to make use of the function. # In[2]: def get_password_score(password): score = 0 strength = "Low" for letter in password: # The numeric equivalent of A-Z in the ASCII table is 65-90 # while the numeric equivalent of 0-9 in the ASCII table is 48-57 if 65 <= ord(letter) <= 90 or 48 <= ord(letter) <= 57: score = score + 2 if len(password) > 7: score = score + 2 if 4 <= score < 10: strength = "Medium" elif score >= 10: strength = "High" return score, strength password = input("Enter a word: ") score, strength = get_password_score(password) print("Total score: " + str(score)) print("Password strength: " + strength)
true
af1247d822a3caf43b668dd211e927bf09b8ea26
pdst-lccs/alt2
/average.py
2,529
4.3125
4
# Program to demonstrate mean, median and mode # A function to return the arithmetic mean of all the values in L def get_mean(L): # set the initial value of total to zero total = 0 # running total of values in L # Now loop over the list for v in L: total = total + v # running total # Divide by the total by the number of values in L return total/5 # A function to return the median of all the values in L def get_median(L): # To find the median we need to sort the list L.sort() # the values are sorted 'in place' # The next step is to find the index of the middle value num_values = len(L) mid = num_values//2 median = L[mid] # the median is in the middle return median # A function to return the mode of all the values in L def get_mode(L): # Build up a list of unique values unique_values = [] for value in L: if value not in unique_values: unique_values.append(value) # Build up a list of frequencies frequencies = [] for value in unique_values: frequency = L.count(value) frequencies.append(frequency) # Find the mode max_frequency = max(frequencies) max_frequency_pos = frequencies.index(max_frequency) mode = unique_values[max_frequency_pos] return mode # Test driver code .... my_list = [18, 16, 17, 18, 19, 18, 17] # Call the functions mean_value = get_mean(my_list) median_value = get_median(my_list) mode_value = get_mode(my_list) # Display the answers print("The mean is:", mean_value) print("The median %.2f is the middle value" %median_value) print("The mode is:", mode_value) # TASKS FOR BREAKOUT # Tasks for get_mean # Modify the function get_mean so that it works for any number of values (not just 5) # Modify the function get_mean to use sum instead of a loop # Tasks for get_median # Modify the function get_median so that it works for an even number of values # Tasks for get_mode # The statement list(set(L)) returns a list of unique elements in L. # Use this information to replace the loop that builds the list of unique values # This version of get_mode works for lists that have a single mode. # Modify the function get_mode so that it .... # - works if there is no mode e.g. L = [18, 16, 17, 21, 19, 16, 22] # - works if there are multiple modes e.g. L = [18, 16, 17, 18, 17, 18, 17] # Modify the program so that it can display the frequency of the mode(s)
true
5fd35cffdbba30c524893db4bc309ae78ca6871b
Polin-Tsenova/Python-Fundamentals
/Palindrome_integers.py
266
4.15625
4
def is_palindrome(num): reversed_num = num[::-1] is_palindrome = True if num != reversed_num: is_palindrome = False return is_palindrome numbers_list = input().split(", ") for n in numbers_list: print(is_palindrome(n))
false
bf2d960307ea82d56a9a1e641859a5643827e094
ujjwalsinghal541/My-Pattern_Programs
/TYPE 5/PATTERN_PROGRAM_6.py
352
4.1875
4
H=''' THIS IS A PATTERN PROGRAM TO PRINT THIS PATTERN 1 3 2 5 4 3 7 6 5 4 9 8 7 6 5 UPTO N ROWS.''' print(H) N=int(input("ENTER N\n")) A=0 for i in range(1,N+1): for j in range(i,N): print(' ',end="") for j in range(2*i-1,i-1,-1): print(j,end=" ") print("\n") input("PRESS ENTER TO EXIT")
false
8e1dc197a95e8e1cf107f2103c838de01cfafd59
onmaxon/algorithm-python
/less2/less_2_task_3.py
404
4.15625
4
# 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. # Например, если введено число 3486, надо вывести 6843. number = int(input('Введите: ')) num = 0 while number > 0: num = num * 10 + number % 10 number = number // 10 print(num)
false
63aac3628de8792208f5c40e17e61a677280e0a8
klewison428/Python-Projects
/Automate the Boring Stuff with Python/table_printer.py
615
4.1875
4
def printTable(): colWidths = [0] * len(tableData) for column in tableData: for row in column: if len(colWidths) < len(row): print("column widths = " + str(colWidths)) print("row = " + str(row)) longest_word = len(row) longest_word = row print(longest_word) tableData = [['apples', 'oranges', 'cherries', 'banana'], #[0][0] = giving me apples ['Alice', 'Bob', 'Carol', 'David'], #[0][1] ['dogs', 'cats', 'moose', 'goose']] #[0][2] printTable() # need to compare the longest word with the # if this longest word is greater than that longest word update colWidths with the longest one
true
a6721a95cf84e30f928b616458ae05196e66baee
PoojaDilipChavan/DataScience1
/Tuples.py
2,290
4.75
5
""" Tuples https://www.geeksforgeeks.org/python-tuples/?ref=lbp https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences https://docs.python.org/3/library/stdtypes.html#typesseq https://wiki.python.org/moin/TimeComplexity -- complexity for tuples is same as lists (indexed) created by placing sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of data sequence. can contain any number of elements and of any datatype (like strings, integers, list, etc.) can contain duplicates accessed via unpacking or indexing immutable objects : An object with a fixed value. Immutable objects include numbers, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored. They play an important role in places where a constant hash value is needed, for example as a key in a dictionary. Time complexity : same as list : access= O(1) iterate = O(n) """ tuple1=() #Creation of empty tuple , paranthesis necessary print(len(tuple1)) tuple1 = "lol", #creation of tuple with single elemenet , comma necessary print(len(tuple1)) tuple1= (1,2,3,"Pooja","sudhir",[5,7,"lol"],1,2) #can have duplicates tuple2= 189,"mgf",90,"hfk" #can be used without paranthesis print(tuple1+tuple2) #concatenation of tuples #Indexing & unpacking print(tuple1[3]) print(tuple1[::-1]) print(tuple1[3:5]) #slicing Tuple3 = tuple('GEEKSFORGEEKS') # Removing First element print("Removal of First Element: ") print(Tuple3[1:]) a,b,c,d=tuple2 #Unpacking of tuples , In unpacking of tuple number of variables on left hand side should be equal to number of values in given tuple a. print(a) print(b) print(c) print(d) tuple4=8,9,"a" del tuple4 #deletion of tuple, Tuples are immutable and hence they do not allow deletion of a part of it #print(tuple4) #Functions tuple4=8,77,89,4,5,7 print(len(tuple4)) print(max(tuple4)) print(min(tuple4)) print(sum(tuple4)) print(sorted(tuple4)) #sorting , input elements in the tuple and return a new sorted list list1=["bfk",5,4,3,2,9] tuple5=tuple(list1) #Convert an iterable to a tuple. print(tuple5)
true
b0ee785fe939fdab53c1e3354e5c847bad47583f
Alyks82/1lesson
/HomeWork/1 lesson/1 task.py
707
4.21875
4
# 1.Поработайте с переменными, создайте несколько, выведите на экран, # запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран. name = 'Aleksandr' surname = 'Lykov' age = 38 print(name, surname, age, sep='*') print(type(name)) print(type(surname)) print(type(age)) pet_name = input('Сообщите имя своего питомца ') maiden_name = input('Введите девичью фамилию Вашей мамы ') print(f'Никогда не используй в паролях {pet_name},{maiden_name} и 123456789')
false
967c30415c763728a96cdd48f8f1ae3be4b41458
emilywz/newCoderFollow
/judegeWord.py
547
4.125
4
# 题目描述 # 写出一个程序,接受一个由字母、数字和空格组成的字符串, # 和一个字母,然后输出输入字符串中该字母的出现次数。不区分大小写。 # 输入描述: # 第一行输入一个由字母和数字以及空格组成的字符串,第二行输入一个字母。 # 输出描述: # 输出输入字符串中含有该字符的个数。 target=input() countWord=input() count=0 for i in target: if i==countWord or i.upper()==countWord or i.lower()==countWord: count+=1 print(count)
false
2105df201becec94f76a59e1bd583d70e9e8a4db
Fey0xFF/python_odin_project
/caesar_cipher/caesar_cipher.py
809
4.125
4
#import string for ascii import string #store user string and shift factor plaintext = input("Please enter a sentence to encrypt: ") shift = int(input("Please enter a shift factor: ")) #cipher function def cipher(text, shiftfactor): #init key lists letters = list(string.ascii_lowercase[:26]) capletters = list(string.ascii_uppercase[:26]) ciphertext = "" #iterate through letter in string for letter in text: if letter in letters: index = letters.index(letter) index -= shiftfactor ciphertext = ciphertext + (letters[index]) elif letter in capletters: index = capletters.index(letter) index -= shiftfactor ciphertext = ciphertext + (capletters[index]) else: ciphertext += letter print (ciphertext) #call cipher cipher(plaintext, shift)
true
a50f7734164da664b05716f87195e43a36a5ec8a
whoisgvb/initial_python
/estruturaRepeticao/002.py
365
4.1875
4
""" Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações. """ while True: user = input("Digite um usuário: ") senha = input("Digite uma senha: ") if(user == senha): print("Usuário não pode ser igual a senha!") else: break
false
0929a445c33490a8ac0a171f95db790ed405ca92
dogusural/arbitrager
/gui/menu.py
756
4.125
4
choice ='0' while choice =='0': print("Please choose currency.") print("Choose 1 for TRY") print("Choose 2 for EUR") choice = input ("Please make a choice: ") if choice == "1" or choice == "2": print("Please choose arbitrage direction.") print("Choose 1 for Turkish -> Europe") print("Choose 2 for Europe -> Turkish") choice = input ("Please make a choice: ") elif choice == "2": print("Do Something 4") elif choice == "3": print("Do Something 3") elif choice == "2": print("Do Something 2") elif choice == "1": print("Do Something 1") else: print("I don't understand your choice.") def second_menu(): print("This is the second menu")
true
e14b1f6839dc96e3f210ca8759baa51d2337f7c0
thejaswini18/pythontraining
/hello.py
480
4.34375
4
'''print("hello world") print(2+5-3*3) i=10 j=15 if(i>10): print(i) print(j) else: print(i+j) ''' height = 5.7 weight = 58 bmi = weight//height**2 print(bmi) c = 'ab'+'cd' print(c) ''' arthematic operators''' print("atrhematic operators") print(2+3) print(2-3) print(2*3) print(10/3) print(10%3) print(10//3) print(2**3) print("relational operators") print(5>2) print(5<3) print(5>=5) print(4<=3) print(5!=4) print("assignment operators") i=5 j=10 print(i+=j) print(y)
false
f4d3ea16f57c651382d204db451dbb11d557522c
JulianConneely/multiParadigm
/Assignment2/10.py
890
4.59375
5
# Verify the parentheses Given a string, return true if it is a nesting of zero or more # pairs of parenthesis, like “(())” or “((()))”. # The only characters in the input will be parentheses, nothing else # For them to be balanced each open brace must close and it has to be in the correct order # ref. https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-python/ def check(my_string): brackets = ['()', '{}', '[]'] while any(x in my_string for x in brackets): for br in brackets: my_string = my_string.replace(br, '') return not my_string # Driver code string = "{[]{()}}" # The zero means that "" is an input which would return true i.e. the empty string print(string, "-", "True" # It's false anytime the braces don't balance for example "((", "(()", or "((())))". if check(string) else "False")
true
67658293f7276aff66812ae1006ec2ebfee8677a
Zalasanjay/hacktoberfest2020-1
/Python/shell_sort.py
1,226
4.1875
4
""" Author: Kadhirash Sivakumar Python program implementing Shell Sort Shell Sort: Similar to Insertion Sort except allows for exchange with farther indexes. Make the array 'h' -sorted for a large 'h' value, and keep reducing 'h' by 1. Array is 'h' sorted if all subarrays of every h'th element is sorted! Time Complexity: O(n(log(n))^2) Space Complexity: O(1) """ import typing from typing import List def shell_sort(arr: List[int]) -> List[int]: size = len(arr) gap = size // 2 # gapped insertion sort: keep adding until array is gap sorted while gap > 0: for i in range(gap, size): temp = arr[i] # save position of arr[i] # shift earlier elements until the correct location j = i while j >= gap and arr[j - gap] > temp: arr[j] = arr[j - gap] j -= gap arr[j] = temp # swap back gap //= 2 # reduce the gap and repeat # testing def main(): arr = [5, 3000, -10, 65.2, 200000] size = len(arr) print("Before shell sort:") print(*arr, sep=", ") shell_sort(arr) print("\n") print("After shell sort:") print(*arr, sep=", ") if __name__ == "__main__": main()
true
761ca059fcff934608c98c8ebd071a8d7268da46
Zalasanjay/hacktoberfest2020-1
/Projects/Python/ball.py
2,295
4.21875
4
import pygame import random # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) SCREEN_WIDTH = 700 SCREEN_HEIGHT = 500 BALL_SIZE = 25 class Ball: """ Class to keep track of a ball's location and vector. """ def __init__(self): self.x = 0 self.y = 0 self.change_x = 0 self.change_y = 0 def make_ball(): """ Function to make a new, random ball. """ ball = Ball() # Starting position of the ball. # Take into account the ball size so we don't spawn on the edge. ball.x = random.randrange(BALL_SIZE, SCREEN_WIDTH - BALL_SIZE) ball.y = random.randrange(BALL_SIZE, SCREEN_HEIGHT - BALL_SIZE) # Speed and direction of rectangle ball.change_x = random.randrange(-2, 3) ball.change_y = random.randrange(-2, 3) return ball def main(): """ This is our main program. """ pygame.init() # Set the height and width of the screen size = [SCREEN_WIDTH, SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("Bouncing Balls") # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() ball_list = [] ball = make_ball() ball_list.append(ball) # -------- Main Program Loop ----------- while not done: # --- Event Processing for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYDOWN: # Space bar! Spawn a new ball. if event.key == pygame.K_SPACE: ball = make_ball() ball_list.append(ball) # --- Logic for ball in ball_list: # Move the ball's center ball.x += ball.change_x ball.y += ball.change_y # Bounce the ball if needed if ball.y > SCREEN_HEIGHT - BALL_SIZE or ball.y < BALL_SIZE: ball.change_y *= -1 if ball.x > SCREEN_WIDTH - BALL_SIZE or ball.x < BALL_SIZE: ball.change_x *= -1 # --- Drawing # Set the screen background screen.fill(BLACK) # Draw the balls for ball in ball_list: pygame.draw.circle(screen, WHITE, [ball.x, ball.y], BALL_SIZE) # --- Wrap-up # Limit to 60 frames per second clock.tick(60) # Go ahead and update the screen with what we've drawn. pygame.display.flip() # Close everything down pygame.quit() if __name__ == "__main__
true
8886bc06ddaed9ff37a5d6190d7791a646b29e8f
cristopherf7604/bluesqurriel
/ex13.py
487
4.1875
4
from sys import argv # read the WYSS section for how to run this script, first, second, third = argv # in bash you can make the first second and third variable it put a word in each variable slot and it determines that by whatever words are after python3.6 # it's saying what script first second and third variable are called. print("the script is called:", script) print("your first variable is:", first) print("your second variable is:", second) print("your third variable is:", third)
true
f6c0165e506e822728faa17a84fccefd1ed30c2a
Lemachuca10/Module-3-assingment-
/area of a circle (2).py
222
4.375
4
#Luis Machuca #1/30/2020 #This program will compute the area of a circle. #formula is p*r^2 for Area of circle p = 3.14 r = int(input ("radius ")) #the caculation for the area print ("The area is ") print (p*r**2)
true
6e551a7376ec75ffc063039826ad30affe7ac3ba
aclairekeum/comprobo15
/useful_tools/useful_trig.py
736
4.21875
4
import math def angle_normalize(z): """ convenience function to map an angle to the range [-pi,pi] """ return math.atan2(math.sin(z), math.cos(z)) def angle_diff(a, b): """ Calculates the difference between angle a and angle b (both should be in radians) the difference is always based on the closest rotation from angle a to angle b examples: angle_diff(.1,.2) -> -.1 angle_diff(.1, 2*math.pi - .1) -> .2 angle_diff(.1, .2+2*math.pi) -> -.1 """ a = angle_normalize(a) b = angle_normalize(b) d1 = a-b d2 = 2*math.pi - math.fabs(d1) if d1 > 0: d2 *= -1.0 if math.fabs(d1) < math.fabs(d2): return d1 else: return d2
true
e5c3ebc8f9589e0957ecdf6747299e3bba8f2e5b
captainGeech42/CS160
/assignment4.py
2,206
4.21875
4
firstRun = True while True: # choose the mod mode = input("Please select 'scientific' or 'programmer' mode: " if firstRun else "Please select next mode, or 'exit' to quit the calculator: ") if (mode == "scientific"): # scientific mode validOperations = ["+", "-", "*", "/", "**"] chosenOperation = "" exponent = False chosenOperation = input("Please pick an operation (+, -, *, /, **): ") while chosenOperation not in validOperations: chosenOperation = input("Please choose a valid operation: ") if chosenOperation == "**": exponent = True try: num1 = float(input("Please enter the first operand: " if not exponent else "Please enter the base: ")) num2 = float(input("Please enter the second operand: " if not exponent else "Please enter the exponent: ")) if (chosenOperation == "+"): print("The sum is " + str(num1 + num2)) elif (chosenOperation == "-"): print("The difference is " + str(num1 - num2)) elif (chosenOperation == "*"): print("The product is " + str(num1 * num2)) elif (chosenOperation == "/"): if (num2 == 0): print("You can not divide by zero.") continue print("The quotient is " + str(num1 / num2)) elif (chosenOperation == "**"): print("The result of the exponentiation is " + str(num1**num2)) else: print("Please enter a valid operator") except ValueError: print("Please enter a valid float for " + ("each operand" if not exponent else "the base/exponent")) elif (mode == "programmer"): # programmer mode decimalNumber = 0 try: decimalNumber = int(input("Decimal number: ")) if (decimalNumber < 0): raise ValueError() numBits = 1 tempDiv = decimalNumber while tempDiv // 2 > 0: numBits += 1 tempDiv = tempDiv // 2 binaryNumber = "" for bit in range(numBits - 1, -1, -1): test = decimalNumber - 2 ** bit if (test >= 0): binaryNumber += "1" decimalNumber = test else: binaryNumber += "0" print("Your binary number is " + str(binaryNumber)) except ValueError: print("Please enter a valid positive integer") elif (mode == "exit"): exit() else: print("Invalid mode specified") firstRun = False
true
0a4f08eaeac3ccd1e47e10f57d4d05c0f31e68d8
nancyorgan/memory
/main.py
2,585
4.15625
4
#!/usr/bin/python ###################################################### ########### card-flip memory game #################### class PRNG(object): def __init__(self, seed): self.state = seed def next(self): x = self.state x = x + 1 x = x << 8 | x >> 8 x = x * 997 * 997 x = x % 1024 self.state = x return self.state print "What is the time?" input_string = raw_input() print "How wide would you like the board to be?" input_width = int(raw_input()) print "How tall would you like the board to be?" input_height = int(raw_input()) # Take the input string and make them random. seed = 0 for character in input_string: seed = seed << 1 seed = seed ^ ord(character) # Now make seed more random prng = PRNG(seed) # Create the letters list letters = [] alphabet = map(chr, range(65, 91)) for i in range(input_width * input_height/2): alphabet_index = (prng.next() % 26) letter = alphabet[alphabet_index] letters.append(letter) letters = letters + letters scrambled_letters = [] for i in range(len(letters)): scrambled_index = (prng.next() % len(letters)) single_letter = letters.pop(scrambled_index) scrambled_letters.append(single_letter) # Make the board def chunks(l, n): n = max(1, n) return [l[i:i + n] for i in range(0, len(l), n)] front_board = chunks(scrambled_letters, input_width) for line in front_board: print line # Make the selection board board_length = range(input_width * input_height) selection_cards = [str(x) for x in board_length] selection_cards = [x.center(4, " ") for x in selection_cards] selection_board = chunks(selection_cards, input_width) for line in selection_board: print line def location(choice, width): row,column = divmod(choice, width) return row,column ############ Repeat this! ############## points = 0 while points < len(scrambled_letters)/2 : # select first card, connect it to the front_board card and print print "Select your first card" first_selection = int(raw_input()) j = location(first_selection, input_width) first = front_board[j[0]][j[1]] print "Card face %s : " % first print "Select your second card" second_selection = int(raw_input()) k = location(second_selection, input_width) second = front_board[k[0]][k[1]] print "Card face %s : " % second # Compare first and second if first == second: selection_board[j[0]][j[1]] = " " selection_board[k[0]][k[1]] = " " points += 1 for i in selection_board: print i else: for i in selection_board: print i print "Your score: %s" % points
true
e9c651b2cf84e60edc1e481d3fa9734618fe65d2
Jolo510/practice_fusion_challenge
/src/doctors.py
1,371
4.125
4
class Doctor: """ Summary of class here. Doctor contains - num_id - name - specialty - area - score Attributes: similarity_score: Generates a similarity score between two doctors """ def __init__(self, num_id, name, specialty, area, score): self.num_id = num_id self.name = name self.specialty = specialty self.area = area self.score = score def __str__(self): return 'ID: {0} Name: {1} Specialty: {2} Area: {3} Score: {4}'.format(self.num_id, self.name, self.specialty, self.area, self.score) def similarity_score(self, comparing_doctor): """ Generates a similarity score Args: comparing_doctor: A doctor object to compare too Returns: A similarity score between the two doctors. Score ranges from 0 - 6 """ score = 0 score_points = { 'specialty': 3, # Largest factor because the doctors have the same profession 'area': 2, 'score': 1 }; if self.specialty == comparing_doctor.specialty: score += score_points['specialty'] if self.area == comparing_doctor.area: score += score_points['area'] # If two scores are in the same range (e.g 78 and 73 are in 70-79 range), full points are awarded comparing_score_range_difference = abs( (self.score // 10) - (comparing_doctor.score // 10) ) / 10 score += score_points['score'] - comparing_score_range_difference return score
true
79953dc7f863590116ef1772ecafc0a65f49e1aa
andbutso/6.0001
/ps 1/ps1a.py
929
4.21875
4
# Problem Set 1a # Name: George Mu # Collaborators: None # Time Spent: 00:20 # Get user inputs annual_salary = int(input('Enter your annual salary:')) portion_saved = float(input('Enter the percent of your salary to save, as a decimal:')) total_cost = int(input('Enter the cost of your dream home:')) # Initialize starting variables r = 0.05 # Annual interest rate of savings portion_down_payment = 0.20 # Share to total_cost that is needed for the down payment current_savings = 0 # Starting savings amount months = 0 # Months required to save up # Convert everything to a monthly basis required_savings = total_cost * portion_down_payment monthly_savings_contribution = annual_salary / 12 * portion_saved monthly_r = r / 12 while current_savings < required_savings: current_savings = current_savings * (1 + monthly_r) current_savings += monthly_savings_contribution months += 1 print("Number of Months:",months)
true
6dd651b8564305dbabc40f6635b46b75c67996b3
jltf/advanced_python
/homework3/1_lock.py
856
4.15625
4
""" Output numbers from 0..100 in order. First thread outputs even numbers. Second thread outputs odd numbers. Using Lock synchronization object. """ from threading import Lock from threading import Thread def print_even_numbers(lock_even, lock_odd): for i in range(0, 101, 2): lock_odd.acquire() print(i) lock_even.release() def print_odd_numbers(lock_even, lock_odd): for i in range(1, 100, 2): lock_even.acquire() print(i) lock_odd.release() if __name__ == '__main__': lock_even = Lock() lock_even.acquire() lock_odd = Lock() even_thread = Thread( target=print_even_numbers, args=(lock_even, lock_odd) ) odd_thread = Thread( target=print_odd_numbers, args=(lock_even, lock_odd) ) even_thread.start() odd_thread.start()
true
03124d060da28ead6b28daa50b2b6468f7339f45
AstroHackWeek/pr_review_tutorial
/Tiwari/template/simple_functions.py
924
4.375
4
#function to calculate a Fibonacci sequence upto a given number def fibonacci(max): #define the first two numbers of the sequence values = [0, 1] #create the fibonacci sequence by adding all previous numbers to create the next number in the sequence while values[-2] + values[-1] < max: values.append(values[-2] + values[-1]) return values #function to calculate a factorial of a given number def factorial(value): #value of 0!=1 if value == 0: return 1 #factorial n = n*(n-1)*(n-2)*....*1 else: return value * factorial(value - 1) #function to check if a number is prime def is_prime(value): #remove 1 and 2 as they are godly primes if value > 2.: for i in range(2,value): #check if it is divisible by any number less than this number if value % i == 0.: return False else: return True else: print('All hail no. 1, the primest of all and also 2')
true
9e8a5a4a78d6fd5c2fb91241509445dfba43a36a
jackson097/ISS_Tracker
/input_validation.py
1,272
4.3125
4
""" Check if the coordinate provided is a valid coordinate for the API call Parameters: type - latitude or longitude coordinate - coordinate value passed as a string Returns: boolean - True if the coordinate is valid, Else False """ def _is_valid_coordinate(type, coordinate): # Determine what the max/min coordinates are by the type if type == "longitude": value = 180 elif type == "latitude": value = 90 else: print("Something went wrong... Ending program.") exit(0) # Validate that the coordinate is an integer try: coordinate = float(coordinate) except: return False # Validate the coordinates are within allowed values if coordinate > value or coordinate < (value-value*2): return False return True """ Checks if coordinate is a valid longitude value Parameters: coordinate - The longitude coordinate to be validated (string) Returns: True if longitude is valid, Else False """ def is_valid_longitude(coordinate): return _is_valid_coordinate("longitude", coordinate) """ Checks if coordinate is a valid latitude value Parameters: coordinate - The latitude coordinate to be validated (string) Returns: True if latitude is valid, Else False """ def is_valid_latitude(coordinate): return _is_valid_coordinate("latitude", coordinate)
true
ae00cbcf05d17aaf51a407129c29fdcf31118781
ethanwood2003/Code
/dads programming problems/Task2/task2-with-function.py
1,281
4.4375
4
# THe below statement uses "def" which defines a function of our own making called "isEven()" # we can then use this isEven() later in the main body of the program. def isEven(number): is_even_number = False # this initialises a boolean variable to False as we assume it's odd to start with. if int(number) % 2 == 0: # this used the modulus function to check if the remainder of a divsion is 0 -- this means it is even. is_even_number = True # inside the if statement, we set the the boolean variable to true return is_even_number # finally, we get the function isEven to return this boolean value. # it will return True if the number is even, and false if it is odd. # Reads in a text file called task2.txt which contains a list of numbers in it, # each on a separate line (you will need to manually create task2.txt in Sublime) with open("task2.txt", "r") as text_file: #this opens the task2.txt file and the "r" reads the file. It also assigns task2.txt to text_file for line in text_file: # this creates a loop over each line in the text file. if isEven(line): # here we use the isEven() function we defined above to check if each line the file is even. #if i divide num by 2 and the awns is a whole num then number is even. print(line + "is even")
true
e7573926bba8abaa9538cfcac1edd00e363f39ab
narsingojuhemanth/pythonlab
/right_triangle.py
282
4.3125
4
# (a^2 + b^2) == c^2 a = int(input("Length of side 1:")) b = int(input("Length of side 2:")) c = int(input("Length of side 3:")) #Determines if it's a right triangle if (a**2 + b**2) == c**2: print("It's a right triangle") else: print("It's not a right triangle")
true
f3203c895769a323491ff7c82be070ce48f5738e
narsingojuhemanth/pythonlab
/stringreverse.py
319
4.25
4
# 20. Write a Python class to reverse a string word by word. class Solution: def solve(self, s): temp = s.split(' ') temp = list(reversed(temp)) print(temp) return ' '.join(temp) ob = Solution() sentence = "Hello world, I love python programming" print(ob.solve(sentence))
true
b491c031b9c506c34820d4fed3d50b29ecaf3149
aifulislam/Python_Demo_Forth_Part
/lesson5.py
2,216
4.3125
4
# 24/12/2020------- # Tamim Shahriar Subeen------- # Function()---------------- def add(n1, n2): return n1 + n2 n = 10 m = 5 result = add(n, m) print(result) n1 = 10 n2 = 10 result = add(n1, n2) print(result) num1 = 20 num2 = 10 print(add(num1, num2)) print(add(2.5, 3.9)) # Turtle---------- import turtle def draw_square(side_length): for i in range(4): turtle.forward(side_length) turtle.left(90) counter = 0 while counter < 90: draw_square(100) turtle.right(4) counter += 1 turtle.exitonclick() # Function()---------------- def myfnc(x): print("inside myfnc", x) x = 10 print("Inside myfnc", x) x = 20 myfnc(x) print(x) # Function()---------------- def myfnc(y): print("Y = ", y) print("x =", x) x = 20 myfnc(20) # Function()---------------- def myfnc(y=10): print("y = ", y) p = 20 myfnc(p) myfnc() # Function()---------------- def myfnc(x, y = 10, z = 0): print("x =", x, "y =", y, "z =",z) x = 5 y = 6 z = 7 myfnc(x, y, z) myfnc(x, y) myfnc(x) # Function()---------------- def myfnc(x, z, y = 10): print("x =", x, "y =", y, "z =",z) myfnc(x = 1, y = 2, z = 5) a = 5 b = 6 myfnc(x = a, z= b) a = 1 b = 2 c = 3 myfnc(y = a, z = b, x = c) # Function()---------------- def add_numbers(numbers): result = 0 for number in numbers: result += number return result result = add_numbers([1, 2, 30, 4, 5, 9]) print(result) # Function()---------------- def test_fnc(li): li[0] = 10 my_list = [1, 2, 3, 4] print("before function call", my_list) test_fnc(my_list) print("after function call", my_list) # Function()---------------- list1 = [1, 2, 3, 4] list2 = list1 print(list1) list2[0] = 100 print(list2) print(list1) # Function()---------------- li = [1, 2, 3] result = sum(li) print(result) # Function()---------------- def add_numbers(numbers): result = 0 for number in numbers: result += number / number return result result = add_numbers([1, 2, 30, 4, 5, 7, 4, 9]) print(result) # ------------End------------- #
false
b9a16d2a39eeeaf2e8fd70c3c759cc1200f821c0
joerlop/Sorting
/src/recursive_sorting/recursive_sorting.py
1,628
4.21875
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge( arrA, arrB ): elements = len( arrA ) + len( arrB ) merged_arr = [0] * elements # TO-DO for i in range(len(merged_arr)): if len(arrA) == 0: merged_arr[i] = arrB[0] arrB.pop(0) elif len(arrB) == 0: merged_arr[i] = arrA[0] arrA.pop(0) elif arrA[0] <= arrB[0]: merged_arr[i] = arrA[0] arrA.pop(0) else: merged_arr[i] = arrB[0] arrB.pop(0) return merged_arr # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort( arr ): # TO-DO # 1. While your data set contains more than one item, split it in half # 2. Once you have gotten down to a single element, you have also *sorted* that element # (a single element cannot be "out of order") if len(arr) > 1: middle = len(arr) // 2 left_arr = merge_sort(arr[0:middle]) right_arr = merge_sort(arr[middle:]) # 3. Start merging your single lists of one element together into larger, sorted sets arr = merge(left_arr, right_arr) # 4. Repeat step 3 until the entire data set has been reassembled return arr # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # TO-DO return arr def merge_sort_in_place(arr, l, r): # TO-DO return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort( arr ): return arr
true
1233a1a8a04a7296c3eebbf8568e99cccf2e3529
bsuman/BlockChain
/assignment/assignment_7.py
2,145
4.15625
4
class Food: #1) Create a Food class with a “name” and a “kind” attribute # as well as a “describe() ” method # (which prints “name” and “kind” in a sentence). def __init__(self, name, kind): self.name = name self.kind = kind #def describe(self): #print('The food has the name: {} and is of the kind: {}'.format(self.name,self.kind)) #2) Try turning describe() from an instance method into a # class and a static method. Change it back to an instance method thereafter. #@classmethod #def describe(cls,name,kind): #print('The food has the name: {} and is of the kind: {}'.format(name,kind)) #@staticmethod #def describe(name,kind): #print('The food has the name: {} and is of the kind: {}'.format(name,kind)) def describe(self): print('The food has the name: {} and is of the kind: {}'.format(self.name,self.kind)) #4) Overwrite a “dunder” method to be able to print your “Food” class def __repr__(self): return str(self.__dict__) my_food = Food('Tea','Cooked') my_food.describe() print(my_food) #Food.describe(my_food.name,my_food.name) #3) Create a “Meat” and a “Fruit” class – both should inherit from “Food”. # Add a “cook() ” method to “Meat” and “clean() ” to “Fruit”. class Meat(Food): #def __init__(self, name, kind): #super().__init__(name,kind) def cook(self): print('Method cook was called') my_meat = Meat('chicken','non-veg') my_meat.describe() my_meat.cook() class Fruit(Food): def __init__(self,name,kind, freshness_level=0.0): super().__init__(name,kind) self.freshness_level = freshness_level def clean(self): print('Current freshness level:{} of the fruit with name:{} and kind:{}'.format(self.freshness_level, self.name, self.kind)) print('After cleaning increased to new freshness level {}'.format(str(self.freshness_level + 1))) my_fruit = Fruit('Apple','Raw',0.5) my_fruit.describe() my_fruit.clean() print(my_fruit)
true
f0b5f65de865af6d7a32ca117c33af5162b63dd8
Gwellir/gb_py_algo
/lesson1/task3.py
943
4.1875
4
# По введенным пользователем координатам двух точек вывести уравнение прямой вида # y = kx + b, проходящей через эти точки. print('Введите координаты первой точки (два вещественных числа).') x1 = float(input('x1: ')) y1 = float(input('y1: ')) print('Введите координаты второй точки (два вещественных числа).') x2 = float(input('x2: ')) y2 = float(input('y2: ')) if x1 == x2: if y1 != y2: print('Не существует уравнения прямой, соответствующего условиям.') else: b = y1 print(f'Уравнение одной из таких прямых: y = 0x + {b}') else: k = (y1 - y2)/(x1 - x2) b = y1 - k * x1 print(f'Уравнение прямой: y = {k}x + {b}.')
false
64b1b7f55b9e7884658d05b34849493fd1844e62
shikha1997/Interview-Preparation-codes
/Binary_tree/dncn.py
1,578
4.25
4
class Node: def __init__(self, data): self.data = data self.right = None self.left = None # Utility function to print the inorder # traversal of the tree def PrintInorderBinaryTree(root): if (root == None): return PrintInorderBinaryTree(root.left) print(str(root.data), end=" ") PrintInorderBinaryTree(root.right) # Function to make current node right of # the last node in the list def FlattenBinaryTree(root): # A global variable which maitains the last node # that was added to the linked list global last if (root == None): return left = root.left right = root.right # Avoid first iteration where root is # the only node in the list if (root != last): last.right = root last.left = None last = root FlattenBinaryTree(left) FlattenBinaryTree(right) if (left == None and right == None): last = root # Build the tree root = Node(1) root.left = Node(2) root.left.left = Node(3) root.left.right = Node(4) root.right = Node(5) root.right.right = Node(6) # Print the inorder traversal of the # original tree print("Original inorder traversal : ", end="") PrintInorderBinaryTree(root) print("") # Global variable to maintain the # last node added to the linked list last = root # Flatten the binary tree, at the beginning # root node is the only node in the list FlattenBinaryTree(root) # Print the inorder traversal of the flattened # binary tree print("Flattened inorder traversal : ", end="") PrintInorderBinaryTree(root)
true
2ba79380f9d570a5e11d92d9b25b27491447292b
ahad-emu/python-code
/Coding/18_range.py
425
4.1875
4
print("range(stop)") for num in range(10): print(num) #print 0 1 2 3 4 5 6 7 8 9 print("range(start,stop)") for num in range(3,10): print(num) #print 3 4 5 6 7 8 9 print("range(start, stop, step)") for num in range(1,10,2): print(num) #print 1 3 5 7 9 print("initialize in array using range operator") array_list = list(range(0,11,2)) #list function print(array_list) #print array_list(variable) 0 2 4 6 8 10
false
22c43c186b319a6cd29da32a948e6809e67a8cad
samdeanefox/tdd_class
/notestdd/_made_by_me/oop_overview.py
1,273
4.21875
4
"""OOP Overview Discuss the advantages and drawbacks of Object Oriented Programming in general and in Python """ ####################################################################### # Generalization/Specialization class Animal: def breathe(self): print('Animal is breathing') def play(self): print('Animal is playing') self.interact() def interact(self): print('Animal is interacting') class Dog(Animal): def interact(self): print('Dog is eating rats') bebe = Dog() bebe.interact() class Cat(Animal): def play(self): print('Cat is playing') self.interact() zena = Cat() ####################################################################### # The "real world" is not so neat class Circle: def bounding_box(self): "Return a square tangent to the circle at exactly four points" pass class Ellipse(Circle): "A kind of circle with a viewing angle" def bounding_box(self): raise NotImplementedError ####################################################################### # Multiple Inheritance class Car: trunk = 1 class Plane: wings = 2 class FlyingCar(Car, Plane): def steering_wheel_or_joystick_or_pedals(self): pass
true
abccf8ed5677b5c0dcbda592e435e5fced78d579
briabar/Katas
/lambdamapfilterreduce.py
1,135
4.15625
4
def square_it(number): return number ** 2 # LAMBDA FUNCTIONS first = lambda x: 2 * x second = lambda x, y: x + y third = lambda x,y: x if x > y else y print(first(3)) print(second(3,2)) print(third(1,2)) # MAP -- APPLY SAME FUNCTION TO EACH ELEMENT OF A SEQUENCE # RETURN MODIFIED LIST numbers = [4,3,2,1] def square_not_map(lst1): lst2 = [] for num in lst1: lst2.append(num ** 2) return lst2 print(square_not_map(numbers)) # THIS IS EQUAL TO..... print (list(map(lambda x: x**2, numbers))) #DOESN'T NEED TO BE A LAMBDA FUNCTION print (list(map(square_it, numbers))) # FILTER FUNCTION # FILTERS OUT ITEMS IN SEQUENCE n = [4,3,2,1] def over_two(lst1): lst2 = [x for x in lst1 if x > 2] return lst2 print(over_two(n)) #SAME AS... print(list(filter(lambda x: x > 2, n))) # REDUCE # APPLIES SAME OPERATION TO ITEMS OF A SEQUENCE # USES RESULT OF OPERATION AS FIRST PARAM OF NEXT OPERATION # RETURNS AN ITEM, NOT A LIST def mult(lst1): prod = lst1[0] for i in range(1,len(lst1)): prod *= lst1[i] return prod print(mult(n)) # SAME AS... print(reduce(lambda x,y: x*y, n))
true
04ee73dcd3048479f881681552c9184c31f26f57
PENGYUXIONG/DataStructutre-Practice-python
/dataStructure/queue/doubly_linked_list_deque.py
2,448
4.15625
4
class Node: def __init__(self, data): self.data = data self.prev = self.next = None class deque: def __init__(self, capacity): self.capacity = capacity self.front = self.rear = None def size(self): size = 0 cur_node = self.front while cur_node is not None: size = size + 1 cur_node = cur_node.next return size def insert_front(self, data): # deque is full condition if self.capacity == self.size(): print('deque is full, insertion failed') return new_node = Node(data) # deque is empty condition if self.front == None: self.front = self.rear = new_node else: self.front.prev = new_node new_node.next = self.front self.front = new_node def insert_last(self, data): # if the deque is full if self.capacity == self.size(): print('deque is full, insertion failed') return new_node = Node(data) # deque is empty condition if self.front == None: self.front = self.rear = new_node else: self.rear.next = new_node new_node.prev = self.rear self.rear = new_node def delete_front(self): # if the deque is empty if self.front == None: print('this is an empty queue, deletion failed') # if there is only one element in the queue elif self.front == self.rear: self.front = self.rear = None else: self.front = self.front.next self.front.prev = None def delete_last(self): # if the deque is empty if self.front == None: print('this is an empty queue, deletion failed') # if there is only one element elif self.front == self.rear: self.front = self.rear = None else: self.rear = self.rear.prev self.rear.next = None def get_front(self): if self.front is None: print('the deque is empty') return print(self.front.data) def get_rear(self): if self.front is None: print('the deque is empty') return print(self.rear.data) def erase(self): self.front = self.rear = None def display(self): data_list = [] cur_node = self.front while cur_node is not None: data_list.append(cur_node.data) cur_node = cur_node.next print(data_list) new_deque = deque(5) new_deque.display() new_deque.delete_front() new_deque.delete_last() new_deque.insert_last(-2) new_deque.insert_front(0) new_deque.insert_front(-1) new_deque.insert_last(1) new_deque.insert_last(2) new_deque.display() new_deque.delete_front() new_deque.display() new_deque.get_front() new_deque.get_rear() new_deque.erase() new_deque.display()
true
5a7a074fe68fef75b7d2f07787b1e9d48c836346
PENGYUXIONG/DataStructutre-Practice-python
/dataStructure/queue/linked_list_queue.py
1,478
4.125
4
class Node: def __init__(self, data): self.data = data self.next = None class linked_list_queue: def __init__(self, capacity): self.front = self.rear = None self.capacity = capacity def size(self): size = 0 cur_node = self.front while cur_node is not None: size = size + 1 cur_node = cur_node.next return size def enqueue(self, data): # empty queue condition if self.front == None: self.front = self.rear = Node(data) # full queue condition elif self.size() == self.capacity: print('this is full queue, enqueue failed!') else: new_node = Node(data) self.rear.next = new_node self.rear = new_node def dequeue(self): # empty queue condition if self.front == None: print('this is an empty queue, dequeue failed') # if there is ony one element inside the queue elif self.front == self.rear: self.front = self.rear = None else: self.front = self.front.next def display(self): # empty condition if self.front == None: print('this is an empty queue') else: data_list = [] cur_node = self.front while cur_node is not None: data_list.append(cur_node.data) cur_node = cur_node.next print(data_list) new_queue = linked_list_queue(5) print(new_queue.size()) new_queue.dequeue() new_queue.enqueue(1) new_queue.display() new_queue.enqueue(2) new_queue.enqueue(3) new_queue.enqueue(4) new_queue.enqueue(5) new_queue.enqueue(6) new_queue.display() new_queue.dequeue() new_queue.display()
true
4389b67d12b2aa4c9279e43310a17698aa749f22
nthnjustice/FletcherPythonWorkshop
/Round1/Conditionals.py
2,295
4.3125
4
a = 3 b = 1 if a == 3: print "a is equal to 3" #this statement will print ########################################################################### a = 3 b = 1 if a < 3: print "a is less than 3" #this statement will NOT print elif a <= 3: print "a is less than or equal to 3" #this statement will print ########################################################################### a = 3 b = 1 if a < 3: print "a is less than 3" #this statement will NOT print elif a == b: print "a is equal to b" #this statement will NOT print else: print "a is not less than 3 nor equal to b" #this statement will print ########################################################################### a = 3 b = 1 if a == 3: print "a is equal to 3" #this statement will print elif a == 1: print "a is equal to 1" #this statement will NOT print elif a == b: print "a is equal to b" #this statement will NOT print else: print "a is not equal to 3 nor 1" #this statement will NOT print ########################################################################### a = 3 b = 1 if a > b: print "a is greater than b" #this statement will print if b < a: print "b is less than a" #this statement will ALSO print #an 'if' statement can't have a parent 'if' statement #all if statements will run regardless of their order or arrangement relative #to other conditional statements ########################################################################### #compound conditionals can be built using 'and' and 'or' #'and' requires both epressions to hold true #'or' needs a minimum of one of the expressions to hold true a = 3 b = 1 if a > b and a == 3: print "a is greater than b and equal to 3" #this statement will print if a > b or a == b: print "a is either greater than b, equal to b, or both" #this will print ########################################################################### a = 3 b = 1 if a > b and a != b: a = 5 else: print "1" if a != 5 or a == 5: a = b elif a > b: b = 7 else: print "2" if a == b and a > 2: print "3" elif a > 0 and b > 0: b = a else: print "4" if a != b or a != 0: print "5" else: a = 5 b = 3 if a > b: print "6" else: print "7" #what will this print? - answer below: #5 #7
true
4ed7b59551dc7a3f9e891f0df93dd2fe5ba5187a
shashank4902/assignment-2-and-3
/prgm3 ass3.py
228
4.1875
4
3#prime or not num=int(input("enter a number")) i=2 count=0 while i<=num : if num%i==0 : count+=1 if count==2 : print("this number is not prime number") break i+=1 if count<=1 : print("this is prime number")
false
24fdff26499381d8f5d97d87b62cd0293bddb779
jeSoosRemirez/lessons
/3_lesson/calculator.py
938
4.25
4
def calculate(): operation = input(''' Type operation: + for addition - for subtraction * for multiplication / for division ''') num_1 = int(input('Type first number: ')) num_2 = int(input('Type second number: ')) if operation == '+': summary = num_1 + num_2 print(f'{num_1} + {num_2} = {summary}') elif operation == '-': summary = num_1 - num_2 print(f'{num_1} - {num_2} = {summary}') elif operation == '*': summary = num_1 * num_2 print(f'{num_1} * {num_2} = {summary}') elif operation == '/': summary = num_1 / num_2 print(f'{num_1} / {num_2} = {summary}') def again(): calc_again = input(''' If you want continue calculate type Y for Yes or N for No. ''') if calc_again.upper == 'Y': calculate() elif calc_again.upper == 'N': print('So long...') else: again() calculate()
false
0d919371825065554dcb9f443c3971a110c30313
GaryMOnline/CiscoDevNetPF
/Dictionaries.py
595
4.34375
4
#Used to add Dictionary Info dict = {"apples":5,"pears":12,"bananas":92} print dict #get length of Dictionary print ("Dict is {} long".value(len(dict))) #Add Value to dictiionary print "\nAdd Value to Dictionary" dict["strawberrys"]=32 print dict #Remove value from dictionary print "\nRemove Value from Dictionary" del dict["pears"] print dict #Test Dictionary if "carrot" in dict: print "There are no Carrots in Dict !!" else print "We have Carrots!!" #Loop through Dictionary print "\nLoop through Dictionary" for fruit,val in dict.items(): print "We have {} {}".value(val,fruit)
true
13d1b61b1c29f2955ae55458c3795046e9cd31ce
YashSaxena75/GME
/dice.py
422
4.25
4
import random print("So let us play another game,So are You ready!!!!") input("Press Enter if you are ready") die1=random.randint(1,6) #random.randrange() generates number between 0-5 so if I add 1 then the numbers will become (1-6) #if you want to start from 0 then use random.randrange() die2=random.randint(1,6) total=int(die1)+int(die2) print("Your total is:",total) input("You loose,press Enter to exit the game")
true
93854c23681f3a0baceb9ce0383b6120af2820a4
sunilkumarc/LearnPython
/day6/example9.py
475
4.21875
4
# Write a function which takes first_name and last_name as arguments # and return True if full name is 'Sunil Kumar' # otherwise return False def correct_name(first_name, last_name): if first_name == 'Sunil' and last_name == 'Kumar': return True return False def correct_name_2(first_name, last_name): full_name = first_name + ' ' + last_name if full_name == 'Sunil Kumar': return True return False res = correct_name('Sunil', 'Kumar') print(res)
true
a952d60f39b1ad6cd9b3ef923664a0cacb9d87ab
sunilkumarc/LearnPython
/day21/class.py
1,897
4.4375
4
''' 1. create employees 2. update employees with new salary 3. assign a computer to an employee ''' ''' Object Oriented Programming: ============================ - Python is a OOP language C, C++, Java, JavaScript, Python OOP: Python, Java, C++ Functional/Procedural: C, Scala ''' ''' Instead of using functions we will use classes in OOP. What is a class? A class is a blueprint for an actual entity in the real world. Example: Let's say we have an employee Employee: (properties) - name: "Sunil" - salary: 100.0 - desk_no: "1A" - id: 1 (functions to update employee) - change employee salary - change employee desk Car: - brand: "Mercedes" - color: "grey" - ground_clearance: 5ft Instead of representing them as dictionaries we use classes to represent real world entities ''' # Blueprint for creating employees class Employee: def __init__(self, name, salary, desk_no, id): self.name = name self.salary = salary self.desk_no = desk_no self.id = id def change_salary(self, new_salary): self.salary = new_salary def change_desk(self, new_desk): self.desk_no = new_desk ''' class definition a function defition We combine properties and functions to update those properties inside a single entity class ''' ''' class Person: def __init__(self, name, age, gender): pass def walk(self, steps): print("Person walked " + steps + " steps") def run(self, speed): print("Person is running at speed" + speed) self argument shoudl be passed as the first argument for every function that is definted within a class in Python. __init__ -> method is called 'constructor' constructor is basically a method which is called when an object is created. basically 'constructor' is just a fancy name for a special method '''
true
b00eec47f89547b0ec7c80113aa08f9320c8a908
wanghan79/2020_Master_Python
/2019102938梁梦瑶/FunctionExample.py
1,912
4.21875
4
##!/usr/bin/python3 """ Author: liangmengyao Purpose: Function Example Created: 4/18/2020 """ import random import string def dataSampling(datatype, datarange, num, strlen=6): # 固定参数;可变参数arg*;默认参数;关键字参数**kwargs ''' :Description: function... :param datatype: input the type of data :param datarange: input the range of data, a iterable data object :param num: the number of data :return: a set of sampling data ''' try: result = set() if datatype is int: while(len(result)!=num): it = iter(datarange) item = random.randint(next(it), next(it)) result.add(item) elif datatype is float: while (len(result) != num): result.add(random.uniform(1, 10)) elif datatype is str: while (len(result) != num): item = ''.join(random.SystemRandom().choice(datarange) for _ in range(strlen)) result.add(item) else: pass except: print("error") finally: return result def dataScreening(dataset, condition): try: result=set() for i in dataset: if type(i)==int or type(i)==float: if i>=condition[0] and i<=condition[1]: result.add(i) elif type(i)==str: if condition[2] in i: result.add(i) except: print("error") finally: return result def apply(): result = dataSampling(int, (1,100), 100) result.symmetric_difference_update(dataSampling(float,(1,100),100)) length=random.randint(1,10) result.symmetric_difference_update(dataSampling(str,string.ascii_letters+string.digits,1000,length)) print(result) print() result1=dataScreening(result,(1,10,"at")) print(result1) apply()
true
69c0183448bc716775307137a57d209283eb29b8
nicklausdporter/Daily_Short_Projects
/Age_Calc.py
822
4.28125
4
#age_calculator name = input("Please enter your name: ") while True: birth_year = input("What year were you born? ") try: birth_year = int(birth_year) except: ValueError print("Please enter a number") continue else: break current_year = 2019 age = current_year - birth_year turn_25 = (25-age) + current_year turn_50 = (50 - age) + current_year turn_75 = (75 - age) + current_year turn_100 = (100 - age) + current_year if turn_25 > current_year: print(f"Hey! {name} will turn 25 in {turn_25}") if turn_50 > current_year: print(f"Hey! {name} will turn 50 in {turn_50}") if turn_75 > current_year: print(f"Hey! {name} will turn 75 in {turn_75}") if turn_100 > current_year: print(f"Hey! {name} will turn 100 in {turn_100}") if age > 100: print(f"Wow! {name} you are {age}!!! Are you actually Nicholas Flamel?")
false
00f4a82b39204779596c1b0a060a311c1a1d182b
ksaubhri12/ds_algo
/practice_450/binary_tree/13_check_tree_balanced_or_not.py
1,785
4.125
4
# Do three things in recursive manner # check if left portion is valid and return the height # check if right portion is valid and return the height # now check the diff between height is less than or equal to one and also check if the left and right portion is valid # or not. If the height diff is okay and left and right constraint are also okay then return the height of this node # and true else false from Node import Node def check_balanced_tree(root: Node): get_height_bal = check_balanced_tree_util(root) return get_height_bal[1] def check_balanced_tree_util(root: Node): if root is None: return [0, True] left_tree_check_height_bal = check_balanced_tree_util(root.left) right_tree_check_height_bal = check_balanced_tree_util(root.right) left_tree_check_height = left_tree_check_height_bal[0] left_tree_check_bal = left_tree_check_height_bal[1] right_tree_check_height = right_tree_check_height_bal[0] right_tree_check_bal = right_tree_check_height_bal[1] height_diff = abs(left_tree_check_height - right_tree_check_height) if height_diff <= 1 and right_tree_check_bal and left_tree_check_bal: return [1 + max(left_tree_check_height, right_tree_check_height), True] else: return [1 + max(left_tree_check_height, right_tree_check_height), False] if __name__ == '__main__': node_1 = Node(1) node_2 = Node(39) node_3 = Node(10) node_4 = Node(5) node_1.left = node_2 node_1.right = node_3 node_2.left = node_4 print(check_balanced_tree(node_1)) anode_1 = Node(1) anode_2 = Node(10) anode_3 = Node(5) anode_1.left = anode_2 anode_2.left = anode_3 print(check_balanced_tree(anode_1)) # 1 # / \ # 10 # 39 # / # 5
true
22fb2cc3ef82831bfff2faec0b430acb22a7b745
ksaubhri12/ds_algo
/practice_450/linkedlist/33_seggregate_even_odd.py
1,339
4.15625
4
from Node import Node from LinkedList import LinkedList def seggregate_even_odd(head: Node): even = None odd = None e = None o = None while head is not None: data = head.data if data % 2 == 0: if even is None: even = head e = head else: e.next = head e = e.next else: if odd is None: odd = head o = head else: o.next = head o = o.next head = head.next if e is not None: e.next = odd if o is not None: o.next = None if even is not None: return even else: return odd if __name__ == '__main__': node_1 = Node(12) node_2 = Node(15) node_3 = Node(10) node_4 = Node(11) node_5 = Node(5) node_6 = Node(6) node_7 = Node(2) node_8 = Node(3) node_1.next = node_2 node_2.next = node_3 node_3.next = node_4 node_4.next = node_5 node_5.next = node_6 node_6.next = node_7 node_7.next = node_8 print('Current Linked List') LinkedList(node_1).print_linked_list() print('Segregating and printing') new_head_node = seggregate_even_odd(node_1) LinkedList(new_head_node).print_linked_list()
false
8b47bd7cb699a728630e861bde2372622b4c71b3
charlenecalderon/Girls_Who_Code
/carnival.py
1,999
4.375
4
print("Welcome to The Carnival!") print("BIG RIDES ARE 7 TICKETS (bumper cars, carousel)") print("SMALL RIDES ARE 3 TICKETS (slide, train ride)") print("You have 15 tickets to spend.") choosingRide = True tickets = 15 while choosingRide == True: print("Which ride would you like go on?") rideChoice = input() if(rideChoice == "bumper cars"): print("Good Choice! Have a crashing time!!") tickets = tickets - 7 if tickets < 3: print("WAIT !!! Sorry, you don't have enough tickets... BUT you can get a prize at the prize booth.") exit() print("You have %d left." %(tickets)) print("Would you like to ride another ride?") answer = input() if answer == "no": print("GOOD-BYE") choosingRide = False elif(rideChoice == "carousel"): print("Great Choice! Don't fall!") tickets = tickets - 7 if tickets < 3: print("WAIT !!! Sorry, you don't have enough tickets... BUT you can get a prize at the prize booth.") exit() print("You have %d left." %(tickets)) print("Would you like to ride another ride?") answer = input() if answer == "no": print("GOOD-BYE") choosingRide = False elif(rideChoice == "slide"): print("Have Fun!") tickets = tickets - 3 if tickets < 3: print("WAIT !!! Sorry, you don't have enough tickets... BUT you can get a prize at the prize booth.") exit() print("You have %d left." %(tickets)) print("Would you like to ride another ride?") answer = input() if answer == "no": print("GOOD-BYE") choosingRide = False else: print("Sorry that is not an option. Pick again")
true
2ca54b6d8384140b07722bfa8b5ebd877e02b45b
cenk314315/patikadev_pythontemel_project_odev
/flatten.py
971
4.28125
4
input = [[1,'a',['cat'],2],[[[3]],'dog'],4,5] result = [] #tüm elemanları sırayla boş bir listenin içerisine aktaracağız. #bunun için for döngüsü kullanacağız. #****************************************************** #we will transfer all the elements in order into an empty list. We will use a for loop for this. def flatten_list(lists): #list tipinde olmayan tüm elemanları boş listeye aktarıyoruz. #************************************************************** #We transfer all elements that are not of type list to the empty list.""" for i in lists: if type(i) != list: result.append(i) #liste tipinde olanları için fonksiyonu tekrar çağırıyoruz. #************************************************************ #We call the function again for the list type ones. else: flatten_list(i) return result print("input: ", input) print("sonuc: ",flatten_list(input))
false
7221bd81ec2b1e1395bab53f7f1a25731cc5a515
bea03/learnpythonhardway3
/ex20.py
982
4.125
4
#ex20 functions files #this line allows us to use argv (variables in script line) from sys import argv #this line assigns argv script, input_file = argv #this line defines a function called print_all() that takes in an arg f def print_all(f): #this line prints what is passed into print_all by reading the file print(f.read()) #this function starts back at beginning at char[0] def rewind(f): f.seek(0) #this function prints a line within the file def print_a_line(line_count, f): print(line_count, f.readline()) #assigns current_file to the input_file current_file = open(input_file) print("first let's print the whole file:\n") print_all(current_file) print("now let's rewind like a tape.") rewind(current_file) print("now let's print 3 lines:") current_line = 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file)
true
1abcf2eaa0e8d7c7781697cb320a3fcc53eedd50
andbra16/CSF
/F13/homework6/hw6.py
1,964
4.3125
4
# Name: Brandon Anderson # Evergreen Login: andbra16 # Computer Science Foundations # Programming as a Way of Life # Homework 6 # You may do your work by editing this file, or by typing code at the # command line and copying it into the appropriate part of this file when # you are done. When you are done, running this file should compute and # print the answers to all the problems. ### ### Problem 3 ### # DO NOT CHANGE THE FOLLOWING LINE print "Problem 3 solution follows:" a=2 b=3 #assert a==b # the assert statement makes a boolean statement: # if your assertion is true, the program runs. # if your assertion is false, the program gets an # assertion error. ### ### Problem 4 ### # DO NOT CHANGE THE FOLLOWING LINE print "Problem 4 solution follows:" def add(x, y): numbSum= x+y return numbSum total= add(a,b) print total # You can identify a function if you see a variable # that has arguments that need to be passed to it # (anything with a name and parenthesis that take arguments) # For example: a(x, y), sum(a, b, c, d) would be functions ### ### Problem 5 ### # DO NOT CHANGE THE FOLLOWING LINE print "Problem 5 solution follows:" v={"a": a, "b": b} assert v=={"a":2, "b":3} ### ### Problem 6 ### # DO NOT CHANGE THE FOLLOWING LINE print "Problem 6 solution follows:" v2={} v2["a"]=a v2["b"]=b assert v==v2 # this method allows you to add new keys/values to the existing dictionary # without having to type out the whole dictionary again with the new key # For example: v={"a": a, "b": b} if i want to add c, I could just do # v["c"]= 4 instead of typing out the whole dictionary of # v={"a": a, "b": b, "c": 4} ### ### Problem 7 ### # DO NOT CHANGE THE FOLLOWING LINE print "Problem 7 solution follows:" for keys in v: print keys print v[keys] # k is all the keys in the dictionary and dictionary["k"] is all the # values for the keys in the dictionary. ### ### Collaboration ### # ... Andrew Loewen (loeand16) # ...
true
7318bec8ea515888fe26cb33f21bd1a0c26b5f05
asadrazaa1/Python-Practice
/tuple_operations_everything_recursive.py
516
4.1875
4
tup1 = ("11", "12", "13", "14", "15") tup2 = (1, 2, 3, 4, 5) tup3 = 'a', 'b', 'c', 'd', 'e' #empty tuple is written with empty parantheses tuple = () #for a single valued tuple, you have to add a comma after the element tup4 = (20, ) #acessing values within the tuple print(tup1[0]) print(tup1[1:4]) print(tup1[:3]) #updating values within the tuple is not possible, tuple are solid state object tup5 = tup1 + tup2 #deleting any element from the tuple del tup1 print(max(tup2)) print(min(tup2)) print(len(tup2))
true
6674c1998f2e0fe2c861186d9589b44a6ce7c8bf
Koutarouu/HackerRank-Algorithms
/ReverseDoubly.py
1,474
4.21875
4
class DoublyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None self.prev = None class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, node_data): node = DoublyLinkedListNode(node_data) if not self.head: self.head = node else: self.tail.next = node node.prev = self.tail self.tail = node def print_doubly_linked_list(node): while node: print(node.data, end=' ') if node.prev: print("link prev: {} ".format(node.prev.data)) if node.next: print("link next: {} ".format(node.next.data)) node = node.next def reverse(head): a=head r=a.prev while a: t = a.next a.prev=a.next a.next = r r = a a = t return r def Reverse(head): if head == None: return head head.next, head.prev = head.prev, head.next if head.prev == None: return head return Reverse(head.prev) #b=head #return b if in the print function you move along node.prev for _ in range(int(input())): llist_count = int(input()) llist = DoublyLinkedList() for _ in range(llist_count): llist_item = int(input()) llist.insert_node(llist_item) llist.head = reverse(llist.head) print_doubly_linked_list(llist.head) """ sample: 1 4 1 2 3 4 4 link next: 3 3 link prev: 4 link next: 2 2 link prev: 3 link next: 1 1 link prev: 2 """
false
39a0126c4dcad38eebb2ed87d48229e513290698
Wojtek001/Dictionary-for-a-little-programmer-
/dictionary_done.py
2,152
4.21875
4
import sys import csv import os def main(): with open("dictionary.csv", mode='r') as infile: reader = csv.reader(infile) my_dict = {rows[0]: (rows[1], rows[2]) for rows in reader} os.system('clear') print('Dictionary for a little programmer:') print('1 - search explanation by appellation') print('2 - add new definition') print('3 - show all appellations alphabetically') print('0 - exit') numbers = ['1', '2', '3', '0'] chosen_number = input("Enter selected number from the list above: ") while chosen_number not in numbers: print ('Invalid number!') chosen_number = input("Enter correct number from the list above: ") if chosen_number == '1': os.system('clear') appelation = input("Enter an appelation: ").upper() if appelation in my_dict: def_source = ' '.join(my_dict[appelation]) print(def_source) elif appelation not in my_dict: os.system('clear') print("No such appellation in a dictionary. Try again.") menu_return() elif chosen_number == '2': os.system('clear') add_appelation = input('Enter new appelation: ').upper() add_explanation = input('Enter explanation: ') add_source = input('Enter a source: ') with open('dictionary.csv', 'a', newline='') as csvfile: new_appelation = ', '.join([add_appelation, add_explanation, add_source]) new_appel = open("dictionary.csv", 'a') new_appel.write(new_appelation) new_appel.write("\n") new_appel.close menu_return() elif chosen_number == '3': os.system('clear') dict_alphabet = sorted(my_dict) for i in dict_alphabet: print (i) menu_return() elif chosen_number == '0': print('See You later!') sys.exit() def menu_return(): decision = input("Press 'q' to quit program or to come back to the main menu - press any other key: ").lower() if decision == "q": print('See You later!') sys.exit() else: main() main()
true
63e96b41906f49f557529a0815da7314d74f6c33
burke3601/Digital-Crafts-Classes
/medium_exercises/box.py
594
4.21875
4
width,height = int(input("Width? ")), int(input("Height? ")) on_row = 0 while on_row <= height: if on_row == 0 or on_row == height: print("*"*width) else: stars = "*" + " "*(width-2) + "*" print(stars) on_row += 1 # height = 0 # width = 0 # while True: # try: # height = int(input("Height? \n")) # width = int(input("width? \n")) # break # except ValueError: # print("choose an integer") # print("* " * width) # while height > 0: # print(f"* " + " " * {width} + " *") # height -+ 1 # print("* " * width)
false
a8f28d8ff664a6b70e96bb10f84edd44be0d2704
burke3601/Digital-Crafts-Classes
/medium_exercises/coins.py
335
4.25
4
coins = 0 print(f"You have {coins} coins.") more = input("would you like another coin? yes or no \n") while more == "yes": coins += 1 print(f"You have {coins} coins.") more = input("would you like another coin? yes or no \n") if more == "no": coins == coins print("bye.") # not sure why this is infinite bye
true
85e910db7967241f540ed3d3fd88e508341aa1fa
burke3601/Digital-Crafts-Classes
/small-exercises/hello2.py
210
4.15625
4
name = str(input("WHAT IS YOUR NAME?\n")) number = len(name) print(f"Hello your name is {name.upper}") print(f"Your name has {number} letters in it! Awesome!") # not sure why this isn't returning upper case
true
ab50abbc1aaf2ef28251cde266ff7bbf8b2f8af5
juggal/99problems
/p04.py
646
4.28125
4
# Find the number of elements of a list from linked_list.sll import sll def count_elements(ll): """ calculate length of linked list Parameters ---------- ll: sll linked list on which to be operated on Returns ------- int length of linked list """ curr = ll.head length = 1 while curr.link != None: length += 1 curr = curr.link return length def main(): values = input("Enter elements:").split() ll = sll() for elem in values: ll.insert(elem) result = count_elements(ll) print(result) if __name__ == "__main__": main()
true
fe2a6a6318f8c509a9e7ffaed6332cab63036b61
Asunqingwen/LeetCode
/easy/Height Checker.py
1,204
4.375
4
# -*- coding: utf-8 -*- # @Time : 2019/8/23 0023 9:37 # @Author : 没有蜡笔的小新 # @E-mail : sqw123az@sina.com # @FileName: Height Checker.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Asunqingwen # @GitHub :https://github.com/Asunqingwen """ Students are asked to stand in non-decreasing order of heights for an annual photo. Return the minimum number of students not standing in the right positions.  (This is the number of students that must move in order for all students to be standing in non-decreasing order of height.)   Example 1: Input: [1,1,4,2,1,3] Output: 3 Explanation: Students with heights 4, 3 and the last 1 are not standing in the right positions.   Note: 1 <= heights.length <= 100 1 <= heights[i] <= 100 """ from typing import List def heightChecker(heights: List[int]) -> int: count_list = [0] * 101 for height in heights: count_list[height] += 1 i = 0 count = 0 for j in range(101): while count_list[j] > 0: if heights[i] != j: count += 1 i += 1 count_list[j] -= 1 return count if __name__ == '__main__': input = [2, 6, 8, 6, 5, 2, 4, 3, 7, 3, 7, 5, 6, 6, 2, 4, 4, 6, 8, 4, 5] output = heightChecker(input) print(output)
true
1944be3fbcd30de7259ba49b9f82c2c7d769083f
Asunqingwen/LeetCode
/medium/Print FooBar Alternately.py
2,523
4.46875
4
# -*- coding: utf-8 -*- # @Time : 2019/9/2 0002 16:39 # @Author : 没有蜡笔的小新 # @E-mail : sqw123az@sina.com # @FileName: Print FooBar Alternately.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Asunqingwen # @GitHub :https://github.com/Asunqingwen """ Suppose you are given the following code: class FooBar { public void foo() {     for (int i = 0; i < n; i++) {       print("foo");   } } public void bar() {     for (int i = 0; i < n; i++) {       print("bar");     } } } The same instance of FooBar will be passed to two different threads. Thread A will call foo() while thread B will call bar(). Modify the given program to output "foobar" n times.   Example 1: Input: n = 1 Output: "foobar" Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar(). "foobar" is being output 1 time. """ from threading import Thread, Condition, Lock def Foo(): print('foo', end='') def Bar(): print('bar', end='') class FooBar1: def __init__(self, n): self.n = n self.flag = True self.cd = Condition() def foo(self, printFoo: 'Callable[[], None]') -> None: for i in range(self.n): # printFoo() outputs "foo". Do not change or remove this line. self.cd.acquire() while not self.flag: self.cd.wait() printFoo() self.flag = False self.cd.notify_all() self.cd.release() def bar(self, printBar: 'Callable[[], None]') -> None: for i in range(self.n): # printBar() outputs "bar". Do not change or remove this line. self.cd.acquire() while self.flag: self.cd.wait() printBar() self.flag = True self.cd.notify_all() self.cd.release() class FooBar2: def __init__(self, n): self.n = n self.flag = True self.mutex1 = Lock() self.mutex2 = Lock() self.mutex2.acquire() def foo(self, printFoo: 'Callable[[], None]') -> None: for i in range(self.n): # printFoo() outputs "foo". Do not change or remove this line. self.mutex1.acquire() printFoo() self.mutex2.release() def bar(self, printBar: 'Callable[[], None]') -> None: for i in range(self.n): # printBar() outputs "bar". Do not change or remove this line. self.mutex2.acquire() printBar() self.mutex1.release() if __name__ == '__main__': n = 5 foobar = FooBar2(n) call_list = [foobar.foo, foobar.bar] call_args = [Foo, Bar] t1 = Thread(target=call_list[0], args=(call_args[0],)) t2 = Thread(target=call_list[1], args=(call_args[1],)) t1.start() t2.start()
true
d340ab735fcd78494df1ba2df13ce3bf7102e16f
Asunqingwen/LeetCode
/easy/Word Pattern.py
1,014
4.375
4
# -*- coding: utf-8 -*- # @Time : 2019/8/29 0029 15:32 # @Author : 没有蜡笔的小新 # @E-mail : sqw123az@sina.com # @FileName: Word Pattern.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Asunqingwen # @GitHub :https://github.com/Asunqingwen """ Given a pattern and a string str, find if str follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. Example 1: Input: pattern = "abba", str = "dog cat cat dog" Output: true Notes: You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space. 企业:Affirm 优步 太平人寿 标签:哈希表 """ def wordPattern(pattern: str, str: str) -> bool: str_list = str.split(' ') return list(map(pattern.index, pattern)) == (list(map(str_list.index, str_list))) if __name__ == '__main__': pattern = "abba" str = "dog cat cat dog" result = wordPattern(pattern, str) print(result)
true
bb7607255cb02f40e6d7577ef1ed9f75c944292e
Asunqingwen/LeetCode
/简单/矩形重叠.py
1,187
4.15625
4
''' 矩形以列表 [x1, y1, x2, y2] 的形式表示,其中 (x1, y1) 为左下角的坐标,(x2, y2) 是右上角的坐标。矩形的上下边平行于 x 轴,左右边平行于 y 轴。 如果相交的面积为 正 ,则称两矩形重叠。需要明确的是,只在角或边接触的两个矩形不构成重叠。 给出两个矩形 rec1 和 rec2 。如果它们重叠,返回 true;否则,返回 false 。   示例 1: 输入:rec1 = [0,0,2,2], rec2 = [1,1,3,3] 输出:true 示例 2: 输入:rec1 = [0,0,1,1], rec2 = [1,0,2,1] 输出:false 示例 3: 输入:rec1 = [0,0,1,1], rec2 = [2,2,3,3] 输出:false   提示: rect1.length == 4 rect2.length == 4 -109 <= rec1[i], rec2[i] <= 109 rec1[0] <= rec1[2] 且 rec1[1] <= rec1[3] rec2[0] <= rec2[2] 且 rec2[1] <= rec2[3] ''' from typing import List class Solution: def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool: return min(rec1[2], rec2[2]) > max(rec1[0], rec2[0]) and min(rec1[3], rec2[3]) > max(rec1[1], rec2[1]) if __name__ == '__main__': rec1 = [0, 0, 2, 2] rec2 = [1, 1, 3, 3] sol = Solution() print(sol.isRectangleOverlap(rec1, rec2))
false
3f69de1e48f7729f90ca74fe5f75b98e00584c10
Asunqingwen/LeetCode
/easy/Largest Perimeter Triangle.py
980
4.1875
4
# -*- coding: utf-8 -*- # @Time : 2019/10/9 0009 9:48 # @Author : 没有蜡笔的小新 # @E-mail : sqw123az@sina.com # @FileName: Largest Perimeter Triangle.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Asunqingwen # @GitHub :https://github.com/Asunqingwen """ Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths. If it is impossible to form any triangle of non-zero area, return 0.   Example 1: Input: [2,1,2] Output: 5 Example 2: Input: [1,2,1] Output: 0 Example 3: Input: [3,2,3,4] Output: 10 Example 4: Input: [3,6,2,3] Output: 8   Note: 3 <= A.length <= 10000 1 <= A[i] <= 10^6 """ from typing import List def largestPerimeter(A: List[int]) -> int: A.sort(reverse=True) for i in range(2, len(A)): if A[i - 1] + A[i] > A[i - 2]: return A[i] + A[i - 1] + A[i - 2] return 0 if __name__ == '__main__': A = [1, 2, 1] result = largestPerimeter(A) print(result)
true
ccf914675bb33ca164414b3b9913ca45fa5073d0
Asunqingwen/LeetCode
/easy/Jewels and Stones.py
1,034
4.125
4
# -*- coding: utf-8 -*- # @Time : 2019/8/13 0013 14:58 # @Author : 没有蜡笔的小新 # @E-mail : sqw123az@sina.com # @FileName: Jewels and Stones.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Asunqingwen # @GitHub :https://github.com/Asunqingwen """ You're given strings J representing the types of stones that are jewels, and S representing the stones you have.  Each character in S is a type of stone you have.  You want to know how many of the stones you have are also jewels. The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". Note: S and J will consist of letters and have length at most 50. The characters in J are distinct. """ def numJewelsInStones(J: str, S: str) -> int: j_dict = {} count = 0 for j in J: j_dict[j] = 0 for s in S: if s in j_dict: count += 1 return count if __name__ == '__main__': J = "z" S = "ZZ" result = numJewelsInStones(J, S) print(result)
true
ef581fc5fdec8061ca47abeff0c4d9add1e76622
Asunqingwen/LeetCode
/easy/Ugly Number.py
1,604
4.375
4
# -*- coding: utf-8 -*- # @Time : 2019/9/19 0019 10:20 # @Author : 没有蜡笔的小新 # @E-mail : sqw123az@sina.com # @FileName: Ugly Number.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Asunqingwen # @GitHub :https://github.com/Asunqingwen """ Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. Example 1: Input: 6 Output: true Explanation: 6 = 2 × 3 Example 2: Input: 8 Output: true Explanation: 8 = 2 × 2 × 2 Example 3: Input: 14 Output: false Explanation: 14 is not ugly since it includes another prime factor 7. Note: 1 is typically treated as an ugly number. Input is within the 32-bit signed integer range: [−231,  231 − 1]. """ # 内存超标 def isUgly(num: int) -> bool: if num <= 0: return False ans = [1] * (num + 1) ans[1] = 0 for i in range(1, num + 1): if not ans[i]: if i * 2 <= num: ans[i * 2] = 0 if i * 3 <= num: ans[i * 3] = 0 if i * 5 <= num: ans[i * 5] = 0 return ans[num] == 0 # 超时 def isUgly1(num: int) -> bool: if num <= 0: return False ans = set() ans.add(1) res = {1: 1} while ans: tmp = ans.pop() for i in [2, 3, 5]: mul = tmp * i if mul <= num: res[mul] = mul ans.add(mul) return num in res def isUgly2(num: int) -> bool: if num <= 0: return False while num != 1: if num % 2 == 0: num /= 2 elif num % 3 == 0: num /= 3 elif num % 5 == 0: num /= 5 else: return False return True if __name__ == '__main__': num = 1000000 result = isUgly2(num) print(result)
true
dc23b3b72329168a7168779480589df6a625c786
Asunqingwen/LeetCode
/easy/Armstrong Number.py
897
4.34375
4
# -*- coding: utf-8 -*- # @Time : 2019/10/22 0022 17:29 # @Author : 没有蜡笔的小新 # @E-mail : sqw123az@sina.com # @FileName: Armstrong Number.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Asunqingwen # @GitHub :https://github.com/Asunqingwen """ The k-digit number N is an Armstrong number if and only if the k-th power of each digit sums to N. Given a positive integer N, return true if and only if it is an Armstrong number.   Example 1: Input: 153 Output: true Explanation: 153 is a 3-digit number, and 153 = 1^3 + 5^3 + 3^3. Example 2: Input: 123 Output: false Explanation: 123 is a 3-digit number, and 123 != 1^3 + 2^3 + 3^3 = 36.   Note: 1 <= N <= 10^8 """ def isArmstrong(N: int) -> bool: S = str(N) size = len(S) ans = 0 for ss in S: ans += int(ss) ** size return ans == N if __name__ == '__main__': N = 153 result = isArmstrong(N) print(result)
true
ad7c1cefea6607deeef015dbd2ea630df92794d7
Asunqingwen/LeetCode
/medium/Bulb Switcher II.py
1,101
4.15625
4
# -*- coding: utf-8 -*- # @Time : 2019/9/18 0018 9:07 # @Author : 没有蜡笔的小新 # @E-mail : sqw123az@sina.com # @FileName: Bulb Switcher II.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Asunqingwen # @GitHub :https://github.com/Asunqingwen """ There is a room with n lights which are turned on initially and 4 buttons on the wall. After performing exactly m unknown operations towards buttons, you need to return how many different kinds of status of the n lights could be. Suppose n lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons are given below: Flip all the lights. Flip lights with even numbers. Flip lights with odd numbers. Flip lights with (3k + 1) numbers, k = 0, 1, 2, ...   Example 1: Input: n = 1, m = 1. Output: 2 Explanation: Status can be: [on], [off] """ def flipLights(n: int, m: int) -> int: if n == 0 or m == 0: return 1 if n == 1: return 2 if n == 2: return 3 if m == 1 else 4 if m == 1: return 4 if m == 2: return 7 return 8 if __name__ == '__main__': n = 2 m = 1 result = flipLights(n, m) print(result)
true
00aede6b2fa2d8a06e12cefca11a73504b510b7c
Asunqingwen/LeetCode
/medium/Strobogrammatic Number II.py
1,021
4.375
4
# -*- coding: utf-8 -*- # @Time : 2019/10/9 0009 17:45 # @Author : 没有蜡笔的小新 # @E-mail : sqw123az@sina.com # @FileName: Strobogrammatic Number II.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Asunqingwen # @GitHub :https://github.com/Asunqingwen """ A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. Example: Input: n = 2 Output: ["11","69","88","96"] """ from typing import List def findStrobogrammatic(n: int) -> List[str]: def helper(n): if n <= 0: return [''] if n == 1: return ['0', '1', '8'] ans = [] for i in helper(n - 2): ans.append('0' + i + '0') ans.append('1' + i + '1') ans.append('6' + i + '9') ans.append('8' + i + '8') ans.append('9' + i + '6') return ans res = [] for i in helper(n): if len(str(int(i))) == n: res.append(i) return res if __name__ == '__main__': n = 2 result = findStrobogrammatic(n) print(result)
false
115b8c6a3d4839acce2b3b720f9854f83499a864
Asunqingwen/LeetCode
/easy/Reverse String II.py
1,029
4.3125
4
# -*- coding: utf-8 -*- # @Time : 2019/9/17 0017 10:52 # @Author : 没有蜡笔的小新 # @E-mail : sqw123az@sina.com # @FileName: Reverse String II.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Asunqingwen # @GitHub :https://github.com/Asunqingwen """ Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original. Example: Input: s = "abcdefg", k = 2 Output: "bacdfeg" Restrictions: The string consists of lower English letters only. Length of the given string and k will in the range [1, 10000] """ def reverseStr(s: str, k: int) -> str: s = list(s) for i in range(0, len(s), 2 * k): s[i:i + k] = reversed(s[i:i + k]) return ''.join(s) if __name__ == '__main__': s = "abcdefgh" k = 3 result = reverseStr(s, k) print(result)
true
66d868b1c698beceb3ca2bcecbb60d823984748b
Asunqingwen/LeetCode
/medium/3Sum Closest.py
1,144
4.125
4
# -*- coding: utf-8 -*- # @Time : 2019/9/19 0019 14:27 # @Author : 没有蜡笔的小新 # @E-mail : sqw123az@sina.com # @FileName: 3Sum Closest.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Asunqingwen # @GitHub :https://github.com/Asunqingwen """ Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example: Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). """ from typing import List def threeSumClosest(nums: List[int], target: int) -> int: nums.sort() res = nums[0] + nums[1] + nums[2] for n in range(len(nums)): i, j = n + 1, len(nums) - 1 while i < j: tmp = sum([nums[n], nums[i], nums[j]]) if abs(tmp - target) < abs(res - target): res = tmp if tmp > target: j -= 1 elif tmp < target: i += 1 else: return res return res if __name__ == '__main__': nums = [-1, 2, 1, -4] target = 1 result = threeSumClosest(nums, target) print(result)
true
003d5d307e18c53534ff299db8922400f1324409
Asunqingwen/LeetCode
/easy/Pascal's Triangle.py
750
4.21875
4
# -*- coding: utf-8 -*- # @Time : 2019/8/6 0006 15:15 # @Author : 没有蜡笔的小新 # @E-mail : sqw123az@sina.com # @FileName: Pascal's Triangle.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Asunqingwen # @GitHub :https://github.com/Asunqingwen """ Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it. """ from typing import List def generate(numRows: int) -> List[List[int]]: if not numRows: return [] nums = [[1]] for i in range(1, numRows): num = [1] + [sum(nums[-1][j:j + 2]) for j in range(i)] nums.append(num) return nums if __name__ == '__main__': m = 3 result = generate(m) print(result)
true