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
dc0e6196eb7f37471b715c7d11e17888585d29de
amans1998/Assignment2
/Design2.py
243
3.859375
4
for i in range(5): for j in range(5): if j==0: print("*",end="") elif j==i: print("*",end="") elif i==4: print("*",end="") else: print(" ",end="") print()
667bbe72e819d8553093757f452f8540232ddfa2
atgrigorieva/Python_lessons_basic
/lesson02/home_work/hw02_normal.py
6,214
4.25
4
# Задача-1: # Дан список, заполненный произвольными целыми числами, получите новый список, # элементами которого будут квадратные корни элементов исходного списка, # но только если результаты извлечения корня не имеют десятичной части и # если такой корень вообще можно извлечь # Пример: Дано: [2, -5, 8, 9, -25, 25, 4] Результат: [3, 5, 2] list1 = [] lenList1 = input('Введите размер списка: ') for el in range(int(lenList1)): #element = input('Введите значение элмента для списка 1: ') #list1.append(element) while True: try: element = int(input('Введите значение элмента для списка: ')) list1.append(element) break; except ValueError: print("Только числа") print("Значения списка: ") print(list1) list2 = [] from math import sqrt for el in list1: try: if sqrt(el) - int(sqrt(el)) == 0: list2.append(sqrt(el)) except: pass print("Значения списка 2: ") print(list2) # Задача-2: Дана дата в формате dd.mm.yyyy, например: 02.11.2013. # Ваша задача вывести дату в текстовом виде, например: второе ноября 2013 года. # Склонением пренебречь (2000 года, 2010 года) M = 1 while True or M < 1 or M > 12: try: M = int(input('Введите значение месяца: ')) break; except ValueError: print("Только числа от 1 до 12") D = 1 if M != 2: while True or D < 1 or D > 31: try: D = int(input('Введите значение дня: ')) break; except ValueError: print("Только числа от 1 до 31") else: while True or D < 1 or D > 28: try: D = int(input('Введите значение дня: ')) break; except ValueError: print("Только числа от 1 до 28") Y = 2011 while True or len(str(Y) > 4) or len(str(Y) < 1): try: Y = int(input('Введите значение года: ')) break; except ValueError: print("Только числа. Длина строки от 1 до 4 символов.") DD = '' if len(str(D)) == 1: DD = '0' + str(D) else: DD = str(D) MM = '' if len(str(M)) == 1: MM = '0' + str(M) else: MM = str(M) YYYY = '' if len(str(Y)) == 1: YYYY = '000' + str(Y) if len(str(Y)) == 2: YYYY = '00' + str(Y) if len(str(Y)) == 3: YYYY = '0' + str(Y) if len(str(Y)) == 4: YYYY = str(Y) Days = { '01': 'первое', '02': 'второе', '03': 'третье', '04': 'четвёртое', '05': 'пятое', '06': 'шестое', '07': 'седьмое', '08': 'восьмое', '09': 'девятое', '10': 'десятое', '11': 'одиннадцатое', '12': 'двенадцатое', '13': 'тринадцатое', '14': 'четырнадцатое', '15': 'пятнадцатое', '16': 'шестнадцатое', '17': 'семнадцатое', '18': 'восемнадцатое', '19': 'девятнадцатое', '20': 'двадцатое', '21': 'двадцать первое', '22': 'двадцать второе', '23': 'двадцать третье', '24': 'двадцать четвёртое', '25': 'двадцать пятое', '26': 'двадцать шестое', '27': 'двадцать седьмое', '28': 'двадцать восьмое', '29': 'двадцать девятое', '30': 'тридцатое', '31': 'тридцать первое' } Months = { '01': 'января', '02': 'февраля', '03': 'марта', '04': 'апреля', '05': 'мая', '06': 'июня', '07': 'июля', '08': 'августа', '09': 'сентября', '10': 'октября', '11': 'ноября', '12': 'декабря' } DateInput = [DD, MM, YYYY] print(Days[DateInput[0]] + ' ' + Months[DateInput[1]] + ' ' + DateInput[2] + ' ' + 'года') # Задача-3: Напишите алгоритм, заполняющий список произвольными целыми числами # в диапазоне от -100 до 100. В списке должно быть n - элементов. # Подсказка: # для получения случайного числа используйте функцию randint() модуля random n = 0 while True: try: n = int(input('Введите размер списка: ')) break; except ValueError: print("Только числа") list1 = [] from random import randint for num in range(int(n)): list1.append(randint(-100, 100)) print(list1) # Задача-4: Дан список, заполненный произвольными целыми числами. # Получите новый список, элементами которого будут: # а) неповторяющиеся элементы исходного списка: # например, lst = [1, 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 2, 4, 5, 6] # б) элементы исходного списка, которые не имеют повторений: # например, lst = [1 , 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 4, 6] lst = [1, 2, 4, 5, 6, 2, 5, 2] lst2 = [] for el in lst: if (el in lst2) == False: lst2.append(el) print("Новые элменты списка 2: ") print(lst2) lst3 = [] for el in lst: countRepeatEl = 0 for el_ in lst: if el == el_: countRepeatEl += 1 if countRepeatEl == 1: lst3.append(el) print("Новые элменты списка 3: ") print(lst3)
fb09d190a829e992fe840062219d565f4722c84f
grantpauker/DeepSpace2019
/src/utils/angles.py
428
3.890625
4
import math def wrapPositiveAngle(in_angle: float): """Wrap positive angle to 0-360 degrees.""" return abs(math.fmod(in_angle, 360.0)) def positiveAngleToMixedAngle(in_angle: float): """Convert an angle from 0-360 to -180-180""" in_angle = wrapPositiveAngle(in_angle) if in_angle > 180 and in_angle < 360: in_angle -= 180 in_angle = 180 - in_angle in_angle *= -1 return in_angle
959a90fd10f78741b6d316f9d3689b76a2cafa7b
raitk3/home-miscellaneous
/Text Replacer/replacer.py
1,046
3.78125
4
import json def get_text(filename): text = "" with open(filename, "r", encoding="utf-8") as file: while True: c = file.read(1) if not c: break text += c return text def get_dict(filename): with open(filename, "r", encoding='utf-8') as file: return json.load(file) def replace_stuff(text, replace_map): new_text = "" for letter in text: if letter.lower() in replace_map: if letter.islower(): new_text += replace_map[letter] else: new_text += replace_map[letter.lower()].upper() else: new_text += letter return new_text def write_new(new_text): with open("new_text.txt", "w") as file: file.write(new_text) if __name__ == '__main__': replace_map = get_dict("replacemap.json") text = get_text("esialgne_tekst.txt") print(text) print(replace_map) new_text = replace_stuff(text, replace_map) write_new(new_text) print(new_text)
4cc92d771b38211afd1de8ce8b90b56bea597995
kmather73/ProjectEuler
/Python27/euler040.py
390
3.828125
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 14 18:31:15 2016 @author: kevin """ def main(): digits, num = 0, 0 prod = 1 nums = [10**i for i in range(0,7)] while digits < 10**6+1: num += 1 for ch in str(num): digits += 1 if digits in nums: prod *= int(ch) print prod if __name__ == "__main__": main()
bacdade7e33dc0bd1e30a92408dee29338266286
njNafir/ntk
/ntk/widgets/canvas.py
8,975
3.9375
4
# Import Tkinter Canvas to use it and modify default from tkinter import Canvas as tkCanvas # Import all util from ntk.utils from ntk.utils import * # Import pyperclip # pyperclip is used to copy and paste canvas element text when it's selected import pyperclip class Canvas(tkCanvas): # canvas class can be called once the root tk is defined # only one must required field is root which is the any of widget # other params can be set to get different type of design # but this is also preferred design to use in your window # every design is custom and can be set twice # Canvas instance will contain the base tkinter canvas instance just with modified styles and methods # init method is getting all of your arguments # and keyword arguments # and passing related # and unknown params # and args to tkinter canvas # so if it cause an error most probably it's getting from tkinter canvas object # see your all arguments and keywords is supporting by ntk Canvas or tkinter canvas def __init__(self, root, # root is a master window to place this button into it bg="bg-white", # background color highlightbackground="bg-white", # background color when canvas is highlighted highlightcolor="fg-dark", # foreground color when canvas is highlighted selectbackground="bg-primary", # element background color when canvas element is selected scrollregion=[0,0,350,96], # [x1, y1, x2, y2] region when canvas is scrolling via scrollbar or mouse relief="flat", # relief design can be flat, groove etc width=350, # canvas width height=96, # canvas height row=0, # row position column=0, # column position rowspan=1, # row spanning size columnspan=1, # column spanning size padx=1, # padding in left and right pady=1, # padding in top and bottom mousescroll=True, # set False if you don't want to scrolling when scrolling via mouse gridcolumn=1, # set 0 if you don't want responsiveness by column in it's root window gridrow=1, # set 0 if you don't want responsiveness by row in it's root window *args, **kwargs # extra arguments and keyword arguments can be passed ): super(Canvas, self).__init__(root, width=width, height=height, scrollregion=scrollregion, relief=relief, background=color(bg), # color of background highlightbackground=color(highlightbackground), #color of background when canvas # highlighted highlightcolor=color(highlightcolor), #color of foreground when canvas # highlighted selectbackground=color(selectbackground), #color of background when canvas # selected *args, **kwargs # extra arguments and keyword arguments will passed ) # scroll region x1 # scroll region y1 # scroll region x2 # scroll region y2 self.scr_x1, \ self.scr_y1, \ self.scr_x2, \ self.scr_y2 = scrollregion self.grid( row=row, # grid configure row column=column, # grid configure column rowspan=rowspan, # grid configure row span columnspan=columnspan, # grid configure column span padx=padx, # grid configure padding left and right pady=pady # grid configure padding top and bottom ) if mousescroll: self.bind("<MouseWheel>", lambda e: self.mousewheel(e)) # canvas scrolling by mouse scrolling self.bind("<Double-Button-1>", lambda e: self.select_clicked(e)) # canvas mouse double click selection command # canvas column configure by grid column root.grid_columnconfigure( column, # column position weight=gridcolumn # column weight ) root.grid_rowconfigure( row, # row position weight=gridrow # row weight ) def select_clicked(self, e=None): # check if clicked object is a text containing object if self.type("current") != "text": # if not clicked object is a text containing object then return return # canvas.focus_set() # can be used to focus in a canvas main widget self.focus_set() # set focus into clicked object from anywhere # canvas.focus(object) # can be used to focus in a specific object self.focus("current") # set focus into current object from anywhere # canvas.select_from(object, position) # can be used to select from this position self.select_from("current", 0) # select starting from 0 index from current clicked object # canvas.select_to(object, position) # can be used to select until this position self.select_to("current", "end") # select end to 'end' index from current clicked object # and at last copy to clipboard selected text from current object # pyperclip.copy function can be used for selecting any text # we are passing our selected text here # canvas.selection_get() method will return # current selected text from this canvas self.bind("<Control-c>", lambda e: pyperclip.copy( "{}".format( self.selection_get() ) ) ) def mousewheel(self, e): # mousewheel method is used to scroll # in canvas when mouse scrolled self.yview_scroll( int(-1*(e.delta/120)), # get and set delta event into into with dividing by 120 "units" # set size into units ) def increase_scrollragion(self, x1=False, y1=False, x2=False, y2=False): # canvas.increase_scrollregion(x1, y1, x2, y2) is used to # increase scrollregion size of a canvas window # scroll region x1 # scroll region y1 # scroll region x2 # scroll region y2 self.scr_x1, \ self.scr_y1, \ self.scr_x2, \ self.scr_y2 = self.scr_x1 + (x1 if x1 else 0), \ self.scr_y1 + (y1 if y1 else 0), \ self.scr_x2 + (x2 if x2 else 0), \ self.scr_y2 + (y2 if y2 else 0) # at last set new scroll region in canvas # canvas.config(scrollregion=[x1, y1, x2, y2]) self.config( scrollregion=[ self.scr_x1, # x1 position in region self.scr_y1, # y1 position in region self.scr_x2, # x2 position in region self.scr_y2 # y2 position in region ] ) def decrease_scrollragion(self, x1=False, y1=False, x2=False, y2=False): # canvas.decrease_scrollragion(x1, y1, x2, y2) is used to # decrease scrollregion size of a canvas window # scroll region x1 # scroll region y1 # scroll region x2 # scroll region y2 self.scr_x1, \ self.scr_y1, \ self.scr_x2, \ self.scr_y2 = self.scr_x1 - (x1 if x1 else 0), \ self.scr_y1 - (y1 if y1 else 0), \ self.scr_x2 - (x2 if x2 else 0), \ self.scr_y2 - (y2 if y2 else 0) # at last set new scroll region in canvas # canvas.config(scrollregion=[x1, y1, x2, y2]) self.config( scrollregion=[ self.scr_x1, # x1 position in region self.scr_y1, # y1 position in region self.scr_x2, # x2 position in region self.scr_y2 # y2 position in region ] )
97d10c5bd2d9e358116e658ab8374fffcae4d510
Ryanj-code/Python-1-and-2
/Projects/Speech - Dictionaries/speech.py
867
4.0625
4
import pprint #Import pprint(prettyprint) speech = open('mlk.txt', 'r') speech = speech.read() speech = speech.lower() #Opens and reads the speech speech = speech.replace('.', '') speech = speech.replace(',', '') speech = speech.replace('?', '') speech = speech.replace('!', '') speech = speech.replace('-', '') #Replaces all these punctuations with blank words = speech.split() print(words) #Print words after words is set speech that is splitted(smaller pieces). DictionaryWords = {} #Sets DictionaryWords to a blank dictionary. for i in range(len(words)): if words[i] in DictionaryWords: DictionaryWords[words[i]] += 1 else: DictionaryWords[words[i]] = 1 #Loops through speech, adds the word if it is not in the dictionary, else do not add the word. pprint.pprint(DictionaryWords) #Use pprints to print the dictionary out in alphabetical order.
0f7b2948d04dc912d8a8fb74e1bf3cc1e51c237b
Anirudh-thakur/LeetCodeProblems
/Contest/CountPrimes.py
818
3.828125
4
#https: // leetcode.com/explore/challenge/card/may-leetcoding-challenge-2021/599/week-2-may-8th-may-14th/3738/ class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ result = 0 if n <= 2: return 0 dyn = [0 for i in range(n)] i = 2 while(i<n): # print("number:"+str(i)) if dyn[i] == 0: result = result + 1 dyn[i] = 1 p = i * i while(p<n): # print("Square number:"+str(p)) dyn[p] = -1 p = p + i i = i+1 # print(dyn) return result if __name__ == '__main__': obj = Solution() result = obj.countPrimes(1000) print(result)
f35705db4b25eefa11a283253169255cd9c3aaaf
rafacasa/OnlineJudgePythonCodes
/Iniciante/p1172.py
193
3.59375
4
x = [] for i in range(10): v = int(input()) if v <= 0: valor = 1 else: valor = v x.append(valor) for i, v in enumerate(x): print('X[{}] = {}'.format(i, v))
2b276e337b8e4123fb143bc3f003e273c9be1132
jO-Osko/Krozek-python
/python_uvod/pogoji.py
1,466
3.609375
4
a = int(input("Vnesi a")) # <- b = int(input("Vnesi b")) # <, <=, >, >=, ==, != if a < b: print("a je manjši od b") print("A je še vedno manjši od b") print("A je še vedno manjši od b") print("A je še vedno manjši od b") print("A je še vedno manjši od b") print("A je še vedno manjši od b") else: print("a ni manjši od b") # Uporabnik naj vpiše številko meseca, mi pa mu odgovorimo s številom milisekund v mesecu # Če pa je vpisal neki nesmiselnega ga pa opozorita in končajta program # miliskeunde v dnevu ur_v_dnevu = 24 mili_v_dnevu = ur_v_dnevu * 60 * 60 * 1000 # 86400000 if a == 3 or a == 4: print("A je 3 ali 4") if a == 3 and a == 4: print("A je 3 in 4...., le kako je to mogoče") mesec = 7 meseci_z_30 = [1, 3, 5, 7, 8, 10, 12] if mesec in meseci_z_30: print(31) elif mesec == 2: print("februar") else: print("Nič od tega") a = 10 b = 0 # % # Napišita program, ki uporabnika povpraša po mesecu in letu ter mu pove število milisekund v tem mesecu # Seznami seznam = [1, 2, 3, 4, 5, 7, 200] dolzina = len(seznam) print(seznam[0]) # Prvi print(dolzina - 1) # Zadnji print(seznam[-2])# print(sedaj[dolzina - 2]) # Short circuit; to ima večina jezikov, tega nima pascal, večina jezikov to ima x = [1, 2, 3] if a > 0 and x [a]: pass if b != 0 and a / b > 3: if a / b > 3: print("To je ziher ok") if a > 10 or a*b > 200: print("to je večje")
5b593c4c1164b660a4b32e24a750470786adb8a8
scottlinehealthcare/TennisSimulation
/src/set.py
1,954
3.65625
4
from .game import Game from .tiebreak import TieBreak class Set(object): def __init__(self, player1, player2, count): self.__player1 = player1 self.__p1Score = 0 self.__player2 = player2 self.__p2Score = 0 self.count = count def run(self): while ((self.__p1Score < 6 and self.__p2Score < 6) or abs(self.__p2Score - self.__p1Score) < 2): if(self.__p1Score == 6 and self.__p2Score == 6): tieBreak = TieBreak(self.__player1, self.__player2).run() if (tieBreak == 1): self.__p1Score += 1 elif (tieBreak == 2): self.__p2Score += 1 else: print("Error: unexpected value in set.py") print("Score %i - %i" % (self.__p1Score, self.__p2Score)) break else: if(self.count % 2 == 0): game = Game(self.__player1, self.__player2).run() if(game == 1): self.__p1Score += 1 elif(game == 2): self.__p2Score += 1 else: print("Error: unexpected value in set.py") break else: game = Game(self.__player2, self.__player1).run() if (game == 1): self.__p2Score += 1 elif (game == 2): self.__p1Score += 1 else: print("Error: unexpected value in set.py") break self.count += 1 print("Score %i - %i" %(self.__p1Score, self.__p2Score)) print("Set finished") if (self.__p1Score > self.__p2Score): return 1 elif (self.__p2Score > self.__p1Score): return 2 else: return -1
2142c3e4db8fca336aa054c5de7d664b5e7e87e3
hakikialqorni88/Pemrograman-Terstruktur-Python
/Chapter 4/latihan4_ch4.py
1,691
3.96875
4
#Menghitung waktu tempuh perjalanan print("_______________Menghitung Waktu Tempuh Perjalanan_______________") jarakAB=float(input("Jarak dari kota A ke B (km):")) kecepatanAB=float(input("Kecepatan rata-rata dari kota A ke B (km/jam):")) print("Waktu tempuh perjalanan dari kota A ke B:", round(jarakAB//kecepatanAB),"Jam",round((jarakAB/kecepatanAB-jarakAB//kecepatanAB)*60),"Menit") print("________________________________________________________________") jarakBC=float(input("Jarak dari kota B ke C (km):")) kecepatanBC=float(input("Kecepatan rata-rata dari kota B ke C (km/jam):")) print("Waktu tempuh perjalanan dari kota B ke C:", round(jarakBC//kecepatanBC),"Jam",round((jarakBC/kecepatanBC-jarakBC//kecepatanBC)*60),"Menit") print("----------------------------------------------------------------") #Menghitung pukul berapa tiba di kota C print("__________________Menghitung Tiba Pukul Berapa__________________") print("Waktu berangkat dari kota A:") jam1=int(input("Jam:")) menit1=int(input("Menit:")) print("Waktu tiba di kota B") print("Jam:",jam1+round(jarakAB//kecepatanAB)) print("Menit:",menit1+round((jarakAB/kecepatanAB-jarakAB//kecepatanAB)*60)) print("Istirahat di kota B") jam2=int(input("Jam:")) menit2=int(input("Menit:")) print("Waktu tiba di kota C") jamtotalC=jam1+round(jarakAB//kecepatanAB)+round(jarakBC//kecepatanBC)+jam2 menittotalC=menit1+round((jarakAB/kecepatanAB-jarakAB//kecepatanAB)*60)+round((jarakBC/kecepatanBC-jarakBC//kecepatanBC)*60)+menit2 if(jamtotalC > 24): print("Jam:",jamtotalC-24) elif(menittotalC > 59): print("Jam:",jamtotalC+1) print("menit:",menittotalC-60) else: print("Jam:",jamtotalC) print("menit:",menittotalC)
b172d2b5ee71add31dc8e8a87bb9868d34805e30
paulosrlj/PythonCourse
/Módulo 3 - POO/Aula3 - MetodosEstaticos/testes.py
753
3.578125
4
import numpy as np class Pokemon: def __init__(self, nome, tipo, nivel): self.nome = nome self.tipo = tipo self.nivel = nivel # Não mexe com o objeto ou a classe em si @staticmethod def lista_todos_tipos(): tipos = np.array(['Fogo', 'Água', 'Elétrico', 'Terra', 'Voador']) for tipo in tipos: print(tipo) @classmethod def adiciona_pokemon_por_id(cls, nome, tipo, nivel, id): cls.nome = nome cls.tipo = tipo cls.nivel = nivel cls.id = id return cls(nome, tipo, nivel) #pkm1 = Pokemon('Pikachu', 'Elétrico', 25) # pkm1.lista_todos_tipos() pkm1 = Pokemon.adiciona_pokemon_por_id('Pikachu', 'Elétrico', 25, '001') print(pkm1.id)
e7f6a66a79be3e6dba3d5edf8b10e4acee73bc43
gan3i/Python_Advanced
/DS_and_AT/GFG/LinnkedList/Reverse.py
726
3.96875
4
#code class Node(): def __init__(self,data,next=None): self.data = data self.next = next def add_node(new_node,head): temp = head head = new_node head.next = temp return head head = Node(14) head = add_node(Node(20),head) head = add_node(Node(13),head) head = add_node(Node(12),head) head = add_node(Node(15),head) head = add_node(Node(10),head) def reverse(head): if not head.next: return head prev = None current = head while current: next = current.next current.next = prev prev = current current = next return prev head = reverse(head) current = head while current: print(current.data) current = current.next
5ea3bedcca2981388a0a03347dab385adc6d18f6
chenwen715/learn_repo
/learnpython/learnP_180703_test.py
1,906
3.828125
4
''' import unittest class Student(object): def __init__(self, name, score): self.name = name self.score = score def get_grade(self): if self.score < 0 or self.score > 100: raise ValueError('分数不在0-100之间') if self.score >= 80: return 'A' elif self.score >= 60: return 'B' return 'C' class TestStudent(unittest.TestCase): def test_80_to_100(self): s1 = Student('Bart', 80) s2 = Student('Lisa', 100) self.assertEqual(s1.get_grade(), 'A') self.assertEqual(s2.get_grade(), 'A') def test_60_to_80(self): s1 = Student('Bart', 60) s2 = Student('Lisa', 79) self.assertEqual(s1.get_grade(), 'B') self.assertEqual(s2.get_grade(), 'B') def test_0_to_60(self): s1 = Student('Bart', 0) s2 = Student('Lisa', 59) self.assertEqual(s1.get_grade(), 'C') self.assertEqual(s2.get_grade(), 'C') def test_invalid(self): s1 = Student('Bart', -1) s2 = Student('Lisa', 101) with self.assertRaises(ValueError): s1.get_grade() with self.assertRaises(ValueError): s2.get_grade() if __name__ == '__main__': unittest.main() ''' class Screen(object): @property def width(self): return self._width @width.setter def width(self,value): self._width=value @property def height(self): return self._height @height.setter def height(self,value): self._height=value @property def resolution(self): return self.height*self.width # 测试: s = Screen() s.width = 1024 s.height = 768 print('resolution =', s.resolution) if s.resolution == 786432: print('测试通过!') else: print('测试失败!')
8f0c82276638e3694fc9b2b6f466db97b1f5374b
pn11/benkyokai
/competitive/AtCoder/ABC130/C.py
406
3.609375
4
'''中心を通るような直線は必ず長方形を半分にする。指定した点が中心と等しくなければ直線は一意に決まる。''' w, h, x, y = map(lambda x: int(x), input().split()) def is_eq(x, y): if abs(x-y) < 1e-9: return True else: return False if is_eq(w/2, x) and is_eq(h/2, y): print("{} 1".format(w*h/2)) else: print("{} 0".format(w*h/2))
2c9d3dda15e27848357a5ff8083a7504cf618e07
PerroSanto/python-concurrencia-introduccion
/muchosThreads.py
849
3.5
4
import threading import time import logging from tiempo import Contador # Para que logging imprima más info sobre los threads logging.basicConfig(format='%(asctime)s.%(msecs)03d [%(threadName)s] - %(message)s', datefmt='%H:%M:%S', level=logging.INFO) # la función para usar para el thread # lo pone a dormir la cantidad de segundos "secs" def dormir(secs): time.sleep(secs) cont = Contador() cont.iniciar() lista = [] #crea una lista vacía #un for con 10 iteraciones for i in range(10): #crear un thead #se crea el hilo que llama a la funcion dormir por 1.5 segundos t = threading.Thread(target=dormir, args=[1.5]) #lanzarlo t.start() # lo a grega a la lista lista.append(t) #por cada hilo en la lista for thread in lista: # lo finaliza con el join thread.join() cont.finalizar() cont.imprimir()
9615f88a4c21572613391441bac00e51cb5e92bf
bioinfolearning/rosalind
/countDNAnucleotides.py
718
3.9375
4
#What I have to do #1. Open the file with the DNA string #2. Read from the file #3. Keep tally of nucleotides #4. Create a new file and write the tally in the order A C G and T from helperfunctions import get_string, write_to_file, make_output_filename #setting file names input_filename = "filename.txt" #opening file and setting up DNA string for counting DNA_string = get_string(input_filename) #make a tally of nucleotides nucleotide_tally = (str(DNA_string.count("A")) + " " + str(DNA_string.count("C")) + " " + str(DNA_string.count("G")) + " " + str(DNA_string.count("T"))) #write tally to new file write_to_file(input_filename, nucleotide_tally)
7bd9ab79777c10191c692c9cf079d03b4f85ad86
bitterengsci/algorithm
/九章算法/String问题/1542.Next Time No Repeat.py
1,579
3.609375
4
#-*-coding:utf-8-*- ''' 给一个字符串,代表时间,如"12:34"(这是一个合法的输入数据),并找到它的下一次不重复(不存在相同的数字)的时间。 如果它是最大的时间"23:59",那么返回的答案是最小的"01:23"。如果输入是非法的,则返回-1 ''' class Solution: """ @param time: @return: return a string represents time """ def nextTime(self, time): if len(time) != 5 or time is None: return "-1" ans = "" temp = time.split(":") hour, mins = int(temp[0]), int(temp[1]) nowtime = hour * 60 + mins if hour >= 24 or mins >= 60: return "-1" digit = [600, 60, 10, 1] for i in range(1, 1440): # 1 day = 1440 mins nexttime = (nowtime + i) % 1440 ans = "" print('next time = ', nexttime) for j in range(4): ans += str(nexttime // digit[j]) print('ans = ', ans) nexttime %= digit[j] print('next time = ', nexttime) # if self.isUnique(ans): # break if list(ans) != set(ans): break return ans[0: 2] + ":" + ans[2:] def isUnique(self, string): print(string) if len(string) == 0: return False Set = set() for i in range(len(string)): if string[i] in Set: return False Set.add(string[i]) return True s = Solution() print(s.nextTime("12:34"))
823a6fdc9e3bc273a22c41cb00b01070760dd7b2
lkapinova/Pyladies
/03/sinus.py
362
3.71875
4
# from math import sin # print(sin(1)) # 0.8414709848078965 # print(sin) # 'builtin_function_or_method' # print(sin + 1) # TypeError: unsupported operand type(s) for +: 'builtin_function_or_method' and 'int' # print('1 + 2', end=' ') # print('=', end=' ') # print(1 + 2, end='!') # print() print(1, "dvě", False) print(1, end=" ") print(2, 3, 4, sep=", ")
fb6ebb5606554ce3da562b0fd4b745e42950f368
ivanhuay/keygen-dictionary
/keygen-dictionary.py
7,251
3.828125
4
#!/usr/bin/python3 import os import itertools import operator class DictionaryMaker: def __init__(self): self.aditionalData = [] self.simpleCollection = ["admin", "adm", "adm", "2015", "2019","2018", "2016", "2017", "2014", ".", "-", "_", "@"] self.convinationLevel = 2 self.domainName = False self.fullName = False self.address = False self.importantDate = False self.identification = False def welcome(self): print("Welcome human, Please answer the following questions...") self.getInputs() self.processInput() self.generateDictionary() def getInputs(self): print("Usage: it is possible to enter an empty response...") convination = input("convination level: (2 recomended)") self.convinationLevel = 2 if convination != "" : self.convinationLevel = int(convination) self.makeQuestion("domain name?", "domainName") self.makeQuestion("address?", "address") self.makeQuestion("full name?", "fullName") self.makeQuestion( "birthdate or important date?(dd-mm-yyyy)", "importantDate") self.makeQuestion( "identifier or identification number?", "identification") self.makeQuestion("aditional data?", "aditionalData") def processNumbers(self, inStr): numbers = [str(s) for s in inStr.split() if s.isdigit()] response = [] for number in numbers: for i in range(1, len(number)): res = itertools.product(number, repeat=i) for convination in res: response.append(''.join(convination)) return response def processStr(self, inStr): response = [str(s) for s in inStr.split() if not s.isdigit()] response.append(inStr) response.append("".join(inStr.split())) return response def processName(self, inStr): response = self.processStr(inStr) words = [str(s) for s in inStr.split() if not s.isdigit()] for word in words: response.append(word[0]) response.append(word[0].title()) res = itertools.product(response, repeat=2) for convination in res: response.append(''.join(convination)) return self.cleanList(response) def processDomain(self, inStr): response = [] response.append(inStr) response.extend(inStr.split(".")) return response def processAddress(self, inStr): response = [] response.append(inStr) response.extend(inStr.split()) response.append(''.join(inStr.split())) response.extend(self.processNumbers(inStr)) response.extend(self.processStr(inStr)) return response def processDate(self, inStr): response = [] if "/" in inStr: response.extend(inStr.split("/")) if "-" in inStr: response.extend(inStr.split("-")) if len(response) == 3 and len(response[2]) == 4: response.append(response[2][:2]) response.append(response[2][2:]) tmpResponse = [] if len(response) == 0: return response res = itertools.combinations(response, 3) for convination in res: response.append(''.join(convination)) # response.append('-'.join(convination)) # response.append('/'.join(convination)) print("date convinations: " + str(len(response)) + ".") return self.cleanList(response) def processIdentification(self, inStr): numbers = [str(s) for s in inStr.split() if s.isdigit()] response = [] for number in numbers: for i in range(1, len(number)): response.append(number[0:i]) response.append(number[:i]) return self.cleanList(response) def makeQuestion(self, questionStr, storeStr): nextQuestion = True if not getattr(self, storeStr): setattr(self, storeStr, []) storeSelf = getattr(self, storeStr) while nextQuestion: tempAnswer = input(questionStr + " (empty = next question): ") if tempAnswer != "": storeSelf.append(tempAnswer) else: nextQuestion = False setattr(self, storeStr, storeSelf) def processInput(self): print("Starting processing...") if len(self.domainName) > 0: print("processing domain name...") for domain in self.domainName: self.simpleCollection.extend(self.processDomain(domain)) if len(self.fullName) > 0: print("processing full name...") for fullName in self.fullName: self.simpleCollection.extend(self.processName(fullName)) if len(self.address) > 0: print("processing address...") for address in self.address: self.simpleCollection.extend(self.processAddress(address)) if len(self.aditionalData) > 0: print("processing additional data...") for data in self.aditionalData: self.simpleCollection.extend(self.processStr(data)) if len(self.importantDate) > 0: print("processing dates...") for date in self.importantDate: self.simpleCollection.extend(self.processDate(date)) if len(self.identification) > 0: print("processing identification...") for identification in self.identification: self.simpleCollection.extend( self.processIdentification(identification)) tempTitles = [] for text in self.simpleCollection: if not str(text).title() in tempTitles: tempTitles.append(str(text).title()) self.simpleCollection.extend(tempTitles) self.greenPrint("Done") def cleanList(self, list): return sorted(set(list)) def greenPrint(self, text): print('\033[92m' + text + " " + u'\u2713' + '\033[0m') def generateDictionary(self): print("making words convinations...") print(str(len(self.simpleCollection)) + " words.") lines = [] for i in range(1, self.convinationLevel + 1): print("starting level: " + str(i) + ".") res = itertools.product(self.cleanList( self.simpleCollection), repeat=i) for j in res: posiblePass = ''.join(j) lines.append(posiblePass) self.greenPrint("leven " + str(i) + ": done") print("cleaning List... " + str(len(lines))) lines = self.cleanList(lines) self.greenPrint("clen list done lines: " + str(len(lines)) + ".") print("writing " + str(len(lines)) + " lines in file...") self.makeFile(lines) self.greenPrint("write file done") def makeFile(self, lines): with open('pass.txt', 'a') as passFile: for line in lines: passFile.write(line + '\n') dictionaryMaker = DictionaryMaker() dictionaryMaker.welcome()
53b83016908837a853ea4a05dd8aeb7be2152baa
BJV-git/leetcode
/stack_q/jose_p/implem_q.py
832
4.46875
4
# why chosen list also here #1. all need to be done is that we need to add lists such that we can add elements at the start of teh list so teh overall # complexity is maintained at O(1) class queue(object): def __init__(self): self.items = [] def isEmpty(self): return self.items ==[] def size(self): return len(self.items) def enqueue(self, item): self.items.insert(0,item) def dequeue(self): if not self.isEmpty(): return self.items.pop() else: return "queue is empty" def peek(self): if not self.isEmpty(): return self.items[-1] else: return "list is empty" s= queue() print(s.isEmpty()) s.enqueue(3) s.enqueue('Hi') s.enqueue(False) print(s.size()) (s.dequeue()) print(s.dequeue())
81c003045944597bc97be3c75c1cd082e2c8ae60
YardenBakish/Data-Clustering-Algorithms-Visualizer
/clustersOutput.py
1,262
3.546875
4
# 208539270 yardenbakish # 208983700 tamircohen1 """This module prints the computed clusters for NSC and K-means algorithms to clusters.txt file""" import numpy as np """This function is called by the main module and recieves: (1) an array which labels each observation to its computed cluster (i'th value is the cluster for the i'th point) (2) number of observations (3) number of clusters. (4) The function is called twice (for NSC and K-means) thus recieving a flag paramter indicating the times which it was called (in order to create document or append)""" def printClusters(label,n,K,flag): if (flag==0): clusters_txt = open("clusters.txt", "w") clusters_txt.write(str(K)+"\n") else: clusters_txt = open("clusters.txt", "a") """The function maps each cluster to its observations using python's dictionary (reverse mapping)""" d= {} for i in range(n): d[i] =[] for i in range(n): d[label[i]].append(i) """The function now prints to clusters.txt""" for i in range(n): for j in range(len(d[i])): if j== len(d[i])-1: clusters_txt.write(str(d[i][j])+"\n") else: clusters_txt.write(str(d[i][j])+",") clusters_txt.close()
553a6cbff21c2dce8b762b7808d1369bdbd4da3e
shivani1611/python
/ListCompare/main.py
505
3.84375
4
#!/usr/bin/env python3 import sys def main( ): # two lists to compare list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] list2 = ['b', 'd', 'f'] # remove all the elements that are in list2 from list1 for a in range( len( list2 ) - 1, -1, -1 ): for b in range( len( list1 ) - ( 1 ), -1, -1 ): if( list1[b] == list2[a] ): del( list1[b] ) # display the results for a in range( 0, len( list1 ), 1 ): print( list1[a] ) if( __name__ == ( "__main__" ) ): sys.exit( main( ) )
4a51fd28aa82203188b17812331dfe7e99f0c77f
FirdavsSharapov/PythonLearning
/Python Course/Learning Python/Data Structures/deque.py
1,030
4.5
4
class Deque: def __init__(self): self.items = [] def add_front(self, item): """This method takes an item as a parameter and inserts it to the list that of representing the Deque. The runtime is linear, or O(n), because every time you insert into the front of a list, all the other items in the list need to shift one position to the right. """ self.items.insert(0, item) def add_rear(self, item): """This method takes an item as a parameter and inserts it to the end of a list that of representing the Deque. The runtime is o(1), or constant because appending to the end of a list happens in constant time. """ self.items.append() def remove_front(self, item): pass def remove_rear(self, item): pass def peek_front(self, item): pass def peek_rear(self, item): pass def size(self, item): pass def is_empty(self): pass
065e4325cf6bb862172c4e88f70b64fc79a8f2dd
trushraut18/Hackerrank-Python
/ShapeReshape.py
112
3.609375
4
import numpy as np entries=list(map(int,input().split())) matrix=np.array(entries).reshape(3,3) print(matrix)
3349d2c00bd9e6c3b1e1b93e985011353b40622e
ramtinsaffarkhorasani/takalif3
/asdasa.py
141
3.65625
4
a=[2,3,5,1,10,14] for i in range(1,(len(a))): if a[i]<a[i-1]: print("noo") break else: print("hoora")
abcf09d34a0b607bd6eb3d50e1b84916bc1944a4
Bibhu-Dash/python-usefull-scripts
/Student_class.py
552
3.65625
4
class Student: perc_rise = 1.05 def __init__(self,first,last,marks): self.first=first self.last=last self.marks=marks self.email=first+'.'+last+'@school.com' def fullname(self): return '{} {}'.format(self.first,self.last) def apply_raise(self): self.marks=int(self.marks * self.perc_rise) std1 = Student('Bibhu','Dash',80) std2 = Student('Pratik','Swain',70) print(std1.email) print(std2.email) #print(std1.__dict__) #print(Student.__dict__) print(std1.marks) std1.apply_raise() print(std1.marks)
6c7a478f9f8177e53b85d07d2ab9f0c705f2ca7d
ciattaa/i-do-not-know
/madlib.py
513
3.890625
4
def main(): name = input("Please enter a name" ) place = input ("Please enter a place") vehicle = input("Please enter a name of a vehicle") verb = input("Please enter a verb") adverb = input("Please enter a adverb") print (name + " went to visit their friends at " + place + " While he was there, he saw a " + vehicle + verb + adverb + " While unsure of what was happening at first, " + name + " soon found out that is was a street race! ") if __name__ == "__main__": main()
3157bd1a551bc73ae0b9df264f1a4da7d62b28f9
lalit97/DSA
/union-find/gfg-union-find.py
409
3.890625
4
''' https://practice.geeksforgeeks.org/problems/disjoint-set-union-find/1 ''' ''' supports 1 based indexing their find means finding root ''' # function should return parent of x def find(arr, x): while arr[x-1] != x: x = arr[x-1] return x # function should not return anything def union(arr, x, z): root_x = find(arr, x) root_z = find(arr, z) arr[root_x-1] = arr[root_z-1]
57dfcb2d29d90087427cfc597c0ec8c2d26515ab
AndHilton/DndFight
/read_character_sheet.py
858
3.59375
4
""" reads in a character sheet file and returns a python dictionary of the necessary data """ import sys from collections import deque, namedtuple import argparse import glob from CharacterSheet import readCharacterSheet parser = argparse.ArgumentParser(description="read in data from a character sheet file") parser.add_argument("-d","--dir", help="directory to search for character files", default="") parser.add_argument("files", nargs=argparse.REMAINDER) def main(): args = parser.parse_args() charData = {} files = [ f"{args.dir}{file}" for file in args.files ] for filename in files: print(filename) charData[filename] = readCharacterSheet(filename) for field in charData[filename]: print(f"{field} : {charData[filename][field]}") print() if __name__ == '__main__': main()
08ffee26e1154d497f563a03c61b45c500c0771a
sushanb/PythonClassesIntroductionBeginners
/ClassesMore.py
740
4.09375
4
class Country(object): def __init__(self, name, capital_city, population): self.name = name self.capital_city = capital_city self.population = population def __str__(self): string = 'The capital city of ' + self.name + ' is ' + self.capital_city return string def bigger(self, other): if self.population > other.population: b = self.name + ' is bigger than ' + other.name else: b = other.name + ' is bigger than ' + self.name return b def __cmp__(self, other): return bigger(self, other) A = Country("Nepal", "Kathmandu", 2000) B = Country("India", "Delhi", 100000) print bigger(A, B) # A.bigger(B) # A > B # A > B #
9b5b5e45335c6855a97bad342d0734ab3f26a60a
sarvparteek/Data-structures-And-Algorithms
/fraction.py
3,020
3.5
4
'''Author: Sarv Parteek Singh Course: CISC 610 Term: Late Summer HW: 1 Problem: 2 ''' # Greatest common Divisor def gcd(m, n): while m % n != 0: #this step ensures that a denominator of 0 won't be allowed - it will raise a divide by zero exception oldm = m oldn = n m = oldn n = oldm % oldn return n class Fraction: #Constructor def __init__(self,num,den=1): #add a den of 1 in case of integer (and not fractional) input if (isinstance(num,int) and isinstance(den,int)): common = gcd(num, den) self.num = num//common self.den = den//common else: raise RuntimeError("Neither numerator nor denominator can have a non-integer value") #Override string operator def __str__(self): return str(self.num) + "/" + str(self.den) #Override add operator def __add__(self,other): return Fraction(self.num * other.den + other.num * self.den, self.den * other.den) #Override sub operator def __sub__(self,other): return Fraction(self.num * other.den - other.num * self.den, self.den * other.den) #Override mul operator: def __mul__(self,other): return Fraction(self.num * other.num, self.den * other.den) #Override truediv operator def __truediv__(self, other): return self.num * other.den, self.den * other.num # Override eq operator def __eq__(self, other): return (self.num *other.den == other.num * self.den) #Override ne operator def __ne__(self, other): return (self.num * other.den != other.num * self.den) #Override gt operator def __gt__(self, other): return (self.num * other.den) > (other.num * self.den) # Override ge operator def __ge__(self, other): return (self.num * other.den) >= (other.num * self.den) #Override lt operator def __lt__(self, other): return (self.num * other.den) < (other.num * self.den) # Override le operator def __le__(self, other): return (self.num * other.den) <= (other.num * self.den) #Accessor functions def getNum(self): return self.num def getDen(self): return self.den def show(self): print(self.num, "/", self.den) '''Test cases frac1 = Fraction(3,4) frac2 = Fraction(4,7) print("Fraction 1 is",frac1) print("Fraction 1's numerator is",frac1.getNum()) print("Fraction 1's denominator is",frac1.getDen()) print("Fraction 2 is", frac2) print("Fraction 2's numerator is",frac2.getNum()) print("Fraction 2's denominator is",frac2.getDen()) print("Fraction 1 + Fraction 2 =",frac1 + frac2) print("Fraction 1 - Fraction 2 =",frac1 - frac2) print("Fraction 1 * Fraction 2 =",frac1 * frac2) print("Fraction 1 / Fraction 2 =",frac1 / frac2) print("Fraction 1 == Fraction 2 is",frac1 == frac2) print("Fraction 1 != Fraction 2 is",frac1 != frac2) print("Fraction 1 > Fraction 2 is", frac1 > frac2) print("Fraction 1 >= Fraction 2 is", frac1 >= frac2) print("Fraction 1 < Fraction 2 is", frac1 < frac2) print("Fraction 1 <= Fraction 2 is", frac1 <= frac2) '''
60313bdb6f2a2f6e689bcd399250dffcbb6bf746
Hulihulu/ichw
/pyassign2/currency.py
1,151
3.984375
4
#!/usr/bin/env python3 """currency.py: Currency converter. __author__ = "Hu Ruihua" __pkuid__ = "1800011843" __email__ = "1800011843@pku.edu.cn" """ from urllib.request import urlopen def exchange(currency_from, currency_to, amount_from): """定义exchange函数 """ original_url = "http://cs1110.cs.cornell.edu/2016fa/a1server.php?from = "\ +currency_from+"&to = "+currency_to+"&amt = "+str(amount_from) doc = urlopen(original_url) docstr = doc.read() doc.close() jstr = docstr.decode("ascii") bool_value = jstr.replace("true","True") jstr = eval(bool_value) return jstr["to"] def test_exchange(): assert "2.1589225 Euros" == exchange("USD","EUR",2.5) assert "37.38225 Argentine Peso" == exchange("USD","ARS",2.5) assert "278.4975 Japanese Yen" == exchange("USD","JPY",2.5) def main(): a = input("Please input the currency on hand: ") b = input("Please input the currency to convert to: ") c = str(input("please input amount of currency to convert:")) test_exchange() print(exchange(a,b,c)) if __name__ == '__main__': main()
99ee90a8599763f934bd7a142dcc42f96eacac74
kgodfrey24/advent-of-code-2018
/day5/day5b.py
584
3.765625
4
import string input = open("day5/input").read().strip() def is_match(a, b): return a != b and (a == b.lower() or a == b.upper()) shortest_result = 9999999 for letter_of_alphabet in string.ascii_lowercase: stack = [] for char in input: if char.lower() == letter_of_alphabet: continue elif not stack: stack.append(char) elif is_match(char, stack[-1]): stack.pop() else: stack.append(char) if len(stack) < shortest_result: shortest_result = len(stack) print shortest_result
2e0729d4d3c64979b7427d8004f58479cceb3123
JCSheeron/PythonLibrary
/bpsList.py
5,274
3.828125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # bpsList.py # Funcitons for dealing with lists # # Break a list into n-size chunks, and return as a list of lists. # If seq cannot be converted to a list, return None. # If chuckSizse cannot be converted to an integer, return the original list. def listChunk(seq, chunkSize): """Given a list, return a list of lists broken into the specified chunk size. If seq cannot be converted to a list, return an empty list. If chuckSizse cannot be converted to an integer, return the original list.""" # Make sure sequence can be turned into a list. Message and out if not. try: srcList = list(seq) except ValueError as ve: print( "ERROR: The seq parameter of the listChuck function must be passed a list or something \ convertable to a list. No list to return." ) print(ve) return list() try: n = int(chunkSize) if 0 >= n: raise ValueError except ValueError as ve: print( "ERROR: The listChunk parameter of the listChuck function must be passed an interger or something \ convertable to an integer, and must >= 0. Returning the original list." ) print(ve) # return the original list return srcList # break the list into chucks using list comprehension # list = <output expression> for i in <input sequence> # (len(srcList) + n -1 // n) will be the number of chunks needed. Range converts this to a zero # based sequence to be used as an index. For each index (i), slicing is used to create a chunk. return [srcList[i * n : (i + 1) * n] for i in range((len(srcList) + n - 1) // n)] # Return a list of duplicate values def listDuplicates(seq): """Given a list, return a list of duplicate values.""" # Make sure sequence can be turned into a list. Message and out if not. try: srcList = list(seq) except ValueError as ve: print( "ERROR: listDuplicates function must be passed a list or something \ convertable to a list." ) print(ve) return None seen = set() # use variable as a function below seen_add = seen.add # adds all elements not yet known to seen, and all others to seen_twice seen_twice = set(x for x in srcList if x in seen or seen_add(x)) # covert to a set and return return list(seen_twice) # Return a list of values found in both lists def listToListIntersection(seqA, seqB): """Given two lists/sets, return a list of values found in both.""" # Make sure listA and ListB can be a list/set. Message and out if not. try: srcSetA = set(seqA) except ValueError as ve: print( "ERROR: listToListIntersection function must be passed two list/set \ objects, or two obejcts that can be converted to sets. This is not the case \ for the 1st argument." ) print(ve) return None try: srcSetB = set(seqB) except ValueError as ve: print( "ERROR: listToListIntersection function must be passed two list/set \ objects, or two obejcts that can be converted to sets. This is not the case \ for the 2nd argument." ) print(ve) return None # return a list of common values. return list(set(srcSetA).intersection(srcSetB)) # Return a list of values found in A but not in B def listANotInB(seqA, seqB): """Given two lists/sets, return a list of values found only in the first one.""" # Make sure listA and ListB can be a set. Message and out if not. try: srcSetA = set(seqA) except ValueError as ve: print( "ERROR: listANotInB function must be passed two list/set \ objects, or two obejcts that can be converted to sets. This is not the case \ for the 1st argument." ) print(ve) return None try: srcSetB = set(seqB) except ValueError as ve: print( "ERROR: listANotInB function must be passed two list/set \ objects, or two obejcts that can be converted to sets. This is not the case \ for the 2nd argument." ) print(ve) return None # return a list of values that are not in the second sequence return list(filter(lambda ele: ele not in srcSetB, srcSetA)) # Return true if list A is a subset of list B def listAisSubset(seqA, seqB): """Given two lists/sets, return true if the first is a subset of the second.""" # Make sure listA and ListB can be a set. Message and out if not. try: srcSetA = set(seqA) except ValueError as ve: print( "ERROR: listAIsSubset function must be passed two list/set \ objects, or two obejcts that can be converted to sets. This is not the case \ for the 1st argument." ) print(ve) return False try: srcSetB = set(seqB) except ValueError as ve: print( "ERROR: listAIsSubset function must be passed two list/set \ objects, or two obejcts that can be converted to sets. This is not the case \ for the 2nd argument." ) print(ve) return False # return true if set A is a subset of B return srcSetA.issubset(srcSetB)
ed23499c92acbcb6c0592b9a6af0db500c1377f3
daniel-reich/turbo-robot
/s89T6kpDGf8Pc6mzf_23.py
1,984
4.0625
4
""" ![](https://edabit-challenges.s3.amazonaws.com/segment4.gif) The table below shows which of the segments `a` through `g` are illuminated on the seven segment display for the digits `0` through `9`. When the number on the display changes, some of the segments may stay on, some may stay off, and others change state (on to off, or off to on). Create a function that accepts a string of digits, and for each transition of one digit to the next, returns a list of the segments that change state. Designate the segments that turn on as uppercase and those that turn off as lowercase. Sort the lists in alphabetical order. For example: seven_segment("805") ➞ [["g"], ["b", "e", "G"]] In the transition from `8` to `0`, the `g` segment turns off. Others are unchanged. In the transition from `0` to `5`, `b` and `e` turn off and `G` turns on. Others are unchanged. Digit| Lit Segments ---|--- 0| abcdef 1| bc 2| abdeg 3| abcdg 4| bcfg 5| acdfg 6| acdefg 7| abc 8| abcdefg 9| abcfg ### Examples seven_segment("02") ➞ [["c", "f", "G"]] seven_segment("08555") ➞ [["G"], ["b", "e"], [], []] # Empty lists designate no change. seven_segment("321") ➞ [["c", "E"], ["a", "C", "d", "e", "g"]] seven_segment("123") ➞ [["A", "c", "D", "E", "G"], ["C", "e"]] seven_segment("3") ➞ [] seven_segment("33") ➞ [[]] ### Notes N/A """ def seven_segment(txt): D={'0':('abcdef','g'), '1':('bc','adefg'), '2':('abdeg','cf'), '3':('abcdg','ef'), '4':('bcfg','ade'), '5':('acdfg','be'), '6':('acdefg','b'), '7':('abc', 'defg'), '8':('abcdefg',''), '9':('abcfg','de')} res=[[] for _ in range(len(txt)-1)] for i in range(len(txt)-1): for x in D[txt[i]][0]: if x in D[txt[i+1]][-1]: res[i].append(x) for y in D[txt[i]][-1]: if y in D[txt[i+1]][0]: res[i].append(y.upper()) B=[sorted(x, key=lambda t: t.lower()) for x in res] return B
78712137f375bac578f34318f0cbe52750f53084
loganfreeman/python-algorithms
/algorithms/math/primality_test.py
991
3.6875
4
from math import sqrt from algorithms.math.sieve_eratosthenes import eratosthenes CACHE_LIMIT = 10 ** 6 primes_cache_list = [] primes_cache_bool = [] def is_prime(number, cache=True): if number < 2: return False global primes_cache_list, primes_cache_bool if cache and len(primes_cache_list) == 0: primes_cache_list,primes_cache_bool = eratosthenes(CACHE_LIMIT, return_boolean=True) for prime in primes_cache_list: primes_cache_bool[prime] = True if number < len(primes_cache_bool): return primes_cache_bool[number] sqrt_number = sqrt(number) for prime in primes_cache_list: if prime > sqrt_number: return True if number % prime == 0: return False to_check = 2 if len(primes_cache_list) > 0: to_check = primes_cache_list[-1] + 1 while to_check <= sqrt_number: if number % to_check == 0: return False to_check += 1 return True
ec9f8c7e3475849d5647339782e2d67a68b448d2
SuxPorT/python-exercises
/Mundo 2 - Estruturas de Controle/Desafio #045.py
1,972
4.09375
4
# Crie um programa que faça o computador jogar Jokenpô com você. from random import choice from time import sleep print("\033[1;33m===" * 10) print(" " * 4, "CAMPEONATO DE JOKENPÔ") print("===" * 10) sleep(1) print(" " * 8, "\033[1;30mCOMEÇANDO EM") sleep(1) print(" " * 13, "3...") sleep(1) print(" " * 13, "2...") sleep(1) print(" " * 13, "1...\033[m") sleep(1) escolha = ["PEDRA", "PAPEL", "TESOURA"] computador = choice(escolha) print("\033[1;37m===" * 10) movimento = str(input("\033[1;37mSeu movimento: ")).upper() print("Movimento do computador: \033[1;32m{}".format(computador)) sleep(3) print("\033[1;37m===" * 10) print("\033[1;33mANALISANDO A SUA DERROTA...") print("\033[1;37m===\033[m" * 10) sleep(3) print("\033[1;34mRESULTADO: {} x {}".format(movimento, computador)) sleep(1) print("\033[1;37m===" * 10) sleep(1) if movimento == "PEDRA" and computador == "PAPEL": print("\033[1;31mO COMPUTADOR VENCEU! QUE PENA, TENTE NA PRÓXIMA!") elif movimento == "PEDRA" and computador == "TESOURA": print('\033[1;34mVOCÊ VENCEU! PARABÉNS!') elif movimento == "PAPEL" and computador == "PEDRA": print("\033[1;34mVOCÊ VENCEU! PARABÉNS!") elif movimento == "PAPEL" and computador == "TESOURA": print("\033[1;31mO COMPUTADOR VENCEU! QUE PENA, TENTE NA PRÓXIMA!") elif movimento == "TESOURA" and computador == "PEDRA": print("\033[1;31mO COMPUTADOR VENCEU! QUE PENA, TENTE NA PRÓXIMA!") elif movimento == "TESOURA" and computador == "PAPEL": print("\033[1;34mVOCÊ VENCEU! PARABÉNS!") elif movimento == computador: print("\033[1;36mEMPATE! TENTE OUTRA VEZ!") elif (movimento != "PEDRA") and (movimento != "PAPEL") and (movimento != "TESOURA"): print(" " * 2, "\033[1;31;mERRO: ESCOLHA INEXISTENTE") sleep(1) print(" " * 2, "\033[1;31;mTERMINANDO O PROGRAMA EM") sleep(1) print(" " * 13, "3...") sleep(1) print(" " * 13, "2...") sleep(1) print(" " * 13, "1...") sleep(1)
7b035471487e8e98e5ae692657d85c930d72e635
vanshamb2061/Tic-tac-toe-Files
/final.py
1,826
4.125
4
def display_board(arr): a=0 while a<3: print(f"{arr[a][0]} | {arr[a][1]} | {arr[a][2]} ") a+=1 def win_check(arr): i=0 while i<3: #to check horizontal if arr[i][0]==arr[i][1] and arr[i][1]==arr[i][2]: print(f"Row {i+1} of {arr[i][0]} formed.") return 0 i+=1 j=0 while j<3: if arr[0][j]==arr[1][j] and arr[1][j]==arr[2][j]: print(f"Column {j} of {arr[0][j]} formed.") return 0 j+=1 if arr[0][0]==arr[1][1] and arr[1][1]==arr[2][2]: print(f"Primary Diagonal formed of {arr[0][0]}.") return 0 elif arr[0][2]==arr[1][1] and arr[1][1]==arr[2][0]: print(f"Secondary Diagonal formed of {arr[1][1]}.") return 0 else: return 1 def place_marker(arr): i=1 control=1 while i<=9 and control==1: if i%2==0: ans='O' else: ans='X' import os res=int(input(f"ENTER position for entering {ans}: ")) os.system("cls") # Windows if res==1: arr[0][0]=ans elif res==2: arr[0][1]=ans elif res==3: arr[0][2]=ans elif res==4: arr[1][0]=ans elif res==5: arr[1][1]=ans elif res==6: arr[1][2]=ans elif res==7: arr[2][0]=ans elif res==8: arr[2][1]=ans elif res==9: arr[2][2]=ans display_board(arr) control=win_check(arr) if control==0: i-=1 if i%2==0: return 'O' else: return 'X' print(f"Control = {control}, Iteration : {i}") i+=1 arr=[1,2,3],[4,5,6],[7,8,9] a=0 print('\n'*100) while a<3: print(f"{arr[a][0]} | {arr[a][1]} | {arr[a][2]} ") a+=1 #displaying grid in form of numpad player1='X' player2='O' player1=input("PLAYER 1: Do you want to be X or O: ") if player1=='X': player2=='O' print("Player 1 will go first") else: player2=='X' print("Player 2 will go first") winner=place_marker(arr) if winner==player1: print("THE WINNER OF THE GAME IS PLAYER1") else: print("THE WINNER OF THE GAME IS PLAYER2")
18afc753b4f6bb7bc63fdd4d22b9517732475940
jsmolka/sandbox-python
/__modules__/utils.py
9,777
4.09375
4
def remap(x, x1, x2, y1, y2): """ Remaps a value from one range to another. :param x: value to process :param x1, x2: range of x :param y1, y2: new range :return: float """ return (x - x1) / (x2 - x1) * (y2 - y1) + y1 def sized_gen(lst, n): """ Splits a list into n-sized chunks. :param lst: list to process :param n: size of chunks :return: generator """ n = min(max(1, n), len(lst)) for idx in range(0, len(lst), n): yield lst[idx:idx + n] def sized(lst, n): """ Splits a list into n-sized chunks. :param lst: list to process :param n: size of chunks :return: list """ return list(sized_gen(lst, n)) def chunk_gen(lst, n): """ Splits a list into n equally sized chunks. :param lst: list to process :param n: amount of chunks :return: generator """ n = min(max(1, n), len(lst)) quo, rem = divmod(len(lst), n) idc = [quo * idx + min(idx, rem) for idx in range(n + 1)] for idx in range(n): yield lst[idc[idx]:idc[idx + 1]] def chunk(lst, n): """ Splits a list into n equally sized chunks. :param lst: list to process :param n: amount of chunks :return: list """ return list(chunk_gen(lst, n)) def unique_gen(lst, key=None): """ Removes duplicates from a list. :param lst: list to process :param key: key to apply :return: generator """ seen = set() if key is None: for x in lst: if x not in seen: seen.add(x) yield x else: for x in lst: value = key(x) if value not in seen: seen.add(value) yield x def unique(lst, key=None): """ Removes duplicates from a list. :param lst: list to process :param key: key to apply :return: list """ return list(unique_gen(lst, key=key)) def duplicates_gen(lst, key=None): """ Finds duplicates in a list. :param lst: list to process :param key: key to apply :return: generator """ seen = set() yielded = set() if key is None: for x in lst: if x in seen and x not in yielded: yielded.add(x) yield x else: seen.add(x) else: for x in lst: value = key(x) if value in seen and value not in yielded: yielded.add(value) yield x else: seen.add(value) def duplicates(lst, key=None): """ Finds duplicates in a list. :param lst: list to process :param key: key to apply :return: list """ return list(duplicates_gen(lst, key=key)) def compact_gen(lst, key=None): """ Removes all falsy values. :param lst: list to process :param key: key to apply :return: generator """ if key is None: for x in lst: if x: yield x else: for x in lst: if key(x): yield x def compact(lst, key=None): """ Removes all falsy values. :param lst: list to process :param key: key to apply :return: list """ return list(compact_gen(lst, key=key)) def index(lst, value, key=None): """ Finds first index of value in a list. :param lst: list to process :param value: value to search :param key: key to apply :return: int """ if key is not None: value = key(value) try: return lst.index(value) except ValueError: return -1 def apply_gen(lst, key): """ Applies a key to a list. :param lst: list to process :param key: key to apply :return: map """ return map(key, lst) def apply(lst, key): """ Applies a key to a list. :param lst: list to process :param key: key to apply :return: list """ return list(apply_gen(lst, key)) def indices_gen(lst, *values, key=None): """ Finds all indices of value in a list. :param lst: list to process :param values: values to search :param key: key to apply :return: generator """ values = set(values) if key is None: for idx, x in enumerate(lst): if x in values: yield idx else: for idx, x in enumerate(lst): if key(x) in values: yield idx def indices(lst, *values, key=None): """ Finds all indices of value in a list. :param lst: list to process :param values: values to search :param key: key to apply :return: list """ return list(indices_gen(lst, *values, key=key)) def flatten_gen(lst): """ Flattens a list. :param lst: list to process :return: generator """ for x in lst: if isinstance(x, list): yield from flatten_gen(x) else: yield x def flatten(lst): """ Flattens a list. :param lst: list to process :return: list """ return list(flatten_gen(lst)) def concat_gen(lst, *others): """ Concatenates lists. :param lst: list to process :param others: lists to concatenate :return: generator """ for x in lst: yield x for other in others: for x in other: yield x def concat(lst, *others): """ Concatenates lists. :param lst: list to process :param others: lists to concatenate :return: list """ new = lst[:] for other in others: new.extend(other) return new def union_gen(lst, *others, key=None): """ Creates the union of passed lists. :param lst: list to process :param others: lists to unionize with :param key: key to apply :return: generator """ return unique_gen(concat_gen(lst, *others), key=key) def union(lst, *others, key=None): """ Creates the union of passed lists. :param lst: list to process :param others: lists to unionize with :param key: key to apply :return: list """ return list(union_gen(lst, *others, key=key)) def difference_gen(lst, other, key=None): """ Creates the difference of passed lists. :param lst: list to process :param other: list to create difference with :param key: key to apply :return: generator """ if key is None: seen = set(other) for x in lst: if x not in seen: yield x else: seen = set(apply_gen(other, key)) for x in lst: if key(x) not in seen: yield x def difference(lst, other, key=None): """ Creates the difference of passed lists. :param lst: list to process :param other: lists to create difference with :param key: key to apply :return: list """ return list(difference_gen(lst, other, key=key)) def without_gen(lst, *values, key=None): """ Creates list without values. :param lst: list to process :param values: values to remove :param key: key to apply :return: generator """ values = set(values) if key is None: for x in lst: if x not in values: yield x else: for x in lst: if key(x) not in values: yield x def without(lst, *values, key=None): """ Creates list without values. :param lst: list to process :param values: values to remove :param key: key to apply :return: list """ return list(without_gen(lst, *values, key=key)) def first(lst, key): """ Finds first item which evaluates key to true. :param lst: list to process :param key: key to evaluate :return: item """ for x in lst: if key(x): return x def where_gen(lst, key): """ Finds all items which evaluate key to true. :param lst: list to process :param key: key to evaluate :return: generator """ for x in lst: if key(x): yield x def where(lst, key): """ Finds all items which evaluate key to true. :param lst: list to process :param key: key to evaluate :return: list """ return list(where_gen(lst, key)) def powerset_gen(lst): """ Calculates the powerset. :param lst: list to process :return: generator """ if lst: for x in powerset(lst[1:]): yield x + [lst[0]] yield x else: yield [] def powerset(lst): """ Calculates the powerset. :param lst: list to process :return: list """ return list(powerset_gen(lst)) def mask_gen(lst, *values, key=None): """ Creates a bool mask. :param lst: list to process :param values: values to mask :param key: key to apply :return: generator """ values = set(values) if key is None: for x in lst: yield x in values else: for x in lst: yield key(x) in values def mask(lst, *values, key=None): """ Creates a bool mask. :param lst: list to process :param values: values to mask :param key: key to apply :return: list """ return list(mask_gen(lst, *values, key=key)) def invert_gen(lst, key=None): """ Inverts a list. :param lst: list to process :param key: key to apply :return: generator """ if key is None: for x in lst: yield not x else: for x in lst: yield not key(x) def invert(lst, key=None): """ Inverts a list. :param lst: list to process :param key: key to apply :return: list """ return list(invert_gen(lst, key=key))
15e376cd3adb7ba42f61f9da84dde1a0ea258bc7
eur-nl/bootcamps
/zzzzz_archive/eshcc/scripts/notjustalabel/not_just_a_label.py
3,671
3.5625
4
import sys import csv import os import requests import time from bs4 import BeautifulSoup URL = 'https://www.notjustalabel.com/designers?page=%s' DETAIL_URL = 'https://www.notjustalabel.com/designer/%s' def fetch_listing_page(page_number): url = URL % page_number print('fetching listing page %s' % page_number) response = requests.get(url) if response.status_code != 200: print('Error fetching listing %s' % page_number) sys.exit(1) soup = BeautifulSoup(response.content, 'html.parser') designers = soup.find_all('div', class_='views-row') designer_urls = [] for designer in designers: url = designer.find_all('a')[-1].attrs['href'] designer_urls.append(url) return designer_urls def fetch_detail_page(page_id): print('fetching detail: %s' % page_id) url = DETAIL_URL % page_id response = requests.get(url) if response.status_code != 200: print('Error fetching detail %s' % page_id) sys.exit(1) soup = BeautifulSoup(response.content, 'html.parser') name = soup.find_all('h1')[0].text.strip() location_field = soup.find_all('div', class_='field-content')[0] city, country = [f.text for f in location_field.find_all( 'div', class_='content')] return dict(id=page_id, name=name, city=city, country=country) """ This is where the main part of program kicks in and where we should start reading. The first block starting with "if not ..." populates the file 'designers.txt' which hold the information to access the individual designers pages later on in the program. The second block starting with "writer = ..." prepares the csv file for writing content into it """ if __name__ == '__main__': if not os.path.isfile('designers.txt'): # If the file is not already there urls = [] # Initialize an empty list called 'urls' for page_number in range(402): # Loop through the range 0-402 # Calls the function above with each of the numbers from the range urls.extend(fetch_listing_page(page_number)) time.sleep(1) # Be nice to the server: One call per second # Write the results of the calls to the file open('designers.txt', 'w').write('\n'.join(urls)) writer = csv.writer(open('designers.csv', 'w')) # Prepare the output file # Names of the columns in the csv file in a list called 'cols' cols = ['id', 'name', 'city', 'country'] writer.writerow(cols) # Write the header to the file # The next line uses the result of the first function stored in the file # designers.txt in a list of urls (one per line) detail_urls = open('designers.txt').read().splitlines() count = 0 # Initialze a variable called count and set it to 0 # Loop, we use one url at a time from our list detail_urls for url in detail_urls: # We call our second function defined above passing in the last part # of the URL we scraped using our first function. We collect the # results in a variable 'details' that we use underneath to fill in # the rows of the csv file. # The actual contents of details is the dict or dictionary returned # by our second function. details = fetch_detail_page(url.split('/')[-1]) time.sleep(1) # Always be nice to the server at the other end # Here we fill the rest of the csv file we setup earlier row = [] for col in cols: row.append(details[col].encode('utf8')) writer.writerow(row) # Just for the workshop, you would want all the results count += 1 if count == 10: break
d0ed45022cf7c2a9ba59a9752cb0ef6d4033a127
RohanAwhad/ValorantBot
/listener.py
977
3.671875
4
from pynput import mouse, keyboard class Listener(): def start(self): self.listener.start() def stop(self): self.listener.stop() class Mouse(Listener): def __init__(self): self.listener = mouse.Listener( on_move=self.on_move, on_click=self.on_click, on_scroll=self.on_scroll) def on_move(self, x, y): print(f'Moved to: ({x}, {y})') def on_click(self, x, y, button, pressed): pressed = 'Pressed' if pressed else 'Released' print(f'{pressed} {button} at ({x}, {y})') def on_scroll(self, x, y, dx, dy): print(f'Scrolled {(dx, dy)} at {(x, y)}') class Keyboard(Listener): def __init__(self): self.listener = keyboard.Listener( on_press=self.on_press, on_release=self.on_release) def on_press(self, key): print(f'{key} pressed') def on_release(self, key): print(f'{key} released')
8ef4bacbdf0fa9f52acac15ec5c8de875a7bbd8c
thoufeeqhidayath/pythonExample
/graphss.py
2,756
3.828125
4
class Vertex: def __init__(self, name,edges={}): self.name = name self.edges = edges def add_edge(self,name): if name not in self.edges: self.edges[name] = 1 else: self.edges[name] = self.edges[name] + 1 def add_edges(self,edges): for name in edges: if name not in self.edges: self.edges[name] = edges[name] else: self.edges[name] = self.edges[name] + edges[name] class Graph: def __init__(self, vertices={}): self.vertices = vertices # Get the keys of the dictionary def get_vertices(self): return list(self.vertices.keys()) def get_edges(self): return self.find_edges() def find_edges(self): output = {} for vertex in self.vertices: for edge in self.vertices[vertex].edges: count = 0 if edge in output: count = output[edge] output[edge] = self.vertices[vertex].edges[edge] + count return output # Add the vertex as a key def add_vertex(self, vertex_name): if vertex_name not in self.vertices: self.vertices[vertex_name] = Vertex(vertex_name,{}) def add_edge(self, fromVertex,toVertex): if fromVertex not in self.vertices: self.vertices[fromVertex] = Vertex(fromVertex,{}) self.vertices[fromVertex].add_edge(toVertex) def log(self): print("-----------graph--------------") for vertex in self.vertices: print vertex,self.vertices[vertex].edges print self.vertices['a'].edges.keys() def logs(self): graph={} for vertex in self.vertices: graph[vertex]=self.vertices[vertex].edges return graph def get_the_graph(self): graph = {} for vertex in self.vertices: graph[vertex] = self.vertices[vertex].edges return graph def get_the_vertex(self): vertex_list=[] for vertex in self.vertices: vertex_list.append(vertex) return vertex_list def vertex_more_two(self): vertex_list =self.get_the_vertex() return vertex_list def get_edges_of_vertex(self,vertex): return self.vertices[vertex].edges.keys() def get_the_key_of_vertex(self): keys={} for vertex in self.get_the_vertex(): keys[vertex] = self.get_edges_of_vertex(vertex) print keys print keys['c'] print self.vertices['a'].edges[(keys['a'])[1]] def get_the_key_of_vertex(self,vertex): keyss = [] keyss.append(self.get_edges_of_vertex(vertex)) print (keyss[0])[0]
2258c049617f1fbdf17defbf16edbbb5c9ad05b0
ar-dragan/instructiunea-FOR
/1.4.py
109
3.90625
4
n = int(input("Introduceti un numar natural ")) for i in range(1,n): if i % 2 == 1: print(i)
ef1fcc7af4cb1ccc6fb11781a2063941641737df
StuartBarnum/Twitter-Sentiment-Analysis
/tweet_sentiment.py
1,020
3.859375
4
import sys import json #Five minutes of the the worldwide twitterstream parsed with JSON and placed in #a Python dictionary #Estimates the sentiment of each tweet in the stream (output.txt), based on a file #listing sentiments associated with English language words (AFINN-111.txt). #Run with the command: # python tweet_sentiment.py AFINN-111.txt output.txt path = "/Users/stuartbarnum/Desktop/Coursera/datasci_course_materials/assignment1" afinnfile = open(sys.argv[1]) twitter_file = open(sys.argv[2]) scores = {} # initialize an empty dictionary for line in afinnfile: term, score = line.split("\t") # The file is tab-delimited. "\t" means "tab character" scores[term] = int(score) # Convert the score to an integer. for line in twitter_file: if "text" in json.loads(line): twitter_text = json.loads(line)["text"] sentiment = 0 for word in twitter_text.split(): if word in scores: sentiment = sentiment + scores[word] print sentiment
f25828fa70fea0d29575525065334980caf559a4
FundingCircle/DjanGoat
/app/tests/mixins/model_crud_test_mixin.py
2,900
3.65625
4
class ModelCrudTests(object): """Mixin for testing CRUD functionality of models. self.model is the model created locally and saved to the database self.attributes is a string array of the names of the attributes of the model self.model_update_input is the new value that model_update_attribute is being set to self.parent is the model's parent object, to which it has a foreign key and a cascade on delete self.parent is None if the object has no parent """ def test_create_model(self): """ Makes sure the model was created and put in the database """ self.assertNotEqual(self._get_from_db(self.model), None) def test_read_model(self): """ Makes sure that the model can be read from the database """ for attribute in self.attributes: db_value = getattr(self._get_from_db(self.model), attribute) local_value = getattr(self.model, attribute) if isinstance(db_value, bytes): db_value = db_value.decode() if isinstance(local_value, bytes): local_value = local_value.decode() self.assertEqual(db_value, local_value) def test_update_model(self): """ Makes sure the model can be updated in the database by doing the following steps: 1. Sets the attribute of the local model 2. Saves the change to the database 3. Asserts that the changed attribute is the same in the local model and the updated database model """ update_attribute = self.attributes[self.model_update_index] setattr(self.model, update_attribute, self.model_update_input) self.model.save() self.assertEqual( getattr(self.model, update_attribute), getattr(self._get_from_db(self.model), update_attribute) ) def test_delete_model(self): response = self.model.delete() num_objects_deleted = response[0] # 1 object deleted from database self.assertEqual(num_objects_deleted, 1) # PTO with primary key matching the deleted pto's primary key no longer in database self.assertEqual(self._get_from_db(self.model), None) def test_delete_user_and_pto(self): """Test to ensure Model is deleted when its parent is deleted. """ if self.parent is not None: self.parent.delete() self.assertIsNone(self._get_from_db(self.parent), "Parent not deleted from the database") self.assertIsNone(self._get_from_db(self.model), "Model not deleted from database with cascade") else: pass @staticmethod def _get_from_db(model): """Helper method to get the model from the database""" return model.__class__.objects.filter(pk=model.pk).first()
4782796680ed022e441cabfcbc403a39a95b7cbd
MafiaAlien/python-learning-projects
/Python Crash course/Chapter 10 try and except/division.py
461
4.09375
4
# try: # print(5/0) # except ZeroDivisionError: # print('You cannot divide by zero') print('Give me two numbers, and I will divide them') print("Enter 'q' to quit.") while True: first_number = input("\nFirst number: ") if first_number == 'q': break second_number = input("Second number: ") try: anwser = int(first_number) / int(second_number) except ZeroDivisionError: print('You cannot divide by zero') else: print(anwser)
67fa6f5ec39eedab4070b5e70520546371cd4372
Jerinca/DataProcessing
/Homework/Week_3/convertCSV2JSON.py
2,105
3.609375
4
#!/usr/bin/env python # Name: Jerinca Vreugdenhil # Student number: 12405965 """ This script converts a CSV file with information about ....... to a json file. https://catalog.data.gov/dataset?tags=winning """ import csv import pandas as pd import numpy as np from bs4 import BeautifulSoup import matplotlib.pyplot as plt INFORMATION = 'AAPL.csv' print(INFORMATION) def open_csv(file): stock_information = [] # open csv file with open(file) as csvfile: # read in file as dictionary datareader = csv.DictReader(csvfile) # for every row in data reader for row in datareader: # create space for a dictionary dictionary = {} # add information to dictionary dictionary['Date'] = row['Date'] dictionary['Open'] = row['Open'] dictionary['High'] = row['High'] dictionary['Low'] = row['Low'] dictionary['Close'] = row['Close'] dictionary['Adj Close'] = row['Adj Close'] dictionary['Volume'] = row['Volume'] # append everything to a list stock_information.append(dictionary) return stock_information def open_file(file): df = pd.DataFrame.from_dict(file) df['Close'] = df['Close'].astype(float) return df def plot_histogram(df): # if graph is being plotted use this style plt.style.use('seaborn-darkgrid') # plot a histogram with the GDP data and set a title, x-label, y-label hist_plot = df['Close'].hist(bins=50, color = "pink") hist_plot.set_title('Closing price AAPL stock') hist_plot.set_xlabel('Date') hist_plot.set_ylabel('Frequency') plt.show() def plot_line_chart(df): # if graph is being plotted use this style plt.style.use('seaborn-darkgrid') x = df['Date'] y = df['Close'] plt.plot(x, y) plt.show() def write_jason(df): """ writes the dataframe to a json file """ # set Country as index of dataframe df = df.set_index('Date') # write datafram to jason file df = df.to_json('appleclose.json', orient='index') if __name__ == "__main__": information = open_csv(INFORMATION) opened = open_file(information) histogram = plot_histogram(opened) linechart = plot_line_chart(opened) winning = write_jason(opened)
1df71cb285593064d11da6ee20e66b234f766d11
marcinpgit/Python_exercises
/Exercises_1/continue break.py
204
3.765625
4
count = 0 while True: count += 1 if count > 10: break if count == 5: continue print (count) input ("\nNaciśnij klawisz enter aby zakończyć.")
707f4ab05837eeb7ed435d672efb45b7952866af
Team2537/spaceRAID
/video_loader.py
9,250
3.625
4
""" Use a video library to get, edit, and save video. The api for this library is as follows. Video(source) """ __author__ = "Matthew Schweiss" __version__ = "0.5" # TODO # Add the meanings of various return codes. __all__ = ["Video", "load_image", "save_image", "show_image", "close_image"] import os import logging import warnings # Get whatever library is avalible. try: basestring except NameError: try: basestring = (str, unicode) except NameError: basestring = str # Actually, dispite the point of this module, we need both cv2 AND ffmpeg. # So don't bother the redundancy. import cv2 #import ffmpeg def load_image(path): """Load the image from file.""" # First make sure the source exists. if not os.path.exists(path): raise ValueError("Image at %r does not exists." % path) return cv2.imread(path) def save_image(image, destination): """Save the image to a file.""" return cv2.imwrite(os.path.abspath(source), image) def show_image(image, title = "Video"): """Display an image on the screen if possible.""" # First, make sure image is not None if image is None: raise TypeError("Image must be a cv2 image, not None") try: cv2.imshow(title, image) if cv2.waitKey(1) & 0xFF == ord('q'): pass except cv2.error: # Problem with running in the terminal. # cv2.error: /tmp/opencv3-20170409-67121-nwgnzg/opencv-3.2.0/modules # /highgui/src/window.cpp:304: error: (-215) size.width>0 && size.he # ight>0 in function imshow # Will not show up at all. msg = "Error displaying images. cv2.error when running in terminal." logging.error(msg) warnings.warn(RuntimeWarning(msg), stacklevel = 2) def close_image(image = None): """Closes windows with images in them.""" if image is None: cv2.destroyAllWindows() # If image is a string, destroy window with that name. elif isinstance(image, basestring): cv2.destroyWindow(image) else: # Was not string raise RuntimeError("Image must be the name of a window displaying" " or None, not %r." % image) class Video(): """A wrapper class for cv2 and ffmpeg of video processing.""" __all__ = ['close', 'closed', 'get_fps', 'get_frame', 'get_frame_index', 'get_frame_height', 'get_frame_width', 'get_progress', 'get_timestamp', 'name', 'path', 'set_frame_index', 'set_progress', 'set_timestamp', 'get_frame_count'] def __init__(self, source): self.path = os.path.normpath(source) self.name = os.path.basename(self.path) self.cap = cv2.VideoCapture(self.path) # If the path is bunk and bogus, cap.isOpened() # will return False now. if not self.cap.isOpened(): # Bad file. raise ValueError( "The path %r is not a readable video file." % source) # Also, check the source. if not os.path.exists(self.path): # Bad file. raise ValueError( "The path %r is not a readable video file." % source) def __repr__(self): return "Video(%r)" % self.path def __iter__(self): """Go through the frames.""" while not self.closed(): # Open frame = self.get_frame() if frame is None: break yield frame # Close cause we are done. self.close() #Current position of the video file in #milliseconds or video capture timestamp. def get_timestamp(self): """Get the position in the video in milliseconds.""" return self.cap.get(cv2.CAP_PROP_POS_MSEC) def set_timestamp(self, timestamp): """Set the position in the video in milliseconds. Returns a status code.""" # Add status meaning. return self.cap.set(cv2.CAP_PROP_POS_MSEC, timestamp) #0-based index of the frame to be decoded/captured next. def get_frame_index(self): """Get the number of frames that have passed.""" return self.cap.get(cv2.CAP_PROP_POS_FRAMES) def set_frame_index(self, frame_count): """Set the number of frames that have passed. Returns a status code.""" # Add status meaning. if frame_count < 0: frame_count = 0 return self.cap.set(cv2.CAP_PROP_POS_FRAMES, frame_count) #Relative position of the video file: #0 - start of the film, 1 - end of the film. def get_progress(self): """Get the percentage that is passed (0 to 1).""" return self.cap.get(cv2.CAP_PROP_POS_AVI_RATIO) def set_progress(self, progress): """Set the percentage that is passed (0 to 1). Returns a status code.""" # Add status meaning. return self.cap.set(cv2.CAP_PROP_POS_AVI_RATIO, progress) #Width of the frames in the video stream. def get_frame_width(self): """Get the width of the frames.""" # Change to an integer as it should be. return int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)) #Height of the frames in the video stream. def get_frame_height(self): """Get the height of the frames.""" # Change to an integer as it should be. return int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) #Frame rate. Frames Per Second def get_fps(self): """Get the frames per second speed of the video.""" return self.cap.get(cv2.CAP_PROP_FPS) #Number of frames in the video file. def get_frame_count(self): """Get the number of frames in the video file.""" # passed as a float but has no buisness being a float. return int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) # Codes that I did not include. # More complicated than I need. cv2.CAP_PROP_FOURCC #4-character code of codec. cv2.CAP_PROP_CONVERT_RGB #Boolean flags indicating whether images should be converted to RGB. cv2.CAP_PROP_FORMAT #Format of the Mat objects returned by retrieve(). cv2.CAP_PROP_MODE #Backend-specific value indicating the current capture mode. # Camera settings only. cv2.CAP_PROP_BRIGHTNESS #Brightness of the image (only for cameras). cv2.CAP_PROP_CONTRAST #Contrast of the image (only for cameras). cv2.CAP_PROP_SATURATION #Saturation of the image (only for cameras). cv2.CAP_PROP_HUE #Hue of the image (only for cameras). cv2.CAP_PROP_GAIN #Gain of the image (only for cameras). cv2.CAP_PROP_EXPOSURE #Exposure (only for cameras). # Only supported the DC1394 v 2.x backend # These first two don't seem present. That is why they are commented out. #cv2.CAP_PROP_WHITE_BALANCE_U #The U value of the whitebalance setting (note: only supported by DC1394 v 2.x backend currently) #cv2.CAP_PROP_WHITE_BALANCE_V #The V value of the whitebalance setting (note: only supported by DC1394 v 2.x backend currently) cv2.CAP_PROP_RECTIFICATION #Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently) cv2.CAP_PROP_ISO_SPEED #The ISO speed of the camera (note: only supported by DC1394 v 2.x backend currently) cv2.CAP_PROP_BUFFERSIZE #Amount of frames stored in internal buffer memory (note: only supported by DC1394 v 2.x backend currently) def get_frame(self): """Read the next frame.""" ret, frame = self.cap.read() if ret: return frame return None def grab_frame(self): """Read the next frame but don't advance.""" ret, frame = self.cap.retrieve() if ret is False: raise RuntimeError("No frame to return.") return frame def closed(self): """Return if the video file is closed.""" return not self.cap.isOpened() def close(self): """Close the file and release the resources.""" self.cap.release() def test(): global video video = Video('Examples/Saturday 3-11-17_ND.mp4') print("Width: %s\tHeight:\t%s" % (video.get_frame_width(), video.get_frame_height())) try: while not video.closed(): frame = video.get_frame() if frame is not None: cv2.imshow('Video', frame) else: break if cv2.waitKey(1) & 0xFF == ord('q'): break except KeyboardInterrupt: print("KeyboardInterrupt") finally: video.close() cv2.destroyAllWindows() # elif ffmpeg: # For ffmpeg compatability it should be possible to use the code found at # https://github.com/Zulko/moviepy/blob/master/moviepy/video/io/ffmpeg_reader.py # https://github.com/dschreij/opensesame-plugin-media_player_mpy/ # These should be enough to make everything work with ffmpeg, though not well. # That said. I am not taking the time now to build the ffmpeg support out. # Also, look the libraries opensesame-plugin-media_player_mpy, mediadecoder, # and moviepy if __name__ == '__main__': test()
219db4f664be921bce204400e8ecaa1028505a3c
tsutaj/deep-learning-lecture
/code/lib/perceptron.py
1,681
3.53125
4
# -*- coding: utf-8 -*- import numpy as np ## @package perceptron # @brief Chapter 2: Basic digital logic gates # @author tsutaj # @date November 6, 2018 ## @brief Calculate \f$x_1\f$ \f$\mathrm{AND}\f$ \f$x_2\f$ # @param x1 boolean # @param x2 boolean # @return boolean \f$x_1\f$ \f$\mathrm{AND}\f$ \f$x_2\f$ def AND(x1, x2): x = np.array([x1, x2]) w = np.array([0.5, 0.5]) b = -0.7 if np.sum(w * x) + b <= 0: return 0 else: return 1 ## @brief Calculate \f$x_1\f$ \f$\mathrm{OR}\f$ \f$x_2\f$ # @param x1 boolean # @param x2 boolean # @return boolean \f$x_1\f$ \f$\mathrm{OR}\f$ \f$x_2\f$ def OR(x1, x2): x = np.array([x1, x2]) w = np.array([0.5, 0.5]) b = -0.2 if np.sum(w * x) + b <= 0: return 0 else: return 1 ## @brief Calculate \f$x_1\f$ \f$\mathrm{NAND}\f$ \f$x_2\f$ # @param x1 boolean # @param x2 boolean # @return boolean \f$x_1\f$ \f$\mathrm{NAND}\f$ \f$x_2\f$ def NAND(x1, x2): x = np.array([x1, x2]) w = np.array([-0.5, -0.5]) b = 0.7 if np.sum(w * x) + b <= 0: return 0 else: return 1 ## @brief Calculate \f$x_1\f$ \f$\mathrm{XOR}\f$ \f$x_2\f$ # @param x1 boolean # @param x2 boolean # @return boolean \f$x_1\f$ \f$\mathrm{XOR}\f$ \f$x_2\f$ # @note XOR gate takes non-linear region, so you cannot describe it using only single perceptron. The combination of AND / OR / NAND gate enables you to describe this gate (2-layered perceptron). def XOR(x1, x2): s1 = NAND(x1, x2) s2 = OR(x1, x2) return AND(s1, s2)
2bf138067dc6eba2101f975995c2d0d531e1f915
maomao905/algo
/minimum-size-subarray-sum.py
894
3.640625
4
""" sum = 7, [2,3,1,2,4,3] two pointers 2,3,1 x 2,3,1,2 -> 3,1,2 x 3,1,2,4 -> 1,2,4 x 1,2,4,3 -> x 2,4,3 -> 4,3 time: O(n) space: O(1) """ from typing import List class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: start = 0 end = 0 min_length = float('inf') tmp_sum = 0 while end < len(nums): if tmp_sum + nums[end] < s: tmp_sum += nums[end] end += 1 else: tmp_sum -= nums[start] min_length = min(min_length, end-start+1) start += 1 # print(start, end, tmp_sum) if min_length == float('inf'): return 0 return min_length s = Solution() # print(s.minSubArrayLen(7, [2,3,1,2,4,3])) # print(s.minSubArrayLen(11, [1,2,3,4,5])) print(s.minSubArrayLen(15, [1,2,3,4,5]))
ff9824b23265ecdec11be9e3179844a23f70e1a9
Nev-Iva/my-projects
/basic python (0 level)/1 intro/2.py
302
3.609375
4
while True: user_inp = int(input('Введите число: ')) if (user_inp < 10) and (user_inp > 0): break else: print('Введите число от 0 до 10') user_inp = user_inp ** 2 print('Ваше число во второй степени: {0}'.format(user_inp))
1c8988521d98ee0021bea51ac506789f0f8579bd
stewartt1982/jupyter2python
/jupyter2python.py
1,521
3.59375
4
# # A small program to extract source code from Jupyter files # and output it to a text python .py file # import sys import argparse import json from os.path import basename from os.path import splitext def main(): #create and define the command line argument parser parser = argparse.ArgumentParser(description='Convert Jupyter JSON file to python .py file') parser.add_argument('inputfile',metavar='inputfile',type=str,nargs='+', help='input source file(s)') #add this feature later #parser.add_argument('--d',help='create new file in the same directory as inputfile') args = parser.parse_args() print args #args.inputfile will have our input files for f in args.inputfile: #open source, we really should check if it exists but will add later fp = open(f,"r") #open output file base = basename(f) ofname = str(splitext(base)[0]) + ".py" of = open(ofname,"w") readJSON = json.loads(fp.read().decode('utf-8')) #check nbformat, two different ways to extract the python source if readJSON["nbformat"] >= 4: #we want to look at cells or cell_type "code" for cell in readJSON["cells"]: if str(cell["cell_type"])=="code": for line in cell["source"]: of.write(line.encode('ascii', 'ignore').decode('ascii')+"\n") fp.close() of.close() if __name__ == "__main__": main()
cb89354abcddcf3c8d703b709132b21137027e19
yangyi1102/Python
/Python/python数据学习/折线图1.py
204
3.875
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 18 18:58:33 2017 @author: 17549 """ import matplotlib.pyplot as plt plt.plot([0,2,4,5,8],[3,1,4,5,2]) plt.ylabel("Grade") plt.axis([-1,10,0,6]) plt.show()
7ea74122bed261731ae9eb47aa405808afe7b2a7
kritikyadav/Practise_work_python
/pattern/pattern23.py
136
3.703125
4
n=int(input('enter the nu. of rows= ')) for i in range(n,0,-1): for j in range(1,i+1): print(n-i+1,end='') print()
f2fa45d2cce67f873c05d9362e64bb4619553880
jeremymiller00/email_marketing
/src/campaign_performance.py
3,079
3.5
4
import numpy as np import pandas as pd import seaborn as sns sns.reset_defaults sns.set_style(style='darkgrid') import matplotlib.pyplot as plt plt.style.use('ggplot') font = {'size' : 16} plt.rc('font', **font) plt.ion() plt.rcParams["patch.force_edgecolor"] = True plt.rcParams["figure.figsize"] = (20.0, 10.0) pd.set_option('display.max_columns', 2000) pd.set_option('display.max_rows', 2000) # quantity clicked from each country def qty_by_feature(df, columns): ''' Prints a series of bar charts displaying the qunatity of users who clicked on a link in a marketing email by feature. Useful for identifying which features lead to a user clicking on the link. Parameters: ---------- input {dataframe, list}: dataframe of users and click data, list of features to plot on output {plots}: a series of barplots representing the quantity of users who clicked in each features category ''' for column in columns: percents = {} for item in df[column].unique(): pct = df[df[column] == item]['clicked'].sum() / df[df[column] == item].shape[0] percents[item] = pct fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12,4)) ax[0].bar(x=df[column].value_counts().index, height=df[column].value_counts().values, color="orange") ax[0].set_title("Users who Received Email by {}".format(column)) ax[0].set_xlabel("Value") ax[0].set_ylabel("Qty") ax[1].bar(x=df[df['clicked'] == 1][column].value_counts().index, height=df[df['clicked'] == 1][column].value_counts().values, color="blue", alpha=0.8) ax[1].set_title("Users Who Clicked by {}".format(column)) ax[1].set_xlabel("Value") ax[1].set_ylabel("Clicked") plt.tight_layout() plt.show() def pct_by_feature(df, columns): ''' Prints a series of bar charts displaying the percents of users who clicked on a link in a marketing email by feature. Useful for identifying which features lead to a user clicking on the link. Parameters: ---------- input {dataframe, list}: dataframe of users and click data, list of features to plot on output {plots}: a series of barplots representing the percentage of users who clicked in each features category ''' for column in columns: percents = {} for item in df[column].unique(): pct = df[df[column] == item]['clicked'].sum() / df[df[column] == item].shape[0] percents[item] = pct plt.figure(figsize=(8,4)) plt.bar(x=percents.keys(), height=percents.values(), color="blue", alpha=0.7) plt.title("Pct Who Clicked by {}".format(column)) plt.xlabel("Value") plt.ylabel("Qty") plt.tight_layout() plt.show() #################################################################### if __name__ == "__main__": df = pd.read_csv('data/joined_data.csv') cols = ['email_text', 'email_version', 'hour', 'weekday', 'user_country', 'user_past_purchases'] pct_by_feature(df, cols)
4c2e6db8107407f218be0ab3f5759f0847d50207
huangsam/ultimate-python
/ultimatepython/advanced/mocking.py
3,632
3.9375
4
""" Mocking objects is a common strategy that developers use to test code that depends on an external system or external resources for it to work properly. This module shows how to use mocking to modify an application server so that it is easier to test. """ from collections import Counter from unittest.mock import MagicMock, PropertyMock, patch # Module-level constants _COUNTER = Counter(pid=1) _START_SUCCESS = "success" _START_FAILURE = "failure" _PROTOCOL_HTTP = "http" _PROTOCOL_HTTPS = "https" _FAKE_BASE_URL = f"{_PROTOCOL_HTTPS}://www.google.com:443" _FAKE_PID = 127 class AppServer: """Application server. Normally we don't mock an application server because it is the runtime environment (AKA central nervous system) for business logic, database endpoints, network sockets and more. However, this server definition is lightweight, so it's okay to mock this. """ def __init__(self, host, port, proto): self._host = host self._port = port self._proto = proto self._pid = -1 @property def endpoint(self): """Get application server endpoint URL.""" return f"{self._proto}://{self._host}:{self._port}" @property def pid(self): """Get application server process ID.""" return self._pid @property def started(self): """Check if application server is started.""" return self.pid > 0 def start(self): """Start application server.""" if self.started: return _START_FAILURE self._pid = _COUNTER["pid"] _COUNTER["pid"] += 1 return _START_SUCCESS class FakeServer(AppServer): """Subclass parent and fake some routines.""" @property def endpoint(self): """Mock output of endpoint URL.""" return _FAKE_BASE_URL @property def pid(self): """Mock output of process ID.""" return _FAKE_PID def main(): # This is the original class instance and it works as expected app_server = AppServer("localhost", 8000, _PROTOCOL_HTTP) assert app_server.endpoint == f"{_PROTOCOL_HTTP}://localhost:8000" assert app_server.start() == _START_SUCCESS assert app_server.started is True assert app_server.start() == _START_FAILURE # But sometimes we cannot test the finer details of a class because # its methods depend on the availability of external resources. This # is where mocking comes to the rescue. There are a couple approaches # that developers use when it comes to mocking # Approach 1: Use a `MagicMock` in place of a real class instance mock_server = MagicMock() assert isinstance(mock_server, MagicMock) assert isinstance(mock_server.start_server(), MagicMock) mock_server.start_server.assert_called() mock_server.endpoint.assert_not_called() # Approach 2: Patch a method in the original class with patch.object(AppServer, "endpoint", PropertyMock(return_value=_FAKE_BASE_URL)): patch_server = AppServer("localhost", 8080, _PROTOCOL_HTTP) assert isinstance(patch_server, AppServer) assert patch_server.endpoint == _FAKE_BASE_URL assert patch_server.started is False assert patch_server.start() == _START_SUCCESS # Approach 3: Create a new class that inherits the original class fake_server = FakeServer("localhost", 8080, _PROTOCOL_HTTP) assert isinstance(fake_server, AppServer) assert fake_server.endpoint == _FAKE_BASE_URL assert fake_server.started is True assert patch_server.start() == _START_FAILURE if __name__ == "__main__": main()
7ac36dea25b90d6afdba8be81972f010ebba4e46
yinhuax/leet_code
/datastructure/binary_tree/BuildTree.py
1,842
3.828125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Mike # @Contact : 597290963@qq.com # @Time : 2021/1/31 14:49 # @File : BuildTree.py from typing import List from datastructure.binary_tree import TreeNode class BuildTree(object): def __init__(self): pass def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: """ 数组赋值方式,简单,但是时间复杂度高 :param inorder: :param postorder: :return: """ assert len(inorder) == len(postorder) if len(inorder) == 0: return None if len(inorder) == 1: return TreeNode(inorder[0]) root = TreeNode(postorder[-1]) pos = inorder.index(postorder[-1]) root.left = self.buildTree(inorder[:pos], postorder[:pos]) root.right = self.buildTree(inorder[pos + 1:], postorder[pos:-1]) return root def buildTree1(self, inorder: List[int], postorder: List[int]) -> TreeNode: """ 计算下标方式,使用左右子树在中序,后序遍历中长度一致原理,计算下标 :param inorder: :param postorder: :return: """ def my_buildTree(i_start, i_end, p_start, p_end): if i_start > i_end or p_start > p_end: return None if i_start == i_end or p_start == p_end: return TreeNode(inorder[i_start]) node = TreeNode(postorder[p_end]) pos = inorder.index(postorder[p_end]) node.left = my_buildTree(i_start, pos - 1, p_start, p_start + (pos - 1 - i_start)) node.right = my_buildTree(pos + 1, i_end, p_start + (pos - 1 - i_start) + 1, p_end - 1) return node return my_buildTree(0, len(inorder) - 1, 0, len(postorder) - 1)
46a86378ae9e24cf158907fb3351246135b9459a
sebastian-chang/gaming_practice
/graphics/graphics.py
2,143
3.875
4
import pygame, sys from pygame.locals import * # Set up pygame pygame.init() # Set up the window. window_surface = pygame.display.set_mode((500, 400), 0, 32) pygame.display.set_caption('Hello World!') # Set up the colors. BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) # Set up the fonts basic_font = pygame.font.Font(None, 48) # Set up the text text = basic_font.render('Hello World!', True, WHITE, BLUE) text_rect = text.get_rect() text_rect.centerx = window_surface.get_rect().centerx text_rect.centery = window_surface.get_rect().centery # Draw the white background onto the surface window_surface.fill(WHITE) # Draw a green polygon onto the surface # surface, color, (x, y) points for each corner of polygon pygame.draw.polygon(window_surface, GREEN, ((146, 0), (291, 106), (236, 277), (56, 277), (0, 106))) # Draw some blue lines onto the surface # surface, color, (starting point), (end point), line thickness pygame.draw.line(window_surface, BLUE, (60, 60), (120, 60), 4) pygame.draw.line(window_surface, BLUE, (120, 60), (60, 120)) pygame.draw.line(window_surface, BLUE, (60, 120), (120, 120), 4) # Draw a blue circle onto the surface # surface, color, (center point), radius of circle, fill of circle pygame.draw.circle(window_surface, BLUE, (300, 50), 20, 0) # Draw a red ellipse onto the surface # surface, color, (left, top, width, height) of ellipse, line thickness pygame.draw.ellipse(window_surface, RED, (300, 250, 40, 80), 1) # Draw the text's background rectangle onto the surface # surface, color, (left, top *corner of rect*, width, height) pygame.draw.rect(window_surface, RED, (text_rect.left - 20, text_rect.top - 20, text_rect.width + 40, text_rect.height + 40)) # Get a pixel array of the surface pixal_array = pygame.PixelArray(window_surface) pixal_array[480][360] = BLACK del pixal_array # Draw the text onto the surface window_surface.blit(text, text_rect) # Draw the window onto the screen pygame.display.update() # Run the game loop while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit()
0f08d83910ae7174c4d10b268142d36e2086c8d5
brianchiang-tw/leetcode
/No_0746_Min Cost Climbing Stairs/min_cost_climbing_stairs_bottom_up_dp.py
1,904
4.21875
4
''' Description: On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1. Example 1: Input: cost = [10, 15, 20] Output: 15 Explanation: Cheapest is start on cost[1], pay that cost and go to the top. Example 2: Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] Output: 6 Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3]. Note: cost will have a length in the range [2, 1000]. Every cost[i] will be an integer in the range [0, 999]. ''' from typing import List class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: # +1 for destination with cost 0 size = len(cost)+1 min_cost = [None] * ( size ) min_cost[0] = cost[0] min_cost[1] = cost[1] for i in range(2, size): if i != size-1: min_cost[i] = min( min_cost[i-1], min_cost[i-2] ) + cost[i] else: min_cost[i] = min( min_cost[i-1], min_cost[i-2] ) return min_cost[size-1] # n : the length of input cost list ## Time Complexity: O( n ) # # The overhead in time is the for loop iterating from 2 to size, which is of O( n ) ## Space Complexity: O( n ) # # The overhead in space is to maintain a min-cost table, which is of O( n ) def test_bench(): test_data = [ [10, 15, 20], [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] ] # expected output: ''' 15 6 ''' for cost_table in test_data: print( Solution().minCostClimbingStairs(cost_table) ) return if __name__ == '__main__': test_bench()
abfeb81c8b34febb1b0976f11b0fb4b979348be7
pacis32/Data-Structure-and-Algorithm-Problem-Solutions
/LeetCode/HashMaps/UniqueNumberOfOccurences.py
566
3.65625
4
# Given an array of integers arr, write a function # that returns true if and only if the number of # occurrences of each value in the array is unique. class Solution: def uniqueOccurrences(self, arr: List[int]) -> bool: hashMap = dict() for i in arr: if i in hashMap: hashMap[i] += 1 else: hashMap[i] = 1 hashSet = set() for key, value in hashMap.items(): if value in hashSet: return False hashSet.add(value) return True
1311f8d9d63381baabec86ea616bbdac5ee2a70a
Orderlee/SBA_STUDY
/0904/13_variantArgs02.py
332
4.03125
4
# minval: 튜플 요소에서 가장 큰 수와 가장 작은 수를 반환하는 함수 만들기 # def minval(*args): # mymin= min(args) # mymax= max(args) # # return mymin,mymax def minval(*args): mylist=[item for item in args] mylist.sort() return mylist[0],mylist[-1] print(minval(3, 5, 8, 2)) #(2,8)
0fcd15a57ce297ae1c4180228c61aaeaa3b74fe1
wanjikum/day1
/fizzbuzz/fizzbuzz.py
309
4.21875
4
"""A program implements the fizzbuzz app""" def fizz_buzz(arg): """A function that tests if the number is divisible by 3 and 5""" if arg%3 == 0 and arg%5 == 0: return 'FizzBuzz' elif arg%5 == 0: return 'Buzz' elif arg%3 == 0: return 'Fizz' else: return arg
ccd1caa37a4bece2e682dff772becc85ddff017f
nchlswtsn/Learn
/ex22.py
424
3.71875
4
REFRAIN = ''' {} bottles of beer on the wall, {} bottles of beer, take one down, pass it around, {} bottles of beer on the wall! ''' bottles_of_beer = 99 while bottles_of_beer >= 1: print REFRAIN.format(bottles_of_beer, bottles_of_beer, bottles_of_beer - 1) bottles_of_beer -= 1 print """1 bottle of beer on the wall, 1 bottle of beer, take it down, pass it around, no more bottles of beer on the wall! """
521b0df7981136e84e99c560ef188fbaa740bdb9
xdzhang-ai/MLInAction
/regression/baoyu.py
2,069
3.625
4
""" 鲍鱼年龄预测 2020-05-09 15:30:03 """ import numpy as np from regression import lwlr_test, load_data def square_error(y, y_s): """ 计算均方误差 :param y: :param y_s: :return: """ return sum((y - y_s)**2) def ridge_regres(data, labels, lam=0.2): """ 岭回归 :param data: :param labels: :param lam: 岭回归系数λ :return: """ n = data.shape[1] xtx = data.T @ data xtx = xtx + lam * np.eye(n) if np.linalg.det(xtx) == 0: print("矩阵不可逆") return -1 w = np.linalg.inv(xtx) @ data.T @ labels return w def ridge_test(x, y): """ 岭回归测试 :param x: :param y: :return: """ # 数据标准化 y_mean = y.mean() y = y - y_mean x_mean = x.mean(0) x_var = x.var(0) x = (x - x_mean) / x_var num_lam = 30 w_mat = np.zeros((num_lam, x.shape[1])) for i in range(num_lam): w_mat[i] = ridge_regres(x, y, np.exp(i-10)) return w_mat def stage_wise(x, y, eps=0.01, num_it=100): """ 前向逐步线性回归 :param x: :param y: :param eps: :param num_it: :return: """ # 数据标准化 y_mean = y.mean() y = y - y_mean x_mean = x.mean(0) x_var = x.var(0) x = (x - x_mean) / x_var m, n = x.shape ws = np.zeros(n) w_list = np.zeros((num_it, n)) for i in range(num_it): # 初始化最小误差为正无穷 min_error = np.inf w_best = np.zeros(n) # 对每个特征 for j in range(n): # 增大或减小 for step in [-1, 1]: ws_test = ws.copy() ws_test[j] += step * eps # 计算新的系数下预测值 y_ = x @ ws_test # 计算新的误差值 error = square_error(y, y_) if error < min_error: w_best = ws_test min_error = error ws = w_best w_list[i] = ws return w_list
60f99a2bdb9d1e78dc3517ac8f68c49ad4888798
katebartnik/katepython
/Kolekcje/Listy.py
632
3.640625
4
my_list = [1, "a", "a", "ala", "kot", 121] print(my_list) print(my_list[0]) my_list2 = [1, 2, 3, my_list] # [1, 2, 3, [1, "a", "ala", "kot", 121]] # print(my_list2[3][1]) # print(dir(my_list)) print(my_list2) print(my_list.append(10)) print(my_list) print(my_list2) # print(my_list.pop()) # print(my_list.pop()) # print(my_list) # print(my_list.index(1)) # print(my_list.index("a")) # print(my_list.count("a")) a = [1, 2, 3] b = [3, 4, a] print(a) print(b) a.append(10) a[0] = 100 print(a) x = (1, 2, 3) print(dir(x)) print(x[0]) y = (4, 5, 6) x = x + y # print(x.index(100)) print(1 in x) print("y" in "abecadło")
7ee0fa053bd5b7311dd89f9e07840209bfaab23c
himanshuks/python-training
/expert/enumeration.py
459
4.5
4
# ENUMERATE - To iterate while tracking index of element list = [3, 8, 5, False, 9, "Himanshu", 22.7] for item in list: print(item) # We can use enumerate to iterate over list using counter track # X,Y can be of any name but first parameter will be index and second parameter will be item itself for index, item in enumerate(list): print(f"The item at {index} index is {item}") for i, j in enumerate(list): print(f"Item at index {i} is {j}")
0f8f14045220aedf4a48a234477b8734cba95f0e
SivaPandeti/python-interview
/src/algorithms/coin_change.py
778
4.1875
4
## Objective ## Write an function to find the minimum number of coins for giving change ## Input ## A list of available coins & an amount. ## e.g. [1, 5, 10, 21, 25] & 63 ## Constraints and clarifications ## There is infinite supply of coins of each type ## Output ## 3 ## Explanation ## In the sample input, you would make maximum profit of 6 if you buy at 5 and sell at 11 ## References ## [Coin change](http://interactivepython.org/runestone/static/pythonds/Recursion/DynamicProgramming.html) def coins(n, C, A): if n in C: A[n] = 1 if not A[n]: A[n] = min([1 + coins(n-c, C, A) for c in C if c < n]) return A[n] if __name__ == '__main__': C = [1, 5, 10, 21, 25] n = 63 A = [0] * (n+1) print coins(n, C, A) assert 3 == coins(n, C, A)
816323ddd44760724f6567127faddcca1aabfc81
Proak47/TIKTOKTOE
/main game.py
5,189
3.84375
4
'''TIKTOKTOE''' #why does GITHUB SUCK SO MUCH SERIOUSLY GITHUB WHY board1 = [" "," "," "," "," "," "," "," "," "," "] player1 = [] player2 = [] '''board = 7,8,9, 4,5,6, 1,2,3''' def playerTurn(y,x): #takes note of the player's turn if x % 2 !=0: player1.append(y) board1[y] = "X" elif x % 2 ==0: player2.append(y) board1[y] = "O" def gameGrid(): #visual representation of the game print("\t" + str(board1[7]) , " | " , str(board1[8]), " | " , str(board1[9])) print("\t--------------") print("\t" + str(board1[4]) , " | " , str(board1[5]) , " | " , str(board1[6])) print("\t--------------") print("\t" + str(board1[1]) , " | " , str(board1[2]) , " | " , str(board1[3])) def showGrid(): # grid to direct the player print("\t7" , " | " , "8" , " | " , "9") print("\t--------------") print("\t4" , " | " , "5" , " | " , "6") print("\t--------------") print("\t1" , " | " , "2" , " | " , "3") def winGame(player): # win detection for x in player: if x == 1: #all combinations that start with 1 for x in player: if x == 2: for x in player: if x == 3: return "1" if x == 4: for x in player: if x == 7: return "1" if x == 5: for x in player: if x == 9: return "1" if x == 2: #all combinations that start with 2 for x in player: if x == 5: for x in player: if x == 8: return "1" if x == 3: #all combinations that start with 3 for x in player: if x == 6: for x in player: if x == 9: return "1" if x == 5: for x in player: if x == 7: return "1" if x == 4: # all combinations that start with 4: for x in player: if x == 5: for x in player: if x == 6: return "1" if x == 7: for x in player: if x == 8: for x in player: if x == 9: return "1" def greetingStart(): print("Hello Players! Welcome to TikTokToe!\nEnter a number from 1 to 9.\nEnter 0 to exit early.") def endScreen(): #this is still shit fix it pls ending = input("Thanks for Playing!\n Play Again? (Y/N): ").upper() if ending == "Y": resetGame(1) gameRun() elif ending == "N": print("See you next Time!") exit() else: print("Error") exit() def resetGame(a): #fix this asap global name1, name2, player2, player1, board1, turn1 board1 = [" "," "," "," "," "," "," "," "," "," "] player1 = [] player2 = [] name1 = "" name2 = "" turn1 = a turn1 = 1 def gameRun(): #main game function global turn1, board1, player1, player2 while turn1 <= 10: if turn1 == 1: greetingStart() showGrid() while turn1 == 1: name1 = input("Enter Your Name, Player 1!\n ") if name1 == " " or len(name1) > 15: print("Enter your name within 15 characters.\n") continue else: name2 = input("Enter Your Name, Player 2!\n ") if name2 == " " or len(name2) > 15: print("Enter your name within 15 characters.\n") continue else: break if turn1 % 2 != 0: print(name1 + "! (X) Your Turn!\n") elif turn1 % 2 == 0: print(name2 +"! (O) Your Turn!\n") try: y = int(input("Enter a Number: ")) except ValueError: continue else: if y > 9 or y < -1: continue elif board1[y] != " ": print("\nPick another number") continue elif board1[y] != " ": print("\nPick another number") continue elif y == 0: endScreen() playerTurn(y,turn1) player1.sort() player2.sort() gameGrid() turn1 += 1 winGame(player2) if winGame(player2) == "1": print("\n") print(name2 +" Wins!") winGame(player1) elif winGame(player1) == "1": print("\n") print(name1 +" Wins!") elif turn1 > 9: print("DRAW") elif turn1 > 9 or winGame(player1) == "1" or winGame(player2) == "1": endScreen() gameRun()
04705752a51cd9ff34b53f8553ab368b41d028a1
jhandal11/meraki-python-training
/car.py
1,183
3.828125
4
class Car(object): wheels = 4 def __init__(self, make, model): self.make = make self.model = model @staticmethod def make_car_sound(): print('VRooooommmm!') @classmethod def is_motorcycle(cls): return cls.wheels == 2 if __name__ == "__main__": mustang = Car('Ford', 'Mustang') print("Class wheels set to 4") print("Mustang wheels:",mustang.wheels) print("Car Class wheels:",Car.wheels) print() Car.wheels = 6 print("Class wheels set to 6") print("Mustang wheels:",mustang.wheels) print("Car Class wheels:",Car.wheels) print() mustang.wheels = 5 print("Mustang wheels set to 5") print("Mustang wheels:",mustang.wheels) print("Car Class wheels:",Car.wheels) print() Car.wheels = 10 print("Class wheels set to 10") print("Mustang wheels:",mustang.wheels) print("Car Class wheels:",Car.wheels) print() trans_am = Car('Pontiac', 'TransAm') print("Mustang wheels:",mustang.wheels) print("TransAm wheels:",trans_am.wheels) print("Car Class wheels:",Car.wheels) print() print(trans_am.make_car_sound())
01a0d66717cf5677c17d539dbcbf2a0d46e700c9
YiseBoge/CompetitiveProgramming2
/Weeks/Week1/linked_list_cycle.py
1,683
3.859375
4
import os class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, node_data): node = SinglyLinkedListNode(node_data) if not self.head: self.head = node else: self.tail.next = node self.tail = node def print_singly_linked_list(node, sep, fptr): while node: fptr.write(str(node.data)) node = node.next if node: fptr.write(sep) # Complete the has_cycle function below. # # For your reference: # # SinglyLinkedListNode: # int data # SinglyLinkedListNode next # # def has_cycle(head): node, visited = head, set() while node: if node in visited: return True visited.add(node) node = node.next return False if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') tests = int(input()) for tests_itr in range(tests): index = int(input()) l_list_count = int(input()) l_list = SinglyLinkedList() for _ in range(l_list_count): l_list_item = int(input()) l_list.insert_node(l_list_item) extra = SinglyLinkedListNode(-1) temp = l_list.head for i in range(l_list_count): if i == index: extra = temp if i != l_list_count - 1: temp = temp.next temp.next = extra result = has_cycle(l_list.head) fptr.write(str(int(result)) + '\n') fptr.close()
26421c37bc8e677f2b44e39644d6a75d99867a91
JarvisFei/leetcode
/剑指offer代码/算法和数据操作/面试题10:斐波那契数列.py
933
3.84375
4
#递归写法 def F(first, second, N): if N < 3: return 1 if N == 3: return first + second return F(second, first + second, N - 1) print(F(1,1,10)) #非递归写法 N = 10 first = 1 second = 1 result = 0 for i in range(3,N + 1,1): result = first + second first, second = second, result print(result) #最快的一种解法,递归使用公式。 #延伸题目1,一直青蛙,每次可以调两级台阶也可以跳一级台阶,请问,n级台阶有多少中跳法?F(n) = F(n-1) + F(n-2) #延伸题目2,一直青蛙,每次可以跳1、2、3。。。n级,请问,n级台阶有多少中跳法?F(n) = F(n-1) + F(n - 2) + ... + F(0) #延伸题目3,用一个小的矩形1X2,无重叠覆盖一个2X9的大矩形,也是斐波那契数列 f_list = [lambda x:x**i for i in range(5)] print("") print(f_list[1](3)) print([f_list[j](10) for j in range(5)]) print(10**2)
76345a1aac1e908738a43e3feb51ba8da4bdb77b
brittany-morris/Bootcamp-Python-and-Bash-Scripts
/python fullstackVM/front_x.py.save
288
3.890625
4
#!/usr/bin/env python3 import sys strings = sys.argv[1:] list_1 = [] list_2 = [] for elem in strings: if elem [0] == 'x': list_1.append(elem) else: list_2.append(elem) sorted_list_1 = words.sort(list_1) sorted_list_2 = words.sort(list_2) print(sorted_list_1 + sorted_list_2)
10943b3deab688dbed5320f23d2390fc62384b07
leohck/python_exercises
/list_overlap_comprehensions.py
727
4.28125
4
__author__ = 'leohck' #exercise 10 """ Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Write using at least one list comprehension. """ #extra """ Randomly generate two lists to test this """ from random import randint a = [randint(0,100) for x in range(0,10)] b = [randint(0,100) for x in range(0,10)] new_list = [] new_list = [x for x in a if x in b if x not in new_list] print('list a: \n',a,'\n list b: \n ',b,' \n new list: \n',new_list)
6d4cc390b1f481cf06d195580cebb3367fb3e00e
fadhil-amree/fadhil-tugas
/P01.21100924.02.py
740
3.546875
4
# NIM / Nama : Muhammad Fadhil Amri # Tanggal : Rabu, 28 April 2021 # Deskripsi : Program RGB warna pengkom warna = input('masukkan warna: ') if warna == 'Yellow': print('Warna RGB yang menyala: \n - Red \n - Green') elif warna == 'Cyan': print('Warna RGB yang menyala: \n - Blue \n - Green') elif warna == 'Magenta': print('Warna RGB yang menyala: \n - Red \n - Blue') elif warna == 'White': print('Warna RGB yang menyala: \n - Red \n - Green \n - Blue') elif warna == 'Green': print('Warna RGB yang menyala: \n - Green') elif warna == 'Red': print('Warna RGB yang menyala: \n - Red') elif warna == 'Blue': print('Warna RGB yang menyala: \n - Blue') else : print('Warna RGB yang menyala: ')
92a90bee48feea36fc314039a2d9253c35e2bd35
yingliufengpeng/algorithm
/数据结构与算法365天刷题特训营/06 二叉树/bin_tree_create_2.py
1,116
3.59375
4
# -*- coding: utf-8 -*- ''' 已知一颗二叉树的先序序列ABCECFG和中序序列DBEAFGC,画出这个二叉树 ''' class Node: def __init__(self, val): self.val = val self.left = self.right = None def __str__(self): return self.val def preorder(self) -> str: res = [] def dfs(root): if root is None: res.append('#') return res.append(root.val) dfs(root.left) dfs(root.right) dfs(self) return ''.join(res) pre_s = 'ABDECFG' inor_s = 'DBEAFGC' def create_node(pre_s, inor_s): if not pre_s: return None v = pre_s[0] root = Node(v) # print('prev, inors v', pre_s, inor_s, v) mid = inor_s.index(v) left = create_node(pre_s[1: mid + 1], inor_s[:mid]) right = create_node(pre_s[mid + 1:], inor_s[mid + 1:]) root.left = left root.right = right return root root = create_node(pre_s, inor_s) r = root.preorder() print(r)
8abf43fdec0d6e82235d017e9d25206b2c7901a2
santhosh-kumar/AlgorithmsAndDataStructures
/python/problems/binary_tree/find_lowest_common_ancestor.py
2,386
3.875
4
""" Find Lowest Common Ancestor in a Binary Tree Given a binary tree (not a binary search tree) and two values say n1 and n2, write a program to find the least common ancestor. """ from common.problem import Problem class FindLowestCommonAncestor(Problem): """ Find Lowest Common Ancestor """ PROBLEM_NAME = "FindLowestCommonAncestor" def __init__(self, root_node, label1, label2): """Find Lowest Common Ancestor Args: root_node: node of the tree label1: First node's label label2: Second node's label Returns: None Raises: None """ super().__init__(self.PROBLEM_NAME) self.root_node = root_node self.label1 = label1 self.label2 = label2 def solve(self): """Solve the problem Note: Args: Returns: integer Raises: None """ print("Solving {} problem ...".format(self.PROBLEM_NAME)) return self.find_lca(self.root_node, self.label1, self.label2) def find_lca(self, root, label1, label2): """Find the lowest common ancestor Args: root: root node of the tree label1: First node's label label2: Second node's label Returns: BinaryTreeNode Raises: None """ # Base case if root is None: return None # If either n1 or n2 matches with root's key, report # the presence by returning root (Note that if a key is # ancestor of other, then the ancestor key becomes LCA if root.data == label1 or root.data == label2: return root # Look for keys in left and right subtrees left_lca = self.find_lca(root.left, label1, label2) right_lca = self.find_lca(root.right, label1, label2) # If both of the above calls return Non-NULL, then one key # is present in once subtree and other is present in other, # So this node is the LCA if left_lca and right_lca: return root # Otherwise check if left subtree or right subtree is LCA if left_lca is not None: return left_lca elif right_lca is not None: return right_lca else: return None
2da13ea7e871c20d06e4dc6f36ddfd8599104b26
esinghroy/python-learning-cohort
/ed/02_guess_that_number_game/program.py
684
4.1875
4
import random print(''' -------------------------------------- GUESS THAT NUMBER GAME -------------------------------------- ''') the_number = random.randint(0, 100) the_guess = -1 while the_guess != the_number: guess_text = input("Guess how much money I have in my bank account (hint, it's between 0 and 100 kr): ") the_guess = int(guess_text) if the_guess < the_number: print(f"Only {the_guess} kr! I'm not that poor! Try again!") elif the_guess > the_number: print(f"{the_guess} kr! You think I'm that rich?! Try again!") else: print("You got it! Now give me your bank account details!")
633fa34f9bf3a98530de725c99413587dd252a13
junglesub/hgu_21summer_pps
/week1/5-2_유정섭_20210708.py
262
3.546875
4
tc = int(input()) answer = [] for _ in range(tc): eq = input().replace("@", "*3").replace("%", "+5").replace("#", "-7").split() ans = float(eq[0]) for e in eq[1:]: ans = eval(str(ans) + e) answer.append(ans) for ans in answer: print("%.2f" % ans)
1bf2b33bdcdd8ba24760ce61bd1661de95ca4ccb
gomilinux/python-PythonForKids
/Chapter9/BuiltInFunctions.py
212
3.984375
4
#Python for Kids Chapter 9 Python's Built-in Functions #your_calculation = input('Enter a calculation: ') #eval(your_calculation) my_small_program = '''print('ham') print('sandwich')''' exec(my_small_program)
5f5a8f0f94aa79cb4da8f8278c10b664687a6ccc
hychrisli/PyAlgorithms
/src/solutions/part1/q209_min_size_sub_sum.py
1,671
3.625
4
import sys from src.base.solution import Solution from src.tests.part1.q209_test_min_size_sub_sum import MinSizeSubSumTestCases """ Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ? s. If there isn't one, return 0 instead. For example, given the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the minimal length under the problem constraint. click to show more practice. More practice: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). """ class MinSizeSubSum(Solution): def print_output(self, output): super(MinSizeSubSum, self).print_output(output) def run_test(self, input): return self.minSubArrayLen(input[0], input[1]) def gen_test_cases(self): return MinSizeSubSumTestCases() def verify_output(self, test_output, output): return test_output == output def minSubArrayLen(self, s, nums): """ :type s: int :type nums: List[int] :rtype: int """ nlen = len(nums) minlen = sys.maxint ssum = 0 si = ei = 0 while ei <= nlen: print(("before",ssum, si, ei)) if ssum < s: if ei < nlen: ssum += nums[ei - 1] ei += 1 else: minlen = min(minlen, ei - si) ssum -= nums[si] si += 1 print(("after", ssum, si, ei)) if minlen == sys.maxint: minlen = 0 return minlen if __name__ == '__main__': sol = MinSizeSubSum() sol.run_tests()
4389b84bce4cd7e06a1db9494dd7604977f8864e
bjumego/python
/untitled1.py
172
4.15625
4
A = int (input("A:")) B = int (input("B:")) if A<B: for A in range(A,B+1): print(A) else: for A in range(A,B-1,-1): print(A)
cb33348cf40a968db5105373aa4f64d36bd83821
stacecadet17/python
/filter_by_type.py
992
3.953125
4
# If the integer is greater than or equal to 100, print "That's a big number!" If the integer is less than 100, print "That's a small number" def integer(num): if num >= 100: print ("That's a big number!") else: print ("that's a small number") # **************************************************************************** # If the string is greater than or equal to 50 characters print "Long sentence." If the string is shorter than 50 characters print "Short sentence." def sentence(str): if len(str) > 50: print ("Thats a long sentence") else: print ("That's a short sentence") # **************************************************************************** # If the length of the list is greater than or equal to 10 print "Big list!" If the list has fewer than 10 values print "Short list." def list_length(list): if len(list) > 10: print ("big list!") else: print ("small list") a = ["bunny", 4, 6, 1, "monkey", "tiger"] list_length(a)
ef6cb280db275e49ea41765d8ae7a882311e2204
wandsen/PythonNotes
/ControlFlow.py
315
4.15625
4
#Lesson 2 Control Flow #If Else Statement x = 5 if x < 10 : print(True) if x > 5 : print(True) else : print(False) #Elif Statement x = 10 if x < 10: print("x is less than 10") elif x > 10: print("x is more than 10") else: print ("x is 10") #While Statement n=0 while n < 3: print(n) n=n+1
cdf52c0c017ced2d52e61ea21799061e02bd0948
SipTech/Python_Class_2020
/beginner_guessing_game.py
1,759
4.375
4
from random import randint # random number equalsTo random integer between (0, 20) random_number = randint(0, 20) # user guess equals None user_guess = None # while user guess is not equal to random number while user_guess != random_number: # get input user guess between 0 and 20 and cast the guess to integer user_guess = int(input("Please guess/enter a number between {0} and {1}: ".format(0, 20))) # check if user guess is between 0 and 20 if 0 <= user_guess <= 20: # if user input equalsTo random number if user_guess == random_number: # print well done the number is x print("Well done the number is: {0}".format(random_number)) # user won the game, let's break the loop break # if user guess is less than random number elif user_guess < random_number: # print your guess is too low print("Your guess {0} is too low..".format(user_guess)) # if user guess is greater than random number elif user_guess > random_number: # print your guess is too high print("Your guess {0} is too high..".format(user_guess)) # let's give the player an option to quit the game quit_game = input("If you wish to give up, type in (any value) or hit (enter) to try again: ") # If quit is not empty, it means user gave up otherwise the game continues if quit_game: # Upon exit, let's reveal or random number to the user print("Oops!! My random number was {0}...\nSad to see you give up :( \nI hope we play again soon :)".format(random_number)) # To end the game by breaking the loop break # If we get here it means user input is not an interger between 0 and 20 else: # Notify the user of their offence print("{0} is invalid!!!\nPlease make sure, your input is an integer between 0 and 20".format(user_guess))
e14049d211e8d052d47d9fcfe434bfb74c771b0f
SergioPeignier/kernels4graphs
/script/atom.py
1,215
3.9375
4
class atom: def __init__(self,name, deg=0, morgan=1): """ Create an atom object. name='C' for Carbon atom, deg holds for the number of neighbors, morgan morgan coeficient :param self: atom object :param name: atom label :type name: String """ self.name=name self.deg=deg self.morgan=morgan self.new_morgan=0 self.old_name=name def __str__(self): """ Redefine print function :param self: atom """ return "atom: "+self.name+" | deg: "+str(self.deg)+" | morgan: "+str(self.morgan) def __eq__(self,other): """ Redefine the equality function :param self: this atom object :param other: another atom object :type other: atom """ return self.name==other.name def __ne__(self,other): """ Redefine the inequality function :param self: this atom object :param other: another atom object :type other: atom """ return self.name!=other.name def refresh_morgan(self): """ Update the atom's morgan index :param self: this atom """ self.morgan = self.new_morgan self.new_morgan=0 def include_morgan_in_name(self): """ Include the morgan index into the atom's name :param self: this atom """ self.name=self.old_name+str(self.morgan)
a4d7e337ae8491ea1f4c2babbf3f63f8687ae537
ShubhamWaghilkar/python
/revision.py
308
3.921875
4
# def revi(n): # # # while i <= n: # # print(i) # # i = i+1 # # # for i in range(1,n): # print(i) # # user = int(input("Enter number \n")) # revi(user) a = int(input("Enter Number")) # i = 1 # while i <= a: # print(i) # i = i+1 for i in range(1,a+1): print(i)
d375dea73da0ac0b4d3bb5a17053ac5b91d33dd2
greenpepper1/Game
/game.py
832
3.5625
4
from business import Business class Top(): def __init__(self): self.companies = [Business(),Business(),Business(),Business(),Business()] def showCompanyValue(self): for company in self.companies: company.showValue() def showCompanyHoldings(self): for company in self.companies: company.showHoldings() print("") def showEnv(self): self.companies[0].showEnv() def businessTurnOver(self): for company in self.companies: company.businessTurnOver() def envirenmentTurnOver(self): self.companies[0].envirenmentTurnOver() test = Top() test.showCompanyHoldings() print("") for x in range (10): test.showEnv() test.showCompanyValue() test.businessTurnOver() test.envirenmentTurnOver() print("")
9370897f01ea81b21d3c9f3cc481ab3705700990
afshinm/python-list-vs-tuple-benchmark
/tuple.py
392
3.609375
4
import time from random import randint x = 1000000 temp_list = [] # create temp list and then convert it to tuple while x > 0: temp_list.append(x) x = x - 1 # convert list to tuple demo_tuple = tuple(temp_list) start = time.clock() # random find elements from tuple y = 2000000 while y > 0: item = demo_tuple[randint(0, 999999)] y = y - 1 print (time.clock() - start)
7c449ec6ddd2300c3228856860817a60dc9297a2
EliteGirls/Camp2017
/Girls21.2/GROUP B/wednesday.py
451
3.953125
4
D =0 while D ==0: D =input("press 0 to continue and any number to quit") if D!=1 break scores = input("enter your score") if scores <=100 and scores >=80: print "A" elif scores <=79 and scores >=70: print "B" elif scores<=69 and scores >=60: print "C" elif scores <=59 and scores >=50: print "D" elif scores <=49 and scores >=45: print"E" else: print "F"
215ca06fe0ec9737b5b2d21c1dccc0a9e9e6f8bd
henrylin2008/Coding_Problems
/LeetCode/Blind 75/Binary Search/4_median_of_two_sorted_arrays.py
3,330
3.890625
4
# 4. Median of Two Sorted Arrays # https://leetcode.com/problems/median-of-two-sorted-arrays/ # Hard # Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. # # The overall run time complexity should be O(log (m+n)). # # # # Example 1: # Input: nums1 = [1,3], nums2 = [2] # Output: 2.00000 # Explanation: merged array = [1,2,3] and median is 2. # # Example 2: # Input: nums1 = [1,2], nums2 = [3,4] # Output: 2.50000 # Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. # # # Constraints: # # nums1.length == m # nums2.length == n # 0 <= m <= 1000 # 0 <= n <= 1000 # 1 <= m + n <= 2000 # -106 <= nums1[i], nums2[i] <= 106 from typing import List class Solution: # Time: Log(min(n, m)); running binary search on the smaller array # Space: O(1); no data structure is used # Logic: find half of total length of 2 lists; run binary search on the shorter length(A), get the middle point of A # and B, and left, right value of A and B; if the partition is correction (A_left <= B_right and B_left <= # A_right): if it's an odd num, return min of either of A_right or B_right; else if it's even, get the min # of (A_right, B_right) and max of (A_left, B_left), then divide 2. def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: A, B = nums1, nums2 total = len(nums1) + len(nums2) # total length of 2 nums half = total // 2 # half of length if len(B) < len(A): # running binary search on A, ensure A is a smaller array A, B = B, A # swap A, B; since we wanted to run binary search on A # run binary search l, r = 0, len(A) - 1 # left, right pointer of the binary search on A while True: i = (l + r) // 2 # middle point; A j = half - i - 2 # rest of the half from B; -2 because index are starting 0 (i and j) # A_left, B_left: last values at left half arrays; # A_right, B_right: beginning values at the right half arrays # set value if inbound else default value A_left = A[i] if i >= 0 else float("-infinity") # if i is inbound(>0) set the value at i else default -inf A_right = A[i + 1] if (i + 1) < len(A) else float("infinity") # if i+1 inbound set val at i+1 else def inf B_left = B[j] if j >= 0 else float("-infinity") # if j is inbound set value at j else default -inf B_right = B[j + 1] if (j + 1) < len(B) else float("infinity") # if j+1 inbound set A[j+1] else default inf if A_left <= B_right and B_left <= A_right: # Partition is correct # odd if total % 2: # if total % 2 == 1 (True), odd return min(A_right, B_right) # min(A_right, B_right) is the middle value for odd length, # even return (max(A_left, B_left) + min(A_right, B_right)) / 2 # med: (max(left arr) + min(right arr))/ 2 elif A_left > B_right: # if left partition of A has too many elements r = i - 1 # reduce size of left partition from A else: # B_left > A_right l = i + 1 # increase size of left partition from A
dfa36e974356bd9e2b1ce613077f3982750097f4
shreyasrbhat/Erricson_hack
/Prediction/utils.py
546
3.65625
4
from nltk.tokenize import word_tokenize from nltk.corpus import stopwords import re from nltk.stem import PorterStemmer def tokenizer(txt): ## returns tokenized corpus without stopwords and special characters ##parameter: ##txt: string ps = PorterStemmer() stop_words = set(stopwords.words('english')) txt = re.sub('[^A-Za-z\s*]', '', txt.lower()) tokens = list(filter(lambda x: x not in stop_words and len(x) > 2, word_tokenize(txt))) return tokens #return list([ps.stem(token) for token in tokens])
e03f0f4f43c5144ccef05e77e64d5f17a88c6da1
pcwu/leetcode
/101-symmetric-tree/isSymmetric.py
1,354
4.0625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ def symmetric(treeLeft, treeRight): if treeLeft is None and treeRight is None: return True if treeLeft.val != treeRight.val: return False outter = False inner = False if treeLeft.left is None and treeRight.right is None: outter = True elif treeLeft.left is None or treeRight.right is None: return False else: if symmetric(treeLeft.left, treeRight.right): outter = True else: return False if treeLeft.right is None and treeRight.left is None: inner = True elif treeLeft.right is None or treeRight.left is None: return False else: if symmetric(treeLeft.right, treeRight.left): inner = True else: return False return inner and outter return symmetric(root, root)
74fee79eda76108b317c444a5004c64975e2f0ec
lerene/GW_HW_EnerelTs
/week3_Python_HW_ET/PyPoll/main.py
2,615
3.890625
4
from collections import defaultdict #filename = "election_data.csv" count = 0 Total_Votes = 0 Candidate_Name_List = defaultdict(int) Candidate_Percentage_of_Votes = 0 Candidate_Total_Votes = {} Candidate_Most_Votes = {} with open("election_data.csv") as file_object: # Columns: Voter ID, County, Candidate #Voter ID,County,Candidate #12864552,Marsh,Khan #17444633,Marsh,Correy #19330107,Marsh,Khan #19865775,Queen,Khan #11927875,Marsh,Khan #19014606,Marsh,Li for line in file_object: count += 1 if ( count == 1 ): continue # continue will cause the next line to be read else: Total_Votes += 1 # increment the total votes count (VoterID, County, Candidate) = line.split(",") # each line has three fields Candidate = Candidate.rstrip() # print("Candidate: " + Candidate + # ", County: " + County + # ", Voter ID: " + VoterID + # "\n") Candidate_Name_List[Candidate] += 1 Winner = Candidate # just initialize the winning variable here but do test below # print the results to the Python console print("Election Results\n") print("-------------------------\n") print("Total Votes: " + str(Total_Votes) + "\n") print("-------------------------\n") print("Candidate List: \n") for Name in sorted(Candidate_Name_List.keys()): percent_of_votes = Candidate_Name_List[Name] / Total_Votes * 100 if Candidate_Name_List[Name] > Candidate_Name_List[Winner]: Winner = Name print("\t" + Name + ": " + str(round(percent_of_votes,4)) + "% (" + str(Candidate_Name_List[Name]) + ")\n") print("-------------------------\n") print("Winner: " + Winner + "\n") print("-------------------------\n") # Do the output file creation and writing outfile = open("election_data.txt","w+") outfile.write("\n\nElection Results\n") outfile.write("\n-------------------------\n") outfile.write("\nTotal Votes: " + str(Total_Votes) + "\n") outfile.write("\n-------------------------\n") outfile.write("\nCandidate List: \n") for Name in sorted(Candidate_Name_List.keys()): percent_of_votes = Candidate_Name_List[Name] / Total_Votes * 100 outfile.write("\n\t" + Name + ": " + str(round(percent_of_votes,4)) + "% (" + str(Candidate_Name_List[Name]) + ")\n") outfile.write("\n-------------------------\n") outfile.write("\nWinner: " + Winner + "\n") outfile.write("\n-------------------------\n") outfile.close()
54e83c8d32810481a2627b6ee54eb7b25a068b61
deepitapai/Coding-Interview-Prep
/Leetcode solutions/sliding-window-maximum.py
463
3.609375
4
from collections import deque def slidingWindowMax(nums,k): deq,output = deque(),[] n = len(nums) def clean_deq(deq,i): while deq and deq[0] == i-k: deq.popleft() while deq and nums[deq[-1]] < nums[i]: deq.pop() for i in range(k): clean_deq(deq,i) deq.append(i) output.append(nums[deq[0]]) for i in range(k,n): clean_deq(deq,i) deq.append(i) output.append(nums[deq[0]]) return output print(slidingWindowMax([1,3,-1,-3,5,3,6,7],3))
43d0067f21c24d5d8d9d9e9815876fb4380d8332
DmytroLuzan/My_home_study_python_part2
/lesson28-Home-Work.py
2,320
4.5
4
""" 1. Дан массив. в вкотором среди прочих єлементов есть слово "odd" (нечетный). Определите, есть ли в списке число, которое является индексом элемента "odd". Напишите функцию, которая будет возвращать True или False, соответственно. """ def odd_ball(arr): value1 = arr.index("odd") value2 = arr.count(value1) return bool(value2) print(odd_ball(["even", 4, "even", 7, "even", 55, "even", 6, "even", 10, "odd", 3, "even"])) # True print(odd_ball(["even", 4, "even", 7, "even", 55, "even", 6, "even", 9, "odd", 3, "even"])) # False print(odd_ball(["even", 10, "odd", 2, "even"])) # True """ 2. Напишите функцибю find_sum(n), где аргумент функции - это конечный элемент последовательности включительно. Функция должна вернуть сумму всех чисел последовательности, кратных 3 и 5. Попробуйте решить задачу двумя способами (один из способов в одну строчку кода). """ def find_sum(n): new_list = [] for n in range(n + 1): if n % 3 == 0 or n % 5 == 0: new_list.append(n) print(sum(new_list)) print(sum([n for n in range(10 + 1) if n % 3 == 0 or n % 5 == 0])) find_sum(5) # return 8 (3 + 5) find_sum(10) # return 33 (3 + 5 + 6 + 9 + 10) """ 3. Дан список имен. Выберите в новый список только те имена, которые состоят из 4-х букв. names = ["Ryan", "Kieran", "Mark", "John", "David", "Paul"] # ["Ryan", "Mark", "John", "Paul"] """ def get_names(names): new_list = [] for x in names: if len(x) == 4: new_list.append(x) print(new_list) names = ["Ryan", "Kieran", "Mark", "John", "David", "Paul"] get_names(names) # names = ['alex', 'rob', 'jhon'] # # print('first way:') # for name in names: # print(name) # # print('second way:') # for x in range(len(names)): # [0,1,2] # print(names[x]) # # print('while loop:') # i = 0 # while i < len(names): # print(names[i]) # i += 1
cc5b1dfdb905c613972a15f2555f7eb8ba72e861
sneha5gsm/Data-Structures-and-Algorithms-Exercises
/Practice Problems/nonDivisibleSubset.py
1,354
3.65625
4
#!/bin/python import math import os import random import re import sys # Complete the nonDivisibleSubset function below. def recursiveFn(arr, sub, k, count, index): if index >= len(arr): return count else: i = 0 count1 = 0 count2 = 0 count3 = 0 flag = 0 # print sub # print count # print 'sub' # print len(sub) while i < len(sub): # print i # print index # print '--------' if (sub[i] + arr[index]) % k == 0: flag = 1 # print 'inside if' count1 = recursiveFn(arr, sub, k, count, index + 1) count2 = recursiveFn(arr, sub[:i] + sub[i + 1:] + [arr[index]], k, count, index + 1) i = i + 1 if flag == 0: count3 = recursiveFn(arr, sub + [arr[index]], k, count + 1, index + 1) count = max(count1, count3, count2) return count def nonDivisibleSubset(k, S): count = recursiveFn(S, [], k, 0, 0) return count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nk = raw_input().split() n = int(nk[0]) k = int(nk[1]) S = map(int, raw_input().rstrip().split()) result = nonDivisibleSubset(k, S) fptr.write(str(result) + '\n') fptr.close()
eaa17cbf5241a6b0e959811839589eb1964e7d2a
aleonsan/python-design-patterns
/design_patterns/visitor/example.py
1,494
4.0625
4
# Design Pattern: Visitor # Visited object class Sword(object): def accept(self, visitor): """ Here we declare the relationiship btw objects """ visitor.visit(self) def shine(self, believer): print(self, "shines holded by ", believer) def do_nothing(self, skeptical): print(self, "do nothing in presence of ", skeptical) class MythologicSword(Sword): pass class FakeSword(Sword): def shine(self, believer): print(self, "looks fake holded by ", believer) # Visitor object class Knight: pass class Believer(Knight): def visit(self, sword): """ Here we declare the how will be the relationiship btw objects """ sword.shine(self) class Skeptical(Knight): def visit(self, sword): """ Here we declare the how will be the relationiship btw objects """ sword.do_nothing(self) def run_example(): print(""" ************************************************ Visitor design pattern: Knights & swords ************************************************ This design pattern shows how objects can interact in different ways depending on its own nature, and not coupling it behaviour to the visited object """) # two knights lancelot = Skeptical() arthur = Believer() # two swords excalibur = MythologicSword() heskalibug = FakeSword() # the facts excalibur.accept(lancelot) heskalibug.accept(arthur) excalibur.accept(arthur)