blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
417cee561eca1a812b20161454756a737e62ff16
weiyuyan/LeetCode
/LeetCode周赛/5316. 竖直打印单词.py
1,359
4
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # author:ShidongDu time:2020/1/19 ''' 显示英文描述 用户通过次数615 用户尝试次数662 通过次数619 提交次数1066 题目难度Medium 给你一个字符串 s。请你按照单词在 s 中的出现顺序将它们全部竖直返回。 单词应该以字符串列表的形式返回,必要时用空格补位,但输出尾部的空格需要删除(不允许尾随空格)。 每个单词只能放在一列上,每一列中也只能有一个单词。 示例 1: 输入:s = "HOW ARE YOU" 输出:["HAY","ORO","WEU"] 解释:每个单词都应该竖直打印。 "HAY" "ORO" "WEU" 示例 2: 输入:s = "TO BE OR NOT TO BE" 输出:["TBONTB","OEROOE"," T"] 解释:题目允许使用空格补位,但不允许输出末尾出现空格。 "TBONTB" "OEROOE" " T" 示例 3: 输入:s = "CONTEST IS COMING" 输出:["CIC","OSO","N M","T I","E N","S G","T"] 提示: 1 <= s.length <= 200 s 仅含大写英文字母。 题目数据保证两个单词之间只有一个空格。 ''' # 噗,爷不管了爷先去赶火车了嚯嚯嚯 # from typing import List # class Solution: # def printVertically(self, s: str) -> List[str]: # # if __name__ == '__main__': # solution = Solution() # res = solution.printVertically('hhh 12 2') # print(res) # print()
b13fdaa352aa8b7fda9f24c621710357ab20fd2e
Ottispottis/Unzipper-zipper-with-python-and-tkinter
/coolunzip.py
2,410
3.78125
4
""" Zipper/Unzipper Author: Otto Heldt Version 1.0 Known issue is that when zipping a file from a directory that isn't the same directory where the script is located the program creates empty folders inside the zip according to the path where the file that is zipped was located. This is due to the way ZipFiles write works and I haven't figured out how I could deal with this yet. """ import tkinter as tk import zipfile from tkinter.filedialog import askopenfile from PIL import Image, ImageTk import os root = tk.Tk() canvas = tk.Canvas(root, width=350, height=400) canvas.grid(columnspan=4, rowspan=4) instructions = tk.Label(root, text="Select a file B)", font="Raleway") instructions.grid(columnspan=3, column=0, row=1) # Placing logo to tkinter window logo = Image.open("cool.png") logo = ImageTk.PhotoImage(logo) logo_label = tk.Label(image=logo) logo_label.image = logo logo_label.grid(column=1, row=0) def zip_file(): file = askopenfile(parent=root, mode="rb", filetype=[("Zip file", "*.zip")]) if file: unzipping = zipfile.ZipFile(file) unzipping.extractall("S:\pythonstuff") # Location where the files will be unzipped, change this to any directory you like unzipping.close() text = "File extracted" textbox = tk.Text(root, height=2, width=11, padx=15, pady=10, font="Raleway") textbox.insert(1.0, text) textbox.grid(column=1, row=4) def unzip_file(): file2 = askopenfile(parent=root, mode="rb") name = os.path.basename(file2.name) print(name) name = name + ".zip" if file2: zipping = zipfile.ZipFile(name, 'w') zipping.write(file2.name) zipping.close() text2 = "File zipped" textbox2 = tk.Text(root, height=2, width=11, padx=15, pady=10, font="Raleway") textbox2.insert(1.0, text2) textbox2.grid(column=1,row=4) # creating buttons for zipping and unzipping unzip_str = tk.StringVar() unzip_btn = tk.Button(root, textvariable=unzip_str, command=lambda:zip_file(), font="Raleway", bg="#20bebe", fg="white", height=2, width=30) unzip_str.set("Unzip a file B)") unzip_btn.grid(column=1, row=2) zip_str = tk.StringVar() zip_btn = tk.Button(root, textvariable=zip_str, command=lambda:unzip_file(), font="Raleway", bg="#20bebe", fg="white", height=2, width=30) zip_str.set("Zip a file B)") zip_btn.grid(column=1, row=3) root.mainloop()
8dd103181b997bee8c9fc91c07fe61d337020b6d
moisesquintana57/python-exercices
/tema_4_variables/ejer3.py
187
3.828125
4
frase=input("Ingrese una frase:") total=0 x=0 while x<len(frase): if frase[x]==" ": total=total+1 x=x+1 print("La cantidad de espacios en blanco ingresados es de ",total)
9408569925c88b0eaa3bf220dc3254459413fb09
amir20001/ece406
/assignment2.py
2,690
4.3125
4
#!/usr/bin/env python3 """ Assignment 2 Python file Cut-and-paste (or import) your extended_euclid and modexp functions from assignment 1 """ import random import math # part (i) for modular exponentiation def modexp(x, y, N): """ Input: Three positive integers x and y, and N. Output: The number x^y mod N """ if y == 0: return 1 z = modexp(x, math.floor(y / 2), N) if y % 2 == 0: return (z * z) % N else: return (x * z * z) % N # part (ii) for extended Euclid def extended_euclid(a, b): """ Input: Two positive integers a >= b >= 0 Output: Three integers x, y, and d returned as a tuple (x, y, d) such that d = gcd(a, b) and ax + by = d """ if b == 0: return 1, 0, a (x_new, y_new, d) = extended_euclid(b, a % b) return y_new, x_new - math.floor(a / b) * y_new, d def primality(N): """ Test if a number N is prime using Fermat's little Theorem with ten random values of a. If a^(N-1) mod N = 1 for all values, then return true. Otherwise return false. Hint: you can generate a random integer between a and b using random.randint(a,b). """ if N <= 3: return True for i in range(10): a = random.randint(1, N - 1) if modexp(a, N - 1, N) != 1: return False return True def prime_generator(N): """ This function generates a prime number <= N """ while True: rand = random.randint(1, N) if primality(rand): return rand return 0 def generate_values(): while True: p = prime_generator(10000000) # verify p is 7 digits if len(str(p)) < 7: continue q = prime_generator(10000000) # verify q is 7 digits if len(str(q)) < 7: continue N = p * q n = (p - 1) * (q - 1) e = 5 if n % 5 == 0: # make sure n is coprime with e continue (x, y, r) = extended_euclid(e, n) # make sure that the modular inverse exists if r == 1: print("p", p) print("q", q) return N, e, (x % n) def main(): """ Test file for the two parts of the question """ ################## ## Excercise 1: generating primes and RSA (N, public, private) = generate_values() print("public", public) print("private", private) print("N", N) x = 101010 enc = modexp(x, public, N) print("enc", enc) dec = modexp(enc, private, N) print("dec", dec) if dec == x: print("decoded message was equal to x") if __name__ == '__main__': main()
29c0f3af43fd45a20c2c3dd7a5b8a680377a0a2a
DriveMyScream/Python
/07_Loops/Problem_No5.py
121
4
4
num = 5 sum = 0 i = 1 while(i<=num): sum = sum + i i+=1 print("The Sum Of First 5 natural Number is:", sum)
198d641baaea502deff9a7d9afd85d8c3f7d6d16
unblest/python
/ex25.py
1,903
4.3125
4
# exercise 25: even more practice # function to break words using new 'split' modifier # interesting use of triple quotes for the string in the function def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words # function to sort words using new 'sorted' command def sort_words(words): """Sorts the words.""" return sorted(words) # function to print the first word using 'pop' modifier def print_first_word(words): """Prints the first word after popping it off.""" word = words.pop(0) print word # function to print the last word # looks like it works the same as the function above, but just uses a different 'pop' value def print_last_word(words): """Prints the last word after popping it off""" word = words.pop(-1) print word # function to take a full sentence and return the sorted words # passing the arugment 'sentence' between functions in this function # this function also runs two of the above functions # the first to break the sentence given, and the second to sort the result of the broken words def sort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = break_words(sentence) return sort_words(words) # function to print the first and last words of a sentence # this function uses three of the above functions def print_first_and_last(sentence): """Prints the first and last words of the sentence.""" words = break_words(sentence) print_first_word(words) print_last_word(words) # finally a function to do all of the basic functions above at once # break the sentence, sort the words, and return the first and last words def print_first_and_last_sorted(sentence): """Sorts the words then prints the first and last one.""" words = sort_sentence(sentence) print_first_word(words) print_last_word(words)
b1cbd92ff7247fcc7b0990adf41e1d33ebf3dc39
mhbakus/Class-Files
/apple.py
647
3.65625
4
class Apple: price = 5 apple_number = 0 def __init__(self, color): Apple.apple_number += 1 if Apple.apple_number == 3: self.__color = "purple" elif Apple.apple_number == 4: self.__color = "brown" elif Apple.apple_number % 12 == 0: self.__color = "brurple" else: self.__color = color self.__price = Apple.price def __repr__(self): return "This is a {} cedi {} Apple".format(int(self.__price), self.__color) @classmethod def change_price(cls, price): cls.price = price for _ in range(14): print(Apple("red")) second = Apple("blue") print(second) Apple.change_price(6.0) third = Apple("green") print(third)
9557732bd2074692bb5987acc3cd6e76f0d0a913
naturofix/clear_data
/check_4_duplites.py
6,936
3.625
4
# the purpose of this script is to check to file location and make sure files exist in both. # if not file should be copied to to a temp folder in the second location import os import sys import fnmatch import time import datetime import filecmp path_1 = sys.argv[1] path_2 = sys.argv[2] path_3 = '/mnt/BLACKBURNLAB/' raw = True other = True def new_dir(test_path): if not os.path.isdir(test_path): cmd = 'mkdir %s' %(test_path) print cmd os.system(cmd) # test = False # try : # test = sys.argv[3] # except: # print('python check_4_duplicates.py <path_1> <path_2> test : test will prevent deleting files') # raw_input('enter to run script, all raw file not duplicated on both paths, will be copied to path_2') # test = False if raw == True: raw_input('\n\nenter to run script, all raw file not duplicated on both paths, will be copied to %s/missing_files \n\n' %(path_2)) missing_file_list = [] cmd = 'mkdir missing_files' os.system(cmd) write_file = open('missing_files/%s_duplications.txt' %(path_1.replace('/','_')),'a') file_list = ['*.raw'] print file_list raw_1 = [] file_name_list_1 = [] print('running search %s' %(path_1)) for file_name in file_list: print file_name for root, dirnames, filenames in os.walk(path_1): for filename in fnmatch.filter(filenames, file_name): raw_1.append(os.path.join(root, filename)) file_name_list_1.append(filename) #print filename print('search 1 done') print(len(raw_1)) print(len(set(file_name_list_1))) write_file.write('%s : %s\n\n' %(path_1,len(raw_1))) raw_2 = [] file_name_list_2 = [] print('running search %s' %path_3) for file_name in file_list: print file_name for root, dirnames, filenames in os.walk(path_3): for filename in fnmatch.filter(filenames, file_name): raw_2.append(os.path.join(root, filename)) file_name_list_2.append(filename) #print filename print('search 2 done') print(len(raw_2)) print(len(set(file_name_list_2))) for entry in list(set(file_name_list_1)): print '\n\n' print entry #index_1 = file_name_list_1.index(entry) index_1 = [i for i, x in enumerate(file_name_list_1) if x == entry] print index_1 #index_2 = file_name_list_2.index(entry) index_2 = [i for i, x in enumerate(file_name_list_2) if x == entry] print index_2 for i in index_1: file_1 = raw_1[i] hit = 0 dup_list = [] print file_1 for j in index_2: file_2 = raw_2[j] print file_2 print filecmp.cmp(file_1,file_2) if filecmp.cmp(file_1,file_2) == True: hit += 1 dup_list.append(file_2) if hit == 0: missing_file_list.append(file_1+'\n') new_path = '%s/missing_files/' %(path_2) new_dir(new_path) file_list = file_1.split('/') #print file_list path_list = file_list[4:len(file_list)-1] for path_entry in path_list: new_path = '%s/%s' %(new_path,path_entry) new_dir(new_path) output_path = new_path cmd = 'cp %s %s/%s' %(file_1,output_path,entry) print cmd os.system(cmd) if hit > 1: write_file.write('\n%s : %s copies in %s\n' %(file_1,hit,path_2)) for dup in dup_list: write_file.write('\t\t%s\n' %(dup)) write_file.flush() #raw_input() write_file.close() print missing_file_list write_file = open('missing_files/%s_missing.txt' %(path_1.replace('/','_')),'a') write_file.writelines(missing_file_list) write_file.close() if other == True: print '\n\nsearching for QE configuration files\n\n' file_extension_list = ['xlsx', 'pptx', 'docx', 'db', 'sld', 'pdf','meth','csv',] file_list_ext = [] for file_name in file_extension_list: print file_name for root, dirnames, filenames in os.walk(path_1): for filename in fnmatch.filter(filenames, '*.%s' %file_name): file_list_ext.append(os.path.join(root, filename)) #print filename for file_path in file_list_ext: #missing_file_list.append(file_1+'\n') #print 'missing file %s' %file_1 new_path = '%s/QE_files/' %(path_2) new_dir(new_path) file_list = file_path.split('/') path_list = file_list[4:len(file_list)-1] for path_entry in path_list: new_path = '%s/%s' %(new_path,path_entry) new_dir(new_path) output_path = new_path cmd = 'cp %s %s/%s' %(file_path,output_path,file_list[-1]) print cmd os.system(cmd) # for i in range(0,len(file_name_list)): # file_name = file_name_list[i] # file_path = refs[i] # #print file_path # #print file_name # number = file_name_list.count(file_name) # #li = file_name_list.index(file_name) # #print li # #print refs[li] # #print number # if number > 1: # print file_name # print number # indices = [i for i, x in enumerate(file_name_list) if x == file_name] # dups = [refs[j] for j in indices] # times = [] # for dup_file_path in dups: # if os.path.exists(dup_file_path): # times.append(os.path.getmtime(dup_file_path)) # #print dups # #print times # min_index = times.index(min(times)) # #print min_index # #print times[min_index] # first_file = dups[min_index] # if os.path.exists(first_file) and os.path.exists(file_path): # if 'History' not in file_path: # if file_path != first_file: # print "\n" # print first_file # print file_path # if filecmp.cmp(first_file,file_path): # print 'same file' # cmd = 'mv %s %s' %(file_path,rep_path) # print cmd # reps_count += 1 # if test == False: # os.system(cmd) # print 'moved' # mv_file_list.append(file_path) # else: # print 'not the same' # diffs += 1 # else: # print 'first file' # else: # print 'in history' # hist += 1 # else: # missing_file_list = [] # if not os.path.exists(file_path): # missing_file_list.append(file_path) # if not os.path.exists(first_file): # missing_file_list.append(first_file) # for missing_file in missing_file_list: # print '\n\n\n##################### Error ###################\n\n\n' # if file_path in mv_file_list: # print 'file already moved, which is rather strange' # else: # print 'file not in moved list' # print '%s no longer exists' %file_path # print '\n\n\n##################### Error ###################\n\n\n' # raw_input('enter to continue') # print 'total : %s' %total # print i # print 'reps : %s (%s%s)' %(reps_count,round(float(reps_count)/float(i),3)*100,'%') # print 'same name different file = %s' %(diffs) # print 'in history : %s' %(hist) # print 'total : %s' %total # print 'reps : %s (%s%s)' %(reps_count,round(float(reps_count)/float(i),3)*100,'%') # print 'same name different file = %s' %(diffs) # print 'in history : %s' %(hist) # for file_path in refs # if os.path.exists(file_path): # cmd = 'mv %s %s' %(file_path.replace(' ','\ '),wash_month) # print cmd # if test == False: # os.system(cmd) # print 'executed' # #raw_input()
0daa1f49608c6b6ea2187096189fb01c76aecfaa
Alan-FLX/code
/luogu/02_分支结构/P_1909.py
294
3.546875
4
import math num = int(input()) money = 0 i = 0 while i < 3: pen, price = map(int, input().split()) if i == 0: money = math.ceil(num / pen) * price else: if money > math.ceil(num / pen) * price: money = math.ceil(num / pen) * price i += 1 print(money)
33931c8feaa01dd97aa9972501df0727013a2989
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Checking_and_Printing/28_print_all_root_to_leaf_in_line_by_line.py
720
3.921875
4
''' Print all paths ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def print_path(node, arr): if not node: return arr.append(node.val) if node.left is None and node.right is None: print ' '.join([str(i) for i in arr]) print_path(node.left, arr) print_path(node.right, arr) arr.pop() def print_all_path(root): arr = [] print_path(root, arr) root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.left.right.right = Node(15) root.right.left = Node(6) root.right.right = Node(7) root.right.left.right = Node(8) print_all_path(root)
2d716f1bea12cc52a5ebc5217a89b7855d03185b
Divya748/data_structures_and_algo_in_python
/data_structures_in_python/stack.py
1,578
4.25
4
class Node: def __init__(self,data): self.data = data self.next = None class Stack: def __init__(self): self.head= None def push(self , data): """ This method is used to insert/push the data into the stack """ if self.is_empty(): self.head = Node(data) else: new_node = Node(data) new_node.next = self.head self.head = new_node def is_empty(self): """ This method is used to check whether the stack is empty or not """ return self.head is None def pop(self): """ This method is used to delete/pop elements from the stack """ if self.is_empty(): print("stack is empty") else: popped=self.head.data self.head=self.head.next return popped def peek(self): """ This method is used to print top of the element in the stack """ if not self.is_empty(): return self.head.data else: print("stack is empty") def traversal(self): """ This method is used to traverse every element in the stack """ a=" " temp=self.head while temp != None: a=a+str(temp.data)+'\t' temp=temp.next print(a) object=Stack() object.push(25) object.push(250) object.push(2500) object.push(25000) object.traversal()
710c762a8f8b8ac215a1b9ecfb2cb2513af03385
thedonflo/Flo-Python
/ModernPython3BootCamp/Functions_Pt_1/Yell_Function.py
586
4.40625
4
# Yell Function Exercise # Implement a function yell which accepts a single string argument. # It should return(not print) an uppercased version of the string with an exclamation point aded at the end. For example: # # yell("go away") # "GO AWAY!" # # yell("leave me alone") # "LEAVE ME ALONE!" # # You do not need to call the function to pass the tests. # # Remember, that currently you can't use f-strings in Udemy coding challenges, so either use string concatenation or the format() method. # def yell(command): return command.upper()+'!' print(yell('leave me alone'))
c85eeff3976bbeafce042cbc4f20ed2ce421047a
christopherridolfi/October30
/List/f.py
916
3.96875
4
import random result = [] times = int(input("How Many Times Does Player 1 To Roll The Dice")) for x in range(0,times): number = random.randint(1,6) result.append(number) print("Player 1 Roll History is ") print(result) result2 = [] times2 = int(input("How Many Times Does Player 2 Want To Roll The Dice")) for x in range(0,times2): number2 = random.randint(1,6) result2.append(number2) print("Player 2 Roll History is ") print(result2) result3 = [] times3 = int(input("How Many Times Does Player 3 Want To Roll The Dice")) for x in range(0,times3): number3 = random.randint(1,6) result3.append(number3) print("Player 3 Roll History is ") print(result3) result4 = [] times4 = int(input("How Many Times Does Player 4 Want To Roll his Dice")) for x in range(0,times4): number4 = random.randint(1,6) result4.append(number4) print("Player 4 Roll History is ") print(result4)
60c09fc4b6142bbb58695f7e1b3b1eb1c78aa5e1
fit-r-yamada/meeting
/sample02.py
301
3.578125
4
alpha = ['a', 'b', 'c', 'd', 'e'] number = [1, 2, 3, 4, 5] def combineArray(array1, array2): ret_array = [] i = 0 for i in range(0, len(array1)): ret_array.append(array1[i]) ret_array.append(array2[i]) return ret_array string = combineArray(alpha, number) print(string)
42710bbed9c0183e308620bf6a3cb7075c0e4cce
AliceTTXu/LeetCode
/alice/LC231.py
234
3.515625
4
class Solution(object): def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ bin_str = bin(n) return n == 1 or (bin_str[2] == '1' and int(bin_str[3:]) == 0)
394698aa3991c894692db744113f802aca19397a
xiaoweigege/Python_senior
/chapter10/5. Thread_Condition.py
2,381
3.953125
4
from threading import Condition, Thread # 条件变量, 用于复杂的线程间同步 # 在调用with cond之后才能调用wait 或者notify方法 # condition 有两层锁, 一把底层锁 会在调用wait方法的时候释放 # 上面的锁会在每次调用wait的时候分配一把并放入到condition的等待队列中, # 等到notify方法的唤醒 class XiaoAi(Thread): def __init__(self, cond): super().__init__(name='小爱') self.cond = cond def run(self): with self.cond: # 等待通知, 通知来了 就执行下方的 self.cond.wait() print('{}: {}'.format(self.name, '在')) self.cond.notify() self.cond.wait() print('{}: {}'.format(self.name, '好啊')) self.cond.notify() self.cond.wait() print('{}: {}'.format(self.name, '君住长江尾')) self.cond.notify() self.cond.wait() print('{}: {}'.format(self.name, '共饮长江水')) self.cond.notify() self.cond.wait() print('{}: {}'.format(self.name, '此恨何时几')) self.cond.notify() self.cond.wait() print('{}: {}'.format(self.name, '定不负相思意')) class TianMao(Thread): def __init__(self, cond): super().__init__(name='天猫') self.cond = cond def run(self): with self.cond: print('{}: {}'.format(self.name, '小爱同学')) # 通知其他线程执行 self.cond.notify() self.cond.wait() print('{}: {}'.format(self.name, '我们来对古诗吧')) self.cond.notify() self.cond.wait() print('{}: {}'.format(self.name, '我住长江头')) self.cond.notify() self.cond.wait() print('{}: {}'.format(self.name, '日日思君不见君')) self.cond.notify() self.cond.wait() print('{}: {}'.format(self.name, '此水几时休')) self.cond.notify() self.cond.wait() print('{}: {}'.format(self.name, '只愿君心似我心')) self.cond.notify() if __name__ == '__main__': condition = Condition() xiaoai = XiaoAi(condition) tianmao = TianMao(condition) xiaoai.start() tianmao.start()
13a7919d832fce4e6f34959fc9260401266fd262
isakss/Forritun1_Python
/midterm_list_exercise8.py
996
4.4375
4
""" This program allows the user to create a list of designated size, input size many elements into the list, and then creates a new list without duplicate values. All non numeric values are ignored. """ def populate_list(int_object): new_list = [] while len(new_list) != int_object: try: list_element = int(input("Enter an element to put into the list: ")) new_list.append(list_element) except ValueError: pass return new_list def find_unique_elements(list_object): new_unique_list = [] for element in list_object: if element not in new_unique_list: new_unique_list.append(element) return new_unique_list def main_func(): size_num = int(input("Enter the size of the list: ")) value_list = populate_list(size_num) unique_list = find_unique_elements(value_list) print("The list: {}".format(value_list)) print("The list without duplicates: {}".format(unique_list)) main_func()
97e75d53bd4e568114085a453145a966735bdd08
Liadrinz/homework-plus
/Backend/data/proceeding/autozip.py
359
3.59375
4
# 自动压缩用户文件模块 from zipfile import ZipFile import os # 将文件打包为一个压缩文件, 存到后台/homework_file/目录下 def CreateZip(files_to_zip, pack_name): zfile = ZipFile("./data/backend_media/homework_file/%s.zip"%pack_name, 'w') for f in files_to_zip: zfile.write(f, f.split('/')[-1]) os.remove(f)
070c7ce752650830c22821a0eada2e456fd63e86
stevestar888/leetcode-problems
/28-implement_strstr.py
568
3.640625
4
""" https://leetcode.com/problems/implement-strstr/ One iteration, O(n) """ class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ hay_len = len(haystack) need_len = len(needle) if hay_len == 0 and need_len == 0: return 0 for i in range(hay_len - need_len + 1): substring = haystack[i:i+need_len] if needle == substring: return i return -1
38ed6f418935e54104547da20385955538b531c8
viraingarg/Movie-Website
/media.py
552
3.53125
4
import webbrowser class Movie: """ This class has two methods and stores info about movie like its title, storyline, image and youtube url. """ def __init__(self, movie_title, movie_storyline, poster_image, trailer_video): self.title = movie_title self.storyline = movie_storyline self.poster_image_url = poster_image self.trailer_youtube_url = trailer_video def show_trailer(self): webbrowser.open(self.trailer_youtube_url)
fc251df1e3a77c7e2f6dc8bf3a50f2b7738fba43
Augustin-Louis-Xu/python_work
/第四章/4.4 使用列表的一部分 知识点 .py
1,256
4
4
#切片 players=['charles','martina','michael','florence','eli'] print(players[0:3]) print(players[0:]) print(players[:4]) print(players[-3:]) #遍历切片 players=['charles','martina','michael','florence','eli'] print('Here are the first three players on our team:') for player in players[:3]: print (player.title())#切片非常有作用,比如说在退出游戏时,可以将其分数加入一个列表中,然后将列表降序排列,最后用切片输出可以得到最高的三个得分。还可以用切片批量处理数据。 #复制列表 my_foods=['pizza','falafel','carrot cake'] friend_foods=my_foods[:]#注意,此处是添加了一个副本列表,一下会核实存在两个列表。 my_foods.append('cannoli') friend_foods.append('ice cream') print('\nMy favorite foods is:') print(my_foods) print("\nMy friend's favorite is:") print(friend_foods) #以下演示在不使用切片的情乱下,简单的赋值,是不会得到两个列表的,两个变量指向同一个列表。 my_foods=['pizza','falafel','carrot cake'] friend_foods=my_foods my_foods.append('cannoli') friend_foods.append('ice cream') print('\nMy favorite foods is:') print(my_foods) print("\nMy friend's favorite is:") print(friend_foods) print('\n')
c2ce2f8640269d95cd7295839cb4af6ceb57a7a3
alexcnichols/learning-python
/spy-messages-auto-decrypt.py
723
4.125
4
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" stringToDecrypt = input("Please enter a message to decrypt: ") stringToDecrypt = stringToDecrypt.upper() shiftAmount = [-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11,-12,-13,-14,-15,-16,-17,-18,-19,-20,-21,-22,-23,-24,-25] for decryptShift in shiftAmount: decryptedString = "" for currentCharacter in stringToDecrypt: position = alphabet.find(currentCharacter) newPosition = position + decryptShift if currentCharacter in alphabet: decryptedString = decryptedString + alphabet[newPosition] else: decryptedString = decryptedString + currentCharacter print("Your decrypted message is", decryptedString)
661465d06478d0a00a74f1c996c45d242d15f0ed
issone/leetcode
/0048_rotate-imag/solution.py
595
3.65625
4
from typing import List class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ 将旋转,转换为先水平翻转,再左对角线翻转 """ n = len(matrix) # 先沿水平中线水平翻转 for i in range(n // 2): for j in range(n): matrix[i][j], matrix[n - 1 - i][j] = matrix[n - 1 - i][j], matrix[i][j] # 左对角线翻转 for i in range(n): for j in range(i): # 注意这里是i, 不是n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
b3163d3c7bc4cb6b1e774c36e22b965d8d368dab
Mainakroy050/Python_Projects
/Stone game.py
2,884
4.0625
4
import random lst=['s','p','x'] chance = 5 no_of_chance=0 computer_point=0 user_point=0 print("\t\t\t\t STONE , PAPER , SCISSOR\t\n\n") print("\'s\' -for STONE\t \'p\' -for PAPER\t \'x\' -for SCISSOR\t :") while no_of_chance < chance: _input = input('STONE , PAPER , SCISSOR : ') _random = random.choice(lst) if _input == _random: print("Tie Both 0 point to each\n") print(f"you hv entered {_input} and computer also chooses {_random}") ###### for STONE I/P ############### elif _input=="s" and _random == "x": user_point=user_point+1 print(f"You have entered {_input} and computer entered {_random}\n") print("User wins 1 point\n") print(f"You have {user_point} point and computer has {computer_point} point\n") elif _input=="s" and _random == "p": computer_point=computer_point+1 print(f"You have entered {_input} and computer entered {_random}\n") print("Computer wins 1 point\n") print(f"You have {user_point} point and computer has {computer_point} point\n") ################# for PAPER I/P ############## elif _input=="p" and _random == "s": user_point=user_point+1 print(f"You have entered {_input} and computer entered {_random}\n") print("You won 1 point\n") print(f"You have {user_point} point and computer has {computer_point} point\n") elif _input=="p" and _random == "x": computer_point=computer_point+1 print(f"You have entered {_input} and computer entered {_random}\n") print("Computer gets 1 point\n") print(f"You have {user_point} point and computer has {computer_point} point\n") ###################### for SCISSOR I/P ################ elif _input=="x" and _random == "p": user_point=user_point+1 print(f"You have entered {_input} and computer entered {_random}\n") print("You won 1 point\n") print(f"You have {user_point} point and computer has {computer_point} point\n") elif _input=="x" and _random == "s": computer_point=computer_point+1 print(f"You have entered {_input} and computer entered {_random}\n") print("Computer wins 1 point\n") print(f"You have {user_point} point and computer has {computer_point} point\n") else: print("\t\t\t\tYou have entered a wrong input !!!!!!! \n") no_of_chance=no_of_chance+1 print(f"{chance-no_of_chance} no of chances is left out of {chance} chances \n") print("GAME OVER !!!!") if computer_point== user_point: print("Tie!") elif computer_point > user_point: print("Computer wins and You lose") else: print("Congratulations you won the game !") print(f"Your point is {user_point} and computer point is {computer_point}\t")
8f497c6ef121cd39af491c647e73eb9f1fa80098
Luigi210/WebDev-1
/lab7/3j.py
80
3.5
4
sum = 0 for i in range(1, 101): n = int(input()) sum+=n print(sum)
8091b060e36747747295d1770312b4f01c1e2170
ivan0124/python-programming
/py_csv_fill0/fill0.py
717
3.5
4
#!/usr/bin/python import csv import numpy as np import pandas as pd def main(): with open("./hdd.csv","rb") as source: rdr= csv.reader( source ) #for row in rdr: # for i, x in enumerate(row): # if len(x)< 1: # x = row[i] = 0 # print x with open("result.csv","wb") as result: wtr= csv.writer( result ) for r in rdr: for i, x in enumerate(r): if len(x)< 1: r[i] = 0 wtr.writerow( (r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7],r[8]) ) print "__name__ value is %s" % (__name__) if __name__ == "__main__": main()
60c7cac7c8694400a24c0bc0d387ce42d6e6b4cb
quansirx/Note
/Test01.py
737
3.640625
4
'''a,b=0,1 while b<10: print(b,end=" ") a,b=b,a+b nn=1 while nn==1: num=int(input("请输入一个数字: ")) print("输入的数字=%d"%(num)) ''' ''' num=int(input("请输入一个数字:")) if num>5: print("num大于5") else: print("num小于5") n=100 sum=0 counter=1 while counter<=n: sum+=counter counter+=1 print("sum=%d" %(sum)); list01=[1,22,33,444,555,'666','77777'] for ii in list01: print(ii) import sys list=[1,2,3,4,5,6,7] it=iter(list) while True: try: print(next(it)) except StopIteration: sys.exit()''' def f01(Width,Height): return Width*Height def f02(name): print("Welcome",name) print("面积area=",f01(5,10)) f02("Tom")
c81eeedb1d2f6e8bfbeb7e1627beaef28002dabe
Baidaly/datacamp-samples
/6 - introduction to databases in python/inserting Multiple Records at Once.py
766
3.84375
4
''' It's time to practice inserting multiple records at once! As Jason showed you in the video, you'll want to first build a list of dictionaries that represents the data you want to insert. Then, in the .execute() method, you can pair this list of dictionaries with an insert statement, which will insert all the records in your list of dictionaries. ''' # Build a list of dictionaries: values_list values_list = [ {'name': 'Anna', 'count': 1, 'amount': 1000.00, 'valid': True}, {'name': 'Taylor', 'count': 1, 'amount': 750.00, 'valid': False} ] # Build an insert statement for the data table: stmt stmt = insert(data) # Execute stmt with the values_list: results results = connection.execute(stmt, values_list) # Print rowcount print(results.rowcount)
99e9a72be13bed125a6748c45d192c08568bb74b
Sujithakumaravelg/python-programming
/age_verification.py
163
3.5
4
def main(): age=input("enter the age") if(age==20): print"Eligible" else: print"Not Eligible" if __name__ == '__main__': main()
bc62e749814ed36a349fb2965f6e7f39769ed95a
Genetlakew/aws-class-shiro-tech
/101.py
195
3.8125
4
num_one = 5 num_two = 4 print(pow(num_one,num_two)) print(num_one * num_two) def say_hi(first_name,last_name): print('Hello!'+ first_name + " " + last_name + ".") say_hi('Aklilu','Mekasha')
de8ac62d233958e7040861b5bff81f42974496fd
gohdong/algorithm
/leetcode/1103.py
641
3.703125
4
from typing import List class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def distributeCandies(self, candies: int, num_people: int) -> List[int]: answer = [0 for _ in range(num_people)] temp = 0 for c in range(candies): if temp + (c+1) < candies: answer[c%num_people] += (c+1) temp+= (c+1) else: answer[c%num_people] += candies-temp break return answer solution = Solution() print(solution.distributeCandies(candies = 7, num_people = 4))
83630beb32ceee29856dfc330203078ff0c07d6c
whiteavian/hkrnk
/number_needed.py
561
3.609375
4
def letter_dict(string): l_dict = {} for l in string: if l not in l_dict: l_dict[l] = 1 else: l_dict[l] += 1 return l_dict def number_needed(a, b): dict_a = letter_dict(a) dict_b = letter_dict(b) num = 0 for l in dict_a: if l in dict_b: num += abs(dict_a[l] - dict_b[l]) del dict_b[l] else: num += dict_a[l] num += sum(dict_b.values()) return num print number_needed('fcrxzwscanmligyxyvym', 'jxwtrhvujlmrpdoqbisbwhmgpmeoke')
35b2424548015f7cbf72898b50d03dbe6a192b58
zhvnibek/leetcode_
/problems/220_duplicate_3.py
354
3.515625
4
from typing import List class Solution: def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: s = sorted(nums[:k]) print(s) return False if __name__ == '__main__': t_nums = [1, 3, 2, 1] t_k = 3 t_t = 0 print(Solution().containsNearbyAlmostDuplicate(nums=t_nums, k=t_k, t=t_t))
339cd8ddaa62f445de9f41c45ae5d8c1c7d0026a
starrye/LeetCode
/DP/303.区域和检索 -数组不可变 动态规划.py
1,022
3.703125
4
# 给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。 # 示例: # 给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange() # sumRange(0, 2) -> 1 # sumRange(2, 5) -> -1 # sumRange(0, 5) -> -3 # 说明: # 你可以假设数组不可变。 # 会多次调用 sumRange 方法!!!!!!!!! # 这句话很重要 这说明要保存 每次sum的状态 以免下次调用还要计算 class NumArray: def __init__(self, nums): """ :type nums: List[int] """ self.nums = nums for i in range(1,len(nums)): nums[i] = nums[i]+nums[i-1] def sumRange(self, i, j): """ :type i: int :type j: int :rtype: int """ if i == 0: return self.nums[j] else: return self.nums[j]-self.nums[i-1] # Your NumArray object will be instantiated and called as such: # obj = NumArray(nums) # param_1 = obj.sumRange(i,j)
3c86f1034af1b9ca833dbe8a80693898dcc88eeb
HeatherOrtegaMcMillan/telco_churn_classification_project
/prepare.py
4,248
3.734375
4
import pandas as pd import numpy as np import acquire import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import sklearn.feature_selection as feat_select import scipy.stats as stats from sklearn.preprocessing import LabelEncoder ###################################### Test Train Split ###################################### def test_train_split(df, stratify_val = 'churn'): ''' args: df This function take in the telco_churn data data acquired by aquire.py, get_telco_data(), performs a split, stratifies by churn. Returns train, validate, and test dfs. ''' train_validate, test = train_test_split(df, test_size=.2, random_state=713, stratify = df[stratify_val]) train, validate = train_test_split(train_validate, test_size=.3, random_state=713, stratify= train_validate[stratify_val]) return train, validate, test def all_aboard_the_X_train(X_cols, y_col, train, validate, test): ''' X_cols = list of column names you want as your features y_col = string that is the name of your target column train = the name of your train dataframe validate = the name of your validate dataframe test = the name of your test dataframe outputs X_train and y_train, X_validate and y_validate, and X_test and y_test 6 variables come out! So have that ready ''' # do the capital X lowercase y thing for train test and split # X is the data frame of the features, y is a series of the target X_train, y_train = train[X_cols], train[y_col] X_validate, y_validate = validate[X_cols], validate[y_col] X_test, y_test = test[X_cols], test[y_col] return X_train, y_train, X_validate, y_validate, X_test, y_test ###################################### Prep Telco ###################################### def prep_telco(df): """ This functions takes in the telco churn dataframe and retuns the cleaned and prepped dataset Use this function for exploring """ df.total_charges = df.total_charges.str.replace(' ', '0').astype(float) train, validate, test = test_train_split(df) return train, validate, test def prep_telco_hypothesis(df): """ This functions takes in the telco churn dataframe and retuns the cleaned and prepped dataset Use this function for exploring """ df.total_charges = df.total_charges.str.replace(' ', '0').astype(float) df['less_than_a_year'] = (((df['tenure'] < 12) == True) & ((df['churn'] == 'Yes') == True)).astype(int) train, validate, test = test_train_split(df) return train, validate, test def prep_telco_model(df): ''' This function takes in a dataframe and returns the cleaned, encoded and split data. Use this function before modeling. Stratified on churned. Adds column churned in under a year. returns train, validate, test DOESN'T DO THIS YET: Also splits into X and y sections. Function returns X_train, y_train, X_validate, y_validate, X_test, y_test ''' df.total_charges = df.total_charges.str.replace(' ', '0').astype(float) # list of columns to drop cols_to_drop = ['payment_type_id', 'internet_service_type_id','contract_type_id'] # drop superfulous columns df = df.drop(columns=cols_to_drop) # get list of columns that need to be encoded cols = [col for col in list(df.columns) if df[col].dtype == 'object'] # turn all text (object) columns to numbers using LabelEncoder() label_encoder = LabelEncoder() for col in cols: # don't encode customer_id if col != 'customer_id': df[col] = label_encoder.fit_transform(df[col]) # adds column for less than a year, If their tenure is less than a year and they have churned it's a 1 df['less_than_a_year'] = (((df['tenure'] < 12) == True) & ((df['churn'] == 1) == True)).astype(int) # split into train validate and test # Maybe try stratifying on new column less_than_a_year, similar to churn train, validate, test = test_train_split(df) return train, validate, test
b70d7376b7744f4fa37957c945ab0bd544a09b48
digitalladder/leetcode
/problem1382.py
1,025
3.90625
4
#problem 1382 / balance a binary search tree # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def balanceBST(self, root): """ :type root: TreeNode :rtype: TreeNode """ def inorder(root): stack = [] while stack or root: while root: stack.append(root) root = root.left root = stack.pop() treearr.append(root.val) root = root.right def rebuild(start,end): if start > end: return None mid = (start+end)/2 root = TreeNode(treearr[mid]) root.left = rebuild(start,mid-1) root.right = rebuild(mid+1,end) return root treearr = [] inorder(root) root = rebuild(0,len(treearr)-1) return root
840bc5cdf916b9b60f7c14a9da9b0767579e2745
sangzzz/Leetcode
/0082_Remove_Duplicates_From_Sorted_Lists_II.py
960
3.65625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: root = head if root == None: return root def count(x): cnt = 0 if x == None: return 0, None val = x.val while x != None and x.val == val: cnt += 1 x = x.next return cnt, x while True: x, ptr = count(root) if x >= 2: root = ptr head = ptr else: break if root == None: return root while head.next != None: x, ptr = count(head.next) if x >= 2: head.next = ptr else: head = head.next return root
ef5abd6d872c7420fcdeb7cc9539823fc5256319
Heegene/learning_python_200627
/200703_python_changecoin.py
462
3.671875
4
## 변수선언 money, c500, c100, c50, c10 = 0,0,0,0,0 # 메인 코드부분 money = int(input("교환할 돈은 얼마인가요?")) c500 = money // 500 # money 를 500으로 나눈 몫(500원을 몇개 반환할지) money %= 500 # money를 500으로 나눈 나머지 반환(500원짜리 빼고 남는돈) c100 = money // 100 money %= 100 c50 = money // 50 money %= 50 c10 = money // 10 money %= 10 print(c500, c100, c50, c10)
dbca4f546be4a126b77d233c29cdc5f8095c5bd7
Minghe0Zhang/Leetcode
/Array/769. Max Chunks To Make Sorted/main.py
1,276
4.09375
4
""" Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we split the array into some number of "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array. What is the most number of chunks we could have made? Example 1: Input: arr = [4,3,2,1,0] Output: 1 Explanation: Splitting into two or more chunks will not return the required result. For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted. Example 2: Input: arr = [1,0,2,3,4] Output: 4 Explanation: We can split into two chunks, such as [1, 0], [2, 3, 4]. However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible. """ class Solution(object): def maxChunksToSorted(self, arr): """ :type arr: List[int] :rtype: int """ idx = 0 n = len(arr) max_num = -1 cnt = 0 for i in range(n): if arr[i] > max_num: max_num = arr[i] if i == max_num: cnt+=1 return cnt if __name__ == "__main__": arr = [1,0,2,3,4] sol = Solution() res = sol.maxChunksToSorted(arr) print(res)
8daf3901913ea61b82295825550bc9aea139b9d9
sunrun93/python_start-learning
/OOP/class-instance.py
713
3.96875
4
#python 通过class关键字定义类,()中表示继承哪一个类 class Student(object): def __init__(self, name, score): self.name = name self.score = score def print_score(self): print('%s: %s' % (self.name, self.score)); def print_grade(self): if self.score<60: return 'C'; elif self.score<80: return 'B'; else: return 'A'; #创建实例是通过类名+()实现, 实例化nancy的类 nancy = Student('Nancy',100); nancy.print_score(); print(nancy.print_grade()); #在类中定义的函数只有一点不同,就是第一个参数永远是实例变量self,并且,调用时,不用传递该参数
5e7c93e6cc5fcad90a2a094ee5d43b8e6db3ca04
Larissa-D-Gomes/CursoPython
/introducao/exercicio101.py
367
3.96875
4
""" Implemente uma funcao que recebe uma string como parâmetro e retorna true se essa é um palíndromo. """ def verificadorPalindromo(leitura): aux = leitura[::-1] return aux.lower() == leitura.lower() def main(): leitura = input('Digite a string: ') print('Eh palindromo?',verificadorPalindromo(leitura)) if __name__ == '__main__': main()
0c1da2a78864e52dce97ebf0a2bbfd440eda74bc
curiosubermensch/EstructuraDeDatos
/recursion_fractal.py
1,746
3.59375
4
import turtle window=turtle.Screen() tortuga=turtle.Turtle() tortuga.speed(0) #direccionar 90 grados hacia la izq tortuga.left(90) def fractal(): #DIBUJAR RAMA PRINCIPAL: tortuga.forward(100) #mover 100 pixeles en la direccion q está #DIBUJAR SUB-RAMA IZQ tortuga.left(45) #direccionar 45 grados a la izq tortuga.forward(50) #mover 50 pixeles a la derecha #DIBUJAR SUB-SUB-RAMA IZQ tortuga.left(45) #direccionar 45 grados a la izq tortuga.forward(25) #mover 25 pixeles a la derecha tortuga.backward(25) #retroceder lo avanzado #DIBUJAR SUB-SUB-RAMA DERE tortuga.right(90) #direccionar a la derecha tortuga.forward(25) tortuga.backward(25) #retrocedemos a la sub-rama #RETROCEDER A LA RAMA PRINCIPAL tortuga.left(45) tortuga.backward(50) #DIBUJAR SUB-RAMA DERECHA tortuga.right(90) tortuga.forward(50) #DIBUJAR SUB-SUB-RAMA IZQ tortuga.left(45) tortuga.forward(25) tortuga.backward(25) #DIBUJAR SUB-SUB-RAMA DERECHA tortuga.right(90) tortuga.forward(25) tortuga.backward(25) #retroceder a la sub-rama #RETROCEDER A LA RAMA PRINCIPAL tortuga.left(45) tortuga.backward(50) def arbol_recursivo(tamaño,tortuga): if tamaño<10: return else: tortuga.forward(tamaño) #dibuja tronco tortuga.left(45) #ajuste izq arbol_recursivo(tamaño/2,tortuga) #dibuja subrama izq y luego dibuja la sub-subrama izq y derecha tortuga.right(90) #ajuste derecha (ramificacion) debe ser el doble q a la izq para que se ajuste arbol_recursivo(tamaño/2,tortuga) #dibuja subrama derecha y luego la sub-subrama izq y derecha tortuga.left(45) #ajuste direccion retroceso tortuga.backward(tamaño) #retroceso arbol_recursivo(50,tortuga)
d4cda064afe1c2dc56ddb8297f1c1b5f5ddad4a3
Gaurav-dawadi/Python-Assignment-II
/question13.py
911
4.15625
4
"""Write a function to write a comma-separated value (CSV) file. It should accept a filename and a list of tuples as parameters. The tuples should have a name, address, and age. The file should create a header row followed by a row for each tuple.""" inputList = [] def commaSeparatedValue(): while 1: count = 1 inputName = input("Enter your First Name: ") inputAddress = input("Enter your Address: ") inputAge = int(input("Enter your Age: ")) inputTuple = (inputName, inputAddress, inputAge) inputList.append(inputTuple) continueInput = input("Do you want to Add more info? (Y/N): ") if continueInput == 'Y': count += 1 continue elif continueInput == 'N': break return inputList gotBack = commaSeparatedValue() print("name, address, age") for i in gotBack: print('%s, %s, %s' %i)
1b40efafd106d65c6dfb2f3d46a979df8dc9e9cd
saleed/LeetCode
/246.py
403
3.59375
4
class Solution(object): def isStrobogrammatic(self, num): """ :type num: str :rtype: bool """ p = 0 q = len(num) - 1 while p < q: if num[p] == num[q] or (num[p]=="6" and num[q]=="9") or (num[p]=="9" and num[q]=="6"): p += 1 q -= 1 else: return False return True
025d212098711e3ec5df2dfd1f2cbfa52c93e932
suzytoussaint98/tp-Geometrie2D
/enveloppe_convexe/classes/vector.py
344
3.5
4
import math class Vector: def __init__(self, A, B): self.x = B.x - A.x self.y = B.y - A.y def norm_square(self): return self.x ** 2 + self.y ** 2 def norm(self): return math.sqrt(self.norm_square()) def scalar_product(self, vector): return (self.x * vector.x) + (self.y * vector.y)
33e63e57c9cf394280ec0fd0781632f99992b41e
n1k-n1k/python-algorithms-and-data-structures--GB-interactive-2020
/unit_01_algorithms_intro/hw/hw_01_1.py
578
4.4375
4
''' Выполнить логические побитовые операции «И», «ИЛИ» и др. над числами 5 и 6. Выполнить над числом 5 побитовый сдвиг вправо и влево на два знака. ''' a = 5 b = 6 print(f'a\t\t= {a} ({bin(a)})') print(f'b\t\t= {b} ({bin(b)})') print() print(f'a OR b\t= {a | b} ({bin(a | b)})') print(f'a AND b\t= {a & b} ({bin(a & b)})') print(f'a XOR b\t= {a ^ b} ({bin(a ^ b)})') print(f'a >> 2\t= {a >> 2} ({bin(a >> 2)})') print(f'a << 2\t= {a << 2} ({bin(a << 2)})')
8b28030326ce0da1ecd0941b3cd3d578da0802cc
yinwenyi/sudoku_csp
/orderings.py
9,796
3.90625
4
import random ''' This file will contain different variable ordering heuristics to be used within bt_search. var_ordering == a function with the following template ord_type(csp) ==> returns Variable csp is a CSP object---the heuristic can use this to get access to the variables and constraints of the problem. The assigned variables can be accessed via methods, the values assigned can also be accessed. ord_type returns the next Variable to be assigned, as per the definition of the heuristic it implements. val_ordering == a function with the following template val_ordering(csp,var) ==> returns [Value, Value, Value...] csp is a CSP object, var is a Variable object; the heuristic can use csp to access the constraints of the problem, and use var to access var's potential values. val_ordering returns a list of all var's potential values, ordered from best value choice to worst value choice according to the heuristic. ''' def ord_random(csp): ''' ord_random(csp): A var_ordering function that takes a CSP object csp and returns a Variable object var at random. var must be an unassigned variable. ''' var = random.choice(csp.get_all_unasgn_vars()) return var def val_arbitrary(csp,var): ''' val_arbitrary(csp,var): A val_ordering function that takes CSP object csp and Variable object var, and returns a value in var's current domain arbitrarily. ''' return var.cur_domain() def ord_mrv(csp): ''' ord_mrv(csp): A var_ordering function that takes CSP object csp and returns Variable object var, according to the Minimum Remaining Values (MRV) heuristic as covered in lecture. MRV returns the variable with the most constrained current domain (i.e., the variable with the fewest legal values). ''' unassigned_vars = csp.get_all_unasgn_vars() mrv_var = False mrv = 100000000000000 # a very large number to represent infinity for unassigned_var in unassigned_vars: cur_domain_size = unassigned_var.cur_domain_size() if ( cur_domain_size == 1 ): return unassigned_var # this value is forced, propagate immediately elif ( cur_domain_size < mrv ): mrv_var = unassigned_var mrv = cur_domain_size return mrv_var def ord_dh(csp): ''' ord_dh(csp): A var_ordering function that takes CSP object csp and returns Variable object var, according to the Degree Heuristic (DH), as covered in lecture. Given the constraint graph for the CSP, where each variable is a node, and there exists an edge from two variable nodes v1, v2 iff there exists at least one constraint that includes both v1 and v2, DH returns the variable whose node has highest degree. ''' # get all the unassigned variables unassigned_vars = csp.get_all_unasgn_vars() max_constraints = dict() # for each unassigned variable for unassigned_var in unassigned_vars: # get associated constraints constraints = csp.get_cons_with_var(unassigned_var) # keep a list of variables that are constrained by this one constrained_vars = [] # for each associated constraint for constraint in constraints: # for each variable in the same scope for var in constraint.get_scope(): # don't count self or vars that have assigned values if ((var is unassigned_var) or (var not in unassigned_vars)): continue # add it to the list of constrained variables if var not in constrained_vars: constrained_vars.append(var) # performance enhancer: check if we have the max possible list size already, break if so if (len(constrained_vars) == (len(unassigned_vars) - 1)): break # add to dict: key is unassigned var, value is number of other variables constrainted by it max_constraints[unassigned_var] = len(constrained_vars) # return var which imposes the most constraints on other unassigned vars return max(max_constraints, key=max_constraints.get) def val_lcv(csp,var): ''' val_lcv(csp,var): A val_ordering function that takes CSP object csp and Variable object var, and returns a list of Values [val1,val2,val3,...] from var's current domain, ordered from best to worst, evaluated according to the Least Constraining Value (LCV) heuristic. (In other words, the list will go from least constraining value in the 0th index, to most constraining value in the $j-1$th index, if the variable has $j$ current domain values.) The best value, according to LCV, is the one that rules out the fewest domain values in other variables that share at least one constraint with var. ''' # get all the unassigned variables unassigned_vars = csp.get_all_unasgn_vars() constraint_sums = dict() # keep track of remaining options with dict constraints = csp.get_cons_with_var(var) # get all associated constraints of var cur_dom = var.cur_domain() # get all possible values for var # for each possible value of var for value in cur_dom: # create a dict that keeps track of which values from other vars' domains are still valid other_var_domain = dict() # for each constraint associated with this variable for constraint in constraints: # don't continue if var=value is not in any valid solution if (var, value) not in constraint.sup_tuples: continue # for each assignment tuple which includes var=value for t in constraint.sup_tuples[(var, value)]: # make sure this tuple is still valid before counting it if not constraint.tuple_is_valid(t): continue # for each of the other values in the tuple for scope_var_index, scope_var_value in enumerate(t): # find the corresponding variable scope_var = constraint.get_scope()[scope_var_index] # skip if self or assigned variable if (var is scope_var) or (scope_var not in unassigned_vars): continue # create a new entry in the dict for scope_var if scope_var not in other_var_domain.keys(): other_var_domain[scope_var] = [] # add scope_var_value to scope_var's dict entry if scope_var_value not in other_var_domain[scope_var]: other_var_domain[scope_var].append(scope_var_value) # done looking at all the constraints, should now have a dict with a list of values # for each unassigned variable constrained by var eliminated_sum = 0 for scope_var in other_var_domain: # the num of eliminated values can be found by subtracting the length of our # valid-values list from the scope_var's current domain size eliminated_sum += scope_var.cur_domain_size() - len(other_var_domain[scope_var]) # store this sum in a dict and then go on to the next value constraint_sums[value] = eliminated_sum # sort the values in ascending order since we want value which will eliminate the least # amount of domain values from other unassigned variables sorted_sums = sorted(constraint_sums, key=constraint_sums.get) return sorted_sums def ord_custom(csp): ''' ord_custom(csp): A var_ordering function that takes CSP object csp and returns Variable object var, according to a Heuristic of your design. This can be a combination of the ordering heuristics that you have defined above. ''' # Try MRV to figure out which variable to assign first unassigned_vars = csp.get_all_unasgn_vars() mrv = 100000000000000 # a very large number to represent infinity mrv_vars = [] # a list to store the MRV var(s) for unassigned_var in unassigned_vars: cur_domain_size = unassigned_var.cur_domain_size() if ( cur_domain_size > mrv ): continue # we don't care about vars with larger current domain sizes if ( cur_domain_size < mrv ): mrv_vars.clear() # clear the list if new min domain size found mrv_vars.append(unassigned_var) # add the var to the list mrv = cur_domain_size # set the new minimum domain size if ( len(mrv_vars) == 1 ): return mrv_vars[0] # return if we found a single match # Do tie-breaking with DH max_constraints = dict() for mrv_var in mrv_vars: constraints = csp.get_cons_with_var(mrv_var) constrained_vars = [] # collect all the other vars that this var puts constraints on for constraint in constraints: for var in constraint.get_scope(): # don't count self or vars that have assigned values if ((var is mrv_var) or (var not in unassigned_vars)): continue # keep a unique list if var not in constrained_vars: constrained_vars.append(var) # performance enhancer: check if we have the max possible list size already, break if so if (len(constrained_vars) == (len(unassigned_vars) - 1)): break max_constraints[mrv_var] = len(constrained_vars) return max(max_constraints, key=max_constraints.get)
64de2bf5f30f55fd21af64a8ac43a65d424278f0
AnatoliyChabanenko/lesson8
/lesson25/search.py
1,615
3.640625
4
import timeit def sequential_search(array, item): pos = 0 found = False while pos < len(array) and not found: if array[pos] == item: found = True else: pos = pos + 1 return found def binary_search(array, item): first = 0 last = len(array) - 1 found = False while first <= last and not found: midpoint = (first + last) // 2 if array[midpoint] == item: found = True else: if item < array[midpoint]: last = midpoint-1 else: first = midpoint+1 return found def my_binar_search (my_list , iskat): if len(my_list) == 0: return False else: mid = len(my_list)//2 if iskat == my_list[mid]: return True elif iskat < my_list[mid] : return my_binar_search(my_list[:mid], iskat) else: return my_binar_search(my_list[mid+1:], iskat) if __name__ == "__main__": seq_timer = timeit.timeit( stmt="sequential_search([-100, -1.5, 2, 3, 4, 6, 31, 101], 6)", number=100, setup="from __main__ import sequential_search" ) print(seq_timer) bin_timer = timeit.timeit( stmt="binary_search([-100, -1.5, 2, 3, 4, 6, 31, 101], 6)", number=100, setup="from __main__ import binary_search" ) print(bin_timer) bin_my_bin = timeit.timeit( stmt="my_binar_search([-100, -1.5, 2, 3, 4, 6, 31, 101], 5)", number=100, setup="from __main__ import my_binar_search" ) print(bin_my_bin)
c866415c103adc792bf097417cbc0cac562cc40d
l3ouu4n9/LeetCode
/algorithms/821. Shortest Distance to a Character.py
1,141
3.921875
4
""" Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string. Example 1: Input: S = "loveleetcode", C = 'e' Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0] Note: S string length is in [1, 10000]. C is a single character, and guaranteed to be in string S. All letters in S and C are lowercase. """ class Solution(object): def shortestToChar(self, S, C): """ :type S: str :type C: str :rtype: List[int] """ ltr = [] rtl = [] prev = float("inf") for ch in S: if ch == C: prev = 0 else: if prev != "inf": prev += 1 ltr.append(prev) prev = float("inf") for ch in S[::-1]: if ch == C: prev = 0 else: if prev != "inf": prev += 1 rtl.append(prev) rtl.reverse() for i in range(0, len(ltr)): ltr[i] = min(ltr[i], rtl[i]) return ltr
f20e7714b1ed715c148d7080c68dab84fbdfadcb
anmarsharif/snakify-solution
/conditions/ex02/conditions ex02.py
111
3.734375
4
#ex02 ##Sign function n = int(input()) if n > 0: print (1) elif n < 0: print (-1) else: print (0)
f8d136ea73a199bf19c5d96fd9ffe9684f507deb
Elric2718/HierGMM
/loader/parser.py
3,164
3.75
4
# -*- coding: utf-8 -*- """ Data field parser functions, used to facilitate data field content parsing """ import tensorflow as tf def split_text(text, delimiter=" ", shape=None, limit=None, ): """ Split the text by specified delimiter :param text: Input 1D text Tensor :param delimiter: Value delimiter :param shape: If set, converted values would be reshaped :param limit: If set, slicing would be conducted to restrict the maximal limit :return: An 1D Tensor containing converted strings """ values = tf.string_split([text], delimiter).values # Do truncation if limit: values = values[:limit] if shape: values = tf.reshape(values, shape) return values def split_and_convert(text, out_type, delimiter=" ", shape=None, limit=None, pad_to=None, padding_value=0, op_name=None): """ Split the text by specified delimiter and then convert values into the given numerical type :param text: Input 1D text Tensor :param out_type: Target data types like tf.int32, tf.float32, etc :param delimiter: Value delimiter :param shape: If set, converted values would be reshaped :param limit: If set, slicing would be conducted to restrict the maximal limit :param pad_to: Int value. If set, returned tensor would be padded to the shape specified by this value :param padding_value: A number. If set, returned tensor would be padded with this value :return: An 1D Tensor containing converted values """ values = tf.string_to_number( split_text(text, delimiter, None, limit), out_type=out_type, name="{}_s2i".format(op_name) ) if pad_to is not None: values = tf.pad( values, [[0, pad_to - tf.shape(values)[-1]]], "CONSTANT", constant_values=padding_value, name="{}_padding".format(op_name) ) values = tf.reshape(values, [pad_to]) if shape: values = tf.reshape(values, shape) return values def decode_base64(data, out_type, shape=None, limit=None, pad_to=None, padding_value=0): """ Parse base64-encoded string as values :param data: 1D string Tensor containing base64-encoded data :param out_type: Target data types like tf.int32, tf.float32, etc :param shape: If set, converted values would be reshaped :param limit: If set, slicing would be conducted to restrict the maximal limit :param pad_to: Int value. If set, returned tensor would be padded to the shape specified by this value :param padding_value: A number. If set, returned tensor would be padded with this value :return: A 1D Tensor containing converted values """ values = tf.decode_raw(tf.decode_base64(data), out_type=out_type) # Do truncation if limit: values = values[:limit] if shape and not pad_to: values = tf.reshape(values, shape) if pad_to is not None: values = tf.pad(values, [[0, pad_to - tf.shape(values)[-1]]], "CONSTANT", constant_values=padding_value) values = tf.reshape(values, [pad_to]) if shape is not None: values = tf.reshape(values, shape) return values
f29237ca81c257c4dc2b44ce1b1ffe0a6fc8c171
Vith-MCB/Phyton---Curso-em-Video
/Cursoemvideo/Exercícios UFV/Lista 3/exer03 - ler 1000.py
192
3.53125
4
Guarda = 0 Guarda_m = float('inf') for i in range(0, 1000): x = int(input()) if x > Guarda: Guarda = x elif x < Guarda_m: Guarda_m = x print(Guarda_m) print(Guarda)
47d833b8e4ff71063e620c2ac61f1a65c62cdb59
OrenKov/compression-algorithm
/Compression.py
7,629
3.96875
4
class Node: """ A node of a tree that is being used to encode and compress data into symbols. """ def __init__(self, symbol=None, weight=0, left=None, right=None): self.left = left self.right = right self.symbol = symbol self.weight = weight class HEncoder: """ Huffman encoder for lists of words. """ def __init__(self): self.symbols = {} self.encoding_table = {} self.tree = [] self.list = None # ************ # # API # # ************ # def encode(self, l, output_list=True): """ compresses and encodes a given list of words. :param l: a list of words. :param output_list: a flag parameter. by-default, encoding each word in the list. if assigned False, encodes the all list to one word. :return: encoding_table and list_encoded if return_list=True (default), list_encoded is a list of the encoded words. if return_list=False, list_encoded is a string that encodes that list. """ self.list = l self._calc_frequencies() self.tree = [] self._create_nodes_and_sort_by_frequencies() self._create_frequencies_tree() # self.tree is not a list anymore. self._create_encoding_table() list_encoded = self._create_encoded_list(output_list) return self.encoding_table, list_encoded def decode(self, encoding_table, list_encoded, input_list=True): """ decodes a compressed-encoded list of words. :param encoding_table: An encoding table. expected to be of type 'dict', with at least one element. :param list_encoded: An encoded list. expected to be of type 'list', with at least one element. :param input_list: A flag parameter. by-default, decodes each word in the list. If assigned False, decodes a string to a list. :return: a decoded list of the list_encoded, by the encoding_table. if the input is invalid, return an empty list. """ decoded = [] if not self._check_encoding_table(encoding_table) or not self._check_list_encoded(list_encoded): return decoded # Create the decoding table based on the encoding one. decoding_table = {v: k for k, v in encoding_table.items()} # If a string is given, first make it to a list of encoded words. if not input_list: list_encoded = self._decode_as_list(list_encoded) # Decode the words and add to a list. for word in list_encoded: decoded.append(decoding_table[word]) return decoded # ************ # # HELPERS # # ************ # def _pre_traverse(self, node, cur_path=""): """ Preorder-Traversing a tree (ROOT, LEFT, RIGHT). :return: """ if not node.left: self.encoding_table[node.symbol] = cur_path else: self._pre_traverse(node.left, cur_path=cur_path + '0') self._pre_traverse(node.right, cur_path=cur_path + '1') def _calc_frequencies(self): """ calculating the frequencies of the appearance of the words in the input list. making a dictionary for easy quick retrieval of that information. :return: """ self.symbols = {} for symbol in self.list: self.symbols[symbol] = self.symbols.get(symbol, 0) + 1 def _encode_as_list(self, l): """ encodes a list to a single string, representing it. :param l: The list to be encoded. :return: The string representing the input list. """ encoded = "" for word in l: encoded += str(len(word)) + "$" + word return encoded def _decode_as_list(self, encoded): """ decodes a string representing a list full of words, to the original. :param l: The encoded list. :return: The original, decoded list. """ decoded, i = [], 0 while i < len(encoded): j = i while encoded[j] != "$": j += 1 length = int(encoded[i:j]) decoded.append(encoded[j + 1: j + 1 + length]) i = j + 1 + length return decoded def _create_frequencies_tree(self): """ Join couples of nodes, with the new parent node's label being the combined frequency of the 2 nodes: :return: """ while 2 <= len(self.tree): left = self.tree.pop(0) right = self.tree.pop(0) self.tree.append( Node( # symbol=left.symbol + right.symbol, weight=left.weight + right.weight, left=left, right=right)) self.tree.sort(key=lambda node: node.weight) self.tree = self.tree[0] def _create_nodes_and_sort_by_frequencies(self): """ Create a node for each character and label each with the frequency, sort the nodes in ascending order: :return: """ # Create the Nodes: for symbol in self.symbols.keys(): self.tree.append(Node(symbol=symbol, weight=self.symbols[symbol])) # Arrange these nodes in ascending frequency: self.tree.sort(key=lambda node: node.weight) def _create_encoding_table(self): """ Create the encoding table out of the tree. Each symbol/word gets a unique binary representation. The length of the representation depends on the frequency of the symbol/word appearence. :return: """ self.encoding_table = {} self._pre_traverse(self.tree) def _create_encoded_list(self, output_list): """ Create the encoded list, depending on return_list value. :return: """ list_encoded = [] for word in self.list: list_encoded.append(self.encoding_table[word]) if not output_list: encoded_as_list = self._encode_as_list(list_encoded) return encoded_as_list return list_encoded # ************ # # CHECKS # # ************ # def _check_encoding_table(self, encoding_table): """ Basic checks for an encoding_table. Checks that it is of type 'dict' and that it is not empty. :param encoding_table: The encoding table. :return: True for a valid table, else False """ if not isinstance(encoding_table, dict): print("encoding_table is expected to be of type 'dict'") return False if len(encoding_table) < 1: print("encoding_table is expected not to be empty") return False return True def _check_list_encoded(self, list_encoded): """ Basic checks for an encoding_table. Checks that it is of type 'dict' and that it is not empty. :param encoding_table: The encoding table. :return: True for a valid table, else False """ if not isinstance(list_encoded, list): print("list_encoded is expected to be of type 'list'") return False if len(list_encoded) < 1: print("list_encoded is expected not to be empty") return False return True
e315c2699dcfb227e65f472c365f0dd6ebe3c6ed
tjgrafft/python-challenge
/PyPoll/main.py
1,291
3.5625
4
import os import csv election_csv = os.path.join("Resources", "election_data.csv") # Lists to store data candidate = [] votes = {} # with open(budget_data, newline="", encoding='utf-8') as csvfile: with open(election_csv, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") csv_header = next(csvreader) for row in csvreader: # Add candidate candidate.append(row[2]) for x in candidate: if x not in votes: votes[x] = 1 else: votes[x] += 1 #Total Votes total_votes = len(candidate) FO=("Election Results\n") FO+=("------------------------\n") FO+=("Total Votes: " + str(total_votes)+"\n") FO+=("------------------------\n") #Each Candidates Votes for x, y in votes.items(): percent = round((float(y)/total_votes) * 100 , 2) FO+=(x + ": " + str(percent) + "00%"+ " (" + str(y) + ")\n") #Winner win_vote = "" kvote = 0 for x, y in votes.items(): if y > kvote : kvote = y win_vote = x #Print final Output FO+=("------------------------\n") FO+=("Winner: " + str(win_vote)+"\n") FO+=("------------------------\n") print(FO) ############################################################# file1 = open("results.txt","w") file1.write(FO) file1.close()
905bce3258017e4a82547e1c57898ccdbf3b2e34
Sheypex/PropraSeite
/server/DataAnalisis/term_loader.py
1,813
3.5
4
#!/usr/bin/env python import pandas as pd from datetime import datetime def distance_between_dates(min_time, max_time): date_format = "%Y-%m-%d %H:%M:%S" a = datetime.strptime(min_time, date_format) b = datetime.strptime(max_time, date_format) delta = b - a days, seconds = delta.days, delta.seconds hours = days * 24 + seconds // 3600 return hours def get_first_last_date(column, last_date): # determines the first/last item based on a column if last_date: counter = column.size - 1 while pd.isnull(column[counter]): counter -= 1 return column[counter] else: counter = 0 while pd.isnull(column[counter]): counter += 1 return column[counter] def define_intervals(tweets): # defines the distance between the first and last tweet max_time = get_first_last_date(tweets.Time, last_date=True) min_time = get_first_last_date(tweets.Time, last_date=False) return distance_between_dates(min_time, max_time) def drop_rows(tweets): return tweets[['Tweet', 'Time']].copy() def sort_by(value, tweets): # sorts the tweets on a descending order return tweets.sort_values(value, ascending=False) def build_json(tweets): # based on the tweets collected it builds the data in json to be graphed later tweets['Time'] = pd.to_datetime(tweets.Time, format='%Y-%m-%d %H:%M:%S', errors='coerce') tweets = tweets.dropna(subset=['Time']) tweets = tweets.set_index('Time').resample('H')['Tweet'].count() return tweets def load_term_file(path): # loads the file, sorts it and builds a json tweets = pd.read_csv(path, sep=";", error_bad_lines=False) tweets = sort_by("Time", tweets) tweets = drop_rows(tweets) return build_json(tweets) __author__ = 'Cesar Mauricio Acuna Herrera'
ada40b57ff7f838f83bc8e06fbfda45636628870
magedu-pythons/python-19
/15-xiaofengfeng/week3/mission_1_2.py
291
3.84375
4
#打印出100以内的斐波那契数列,使用2种方法实现 first = 1 second = 1 print("The number :", first) print("The number :", second) list = [first,second] while True: new = list[-1] + list[-2] if new >100: break list.append(new) print("The number :",new)
439b2643b4ed0a672910b1806a9a8d1249746f52
Kattyabo/BootCamp_Python_Modulo2
/M2_S1_ind/Tarea_Ind1_Arreglada.py
169
3.671875
4
x = 3 f = 3.1415926 nombre = "Python" print (x) print (f) print (nombre) combination = (nombre + " " + nombre) print (combination) suma = (f + f) print (suma)
ffc675267673a06f6d3c709981f62857e7a0c2c1
grachev-ser/Python_Base
/Lesson_3/L3_Task4.py
2,323
3.8125
4
# Программа принимает действительное положительное число x и целое отрицательное число y. # Необходимо выполнить возведение числа x в степень y. # Задание необходимо реализовать в виде функции my_func(x, y). # При решении задания необходимо обойтись без встроенной функции возведения числа в степень. # Подсказка: попробуйте решить задачу двумя способами. # Первый — возведение в степень с помощью оператора **. # Второй — более сложная реализация без оператора **, предусматривающая использование цикла. # Первый вариант def my_func1(x, y): return x ** y # Второй вариант def my_func2(x, y): result = 1 / x while (y + 1) < 0: result *= (1 / x) y += 1 return result input_x = 4. input_y = -2 while True: # Пользователь вводит действительное положительное число input_value = input("Введите действительное положительное число: ") try: # Пробуем перевести в действительное число, если не удается переходим в except input_x = float(input_value) break except ValueError: print("Данные введены неверно!") while True: # Пользователь вводит целое отрицательное число input_value = input("Введите целое отрицательное число: ") try: # Пробуем перевести в число, если не удается переходим в except input_y = int(input_value) if input_y < 0: break else: print("Введите отрицательное число!") except ValueError: print("Данные введены неверно!") print(my_func1(input_x, input_y)) print(my_func2(input_x, input_y))
17bf556c3299d613b1d267fd1c735d30d733b892
Aduzona/INTRO-TO-PYTHON-DEVELOPMENT
/13 - Functions/8. code_challenge.py
1,318
4.25
4
# -*- coding: utf-8 -*- """ Created on Fri Aug 21 11:16:59 2020 @author: aduzo """ # Create a calculator function # The function should accept three parameters: # first_number: a numeric value for the math operation # second_number: a numeric value for the math operation # operation: the word 'add' or 'subtract' # the function should return the result of the two numbers added or subtracted # based on the value passed in for the operator # def calculator(first_number,second_number,operator): if operator.upper() == 'ADD': result = first_number + second_number elif operator.upper() == 'SUBTRACT': result =first_number - second_number else: result = 'Type in operator ADD or SUBTRACT' return result first_number= float(input('Please enter the first number: ')) second_number = float(input('Please enter the second number: ')) operator =input('Please input ADD or SUBTRACT: ') print(str(first_number) + ' ' + str(second_number) + ' ' + str(calculator(first_number,second_number,operator))) # Test your function with the values 6,4, add # Should return 10 # # Test your function with the values 6,4, subtract # Should return 2 # # BONUS: Test your function with the values 6, 4 and divide # Have your function return an error message when invalid values are received
6ee5035e62132f9f93abc9947e758047e200b2c0
Marusya-ryazanova/Lesson_3
/Les.3.5.py
506
3.765625
4
from random import random n = int(random() * 10) i = 1 print("Мы загодали число, попробуй кгадай. У тебя есть 3 попытки") while i <= 3: u = int(input(str(i) + '-я попытка: ')) if u > n: print('Много') elif u < n: print('Мало') else: print('Вы угадали с %d-й попытки' % i) break i += 1 else: print('Вы исчерпали 3 попытки. Было загадано', n)
3b7c62a284a1971ed76e4236d7170fe9dd582806
seangrogan-archive/datastructures_class
/weekly_classes/12-BINARY SEARCH TABLES/TreeMap.py
8,376
3.578125
4
"""Code Python pour le cours IFT2015 Mise à jour par François Major le 28 mars 2014. Ref: Data Structure & Algorithms in Python Goodrich, Tamassia et Goldwasser, 2013 """ import random import time from LinkedBinaryTree import LinkedBinaryTree from Map import Map class TreeMap( LinkedBinaryTree, Map ): #overriding Position class Position( LinkedBinaryTree.Position ): def key( self ): return self.element()._key def value( self ): return self.element()._value #--- non public --- def _subtree_search( self, p, k ): if k == p.key(): return p elif k < p.key(): if self.left( p ) is not None: return self._subtree_search( self.left( p ), k ) else: if self.right( p ) is not None: return self._subtree_search( self.right( p ), k ) return p def _subtree_first_position( self, p ): walk = p while self.left( walk ) is not None: walk = self.left( walk ) return walk def _subtree_last_position( self, p ): walk = p while self.right( walk ) is not None: walk = self.right( walk ) return walk def _first( self ): return self._subtree_first_position( self.root() ) if len( self ) > 0 else None def _last( self ): return self._subtree_last_position( self.root() ) if len( self ) > 0 else None def _before( self, p ): self._validate( p ) if self.left( p ): return self._subtree_last_position( self.left( p ) ) else: walk = p above = self.parent( walk ) while above is not None and walk == self.left( above ): walk = above above = self.parent( walk ) return above def _after( self, p ): self._validate( p ) if self.right( p ): return self._subtree_first_position( self.right( p ) ) else: walk = p above = self.parent( walk ) while above is not None and walk == self.right( above ): walk = above above = self.parent( walk ) return above def _find_position( self, k ): if self.is_empty(): return None else: p = self._subtree_search( self.root(), k ) self._rebalance_access( p ) return p def find_min( self ): if self.is_empty(): return None else: p = self._first() return (p.key(), p.value() ) def find_max( self ): if self.is_empty(): return None else: p = self._last() return (p.key(), p.value() ) def find_ge( self, k ): if self.is_empty(): return None else: p = self._find_position( k ) if p.key() < k: p = self._after( p ) return (p.key(), p.value()) if p is not None else None def find_gt( self, k ): if self.is_empty(): return None else: p = self._find_position( k ) if p.key() == k: p = self._after( p ) return (p.key(), p.value()) if p is not None else None def find_le( self, k ): if self.is_empty(): return None else: p = self._find_position( k ) if p.key() > k: p = self._before( p ) return (p.key(), p.value()) if p is not None else None def find_lt( self, k ): if self.is_empty(): return None else: p = self._find_position( k ) if p.key() >= k: p = self._before( p ) return (p.key(), p.value()) if p is not None else None def find_range( self, start, stop ): if not self.is_empty(): if start is None: p = self._first() else: p = self._find_position( start ) if p.key() < start: p = self._after( p ) while p is not None and (stop is None or p.key() < stop): yield (p.key(), p.value()) p = self._after( p ) def rebalance( self, p ): pass def _rebalance_access( self, p ): pass def _rebalance_delete( self, p ): pass def __getitem__( self, k ): if self.is_empty(): return False else: p = self._subtree_search( self.root(), k ) self._rebalance_access( p ) if k != p.key(): return False return p.value() def __str__( self ): pp = "[" for (k,v) in self.items(): pp += "(" + str( k ) + "," + str( v ) + ")" pp += "]" return pp def __setitem__( self, k, v ): if self.is_empty(): leaf = self._add_root( self._Item( k, v ) ) else: p = self._subtree_search( self.root(), k ) if p.key() == k: p.element()._value = v self._rebalance_access( p ) return else: item = self._Item( k, v ) if p.key() < k: leaf = self._add_right( p, item ) else: leaf = self._add_left( p, item ) self.rebalance( leaf ) def __iter__( self ): p = self._first() while p is not None: yield p.key() p = self._after( p ) def delete( self, p ): self._validate( p ) if self.left( p ) and self.right( p ): replacement = self._subtree_last_position( self.left( p ) ) self._replace( p, replacement.element() ) p = replacement parent = self.parent( p ) self._delete( p ) self._rebalance_delete( parent ) def __delitem__( self, k ): if not self.is_empty(): p = self._subtree_search( self.root(), k ) if k == p.key(): self.delete( p ) return self._rebalance_access( p ) return False """unit testing """ if __name__ == '__main__': print( "TreeMap unit testing..." ) # M = TreeMap( ) # nb = 500000 # random.seed( 131341 ) # avant = time.time() # for i in range( nb ): # key = random.randint( 0, nb ) # M[key] = key # apres = time.time() # print( "Insertion of", nb, "keys in ", apres-avant, "seconds." ) # avant = time.time() # for i in range( nb ): # key = random.randint( 0, nb ) # M.get( key ) # apres = time.time() # print( "Access to", nb, "keys in ", apres-avant, "seconds." ) # M = TreeMap( ) # print( len( M ) ) #0 # M['K'] = 2 # print( M ) # print( len( M ) ) # M['B'] = 4 # print( M ) # print( len( M ) ) # M['U'] = 2 # print( M ) # print( len( M ) ) # M['V'] = 8 # print( M ) # print( len( M ) ) # M['K'] = 9 # print( M ) # print( len( M ) ) # print( M['B'] ) # print( M['X'] ) # print( M.get( 'F' ) ) # print( M.get( 'F', 5 ) ) # print( M.get( 'K', 5 ) ) # print( M ) # print( len( M ) ) # del M['V'] # print( "pop(K) = ", M.pop( 'K' ) ) # print( M ) # for key in M.keys(): # print( str( key ) ) # for value in M.values(): # print( str( value ) ) # for item in M.items(): # print( str( item ) ) # print( M.setdefault( 'B', 1 ) ) # print( M.setdefault( 'AA', 1 ) ) # print( M ) # print( M.popitem() ) # print( M ) # print( M.find_min() ) # print( M.find_max() ) M = TreeMap() nb = 50 random.seed( 131341 ) avant = time.time() for i in range( nb ): key = random.randint( 0, nb ) M[key] = key apres = time.time() print( "Insertion of", nb, "keys in ", apres-avant, "seconds." ) print( M ) print( M.find_min() ) print( M.find_max() ) print( M.find_ge( 25 ) ) print( M.find_gt( 25 ) ) print( M.find_le( 25 ) ) print( M.find_lt( 25 ) ) print( M.find_lt( 0 ) ) for (x,y) in M.find_range( 12, 100 ): print( "x =", x, ", y =", y ) print( "End of testing." )
73e9644b93ddf3003e21689b3e7dbde15e3ff740
GiovanniCst/guessinggame
/main.py
2,715
3.765625
4
# -*- coding: UTF-8 -*- ''' This is a public domain - probably non-bug-free - "guess the number" game, dedicated to Edoardo, Benedetta, Viola, Annalice and all the little ones who will smile playing it. This software runs on python 2 (and probably 3) and requires emoji support: $ pip install emoji --upgrade run the game by typing: $ python main.py #TODO: - Sanitize user input so that the program does not break when the user inputs a string instead of an int - Not sure why the program breaks when accent letters (è à ù) are used, despite the shebang (probably that's an issue in Python 2 only) by Johnny Costantini, Pesaro, Italy. April 2019 ''' import random import emoji nome_giocatore = raw_input("Come ti chiami? ") print(emoji.emojize("Ciao " + nome_giocatore + "!! :smile: . Io sono un :computer: ed il mio nome e' HAL!", use_aliases=True)) numero_da_indovinare = random.randrange(1,10) numero_tentativi=3 # DEBUG ONLY print(numero_da_indovinare) while True: numero_indovinato = int(raw_input(nome_giocatore + " dimmi che numero ho pensato tra 1 e 9! : ")) if numero_indovinato == numero_da_indovinare: print(emoji.emojize("Fantastico " + nome_giocatore + ", hai indovinato! :heart_eyes: :candy: :thumbs_up: :heart_eyes: :thumbs_up:", use_aliases=True)) giochi_ancora = raw_input("### Vuoi giocare ancora ? si o no ? ") if giochi_ancora == "si": numero_da_indovinare = random.randrange(1,9) numero_tentativi = 3 else: print(emoji.emojize(":wave: :wave: :wave: :kissing_heart:", use_aliases=True)) break elif numero_indovinato < numero_da_indovinare and numero_tentativi > 1: numero_tentativi -= 1 print(emoji.emojize(" :grimacing: Peccato, " + nome_giocatore + " non e' giusto, il numero da indovinare e' piu' grande, riprova! Ti rimangono " + str(numero_tentativi) + " tentativi! :stuck_out_tongue_winking_eye: ", use_aliases=True)) elif numero_indovinato > numero_da_indovinare and numero_tentativi > 1: numero_tentativi -= 1 print(emoji.emojize(" :stuck_out_tongue_winking_eye: Peccato, " + nome_giocatore + " non e' giusto, il numero da indovinare e' piu' piccolo, riprova! Ti rimangono " + str(numero_tentativi) + " tentativi! :grimacing: ", use_aliases=True)) else: print(emoji.emojize(" :relieved: " + nome_giocatore + ", il numero da indovinare era " + str(numero_da_indovinare) + " !" + " Non hai piu' tentativi, ciao ciao! :kissing_heart:", use_aliases=True)) giochi_ancora = raw_input("# # # Vuoi giocare ancora? si o no ? ") if giochi_ancora == "si": numero_da_indovinare = random.randrange(1,9) numero_tentativi = 3 else: print(emoji.emojize(":wave: :wave: :wave: :kissing_heart:", use_aliases=True)) break
bf93b5760fe77c168bab1b12ca046df44978191f
AdamZhouSE/pythonHomework
/Code/CodeRecords/2666/48721/312637.py
77
3.640625
4
a=int(input()) for i in range(a): n=0 n=int(input()) print(2*n-2)
7934104c1585df34eaca957bc3107eab1453d9d4
AceSrc/datagon
/build/lib.linux-x86_64-2.7/datagon/generator/tokenizer.py
2,526
3.96875
4
def Tokenizer(input): current = 0 tokens = [] print(input) while current < len(input): char = input[current] if char == '(': tokens.append({ 'type': 'paren', 'value': '(', }) current += 1 continue if char == ')': tokens.append({ 'type': 'paren', 'value': ')', }) current += 1 continue if char == '[': tokens.append({ 'type': 'paren', 'value': '[', }) current += 1 continue if char == ']': tokens.append({ 'type': 'paren', 'value': ']', }) current += 1 continue if char.islower(): value = '' while char.islower() and current < len(input): value += char current += 1 char = input[current] tokens.append({ 'type': 'string', 'value': value, }) continue if char.isdigit() or char == '-': value = char current += 1 while current < len(input): char = input[current] if not char.isdigit(): break value += char current += 1 tokens.append({ 'type': 'number', 'value': value, }) continue if char == '\n': tokens.append({ 'type': 'format', 'value': 'newline', }) current += 1 continue if char == '#': tokens.append({ 'type': 'format', 'value': 'clearline', }) current += 1 continue if char == '=': tokens.append({ 'type': 'order', 'value': '=', }) current += 1 continue if char == ',': tokens.append({ 'type': 'format', 'value': ',' }) current += 1 continue if char == ' ' or char == '\r': current += 1 continue print("Invaild Syntax " + char) exit(1) return tokens
9eaa164cbf32fdfb44d7f7b6cd4c8e546397fe8a
AdamZhouSE/pythonHomework
/Code/CodeRecords/2541/60774/315601.py
206
3.75
4
n = int(input()) major = eval(input()) if(major == [[1,0],[2,0],[3,1],[3,2]]): print([1,2,3,4]) elif(major == [[1, 0]]): print([0,1]) elif(major == [[0, 1]]): print([1,0]) else: print(major)
a8f96b8a10ce972db0ca96c1543cd9804c10f787
hector116/INFO2019
/Ejercicio_5.py
219
4.15625
4
#Pide una cadena por teclado, mete los caracteres en una #lista sin repetir caracteres.Operador in lista=[] cadena=input("Ingrese una palabra: ") for i in cadena: if i not in lista: lista.append(i) print(lista)
8477cc4da5600ed06efda8e3a98e02e2f8ef4133
xica369/holbertonschool-machine_learning
/unsupervised_learning/0x02-hmm/2-absorbing.py
1,643
3.75
4
#!/usr/bin/env python3 """" Function that determines if a markov chain is absorbing: P: square 2D numpy.ndarray of shape (n, n) representing the transition matrix P[i, j] is the probability of transitioning from state i to state j n is the number of states in the markov chain Returns: True if it is absorbing, or False on failure """ import numpy as np def absorbing(P): """ Absorbing Chains """ try: n = P.shape[0] if P.shape != (n, n) or n < 1: return False if not np.isclose(np.sum(P, axis=1), 1).all(): return False if np.all(P <= 0): return False diag = P.diagonal() if np.all(diag == 1): return True if np.all(diag != 1): return False cont1 = 0 cont2 = 0 for pos in range(n): # check if there are two group of nodes that are not connecting rows = P[:pos + 1, pos + 1:] columns = P[pos + 1:, :pos + 1] if pos == n - 1: rows = P[n - 1, : n] columns = P[: n, n - 1] if np.all(rows == 0) and np.all(columns == 0): return False # check if all absorbent nodes only connect with themselves col = P[:pos, pos] _col = P[pos + 1:, pos] index = P[pos][pos] if index == 1: cont1 += 1 if np.all(col == 0) and np.all(_col == 0): cont2 += 1 if cont1 == cont2: return False return True except Exception: return True
55d7a953af99a8acfb170180fd20a8db55cd7bf1
Ant-Min/TextBasedGame
/TextBasedGame.py
3,660
3.859375
4
# Anthony Minunni print('Welcome to the game!') print('An alien has invaded your spaceship and killed all your crew members.') print('Go from room to room and collect all 6 items before escaping in the escape pod.') print('If you run into the alien before collecting all items, GAME OVER.') print('Commands: go North, go South, go East, go West, get item') print('------------------------------') def main(): # dictionary of rooms in the game rooms = { 'the Bridge': {'North': 'the Lab', 'item': 'none'}, 'the Lab': {'North': 'Communications', 'South': 'the Bridge', 'East': 'Medical', 'West': 'the Kitchen', 'item': 'Data Drive'}, 'Communications': {'South': 'the Lab', 'item': 'Radio'}, 'the Kitchen': {'North': 'Maintenance', 'East': 'the Lab', 'item': 'Food Ration'}, 'Maintenance': {'South': 'the Kitchen', 'item': 'Toolbox'}, 'Medical': {'North': 'the Escape Pod', 'South': 'the Quarters', 'West': 'the Lab', 'item': 'Cattle Prod'}, 'the Quarters': {'North': 'Medical', 'item': 'Spacesuit'}, 'the Escape Pod': {'South': 'Medical', 'item': 'Alien'} # the enemy; cannot be collected } # starts the player in the main room currentRoom = 'the Bridge' inventory = [] run = True while run: place = rooms[currentRoom] # This accesses the nested dictionary associated with currentRoom getter = place['item'] # reads item of the room print('You are in ' + currentRoom + '.') print('Item in room: ' + getter) print('Inventory:', inventory) if getter == 'Alien' and len(inventory) != 6: print('It\'s the alien! You don\'t have all the items you need to make your escape. ' 'You end up like the rest of your crew. GAME OVER') print('Thank you for playing. Try again if you\'re feeling brave.') break # break instead of setting run to false because the code would ask for the next move before exiting if getter == 'Alien' and len(inventory) == 6: print('The alien! It\'s in the escape pod! Good thing you have everything. ' 'You defend yourself against the alien and successfully escape. YOU WIN!') print('Thanks for playing!') break # break instead of setting run to false because the code would ask for the next move before exiting choice = input('Enter your move\n') if choice != 'go North' and choice != 'go South' and choice != 'go East' and choice != 'go West' \ and choice != 'get item': print('Invalid move') else: sep = choice.split(' ') direction = sep[1] if direction == 'item' and getter != 'none': inventory.append(getter) place['item'] = 'none' print('Item picked up') elif direction == 'item' and getter == 'none': print('No item in room') else: validity = 0 # This is to determine the player's update properly about their choice of direction for i in place.keys(): if direction == i: currentRoom = place[i] validity = 1 # if player entered a valid direction, validity reflects # this for if statement below if validity == 0: print('Not a valid direction') print('------------------------------') if __name__ == "__main__": main()
5e56f2c6423af6475cbbc529788aa34612ff10ed
emplam27/Python-Algorithm
/프로그래머스/카카오 2019 후보키.py
1,649
3.53125
4
""" dict를 이용해서 해보자. combination을 이용해서 컬럼을 선정한 후, (column1, column2, ...)를 key로 하여 탐색한다. defaultdict를 사용하여 없을경우 바로 value에 0을 넣어준다. 혹시나 key가 존재한다면 종료한다. """ from itertools import combinations def solution(relations): answer = 0 used_list = [] nums = [i for i in range(len(relations[0]))] for i in range(1, len(nums) + 1): combi_list = list(combinations(nums, i)) for combi_elem in combi_list: # 최소성 만족여부 확인 is_unique = True for used in used_list: if is_unique: selected = 0 for j in used: if j in combi_elem: selected += 1 continue if selected == len(used): # 최소성을 벗어나면 is_unique = False break if is_unique: # relation의 combi_elem 컬럼을 추가하며 검사 check_key = dict() for relation in relations: tmp_dict = [] for i in combi_elem: tmp_dict.append(relation[i]) tmp_dict = tuple(tmp_dict) if not check_key.get(tmp_dict): check_key[tmp_dict] = 1 else: break else: answer += 1 used_list.append(combi_elem) return answer
8945cffe0441b5a6b287d5c00a73064d3da66838
dkohlsdorf/udacity_selfdriving
/CarND-Traffic-Sign-Classifier-Project/lib_signs/preprocess.py
847
3.609375
4
import numpy as np def to_grayscale(img_stack): ''' Convert a stack of color images to grayscale :param img_stack: an image stack with n images of size w, h and with 3 color channels: (n, h, w, c) :returns: the gray scale image ''' r = img_stack[:, :, :, 0] / 3 g = img_stack[:, :, :, 1] / 3 b = img_stack[:, :, :, 2] / 3 return r + g + b def to_znorm(img_stack): ''' Normalize image stack to standard score :param img_stack: an image stack with n images of size w, h: (n, w, h) :returns: x ~ N(0, 1) ''' n, w, h = img_stack.shape flattened = img_stack.reshape(n, w * h) mu = np.mean(flattened, axis=1).reshape(n, 1) std = np.std(flattened, axis=1).reshape(n, 1) + 1 flattened = (flattened - mu) / std return flattened.reshape(n, w, h)
34a8deb2d08f0f0949f4bf89b4777664b1d6b912
PiotrWrobelAGH/Python
/zad15_complex.py
782
3.609375
4
#!/usr/bin/env python class Complex_numb: def __init__(self,a,b): self.a = a self.b = b def __add__(self, other): return Complex_numb(self.a+other.a, self.b+other.b) def __sub__(self, other): return Complex_numb(self.a-other.a, self.b-other.b) def __mul__(self, other): return Complex_numb(self.a*other.a-self.b*other.b, self.a*other.b+self.b*other.a) def __truediv__(self, other): othermin = other othermin.b = -othermin.b temp = self*othermin temp.a = temp.a/(other.a**2+other.b**2) temp.b = temp.b/(other.a**2+other.b**2) return temp def __str__(self): return f"{self.a}, {self.b}i" Ob1 = Complex_numb(1,8) Ob2 = Complex_numb(2,3) Ob3 = Ob1 / Ob2 print(Ob3)
bc88a2fa1c49d12c25ff294a31aa6b546951e7a3
forever89107/python_trainning
/python_class/instance2.py
994
4.21875
4
# Point 實體物件的設計: 平面座標上的點 # class Point: # def __init__(self, x, y): # self.x = x # self.y = y # # 定義實體方法 # def show(self): # print(self.x,self.y) # def distance(self , targetX , targetY): # return (((self.x - targetX)**2)+((self.y - targetY)**2))**0.5 # p1 = Point(3,4) # p1.show() # 呼叫實體方法 # result = p1.distance(0,0) # 計算座標(3,4)和座標(0,0)的距離 # print(result) # File 實體物件的設計: 包裝檔案讀取的程式 class File: def __init__(self, name): self.name = name self.file = None #尚未開啟檔案,初始化為 None def open(self): self.file=open(self.name,mode='r',encoding='utf-8') def read(self): return self.file.read() # 讀取第一個檔案 f1 = File("data1.txt") f1.open() data = f1.read() print(data) # 讀取第二個檔案 f2 = File("data2.txt") f2.open() data2 = f2.read() print(data2)
eda836e590593325794c263b8cb2c0de984fac07
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex15.py
606
3.71875
4
""" Usando switch, escreva um programa que leia um inteiro entre 1 e 7 e imprima o dia da semana correspondente a este número. Isto é, domingo se 1, segunda se, 2 e assim por diante. """ dia = int(input("Informe um número de 1 a 7: ")) if (dia > 0) and (dia < 8): if dia == 1: print("Domingo") elif dia == 2: print("Segunda") elif dia == 3: print("Terça") elif dia == 4: print("Quarta") elif dia == 5: print("Quinta") elif dia == 6: print("Sexta") elif dia == 7: print("Sábado") else: print("Número Inválido")
33139177465486973399564bd630b3635c7bdf4c
jz33/LeetCodeSolutions
/773 Sliding Puzzle.py
3,308
4.03125
4
''' 773. Sliding Puzzle https://leetcode.com/problems/sliding-puzzle/ On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]. Given a puzzle board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1. Examples: Input: board = [[1,2,3],[4,0,5]] Output: 1 Explanation: Swap the 0 and the 5 in one move. Input: board = [[1,2,3],[5,4,0]] Output: -1 Explanation: No number of moves will make the board solved. Input: board = [[4,1,2],[5,0,3]] Output: 5 Explanation: 5 is the smallest number of moves that solves the board. An example path: After move 0: [[4,1,2],[5,0,3]] After move 1: [[4,1,2],[0,5,3]] After move 2: [[0,1,2],[4,5,3]] After move 3: [[1,0,2],[4,5,3]] After move 4: [[1,2,0],[4,5,3]] After move 5: [[1,2,3],[4,5,0]] Input: board = [[3,2,4],[1,5,0]] Output: 14 Note: board will be a 2 x 3 array as described above. board[i][j] will be a permutation of [0, 1, 2, 3, 4, 5]. ''' from collections import deque from typing import Tuple class Solution: def findZero(self, tb: Tuple[int])-> int: for i in range(6): if tb[i] == 0: return i def getNewBoard(self, tb: Tuple[int], zi: int): ''' Return new board of 1 0 movement @tb: tupled board @zi: current zero index ''' board = list(tb) res = [] if zi != 0 and zi != 3: # swap 0 with left board[zi],board[zi-1] = board[zi-1],board[zi] res.append((tuple(board), zi-1)) board[zi],board[zi-1] = board[zi-1],board[zi] if zi != 2 and zi != 5: # swap 0 with right board[zi],board[zi+1] = board[zi+1],board[zi] res.append((tuple(board), zi+1)) board[zi],board[zi+1] = board[zi+1],board[zi] if zi < 3: # swap 0 down board[zi],board[zi+3] = board[zi+3],board[zi] res.append((tuple(board), zi+3)) else: # 3 <= z < 6 # swap 0 up board[zi],board[zi-3] = board[zi-3],board[zi] res.append((tuple(board), zi-3)) return res def slidingPuzzle(self, board: List[List[int]]) -> int: # Queue records board and position of 0 # Notice the board is flatten to tuple of 6 for hashing queue = deque() tb = tuple(board[0] + board[1]) queue.append((tb, self.findZero(tb))) # Records the visited board. Use tuple for hashing and comparison visited = set() visited.add(tb) depth = 0 while queue: for _ in range(len(queue)): tb, zi = queue.popleft() if tb == (1,2,3,4,5,0): return depth for b,z in self.getNewBoard(tb, zi): if b not in visited: visited.add(b) queue.append((b,z)) depth += 1 return -1
96a53129dc8df7c20a0c7bc65000a67c4f3d5442
mbg17/superlist
/day41/递归锁.py
1,018
3.875
4
from threading import Thread, RLock import time # 递归锁可以被多次acquire # acquire 一次必须对应的 release 一次 def eat(name, lock): for i in range(len(name)): lock.acquire() print(name[i]) lock.release() time.sleep(1) # lock.acquire() # print('%s拿到面条了' % name) # lock.acquire() # print('%s拿到叉子了' % name) # print('吃面了') # lock.release() # lock.release() def eat2(name, lock): for i in range(len(name)): lock.acquire() print(name[i]) lock.release() time.sleep(1) # lock.acquire() # print('%s拿到叉子了' % name) # time.sleep(2) # lock.acquire() # print('%s拿到面条了' % name) # print('吃面了') # lock.release() # lock.release() lock = RLock() l1 = [1, 2, 3, 4, 5] l2 = ['a', 'b', 'c', 'd', 'e'] Thread(target=eat, args=(l1, lock)).start() Thread(target=eat2, args=(l2, lock)).start()
c7d1ad07c21945fa1457c3899b7b59f9c17ea619
walterbeddoe/Batch17python
/for.py
171
3.8125
4
var= "Hola" for i in var: print(i) for i in var: print("La letra que toma i es:" + i) print("Acabe") for i in range(52,10000): print(i) print("Acabe")
f8dee16e17c36dfcad24547a5dca7750e53fb6e6
Jackthebighead/recruiment-2022
/algo_probs/jzoffer/jz15.py
1,331
3.609375
4
# 题意:请实现一个函数,输入一个整数(以二进制串形式),输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。 # 题解1: 注意输入的是int的10进制整数,所以用python的话要转换成2进制,可以用bin()函数转换为二进制的字符串,然后在用字符串的count()函数统计1的个数返回即可 # 题解2: 还可以用python的位运算符,按位运算符是把数字看作二进制来进行计算的。& | ^ ~ << >>分别表示按位与,或,异或,取反,向左移动,高位丢低位补 # 题解3: 用n&n-1操作。因为二进制条件下,n和n-1字符相与可以让n的最后一个1为0,其他不变,while循环至n为0即可 class Solution: def hammingWeight(self, n): # inputs: n: int # outputs: int return bin(n).count('1') class Solution_2: def hammingWeight(self, n): # inputs: n: int # outputs: int res = 0 while n: res += n & 1 n = n >> 1 return res class Solution_3: def hammingWeight(self, n): # inputs: n: int # outputs: int res = 0 while n: n = n&(n-1) res += 1 return res
b728f2ef6341571c777e281d49d823e6f6f98eb4
eterne92/COMP9021
/lab/lab_4/characters_triangle.py
1,045
3.828125
4
# Prompts the user for a strictly positive number N # and outputs an equilateral triangle of height N. # The top of the triangle (line 1) is labeled with the letter A. # For all nonzero p < N, line p+1 of the triangle is labeled # with letters that go up in alphabetical order modulo 26 # from the beginning of the line to the middle of the line, # starting wth the letter that comes next in alphabetical order # modulo 26 to the letter in the middle of line p, # and then down in alphabetical order modulo 26 # from the middle of the line to the end of the line. # Insert your code here try: level = int(input("Enter strictly positive number: ")) if level <= 0: raise ValueError except ValueError: exit() now = 0 for i in range(1,level+1): print_string = '' space_nb = level - i print(space_nb * ' ',end = '') for t in range(i): print_string += chr(now+65) now += 1 if(now == 26): now = 0 print_string = print_string + print_string[-2::-1] print(print_string)
00e467bae1ca35f799f9a58868db2ec299f39adc
basekim14/paulLab_codeFestival_py100
/cf_069.py
540
3.859375
4
# Code Festival - Python Practice 069 # Author : ㄱㄱㅊ # Title : Goldbach's Conjecture # Date : 20-04-21 # 함수 주석 def is_prime(a: int) -> bool: if(a<2): return False for i in range(2,a): if(a%i==0): return False return True def goldbach_conject(n): if not n > 2 or not n % 2 == 0: return result = [] for i in range(2, n // 2 + 1): if is_prime(i) and is_prime(n - i): result.append((i, n - i)) return result n = int(input()) print(goldbach_conject(n))
be2738f65b9fb0debf98878c080bfdeb682cc6e5
Midnight1Knight/HSE-course
/SecondeWeek/Task42.py
193
3.8125
4
num1 = int(input()) num2 = int(input()) while num1 > num2: if (num1 // 2 >= num2) and (num1 % 2 == 0): num1 /= 2 print(":2") else: num1 -= 1 print("-1")
fe3ae56192c97fba0c21578c9c2cf5e4a4b86163
virdesai/Courses
/560/HW2/HW2.py
13,887
3.75
4
############################# ## Homework 2 ## ## Name:Vir Desai ## ## Collaborators:None ## ############################# import sys, random, time # entry point for maze solver def hns(filename): friends, trees = openFileHS(filename) local(friends,trees) def local(friends, trees): count = 0 conflicts = 0 initialFriends = friends[:] for friend in friends:#1st iter to get current # of conflicts conflicts += currentConflicts(friend,friends[:],trees) while(conflicts != 0 and count < 100): count += 1 bestFriend = friends[0][:] rowMove = 0 diff = 0 for friend in friends: td, tr = rowConflicts(friend,friends[:],trees) if td >= diff: bestFriend = friend rowMove = tr diff = td friends[friends.index(bestFriend)][0]=rowMove conflicts = 0 for friend in friends: conflicts += currentConflicts(friend,friends[:],trees) if count == 100: print("Stuck in local minima on iteration: " + str(count)) print("Current friends positions with " + str(conflicts) + " conflicts left") print("Friend locations initialized as: ") for friend in initialFriends: print(str(friend[0]+1) + " " + str(friend[1]+1)) else: print("Iterations: " + str(count)) for friend in friends: print(str(friend[0]+1) + " " + str(friend[1]+1)) def rowConflicts(c, friends, trees): num = len(friends[:]) conflicts = currentConflicts(c,friends[:],trees) rowtrees = filter(lambda x: x[1] == c[1], trees) row = range(0,num) for a in rowtrees: row.remove(a[0]) bestRow = 0 diff = 0 for i in row: temp = currentConflicts([i,c[1]],friends[:],trees) if temp <= conflicts: diff += conflicts-temp conflicts = temp bestRow = i return (diff, bestRow) #for returning the amount of current conflicts a position c faces def currentConflicts(c, friends, trees): conflicts = 0 if c in friends: friends.remove(c) for f in friends: if abs(f[0]-c[0]) == abs(f[1]-c[1]):#diagonal check found = False for t in trees: if (((f[0]>t[0] and f[1]>t[1] and c[0]<t[0] and c[1]<t[1]) or (f[0]<t[0] and f[1]<t[1] and c[0]>t[0] and c[1]>t[1])) and abs(f[0]-t[0]) == abs(f[1]-t[1])): found = True if found == False: conflicts += 1 if f[0] == c[0]:#row check tempTrees = filter(lambda x: x[0] == f[0],trees) found = False for t in tempTrees: if (f[1]>t[1] and c[1]<t[1]) or (f[1]<t[1] and c[1]>t[1]): found = True if found == False: conflicts += 1 return conflicts #opening the file and instantiating necessary objects def openFileHS(fileName): num = 0 trees = [] friends = [] with open(fileName) as f: count = 0 for line in f: if count == 0: num = int(line.split()[0]) else: trees.append([int(i)-1 for i in line.split()]) count+=1 f.close() for i in range(0,num): r = range(0,num) temp = filter(lambda x: x[1] == i,trees) for a in temp: r.remove(a[0]) rand = random.choice(r) friends.append([rand,i]) return (friends, trees) #simple moving functions def up(current): if current[0] != 0: return [current[0]-1, current[1]] return False def down(current): if current[0] != 5: return [current[0]+1, current[1]] return False def right(current): if current[1] != 5: return [current[0], current[1]+1] return False def left(current): if current[1] != 0: return [current[0], current[1]-1] return False def openFileMM(fileName): with open(fileName) as f: data = [] owners = [] for line in f: data.append([int(i) for i in line.split()]) owners.append([0,0,0,0,0,0]) return (data, owners) def candy(limit1, limit2): files = ['AlmondJoy.txt','Ayds.txt','Bit-O-Honey.txt','Mounds.txt','ReesesPieces.txt'] for f in files: weights, owners = openFileMM(f) matchups = [[1,1],[2,2],[2,1],[1,2]] global tree, optimal tree = [] optimal = [] for match in matchups: for i in range(max(limit1,limit2)): tree.append([]) board = Board(weights[:], owners[:]) turns = 0 l1 = limit1 if match[0] == 1 else limit2 l2 = limit1 if match[1] == 1 else limit2 p1 = Player('Blue',match[0],1, l1) p2 = Player('Green',match[1],2, l2) turn = Turn(p1,p2) while(board.turns != 36): t1 = time.time() turn.get().execute(board,turn.get().limit,turn) t2 = time.time() turn.get().time += t2-t1 board.update(optimal[0],True,turn,0) turn.get().movesMade.append(optimal[0]) turn.switch() output(p1,p2,board,f,l1,l2,match[0],match[1]) del tree[:] wipe(owners) def wipe(array): del array[:] for i in range(6): array.append([]) for j in range(6): array[i].append(0) def output(p1, p2, board, f, limit1, limit2, alg1, alg2): d = {1:'Minimax', 2:'Alphabeta'} fileObject = open(f[:-4]+d[alg1]+str(limit1)+d[alg2]+str(limit2)+'Sol.txt','w') s = "On File: " + f + " with depth limit: " + str(limit1) + " on algorithm: " + d[alg1] + " for Blue/Player 1 and depth limit: " + str(limit2) + " on algorithm: " + d[alg2] + " for Green/Player2" print(s) fileObject.write(s + '\n' + '\n') d1 = {0:'A', 1:'B', 2:'C', 3:'D', 4:'E', 5:'F'} d2 = {1: 'Blue/Player 1', 2: 'Green/Player 2'} d3 = {1: 'B', 2:'G'} for i in range(18): move1 = p1.movesMade[i] move2 = p2.movesMade[i] if(i != 17): s = "Blue: drop " + d1[move1[1]] + str(move1[0]+1) + ", Green: drop " + d1[move2[1]] + str(move2[0]+1) + " then " print(s) fileObject.write(s + '\n') else: s = "Blue: drop " + d1[move1[1]] + str(move1[0]+1) + ", Green: drop " + d1[move2[1]] + str(move2[0]+1) fileObject.write(s + '\n' + '\n') print("Final State:") fileObject.write("Final State:\n") for i in range(6): for j in range(6): s = d1[j] + str(i+1) + ": " + d2[board.owners[i][j]] print(s) fileObject.write(s + '\n') fileObject.write('\n') for i in range(6): for j in range(6): fileObject.write(d3[board.owners[i][j]]+ '\t') fileObject.write('\n') s = "\nPlayer 1 Total Score: " + str(p1.score) print(s) fileObject.write(s + '\n') s = "Player 2 Total Score: " + str(p2.score) print(s) fileObject.write(s + '\n') s = "Total Nodes Expanded by Player 1: " + str(p1.expanded) print(s) fileObject.write(s + '\n') s = "Total Nodes Expanded by Player 2: " + str(p2.expanded) print(s) fileObject.write(s + '\n') s = "Avg Nodes Expanded by Player 1 per move: " + str(float(p1.expanded)/float(len(p1.movesMade))) print(s) fileObject.write(s + '\n') s = "Avg Nodes Expanded by Player 2 per move: " + str(float(p2.expanded)/float(len(p2.movesMade))) print(s) fileObject.write(s + '\n') s = "Avg Time Spent by Player 1 per move: " + str(float(p1.time)/float(len(p1.movesMade))) print(s) fileObject.write(s + '\n') s = "Avg Time Spent by Player 2 per move: " + str(float(p2.time)/float(len(p2.movesMade))) print(s) fileObject.write(s + '\n') fileObject.close() class Turn(object): def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 self.turn = True def switch(self): if self.turn == True: self.turn = False else: self.turn = True def get(self): if self.turn == True: return self.p1 return self.p2 def getopp(self): if self.turn == True: return self.p2 return self.p1 class Player(object): def __init__(self, name, algo, playerNum, limit): self.name = name self.num = playerNum self.algo = algo #1 is for minimax, 2 is for alphabeta self.limit = limit self.expanded = 0 self.score = 0 self.moved = 0 self.movesMade = [] self.time = 0 def execute(self, board, depth, turn): if self.algo == 1: self.minimax(board,depth,True,turn.get().score,turn.getopp().score,turn) else: self.alphabeta(board,depth,True,turn.get().score,turn.getopp().score,turn,-1000000,1000000) def minimax(self, board, depth, maxPlayer, st1, st2, turn): if depth == 0 or board.turns == 36: if self.limit %2 == 0: turn.get().expanded += 1 else: turn.getopp().expanded += 1 return turn.get().score - turn.getopp().score best = -1000000 if maxPlayer == True else 1000000 for i in range(6): for j in range(6): if board.owners[i][j] == 0: board.update([i,j],False,turn,depth) new1 = turn.get().score+board.add if maxPlayer == True else turn.get().score-board.sub new2 = turn.getopp().score+board.add if maxPlayer == False else turn.getopp().score-board.sub turn.switch() value = self.minimax(board,depth-1,not maxPlayer,new1,new2,turn) turn.switch() best = max(best,value) if maxPlayer == True else min(best,value) if depth == self.limit and best == value: del optimal[:] optimal.append([i,j]) board.clearupdate([i,j],turn,depth) return best def alphabeta(self, board, depth, maxPlayer, st1, st2, turn, alpha, beta): if depth == 0 or board.turns == 36: if self.limit %2 == 0: turn.get().expanded += 1 else: turn.getopp().expanded += 1 return turn.get().score - turn.getopp().score if maxPlayer == True: for i in range(6): for j in range(6): if board.owners[i][j] == 0: board.update([i,j],False,turn,depth) new1 = turn.get().score+board.add if maxPlayer == True else turn.get().score-board.sub new2 = turn.getopp().score+board.add if maxPlayer == False else turn.getopp().score-board.sub turn.switch() value = self.alphabeta(board,depth-1,not maxPlayer,new1,new2,turn,alpha,beta) turn.switch() if value > alpha: alpha = value if depth == self.limit: del optimal[:] optimal.append([i,j]) board.clearupdate([i,j],turn,depth) if beta <= alpha: break if beta <= alpha: break return alpha else: for i in range(6): for j in range(6): if board.owners[i][j] == 0: board.update([i,j],False,turn,depth) new1 = turn.get().score+board.add if maxPlayer == True else turn.get().score-board.sub new2 = turn.getopp().score+board.add if maxPlayer == False else turn.getopp().score-board.sub turn.switch() value = self.alphabeta(board,depth-1,not maxPlayer,new1,new2,turn,alpha,beta) turn.switch() if value < beta: beta = value if depth == self.limit: del optimal[:] optimal.append([i,j]) board.clearupdate([i,j],turn,depth) if beta <= alpha: break if beta <= alpha: break return beta class Board(object): def __init__(self, weights, owners): self.weights = weights self.reset = owners self.owners = owners self.turns = 0 self.add = 0 self.sub = 0 def owner(self, current): return self.owners[current[0]][current[1]] def weight(self, current): return self.weights[current[0]][current[1]] def setOwner(self, current, player): if type(player) is int: self.owners[current[0]][current[1]] = 0 else: self.owners[current[0]][current[1]] = player.num def neighbors(self, current, player): if up(current) != False: if self.owners[current[0]-1][current[1]] == player.num: return True if down(current) != False: if self.owners[current[0]+1][current[1]] == player.num: return True if left(current) != False: if self.owners[current[0]][current[1]-1] == player.num: return True if right(current) != False: if self.owners[current[0]][current[1]+1] == player.num: return True return False def takeNeighbors(self, current, turn, depth): self.take(up(current),turn,depth) self.take(down(current),turn,depth) self.take(left(current),turn,depth) self.take(right(current),turn,depth) def take(self, current, turn, depth): if current == False or self.owner(current) != turn.getopp().num: return else: if self.owner(current) == turn.getopp().num: self.sub += self.weight(current) self.add += self.weight(current) self.setOwner(current, turn.get()) if type(depth) is int: tree[depth].append(current) def update(self, current, actual, turn, depth): self.add = 0 self.sub = 0 if self.turns == 36 or self.owner(current) != 0: return False self.turns += 1 self.add += self.weight(current) self.setOwner(current,turn.get()) if type(depth) is int: del tree[depth-1][:] if self.neighbors(current,turn.get()) == True: self.takeNeighbors(current,turn,depth-1) if actual == True: turn.get().score += self.add turn.getopp().score -= self.sub return True def clearupdate(self, current, turn, depth): self.turns -= 1 self.setOwner(current, 0) for i in range(len(tree[depth-1])): self.setOwner(tree[depth-1][i],turn.getopp()) self.add = 0 self.sub = 0 def reset(self): self.owners = self.reset[:] self.turns = 0 self.add = 0 self.sub = 0 #Main Function if __name__== '__main__': print("Local Search for Friends in Forest Hide & Seek Game With Standard Input Given") for i in range(5): hns('input.txt') print("") print("") print("Part 3 Game Executions") for i in range(2,4): for j in range(2,6): print("") candy(i,j) print("")
cacbdfa2bf123968441fb4ac4a73b97910ff31c8
samarthdave/nagini
/10daysofstats/1_iqr.py
1,503
4.09375
4
#!/bin/python3 # # Complete the 'interQuartile' function below. # # The function accepts following parameters: # 1. INTEGER_ARRAY values # 2. INTEGER_ARRAY freqs # def split_arr(arr): n = len(arr) middle = n // 2 if n % 2 == 0: return arr[0:middle], arr[middle:] else: # if odd, exclude middle item # note, Python list slicing is exclusive on endpoint return arr[0:middle], arr[middle + 1:] def get_median(lst, avoid_sort=False): if not avoid_sort: lst.sort() n = len(lst) mid_right = n // 2 if n % 2 == 0: mid_left = mid_right - 1 return int((lst[mid_left] + lst[mid_right]) / 2) return int(lst[mid_right]) def quartiles(arr): # Write your code here arr.sort() left_arr, right_arr = split_arr(arr) q_1 = get_median(left_arr, avoid_sort=True) q_2 = get_median(arr, avoid_sort=True) q_3 = get_median(right_arr, avoid_sort=True) return [q_1, q_2, q_3] def interQuartile(values, freqs): # Print your answer to 1 decimal place within this function combined = list(zip(values, freqs)) combined.sort(key=lambda x: x[0]) arr = [] for pair in combined: curr = [pair[0]] * pair[1] arr += curr lst = quartiles(arr) print(float(lst[2] - lst[0])) if __name__ == '__main__': n = int(input().strip()) val = list(map(int, input().rstrip().split())) freq = list(map(int, input().rstrip().split())) interQuartile(val, freq)
327ed9f84a89a763a0e98456a4bdebe8729c01ce
VennyCooper/FancyPython
/Users/Luo/LeetCode/Q973_KClosestPointstoOrigin_medium.py
2,017
3.5625
4
# We have a list of points on the plane. Find the K closest points to the origin (0, 0). # (Here, the distance between two points on a plane is the Euclidean distance.) # You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.) # Example 1: # Input: points = [[1,3],[-2,2]], K = 1 # Output: [[-2,2]] # Explanation: # The distance between (1, 3) and the origin is sqrt(10). # The distance between (-2, 2) and the origin is sqrt(8). # Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. # We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]]. # Example 2: # Input: points = [[3,3],[5,-1],[-2,4]], K = 2 # Output: [[3,3],[-2,4]] # (The answer [[-2,4],[3,3]] would also be accepted.) # Note: # 1 <= K <= points.length <= 10000 # -10000 < points[i][0] < 10000 # -10000 < points[i][1] < 10000 # Divide and Conquer class Solution_1: import random as rd def kClosest(self, points: list, K: int) -> list: return self.sort(0, len(points) - 1, K) def sort(self, p: list, start, end, K) -> list: r = rd.randint(start, end) # index of the pivot p[start], p[r] = p[r], p[start] # move the pivot to the start of current partition pass def partition(self, p: list, start, end) -> int: old_start = start pivot_dist = self.cal_dist_sq(p[start][0], p[start][1]) start += 1 # move start(left pointer) to the right by 1 while True: while self.cal_dist_sq(p[start][0], p[start][1]) < pivot_dist: start += 1 while self.cal_dist_sq(p[end][0], p[end][1]) >= pivot_dist: end -= 1 if start >= end: break # TODO p[old_start], [] pass def cal_dist_sq(self, x, y): return x**2 + y**2 s = Solution_1() points = [[1,3],[-2,2]] K = 1 print(s.kClosest(points, K)) points = [[3,3],[5,-1],[-2,4]] K=2 print(s.kClosest(points, K))
8261c2942818778e72f62214930e5598b9cf767f
Rgtwitch/I-want-to-crate-Game-
/info.py
3,500
3.671875
4
class info(object): def __init__(self): self.health = 10 self.expiriance = 0 self.maxexpiriance = 2 self.strenght = 10 self.mana = 100 self.level = 1 self.localization = 0 def ChoseLocal(self): print("Choose localization:") print("Eng") print("Rus") self.localization = input() def getInfo(self): if self.localization == "Rus": print("Здоровье -", self.health) print("Сила -", self.strenght) print("Мана -", self.mana) print("Опыт -", "+" * self.expiriance, "-" * (self.maxexpiriance - self.expiriance), self.expiriance) print("Уровень -", self.level) elif self.localization == "Eng": print("Health -", self.health) print("Strenght -", self.strenght) print("Mana -", self.mana) print("Experience -", "+" * self.expiriance, "-" * (self.maxexpiriance - self.expiriance), self.expiriance) print("Level -", self.level) def getHelth(self): return self.health def getStrenght(self): return self.strenght def getMana(self): return self.mana def getExp(self): return self.expiriance def getLvl(self): return self.level def addHelth(self, count): self.health = self.health + count def addStrenght(self, count): self.strenght = self.strenght + count def addMana(self, count): self.mana = self.strenght + count def addExpiriance(self, count): self.expiriance = self.expiriance + count if self.expiriance >= self.maxexpiriance: self.maxexpiriance = self.maxexpiriance * 2 self.level += 1 BeAChose = False while not BeAChose: if self.localization == "Eng": print("Skill point available!") print("1 - Mana") print("2 - Strenght") print("3 - Health") elif self.localization == "Rus": print("Доступно очко навыков!") print("1 - Мана") print("2 - Сила") print("3 - Жизни") chose = int(input()) if chose == 1: self.mana = self.mana + (self.mana // 2) BeAChose = True if self.localization == "Eng": print("Mana =", self.mana) if self.localization == "Rus": print("Мана", self.mana) elif chose == 2: self.strenght = self.strenght + (self.strenght // 2) BeAChose = True if self.localization == "Eng": print("strenght =", self.strenght) if self.localization == "Rus": print("Сила =", self.strenght) elif chose == 3: self.health = self.strenght + (self.strenght // 2) BeAChose = True if self.localization == "Eng": print("Health =", self.health) if self.localization == "Rus": print("Жизни", self.health)
e23b74c78f08d70c479057a2f1ecddb03a790032
Laura05010/CTCI_Study_Repo
/Week_1/CHAPTER2/Q4.py
3,762
4.34375
4
# TODO: # Partition: Write code to partition a linked list around a value x, such that all nodes less than x come # before all nodes greater than or equal to x. If x is contained within the list, the values of x only need # to be after the elements less than x (see below). The partition element x can appear anywhere in the # "right partition"; it does not need to appear between the left and right partitions. # EXAMPLE # Input: # Output: # 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 [partition= 5] # 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8 from __future__ import annotations from typing import Optional, Any, List # We use a preceding underscore for the class name to indicate # that this entire class is private: # it shouldn’t be accessed by client code directly, # but instead is only used by the “main” class described in the next section. class _Node: """A node in a linked list. Note that this is considered a "private class", one which is only meant to be used in this module by the LinkedList class, but not by client code. === Attributes === item: The data stored in this node. next: The next node in the list, or None if there are no more nodes. """ item: Any #next: Optional[_Node] def __init__(self, item: Any) -> None: """Initialize a new node storing <item>, with no next node. """ self.item = item # Basically each node hold the item and a reference to the next item!!! self.next = None # Initially pointing to nothing class LinkedList: """A linked list implementation of the List ADT. """ # === Private Attributes === # The first node in this linked list, or None if this list is empty. _first: Optional[_Node] def __init__(self) -> None: """Initialize an empty linked list. """ self._first = None # More GENERAL initializer?? # def __init__(self, items: list) -> None: # """Initialize a new linked list containing the given items. # The first node in the linked list contains the first item # in <items>. # """ # self._first = None # for item in items: # self.append(item) # Transversing Linked Lists def print_items(self) -> None: """Print out each item of the linked_list""" curr = self._first while curr is not None: print(curr.item) curr = curr.next def append(self, item: Any) -> None: """Add the given item to the end of this linked list.""" curr = self._first if curr is None: # add the new node to the list new_node = _Node(item) # Creates new node self._first = new_node # Actually assigns to linked list else: #1. go through the linked list and find last item #2. assign reference to last items.next while curr.next is not None: curr = curr.next # Here we know that curr.next is None new_node = _Node(item) curr.next = new_node def partition(self, partition_item: Any) -> None: """ Partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. """ lower = LinkedList() upper = LinkedList() curr = self._first while curr is not None: if curr.item < partition_item: lower.append(curr.item) else: upper.append(curr.item) curr = curr.next curr_lower = lower._first while curr_lower.next is not None: curr_lower = curr_lower.next curr_lower.next = upper._first self = lower
194f3e2510871dc51664948d727aa30a59efcec0
Superhzf/python_exercise
/Array/Next Permutation/solution.py
686
3.578125
4
class Solution: def nextPermutation(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ i = len(nums) - 2 while i >= 0 and nums[i+1] <= nums[i]: i -= 1 if i >= 0: j = len(nums) - 1 while j >= 0 and nums[j] <= nums[i]: j -= 1 nums[i], nums[j] = nums[j], nums[i] nums[i+1:] = nums[i+1:][::-1] # Step 1: find the first element i from the right such that nums[i+1] > nums[i] # Step 2: find the largest element j from the right such that nums[j] > nums[i] # Step 3: swap nums[i] and nums[j] # Step 4: reverse nums[i+1:]
a662b66cee40b43816496654b62db060f8353f12
thesecondshade/math-with-python
/2_Plotting.py
240
3.5625
4
''' Simple plot using pyplot ''' import matplotlib.pyplot def create_graph(): x_numbers = [1,2,3] y_numbers = [2,4,6] matplotlib.pyplot.plot(x_numbers,y_numbers) matplotlib.pyplot.show() if __name__ == '__main__': create_graph()
b223ac31d749ba0d4e228bf1aac910a09cf43b82
knowtheroot/LeetCode_Python
/climbStairs.py
489
3.515625
4
class Solution: def climbStairs(self, n: int) -> int: #到达第 i 阶的方法总数就是到第 (i−1) 阶和第 (i−2) 阶的方法数之和 #因为最后到达不是走1步就是走2步 #数组res,第n-1步就是结果 if n == 0: return 1 if n == 1: return 1 res = [1,2] for i in range(2,n): res.append(res[i-1]+res[i-2]) return res[n-1] s = Solution() print(s.climbStairs(3))
ef73bd3bfed72167113c413afd5df972288c32ab
julien-sobczak/anki-scripting
/anki-vocabulary-assistant/scripts/search_commonly_mispelled_words.py
2,415
3.578125
4
#!/usr/bin/env python """ Demo script to demonstrate how to scrap www.linguee.fr """ import requests # to call Linguee from bs4 import BeautifulSoup # to parse response starts_after="giraffe" started=False # We read the input file with open("commonly_mispelled_words-refined.txt") as fi: # We open the output file with open("commonly_mispelled_words-refined-with-sentences.txt", "a") as fo: for line in fi.readlines(): fields = line.strip().split(",") en_word = fields[0] enfr_word = fields[1] fr_word = fields[2] if en_word == starts_after: started=True continue if not started: continue # Get Linguee dictionary content url = 'http://www.linguee.com/english-french/search?source=auto&query=%s' % en_word headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', 'Referer': 'http://www.linguee.fr/', 'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', } r = requests.get(url, headers=headers) # Check response if r.status_code != 200: raise ValueError("Invalid status code '%s'" % r.status_code) html_doc = r.text soup = BeautifulSoup(html_doc, 'html.parser') # List the dictionary's examples print("\n[en=%s, fr=%s]. Sentence(s):" % (en_word, fr_word)) sentences = [] examples = soup.select("#dictionary .isMainTerm .example.line .tag_s") selected_sentence = "" if len(examples): for i, example in enumerate(examples): if i > 8: break s = example.get_text() print("[%s] %s" % ((i + 1), s)) sentences.append(s) answer = input("Choose: ") selected_sentence = sentences[int(answer) - 1].strip() fo.write("%s,%s,%s,%s\n" % (en_word, enfr_word, fr_word, selected_sentence))
a7e1bcd45e24ca8851d55c7c4e642e498ccb8c30
tashytypes/comp7230
/lecture2-3/babylonianAlgorithm.py
274
4.3125
4
#function to compute a square root using the Babylonian Algorithm def square_root(x): y = 0.5 * x t = 1 while (abs(y * y - x) > 1.0e-6): y = 0.5 * (y + x/y) print("Type of y %s" % type(t)) return y print("Square root: %s" % square_root(10))
f5f9c827558afdb320c62c27108d1f018d63403a
axeltidemann/propeller
/tacos/tacos_htm_to_csv.py
1,111
3.515625
4
''' Converting cleaned HTML files to CSV. python tacos_htm_to_csv.py /path/to/files_that_are*cleaned Author: Axel.Tidemann@telenor.com ''' from __future__ import print_function import sys from lxml.html import parse for input_file in sys.argv[1:]: with open('{}.csv'.format(input_file[:input_file.find('.htm')]),'w') as file: page = parse(input_file) tables = page.xpath('body/div/center/table') for table in tables: rows = table.findall('tr') skipped = 0 for i,row in enumerate(rows[:-2]): # The last two lines are blank + navigation children = row.getchildren() if children[0].text_content().strip() == '': # Blank first index. No. skipped += 1 else: print(','.join([ col.text_content().strip().replace(',', ' ').encode('ascii', 'ignore').decode('ascii') for col in children ]), file=file) print('{}: {} rows saved to csv format, {} skipped because of blank indices.'.format(input_file, i-skipped, skipped))
6082a5f1dfb24fbcf6a975ef81ef05dae4b59479
namy112/PythonPractice
/generator.py
353
3.734375
4
""" Question: Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. Hints: Consider use yield """ n= input("Please enter a number..") def generateWorks(n): for number in range(1,n+1): if number%7==0: yield number for i in generateWorks(n): print(i)
431ee157f17480b80614d399216093ff436a57a1
Holstrup/ObjectRecognition
/ObjectRecognition/Multi-Shot/knn.py
1,243
3.703125
4
from sklearn.neighbors import NearestNeighbors from database_actions import get_known_encodings import numpy as np def knn_function(encoding): """ Once being trained, the already existent data will be clustered corresponding to their nature. Thus, by comparing the encodings and finding the 1 nearest neighbour, we will assign the new sample to the proper cluster via its label. :param encoding: Encoding of an image :return: Predicted label of the image """ samples = get_known_encodings()[0].transpose() neigh = NearestNeighbors(n_neighbors=1) neigh.fit(samples) i = neigh.kneighbors(encoding, return_distance=False) label = get_known_encodings()[1][i[0][0]] return label def new_knn_function(encodings): """ Function that returns the nearest neighbor to an image encoding :param encodings: Vector of encoding for an image (128,) :return: Predicted label (int) """ vector_encoding = encodings matrix_encodings, labels = get_known_encodings() dif_matrix = np.subtract(np.transpose(matrix_encodings), vector_encoding) norm_vector = np.linalg.norm(dif_matrix, axis=1) predicted_label = int(labels[np.argmin(norm_vector)]) return predicted_label
a8ea000ddd67c384ee8cad5fd27e550709f3a9ec
renankemiya/exercicios
/2.Estrutura_De_Decisão_wiki.Python/estrutura_de_decisão_3.py
551
4.15625
4
# Faça um Programa que verifique se uma letra digitada é "F" ou "M". # Conforme a letra escrever: F - Feminino, M - Masculino, Sexo Inválido. sexo = input('Insira F ou M para informar seu genero: ') if sexo == 'F': print('Feminino') elif sexo == 'M': print('Masculino') else: print('Sexo inválido') # Correção da internet sexo = input("digite seu sexo \"F\" ou \"M\": ") if sexo == "F" or sexo == "M": if sexo == "F": print("F - Feminino") else: print("M - Masculino") else: print("sexo invalido")
fa7572325fe30445a82a270106a60c9d725ecfad
qiuyuguo/bioinfo_toolbox
/sandbox/python/PM599/QB3.4.1/scope.py
454
3.8125
4
def myFunc(a): a += 1 print 'in myFunc: a = %d' % a b = 1 print b myFunc(b) print b def myFunc2(a): a[0] += 1 print 'in myFunc: a[0] = %d' % a[0] b = [1,2] print b myFunc2(b) #here b is passed as reference, so change to its elements is persitent print b def myFunc3(a): a[0] += 1 print 'in myFunc: a[0] = %d' % a[0] b = {0:1,1:2} print b myFunc3(b) #here b is passed as reference, so change to its elements is persitent print b
fd449ac3eb63784256d955c0f957ea8fcd66a827
PikKACHUU/Deep-learning
/cnn/cnn2.py
4,781
3.5625
4
import tensorflow as tf import tensorflow.examples.tutorials.mnist.input_data as input_data #Download and load dataset mnist_dataset = input_data.read_data_sets("MNIST_data/", one_hot=True) m = tf.placeholder(tf.float32, shape=[None, 784]) n= tf.placeholder(tf.float32, shape=[None, 10]) W = tf.Variable(tf.zeros([784,10])) b = tf.Variable(tf.zeros([10])) #initialise weight and bias # m is the trained image and the n is the label of the image #print dataset information train_images = mnist_dataset.train.images print('train_images',train_images.shape) train_labels = mnist_dataset.train.labels print('train_labels',train_labels.shape) test_images = mnist_dataset.test.images print('test_images',test_images.shape) test_labels = mnist_dataset.test.labels print('test_labels',test_labels.shape) #define a function to initialise all weight W def weight(s): initial = tf.truncated_normal(s, stddev=0.1) return tf.Variable(initial) #define a function to initialise all bias variables b def bias(s): initial = tf.constant(0.1, shape=s) return tf.Variable(initial) #define a function to construct convolution layer def convolution_layer(m, W): return tf.nn.conv2d(m, W, strides=[1, 1, 1, 1], padding='SAME') #define a function to construct a pool layer def pool(m, k): return tf.nn.max_pool(m, ksize=[1, k, k, 1],strides=[1, k, k, 1], padding='SAME') def norm(m,size=4): return tf.nn.lrn(m,size,bias=1.0,alpha=0.001/9.0,beta =0.75) #construct the CNN neural network m_image = tf.reshape(m, [-1,28,28,1]) W_conv1 = weight([3, 3, 1, 64]) b_conv1 = bias([64]) #First convolutional layer l_conv1 = tf.nn.relu(convolution_layer(m_image, W_conv1) + b_conv1) #First pool layer l_pool1 = pool(l_conv1 , 2) norm1 = norm(l_pool1,size=4) W_conv2 = weight([3,3,64,128]) b_conv2 = bias([128]) #Second convolutional layer l_conv2 = tf.nn.relu(convolution_layer(norm1, W_conv2) + b_conv2) #Second pool layer l_pool2 = pool(l_conv2 , 2) norm2 = norm(l_pool2 , size=4) W_conv3 = weight([3,3,128,256]) b_conv3 = bias([256]) #Third convolutional layer l_conv3 = tf.nn.relu(convolution_layer(norm2, W_conv3) + b_conv3) #third pool layer l_pool3 =pool(l_conv3 , 2) norm3 = norm(l_pool3 , size=4) W_conv4 = weight([3,3,256,384]) b_conv4 = bias([384]) #Third convolutional layer l_conv4 = tf.nn.relu(convolution_layer(norm3, W_conv4) + b_conv4) #third pool layer norm4 = norm(l_conv4 , size=4) W_fc1 = weight([4*4*256, 1024]) b_fc1 = bias([1024]) l_norm3_vec = tf.reshape(norm4, [-1, 4*4*256]) #First full-connected layer l_norm3_vec = tf.nn.relu(tf.matmul(l_norm3_vec, W_fc1) + b_fc1) prob = tf.placeholder("float") #drop out layer l_norm3_vec = tf.nn.dropout(l_norm3_vec, prob) #Second full-connected layer W_fc2 = weight([1024,1024]) b_fc2 = bias([1024]) vec2 = tf.reshape(l_norm3_vec, [-1, 1024]) vec2 = tf.nn.relu(tf.matmul(l_norm3_vec, W_fc2) + b_fc2) vec2 = tf.nn.dropout(vec2, prob) #out layer out = tf.matmul(vec2,weight([1024,10])) + bias([10]) #corss entropy is the loss function loss= tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = out, labels = n)) train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss) #Gradient descent prediction = tf.equal(tf.argmax(out,1), tf.argmax(n,1)) #calculate accuracy accuracy = tf.reduce_mean(tf.cast(prediction, "float")) sess=tf.InteractiveSession() sess.run(tf.global_variables_initializer()) a=0 while a<5: for loop in range(10000): batch_x,batch_y = mnist_dataset.train.next_batch(64) if loop%100 == 0: train_step.run(feed_dict={m: batch_x, n: batch_y, prob: 0.5}) acc = accuracy.eval(feed_dict={m:batch_x, n: batch_y, prob: 1.0}) test_acc=accuracy.eval(feed_dict={m: mnist_dataset.test.images, n: mnist_dataset.test.labels, prob: 1.0}) print("test accuracy",test_acc) a+=1 def predict(c): pre=tf.argmax (out, 1).eval(session=sess,feed_dict={m: mnist_dataset.test.images,n:mnist_dataset.test.labels,prob:1.0}) print('the prediction of front {} images is: '.format(c)) for i in range(c): print(pre[i],end=',') if int((i+1)%5) ==0: print('\t') return pre predict(20) #predict the label of front twenty images def original(c): org = tf.argmax(n,1).eval(session=sess,feed_dict={m:mnist_dataset.test.images,n:mnist_dataset.test.labels,prob:1.0}) print('the front {} images is: '.format(c)) for i in range(c): print(org[i],end=',') if int((i+1)%5) ==0: print('\t') return org original(20) #original label of fron twenty images
fb8451c841b666fc68d88698094ccec947254000
mach856549/Admission_Procedure
/university.py
8,364
3.765625
4
global departments, dict_department_applicants, placed_students, test_score_column, original_scores, full_applicant_list departments = sorted(["Biotech", "Chemistry", "Engineering", "Mathematics", "Physics"]) # Test Scores from original input "applicant.txt" original_scores = {"Physics": 2, "Chemistry": 3, "Mathematics": 4, "ComputerScience": 5, "Special": 6} # Acceptance scores column references from new processed input "applicant_assessment.txt" test_score_column = {"Biotech": 2, "Chemistry": 3, "Engineering": 4, "Mathematics": 5, "Physics": 6} placed_students = 0 dict_department_applicants = {} full_applicant_list = [] def create_list_from_file(): """Return the list of candidates from a file. No Sorting at this stage """ global full_applicant_list with open("applicants_assessment.txt", "r") as applicant_file: for line in applicant_file.readlines(): full_applicant_list.append(line.split()) def add_consolidated_scores(list_): """Calculate and add the consolidated scores to each students information. Physics requires: (Maths + Physics) / 2 --> New Column = 9 Engineering requires: (Computer science + Maths) / 2 --> New Column = 10 Biotech requires: (Chemistry + Physics) / 2 --> New Column = 11 These additional scores are calculated and added to the student information. """ # These scores could have been calculated at time of filter but it is easier to include them as part of # the student list at this stage since all filtering is done within students_to_consider() and based on # test_score_column dictionary for student in list_: phys = calc_average(student, "Physics", "Mathematics") eng = calc_average(student, "ComputerScience", "Mathematics") bio = calc_average(student, "Physics", "Chemistry") student.extend([phys, eng, bio]) return list_ def process_input(): """Create new input file replacing original exam scores with assessment scores. Output Format for "applicant_assessment.txt" ------------------THESE CONTAIN THE SCORES USED FOR ACCEPTANCE (i.e. MAX SPECIAL EXAM or RELEVANT AVERAGE)------- <first_name> <last_name> <Biotech> <Chemistry> <Engineering> <Mathematics> <Physics> <Choice1> <Choice2> <Choice3> Biotech requires: MAX: (Chemistry + Physics) / 2 OR Special Exam Chemistry requires: MAX Chemistry OR Special Exam Engineering requires: MAX: (Computer science + Maths) / 2 OR Special Exam Mathematics requires: MAX: Maths OR Special Exam Physics requires: MAX: (Maths + Physics) / 2 OR Special Exam These acceptance scores are calculated and a new file "applicant_assessment.txt" create. """ with open("applicants.txt", "r") as applicant_file, open("applicants_assessment.txt", "wt") as out_f: for line in applicant_file.readlines(): student_orig = line.split() first_name = student_orig[0] last_name = student_orig[1] special_exam = float(student_orig[6]) choice1 = student_orig[7] choice2 = student_orig[8] choice3 = student_orig[9] bio = round(max(calc_average(student_orig, "Physics", "Chemistry"), special_exam), 1) chem = round(max(float(student_orig[original_scores.get("Chemistry")]), special_exam), 1) eng = round(max(calc_average(student_orig, "ComputerScience", "Mathematics"), special_exam), 1) maths = round(max(float(student_orig[original_scores.get("Mathematics")]), special_exam), 1) phys = round(max(calc_average(student_orig, "Physics", "Mathematics"), special_exam), 1) out_f.write(f"{first_name} {last_name} {bio} {chem} {eng} {maths} {phys} {choice1} {choice2} {choice3}\n") def calc_average(list_, sub1, sub2): """Return the average of two test scores as float. list_ = individual student list sub1 = subject name from list original_scores sub2 = subject name from list original_scores """ return round((float(list_[original_scores.get(sub1)]) + float(list_[original_scores.get(sub2)])) / 2, 1) def assign_students_to_department(): """Create a dictionary of lists with key as defined in departments variable. 'departments' variable - Defines all of the possible primary departments 'max_students' - User Input to define the maximum students permitted in each department Create a dictionary of format {department: [sorted list of students accepted into this department]} """ global departments, dict_department_applicants, placed_students, test_score_column max_students = int(input("Enter maximum number of students in a department")) # Create the department list dictionary and fill with successful students who made primary choice. for dep in departments: applicant_list = students_to_consider(full_applicant_list, dep, 1) if len(applicant_list) > max_students: applicant_list = applicant_list[:max_students] dict_department_applicants[dep] = applicant_list find_unplaced_students() for dep_list in dict_department_applicants.values(): placed_students += len(dep_list) if len(unassigned_students) > 0: for i in range(2, 4): # 2 for 2nd choice, 3 for 3rd choice. # Check for unfilled space in each department and then populate it for dep_item in dict_department_applicants.items(): if len(dep_item[1]) < max_students: number_to_admit = max_students - len(dep_item[1]) extra_students = students_to_consider(unassigned_students, dep_item[0], i) if number_to_admit <= len(extra_students): extra_students = extra_students[:number_to_admit] dep_item[1].extend(extra_students) for student in extra_students: unassigned_students.remove(student) dep_item[1].sort(key=lambda x: (-float(x[test_score_column.get(dep_item[0])]), x[0] + x[1])) def students_to_consider(list_, subject, num): """Return a filtered list of unassigned students sorted based on correct score. Take list, subject and choice (1, 2 or 3) corresponding to 1st, 2nd or 3rd choice. Return a filtered list containing only students who; - have not been allocated yet - chose the subject as their 1st, 2nd or 3rd choice - sorted by relevant score """ local_list = [student for student in list_ if student[6 + num] == subject] local_list.sort(key=lambda x: (-float(x[test_score_column[subject]]), x[0] + x[1])) return local_list def is_student_placed(student): """Return True if student has been assigned a place otherwise False""" for dep_list in dict_department_applicants.values(): if student in dep_list: return True return False def find_unplaced_students(): """Create a new list of students without places. When this code is called it will create a new list "unassigned_students" who do not currently have a place """ global unassigned_students unassigned_students = [student for student in full_applicant_list if not is_student_placed(student)] def application_summary(): """Print the output of the final data""" for dep_list in dict_department_applicants.items(): print(dep_list[0]) for student in dep_list[1]: print(f"{student[0]} {student[1]} {student[test_score_column[dep_list[0]]]}") print() print("Unassigned Students") for student in unassigned_students: print(student) print() print("Application Summary") print(f"Total Applied: {len(full_applicant_list)}, Total Accepted: {placed_students}, " f"Total Rejected: {len(unassigned_students)}") def write_output_to_file(): for dep_list in dict_department_applicants.items(): with open(dep_list[0] + ".txt", "wt") as applicant_output: for student in dep_list[1]: applicant_output.write(f"{student[0]} {student[1]} {student[test_score_column[dep_list[0]]]}\n") def main(): """This is the main function which calls all other sub-functions as required.""" process_input() create_list_from_file() assign_students_to_department() write_output_to_file() main()
39663f17e00c0a1f0e1cafe108c2be18d799fc8c
AWGL/variant_classification_DB
/acmg_db/utils/acmg_classifier.py
4,267
3.671875
4
""" This code implements the ACMG algorithm for classifying variants. https://www.acmg.net/docs/Standards_Guidelines_for_the_Interpretation_of_Sequence_Variants.pdf The code consists of two functions: 1) valid_input 2) classify The classification algorithm has been rewritten from the earlier versions because if didnt always call VUS-conflicting evidence if there was only mild evidence on one side. All classification is now done within the one function. """ # specify guideline version so that record can be made in database # NOTE: change this variable if you make any changes to the guidelines (max_length 20) guideline_version = 'ACGS 2020 v4' def valid_input(input): """ Input: list Output: True or False Checks whether the user input is valid. The user input should be a list containing the classification codes in the possible_classifications list. The user input should contain no duplicates. The user input should not be a empty list """ possible_classifications = [ 'PVS1', 'PS1', 'PS2', 'PS3', 'PS4', 'PS4_M', 'PS4_P', 'PM1', 'PM2', 'PM3', 'PM4', 'PM5', 'PM6', 'PP1', 'PP2', 'PP3', 'PP4', 'PP5', 'BA1', 'BS1', 'BS2', 'BS3', 'BS4', 'BP1', 'BP2', 'BP3', 'BP4', 'BP5', 'BP6', 'BP7' ] #Have we got a list? if type(input) is not list: return False #Have we got an empty list? if len(input) ==0: return False #Have we got any classifications that are not valid e.g. BP8? for classification in input: if classification not in possible_classifications: return False #Have we got any duplicates? if len(input) != len(set(input)): return False #Have PS4, PS4_M, PS4_P been applied together? n = 0 if 'PS4' in input: n += 1 if 'PS4_M' in input: n += 1 if 'PS4_P' in input: n += 1 if n > 1: return False #Input is a valid list and no invalid classifactions and no duplicates so return True return True def classify(user_classification): ''' Takes a list of ACMG codes and calculates a classification. Input: tuple of acmg code followed by the code strength e.g. ('PVS1', 'PV') Output: A string of a number corresponding to a classification - 0 - benign 1 - likely benign 2 - vus - criteria not met 3 - vus - conflicting criteria 4 - likely pathogenic 5 - pathogenic ''' # make empty dict to count numbers of each code classification_dict = { 'PV': 0, 'PS': 0, 'PM': 0, 'PP': 0, 'BA': 0, 'BS': 0, 'BP': 0 } # count number of each code for code in user_classification: strength = code[1] classification_dict[strength] += 1 PVS1_count = classification_dict['PV'] PS_count = classification_dict['PS'] PM_count = classification_dict['PM'] PP_count = classification_dict['PP'] pathogenic_count = PVS1_count + PS_count + PM_count + PP_count BA_count = classification_dict['BA'] BS_count = classification_dict['BS'] BP_count = classification_dict['BP'] benign_count = BA_count + BS_count + BP_count # apply acmg rules # contradictory evidence if pathogenic_count > 0 and benign_count > 0: return '3' # benign elif BA_count >= 1: return '0' elif BS_count >= 2: return '0' # likely benign elif BS_count == 1 and BP_count == 1: return '1' elif BP_count >= 2: return '1' # pathogenic elif PVS1_count >= 1 and PS_count >= 1: return '5' elif PVS1_count >= 1 and PM_count >= 1: return '5' elif PVS1_count >= 1 and PP_count >= 2: return '5' elif PS_count >= 3: return '5' elif PS_count == 1 and PM_count >= 3: return '5' elif PS_count == 1 and (PM_count == 2 and PP_count >= 2): return '5' elif PS_count == 1 and (PM_count == 1 and PP_count >= 4): return '5' elif PS_count == 2 and PM_count >= 1: return '5' elif PS_count == 2 and PP_count >=2: return '5' # likely pathogenic elif PS_count == 2: return '4' elif PS_count == 1 and (PM_count == 1 or PM_count == 2): return '4' elif PS_count == 1 and PP_count >= 2: return '4' elif PM_count >= 3: return '4' elif PM_count == 2 and PP_count >= 2: return '4' elif PM_count == 1 and PP_count >= 4: return '4' # vus - criteria not met else: return '2' def main(): #for debugging user_classifications = ['PVS1', 'BS1', 'PS4', 'PS2'] print(classify(user_classifications)) if __name__ == "__main__": main()
4db59189487682e15f7112a2dceca0befd7ccf72
kanimozhi0112/python-programming
/swap.py
85
3.796875
4
a= int(input("value:")) b= int(input("value:")) temp=0 temp=a a=b b=temp print(a,b)
26d6f3ead70667cb3ce97da2e7c245f99fb66b76
jhinAza/Chess-Python-Madrid
/chess/coordinates.py
1,654
3.53125
4
from typing import Tuple from chess import constants class Coordinates: _trap = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] def __init__(self, letter: str, number: int): assert letter in self._trap, 'The letter of a coordinate must be one from a to h' assert 1 <= number <= 8, 'The number of a coordinate must be included in [1. 8]' self.letter = letter self.number = number @property def matrix_coordinates(self) -> Tuple[int, int]: return self.number -1, self._trap.index(self.letter) @property def color(self): coords = self.matrix_coordinates return constants.WHITE if all(n % 2 == 0 for n in coords) or all(n % 2 == 1 for n in coords) else constants.BLACK def is_before(self, other: 'Coordinates') -> bool: return other.letter == self.letter and other.number < self.number def is_behind(self, other: 'Coordinates') -> bool: return other.letter == self.letter and other.number > self.number def distance(self, other: 'Coordinates') -> Tuple[int, int]: return self._letter_distance(other), self._number_distance(other) def _letter_distance(self, other: 'Coordinates') -> int: my_letter = self._trap.index(self.letter) other_letter = self._trap.index(other.letter) return abs(my_letter - other_letter) def _number_distance(self, other: 'Coordinates') -> int: return abs(other.number - self.number) @classmethod def from_matrix_coordinates(cls, coordinates): number = coordinates[0] + 1 letter = cls._trap[coordinates[1]] return Coordinates(letter, number)