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
b229602c3c231f06644b1c1ae25c2faf2d1ee5b8
Sholes/Stalker-Alert
/StalkerAlert.py
658
3.515625
4
#python program #!/usr/bin/env python import re emails = open("H:\\fbproject\\test1.txt","r") #opens the file to analyze resultsList = [] for line in emails: if "InitialChatFriendsList" in line: #recgonizes the beginning of a email message and adds a linebreak # newMessage = re.findall(r'\w\w\w\s\w\w\w.*', line) #matches=re.findall(r'\"([0-9]-2)\"',line) #address = re.findall(r'"[\d.-]+"', line) array= re.findall("[+]?\d+[\.]?\d*", line) i=0 #for i in array: print array[9] #print address emails.close()
41776a4506e2a725f3a98f36e42299f8e58f0970
else12mos/lesson1
/dict.py
267
4.03125
4
dictionary = {'city': 'Москва', 'temperature': '20'} print(dictionary['city']) dictionary['temperature'] =int(dictionary['temperature']) - 5 print(dictionary) print(dictionary.get('country', 'Россия')) dictionary["date"] = '27.05.2019' print(dictionary)
1a28848186e44bc7d6c7ffe4ab3d90957d582eef
rvm8h/python-exercice
/solution_employee_JB.py
914
3.875
4
# creer une classe employee # avec une methode __init__ qui prend name et salary comme parameters # creer une variable de classe globale qui compte les employees, faire des recherches google # creer une methode displaycount qui affiche le nombre d'employees # creer une methode display qui affiche un employee class Employee: count = 0 deleteCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.count += 1 Employee.deleteCount += 1 def __del__(self): Employee.count -= 1 def display(self): print(self.name + ' has got ' + self.salary) def displayCount(Employee): print("Total employees are : {}".format(Employee.count)) a = Employee('jean', '30k') b = Employee('dj', '100k') c = Employee('jay', '1000k') a.display() b.display() c.display() displayCount(Employee) del a displayCount(Employee)
98ef01a444ac95b855f6c9441b5cf23c1db50b77
emilianot04/Exercise_Python
/Think-Python/capitolo_8/esercizio-8.3.py
206
3.84375
4
def palindroma(parola): if parola == parola[::-1]: return True else: return False print(palindroma('otto')) #true print(palindroma('radar'))#true print(palindroma('pippo'))#false
a8ec864c980e2b7ac20280e8ada1170ddac82afc
ashishsubedi/algorithm_labs
/Lab3/test_bst.py
7,074
3.984375
4
import unittest from bst import BinarySearchTree import random class BSTTestCase(unittest.TestCase): def setUp(self): """ Executed before each test method. Before each test method, create a BST with some fixed key-values. """ self.bst = BinarySearchTree() self.bst.add(10, "Value for 10") self.bst.add(52, "Value for 52") self.bst.add(5, "Value for 5") self.bst.add(8, "Value for 8") self.bst.add(1, "Value for 1") self.bst.add(40, "Value for 40") self.bst.add(30, "Value for 30") self.bst.add(45, "Value for 45") def test_add(self): """ tests for add """ # Create an instance of BinarySearchTree bsTree = BinarySearchTree() # bsTree must be empty self.assertEqual(bsTree.size(), 0) # Add a key-value pair bsTree.add(15, "Value for 15") # Size of bsTree must be 1 self.assertEqual(bsTree.size(), 1) # Add another key-value pair bsTree.add(10, "Value for 10") # Size of bsTree must be 2 self.assertEqual(bsTree.size(), 2) # The added keys must exist. self.assertEqual(bsTree.search(10), "Value for 10") self.assertEqual(bsTree.search(15), "Value for 15") def test_inorder(self): """ tests for inorder_walk """ self.assertListEqual(self.bst.inorder_walk(), [1, 5, 8, 10, 30, 40, 45, 52]) # Add one node self.bst.add(25, "Value for 25") # Inorder traversal must return a different sequence self.assertListEqual(self.bst.inorder_walk(), [1, 5, 8, 10, 25, 30, 40, 45, 52]) def test_postorder(self): """ tests for postorder_walk """ self.assertListEqual(self.bst.postorder_walk(), [1, 8, 5, 30, 45, 40, 52, 10]) # Add one node self.bst.add(25, "Value for 25") # Inorder traversal must return a different sequence self.assertListEqual(self.bst.postorder_walk(), [1, 8, 5, 25, 30, 45, 40, 52, 10]) def test_preorder(self): """ tests for preorder_walk """ self.assertListEqual(self.bst.preorder_walk(), [10, 5, 1, 8, 52, 40, 30, 45]) # Add one node self.bst.add(25, "Value for 25") # Inorder traversal must return a different sequence self.assertListEqual(self.bst.preorder_walk(), [10, 5, 1, 8, 52, 40, 30, 25, 45]) def test_search(self): """ tests for search """ self.assertEqual(self.bst.search(40), "Value for 40") self.assertFalse(self.bst.search(90)) self.bst.add(90, "Value for 90") self.assertEqual(self.bst.search(90), "Value for 90") def test_remove(self): """ tests for remove """ self.bst.remove(40) self.assertEqual(self.bst.size(), 7) self.assertListEqual(self.bst.inorder_walk(), [1, 5, 8, 10, 30, 45, 52]) self.assertListEqual(self.bst.preorder_walk(), [10, 5, 1, 8, 52, 45,30]) def test_smallest(self): """ tests for smallest """ self.assertTupleEqual(self.bst.smallest(), (1, "Value for 1")) # Add some nodes self.bst.add(6, "Value for 6") self.bst.add(4, "Value for 4") self.bst.add(0, "Value for 0") self.bst.add(32, "Value for 32") # Now the smallest key is 0. self.assertTupleEqual(self.bst.smallest(), (0, "Value for 0")) def test_largest(self): """ tests for largest """ self.assertTupleEqual(self.bst.largest(), (52, "Value for 52")) # Add some nodes self.bst.add(6, "Value for 6") self.bst.add(54, "Value for 54") self.bst.add(0, "Value for 0") self.bst.add(32, "Value for 32") # Now the largest key is 54 self.assertTupleEqual(self.bst.largest(), (54, "Value for 54")) class CustomBSTTest(unittest.TestCase): def setUp(self): self.data = [(11,11),(10,10),(15,15),(1,1),(17,17),(25,25),(6,6)] self.bst = BinarySearchTree() for (key,val) in self.data: self.bst.add(key,val) def testAdd(self): bsTree = BinarySearchTree() self.assertEqual(bsTree.size(), 0) bsTree.add(15, 15) self.assertEqual(bsTree.size(), 1) bsTree.add(10,10) # Size of bsTree must be 2 self.assertEqual(bsTree.size(), 2) self.assertEqual(bsTree.search(10), 10) self.assertEqual(bsTree.search(15), 15) self.assertEqual(bsTree.search(25), False) def testInorder(self): data = self.data.copy() data.sort(key=lambda x: x[0]) self.assertListEqual(self.bst.inorder_walk(), list(map(lambda x: x[0],data))) # Add one node self.bst.add(50, 50) data.append((50,50)) data.sort(key=lambda x: x[0]) self.assertListEqual(self.bst.inorder_walk(),list(map(lambda x: x[0],data))) def testPostorder(self): self.assertListEqual(self.bst.postorder_walk(), [6,1,10,25,17,15,11]) self.bst.add(12,12) self.assertListEqual(self.bst.postorder_walk(), [6,1,10,12,25,17,15,11]) def testPreorder(self): self.assertListEqual(self.bst.preorder_walk(), [11,10,1,6,15,17,25]) self.bst.add(12, 12) self.assertListEqual(self.bst.preorder_walk(), [11,10,1,6,15,12,17,25]) def testSearch(self): self.assertEqual(self.bst.search(11), 11) self.assertFalse(self.bst.search(90)) self.assertEqual(self.bst.search(10), 10) def testRemove(self): self.assertFalse(self.bst.remove(40)) self.assertEqual(self.bst.size(), 7) self.assertTrue(self.bst.remove(11)) self.assertEqual(self.bst.size(), 6) self.assertListEqual(self.bst.inorder_walk(), [1,6, 10, 15,17,25]) self.assertListEqual(self.bst.preorder_walk(), [15,10,1,6,17,25]) def testSmallest(self): self.assertTupleEqual(self.bst.smallest(), (1, 1)) self.bst.add(6,6) self.bst.add(4,4) self.bst.add(0,0) self.bst.add(32,32) # Now the smallest key is 0. self.assertTupleEqual(self.bst.smallest(), (0, 0)) def testLargest(self): self.assertTupleEqual(self.bst.largest(), (25, 25)) self.bst.add(6,6) self.bst.add(54,54) self.bst.add(0,0) self.bst.add(32,32) # Now the largest key is 54 self.assertTupleEqual(self.bst.largest(), (54, 54)) if __name__ == "__main__": unittest.main()
b6b3632fa863389ec3cb826c182a402f2822a646
AlexandruSte/100Challenge
/Paduraru Dana/15_meeting.py
803
3.65625
4
# https://www.codewars.com/kata/meeting/train/python def meeting(s): s = s.upper() names = [] for full_name in s.split(';'): name = full_name.split(':') names.append('(' + name[1] + ', ' + name[0] + ')') names.sort() output = '' for name in names: output += name return output string = 'Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill' meeting(string) string = 'Alexis:Wahl;John:Bell;Victoria:Schwarz;Abba:Dorny;Grace:Meta;Ann:Arno;Madison:STAN;Alex:Cornwell;Lewis:Kern' \ ';Megan:Stan;Alex:Korn ' meeting(string) # should equal '(ARNO, ANN)(BELL, JOHN)(CORNWELL, ALEX)(DORNY, ABBA)(KERN, LEWIS)(KORN, ALEX)(META, GRACE)(SCHWARZ, # VICTORIA)(STAN, MADISON)(STAN, MEGAN)(WAHL, ALEXIS)'
b2075dc9a570f21e66a0ac850a16df388dcf0309
lidymonteirowm/study-python
/PythonBrasil/estrutura-sequencial/ex15.py
1,091
3.640625
4
''' 15) Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda, 8% para o INSS e 5% para o sindicato, faça um programa que nos dê: salário bruto. quanto pagou ao INSS. quanto pagou ao sindicato. o salário líquido. calcule os descontos e o salário líquido, conforme a tabela abaixo: + Salário Bruto : R$ - IR (11%) : R$ - INSS (8%) : R$ - Sindicato ( 5%) : R$ = Salário Liquido : R$ Obs.: Salário Bruto - Descontos = Salário Líquido. ''' vh = float(input('Valor da hora:')) qh = int(input('Quantidade de horas trabalhadas:')) salario_bruto = vh * qh inss = 8/100 * salario_bruto sindicato = 5/100 * salario_bruto ir = 11/100 * salario_bruto salario_liquido = salario_bruto - inss - sindicato - ir print (' + Salário Bruto: R$ %.2f' %salario_bruto) print (' - IR: R$ %.2f' %ir) print (' - INSS: R$ %.2f' %inss) print (' - Sindicato: R$ %.2f' %sindicato) print (' = Salário Liquido: R$ %.2f' %salario_liquido)
d08ae4a31a0838a9201a70d5cfa7348f4f0aaad6
WellseeC/Python
/Lecture Code/20161104_Lecture 17 Problem 2.py
562
3.5
4
f=input('Enter the name of the IMDB file ==> ') print(f) f=open(f,encoding='ISO-8859-1') c=dict() for line in f: words=line.strip().split('|') name1=words[1].strip() name0=words[0].strip() if name1 in c: c[name1].add(name0) else: c[name1]=set([name0]) l=list(c.keys()) n=0 counts=0 name='' for i in l: x=list(c[i]) t=0 for j in x: t+=1 if n<t: n=t name=i for i in l: x=list(c[i]) t=0 for j in x: t+=1 if t==1: counts+=1 print(n) print(name) print(counts)
67a57151027f3ca1f544eca8deaa010dd4e42117
burnettk/origin
/Python/BuckysCodeExamples/ReturnValue.py
362
3.5625
4
def celsiusToFahrenheit(celsius_temp): fahrenheit_temp = (celsius_temp * 9 / 5) + 32 return fahrenheit_temp def fahrenheitToCelcius(fahrenheit_temp): celsius_temp = (fahrenheit_temp - 32) * 5 / 9 return celsius_temp print(celsiusToFahrenheit(0)) print(fahrenheitToCelcius(32)) print(celsiusToFahrenheit(100)) print(fahrenheitToCelcius(100))
c56632c03217c3fbe0da60ac204bf92733fbaa71
ziiin/perli
/memoryCodes/binarySearchTree.py
5,208
4.0625
4
import sys import os #[TODO] Deletions for BST #[TODO] Empty tree and reconstruction #{TODO] Tree empty check on all operations # TODO Traversals, preorder and post order class node: ''' stores integral entries in binary search tree ''' def __init__ (self, num): self.rightNode = None self.leftNode = None self.data = num class binarySearchTree: ''' Binary search tree implementation''' def __init__ (self, num): self.root = node(num) def insertNode (self, parNode, num): if parNode != None: if num < parNode.data : if parNode.leftNode == None: parNode.leftNode = node(num) else: self.insertNode(parNode.leftNode, num) else: if parNode.rightNode == None: parNode.rightNode = node(num) else : self.insertNode(parNode.rightNode, num) return def printInorder (self, node): '''Inorder display of Binary Search tree ''' if node == None: return if node.leftNode != None: self.printInorder (node.leftNode) print str(node.data) if node.rightNode != None: self.printInorder (node.rightNode) def searchElement (self, node, num): ''' Searches integer number in the BST ''' if node.data == num: return (node, True) elif num < node.data : if node.leftNode == None: return (node, False) else: return self.searchElement (node.leftNode, num) else : if node.rightNode == None: return (node, False) else : return self.searchElement (node.rightNode, num) def detatchNode (self, node): if node == self.root: self.root = None else: parentNode = self.root while ( True ): print parentNode.data if node.data == parentNode.data: if parentNode.leftNode is node: print "Found" parentNode.leftNode = None break elif parentNode.rightNode is node: print "Found" parentNode.rightNode = None break if node.data < parentNode.data: if parentNode.leftNode is node: print "FOUND" parentNode.leftNode = None break else : parentNode = parentNode.leftNode else : if parentNode.rightNode is node: print "FOUND" parentNode.rightNode = None break else : parentNode = parentNode.rightNode def deleteElement (self, node): ''' deletes specific node of BST ''' if node.leftNode == None and node.rightNode == None: print "Node being deleted is : " + str(node.data) self.detatchNode (node) elif node.leftNode != None and node.rightNode != None: node.data = node.leftNode.data self.deleteElement (node.leftNode) else : if node.leftNode != None: node.data = node.leftNode.data self.deleteElement (node.leftNode) else: node.data = node.rightNode.data self.deleteElement (node.rightNode) def deleteElementWrap (self, num): ''' deletes a number from a BST ''' node, isFound = self.searchElement (self.root, num) if isFound == True: self.deleteElement (node) else : print "Element not found, Can't delete" def hasChild (self, node): ''' Checks if node has children or not ''' if node == None: print "Node is None" return else: if node.leftNode != None or \ node.rightNode != None: return True else: return False def main(): print "Enter\nCreate Tree (1) \nPrintInorder (2)\nInsert Element(3) \nSearch element (4)"+ \ "\nDelete Element (5)" while (1) : case = int(raw_input("ENTER: ")) if case == 1: num = int(raw_input ("Root : ")) tree = binarySearchTree(num) elif case == 2: tree.printInorder (tree.root) elif case == 3: num = int(raw_input ("Enter num to insert : ")) tree.insertNode (tree.root, num) elif case == 4: num = int(raw_input ("Enter num to find : ")) node, isFound = tree.searchElement (tree.root, num) if isFound == True: print "FOUND" else: print "NOT Found" elif case == 5: num = int(raw_input ("Enter num to delete : ")) tree.deleteElementWrap (num) if __name__ == "__main__": main()
6e7d800d2df36e8f0950b0d665780cffa64a729d
taoes/python
/007_函数式编程/001_高阶函数_sorted.py
259
3.59375
4
#!/usr/bin/env python # encoding: utf-8 """ @author: 周涛 @contact: zhoutao825638@vip.qq.com """ def sorted_str(str_list): str_list_sorted = sorted(str_list) print(str_list_sorted) if __name__ == '__main__': sorted_str(['a', 'c', 'd', 'b', 'e', 'h', 'g'])
ec1728df9feffb938f804422fd585c7283935028
aaabhilash97/thinkpython
/mul_time.py
319
3.515625
4
class Time(): """time rep""" def int2time(x): t1=Time() t1.h=x/3600 x=x%3600 t1.m=x/60 t1.s=x%60 return t1 def multime(t1,m): return int2time(((t1.h*60*60)+(t1.m*60)+(t1.s))*m) time=Time() time.h=1 time.m=23 time.s=60 new=multime(time,2) print new.h,new.m,new.s
24dcd6f75dec76b8117b3eedebf4cef8eab944f6
allertjan/LearningCommunityBasicTrack
/week 5/5.1.19/5.5.py
506
4.09375
4
import string def letter_check(text, letter): text_without_punc = "" for letter in text: if letter not in string.punctuation: text_without_punc += letter text_split = text_without_punc.split() total_words = len(text_split) words_w_e = 0 for words in text_split: a = words.find(letter) if a > 0: words_w_e += 1 return total_words, words_w_e print(letter_check("hello how are you doing...? I'm very curious about that!", "l"))
1689c362cf7c7344c231ac9f65d6b1e1f1c8975b
MagicTearsAsunder/playground
/classes_introspector.py
860
3.6875
4
""" Pass an instance of any class to instance() function. Returns recursevely all subclasses and superclasses. """ def inspector(instance): print("Instance attributes:") for i in sorted(instance.__dict__.keys()): print(f"{i}: {instance.__dict__[i]}") print("-" * 65) print(" Attributes | Value") cache = set() recsearch(instance.__class__, cache) def recsearch(the_class, cache): print("-" * 65) cache.add(the_class) for i in sorted(the_class.__dict__.keys()): placeholder = " " * (15 - len(i)) print(f"{i}{placeholder}| {the_class.__dict__[i]}") if the_class.__bases__ == (object,): print("-" * 65) print("Max superclasses origin depth was reached.\n") else: for i in the_class.__bases__: if i not in cache: recsearch(i, cache)
17d8eda143520015721cc5adf206e46293dc5cfc
yui-chouchou/AMECOBA_PROJECTS
/AMECOBA_SEMESTER1/ADRIAN_PROJECTS/AMECOBA_PROJECT/SECTION_1/python/part1/amecoba-answer.py
3,980
4
4
#端末で初めてのHELLOWORLDを出力してみよう print("hello world") print(10-1) #文字列や数字を合わせて表示する print("NUMBER", 10 + 2) print("WELCOME" + "to" + "AMECOBA") #モジュール(部品)を使って簡単なおみくじプログラムを作ってみよう import random #シャフルするので、Randomという部品を使います。 kujibiki = ["VERY LUCKY", "LUCKY", "GOOD", "NOT BAD", "BAD", "VERY BARD"] #変数 = [要素0, 要素1, 要素2, 要素3, 要素4, 要素5] print(random.choice(kujibiki)) #出力(モジュール.選ぶ(変数)) #BMI直計算プログラムの身長と体重の総合を測ってみよう HEIGHT = float(input("身長何センチですか?")) #身長 = 浮動小数点(入力("身長何センチですか?")) WEIGHT = float(input("体重何キロですか?")) #体重 = 浮動小数点(入力("体重何キロですか?")) BMI = WEIGHT / (HEIGHT * HEIGHT) #BMI = 体重 / (身長 ✖️ 身長) print("あなたのBMI値:", BMI, "ですね!") #出力("あなたのBMI値", BMI(変数), "ですね!") #様々なデータの種類を理解しよう #変数に入れることができるデータには、「数値」、「文字」などいろいろな種類がある = データ型 number = 100 float_number = 13.2 string_word = "hello" b = True #反対はFalse print(type(number)) #個数や順番に使う print(type(float_number)) #一般的な計算に使う print(type(string_word)) #文字数を扱う時に使う print(type(b)) #true か false かの二択の時に使う #文字列の操作を覚えよう write = "hello" + "my name is amecoba" print(write) print(len(write)) #文字数を調べる lenメソッド print(write[0]) #出力(変数[要素番号]) print(write[6:12]) #出力(変数[開始要素番号:最後の要素番号から一つ前]) print(write[-3:]) ##出力(変数[逆の要素番号]) print("hello \n world.") #文字列を改行 print("hello wo\trld.") #タブ文字 #データ型を変換する a = "100" print(a + 23) # TypeError なぜかというと 100という数字ではなく、文字列として扱われているから print(int(a) + 23) #123 #変換できない時はエラーになる b = "hello" print(int(b) + 23) #Type Error #isdigitメソッドを用いて数値に変換できるのか a = "100" b = "hello" print(a.isdigit()) print(b.isdigit()) #データをまとめるためのリストを使ってみよう fruits = ["apple", "banana", "cherry", "blueberry"] print(fruits[2]) #=========================================================================== #if文を使ってみよう #if 条件式: #条件式が正しい時にする処理 tennsu = 100 if tennsu >= 80: #もしも #>=とは 比較演算子 print("Good job!") elif tennsu >= 60: #そうでないけれど、もしも print("good") else: #そうでないとき print("Don't worry about tennsu") #for文を使ってみよう #for カウント変数 in range(回数): #繰り返す処理 for i in range(10): print(i) #for文を使ってリストを取り出しみる #for 要素をいれる変数 in リスト: #繰り返す処理 score = [64, 100, 78, 80, 72] for i in score: print(i) #for文によるネスト化(入れ子) #for カウント変数 in range(回数): #for カウント変数 in range(回数): # 繰り返す処理 for i in range(10): for j in range(10): print(j * i) #def関数を使って簡単に一つ #def 関数名(): # 関数で行う処理 def hello(): print("hello") hello() # return を使う # def 関数名(引数1, 引数2): # 関数で行う処理 # return 戻り値 def postTaxPrice(): ans = 100 * 1.08 return ans # print("hello") #呼び出されることはない, returnがあるので print(postTaxPrice())
063a95e64912930618a5be1928a8da18cb9f1b6b
noemidmjn/COM404
/1-basics/4-repetition/5-sum-user-10/bot.py
141
4.03125
4
# sum of 10 given numbers print("Give me 10 numbers") total = 0 for count in range(1, 11): num = int(input()) total += num print(total)
f2232baf5a3016a714768a6309b3f848ebddeb2c
Miguel-leon2000/POO_Grupo_2A6
/Objeto.py
451
3.953125
4
from Ecuacion import Ecuacion Soluciones = Ecuacion(2, 5, 2) #Se le asigna valores al parametro del metodo constructor de la clase "Ecuacion" Soluciones.calcularRaizCuadrada() #Se manda llamar al metodo "calcularRaizCuadrada" print("------------Soluciones Reales---------------") print ("El resultado de x1 es: ", Soluciones.getx1()) #Imprime mensajes para saber las soluciones de x1 y x2 print ("El resultado de x2 es: ", Soluciones.getx2())
d843703c60d327249d809c22d61015a90f4bbd01
kantal/WPC
/ISSUE-20/SOLUTION-10/anagrams.py
1,296
3.796875
4
#!/usr/bin/python # Richard Park # richpk21@gmail.com # Olimex Weekend Challenge #20 Anagrams import re class Word: def __init__(self, text=""): self.histogram = {} self.text=text for c in text: try: c=c.lower() except: print 'Warning: none-alphabet character exists in the text: %s' % text try: self.histogram[c]+=1 except: self.histogram[c]=1 def compare(self,word): if len(self.text) != len(word.text): return None for k,v in self.histogram.iteritems(): try: if word.histogram[k]!=v: #print '%s Different Histogram' % word.text return None except: return None #print '%s Same Histogram' % word.text return word.text # test ############################################## input="warned" text="This 'warned' war-ned andrew wander fun wand-e" #list of words words = re.findall('\w+', text) #filter words by length and make 'Word' object for each word n=len(input) wordlist=[] for w in words: if n==len(w): wordlist.append( Word(w)) #make 'Word' object with one input word a=Word(input) #compare histograms final_list=[] for w in wordlist: t=a.compare(w) if t != None and t not in final_list: final_list.append(t) if final_list: print '<-Found->' print final_list else: print '<-Not Found->'
cc1ceb3877fabad6b5c9c0e6b5342f52c17f58f5
Redennison/CCC-Solutions
/CCC-2016/Python/S1.py
625
3.8125
4
from collections import Counter string, anagram = input(), input() # Count amount of each letter in string numLetters = Counter() for char in string: numLetters[char] += 1 letterSet = set(string) numAsterisks = 0 # Decremement amount of letter if in anagram for char in anagram: if char == '*': numAsterisks += 1 else: numLetters[char] -= 1 # Checks if number of asterisks satisfies amount of letters off for char in letterSet: if numLetters[char] > 0: numAsterisks -= numLetters[char] if numAsterisks < 0: print('N') break if numAsterisks >= 0: print('A')
329538e285a234664559d95d5d8d2ae8abc71acb
Sergioeabarcaf/curRasPy
/practical_exercise_module_1.py
691
3.96875
4
# Autor: Sergio Abarca Flores # Contacto: sergioaf1991@gmail.com # Practical Internet of Things (loT) with RaspberryPi # Practical exercise, module 1 # Make a python program that makes an LED blink three times when a # button is pressed. This exercise will be corrected by some of your partners. import RPi.GPIO as GPIO import time # Variables led = 4 button = 14 # Settings GPIO.setmode(GPIO.BCM) GPIO.setup(led, GPIO.OUT) GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Main while True: input_state = GPIO.input(button) if input_state != True: for i in range(0, 3): GPIO.output(led, True) time.sleep(1) GPIO.output(led, False) time.sleep(1)
8a0961c01379589fa7e228b75d00cb71c2462c47
duochen/Python-Beginner
/Python_Crash_Course_2e_Solutions/ch03/SeeingtheWorld.py
592
3.53125
4
locations = ['himalaya', 'andes', 'tierra del fuego', 'labrador', 'guam'] print("Original order:") print(locations) print("\nAlphabetical:") print(sorted(locations)) print("\nOriginal order:") print(locations) print("\nReverse alphabetical:") print(sorted(locations, reverse=True)) print("\nOriginal order:") print(locations) print("\nReversed:") locations.reverse() print(locations) print("\nOriginal order:") locations.reverse() print(locations) print("\nAlphabetical") locations.sort() print(locations) print("\nReverse alphabetical") locations.sort(reverse=True) print(locations)
d8e422ee8985a2491d77bad150551d22dc5f2ef3
alexgarces98/Pythonprogramas
/barajaEspañola.py
950
4.03125
4
'''Programe una función recursiva en Python que calcule el número de “triunfos” de que hay en una baraja española de 40 cartas (array de cartas) entre dos posiciones. Las cartas son registros con palo (oros, copas, espadas o bastos) y valor (números enteros del 1 al 7 y del 10 al 12), y se consideran “triunfos” el as, el 3, la sota (10), el caballo (11) y el rey (12).''' def suma_triunfos(baraja, inicio, fin): """ lista, int, int, string -> int OBJ: Determina el número de cartas "triunfo" (as,3,10,11 y 12) entre 2 límites [inicio..fin] en una baraja de cartas PRE: Existe un tipo registro "Carta" con dos campos: palo y valor """ if inicio > fin: resultado = 0 else: if baraja[0].valor in [1,3,10,11,12]: resultado = 1 + suma_triunfos(baraja, inicio+1, fin) else: resultado = suma_triunfos(baraja, inicio+1, fin) return resultado
9ffe00b332322c2619321bf48341acf767d26656
georgia27rh/Hearts
/Game.py
3,116
3.515625
4
from Deck import Deck from Player import Player from Card import Card class Game: def __init__(self): self.deck = Deck() self.players = self.set_players() self.starting_player_index = 0 self.leading_card = None self.hearts_is_broken = False self.cards_played = [] def deal_cards(self): while self.deck.has_cards(): for player in self.players: self.give_card(player, self.deck) for player in self.players: player.sort_cards() def give_card(self, player, deck): card = deck.get_card() player.take_card(card) def set_players(self): players = [Player()] for i in range(3): name = input("Please enter a player name: ") players.append(Player(name)) return players def find_starting_player(self): for i in range(len(self.players)): player = self.players[i] if player.has(Card('CLUB', 2)): return i def play_round(self): for i in range(4): player = self.players[(self.starting_player_index + i) % 4] played_card = player.make_move(self.leading_card, self.hearts_is_broken) print(player.name + " played " + str(played_card)) if i == 0: self.leading_card = played_card if played_card.suit == 'HEART': self.hearts_is_broken = True self.cards_played.append(played_card) highest_value = 0 highest_card = None for card in self.cards_played: if card.suit == self.leading_card.suit and card.value > highest_value: highest_card = card highest_value = card.value taking_player = self.players[((self.starting_player_index + self.cards_played.index(highest_card)) % 4)] print(taking_player.name + " took the trick.") for card in self.cards_played: if card.suit == "HEART": taking_player.points += 1 if card.suit == "SPADE" and card.value == 12: taking_player.points += 13 print("\n=== CURRENT STANDINGS ===") for player in self.players: print(player) print("") self.starting_player_index = self.players.index(taking_player) self.leading_card = None self.cards_played = [] def play_game(self): self.deal_cards() self.starting_player_index = self.find_starting_player() print("Your starting hand: " + str(self.players[1].cards)) while self.players[-1].cards: self.play_round() for player in self.players: if player.points == 26: for player_2 in self.players: if player_2.name == player.name: player.score = 0 else: player.score = 26 break for player in self.players: print(player) if __name__ == '__main__': game = Game() game.play_game()
96334406179fa6ee59d90773818dbbd4b63452bc
HanSeokhyeon/Baekjoon-Online-Judge
/code/9020_Goldbach's_conjecture.py
667
3.828125
4
def check_prime_number(x): if x < 2: return False if x in (2, 3): return True if x % 2 is 0 or x % 3 is 0: return False if x < 9: return True k, l = 5, x**0.5 while k <= l: if x % k is 0 or x % (k+2) is 0: return False k += 6 return True if __name__ == '__main__': t = int(input()) case = [int(input()) for _ in range(t)] for n in case: a = b = n//2 while a > 1: if check_prime_number(a) and check_prime_number(b): break else: a -= 1 b += 1 print("{} {}".format(a, b))
b6cf2f7a80d8d090de1d3d55b827641d03942e08
AaronWWK/Courses-Taken
/6.00.1x/Lecture4/Problem set 2 --Problem 3.py
2,299
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 4 10:19:13 2017 @author: Weikang_Wan """ """ def lp(b,air): ##Input Balance ##Output monthly payment through bisection method def lowest_payment(lp): mir = air /12 lb =b /12 ub =(b*(1+mir)**12)/12 lp = (lb+ub)/2 b0=b for i in range(12): b0 = b0 - lp b0 = b0 + 0.2/12*b0 ##年利率 20% lp:每个月最低还款数 if b0 > 0.001: lb = lp lp2 = (lb+ub)/2 return lowest_payment(lp2) elif b0 < -0.001: ub = lp lp2 = (lb+ub)/2 return lowest_payment(lp2) else: return lp return round(lowest_payment(lp),2) print('Lowest Payment:',lp(4737,0.2)) """ def lp(b,air): ##Input Balance ##Output monthly payment through bisection method mir = air /12 lb =b /12 ub =(b*(1+mir)**12)/12 lp = (lb+ub)/2 def lowest_payment(a,ub,lb,lp): ub2= ub lb2= lb b0=b a2 = a+1 for i in range(12): b0 = b0 - lp b0 = b0 + mir*b0 ##年利率 20% lp:每个月最低还款数 if b0 > 0.001: lb2 = lp lp2 = (lb+ub)/2 return lowest_payment(a2,ub2,lb2,lp2) elif b0 < -0.001: ub2 = lp lp2 = (lb+ub)/2 return lowest_payment(a2,ub2,lb2,lp2) else: return lp return round(lowest_payment(a,ub,lb,lp),2) a=1 balance = 320000 annualInterestRate = 0.2 print('Lowest Payment:',lp(balance,annualInterestRate)) ############## 终于写对了!!!!!!! """ b = 999999 air = 0.18 mir = air /12 lb =b /12 ub =(b*(1+mir)**12)/12 ## True while True: lp = (ub + lb)/2 b0 = b for i in range(12): b0 -=lp b0 += mir*b0 if abs(b0)< 0.01: print(round(lp,2)) break elif b0 > 0: lb = lp else: ub = lp b = 999999 air = 0.18 mir = air /12 lb =b /12 ub =(b*(1+mir)**12)/12 b0=b while abs(b0)> 0.01: lp = (ub + lb)/2 b0 = b for i in range(12): b0 -=lp b0 += mir*b0 if b0 > 0: lb = lp else: ub = lp print(round(lp,2)) """
65697524c03f48dfd8a343e68ca9fe306e918cce
XindoliaRing/python_learning
/End Zeros.py
1,219
4
4
# -*- coding: utf-8 -*- """ Created on Mon Nov 22 16:59:16 2021 Title: End Zeros Try to find out how many zeros a given number has at the end. @author: Ring """ def end_zeros(num: int) -> int: t = 0 n = str(num) for x in n[::-1]: if x == '0': t += 1 else: num = int(x) break return t if __name__ == '__main__': print("Example:") print(end_zeros(0)) print(end_zeros(1)) print(end_zeros(10)) print(end_zeros(101)) print(end_zeros(245)) print(end_zeros(1900100)) ''' # 1 def end_zeros(num: int) -> int: return len(s := str(num)) - len(s.rstrip('0')) # 2 def end_zeros(num: int) -> int: for x in str(num)[::-1]: if x != '0': return str(num)[::-1].find(x) return len(str(num)) # 3 def end_zeros(num: int) -> int: if num == 0: return 1 zeros = 0 while num % 10 == 0: num //= 10 zeros += 1 return zeros # 4 def end_zeros(b): if b==0: return 1 for i in np.arange(1,len(str(b))+1): if float(b/(10**i)).is_integer()==False: break return i-1 '''
8f79f57cae8de985e597c48318e5b89a4482452a
NC-2019/Coursera_Discrete_Optimization
/03Traveling_Salesman/solver.py
8,702
3.84375
4
#!/usr/bin/python # -*- coding: utf-8 -*- import math import numpy as np from matplotlib import pyplot as plt import random import sys def solve_it(input_data): # parse the input lines = input_data.split('\n') global node_count node_count = int(lines[0]) global points points = np.zeros((node_count, 2)) for i in range(0, node_count): line = lines[i+1] parts = line.split() points[i] = [float(parts[0]), float(parts[1])] # show the size of problem print('\n') print('Number of Nodes:', node_count) # build a distance matrix print('Build a distance matrix...') global distances distances = distanceMatirx(points) # generate an initial solution by greedy algorithm print('Starting with greedy algorithm...') solution = greedy() # calculate the length of the tour obj = pathLength(solution) # use simulated annealing alorithm with k-opt print('Using simulated annealing alorithm...') # set the intial temperature and cooling rate T0 = 1000 alpha = 0.9 solution, obj = simulatedAnnealing(T0, alpha, solution, obj, 'greedy') # reheat the simulated annealing print('Reheat...') # set the times of reheats if node_count < 500: M = 150 elif node_count < 10000: M = 90 else: M = 60 for i in range(1, M+1): # choose nodes randomly node_choose = 'random' if i and i % 30 == 0: print('Reheat {} times...'.format(i)) # chose node greedily every 10 times node_choose = 'greedy' solution, obj = simulatedAnnealing(T0, alpha, solution, obj, node_choose) # plot the path pathPlot(solution) # prepare the solution in the specified output format output_data = '%.2f' % obj + ' ' + str(0) + '\n' output_data += ' '.join(map(str, solution)) return output_data def distanceMatirx(points): # initialize the squared matrix distances = np.zeros((node_count, node_count)) # calculate the distance by matrix multiplication if node_count <= 10000: G = np.dot(points, points.T) H = np.tile(np.diag(G), (node_count, 1)) return np.sqrt(H + H.T - 2 * G) # avoid memory error else: for i in range(node_count-1): temp = np.array([points[i]]) i_distances = np.sqrt(np.square(temp[i:, 0] - points[i:, 0]) + np.square(temp[i:, 1] - points[i:, 1])) distances[i, i:] = i_distances distances[i:, i] = i_distances # display progress if i and i % 10000 == 0: print('Filled {} nodes...'.format(i)) return distances def pathPlot(solution): plt.ion() # sort as the solution co_ords = points[solution, :] # get x, y seperately x, y = co_ords[:, 0], co_ords[:, 1] plt.plot(x, y, color='b') plt.scatter(x, y, color='r') # connect the last node to the first node x, y = [co_ords[-1, 0], co_ords[0, 0]], [co_ords[-1, 1], co_ords[0, 1]] plt.plot(x, y, color='b') plt.scatter(x, y, color='r') plt.pause(15) plt.close() def greedy(): # start with the first node cur = 0 solution = [0] # if all nodes are visisted while len(solution) != node_count: # visit the nearest unvisited node unvisited_distances = np.delete([distances[cur], range(node_count)], solution, axis=1) cur = int(unvisited_distances[:, np.argmin(unvisited_distances[0, :])][1]) solution.append(cur) return solution def pathLength(solution): obj = distances[solution[-1], solution[0]] for i in range(0, node_count-1): obj += distances[solution[i], solution[i+1]] return obj def simulatedAnnealing(T, alpha, solution, obj, node_choose): best_solution, best_obj = solution, obj # store temperature and obj as list for visualization T_list = [T] obj_list = [obj] # set the number of steps if node_count < 10000: N = 1000 else: N = 300 # set upper bound of k k_upper = 100 if node_choose == 'random': # randomly choose node nodes = [random.randrange(node_count) for _ in range(N)] elif node_choose == 'greedy': # choose the logest x1 edge first nodes = length_sort(solution)[:N] # set find flag find = False for node in nodes: # use k-opt for local search cur_solution, cur_obj = kOpt(solution, obj, node, k_upper) # when current solution is better if cur_obj <= obj: obj, solution = cur_obj, cur_solution[:] # when current solution is worse else: # calculate probability prob = 1 / (np.exp((cur_obj - obj) / T)) # generate random number rand_num = random.random() # accept current solution with probability if rand_num <= prob: obj, solution = cur_obj, cur_solution # find a better solution if int(obj) < int(best_obj): find = True # store best solution and obj if obj <= best_obj: best_solution, best_obj = solution[:], obj # cool down T = alpha * T # append temperature and obj to list for visualization T_list.append(T) obj_list.append(obj) # visualize when find a better cur_solution if find: plt.ion() plt.xlabel("Temperature") plt.ylabel("Distance") plt.gca().invert_xaxis() plt.plot(T_list, obj_list) plt.pause(5) plt.close() return best_solution, best_obj def length_sort(solution): # initialize list of solution length lengths = [] # get the length between nodes for i in range(0, node_count-1): lengths.append([solution[i], distances[solution[i], solution[i+1]]]) lengths.append([solution[-1], distances[solution[-1], solution[0]]]) # sort nodes by length lengths.sort(key = lambda x: x[1], reverse=True) nodes = np.array(lengths, dtype=np.int)[:, 0] return nodes def kOpt(solution, obj, t1, k_upper): # start with 2-opt k = 2 # initialize solution and obj best_solution = [] best_obj = float('inf') # stop when k achieve upper bound while k <= k_upper: temp_solution, temp_obj, end = kOptIterate(solution, obj, t1) # keep the best solution if temp_obj <= best_obj: best_solution, best_obj = temp_solution, temp_obj # stop when distance of x2 < distance of x1 do not exist if end: break # increase k k += 1 return best_solution, best_obj def kOptIterate(solution, obj, t1): # initialize end flag end = False # get t2 t1_index = solution.index(t1) t2 = solution[(t1_index + 1) % node_count] # get edge x1 = (t1, t2) x1_length = distances[t1, t2] # get rank of length between t2 and others length_rank = np.argsort(distances[t2]) # choose t3 correctly if solution[(t1_index + 2) % node_count] == np.argsort(distances[t2])[1]: length_rank = length_rank[2:] else: length_rank = length_rank[1:] if distances[t2, length_rank[0]] < x1_length: # get t3 randomly x2_length = float('inf') while x2_length >= x1_length: t3 = random.choice(length_rank[:25]) # get x2 = (t2, t3) x2_length = distances[t2, t3] # get t3 greedily # t3 = length_rank[0] # x2_length = distances[t2, t3] # get t4 t3_index = solution.index(t3) t4_index = (t3_index - 1) % node_count t4 = solution[t4_index] # get solution and obj temp_solution = swap(solution, obj, t1_index, t4_index) temp_obj = obj - distances[t1, t2] - distances[t3, t4] + distances[t1, t4] + distances[t2, t3] else: # stop k-opt end = True temp_solution, temp_obj = solution[:], obj return temp_solution, temp_obj, end def swap(solution, obj, t1_index, t4_index): a, b = sorted([t1_index, t4_index]) temp_solution = solution[:a+1] + solution[b:a:-1] + solution[b+1:] return temp_solution if __name__ == '__main__': if len(sys.argv) > 1: file_location = sys.argv[1].strip() with open(file_location, 'r') as input_data_file: input_data = input_data_file.read() print(solve_it(input_data)) else: print('This test requires an input file. Please select one from the data directory. (i.e. python solver.py ./data/tsp_51_1)')
e49ea16e431581e39965381175cb8f5fc7283f94
zhaozz-lab/CS61
/CS61A/chapter1.py
2,737
4.09375
4
# fucnction as argument def sum_naturals(n): total,k = 0,1 while k<=n: total,k = total+k,k+1 return total def sum_cubes(n): total, k = 0, 1 while k <= n: total, k = total + k*k*k, k + 1 return total def pi_sum(n): total, k = 0, 1 while k <= n: total, k = total + 8 / ((4*k-3) * (4*k-1)), k + 1 return total def summation(n, term): total, k = 0, 1 while k <= n: total, k = total + term(k), k + 1 return total def cube(x): return x*x*x def pi_term(x): return 8 / ((4*x-3) * (4*x-1)) print(summation(3,cube)) # function as general method # iteration judge x^2 equal to x+1 def improve(update, close, guess=1): while not close(guess): guess = update(guess) return guess def golden_update(guess): return 1/guess + 1 def approx_eq(x, y, tolerance=1e-15): return abs(x - y) < tolerance def square_close_to_successor(guess): return approx_eq(guess * guess, guess + 1) improve(golden_update, square_close_to_successor) # Defining Functions: Nested Definitions # Example Newton's method,牛顿方法的实现原理为,取初始点切线的根作为下一次的预测点,直到函数的值接近0为止 def newton_update(f, df): def update(x): return x - f(x) / df(x) return update def find_zero(f, df): def near_zero(x): return approx_eq(f(x), 0) return improve(newton_update(f, df), near_zero) # define f(x) as x^2 - a,the derivation is 2x def square_root_newton(a): def f(x): return x * x - a def df(x): return 2 * x return find_zero(f, df) print(square_root_newton(64)) def power(x, n): """Return x * x * x * ... * x for x repeated n times.""" product, k = 1, 0 while k < n: product, k = product * x, k + 1 return product def nth_root_of_a(n, a): def f(x): return power(x, n) - a def df(x): return n * power(x, n-1) return find_zero(f, df) print(nth_root_of_a(2,64)) print(nth_root_of_a(3,64)) print(nth_root_of_a(6,64)) ## Currying # first call h,then y def curried_pow(x): def h(y): return pow(x, y) return h print(curried_pow(2)(3)) def map_to_range(start, end, f): while start < end: print(f(start)) start = start + 1 print(map_to_range(0,2,curried_pow(2))) ## Lambda Expressions s=lambda x:x*x print(s(2)) """ python decorater """ def trace1(fn): def wrapped(x): print('->',fn,'(',x,')') return fn(x) return wrapped @trace1 def triple(x): return x*3 print(triple(12))
87dcdaccfb86c864dd06286e294fd39ca05e391f
ciscorucinski/Boolean-Gates
/component/processor/adder.py
2,034
3.515625
4
from component.logic_gates.basic import and_gate, or_gate from component.logic_gates.composite import xor_gate from utility.alias import Byte, Bit, Adder def half_adder(a: Bit, b: Bit) -> Adder: """ Sums two single bits :param a: bit 1 :param b: bit 2 :return: Returns the sum and carry bits of adding two bits. [0] = sum, [1] = carry """ sum = xor_gate(a, b) carry = and_gate(a, b) return Adder(sum, carry) def full_adder(a: Bit, b: Bit, c: Bit) -> Adder: """ :param a: bit 1 :param b: bit 2 :param c: bit 3 :return Returns the sum and carry bits of adding three bits. [0] = sum, [1] = carry """ xor_ab = xor_gate(a, b) sum = xor_gate(xor_ab, c) carry = or_gate(and_gate(a, b), and_gate(xor_ab, c)) return Adder(sum, carry) def adder(byte1: Byte, byte2: Byte) -> Byte: """ :param byte1: byte 1 :param byte2: byte 2 :return: Returns the sum of two bytes as a tuple of 8 bits """ # print(byte1.binary) add_bits_1 = half_adder(byte1.bit1, byte2.bit1) add_bits_2 = full_adder(byte1.bit2, byte2.bit2, add_bits_1.carry) add_bits_3 = full_adder(byte1.bit3, byte2.bit3, add_bits_2.carry) add_bits_4 = full_adder(byte1.bit4, byte2.bit4, add_bits_3.carry) add_bits_5 = full_adder(byte1.bit5, byte2.bit5, add_bits_4.carry) add_bits_6 = full_adder(byte1.bit6, byte2.bit6, add_bits_5.carry) add_bits_7 = full_adder(byte1.bit7, byte2.bit7, add_bits_6.carry) add_bits_8 = full_adder(byte1.bit8, byte2.bit8, add_bits_7.carry) value = Byte(bit1=add_bits_1.sum, bit2=add_bits_2.sum, bit3=add_bits_3.sum, bit4=add_bits_4.sum, bit5=add_bits_5.sum, bit6=add_bits_6.sum, bit7=add_bits_7.sum, bit8=add_bits_8.sum ) if add_bits_8.carry == 1: print("8-bit Adder Overflow", byte1, "+", byte2, "=", value) print("Sum = " + value.binary) return value
0923fadb046c8124ee9e9b25ad8063ec394d1145
morozj01/Python-Problems
/Assignment 7/MorozJustin_assign7_problem1a.py
1,113
4.15625
4
#Justin Moroz 11/17/2016 Section 002 user=input("Pleae enter a username: ") accept=False while accept==False: if len(user)>15 or len(user)<8: print("Username must be between 8 and 15 characters") user=input("Please enter another user name: ") if user.isalnum()==False: print("Username can only contain letters and numbers") user=input("Please enter another username") if user.isupper()==True: print("Username must contain at least one lowercase letter") user=input("Please enter another username") if user.islower()==True: print("Username must contain at least one uppercase letter") user=input("Please enter another username") if user.isalpha()==True: print("Username must contain at least one number") user=input("Please enter another username") if user[0].isnumeric() or user[-1].isnumeric==True: print("Username cannot have a number as the first or last character") user=input("Please enter another username") else: print("Uername is valid") break
91a3b72bb3141769153dd42e1ed5615ee2e37d0b
gagan1510/PythonBasics
/PythonRef/classAdv2.py
1,007
3.90625
4
class Account(object): "This is a simple class" num_accounts = 0 def __init__(self, name, balance): "A new account is being created" self.name = name self.balance = balance Account.num_accounts += 1 def __del__(self): Account.num_accounts = -1 def deposit(self, amt): "Add to the balance" self.balance += amt def withdraw(self,amt): "Subtract from balance" self.balance -= amt def inquire(self): print("\nThese are the details of the account holder:") print("Name:\t" + self.name) print("Balance:\t", self.balance) class lowbal(Account): def islow(self): if self.balance < 500: return 'low bal' return 'appropriate bal' def tax(self): topay = (self.balance * 14.0/100) return topay one = lowbal("Gagan", 1000) one.deposit(500) one.inquire() one.withdraw(750) one.inquire() print("\nThe tax to be paid is: " + str(one.tax()))
820ecbd9eab2801ecd94a61fbad2127d5cfb95cf
mc-mario/PracticePython
/PycharmProjects/PracticePython/Ex2.OddorEven.py
360
3.875
4
number = int(input("Introduce un número: ")) if (number % 2) == 1: print("Impar") else : print("Par") if (number % 4) == 0: print("Múltiplo de 4!!!!") print("Extra: Introduce dos números") enum = int(input("Primer número: ")) enum2 = int(input("Segundo número: ")) print("{0} / {1} resulta en : {2}".format(enum,enum2,enum/enum2))
d1ac9ad2bec56d0222d08a5f5dd8a9786065b9ae
hailschwarz/ProyectoCompletoFinal
/PROYECTO/Representacion teclas.py
304
3.703125
4
from tkinter import * def keypress(event): if (event.keysym == 'Escape'): mainRoot.destroy() keyPressed=event.char print("You pressed" + keyPressed) mainRoot = Tk() print("Press a key") mainRoot.bind_all('<Key>',keypress) mainRoot.withdraw() mainRoot.mainloop()
093e21c79c1217933a20d00f619bcbe729d40106
marcciosilva/maa
/Lab1/Players/RandomPlayer.py
817
3.609375
4
# -*- coding: utf-8 -*- from Player import Player import random class RandomPlayer(Player): """Jugador que elige una jugada al azar dentro de las posibles.""" name = 'Random' def __init__(self, color): super(RandomPlayer, self).__init__(self.name, color=color) def move(self, board, opponent_move): possible_moves = board.get_possible_moves(self.color) i = random.randint(0, len(possible_moves) - 1) return possible_moves[i] def on_win(self, board): print 'Gané y soy el color:' + self.color.name def on_defeat(self, board): print 'Perdí y soy el color:' + self.color.name def on_draw(self, board): print 'Empaté y soy el color:' + self.color.name def on_error(self, board): raise Exception('Hubo un error.')
a94a0ae8a789b46ea3f067b3724f6c550bb240d0
kenshinji/codingbat_python
/Logic-2/make_bricks.py
197
3.625
4
def make_bricks(small, big, goal): if goal / 5 >= big: rest = goal - big * 5 return rest <= small else: rest = goal - goal / 5 * 5 return rest <= small
506d7a651b513b3474ac3b5cc718e0a9e9331929
lihujun101/LeetCode
/LinkList/L19_remove-nth-node-from-end-of-list.py
1,857
3.65625
4
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): # 两次遍历 def removeNthFromEnd1(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ length = 0 head_0 = head # 链表长度 while head_0 is not None: head_0 = head_0.next length += 1 # 正序的位置 idx_n = length - n # 排序为0 if idx_n == 0: head = head.next return head head_0, cur, idx = head, head_0, 0 while idx < idx_n: cur, head_0 = head_0, head_0.next idx += 1 if head_0 is None: cur.next = None else: cur.next = head_0.next del head_0 return head # 一次遍历,两个指针差值为n def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ idx = 0 head_i, head_j = head, head while idx < n: head_j = head_j.next idx += 1 # 如果n为第一个节点的话,需特殊处理 if head_j is None: head = head.next return head # 当head_j.next指向None的时候,head_i.next就是倒数第n个值 while head_j.next is not None: head_i = head_i.next head_j = head_j.next cur = head_i.next head_i.next = cur.next del cur return head if __name__ == '__main__': l1 = ListNode(0) l1.next = ListNode(1) l1.next.next = ListNode(2) l1.next.next.next = ListNode(3) l1.next.next.next.next = ListNode(4) s = Solution() l2 = (s.removeNthFromEnd(l1,5)) print(l2)
3cd5430be3792f72bc64f4878e22b56c3f649a50
orionzhou/maize
/utils/iter.py
8,744
3.875
4
""" Itertools recipes (copied and pasted from http://docs.python.org/library/itertools.html) with some modifications. """ from itertools import * from collections import Iterable def take(n, iterable): "Return first n items of the iterable as a list" return list(islice(iterable, n)) def tabulate(function, start=0): "Return function(0), function(1), ..." return imap(function, count(start)) def consume(iterator, n): "Advance the iterator n-steps ahead. If n is none, consume entirely." # Use functions that consume iterators at C speed. if n is None: # feed the entire iterator into a zero-length deque collections.deque(iterator, maxlen=0) else: # advance to the empty slice starting at position n next(islice(iterator, n, n), None) def nth(iterable, n, default=None): "Returns the nth item or a default value" return next(islice(iterable, n, None), default) def quantify(iterable, pred=bool): "Count how many times the predicate is true" return sum(imap(pred, iterable)) def padnone(iterable): """Returns the sequence elements and then returns None indefinitely. Useful for emulating the behavior of the built-in map() function. """ return chain(iterable, repeat(None)) def ncycles(iterable, n): "Returns the sequence elements n times" return chain.from_iterable(repeat(tuple(iterable), n)) def dotproduct(vec1, vec2): return sum(imap(operator.mul, vec1, vec2)) def flatten(listOfLists): "Flatten one level of nesting" return chain.from_iterable(listOfLists) def repeatfunc(func, times=None, *args): """Repeat calls to func with specified arguments. Example: repeatfunc(random.random) """ if times is None: return starmap(func, repeat(args)) return starmap(func, repeat(args, times)) def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return zip(a, b) def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return zip_longest(fillvalue=fillvalue, *args) def roundrobin(*iterables): "roundrobin('ABC', 'D', 'EF') --> A D E B F C" # Recipe credited to George Sakkis pending = len(iterables) nexts = cycle(iter(it).next for it in iterables) while pending: try: for next in nexts: yield next() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending)) def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) def unique_everseen(iterable, key=None): "List unique elements, preserving order. Remember all elements ever seen." # unique_everseen('AAAABBBCCDAABBB') --> A B C D # unique_everseen('ABBCcAD', str.lower) --> A B C D seen = set() seen_add = seen.add if key is None: for element in ifilterfalse(seen.__contains__, iterable): seen_add(element) yield element else: for element in iterable: k = key(element) if k not in seen: seen_add(k) yield element def unique_justseen(iterable, key=None): "List unique elements, preserving order. Remember only the element just seen." # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B # unique_justseen('ABBCcAD', str.lower) --> A B C A D return imap(next, imap(itemgetter(1), groupby(iterable, key))) def iter_except(func, exception, first=None): """ Call a function repeatedly until an exception is raised. Converts a call-until-exception interface to an iterator interface. Like __builtin__.iter(func, sentinel) but uses an exception instead of a sentinel to end the loop. Examples: bsddbiter = iter_except(db.next, bsddb.error, db.first) heapiter = iter_except(functools.partial(heappop, h), IndexError) dictiter = iter_except(d.popitem, KeyError) dequeiter = iter_except(d.popleft, IndexError) queueiter = iter_except(q.get_nowait, Queue.Empty) setiter = iter_except(s.pop, KeyError) """ try: if first is not None: yield first() while 1: yield func() except exception: pass def random_product(*args, **kwds): "Random selection from itertools.product(*args, **kwds)" pools = map(tuple, args) * kwds.get('repeat', 1) return tuple(random.choice(pool) for pool in pools) def random_permutation(iterable, r=None): "Random selection from itertools.permutations(iterable, r)" pool = tuple(iterable) r = len(pool) if r is None else r return tuple(random.sample(pool, r)) def random_combination(iterable, r): "Random selection from itertools.combinations(iterable, r)" pool = tuple(iterable) n = len(pool) indices = sorted(random.sample(xrange(n), r)) return tuple(pool[i] for i in indices) def random_combination_with_replacement(iterable, r): "Random selection from itertools.combinations_with_replacement(iterable, r)" pool = tuple(iterable) n = len(pool) indices = sorted(random.randrange(n) for i in xrange(r)) return tuple(pool[i] for i in indices) def tee_lookahead(t, i): """Inspect the i-th upcomping value from a tee object while leaving the tee object at its current position. Raise an IndexError if the underlying iterator doesn't have enough values. """ for value in islice(t.__copy__(), i, None): return value raise IndexError(i) """ Following code is stolen from Erik Rose: <https://github.com/erikrose/more-itertools> """ _marker = object() def chunked(iterable, n): """Break an iterable into lists of a given length:: >>> list(chunked([1, 2, 3, 4, 5, 6, 7], 3)) [[1, 2, 3], [4, 5, 6], [7]] If the length of ``iterable`` is not evenly divisible by ``n``, the last returned list will be shorter. This is useful for splitting up a computation on a large number of keys into batches, to be pickled and sent off to worker processes. One example is operations on rows in MySQL, which does not implement server-side cursors properly and would otherwise load the entire dataset into RAM on the client. """ # Doesn't seem to run into any number-of-args limits. for group in (list(g) for g in zip_longest(*[iter(iterable)] * n, fillvalue=_marker)): if group[-1] is _marker: # If this is the last group, shuck off the padding: del group[group.index(_marker):] yield group class peekable(object): """Wrapper for an iterator to allow 1-item lookahead Call ``peek()`` on the result to get the value that will next pop out of ``next()``, without advancing the iterator: >>> p = peekable(xrange(2)) >>> p.peek() 0 >>> p.next() 0 >>> p.peek() 1 >>> p.next() 1 Pass ``peek()`` a default value, and it will be returned in the case where the iterator is exhausted: >>> p = peekable([]) >>> p.peek('hi') 'hi' If no default is provided, ``peek()`` raises ``StopIteration`` when there are no items left. To test whether there are more items in the iterator, examine the peekable's truth value. If it is truthy, there are more items. >>> assert peekable(xrange(1)) >>> assert not peekable([]) """ # Lowercase to blend in with itertools. The fact that it's a class is an # implementation detail. def __init__(self, iterable): self._it = iter(iterable) def __iter__(self): return self def __nonzero__(self): try: self.peek() except StopIteration: return False return True def peek(self, default=_marker): """Return the item that will be next returned from ``next()``. Return ``default`` if there are no items left. If ``default`` is not provided, raise ``StopIteration``. """ if not hasattr(self, '_peek'): try: self._peek = self._it.next() except StopIteration: if default is _marker: raise return default return self._peek def next(self): ret = self.peek() del self._peek return ret if __name__ == '__main__': import doctest doctest.testmod()
6de3ff14b94788cf43a8cb72b57e2c65feeb7fed
debajyoti94/FightAgainstCancer
/src/feature_engg.py
3,206
3.90625
4
""" In this code we will perform data cleaning operations""" import abc import pickle import seaborn as sns import sklearn.preprocessing as preproc # create an abc for feature engineering class # doing this so that i do not forget the absolute necessary functions class MustHaveForFeatureEngineering: __metaclass__ = abc.ABCMeta @abc.abstractmethod def cleaning_data(self): """ Apply feature engineering techniques and clean data :return: cleaned data """ return @abc.abstractmethod def plot_null_values(self): """ To check the if any null values exist in the dataset :return: """ return class FeatureEngineering(MustHaveForFeatureEngineering): def label_encoder(self, dataset, features_to_encode): """ For handling categorical features. In this case, for handling target feature. :param dataset: input data :param features_to_encode: features that we want to encode :return: encoded feature """ le = preproc.LabelEncoder() encoded_feature = le.fit_transform(dataset[features_to_encode]) return encoded_feature def scaling_data(self, dataset): """ Applying minmax scaling :param dataset: input data :return: scaled data """ for feature in dataset.columns: dataset[feature] = preproc.minmax_scale(dataset[[feature]]) return dataset def cleaning_data(self, dataset): """ overriding the cleaning data function from abc class :param dataset: dataset to be cleaned :return: cleaned data X, cleaned Y """ # apply label encoding to target class # 1 is the target class # print(type(dataset)) encoded_features = self.label_encoder(dataset, [1]) dataset[1] = encoded_features # print(type(dataset)) # print(dataset[[0,1]]) dataset.drop(["index", 0], axis=1, inplace=True) # apply minmax scaling to remaining features scaled_dataset = self.scaling_data(dataset) return scaled_dataset def plot_null_values(self, dataset): """ Create a heatmap to verify if any null value exists :param dataset: dataset to be verified :return: heatmap plot """ sns_heatmap_plot = sns.heatmap( dataset.isnull(), cmap="Blues", yticklabels=False ) sns_heatmap_plot.figure.savefig(config.NULL_CHECK_HEATMAP) class DumpLoadFile: def load_file(self, filename): """ Pickled file that you want to load :param filename: consists of filename + path :return: unpickled file """ with open(filename, "rb") as pickle_handle: return pickle.load(pickle_handle) def dump_file(self, file, filename): """ Create a pickled file :param file: file that you want to pickle :param filename: Filename for that pickled file :return: nothing """ with open(filename, "wb") as pickle_handle: pickle.dump(file, pickle_handle)
c20731a20495aca562cb938427a424158321901e
udhayprakash/PythonMaterial
/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/c_locks/b3b_with_locks_check_prime.py
1,096
3.796875
4
""" Purpose: Using threaing.Lock() The acquire() method is used to lock access to a shared variable The release() method is used to unlock the lock. The release() method throws a RuntimeError exception if used on an unlocked lock. """ import threading class Primenum(threading.Thread): prime_nums = {} lock = threading.Lock() def __init__(self, num): threading.Thread.__init__(self) self.num = num Primenum.lock.acquire() Primenum.prime_nums[num] = "None" Primenum.lock.release() def run(self): ctr = 2 res = True while ctr * ctr < self.num and res: if self.num % ctr == 0: res = False ctr += 1 Primenum.lock.acquire() Primenum.prime_nums[self.num] = res Primenum.lock.release() threads = [] while True: input_val = int(input("number: ")) if input_val < 1: print(f"{Primenum.prime_nums =}") break thread = Primenum(input_val) threads += [thread] thread.start() for x in threads: x.join()
e9fa9ade8567d70fa9ec5fb7ad48d5ad29a5a5e0
mmelqonyan/Stepanavan
/Gayane Gevorgyan/1.04/json.py
230
3.578125
4
#!/usr/bin/python3.5 import re import json with open('file', 'r') as dict_or_not: obj=dict_or_not.read() if re.findall(r"^\{'(.*?)':'(.*?)',?\s*\}$", obj): print("Valid json\n") else: print("Invalid json")
9c9f8311e411da2a2913255e5af29ba5709bc5b7
daniel-reich/ubiquitous-fiesta
/mYGipMffRTYxYmv5i_9.py
235
3.84375
4
def simple_equation(a, b, c): if a+b==c: return '{}+{}={}'.format(a,b,c) elif a-b==c: return '{}-{}={}'.format(a,b,c) elif a*b==c: return '{}*{}={}'.format(a,b,c) elif a/b==c: return '{}/{}={}'.format(a,b,c) else:return ""
982e7f2b41fac65df34e6acdafba0ed5e3c461a4
arnabs542/Competitive-Programming
/Leetcode/Easy/1281_SubtractTheProductAndSumOfDigitsOfAnInteger.py
330
3.75
4
# https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/ class Solution: def subtractProductAndSum(self, n: int) -> int: product = 1 _sum = 0 n = str(n) for i in n: x = int(i) product *= x _sum += x return product - _sum
d5665b65ab0dd1d787ec7f86f6b392cedf838d21
4ever-blessed/Github_python2_code
/python_basic_knowledge/简易的摄氏华氏转换(getset方法).py
693
3.921875
4
class Celsius(object): def __init__(self,value = 26.0): self.value = float(value) def __get__(self, instance, owner): return self.value def __set__(self, instance, value): self.value = float(value) class Fahrenheit(object): def __get__(self, instance, owner): return instance.cel * 1.8 + 32 def __set__(self, instance, value): instance.cel = (float(value) - 32) / 1.8 class Temperature(object): cel = Celsius() fah = Fahrenheit() temp_1 = Temperature() temp_1.cel = 30 print 'The temp is 30 , the fahrenheit is ',temp_1.fah temp_2 = Temperature() temp_1.fah = 131 print 'The fahrenheit is 131 , the temp is ',temp_2.cel
8d8a4b2b3304dc78db56c8b23112f7ff351f2cba
ShravanKumar-Technology/personalPython
/characterCount.py
189
3.5
4
message = 'it was bright cold day in april.' count = {} for character in message.upper(): count.setdefault(character,0) count[character] = count[character] + 1 print(count)
7bdeb15603470a3de38416587ec1972337427bcc
ckronber/python_files
/Computer Science/Hash Tables/hashMap1.py
1,006
3.640625
4
class HashMap(): def __init__(self,array_size): self.array_size = array_size self.array = [None]*array_size def hash(self,key): key_bytes = key.encode() hash_code = sum(key_bytes) print(hash_code) return hash_code def compressor(self,hash_code): return hash_code%self.array_size def assign(self,key,value): array_index = self.compressor(self.hash(key)) current_array_value = self.array[array_index] if current_array_value is None: self.array[array_index] = [key, value] return if current_array_value[0] == key: self.array[array_index] = [key, value] return # current_array_value currently holds different key return def retrieve(self,key): array_index = self.compressor(self.hash(key)) return self.array[array_index] hash_map = HashMap(20) hash_map.assign("gneiss","metamorphic") hash_map.assign("gneises","cats") print(hash_map.retrieve("gneiss")) print(hash_map.retrieve("gneises"))
3911d521696bc2767667e9d4cb3bcb54564a0393
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/codewar/_Codewars-Solu-Python-master/src/kyu5_Going_to_Zero_or_to_Infinity.py
2,257
3.828125
4
from math import factorial, trunc class Solution(): """ https://www.codewars.com/kata/going-to-zero-or-to-infinity Consider the following numbers (where n! is factorial(n)): u1 = (1 / 1!) * (1!) u2 = (1 / 2!) * (1! + 2!) u3 = (1 / 3!) * (1! + 2! + 3!) un = (1 / n!) * (1! + 2! + 3! + ... + n!) Which will win: 1 / n! or (1! + 2! + 3! + ... + n!)? Are these number going to 0 because of 1/n! or to infinity due to the sum of factorials? Task: Calculate (1 / n!) * (1! + 2! + 3! + ... + n!) for a given n. Call this function "going(n)" where n is an integer greater or equal to 1. To avoid discussions about rounding, if the result of the calculation is designed by "result", going(n) will return "result" truncated to 6 decimal places. Examples: 1.0000989217538616 will be truncated to 1.000098 1.2125000000000001 will be truncated to 1.2125 Remark: Keep in mind that factorials grow rather rapidly, and you can need to handle large inputs. """ def __init__(self): pass def going_01(self, n): """ """ if n == 1: return 1 fn = factorial(n) ret = (1 + sum(factorial(x) for x in range(2, n))) / fn + 1 return int(ret * 1000000) / 1000000 def going_02(self, n): """ """ if n == 1: return 1 ret = 1 f = 1 for i in range(2, n + 1): f *= i ret += f return round(ret / f - 0.000000499, 6) def going_03(self, n): """ """ if n == 1: return 1 ret = 1 f = 1 for i in range(2, n): f *= i ret += f return trunc((ret / (f * n) + 1) * 1000000) / 1000000 def sets_gen(going): test_sets = [] for n in range(1, 500): match = going(n) test_sets.append(( (n,), match )) return test_sets if __name__ == '__main__': sol = Solution() from test_fixture import Test_Fixture tf = Test_Fixture(sol, sets_gen) tf.prep() tf.test(prt_docstr=False) tf.test_spd(10, prt_docstr=True)
24fa551bb65757d8786987f02f7c39a87bf7bfa7
Han-Sora/pp2021
/Student.Mark.OOP.lw3.py
3,922
3.703125
4
import math import numpy as np import curses Student = [] StudentName = [] StudentDoB = [] StudentID = [] Course = [] CourseID = [] CourseName = [] Mark = [] Credit = [] gpa = [] MarkGPA = [] class Std: def __init__(self, id, name, dob): self.__id = id self.__name = name self.__dob = dob Student.append(self) StudentID.append(self.__id) def get_id(self): return self.id def get_name(self): return self.name def get_dob(self): return self.dob class Cse: def __init__(self, cid, cname): self._cid = cid self._cname = cname Course.append(self) CourseID.append(self._cid) def get_id(self): return self._cid def get_name(self): return self.cname class Marks: def __init__(self, mid, nid, mark): self._mid = mid self._nid = nid self._mark = mark Mark.append(self) def get_mid(self): return self.mid def get_nid(self): return self.nid def get_mark(self): return self.mark def get_gpa(self): return self.gpa def student_num(): student = int(input("Enter students in class: ")) return student # Add student def add_student(): print("STUDENT INFO") name = input("Enter Student's name: ") id = input("Enter Student's ID: ") dob = input("Enter Student's DoB: ") st_u = { 'id': id, 'name': name, 'dob': dob } Student.append(st_u) StudentID.append(id) # Add number of course def course_num(): course = int(input("Enter total number of course: ")) return # Add course def add_course(): print("COURSE") cname = input("Enter Course's name: ") cid = input("Enter Course's ID: ") cc = input("Enter Course's Credit:") cr_o = { 'cid': cid, 'cname': cname, 'cc': cc } Course.append(cr_o) CourseID.append(cid) # Create mark for students def create_mark(): g = 1 tu = len(Student) while g <= tu: g += 1 mid = input("Enter the Student ID: ") if mid in Student: for i in range(0, len(CourseID)): nid = input("Enter the Course ID: ") if nid in CourseID: mark = float(input("Enter Student Mark: ")) kk = { 'mid': mid, 'nid': nid, 'mark': mark } else: print("Student ID NOT FOUND !!") break Mark.append(kk) else: print("Course ID NOT FOUND !!") break def aver_gpa(): var=np.array([gpa_d]) cred=np.array([Credit]) print("GPA: ") name =T_pain.getstr().decode() if name in Student: for i in range(len(Mark)): recallcre=np.sum(cred) recallvar=np.sum(np.multiply(var,cred)) T_pain.refresh() Gpa=recallvar/recallcre T_pain.refresh() else: return 0 gpa_s.append(Gpa) T_pain.refresh() for st_infor in Mark: T_pain.clear() T_pain.refresh() T_pain.addstr(" Mark_studentid: %s Gpa:%s \n" %(st_infor.get_id_course(), Gpa)) T_pain.refresh() break def show_list_student(): print("STUDENT LIST") for i in range(0, len(Student)): print(f"ID:{Student[i]['id']} name:{Student[i]['name']} DoB:{Student[i]['dob']}") def show_list_course(): print("COURSE LIST") for i in range(0, len(Course)): print(f"ID:{Course[i]['id']} name : {Course[i]['name']}") def show_mark(): print("STUDENTS MARK LIST") for i in range(0, len(Mark)): print(f"ID-course: {Mark[i]['b']} ID-Student: {Mark[i]['a']} mark:{Mark[i]['mark']}") def aver_gpa(): print("GPA")
3d529053e7cb746231380c2095b4842ba4f50f7c
AvijitMaity/Avijit-Maity-Computational-Physics-2-Assignment-2
/Problem 3.py
1,885
3.78125
4
''' Runge-Kutta Method ==================================================================== Author: Avijit Maity ==================================================================== This Program solves the differential equation using with Runge-Kutta Method ''' import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint # The ordinary differential equation def f(x,y,z ): return z def g(x,y,z ): return 2*z - y + x*np.exp(x) - x # Define the initial values and mesh # limits: 0.0 <= x <= 1.0 a=0 b=1 h= 0.01 # determine step-size x = np.arange( a, b+h, h ) # create mesh N = int((b-a)/h) y = np.zeros((N+1,)) # initialize y z = np.zeros((N+1,)) # initialize z x[0]=0 y[0]=0 z[0]=0 for i in range(1,N+1): # Apply Runge-Kutta Method k1 = h * f(x[i - 1], y[i - 1], z[i - 1]) l1 = h * g(x[i - 1], y[i - 1], z[i - 1]) k2 = h * f(x[i - 1] + h / 2.0, y[i - 1] + k1 / 2.0, z[i - 1] + l1 / 2.0 ) l2 = h * g(x[i - 1] + h / 2.0, y[i - 1] + k1 / 2.0, z[i - 1] + l1 / 2.0 ) k3 = h * f(x[i - 1] + h / 2.0, y[i - 1] + k2 / 2.0, z[i - 1] + l2 / 2.0) l3 = h * g(x[i - 1] + h / 2.0, y[i - 1] + k2 / 2.0, z[i - 1] + l2 / 2.0) k4 = h * f(x[i-1]+h, y[i - 1] + k3, z[i - 1] + l3) l4 = h * g(x[i-1]+h, y[i - 1] + k3, z[i - 1] + l3) y[i] = y[i - 1] + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0 z[i] = z[i - 1] + (l1 + 2.0 * l2 + 2.0 * l3 + l4) / 6.0 # The exact solution for this initial value def exact( x ): return (-12 + 12*np.exp(x) - 6*x - 6*np.exp(x)*x + np.exp(x)*x**3)/6 # Plot the Euler solution from matplotlib.pyplot import * plot( x, y, label='approximation' ) plot( x, exact(x),":",color="red",label='exact' ) title( "Runge-Kutta Method in a Python, h= 0.01" ) suptitle("Problem 3") xlabel('x') ylabel('y(x)') legend(loc=4) grid() show()
b603cc0fda7639dd58d284bb8ab427bf92d45e21
Sanjay-Leo/cracking-the-coding-interview
/3. stacks-queues/4. queue-using-stacks.py
322
3.546875
4
class Queue: def __init__(self): self.inbox = [] self.out = [] def enqueue(self, value): self.inbox.append(value) def dequeue(self): if len(self.out) == 0: while len(self.inbox) != 0: self.out.append(self.inbox.pop()) return self.out.pop()
0898be5d11c363449d86a4dbc4b4613e172ff2cb
alirezahi/SearchAlgorithms
/Graph.py
15,038
4.03125
4
class Graph(): def __init__(self,problem): self.nodes = [problem.initial_state()] self.edges = dict() self.edges[problem.initial_state()] = dict() self.problem = problem self.parent = {} self.nodes_expanded_count = 1 self.nodes_count = 1 self.max_nodes = [] def insert(self,primary_node,second_node=None,weight=-1): if primary_node: if not (primary_node in self.nodes): # add first_node if it doesn't exist self.nodes.append(primary_node) self.edges[primary_node] = dict() if second_node: if not(second_node in self.nodes): # add second node if it doesn't exist self.nodes.append(second_node) self.edges[second_node] = dict() # adding edge of first and second node self.edges[primary_node][second_node] = weight self.edges[second_node][primary_node] = weight return None def print_path(self,start): print('Nodes Expanded: ' + str(self.nodes_expanded_count)) print('Nodes Visited: ' + str(self.nodes_count)) print('Memory Usage: ' + str(max(self.max_nodes))) path_node = start path_list = [] while path_node: path_list.append(path_node) path_node = self.parent[path_node] if path_node in self.parent else None print('Path Cost: ' + str(len(path_list)-1)) for i in reversed(path_list): print(i) def bfs_graph_search(self,start): self.__init__(self.problem) if start is None or start not in self.nodes: return None visited = set() queue = [start] while queue: self.max_nodes.append(len(visited) + len(queue)) current_node = queue.pop(0) self.nodes_expanded_count += 1 if self.problem.is_goal_test(current_node): self.print_path(current_node) return if current_node not in visited: visited.add(current_node) self.nodes_count += len(list(set(self.problem.actions(current_node)))) for node in list(set(self.problem.actions(current_node))-visited): self.insert(current_node,node) self.parent[node] = current_node queue.extend(set(self.edges[current_node].keys()) - visited) return visited def bfs_tree_search(self, start): self.__init__(self.problem) if start is None or start not in self.nodes: return None queue = [start] while queue: self.max_nodes.append(len(queue)) current_node = queue.pop(0) self.nodes_expanded_count += 1 if self.problem.is_goal_test(current_node): self.print_path(current_node) return self.nodes_count += len(self.problem.actions(current_node)) for node in self.problem.actions(current_node): self.insert(current_node, node) self.parent[node] = current_node queue.extend(set(self.edges[current_node].keys())) return def dfs_graph_search(self,start): self.__init__(self.problem) if start is None or start not in self.nodes: return None visited = set() nodes_stack = [start] while nodes_stack: self.max_nodes.append(len(visited) + len(nodes_stack)) current_node = nodes_stack.pop() self.nodes_expanded_count += 1 if self.problem.is_goal_test(current_node): self.print_path(current_node) return 'find' if current_node not in visited: visited.add(current_node) self.nodes_count += len(list(set(self.problem.actions(current_node)))) for node in list(set(self.problem.actions(current_node))-visited): self.insert(current_node, node) self.parent[node] = current_node nodes_stack.extend(set(self.edges[current_node].keys()) - visited) return None def dfs_tree_search(self, start): self.__init__(self.problem) if start is None or start not in self.nodes: return None nodes_stack = [start] while nodes_stack: self.max_nodes.append(len(nodes_stack)) current_node = nodes_stack.pop() self.nodes_expanded_count += 1 if self.problem.is_goal_test(current_node): self.print_path(current_node) return 'find' self.nodes_count += len(self.problem.actions(current_node)) for node in self.problem.actions(current_node): self.insert(current_node, node) self.parent[node] = current_node nodes_stack.extend(set(self.edges[current_node].keys())) return None def dfs_graph_limited_search(self, start,depth=0): self.__init__(self.problem) self.nodes = [(self.problem.initial_state(), 0)] self.edges[(self.problem.initial_state(), 0)] = dict() if start is None or start not in [x[0] for x in self.nodes]: return None visited = set() nodes_stack = [(start,0)] while nodes_stack: self.max_nodes.append(len(visited) + len(nodes_stack)) current_node = nodes_stack.pop() self.nodes_expanded_count += 1 if self.problem.is_goal_test(current_node[0]): self.print_path(current_node[0]) return 'final' if current_node[0] not in [x[0] for x in visited]: visited.add(current_node) if current_node[1] != depth: self.nodes_count += len(list(set(self.problem.actions(current_node[0])))) for node in list(set(self.problem.actions(current_node[0])) - set([x[0] for x in visited])): self.insert(current_node, (node,current_node[1]+1)) self.parent[node] = current_node[0] nodes_stack.extend(set(self.edges[current_node].keys()) - visited) return None def dfs_tree_limited_search(self, start,depth=0): self.__init__(self.problem) self.nodes = [(self.problem.initial_state(), 0)] self.edges[(self.problem.initial_state(), 0)] = dict() if start is None or start not in [x[0] for x in self.nodes]: return None nodes_stack = [(start,0)] while nodes_stack: self.max_nodes.append(len(nodes_stack)) current_node = nodes_stack.pop() self.nodes_expanded_count += 1 if self.problem.is_goal_test(current_node[0]): self.print_path(current_node[0]) return 'final' if current_node[1] != depth: self.nodes_count += len(self.problem.actions(current_node[0])) for node in self.problem.actions(current_node[0]): self.insert(current_node, (node, current_node[1] + 1)) self.parent[node] = current_node[0] nodes_stack.extend(set(self.edges[current_node].keys())) return None def iddfs_graph_search(self,start): problem_depth = 1 res = self.dfs_graph_limited_search(start,depth=problem_depth) while not res: problem_depth += 1 res = self.dfs_graph_limited_search(start, depth=problem_depth) def iddfs_tree_search(self, start): problem_depth = 1 res = self.dfs_tree_limited_search(start, depth=problem_depth) while not res: problem_depth += 1 res = self.dfs_tree_limited_search(start, depth=problem_depth) def bidirectional_graph_search(self,start,goal): #this part of code is not complete and has to be completed!!!!!!!!!! self.__init__(self.problem) self.nodes = [self.problem.initial_state()] self.edges[self.problem.initial_state()] = dict() #adding destination node to start from there and reach to the start node dest_nodes = list() dest_nodes.extend(self.problem.goal_tests()) dest_edges = dict() if start is None or start not in self.nodes: return None visited = set() visited_second = set() nodes_stack = [start] nodes_second_stack = [goal] while nodes_stack or nodes_second_stack: self.max_nodes.append(len(visited) + len(nodes_stack) +len(visited_second) + len(nodes_second_stack)) current_node = nodes_stack.pop() self.nodes_expanded_count += 1 if self.problem.is_goal_test(current_node): print('FOUND!!!') return if current_node not in visited: visited.add(current_node) self.nodes_count += len(self.problem.actions(current_node)) for node in list(set(self.problem.actions(current_node))-visited): self.insert(current_node, node) nodes_stack.extend(set(self.edges[current_node].keys()) - visited) current_node_second = nodes_second_stack.pop() self.nodes_expanded_count += 1 if current_node_second == self.problem.initial_state(): print('FOUND!!!') return if current_node_second not in visited_second: visited_second.add(current_node_second) self.nodes_count += len(self.problem.actions(current_node_second, straight=False)) for node in list(set(self.problem.actions(current_node_second,straight=False))-visited_second): self.insert(current_node_second, node) nodes_second_stack.extend(set(self.edges[current_node_second].keys()) - visited_second) common_nodes = (set(nodes_stack) | set(visited)) & (set(nodes_second_stack) | set(visited_second)) if len(common_nodes) > 0: return return visited def UCS_graph_search(self, start): self.__init__(self.problem) self.nodes = [self.problem.initial_state()] self.edges[self.problem.initial_state()] = dict() visited = set() #defining list for nodes, [node,g(n)] nodes = [[start, 0]] while nodes: self.max_nodes.append(len(visited) + len(nodes)) current_node = min(nodes, key=lambda k: k[1]) self.nodes_expanded_count += 1 visited.add(current_node[0]) if self.problem.is_goal_test(current_node[0]): self.print_path(current_node[0]) return current_node[0] self.nodes_count += len(list(set(self.problem.actions(current_node[0])))) for node in list(set(self.problem.actions(current_node[0])) - visited): cost = self.problem.edge_cost(current_node[0], node) self.insert(current_node[0], node, cost) self.parent[node] = current_node[0] current_cost = list(filter(lambda element: element[0] == current_node[0], nodes))[0][1] + cost nodes.append([node, current_cost]) nodes.remove(current_node) def UCS_tree_search(self, start): self.__init__(self.problem) self.nodes = [self.problem.initial_state()] self.edges[self.problem.initial_state()] = dict() #defining list for nodes, [node,g(n)] nodes = [[start, 0]] while nodes: self.max_nodes.append(len(nodes)) current_node = min(nodes, key=lambda k: k[1]) self.nodes_expanded_count += 1 if self.problem.is_goal_test(current_node[0]): self.print_path(current_node[0]) return current_node[0] self.nodes_count += len(list(set(self.problem.actions(current_node[0])))) for node in list(set(self.problem.actions(current_node[0]))): cost = self.problem.edge_cost(current_node[0], node) self.insert(current_node[0], node, cost) self.parent[node] = current_node[0] current_cost = list(filter(lambda element: element[0] == current_node[0], nodes))[0][1] + cost nodes.append([node, current_cost]) nodes.remove(current_node) def A_Star_graph_search(self,start): self.__init__(self.problem) self.nodes = [self.problem.initial_state()] self.edges[self.problem.initial_state()] = dict() visited = set() #defining list for nodes, [node,g(n),h(n)+g(n)] nodes = [[start,0,0]] while nodes: self.max_nodes.append(len(visited) + len(nodes)) current_node = min(nodes, key = lambda k : k[2]) self.nodes_expanded_count += 1 visited.add(current_node[0]) if self.problem.is_goal_test(current_node[0]): self.print_path(current_node[0]) return current_node[0] self.nodes_count += len(list(set(self.problem.actions(current_node[0])))) for node in list(set(self.problem.actions(current_node[0])) - visited): cost = self.problem.edge_cost(current_node[0],node) self.insert(current_node[0],node,cost) self.parent[node] = current_node[0] current_cost = list(filter(lambda element: element[0] == current_node[0],nodes))[0][1] + cost nodes.append([node,current_cost,current_cost + self.problem.heuristic(node)]) nodes.remove(current_node) def A_Star_tree_search(self, start): self.__init__(self.problem) self.nodes = [self.problem.initial_state()] self.edges[self.problem.initial_state()] = dict() #defining list for nodes, [node,g(n),h(n)+g(n)] nodes = [[start, 0, 0]] while nodes: self.max_nodes.append(len(nodes)) current_node = min(nodes, key=lambda k: k[2]) self.nodes_expanded_count += 1 print_table(current_node) if self.problem.is_goal_test(current_node[0]): self.print_path(current_node[0]) return current_node[0] self.nodes_count += len(list(set(self.problem.actions(current_node[0])))) for node in list(set(self.problem.actions(current_node[0]))): cost = self.problem.edge_cost(current_node[0], node) self.insert(current_node[0], node, cost) self.parent[node] = current_node[0] current_cost = list(filter(lambda element: element[0] == current_node[0], nodes))[0][1] + cost nodes.append([node, current_cost, current_cost +self.problem.heuristic(node)]) nodes.remove(current_node)
d3443534caf691607f2d0668c0a89af07ff21e62
satyam-seth-learnings/ds_algo_learning
/Applied Course/2.Data Structure/2.Doubly Linked List/doubly_linked_list.py
3,708
4.03125
4
import sys class Node: def __init__(self,info,prev=None,next=None): self.info=info self.prev=prev self.next=next class LinkedList: def __init__(self): self.head=None def insert_at_beg(self,ele): new_node=Node(ele) if self.head == None: self.head=new_node else: new_node.next=self.head self.head.prev=new_node self.head=new_node def insert_at_end(self,ele): new_node=Node(ele) if self.head == None: self.head=new_node else: current=self.head while current.next != None: current=current.next current.next=new_node new_node.prev=current def insert_after_given_node(self,data,item): current=self.head while current is not None: if current.info==item: new_node=Node(data) new_node.prev=current new_node.next=current.next if current.next: current.next.prev=new_node current.next=new_node return current=current.next def delete(self,ele): # base case if self.head == None: print('List is empty.') return # if only one node is present if self.head.next == None: if self.head.info == ele: temp=self.head self.head=None temp=None return else: print('Element is not found in our list.') return # delete node between temp=self.head.next while temp.next != None: if temp.info == ele: temp.prev.next=temp.next temp.next.prev=temp.prev temp=None return temp=temp.next #delete last node if temp.info == ele: temp.prev.next=None temp=None return print("Element is not found in the list") def reverse(self): if self.head == None: return p1=self.head p2=p1.next p1.next=None p1.prev=p2 while p2 is not None: p2.prev=p2.next p2.next=p1 p1=p2 p2=p2.prev self.head=p1 print("List reversed\n") def display(self): if self.head == None: print('List is empty.') return current=self.head while current != None: print(current.info) current=current.next if __name__=='__main__': llist = LinkedList() while(1): print("1.Display") print("2.Insert new node at the beginning") print("3.Insert new node at the end") print("4.Insert new node after the given node") print("5.Delete node") print("6.Reverse list") print("7.Quit\n") print("Enter your choice : ") choice=int(input()) if(choice==1): llist.display() elif(choice==2): value=int(input()) llist.insert_at_beg(value) elif(choice==3): value=int(input()) llist.insert_at_end(value) elif(choice==4): print("enter the value : ") value=int(input()) print("Enter the element after which to insert : ") item=int(input()) llist.insert_after_given_node(value,item) elif(choice==5): value=int(input()) llist.delete(value) elif(choice==6): llist.reverse() else: sys.exit(0)
7466c79217cf1b4db24db6f856b946fa8a728bfa
nosoccus/Information-Security-Technologies
/RSA/encrypt.py
1,526
3.703125
4
from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP import base64 import time # Encryption function def encrypt(text, public_key): # Import the public key using PKCS1_OAEP rsa_key = RSA.importKey(public_key) rsa_key = PKCS1_OAEP.new(rsa_key) # Chunk size determines as the private key length used in bytes # and subtract 42 bytes(when using PKCS1_OAEP) chunk_size = 470 offset = 0 end_loop = True encrypted = bytes("", encoding='utf-8') while end_loop: chunk = text[offset:offset + chunk_size] # If chunk is less then the chunk size, then add padding(" "). # This indicates end of loop. if len(chunk) % chunk_size != 0: end_loop = False chunk += bytes(" ", encoding='utf-8') * (chunk_size - len(chunk)) # Append the encrypted chunk encrypted += rsa_key.encrypt(chunk) # Change offset(add chunk size) offset += chunk_size # Base 64 encode the encrypted file return base64.b64encode(encrypted) start = time.process_time() # Use the public key for encryption with open("public_key.pem", "rb") as f: public_key = f.read() # File to be encrypted with open("text.txt", "rb") as f: text_to_encrypt = f.read() encrypted_text = encrypt(text_to_encrypt, public_key) # Write the encrypted content to a file with open("encrypted_rsa.txt", "wb") as f: f.write(encrypted_text) enc_time = (time.process_time() - start) print(f"Time for encryption: {enc_time}")
cef020585093fe18871d9fcf8ae0b558ba9642e8
APSingh10/basic_python_code
/fibonaci.py
200
4
4
f1=0 f2=0 fibo=0 num=int(input("enter the numer of fibonaci series:")) for i in range(0,num+1): f2=f1+i #print(f2,end="") f1=f2 f2=i f2=f1+f2 #f2=i #f2=f1+f2 print(f2)
863823f626d32d760e2ae300a1dbd182075091f5
FelipePRodrigues/hackerrank-practice
/problem-solving/algorithms/bill_division/bill_division_solution.py
363
3.640625
4
# AVAILABLE AT https://www.hackerrank.com/challenges/bon-appetit/problem def bonAppetit(bill, itemNotEated, annaPart): newBillTotal = sum(bill) - bill[itemNotEated] eachPart = newBillTotal / 2 if eachPart == annaPart: message = 'Bon Appetit' else: message = str(int(annaPart - eachPart)) # print(message) return message
4e4cbd7948fee048b40d1d555294f3b5ca9bc84b
maxtiff/python_intro
/Coursera_HW/a2.py
4,148
4.28125
4
def get_length(dna): """ (str) -> int Return the length of the DNA sequence dna. >>> get_length('ATCGAT') 6 >>> get_length('ATCG') 4 """ if len(dna) > 0: for nucleotide in dna: if nucleotide in 'ATCG': return len(dna) else: return 'Error' else: return len(dna) def is_longer(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna1 is longer than DNA sequence dna2. >>> is_longer('ATCG', 'AT') True >>> is_longer('ATCG', 'ATCGGA') False """ if get_length(dna1) > get_length(dna2): return True else: return False def count_nucleotides(dna, nucleotide): """ (str, str) -> int Return the number of occurrences of nucleotide in the DNA sequence dna. >>> count_nucleotides('ATCGGC', 'G') 2 >>> count_nucleotides('ATCTA', 'G') 0 """ nuke_count = 0 if len(dna) > 0 and len(nucleotide) > 0: for letter in dna: if letter in nucleotide: nuke_count = nuke_count + 1 return nuke_count else: return nuke_count def contains_sequence(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna2 occurs in the DNA sequence dna1. >>> contains_sequence('ATCGGC', 'GG') True >>> contains_sequence('ATCGGC', 'GT') False """ if len(dna1) and len(dna2) > 0: if dna2 in dna1: return True else: return False else: return 'Error' def is_valid_sequence(dna): ''' (str) -> bool Return True if and only if the input is a valid DNA sequence (A, T, C, G). >>> is_valid_sequence('ATCG') True >>> is_valid_sequence('AATTCCGG') True >>> is_valid_sequence('aATC') False >>> is_valid_sequence('') True ''' valid = True if len(dna) > 0: for nucleotide in dna: if nucleotide not in 'ATCG': valid = False return valid return valid else: return valid def insert_sequence(dna1, dna2, int): ''' (str, str, int) -> str Inserts dna2 into dna1 at index int if and only if both dna inputs are valid and then returns the concatenated value. >>> insert_sequence('ATTG', 'AC', 2) 'ATTACG' >>> insert_sequence('','TGA',3) 'Error - Please provide a valid DNA sequence' >>> insert_sequence('AAGCT', 'TGA', 0) 'TGAAAGCT' >>> insert_sequence('AACCGT', 'TGCA', 7) 'Error - invalid index for interpolation to dna1' ''' sequence = '' if is_valid_sequence(dna1) and is_valid_sequence(dna2): if not int > len(dna1): sequence = dna1[:int] + dna2 + dna1[int:] return sequence else: return 'Error - invalid index for interpolation to dna1' else: return 'Error - Please provide a valid DNA sequence' def get_complement(nucleotide): '''(str) -> str Returns the complement of the Nucleotide nucleotide. Only 'A','T', 'C', and 'G' are valid inputs. >>>get_complement('A') 'T' >>>get_complement('G') 'C' ''' complement = '' for char in nucleotide: if char in 'ATCG': if char == 'A': complement = 'T' elif char == 'T': complement = 'A' elif char == 'C': complement = 'G' elif char == 'G': complement = 'C' if char == '' : complement return complement def get_complementary_sequence(dna): '''(str) -> str Returns the complement DNA sequence to string dna. Only 'A','T', 'C', and 'G' are valid inputs. >>>get_complementary_sequence('AT') 'TA' >>>get_complementary_sequence('ATCGGT') 'TAGCCA' ''' complement_sequence = '' for char in dna: complement_sequence = complement_sequence + get_complement(char) return complement_sequence
027bfbcc57ceab4fb6b6a21cf6bfa53d0305adc3
f-vdb/sudoku
/fvdb/sudokuLöser.py
2,595
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import logging # loglevel - comment out the next line and you will see loggings # logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) def check(x, y, wert): if(checkHorizontal(y, wert)): return 1 if(checkVertikal(x, wert)): return 1 if(checkBox(x, y, wert)): return 1 return 0 def checkVertikal(x, wert): for i in xrange(9): if(pitch[i][x] == wert): #logging.debug("nein V " + str(wert)) return 1 #print("ja V ", wert) return 0 def checkHorizontal(y, wert): for i in xrange(9): if(pitch[y][i] == wert): #print("nein H", wert) return 1 #print("ja H ", wert) return 0 def checkBox(x, y, wert): xBox = (int)(x / 3) * 3 yBox = (int)(y / 3) * 3 #print("checkBox x: ", x, y, xBox,yBox) #print("Wert: ", wert) for i in xrange(yBox, yBox+3): for j in xrange(xBox, xBox+3): if(pitch[i][j] == wert): #print("nein B ", wert, xBox, yBox) return 1 #print("ja B ", wert, xBox, yBox) return 0 def solve(x, y): if(x == 9): y += 1 x = 0 if(y == 9): return 1 if(pitch[y][x] > 0): return solve(x+1, y) for i in xrange(9+1): if(not(check(x, y, i))): pitch[y][x] = i #logging.debug(printPitch()) # nice debug if(solve(x+1, y)): global solution solution += 1 print("Loesung ", solution, "\n") printPitch() pitch[y][x] = 0 return 0 def usage(): print("usage ./sudoku.py name_der_sudoku_datei.txt") def printPitch(): for i in xrange(9): print("\n\t", end="") for j in xrange(9): print(pitch[i][j], " ", end='') print("\n") def slurpFileToPitch(filename): try: with open(filename) as f: logging.debug("file " + filename + " exists") for i in xrange(9): for j in xrange(9): c = f.read(1) if(c=='\n'): c = f.read(1) pitch[i].append(int(c)) except IOError: logging.debug("file " + filename + "does not exitst") if __name__ == "__main__": solution = 0 pitch = [[],[],[],[],[],[],[],[],[]] n = len(sys.argv) if n == 1 or n > 2: usage() exit() else: slurpFileToPitch(sys.argv[1]) printPitch() solve(0, 0)
e23e8720deb47adb8ffdfade5b879d2937308e32
xmu-ggx/leetcode
/94.py
377
3.546875
4
class Solution: def inorderTraversal(self, root): if root is None: return root res = [] stack = [] while stack or root: while root: stack.append(root) root = root.left node = stack.pop() res.append(node.val) root = node.right return res
abc816db3d1463c45cd3a80eb188ebef14a8d232
Terorras/pystuff
/prac12.py
444
3.921875
4
from sys import argv script, number, number2 = argv def function(arg1, arg2): print "Is %d greater than %d?" % (arg1, arg2) print arg1 > arg2 print "So that's the answer.\n" print function(2, 3) print function(5, 4) print function(6, 7) print function(int(raw_input('What\'s the first number you want to compare?')), int(raw_input('What\'s the second number you want to compare?'))) print function(int(number), int(number2))
d6d594f44c10da29eb00a17aaa28c9121e163279
davidzeng21/CUHKSZ-CSC1001
/Assignment1/q5.py
687
4.09375
4
while True: N = input("Enter a positive integer:") if N.isdigit(): N=int(N) prime_list = list() for digit in range(2, N): flag = True for i in range (2, int(digit**0.5 + 1)): if digit % i == 0: flag = False break if flag: prime_list.append(digit) print("The prime numbers smaller than", N, "include:") order = 0 for prime in prime_list: print(prime, end =" ") order += 1 if order % 8 == 0: print() break else: print("Please enter a positive integer")
483f8a7c04c37f7f68d85b7797afd80ad86ff47a
ayesha786012/irt_parameter_estimation-master
/doc/QuickTutorial.py
6,588
3.65625
4
#!/usr/bin/env python # coding: utf-8 # # Tutorial for irt_parameter_estimation # Here, we show a quick sample usage of the MLE routines in irt_parameter_estimation. # # First of all, here is a sample item characteristic curve (ICC), a logistic function given item paramters: # * a=10 (discimination) # * b=0.6 (difficulty) # * c=0.25 (guessing parameter) # # This could be a multiple choice question that: # * has four equally interesting choices # * is slightly harder than average # * discriminates between novices and experts very well # # This explains the likelihood that a user at any given ability level (x axis) will answer the question correctly. # In[1]: import numpy as np import irt_parameter_estimation import matplotlib.pyplot as plt np.random.seed(2) # Chosen so 3PL will converge below # Sample question score curve a = 10 b = 0.6 c = 0.25 theta = np.arange(0, 1, 0.01) prob_correct = irt_parameter_estimation.logistic3PLabc(a, b, c, theta) plt.plot(theta, prob_correct) plt.xlabel("user ability") plt.ylabel("probability of correctly answering") _ = plt.title(f"Sample ICC a={a}, b={b}, c={c}") # Next, we create some sample user abilities with np.random.normal. # # These users have mean ability of 0.5 with std 0.2. # In[2]: mean_user_ability = 0.5 std_user_ability = 0.2 n_users = 400 user_abilities = np.random.normal(mean_user_ability, std_user_ability, n_users) plt.hist(user_abilities) plt.xlabel("user ability") plt.ylabel("number of users") _ = plt.title(f"Histogram of sample user abilities (mean=0.5, std=0.2)") # Next, we sample the ICC to generate the probability each user will answer the question correctly and draw a random variable to decide whether each user gets the question right. # # We define bins of size 0.1 and will use them below as well. # # The plot shows the correct and incorrect responses binned by user ability level in green and red respectively. # In[3]: user_probability_correct = irt_parameter_estimation.logistic3PLabc( a, b, c, user_abilities, ) user_results = np.random.rand(n_users) < user_probability_correct bins = np.arange(0, 1.1, 0.1) correct_users = user_abilities[user_results] incorrect_users = user_abilities[np.logical_not(user_results)] plt.hist(correct_users, bins=bins, alpha=0.6, color="green", label="correct") plt.hist(incorrect_users, bins=bins, alpha=0.6, color="red", label="incorrect") plt.legend() plt.xlabel("user ability") plt.ylabel("number of responses") _ = plt.title("Histogram of correct and incorect responses") # Next, we create the binned data more efficiently using numpy. # # The MLE routines need the correct responses and total responses binned by ability (*r* and *f* in Baker's terminology). # # There are fewer total responses (f) on the extreme ends because there are fewer total users at those levels of ability. # In[4]: correct_binned = np.bincount(np.digitize(correct_users, bins[:-1]), minlength=11) total_binned = np.bincount(np.digitize(user_abilities, bins[:-1]), minlength=11) plt.plot(bins, correct_binned, 'go', label='correct') plt.plot(bins, total_binned, 'ko', label='total') plt.legend() plt.xlabel("user ability") plt.ylabel("number of responses") _ = plt.title("Correct and total user ability counts per bin") # We can visualize the reconstructed ICC by plotting the correct reponses divided by the total responses (r / f). # In[5]: measured_prob_correct = correct_binned / total_binned plt.plot(bins, measured_prob_correct, '.') plt.xlabel("user ability") plt.ylabel("probability correct (measured)") _ = plt.title("Ratio of correct responses by ability level") # Now we are ready to do the maximum likelihood estimation (MLE) to reconstruct the item parameters (in this case a, b, and c). # # First, we do the 2 parameter fits. # # We can user either the zlc or abc module to do the fits. abc will do the fits directly and zlc will do the conversion under the hood (see [the pdf](https://github.com/pluralsight/irt_parameter_estimation/blob/master/doc/zlc-irt-formulation.pdf) to understand the differences). # # Here we show that we can reconstruct the original parameters pretty closely, but the 2PL does not fit the guessing parameter so it will predict the question is easier and less discriminating than than it really is. # # Both methods come up with roughly a=6 (instead of 10) and b=0.585 (instead of 0.6). # In[6]: # 2PL fits, using different formulations input_a, input_b, input_c = 10, 0.5, 0 a, b, _, chi2, success = irt_parameter_estimation.abc.mle_abc(2, bins, correct_binned, total_binned, input_a, input_b, input_c) print(f"2PL fit (a/b formulation): a={a}, b={b}, error={chi2}, success? {success}") a, b, _, chi2, success = irt_parameter_estimation.zlc.mle_abc(2, bins, correct_binned, total_binned, input_a, input_b, input_c) print(f"2PL fit (zeta/lambda formulation): a={a}, b={b}, error={chi2}, success? {success}") prob_correct_2pl_fit = irt_parameter_estimation.logistic3PLabc(a, b, 0, theta) # for plotting later # In[7]: # 3PL fits (will converge given close-ish input parameters) input_a, input_b, input_c = 5, 0.5, 0.3 a, b, c, chi2, success = irt_parameter_estimation.abc.mle_abc(3, bins, correct_binned, total_binned, input_a, input_b, input_c) print(f"3PL fit (a/b/c formulation): a={a}, b={b}, c={c}, error={chi2}, success? {success}") a, b, c, chi2, success = irt_parameter_estimation.zlc.mle_abc(3, bins, correct_binned, total_binned, input_a, input_b, input_c) print(f"3PL fit (zeta/lambda/c formulation): a={a}, b={b}, c={c}, error={chi2}, success? {success}") prob_correct_3pl_fit = irt_parameter_estimation.logistic3PLabc(a, b, c, theta) # for plotting later # In[8]: plt.plot(bins, measured_prob_correct, '.', label="measured") plt.plot(theta, prob_correct, 'b', label="true") plt.plot(theta, prob_correct_2pl_fit, 'c', label="2PL") plt.plot(theta, prob_correct_3pl_fit, 'm', label="3PL") plt.legend() plt.xlabel("user ability") plt.ylabel("probability correct") _ = plt.title("Comparison of various ICC's") # The 3PL fits in particular are quite finnicky, because the function being fit is not very smooth in paramter space (some dimensions are much steeper than others, local minima, etc). # # In real-world situations, we recommend running multiple trials with different input parameters to find good convergence (low chi2, no convergence errors). # # There are newer methods for performing this type of fit, but we have not had a change to evaluate them yet: # https://journal.r-project.org/archive/2019/RJ-2019-003/RJ-2019-003.pdf # In[ ]:
ad3617151b61159130142c5d42597482cbecb88f
magik2art/DZ_5_Mamaev_Pavel
/task5.py
766
3.9375
4
# К сожалению в этот раз не успел сделать и сдать домашнее задание полностью и вовремя, сдаю за 10 минут до того как закроют возможность сдать дз # Просьба дать время еще на сдачу ДЗ # result = [23, 1, 3, 10, 4, 11] src = [2, 2, 2, 7, 23, 1, 44, 44, 3, 2, 10, 7, 4, 11] result = [] result_all = list(set(src)) print(result_all) # [1, 2, 3, 4, 7, 10, 11, 44, 23] i = 0 while i > len(result_all): x = result_all[i] i_ = 0 while i_ > len(src): result_ = 0 y = src[i_] if x == y: result_ += 1 if result_ == 0: result.append(result_all[i]) print(result)
d17e73735b3664cbcda309ec06e1d1f96008cbc3
wklesss/python-study
/0.code/python-100-days/day07/list.py
1,510
3.90625
4
import sys ly1 = ('*' *80) list1 = [1, 3, 5, 7, 100] print(list1) # [1, 3, 5, 7, 100] list2 = ['hello'] * 3 print(list2) print(len(list1)) print(list1[0]) print(list1[4]) print(list1[-1]) print(list1[-3]) list1[2] =300 print(list1) for index in range(len(list1)): print(list1[index]) for elem in list1: print(elem) for index, elem in enumerate(list1): print(index, elem) # 添加元素 list1.append(200) list1.insert(1, 400) list1 += [1000, 2000] print(list1) print(len(list1)) if 3 in list1: list1.remove(3) if 1234 in list1: list.remove(1234) print(list1) list1.pop(0) list1.pop(len(list1) - 1) print(list1) list1.clear() print(list1) # 切片操作 fruits = ['grape', 'apple', 'strawberry', 'waxberry'] fruits += ['pitaya', 'pear', 'mango'] fruits2 = fruits[1:4] print(fruits2) fruits3 = fruits[:] print(fruits3) fruits4 = fruits[-3:-1] print(fruits4) fruits5 = fruits[::-1] print(fruits5) # 列表的排序 list3 = ['orange', 'apple', 'zoo', 'internationalization', 'blueberry'] list4 = sorted(list1) list5 = sorted(list3, reverse=True) list6 = sorted(list3, key=len) print(list3) print(list4) print(list5) print(list6) list3.sort(reverse=True) print(list3) print(ly1) #生成式和生成器 f1 = [x for x in range(1, 10)] print(f1) f2 = [x + y for x in 'ABCDE' for y in '1234567'] print(f2) f3 = [x ** 2 for x in range(1, 1000)] print(sys.getsizeof(f3)) print(f3) f4 = (x ** 2 for x in range(1, 1000)) print(sys.getsizeof(f4)) print(f4) for val in f4: print(val)
3ba7a3b275195c8e5808d2952605f461c53c13fb
Aadeshkale/Python-devlopment
/1.Basic/6.String.py
973
4
4
# Strings in python s="Sachin" s1="Mane" print(s) l = len(s) print("length of string is :",l) print("Acessing single element:",s[0]) # Strings concatanation con=s+s1 print(con) print("length",len(con)) s+" Shivam" print(s) # polling concept i.e non mutable / immutable # string spilt sp=s.split('c') print(sp) # string opration print("Start to end:",s[0:]) print("Start to end:",s[1:4]) print("Start to end with dtep count 1:",s[1:4:1])# default step count print("Start to end with dtep count 2:",s[1:4:2])# step count = 2 print("end to Start:",s[4:1]) # 4+1= 5 hence it is not reaching at end print("Start to end with dtep count -1:",s[1:4:-1])# step count #reverse of String rev=s[::-1] print("reverse:",rev) # String join print("String join:","-".join(sp)) # string membership s in "S" print("S" in s) print("Sa" in sp) print("z" not in s) print("S" not in s) # find print(s.find("Sa")) print(s.find("xv")) # index print(s.index("Sa")) print(s.index("xv"))
6d481bb764d3cf7306539ecaf5b10bdf001d2871
Nisar-1234/Data-structures-and-algorithms-1
/Greedy Programming/Choose and Swap.py
1,003
3.765625
4
""" swap two chars in a string such that we get lexicographically smaller string input = "abcabcpop" output = "abcabcopo" """ class Solution: def LexicographicallyMinimum(self, str): temp = sorted(str) ch1 = '$' ch2 = '$' flag = False for i in range(len(str)): # print("============") k = str.index(temp[i]) # print("i =",i,"temp[i] =",temp[i],"k =",k) for j in range(k): if str[j] > temp[i]: # print(str[j],"is greator than",temp[i]) ch1 = str[j] ch2 = temp[i] flag = True break if flag == True: break res = "" for char in str: if char == ch1: res += ch2 elif char == ch2: res += ch1 else: res += char return res
d2cf078470439ab82719bb7128789bc02adfe372
brianbbsu/program
/code archive/hackercup/2019/Q/pC.py
271
3.609375
4
#!/usr/bin/env python3 T = int(input()) for kz in range(T): print("Case #{}: ".format(kz + 1), end="") s = input() if eval(s.replace("x", "0").replace("X", "1")) != eval(s.replace("x", "1").replace("X", "0")): print("1") else: print("0")
ebe2af1a08476bd5f4e88894a426410b2b81857b
Korabliov/python-labs
/Starter/002_Examples/09-comparisons.py
690
4.4375
4
a = 2 b = 5 print(a < b) # меньше print(b > 3) # больше print(a <= 2) # меньше или равно print(b >= 7) # больше или равно print(a < 3 < b) # двойное сравнение print(a == b) # равенство print(a != b) # неравенство print(a is b) # идентичность объектов в памяти print(a is not b) # a и b – разные объекты (хотя значения их могуть быть равны) string = "some string" second_string = string third_string = input('Введите строку: ') print(string is second_string) print(string is third_string)
0403310f48049ad0bed5b8fc937169d23986853e
GetPastTheMonkey/advent-of-code
/aoc2016/day17/day17_common.py
1,268
3.5625
4
from hashlib import md5 from queue import Queue from typing import Union PASSWORD = "veumntbg" ROWS, COLS = 4, 4 DIRECTIONS = [ ("U", -1, 0), ("D", 1, 0), ("L", 0, -1), ("R", 0, 1), ] def day17_solve(part_1: bool) -> Union[str, int]: queue = Queue() queue.put((0, 0, "")) longest_path_len = 0 while not queue.empty(): pos_x, pos_y, path = queue.get() if pos_x == ROWS - 1 and pos_y == COLS - 1: if part_1: return path longest_path_len = max(len(path), longest_path_len) continue for idx, char in enumerate(md5((PASSWORD + path).encode()).hexdigest()[:4]): if char.isdigit() or char == "a": # The door in this direction is closed continue next_step, dx, dy = DIRECTIONS[idx] next_x = pos_x + dx next_y = pos_y + dy if not (0 <= next_x < ROWS): # The move would be outside the grid in the X axis continue if not (0 <= next_y < COLS): # The move would be outside the grid in the Y axis continue queue.put((next_x, next_y, path + next_step)) return longest_path_len
838880d9f6778dffdc861694af7ed84769a26368
VittorioYan/Leetcode-Python
/257.py
938
3.921875
4
from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: result = [] if not root: return result def helper(node:TreeNode, path:str): path += "->" + str(node.val) if node.right is None and node.left is None: result.append(path[2:]) return if node.right is not None: helper(node.right, path) if node.left is not None: helper(node.left, path) helper(root, "") return result a = Solution() in_para1 = [1, 2, 3, 1] in_para2 = 9 t1 = TreeNode(1) t2 = TreeNode(2) t3 = TreeNode(3) t4 = TreeNode(5) t1.left= t2 t1.right = t3 t2.right = t4 resu = a.binaryTreePaths(None) print(resu)
ffd3ee9329913defe03e0dedfb48ad488df6d664
oluiscabral/estrutura-de-dados
/trab05/main.py
333
3.78125
4
from balancedtree import BalancedTree def main(): tree = BalancedTree() n = int(input()) for _ in range(n): value = int(input()) tree.insert(value) print(*tree.preordered(), sep=" ") print(*tree.ordered(), sep=" ") print(*tree.postordered(), sep=" ") if __name__ == '__main__': main()
81e8d1089ce4066553d76f4bcfd6a2bc0ed1da27
GustavoBeckhauserSouza/apex-ensino-202103
/aula-20210324/prog03.py
292
3.96875
4
# continue -> Volta ao início da execução do laço for, para o proximo # item if __name__ == '__main__': lista_de_numeros = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] for numero in lista_de_numeros: if numero % 2 == 1: continue print(numero ** 2)
190693cd0e5f174c9eaa80ade6f3613c2bc3cb39
jose-rgb/-ifpi-ads-algoritmos2020
/Exercicios_de_condicionais/exercicio26_lista2a.py
922
3.96875
4
def main(): l1 = int(input('Digite o primeiro lado do triângulo: ')) l2 = int(input('Digite o segundo lado do triângulo: ')) l3 = int(input('Digite o terceiro lado do triângulo: ')) hipotenusa = calculo(l1, l2, l3) catetos = calculo2(l1, l2, l3) print(f'À hipotenusa é o {hipotenusa},portanto, {catetos} são os catetos.') def calculo(l1, l2, l3): if l1 > l2 >= l3 or l1 > l3 >= l2: return 'primeiro lado' if l2 > l1 >= l3 or l2 > l3 >= l1 : return 'segundo lado' if l3 > l2 >= l1 or l3 > l1 >= l2: return 'terceiro lado' def calculo2(l1, l2, l3): if l1 > l2 >= l3 or l1 > l3 >= l2: return 'o segundo é o terceiro lado' if l2 > l1 >= l3 or l2 > l3 >= l1 : return 'o primeiro é o terceiro lado' if l3 > l2 >= l1 or l3 > l1 >= l2: return 'o primeiro é o segundo lado' main()
9fdcd5460d8538e2a12d1d2ba36d882ca28454b8
SanthoshKR93/Python_Anandology_Solutions
/Working_with_Data/problem_15_unique_using_sets.py
194
3.625
4
# Reimplement the unique function implemented in the earlier examples using sets. def unique2(x): x = list(set(x)) print(x) unique2([1,2,1,1,2,1,3]) unique2(['hello','Hello','ad','ad'])
6e8637a98ac5e58d84ec6fec9c6a345c3579a3de
Abrahamyan-R/algorithms-bucket
/data structers/stack(array).py
422
3.828125
4
class Stack: def __init__(self, size): self.items = [] self.size = size self.top = 0 def push(self, data): if self.top == self.size: raise ValueError("Stack is full") self.items.append(data) self.top += 1 def pop(self): if self.top == 0: raise ValueError("Stack is empty") self.top -= 1 return self.items.pop()
6c2677a4a1f5cfbd07f9cab683db57fbc06195f5
maecchi/PE
/pe109.py
893
3.703125
4
#!/usr/bin/env python #-*- coding: utf-8 -*- # # pe109.py - Project Euler # # ダブルの点数を除いた点数から取りうる全てのポイントを並べて前から取っていく from itertools import * NUM = 20 LIMIT = 100 total = 0 double_score_list = range(2, 2*(NUM+1), 2) + [50] all_score_list = range(1, NUM+1) + [25] + double_score_list + range(3, 3*(NUM+1), 3) # 残りの試行回数と使用したスコアリスト要素番号を引数として # スコアを生成する def generateScore(c, k0): if c == 1: # 最後の試行のとき for pt in double_score_list: yield pt else : # それ以外の試行回数のとき for k in xrange(k0, len(all_score_list)): pt0 = all_score_list[k] for pt in generateScore(c-1, k): yield pt + pt0 for c in range(1, 4): total += sum(1 for pt in ifilter(lambda x: x < LIMIT, generateScore(c, 0))) print total
178c47533c2fd42b2e43b2d6859a2e749bc8195b
johnnyhicks95/parkinson-test-python-tkinter
/1-Home.py
2,143
3.5
4
from tkinter import * Home = Tk() #window size # Home.geometry("950x650") Home.title('Home screen') # label1 = Label(Home, width='20', height='3', bg='red', text='Hello') # label2 = Label(Home, width='20', height='3', bg='green', text='world') # label1.grid(row=0, column = 1) # label2.grid(row=0, column = 6) frame1 =Frame(Home) frame1.grid(row=0, column=0, padx=(50,50), pady=(20,30) ) frame1.columnconfigure(0 , weight=1) frame1.rowconfigure(0 , weight=1) # nombre de la universidad nameUta = Label(frame1, text='Universidad Técnica de Ambato', bg='#5cb85c', width=40,height=2) nameUta.grid(column=2 , row=1) appName = Label(frame1, text='Test de Parkinson', bg='#3EB489',width=30) appName.grid(column=2 , row=2) description= Label(frame1, text=''' Bienvenido! Este es el proyecto de final de curso de Programacion orientada a objetos Qué es la enfermedad del "Parkinson"? Es un trastorno del sistema nervioso central que afecta el movimiento y suele ocasionar temblores. Qué hace este programa? Esta aplica un test para dar una probabilidad de si usted podría padecer de la enfermedad de Parkinson.''', bg = '#f9f9f9', pady=10,bd=1, anchor=W ) description.grid(column=2, row= 3) authorsNames = Label(frame1, text='''Autores: -> Sr. Guamanquispe Johnny -> Srta. López Cristina FISEI-Software © 2020''', bg = '#f9f9f9', relief=SUNKEN, pady=10,bd=1, anchor=W ) authorsNames.grid(column=0, row=4) comments =Label(frame1, text='''******* Indicaciones para *********** ->Empezar el test, click en "Continuar" ->Terminar el programa, click en "Salir" ''', bg = '#f9f9f9', relief=SUNKEN, pady=10,bd=1, anchor=W ) comments.grid(column=3, row=4) # input for name? # userName = '' # inputUserName = Entry( frame1, width=20, textvariable= userName ) # inputUserName.grid(column=1, row=5) # Buttons continueBut = Button(frame1, text='Continuar', bg='#428bca', relief=RAISED, width=14, height=1) continueBut.grid(column=2 , row=5) exitBut = Button(frame1, text='Salir', bg="#d9534f",fg="#fff", command=Home.quit, width=14, height=1) exitBut.grid(column=3, row=5) Home.mainloop()
ba3c17232dde270dcdb0dd2a9339f0e73eda403d
AB036/remote_robot
/rasp/rasbpberry_package/scripts/Robot.py
2,104
3.90625
4
import Motor import time class Robot: """This class controls the motors of the robot in function of the command""" def __init__(self, left_motor, right_motor, ros_node): if not isinstance(left_motor, Motor.Motor): raise ValueError("motor should be Motor Objects") if not isinstance(right_motor, Motor.Motor): raise ValueError("motor should be Motor Objects") self.__left_motor = left_motor self.__right_motor = right_motor self.__ros_node = ros_node self.__straight_speed = 95.0 # Speed for straight movement. Between 0 and 99 self.__turning_speed = 95.0 # Speed for turning. Between 0 and 99 def process_command(self, command): """Process the command : should be called frequently (10Hz)""" if time.time() - self.__ros_node.last_time < 0.5: # After one second, robot stops, waiting for a new command if command == "up": print("Move up") self.__move_forward() elif command == "down": self.__move_backward() elif command == "left": self.__turn_left() elif command == "right": self.__turn_right() elif command == "stop": self.__stop() else: self.__stop() else: self.__stop() def __move_forward(self): self.__left_motor.move_speed(self.__straight_speed) self.__right_motor.move_speed(-self.__straight_speed) def __move_backward(self): self.__left_motor.move_speed(-self.__straight_speed) self.__right_motor.move_speed(self.__straight_speed) def __turn_left(self): self.__left_motor.move_speed(self.__turning_speed) self.__right_motor.move_speed(self.__turning_speed) def __turn_right(self): self.__left_motor.move_speed(-self.__turning_speed) self.__right_motor.move_speed(-self.__turning_speed) def __stop(self): self.__left_motor.move_speed(0.0) self.__right_motor.move_speed(0.0)
801aa444ae300dbc189bbed7bad6bdd7c2806a46
Crispy96/COIN_API
/criptovalue/views.py
1,669
3.53125
4
from tkinter import * #usado para crear interfaces gráficas from tkinter import ttk from criptovalue._init_ import MONEDAS class CriptoValueView(): def pedir(self): de = input("Moneda de origen: ") a = input("Moneda de destino: ") return de, a def muestra(self, origen, destino, valor): print(f"1 {origen} vale {valor} {destino}") def funcion_del_boton(): print("Click") #frame(parent,option) es como un contenedor class Exchanger(ttk.Frame): def __init__(self, parent, funcion_click_del_controlador): super().__init__(parent, height=300, width=430) self.grid_propagate(0) #sirve para que el contenedor se adapte al tamaño y no al contenido self.desde_valor = StringVar() self.desde = ttk.Combobox(self, values=MONEDAS, textvariable = self.desde_valor) self.desde.grid(column=0, row=0) self.hasta_valor = StringVar() #monedas para escoger self.hasta = ttk.Combobox(self, values=MONEDAS, textvariable = self.hasta_valor) self.hasta.grid(column=1, row=0) self.valor = ttk.Label(self, anchor=CENTER, text="0.0") #texto self.valor.grid(column=0, row=1, columnspan=2) self.calcular = ttk.Button(self, text="Calcular", command=funcion_click_del_controlador) #boton, command llama a un paramatro self.calcular.grid(column=1, row=2) def moneda_desde(self): return self.desde_valor.get()[:3] #le pido que me coja el texto hasta el valor que queramos def moneda_hasta(self): return self.hasta_valor.get()[:3] def set_valor(self, texto): self.valor.config(text=texto)
033982803269a8a3f5051c2bc3a90a0029406709
komerela/twitterbot
/user.py
624
3.5625
4
#!/usr/bin/python3 """ User class """ class User: """ Documentation """ def __init__(self): """ Documentation """ self.__email = 0 @property def email(self): """ Getter function """ print("getter method called") return self.__email @email.setter def email(self, email): """ Setter Function """ if type(email) is not str: raise TypeError("email must be a string") print("setter method called") self.__email = email if __name__ == "__main__": u = User() u.email = "john@snow.com" print(u.email)
c09e5e0dbdc0f6a769c3fc5697e49174ba8d685c
Josh7GAS/Oficina
/Python/listC.py
584
3.9375
4
#create 3 list with the same size and the values # of the third should be the values of the first index should be less than the second firstList = [] secondList = [] thirdList = [] listRange = 2 print("Give me 20 numbers") for count in range(listRange): print("Give me a number ") firstList.append(input()) secondList.append(int(firstList[count])*2) thirdList.append(int(firstList[count])-int(secondList[count])) print("The First List is: \n" + str(firstList) + "\n The Second List is:\n" + str(secondList) + "\n The thirdh List is:\n" + str(thirdList) )
f570f1a855ad589562e83e1017e0c00945de648e
shuke1995/Final_Project
/Air Pollution.py
2,683
3.59375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import numpy as np # In[2]: def read_indata(path): ''' :param path: a string of path saved the dataset :return: pandas datarame ''' data = pd.read_csv(path) return data ## generate new column year for every data def generate_year_month(df, colname): ''' :param df: dataframe we want to add column year and month :param colname: a stirng column name in the dataframe saved the dateandtime :return: dataframe after adding the column ''' df['year'] = pd.DatetimeIndex(df[colname]).year df['month'] = pd.DatetimeIndex(df[colname]).month #df['indextype'] = str(string) return df # In[5]: city_attributes = read_indata('./historical-hourly-weather-data/city_attributes.csv') airpollution = read_indata('./pollution_us_2000_2016.csv') #extract columns that need to analyze airpollution = airpollution[['City', 'Date Local', 'NO2 Mean','NO2 AQI', 'O3 Mean','O3 AQI','SO2 Mean','SO2 AQI','CO Mean','CO AQI']] airpollution.head() # In[7]: #generate year and month airpollution = generate_year_month(airpollution, 'Date Local') airpollution.head() # In[39]: def city_groupby(df, colname, city_name): ''' :param df: dataframe we want to divide base on city name :param colname: the column name in the dataframe saved the city name :param city_name: the specific city name :return: dataframe after filter city and year from 2012 to 2018, group by year and month ''' df = df[(df[colname]==city_name) & (df.year>=2012) & (df.year<2018)] df = df.groupby(['year','month']).agg({'mean'}) return df # In[86]: Chicago_airpollution = city_groupby(airpollution, 'City', 'Chicago') Chicago_airpollution.head() airpollution[(airpollution['City']=='Chicago')] #NYC_airpollution = city_groupby(airpollution, 'City', 'New York') #NYC_airpollution.head() #LA_airpollution = city_groupby(airpollution, 'City', 'Los Angeles') #LA_airpollution.head() # In[35]: chicago_crime = read_indata('./Chicago_crime_2012-2017.csv') chicago_crime.head() ## count chicago crime #chi_crime_per_month = chicago_crime[['ID', 'year', 'month']].groupby(['year', 'month']).size() # In[36]: generate_year_month(chicago_crime, 'Date').head() # In[66]: chicago_crime = chicago_crime[(chicago_crime.year>=2012) & (chicago_crime.year<2018)] chi_crime_per_month = chicago_crime[['ID', 'year', 'month']].groupby(['year', 'month']).count().rename(columns={'ID':'count'}) chi_crime_per_month.head() # In[75]: pd.merge(Chicago_airpollution, chi_crime_per_month,on=['year','month']) # In[76]: Chicago_airpollution # In[ ]:
0fdede89eccd2567ebe986ba21d5939b604df3f3
Abhi4899/data-structures-and-algorithms
/python practice/maxElement.py
212
3.703125
4
def maximum(lst): if len(lst)==2: return lst[0] if lst[0]>=lst[1] else lst[1] submax=maximum(lst[1:]) return lst[0] if lst[0]>submax else submax print(maximum([2,7,21,9,100]))
529f3a1c9bdba276596fe28de77f48835e8295f8
jeshc/CYPJesusHC
/proyecto/equipo15/PS2_17.py
687
3.796875
4
opcion = int(input("--Opciones-- \n1. Pulgadas a milimetros \n2. Yardas a metros \n3. Millas a kilometros \n" "Ingrese la opcion que necesite,'1, 2, 3':")) if opcion == 1: pulgadas = float(input("Ingrese las pulgadas:")) milimetros = pulgadas * 25.40 print(f"{pulgadas} pulgadas equivalen a {milimetros} milimetros.") elif opcion == 2: yardas = float(input("Ingrese las yardas:")) metros = yardas * 0.9144 print(f" {yardas} yardas es igual a {metros} metros ") elif opcion == 3: millas = float(input("Ingrese las millas:")) kilometros = millas * 1.6093 print(f" {millas} millas es igual a {kilometros} kilometros") print("Fin del programa! :D")
52a88167785bcd83138d0d41364784948638ef85
guanguanboy/TestPytorch
/list_comprehension.py
373
4.15625
4
#list comprehension: # 列表推导式,列表解析式 nums = [0, 1, 2, 3, 4] squares = [] for x in nums: squares.append(x ** 2) print(squares) #使用列表推导式完成上述功能如下: squares = [x ** 2 for x in nums] print(squares) #list comprehensions can also contain conditions: even_squares = [ x ** 2 for x in nums if x % 2 == 0] print(even_squares)
653045271b468415030da6c9fe7533ba5337c33d
wjosew1984/python
/ejerc17.py
236
3.71875
4
e=0 a=1 cant=int(input("ingrese la cantidad de alumnos: ")) while cant>=a: edad=int(input("ingrese la edad del alumno: ")) print(a) a=a+1 e=edad+e promedio=e/cant print("la edad promedio es de: ",promedio)
eae64dadc492af69280c13af950bd17175920520
MeetGandhi/Computing
/lb3/digits.py
74
3.703125
4
a=input("a:") n=0 while a!=0: a=a/10 n=n+1 print n,"digits"
485f774b1d07b641c03779c2a2fa275078c5496d
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Sets/program-2.py
1,179
4.25
4
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Iterates over sets. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : December 20, 2019 # # # ############################################################################################ from random import randint def random_set_data(low: int, high: int, size: int) -> set: if size < 0: raise ValueError(f"Invalid new set size ({size})") return set([randint(low, high) for _ in range(size)]) def print_set_data(main_set: set) -> None: for (ind, val) in enumerate(main_set): print(f'#{ind+1} -> {val}') if __name__ == "__main__": new_set = random_set_data(low=0, high=10, size=15) print(f'New set data: {new_set}') print('-' * 40) print_set_data(main_set=new_set)
9f4a666a218985e40819aeada37ee2aae1f27a72
Carolusian/leetcode
/p3-longest-substring-without-repeating-characters.py
1,024
4.1875
4
""" 3. Longest Substring Without Repeating Characters Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. """ def is_unique(s: str) -> bool: return len(set(s)) == len(s) def lengthOfLongestSubstring(s: str) -> int: i, j, longest = 0, 0, 0 while j <= len(s): substring = s[i:j] if is_unique(substring): longest = len(substring) if len(substring) > longest else longest j += 1 else: i += 1 return longest print(lengthOfLongestSubstring('pwwkew')) print(lengthOfLongestSubstring('au')) print(lengthOfLongestSubstring(' '))
679e5e6734b9f3fa577e914c7b6ca3655dfc3884
StefanoskiZoran/Python-Learning
/Practise provided by Ben/Clock Calculator by Me.py
1,210
4.125
4
""" Request the amount of seconds via keyboard, turn the seconds into months/days/years/decades etc. """ def main(): seconds_request = int(input(f'Please input your desired seconds: ')) minute_result = 0 hour_result = 0 day_result = 0 month_result = 0 year_result = 0 decade_result = 0 century_result = 0 millennia_result = 0 seconds = seconds_request % 60 minute_result = seconds_request / 60 minute = minute_result % 60 hour_result = minute_result / 60 hour = hour_result % 60 day_result = hour_result / 24 day = day_result % 60 week_result = day_result / 7 week = week_result % 7 month_result = day_result / 30 month = month_result % 30 year_result = month_result / 12 year = year_result % 12 decade_result = year_result / 10 decade = decade_result % 10 century_result = decade_result / 10 century = century_result % 10 millennia_result = century_result / 10 millennia = millennia_result % 10 print(f'{millennia:02.0f}:{century:02.0f}:{decade:02.0f}:{year:02.0f}:{month:02.0f}:{week:02.0f}:{day:02.0f}:{hour:02.0f}:{minute:02.0f}:{seconds:02.0f}') if __name__ == '__main__': main()
747e4bfa705c7df2ad21ca56ab88c8cee2a259ee
liuweilin17/algorithm
/leetcode/377.py
942
3.765625
4
########################################### # Let's Have Some Fun # File Name: 377.py # Author: Weilin Liu # Mail: liuweilin17@qq.com # Created Time: Sat Feb 9 16:56:42 2019 ########################################### #coding=utf-8 #!/usr/bin/python #377. Combination Sum IV # when backtrack is of great cost, take dp into consideration # The reason why dp is more efficient is that d memorizes the combinations of given sum, # while recursive method may calculate the combinations of given sum mulitple times. # For example, after [1,1] and [2], we have to calculte combinations of target-2 twice. class Solution: def combinationSum4(self, nums: 'List[int]', target: 'int') -> 'int': # d[i], the number of combinations with sum of i d = [0] * (target+1) d[0] = 1 for i in range(1, target+1): for num in nums: if num <= i: d[i] += d[i-num] return d[target]
f894782699e03aee5608539fbdc9baf901902d3c
sterbinsky/APSpyLecture5
/lecture5_lib.py
3,810
3.75
4
''' library of functions used in APS 2016 Python lecture 5 .. autosummary:: peak_position center_of_mass fwhm ''' def _get_peak_index(y): ''' report the index of the first point with maximum in y[i] :param [float] y: array (list of float) of values :return int: index of y ''' peak = max(y) # advanced homework # TODO: what if more than one point has the maximum value? # answer: this returns the index of the first occurrence of the value return list(y).index(peak) def peak_position(x, y): ''' report the x value of the maximum in y(x) :param [float] x: array of ordinates :param [float] y: array of abcissae :return float: peak position x & y must have the same length ''' # homework # TODO: raise IndexError exception if x & y arrays (lists) do not have same length x[len(y)-1] y[len(x)-1] # TODO: raise IndexError exception if x or y array (list) have zero length # solution to Q1 works for this too position = _get_peak_index(y) return x[position] def center_of_mass(x, y): ''' report the center of mass of y(x) :param [float] x: array (list of float) of ordinates :param [float] y: array (list of float) of abcissae :return float: center of mass The equation of the center of mass of :math:`y(x)`, .. math:: C ={ \int_{-\infty}^{-\infty}{x \\ y \\ dx} \over \int_{-\infty}^{-\infty}{y \\ dx}} For a discrete set of :math:`n` ordered pairs of points, writing the math with the first point indicated by subscript *zero* as in :math:`(x_0, y_0)`, .. math:: C = {\sum_{i=1}^{i=n-1}(\\bar x \\ \\bar y \\ \Delta x) \over \sum_{i=1}^{i=n}(\\bar y \\ \Delta x)} where :math:`\Delta x = x_i - x_{i-1}`, :math:`\\bar{x} = (x_i + x_{i-1})/2`, and :math:`\\bar{y} = (y_i + y_{i-1})/2`. x & y must have the same length ''' # advanced homework # TODO: first subtract a background area_x_y_dy = 0 area_y_dy = 0 for i in range(1, len(y)): dx = x[i] - x[i-1] x_mean = (x[i] + x[i-1])/2 y_mean = (y[i] + y[i-1])/2 area_x_y_dy += x_mean * y_mean * dx area_y_dy += y_mean * dx # homework # - Describe what happens when area_y_dy is zero # Answer: ZeroDivisionError: return area_x_y_dy / area_y_dy def fwhm(x, y): ''' report the full-width at half-maximum of y(x) Start at the peak position and walk down each side, stopping at the first point where *y* value is less than or equal to the peak *y* value. The difference between the *x* values of the two sides is the FWHM. :param [float] x: array of ordinates :param [float] y: array of abcissae :return float: FWHM x & y must have the same length ''' position = _get_peak_index(y) half_max = y[position] / 2 # homework # - Describe what happens when the data is noisy? # advanced homework # TODO: use linear interpolation to improve precision # walk down the left side of the peak left = position while y[left] > half_max: left -= 1 # HW problem3 solution if left < 0: return "FWHM out of data range" # homework # TODO: make sure that "left" will not advance too far, out of range of the indexes # otherwise, y[-1] will generate an exception # This chart shows an example when this would happen # http://usaxs.xray.aps.anl.gov/livedata/specplots/2010/04/04_25/s00095.png # walk down the right side of the peak right = position while right < len(y)-1 and y[right] > half_max: right += 1 # compute FWHM return abs(x[left] - x[right])
abf6f8233105664c8f2003be104b6ff701d8b0fb
huotong1212/mylearnpy
/code/day03/闭包.py
928
3.734375
4
# 如果一定要引用循环变量怎么办?方法是再创建一个函数, # 用该函数的参数绑定循环变量当前的值,无论该循环变量后续如何更改,已绑定到函数参数的值不变: def count(): def f(j): def g(): return j*j return g fs = [] for i in range(1, 4): fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f() return fs f1, f2, f3 = count() def createCounter(): i = 0 def counter(): nonlocal i #使用外层变量 i+=1 return i return counter def createCounter1(): li = [0] def counter(): li.append(li[-1] + 1) return li[-1] return counter countA = createCounter() print(countA(),countA()) # countB所指向的仅仅是counter这个函数,只是可以调用createCounter1中的局部变量 countB = createCounter1() print(countB(),countB())
a535960d44b122e9d4c16e1cfe3925efaeddd4ec
ijcardin/Kattis-CPC
/oddities.py
251
3.921875
4
numberOfTestCases = int(input()) testCases = [] for i in range(numberOfTestCases): testCases.append(int(input())) for testCase in testCases: if testCase % 2 == 0: print(testCase, 'is even') else: print(testCase, 'is odd')
65712f7620675c5c2b49e144e32f6189be53ef21
sbrrr/Baby-scripts
/exercise3_4.py
106
3.640625
4
c=int(input("Enter number: ")) a = [1, 1, 3, 3, 5, 8, 13, 21, 34, 55, 89] print([i for i in a if i <= c])
a1de9c6fadf4ac78f52b5bbac20880103cb05dac
Ret-David/Python
/IS 201/Practical Exercises/PE03_David_Martinez_5.py
994
4.3125
4
# David Martinez # Write a Python program to match key values in two dictionaries. # Sample dictionary: {'key1': 1, 'key2': 3, 'key3': 2}, {'key1': 1, 'key2': 2} # Expected output: key1: 1 is present in both x and y sample_dictionary = {'key1': 1, 'key2': 3, 'key3': 2}, {'key1': 1, 'key2': 2} x = sample_dictionary[0] # set index 0 as dict{x} y = sample_dictionary[1] # set index 1 as dict{y} present_in_both = dict() # make an empty dictionary for output for key in x: # for loop through dict{x} if (key in y and x[key] == y[key]): # compare dictionary key/value present_in_both[key] = x[key] # store common key/value found between dictionaries for key, value in present_in_both.items(): # use dict.items to cycle through key/value print("{}: {}".format(key, value) + " is present in both x and y") # use str.format to achieve Expected Output
e452de3870dd70d16aabedede654d05b85bcc8db
aleks96n/DS_T1
/DHT.py
1,166
3.875
4
import sys def list(): #list the nodes in the ring return def lookup(): #lookup for a node containing a particular key. read document for more, got no idea return def join(): #new node to join the ring return def leave(): #remove node from ring return def shortcut(): #adds a shortcut from one node to another return def main(): upper, lower = None, None node_list = [] shortCut_string = None nodeCheck, keyCheck, shortcutCheck = False, False, False #very naive, but works with open(sys.argv[1], 'r') as f: for line in f: if(line.startswith("#k")): keyCheck = True continue elif(line.startswith("#n")): nodeCheck = True continue elif(line.startswith("#s")): shortcutCheck = True continue if(nodeCheck): helper = line.split(",") node_list.extend(int(i) for i in helper) nodeCheck = False elif(keyCheck): helper = line.split(",") upper, lower = int(helper[1]), int(helper[0]) keyCheck = False elif(shortcutCheck): shortCut_string = line shortcutCheck = False print(upper) print(lower) print(node_list) print(shortCut_string) if __name__ == "__main__": main()
26cf3cdf97df3d3b3c60fc8e482ef9368a1a7cc0
rishavsharma47/ENC2020P1
/Session11B.py
3,187
4.53125
5
# 1. Think of an Object # Customer is Object # name, phone, email, gender, address are Attributes # 2. Create its Class class Customer: # __init__ : constructor, which gets executed when we create object # init can have inputs as many as you want # self is a reference variable, which holds the hashcode of current object # name of self can by any name of your choice # BUT self is always the first input to __init__ def __init__(self, name, phone, email, gender, address): print("init executed") print(">> self is:", self) # LHS | self.name | is creating attribute in current Object # RHS | name | is input containing data which we assign to attribute self.name = name self.phone = phone self.email = email self.gender = gender self.address = address # OVERLOADING : NOT SUPPORTED # Creating same __init__ function will create new init and delete old init """ def __init__(self, name, phone, email, gender, address, customerType): print("init executed") print(">> self is:", self) # LHS | self.name | is creating attribute in current Object # RHS | name | is input containing data which we assign to attribute self.name = name self.phone = phone self.email = email self.gender = gender self.address = address """ def upgradeCustomerToPrime(self, customerType, wallet): self.customerType = customerType self.wallet = wallet def updateCustomerDetails(self, name, phone, email, gender, address): self.name = name self.phone = phone self.email = email self.gender = gender self.address = address # if we create any function in class, its first input is self def showCustomerDetails(self): print(">> {} can be called at {} and lives in {}. For Email {}".format(self.name, self.phone, self.address, self.email)) print(">> Gender:", self.gender) def showPrimeCustomerDetails(self): print(">> {} can be called at {} and lives in {}. For Email {}".format(self.name, self.phone, self.address, self.email)) print(">> Gender:", self.gender) print(">> Wallet Balance: \u20b9",self.wallet) # 3. From Class Create Real Object cRef1 = Customer("John", "+91 99999 88888", "john@example.com", "Male", "Redwood Shores") # Object Construction Statement print(">> cRef1 is:", cRef1) cRef2 = Customer("Fionna", "+91 90909 80808 ", "fionna@example.com", "Female", "Country Homes") # Object Construction Statement print(">> cRef2 is:", cRef2) cRef1.upgradeCustomerToPrime("Prime", 100) # cRef1.showCustomerDetails() cRef1.showPrimeCustomerDetails() cRef2.showCustomerDetails() cRef2.updateCustomerDetails("Fionna Flynn", "+91 90909 80808 ", "fionna.flymm@example.com", "Female", "Country Homes") # cRef2.name = "Fionna Flynn" # cRef2.customerType = "Prime" # del cRef2.gender print(">> cRef1 :", cRef1.__dict__) print(">> cRef2 :", cRef2.__dict__)
bec8b24dab7397883c7e40c8870ef977989ea6ba
johannareyy/learning-python
/aula 3/graf1.py
466
3.859375
4
#site #grafico simples e conceitos fundamentais #listas em python import matplotlib.pyplot as plt #import = include em C #pyplot sub biblioteca do matplotlib #as plt pra chamar por um apelido, pode dar o nome quiser plt.plot([1.1, 1.2, 5.6, 8], [1, 2, 3, 4], "ro-") #se n der o x ele usa o indice da lista # r=read, o=plotar pontos como bolinhas, -=conectar os pontos por linhas plt.ylabel('alguns números') #descricao do y plt.show() plt.savefig("gráfico.png")
b850eb21f223467113113f7bfb4f295016bbf308
Sethuaswin/Haker_rank_python
/8_Nested Lists.py
2,311
4.4375
4
# Question 8 - Nested Lists: # Given the names and grades for each student in a class N of students, # store them in a nested list and print the name(s) of any student(s) having the second lowest grade. # # # Note: If there are multiple students with the second lowest grade, # order their names alphabetically and print each name on a new line. # # # Example # records = [["chi",20.0],["beta",50.0],["alpha",50.0]] # The ordered list of scores is [20.0,50.0,50.0], so the second lowest score is 50.0. # There are two students with that score: ["beta","alpha"]. Ordered alphabetically, the names are printed as: # # alpha # beta # # Input Format # The first line contains an integer,N, the number of students. # The 2N subsequent lines describe each student over lines. # # The first line contains a student's name. # The second line contains their grade. # # Constraints # # 2 <= N <=5 # There will always be one or more students having the second lowest grade. # Output Format # Print the name(s) of any student(s) having the second lowest grade in. # If there are multiple students, order their names alphabetically and print each one on a new line. # # Sample Input 0 # # 5 # Harry # 37.21 # Berry # 37.21 # Tina # 37.2 # Akriti # 41 # Harsh # 39 # # Sample Output 0 # Berry # Harry # # Explanation 0 # There are 5 students in this class whose names and grades are assembled to build the following list: # # # python students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]] # # # The lowest grade of 37.2 belongs to Tina. # The second lowest grade of 37.21 belongs to both Harry and Berry, # so we order their names alphabetically and print each name on a new line. students_grade = [] for i in range(int(input("Enter how many student details need to be entered: "))): name = input("Enter the student name: ") score = float(input("Enter the score: ")) students_grade.append([name, score]) sorted_score = sorted(list(set([x[1] for x in students_grade]))) second_last = sorted_score[1] final_second_last = [] for student in students_grade: if second_last == student[1]: final_second_last.append(student[0]) for student in sorted(final_second_last): print(student)
a8094111e5b2a991cee5977c8de9732799f1de38
lfmartins/real-python-lessons
/sql/carsdb_02.py
838
3.890625
4
import sqlite3 connection = sqlite3.connect('cars.db') c = connection.cursor() data = [ ( 'Ford', 'Taurus', 120), ( 'Ford', 'Mustang', 40), ( 'Honda', 'Accord', 110), ( 'Honda', 'Civic', 86), ( 'Honda', 'CR-V', 45), ] c.executemany(""" INSERT INTO inventory(Make, Model, Quantity) VALUES (?, ?, ?)""", data) print('\nInitial Inventory:\n') rows = c.execute(""" SELECT * FROM inventory """) for make, model, quantity in rows: print(make, model, quantity) c.execute(""" UPDATE inventory SET quantity=87 WHERE Model='Accord' """) c.execute(""" UPDATE inventory SET quantity=32 WHERE Model='Mustang' """) print('\n\nFord Vehicles:\n') rows = c.execute(""" SELECT Model, Quantity FROM inventory WHERE Make='Ford' """) for model, quantity in rows: print(model, quantity) connection.commit() connection.close()
12a7516864ae1d254ba91178587d5e9938ef9d84
gauravsingh58/algo
/topCoder/srms/400s/srm493/div2/amoeba_div_two.py
327
3.515625
4
from itertools import groupby class AmoebaDivTwo: def count(self, table, K): def count(r): return sum(max(len(list(g))-K+1, 0) for k, g in groupby(r) if k == 'A') return sum(count(r) for r in table) + \ (sum(count(r) for r in zip(*table)) if K > 1 else 0)