blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a56dd25e5986d8fab3ff3bd4aa62c917ce947b02
ShreyanshJainJ/dunzo-coffee-machine
/coffee_machine/services/drink.py
1,157
3.84375
4
from dataclasses import dataclass from typing import Dict, List @dataclass class Beverages: """Dataclass for different beverages Returns: [type]: [description] """ drinks: Dict[str, Dict[str, int]] def get_receipe(self, drink_type: str) -> Dict[str, int]: """This method gets the ingredient composition for the provided drink type Args: drink_type (str): [description] Returns: Dict[str, int]: [description] """ return self.drinks.get(drink_type, {}) def get_ingredients(self, drink_type: str) -> List[str]: """This method gets the list of ingredients for the provided drink type Args: drink_type (str): [description] Returns: List[str]: [description] """ return [ingredient for ingredient in self.get_receipe(drink_type)] def get_types_of_drink(self) -> List[str]: """This method returns all the available drinks in the machine Returns: [type]: [description] """ return [drink_type for drink_type in self.drinks]
f279ea39e1c7a20cc3ab57ba6177463c89cf1072
BRPawanKumarIyengar/Matplotlib_Module_Tutorial
/Bar_Graph_Example.py
580
4.40625
4
#This is most basic and simplesr ,use of matplotlib #W import matplotlib as my_plt for easy reference from matplotlib import pyplot as my_plt #Here we are manually feeding data for x and Y a #my_plt.plot([1,2,3,4,5],[1,3,5,7,9],) #Here we add lables (that tell us what are values of X and Y ) to x and y axis my_plt.xlabel('X - Axis') my_plt.ylabel('Y - Axis') #Here we add the title of the graph (Tells us what to do) my_plt.title('Title of Graph') #Here we plot a bar graph my_plt.bar([1,2,3,4,5,6,7,8,9],[1,3,5,7,9,7,5,3,1]) my_plt.show()
46cce42fb532f74c8a2ff5a36bf9a5940838a95d
sh05git/address_search_APP
/test_address_seacher.py
1,090
3.71875
4
import unittest from address_seacher import AddressSeacher class TestAddressSeacher(unittest.TestCase): def test_岩手県八幡平市大更の地名を郵便番号から取得できる(self): address_sercher = AddressSeacher() actual = address_sercher.search(postal_code="0287111") self.assertEqual("岩手県八幡平市大更", actual) def test_東京都練馬区豊玉南の地名を郵便番号から取得できる(self): address_sercher = AddressSeacher() actual = address_sercher.search(postal_code="1760014") self.assertEqual("東京都練馬区豊玉南", actual) def test_存在しない郵便番号が入力されたらエラーメッセージを表示する(self): address_searcher = AddressSeacher() actual = address_searcher.search(postal_code="1234567") expected = "該当するデータは見つかりませんでした。検索キーワードを変えて再検索してください。" self.assertEqual(expected, actual) if __name__ == "__main__": unittest.main()
27cf2ac960a447bffba4fae886c09be7024003f2
jigarshah2811/Python-Programming
/Interviews/Roblox/Find-Peak-Element.py
1,317
3.5
4
class Solution: def findPeakElement(self, nums: List[int]) -> int: # Edge cases N = len(nums) if N <= 1: return 0 # The element at index 0 is peak! # Since we'r checking mid+1 and mid-1 in our solution, we have to cover 0th and N-1th position if nums[0] > nums[1]: return 0 if nums[N-1] > nums[N-2]: return N-1 # Now regular binary search for indexes between 1 to N-1 low, high = 1, N-2 while low <= high: mid = low + (high-low) // 2 # Case 1: mid is greater then both neighbors - mid is peak! # Example [5, 6, 4] if nums[mid] > nums[mid-1] and nums[mid] > nums[mid+1]: return mid # Case 3: ASCENDING # mid is less then "next" neighbor: peak is on -----> right # Example: [3, 5, 6] elif nums[mid] < nums[mid+1]: low = mid+1 # Case 2: DESCENDING # mid is less then "prev" neighbor: peak is on <---- left # Example: [6,4,1] # elif nums[mid] < nums[mid-1]: else: end = mid-1 return low if nums[low] >= nums[high] else high
de60feccc4c4ebbe77b29557d5cf3b3b35d69d20
coc0dev/w2d2-exercise
/exercise1.py
1,924
4.34375
4
# Exercise 1 # ------------ # Takes Input # Stores input into a list # user can add or delete items # user can see current shopping list # loops until user 'quits' # after quitting bring out all items in cart def shopping_cart(): print(""" ____________________\n WELCOME TO THE SHOP! ____________________\n""") cart = [] sum_ = 0 checkout = {} stocklist = { # Dictionary of available items 1:{ "name": "graphic t-shirt", "qty": 5, "price": "1" }, 2:{ "name": "jeans", "qty": 5, "price": "1" }, 3:{ "name": "hat", "qty": 5, "price": "1" }, 4:{ "name": "blazer", "qty": 5, "price": "1" }, 5:{ "name": "boots", "qty": 5, "price": "1" }, 6:{ "name": "shoes", "qty": 5, "price": "1" }, } # Initial instructions for the user instructions = print(""" Type 'shop' to see the options. Type 'view' to see your cart. Type 'del' to remove the last item you added fromm the cart. Type 'checkout' to purchase your items.""") active = True while active: # Starts shopping loop choice = input("\nWhat would you like to do? 'shop', 'view', 'del', 'checkout': ") # Takes input for options if choice == 'shop': # Shows user availible items for i in stocklist.values(): print(i['name']) add = input("\ntype the name of the item to add it: ") # Allows user to add item to cart for i in stocklist.values(): if add == i["name"]: cart.append(i["name"]) print("\n-- * You added " + i["name"] + " * --\n") elif choice == 'view': # User can view cart print("\nItem(s) in cart -- "+str(cart)+" --") elif choice == 'del': # User can del most recent addition to the cart cart.pop() else: # User can checkout and end loop/ program if choice == 'checkout': active = False print("\n-- Thanks for shopping with us! --") print("Item(s) you purchased --"+str(cart)+"--\n") shopping_cart()
a43d3cd715fdf9f7dabf136669022a38da504fc3
jjc521/E-book-Collection
/Python/Python编程实践gwpy2-code/code/alg/sort_then_find3.py
556
4.15625
4
def find_two_smallest(L): """ (list of float) -> tuple of (int, int) Return a tuple of the indices of the two smallest values in list L. >>> find_two_smallest([809, 834, 477, 478, 307, 122, 96, 102, 324, 476]) (6, 7) """ # Get a sorted copy of the list so that the two smallest items are at the # front temp_list = sorted(L) smallest = temp_list[0] next_smallest = temp_list[1] # Find the indices in the original list L min1 = L.index(smallest) min2 = L.index(next_smallest) return (min1, min2)
d6eea6c5bb11d1b9c2be3c3c5d56bdfad044054a
togarobaja/Togar-Obaja-Nainggolan_I0320103_Tiffany-Bella-Nagari_Tugas-6
/Exercise 6.13.py
193
3.71875
4
def tambah (a,b): c = a + b return c x = int(input("masukkan bilangan ke 1:")) y = int(input("masukkan bilangan ke 2:")) hasil = tambah(x,y) print("%d + %d = %d" % (x,y, hasil))
3359142fb4f507dbaf6cfe48099363e945fcb822
Snikers1/repo
/Python/lesson_5/Task3.py
979
3.59375
4
#Создать текстовый файл (не программно), построчно записать фамилии сотрудников # и величину их окладов. # Определить, кто из сотрудников имеет оклад менее 20 тыс., # вывести фамилии этих сотрудников. # Выполнить подсчет средней величины дохода сотрудников. employees = dict() with open('Salaries.txt', 'r', encoding='utf-8') as salaries: for line in salaries.readlines(): emp, sal = line.strip().split() employees[emp] = sal less_20 = {emp: sal for emp, sal in employees.items() if int(sal) < 20000} print("Сотрудники, получающие менее 20 тыс.", less_20.keys()) salaries = list(map(float, employees.values())) print("Средняя величина дохода сотрудников", sum(salaries) / len(salaries))
251f78cf2d48f24f1d820b0774c5eceeaee46ee8
gjwlsdnr0115/algorithm-study
/pre-warmup/8.math1/math1_02.py
221
3.515625
4
n = int(input()) if n==1: print(1) else: count = 2 current = 7 while True: if current >= n: break else: current += (count*6) count += 1 print(count)
a29b8b0d5617a5897139141d71c02aa0fd8215dd
GuillermoLopezJr/Project-Euler
/Euler-015/Euler015.py
879
3.953125
4
#dynamic programming solution #answer: 137846528820 def printGrid(grid): for row in grid: for elt in row: print(elt, end=" ") print("\n") def getPaths(grid, startx, starty, goalx, goaly): if startx == goalx and starty == goaly: return 1 if (startx > goalx or starty > goaly): return 0 #look up if grid[startx][starty] != 0: return grid[startx][starty] else: grid[startx][starty] = getPaths(grid, startx+1, starty, goalx, goaly) + \ getPaths(grid, startx, starty+1, goalx, goaly) return grid[startx][starty] def main(): gridWidth, gridHeight = 20, 20 grid = [[0 for x in range(gridWidth+1)] for y in range(gridHeight+1)] startx, starty = 0, 0 goalx, goaly = 20,20 #print('printing grid'); #printGrid(grid) ans = getPaths(grid, startx, starty, goalx, goaly) print('answer: ', str(ans)) #print('printing grid'); #printGrid(grid) main()
025f51f655d4901d06b237f5cd738298ac53b0d1
Meeshbhoombah/makeschool
/CS3/source/search.py
2,600
4.28125
4
#!python def linear_search(array, item): """return the first index of item in array or None if item is not found""" # implement linear_search_iterative and linear_search_recursive below, then # change this to call your implementation to verify it passes all tests #return linear_search_iterative(array, item) return linear_search_recursive(array, item) def linear_search_iterative(array, item): # loop over all array values until item is found for index, value in enumerate(array): if item == value: return index # found return None # not found def linear_search_recursive(array, item, index=0): # implement linear search recursively here # once implemented, change linear_search to call linear_search_recursive # to verify that your recursive implementation passes all tests if index == len(array): return None if item == array[index]: return index linear_search_recursive(array, item, index + 1) def binary_search(array, item): """return the index of item in sorted array or None if item is not found""" # implement binary_search_iterative and binary_search_recursive below, then # change this to call your implementation to verify it passes all tests return binary_search_iterative(array, item) # return binary_search_recursive(array, item) def binary_search_iterative(array, item): # implement binary search iteratively here # once implemented, change binary_search to call binary_search_iterative # to verify that your iterative implementation passes all tests start_index = 0 stop_index = len(array) - 1 while start_index <= stop_index: split_index = int((start_index + stop_index) / 2) if array[split_index] == item: return split_index else: if item < array[split_index]: stop_index = split_index - 1 else: start_index = split_index + 1 def binary_search_recursive(array, item): # implement binary search recursively here # once implemented, change binary_search to call binary_search_recursive # to verify that your recursive implementation passes all tests if len(array) == 0: return else: split = len(array) // 2 if array[midpoint] == item: return True else: if item < array[split]: return binary_search_recursive(array[:midpoint], item) else: return binary_search_recursive(array[midpoint + 1:], item)
62a570e3ee8b1f00ea4c8944d42885b0f3bfc3cd
Ulfatin/PyMath
/PyMath/sqroot1.py
253
4.21875
4
# Program to read a number at run time and find its square root and ceiling value using math library functions. import math print("Program to calculate the Square root and absolute Value") num=121.56 print(math.sqrt(num)) print(math.ceil(num))
842c5df68edda8658ba4d8d5279059ab3e8e6e2b
Anirban2404/LeetCodePractice
/neigh.py
1,882
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 20 17:41:50 2019 @author: anirban-mac """ """ https://www.interviewbit.com/problems/neigh/ In real world horses neigh, and you can count them by listening to them. For this problem you will be given an input string consisting of lowercases letters which represents combination of neigh of different horses. You need to return an integer corresponding to minimum number of distinct horses which can produce the given sequence. If the input string is not a combination of valid neigh from different horses return -1. Example : Input : "nei" Output : -1 Explanation: Not a valid neigh. Input : "neighneigh" Output : 1 Explanation: Single horse yelling neigh two times. Input : "neingeighh" Output : 2 Explanation: Second horse can be seen speaking before the first one finished. """ class Solution: # @param A : string # @return an integer def solveneigh(self, A): word = "neigh" charDict = {val: key for key,val in enumerate(word)} print(charDict) dp = [0] * (len(word)) maxC = curC = 0 #Invalid Cases if len(A) % len(word) != 0 or A[0] != word[0]: return -1 for i in range(len(A)): #print(A[i]) if A[i] not in charDict: return -1 idx = charDict[A[i]] print(dp, idx) if idx == 0: curC += 1 maxC = max(maxC, curC) dp[0] += 1 else: if (dp[idx - 1] == 0): return -1 dp[idx - 1] -= 1 if idx == len(word) - 1: curC -= 1 else: dp[idx] += 1 print(dp, idx) return maxC A = "neigneihgh" print(Solution().solveneigh(A))
7a28acff2dc11e884ffe29b28e951f8b1292640d
CiyoMa/leetcode
/validParentheses.py
503
3.96875
4
class Solution: # @return a boolean def isValid(self, s): stack = [] for char in s: if char in ['(', '[', '{']: stack.append(char) else: if len(stack) == 0: return False left = stack.pop() if left == '{' and char == '}' or left == '(' and char == ')' or left == '[' and char == ']': continue else: return False return len(stack) == 0 s = Solution() print s.isValid("]]")
d3840e8d57d64cbed77d292c699a2d095b5a8b4d
LuisEnriqueCM/TestingSistemas
/ene-jun-2021/Luis Enrique Cazares Martinez/practicas/Practica 3/Triangulo_Test.py
665
3.625
4
import unittest import Triangulos class TestTriangulo(unittest.TestCase): def test_tipo(self): test_casos=[(1,2,3,"No es un Triangulo"), (4,4,4,"Es un Triangulo Equilatero"), (4,4,5,"Es un Triangulo Isoceles"), (4,3,6,"Es un Triangulo Escaleno"), (-1,0,9,"No es un Triangulo"), (0,0,0,"No es un Triangulo"), (-8,-10,-7,"No es un Triangulo")] for a,b,c,esperado in test_casos: actual = Triangulos.tipo_triangulo(a,b,c) self.assertEqual(esperado,actual) if __name__ == "__main__": unittest.main()
26619a19c53f4e9fc814cb3e2ac570bf70aa2e5f
dannko97/python_github
/麦叔-博客系统/learn_flask/init_db.py
659
3.5625
4
import sqlite3 # 创建数据库链接 connection = sqlite3.connect('database.db') # 执行db.sql中的SQL语句 with open('db.sql') as f: connection.executescript(f.read()) # 创建一个执行句柄,用来执行后面的语句 cur = connection.cursor() # 插入两条文章 cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)", ('学习Flask1', '跟麦叔学习flask第一部分') ) cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)", ('学习Flask2', '跟麦叔学习flask第二部分') ) # 提交前面的数据操作 connection.commit() # 关闭链接 connection.close()
56fd54e89964d46c1fc747655476597a3e8ae417
EvaOEva/python1
/10-逻辑运算符.py
433
3.8125
4
# 逻辑运算符: and, or, not score = 90 # and 表示左右两边条件都成立才会执行if语句 if score >= 90 and score <= 100: print("优秀") num1 = 1 # or 表示左右两边条件有一个条件成立就执行if语句 if num1 == 1 or num1 == 2: print("这个数字是我需要的") # not: 对结果进行取反, not对False 取反就True,对True就是False if not 1 == 2: print("条件成立执行")
008c269b078d05ac7eb6b3aa6cf2847bb5498de1
mothebad/mothebads-epicness
/play.py
582
3.8125
4
import random def clear(): print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") def printc(text): clear() print(text) printc("Hello!") input() printc("I'm mothebad!") input() printc("Type a number between 1 and 10") input() randomnum=-1 while randomnum<0 or randomnum>10: randomnum=int(input()) guess=random.randint(1,10) if randomnum==guess: print("You guessed it! :-)") else: print("You failed :-(")
518a37ea7bc3b6815efc423fdb4cde7776d2db03
sandhya563/function_question
/calculator.py
542
3.84375
4
# # question no 6 ka part one # def my_fun(x,y,sign): # if sign=="+": # return (x+y) # elif sign=="-": # return (x-y) # elif sign=="*": # return (x*y) # elif sign=="/": # return (x/y) # x=int(input("no==")) # y=int(input("2 no==")) # sign=input("enter the sign") # print(my_fun(x,y,sign)) def list_change(list1,list2): i=0 list=[] while i < len(list1): stor=my_fun(list1[i],list2[i],sign) list.append (stor) i=i+1 return list print(list_change([5, 10, 50, 20],[2, 20, 3, 5]))
486160b2ec8f83fd9ffbe271f14d3e8632d77085
AzinT/SpotGenius
/SpotGenius.py
2,425
3.5625
4
import sys, requests from bs4 import BeautifulSoup import json def currentSong(): url = "https://api.spotify.com/v1/me/player/currently-playing" payload = {} headers = { 'Authorization': 'YOUR SPOTIFY OAUTH TOKEN' } response = requests.request("GET", url, headers=headers, data = payload) respnoseJson = response.json() artistName = respnoseJson['item']['artists'][0]['name'] songName = respnoseJson['item']['name'] return {'artist': artistName, 'title': songName} def Searchgenius(song_title, artist_name): base_url = 'https://api.genius.com' headers = {'Authorization': 'Bearer ' + 'YOUR GENIUS TOKEN'} search_url = base_url + '/search' data = {'q': song_title + ' ' + artist_name} response = requests.get(search_url, data=data, headers=headers) return response def removeSongUrl(url): page = requests.get(url) html = BeautifulSoup(page.text, 'html.parser') [h.extract() for h in html('script')] lyrics = html.find('div', class_='lyrics').get_text() return lyrics def main(): #Get the song we trying to find lyrics for args_length = len(sys.argv) if args_length == 1: # Show lyrics for what user is playing on Spotify current_song = currentSong() artist_name = current_song['artist'] song_title = current_song['title'] elif args_length == 3: # Use input as song title and artist name song_info = sys.argv artist_name, song_title = song_info[1], song_info[2] else: print('Wrong number of arguments.\n' \ 'Use two parameters to perform a custom search ' \ 'or none to get the song currently playing on Spotify.') return print('{} by {}'.format(song_title, artist_name)) # Search for matches in request response response = Searchgenius(song_title[:30], artist_name) json = response.json() remote_song_info = None for hit in json['response']['hits']: if artist_name.lower() in hit['result']['primary_artist']['name'].lower(): remote_song_info = hit break # Extract lyrics from URL if song was found if remote_song_info: song_url = remote_song_info['result']['url'] lyrics = removeSongUrl(song_url) print(lyrics) else: print('Error 404: No lyrics found') if __name__ == '__main__': main()
2997ffb3af5a076ef8159a6b1a75a979eeb1a128
py2-10-2017/MatthewKim
/Fundamentals/DictInTupOut.py
488
3.71875
4
# function input my_dict = { "Speros": "(555) 555-5555", "Michael": "(999) 999-9999", "Jay": "(777) 777-7777" } #function output [("Speros", "(555) 555-5555"), ("Michael", "(999) 999-9999"), ("Jay", "(777) 777-7777")] def tupleit(my_dict): new_tuple=() keycount=0 for key,data in my_dict.items(): new_tuple+=(key,data) return new_tuple a=tupleit(my_dict = { "Speros": "(555) 555-5555", "Michael": "(999) 999-9999", "Jay": "(777) 777-7777" }) print a
4066a5d7de06cb38cfff3372be1e475076ada1ec
NathanRomero2005/Exercicios-Resolvidos-de-Python
/ex.008.py
895
4.25
4
# 8. Escreva um programa que leia um valor em metros e o exiba convertido em km, hm, dam, dm, cm, mm: m = float(input('Digite um valor em metros: ')) km = m / 1000 hm = m / 100 dam = m / 10 dm = m * 10 cm = m * 100 mm = m * 1000 print('{}{}{}, em metros, equivale a {}{}{} Km;'.format('\033[33m', m, '\033[m', '\033[35m', km, '\033[m')) print('{}{}{}, em metros, equivale a {}{}{} Hm;'.format('\033[33m', m, '\033[m', '\033[35m', hm, '\033[m')) print('{}{}{}, em metros, equivale a {}{}{} Dam;'.format('\033[33m', m, '\033[m', '\033[35m', dam, '\033[m')) print('{}{}{}, em metros, equivale a {}{}{} Dm;'.format('\033[33m', m, '\033[m', '\033[35m', dm, '\033[m')) print('{}{}{}, em metros, equivale a {}{}{} Cm;'.format('\033[33m', m, '\033[m', '\033[35m', cm, '\033[m')) print('{}{}{}, em metros, equivale a {}{}{} Mm.'.format('\033[33m', m, '\033[m', '\033[35m', mm, '\033[m'))
bf1d1dd16d93790ee8c6160b8b70f71e5a1dfc61
ktyu/Algorithm_Practice
/Practice_BasicAlgorithms.py
2,351
3.890625
4
# -*- coding: utf-8 -*- import copy # 맨 뒤에 큰 숫자들이 차례로 간다 def bubbleSort(raw_arr): arr = copy.deepcopy(raw_arr) for i in range(len(arr)-1): for j in range(len(arr)-1-i): if arr[j] > arr[j+1]: temp = arr[j] arr[j] = arr[j+1] arr[j+1] = temp return arr # 정렬 안된 전체 배열 스캔 후 가장 작은걸 맨 왼쪽으로 보냄 def selectionSort(raw_arr): arr = copy.deepcopy(raw_arr) for i in range(len(arr)): smallest_idx = i for j in range(i, len(arr)): if arr[smallest_idx] > arr[j]: smallest_idx = j temp = arr[i] arr[i] = arr[smallest_idx] arr[smallest_idx] = temp return arr # 다음 원소를 골라서, 이미 정렬된 왼쪽 배열의 적절한 위치를 찾아 땡기다가 해당 위치를 찾으면 삽입 def insertionSort(raw_arr): arr = copy.deepcopy(raw_arr) for i in range(1, len(arr)): picked = arr[i] for j in reversed(range(i)): if arr[j] > picked: arr[j+1] = arr[j] arr[j] = picked else: break return arr # 퀵소트 분할정복 (재귀, 추가 메모리 사용(코드 단순화 목적)) def quickSort(x): if len(x) <= 1: return x pivot = x[len(x) // 2] # // 은 나눗셈의 몫(정수)만 구하는 연산 less = [] more = [] equal = [] for a in x: if a < pivot: less.append(a) elif a > pivot: more.append(a) else: equal.append(a) return quickSort(less) + equal + quickSort(more) # 팩토리알 구하기 (재귀) def factorial(n): if n==0: return 1 elif n==1: return 1 return factorial(n-1)*n # 피보나치 수열 구하기 (재귀x, 반복문으로) def fibo(n): a=0 b=1 for i in range(n): a = a+b b = a-b return a raw_arr = [10,9,8,7,4,1,2,3,5,6] print "Raw :", raw_arr print "Bubble :", bubbleSort(raw_arr) print "Selection :", selectionSort(raw_arr) print "Insertion :", insertionSort(raw_arr) print "Quick :", quickSort(raw_arr) print "factorial :", factorial(10) print "fibo :",fibo(6)
8a3e40c06cdc3e525ec9c88c9cfd0bf81c0771fc
gubenkoved/daily-coding-problem
/python/dcp_331_flip_count.py
1,667
4.125
4
# This problem was asked by LinkedIn. # You are given a string consisting of the letters x and y, such as xyxxxyxyy. In addition, # you have an operation called flip, which changes a single x to y or vice versa. # Determine how many times you would need to apply this operation to ensure that all x's come # before all y's. In the preceding example, it suffices to flip the second and sixth characters, # so you should return 2. def flip_count(s: str) -> int: best = len(s) n = len(s) y_to_left = [0 for _ in range(n)] x_to_right = [0 for _ in range(n)] for idx in range(0, n): if s[idx] == 'y': y_to_left[idx] += 1 if idx > 0: y_to_left[idx] += y_to_left[idx - 1] for idx in range(n-1, -1, -1): if s[idx] == 'x': x_to_right[idx] += 1 if idx < n - 1: x_to_right[idx] += x_to_right[idx + 1] # suppose 'y' series starts at idx for idx in range(0, n + 1): cost = 0 # we need to flip all these 'x' to the right if idx < n: cost += x_to_right[idx] # AND we need to flip all these 'y' to the left if idx > 1: cost += y_to_left[idx - 1] best = min(best, cost) return best assert flip_count('xyxxxyxyy') == 2 # xXxxxXxyy assert flip_count('xyxxxyxyyx') == 3 # xXxxxXxyyY or xXxxxyYyyY assert flip_count('xyxxxyxyyxx') == 4 # xXxxxXxyyYY or .. assert flip_count('xyxxxyxyyxxx') == 4 # xXxxxXxXXxxx assert flip_count('yxxxxxxx') == 1 # Xxxxxxxx assert flip_count('yyx') == 1 # yyY assert flip_count('yyxx') == 2 # yyYY or XXxx assert flip_count('yyxxx') == 2 # XXxxx
e8ba9334988f01e7e92b4f1246633f6a388a4e90
kolyasalubov/Lv-627.PythonProject
/Tasks/task_088v.py
432
3.765625
4
from task import Task def _task(n: int) -> int: """ Given a natural number n, swap first and last digits of this number """ n = str(n) answer = f"{n[-1]}{n[1:-1]}{n[0]}" if len(n) > 1 else n return int(answer) task_088v = Task( name="task_088v", body=_task, description=""" Given a natural number n, swap first and last digits of this number """, test="Tasks/test_task_088v.py" )
7f51d41e9a5d82f93a1965460f29e02df2316caa
singultek/ModelAndLanguagesForBioInformatics
/Python/List/3.sublist.py
1,876
4.0625
4
from typing import List, Any def ascending(list): for i in range(len(list)-1): if list[i] < list[i+1]: return True return False def subset(list1: List, list2: List) -> bool: """ Check if all the element of list1 are inside list2, preserving only the order :param list1: list1 of element to find :param list2: list2 target list :return: a boolean which represent True if the statement is respected """ idx_position: List[int] = [] for element in list1: _idx = idx_position[-1] if len(idx_position) > 0 else 0 while _idx < len(list2): if element == list2[_idx]: idx_position.append(_idx) break _idx += 1 return ascending(idx_position) and len(idx_position) == len(list1) def sublist(list1: list, list2: list) -> bool: """ Check if all the element of list1 are inside list2, preserving the order and subsequence of the elements :param list1: list1 of element to find :param list2: list2 target list :return: a boolean which represent True if the statement is respected """ _list2_idx = 0 for element in list2: if element == list1[0]: _list1_idx = 1 _list2_iterator = _list2_idx+1 while _list1_idx < len(list1): try: _value = list2[_list2_iterator] except Exception as ex: return False if _value != list1[_list1_idx]: break _list2_iterator +=1 _list1_idx +=1 if _list1_idx == len(list1): return True _list2_idx +=1 return False if __name__ == "__main__": print(subset([1,2,3],[4,2,45,6,1,7,8,3,10])) print(sublist([1, 2, 3], [4, 2, 1, 2, 3, 3, 3, 1, 2, 4]))
54d92ea57071a75db6057d43917832946ea9a963
pisskidney/leetcode
/medium/109.py
2,196
3.859375
4
""" 109. Convert Sorted List to Binary Search Tree https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ """ from typing import Optional # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __str__(self): return str(self.val) # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def __str__(self): return ( f' {self.val}\n' f' / \\\n' f'{self.left.val if self.left else None} ' f'{self.right.val if self.right else None}\n' ) def inorder(head): if head is None: return inorder(head.left) print(head.val) inorder(head.right) class Solution: def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]: def go(l, r): print(l, r) if l is None and r is None: return TreeNode(l.val) if l is None: return TreeNode(r.val) if r is None: return TreeNode(l.val) if l is r: return TreeNode(l.val) prev = None slow = l fast = l while fast != r and fast.next and fast.next != r and fast.next.next: prev = slow slow = slow.next fast = fast.next.next node = TreeNode(slow.val) if prev is not None: node.left = go(l, prev) node.right = go(slow.next, r) return node if not head: return None last = head while last.next: last = last.next return go(head, last) def main(): s = Solution() a = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5, ListNode(6)))))) inorder(s.sortedListToBST(a)) inorder(s.sortedListToBST(ListNode(-10, ListNode(-3, ListNode(0, ListNode(5, ListNode(9))))))) if __name__ == '__main__': raise(SystemExit(main()))
214c264c2f75facb9ef37af98af9d8a67cd8d932
saabii/HW-lession-03
/ex4.2.py
224
3.71875
4
invitation = input('Dear ') l = invitation.split(' ') male = 'mr' female = ['mrs', 'miss', 'ms'] if l[0].lower() in female: print('Female') elif l[0].lower() in male: print('Male') else: print('Error')
195b259035c4e9d3b9b885fcad089c04372f557d
Nubstein/Python-exercises
/Condicionais e Loop/Ex8.py
497
4.125
4
#Faça um Programa que pergunte em que turno você estuda. Peça para digitar M-matutino ou V-Vespertino ou N- Noturno. #mensagem "Bom Dia!", "Boa Tarde!" ou "Boa Noite!" ou "Valor Inválido!", conforme o caso. x=input("Qual turno você estuda? ") x=x.upper() if x=="MATUTINO" or x=="MANHÃ" or x=="M": print("Bom dia!") elif x=="VESPERTINO" or x=="TARDE" or "T": print ("Boa Tarde!") elif x=="NOITE" or x=="NOTURNO" or x=="N": print("Boa Noite!") else: print("Valor Inválido")
588bc43c54559574a023c1a204d40fb3f902f1b9
KiruthikaaaPandiyann/pythonprograms
/alpha.py
100
3.765625
4
str=input() s=str.lower() l=ord(s) if(l>=97 and l<=122): print("Alphabet") else: print("No")
8906c665b26dce526e3e2639e9ece06ed45ee57d
DiogoM14/Python-Exercicios
/PythonTeste/aula13.py
502
3.890625
4
for c in range(7, 0, -1): print(c) print('FIM') for c in range(0, 7, 2): print(c) print('FIM') n = int(input('Escreva um número: ')) for c in range (0, n+1): print(c) print('FIM') i = int(input('INICIO: ')) s = int(input('SALTO: ')) f = int(input('FIM: ')) for c in range(i, f+1, s): print(c) print('FIM') s = 0 for c in range(0, 4): n = int(input('Escreva um número: ')) s = s + n print('A soma de todos os valores é de {}'.format(n))
6e17aaaa30f3c40ded66ebecbd51951b1a5b7790
abhishekkrm/Projects
/OS/MP1/q10-speeddate.py
1,892
3.90625
4
from threading import Thread, Lock import time, random # This problem models a speed dating application. A matchmaker thread will # repeatedly select two eligible bachelors and then let them meet for a few # minutes to see if they have chemistry. # # A bachelor can only participate in one date at a time. # # Modify the following code to avoid deadlocks bachelors = [Lock() for i in range(100)] class Matchmaker(Thread): def __init__(self, id): Thread.__init__(self) self.id = id def run(self): while True: b1 = random.randrange(100) b2 = random.randrange(100) # you can't date yourself if b1 == b2: continue # # The problem here is one thread may be waiting for b2 which is # locked by other thread and vice versa. For Example, lets say # thread one is waiting for b2(10) with lock on b1(5) and thread # two may be waiting for b2(5) with lock on b1(10). This result # in deadlock as none of the thread can make progress. # # To avoid deadlock we need to make sure that resources are always # acquired in well defined order. # Therefore by ensuring b1 < b2 (or b1 > b2) we can avoid deadlock. # # If b1 is more than b2 then swap so that b1 always less than b2. # if b1 > b2: b1,b2 = b2,b1 bachelors[b1].acquire() bachelors[b2].acquire() # check for chemistry (which apparently involves sleeping) print ("matchmaker %i checking bachelors %i and %i" % (self.id, b1, b2)) time.sleep(0.1) bachelors[b1].release() bachelors[b2].release() for i in range(20): Matchmaker(i).start() ## ## vim: ts=4 sw=4 et ai ##
18b71b68467927cfbdd0b8681e9ad66adfc6c5a7
Honichstulle/PythonStuff
/hangman.py
1,363
3.6875
4
import random #Funktion die prüft ob der eingegebene Buchstabe im Wort vorhanden ist def check_letter(wd,wl,array): wrong = 0 strike = 0 counter = 0 guess_array = array while strike < 11: guess = input("Rate einen Buchstaben: ") for i in wd: if guess == i: counter = counter + 1 guess_array.insert(counter,i) del guess_array[counter - 1] else: wrong = wrong + 1 counter = counter + 1 if wrong == wl: strike = strike + 1 print("Incorrect!") print("Wrong Guesses: " + str(strike)) print(guess_array) wrong = 0 counter = 0 else: print("Correct!") print(guess_array) wrong = 0 counter = 0 if "-" not in guess_array: return print ("Congratulations, you guessed the word!") #Liste die alle verfügbaren Wörter enthält wordlist = ['feuerwehr', 'polizei', 'rettungswagen'] #Funktion um ein zufälliges Wort aus der Liste auszuwählen word = random.choice(wordlist) #Länge des aktuellen Wortes wordlength = len(word) #Erstellen des Arrays, welches später die richtig geratenen Buchstaben enthält guess_array = [] for i in word: guess_array.append("-") print("Das gesuchte Wort hat " + str(wordlength) + " Buchstaben") check_letter(word,wordlength,guess_array)
fcab4d319bd5c691c73777b74ed8b02fff77d02b
Blinkinlabs/BlinkyTape_Python
/binary_clock.py
1,675
3.703125
4
"""Binary clock example using BlinkyTape.py Displays UNIX epoch time using 32 LEDs (white), localtime hours using 6 LEDs (red), localtime minutes using 6 LEDs (green), localtime seconds using 6 LEDs (blue) """ from blinkytape import BlinkyTape import time from datetime import datetime, timedelta import optparse MAX_BRIGHTNESS = 50 # in range(255) def display(blinky): dt = datetime.now() send_binary(int(time.time()), 32, blinky, MAX_BRIGHTNESS, MAX_BRIGHTNESS, MAX_BRIGHTNESS) send_binary(dt.hour, 6, blinky, MAX_BRIGHTNESS, 0, 0) send_binary(dt.minute, 6, blinky, 0, MAX_BRIGHTNESS, 0) send_binary(dt.second, 6, blinky, 0, 0, MAX_BRIGHTNESS) # padding empty pixels - can add more info send_binary(0, 10, blinky, 0, 0, 0) blinky.show() def send_binary(word, length, blinky, r, g, b): fmt = "{0:0" + str(length) + "b}" array = list(fmt.format(word)) for bit in array: blinky.sendPixel(r * int(bit), g * int(bit), b * int(bit)) parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="portname", help="serial port (ex: /dev/ttyUSB0)", default=None) options, args = parser.parse_args() if options.portname is not None: port = options.portname else: print("Usage: python binary_clock.py -p <port name>") print("(ex: python binary_clock.py -p /dev/ttypACM0)") exit() blinky = BlinkyTape(port) # roughly synchronize with seconds time.sleep(1 - datetime.now().microsecond / 1000000.0) while True: timeBegin = time.time() display(blinky) timeEnd = time.time() timeElapsed = timeEnd - timeBegin time.sleep(1 - timeElapsed)
8b77669a6a88de5396d39d7a6e0122a2f6b42b4d
jen8/Object-Oriented-Apps
/pack_geometry.py
234
3.765625
4
import tkinter as tk # import library root = tk.Tk() # create window label1 = tk.Label(root, text="BANANA") # create label button1 = tk.Button(root, text="Button!") label1.pack() button1.pack() root.mainloop() # keep window open
e70e0c9ea3b7d356abc0e60fb23bdc1c30b295a5
CapCorrector/uscs-classes
/python/assign2/mult_table.py
420
3.65625
4
def table_loop(): pass res = [] for x in range(1, 10): res.append([]) for y in range(1, x+1): res[x-1].append((str(y) + ' * ' + str(x) + ' = ' + str(x*y))) print(' '.join((res[x-1]))) def table_comp(): resc = [[str(y) + ' * ' + str(x) + ' = ' + str(x*y) for y in range(1, x+1)] for x in range(1,10)] for x in range(0, 9): print(' '.join(resc[x])) if __name__ == '__main__': table_loop() table_comp()
5fb8504c82b64c0225263623164ecab0f42d9cc1
markbeutnagel/word-search-trie
/search.py
6,366
3.5625
4
#!/usr/bin/python3 import argparse import pdb help_msg = ''' Given two files: (1) a rectagular letter grid (i.e. word-search puzzle), and (2) a list of words, one per line Print each word with one or more "origins", or "False" if not found. Each word origin is {row}_{column}_{direction}, e.g. "12_5_UL", where "UL" means the upper-left diagonal starting from (12,5). ''' # 2019-05 Mark Beutnagel # # This solution builds a trie from the puzzle grid, then searches words # one at a time. The trie also encodes the origin and direction of each # string. # # - NB: To avoid spurious duplication, all single-letter "strings" are # recorded with 'X' representing a null direction: "X marks the spot". # This will prevent the word "A" from appearing 8 times at the same coordinate, # each with a different direction. # TODO: Unit tests # TODO: Timing # TODO? Create a TrieNode class rather than use a special key for origin coordinates? # TODO? Write output as JSON for more flexible testing? ##----------------------------------------------------------------------- ## Constants # Directions within letter grid are the cap-letter abbreviations of # Right, Left, Up, Down, UpRight, UpLeft, DownRight, DownLeft # The table values are (row, column) increments to index the next character # in a row, column, or diagonal. Special non-direction X applies only to # single-characters, and is used to prevent the single-character work "A" # from being recorded with 8 different directions. # TODO? for 'X' we could replace (None,None) with (MAXINT, MAXINT). # One step in any direction is outside the puzzle and no further logic # is needed to prevent use. DIRECTIONS = { 'U': (-1, 0), 'UR': (-1, +1), 'R': (0, +1), 'DR': (+1, +1), 'D': (+1, 0), 'DL': (+1, -1), 'L': (0, -1), 'UL': (-1, -1), 'X': (None, None) } # Keep a list of word-start tuples in each node. For now just use the following # non-letter key within the existing letter dictionary. Example: if the word # "atom" apears twice in the puzzle, and "atomic" appears once, the trie # might contain something like this: # # ... {'o': ... # {'m': # {'i': {'c'; ...}, # 'WORD_ORIGINS': [(3,6,'DR'),(12,8,'U')], # ... }, ... }} # # This shows "atom" is found at row 3, column 6 going down-right and at row 12, # column 3 straight up. Note that the 'm' node contains both the origin info # and the continuation of the word 'atomic'. Also note that every node on the # path to "atomic" will include the same origin info, so e.g. the word "at" # will include these origins, and perhaps many others (e.g. "attic"). WORD_ORIGINS = '<Origins>' ##----------------------------------------------------------------------- ## Utility Functions def populate_trie(trie, grid, nrows, ncols, env): '''For every starting point and every direction, scan that string into the trie.''' if env['verbose']: print(grid) for row in range(nrows): if env['verbose']: print(f'processing row {row}') for col in range(ncols): if env['verbose']: print(f'processing column {col}') for d in DIRECTIONS: if d in ['X']: continue r_step, c_step = DIRECTIONS[d] if env['verbose']: print(f'processing direction {d}') # first level uses the 'X' to collapse directions for single-letters multi_character = False origin_x = f'{row}_{col}_X' origin = f'{row}_{col}_{d}' # temporary vars for loop below r, c, t = row, col, trie while r>=0 and r<nrows and c>=0 and c<ncols: letter = grid[r][c] if env['verbose']: print(f'letter: {letter} at ({r},{c})') if not letter in t: # uses set() to collapse multiple 'X' origin entries t[letter] = {WORD_ORIGINS: set()} t = t[letter] t[WORD_ORIGINS].add(origin if multi_character else origin_x) multi_character = True if env['verbose']: print(r,c,letter) r += r_step c += c_step ##----------------------------------------------------------------------- ## Classes # Class Puzzle, constructed from the 2-D letter array class Puzzle(object): def __init__(self, list_of_strings, env): self.nrows = 0 self.ncols = 0 self.trie = {} self.env = env if list_of_strings: self.ingest(list_of_strings) def search(self, word): t = self.trie for ch in word: if ch not in t: return False t = t[ch] return t[WORD_ORIGINS] def ingest(self, lofs): if self.trie: raise Exception('This object has already been initialized.') # validate list of strings; init number of rows & columns grid = [] if not lofs: raise Exception('Input cannot be empty') if type(lofs) not in [list, tuple]: raise Exception('Input must be a list or tuple of strings') for s in lofs: self.nrows += 1 if not self.ncols: self.ncols = len(s) elif self.ncols != len(s): raise Exception(f'Expected #columns {self.ncols}, but row {self.nrows} has {len(s)}') grid.append(s) populate_trie(self.trie, grid, self.nrows, self.ncols, self.env) ##----------------------------------------------------------------------- ## MAIN parser = argparse.ArgumentParser(description=help_msg) parser.add_argument('--words', type=argparse.FileType('r'), required=True, help='Filename of the word list') parser.add_argument('--puzzle', type=argparse.FileType('r'), required=True, help='Filename of the puzzle grid') parser.add_argument('--verbose', '-v', dest='verbose', action='store_true', default=False) args = parser.parse_args() puzzle = [line.strip() for line in args.puzzle] puzzle = [line for line in puzzle if line] words = [line.strip() for line in args.words] words = [line for line in words if line] env = {'verbose': args.verbose} p = Puzzle(puzzle, env) for w in words: print(w, p.search(w))
c87fb4cffb1acf37da7fd32327af3f0f868bf403
dailycodemode/dailyprogrammer
/Python/022_appendMissingCharacters.py
1,021
4
4
# # https://www.reddit.com/r/dailyprogrammer/comments/qr0hg/3102012_challenge_22_easy/ # list1, list2 = ["a","b","c",1,4,], ["a", "x", 34, "4"] # # # MINE # def append_list(list1, list2): # for c in list2: # if c not in list1: list1.append(c) # return list1 # # # # ANSWER by idliketobeapython # def append_unique(a, b): # return a + [item for item in b if item not in a] # # # BREAKDOWN # a + [item for item in b if item not in a] # # is our first list and everything after that it just another line being added on # paul = [item for item in list2] # except we don't want all of # # list2 so we add a conditional # paul = [item for item in list2 if item not in list1] # # SUMMARY # i've started to notice that one liners are are a very popular thing # to do in python and it is a mark of ability to be able to achieve them # The answer is neat and short. The only difference I would make is changing # the variable names however, this was likely done to keep it neat.
1c43def9b024a492a436c5b00c359d612f235ab8
hpoleselo/effectivenotations
/effectivepython.py
9,224
4.03125
4
import collections import argparse print(" ") print("-------- Book Notes from Effective Python --------") print(" ") print("Chapter 2: Methods and Functions, give number 2 as input.") print("Chapter 3: Classes, give number 3 as input.") print(" ") chapter = input("Which chapter do you want to run? ") if chapter == 2: print(" ") class NotesChapter2(object): def __init__(self): self.ten = 10 self.three = 3 self.nine = 9 self.list = [20, 30, 40, 70] def generator(self): """ What is really a generator """ pass def trying_excepting(self): """ except gives us the possibility to cleanup our code regardless what happens on the try block! """ print (" ") print ("---- Trying Excepting Finally ---- ") try: print "Always gonna be executed" print self.three > self.nine print 4/0 except: print "Only will be called when an exception error is raised. In this case ValueError!" else: print "Come on... Another error?" finally: print "Will ALWAYS be executed as well!" def handling_exception(self): print (" ") print "---- Handling Exception ----" def divide(a, b): try: a/b except ZeroDivisionError as e: raise ValueError("Division not possible, invalid inputs") x,y = 5,0 divide(x,y) def closure(): ''' Closure allows us to a function access variables from other function, like in our case we can call the helper function and iterate over the values from the main function. The flag Found is in Python 2 poorly implemented because we don't have the nonlocal keyword, hence we Found as list (mutable). ''' print (" ") print "---- Closure ----" def sorting_w_prio(values, group): Found = [False] def helper(x): # Uncomment the line below if you are using Python 3 #nonlocal Found if x in group: Found[0] = True print Found[0] return 0, x return 1, x values.sort(key=helper) values = [10, 32, 40, 100, 5, 9] group = {5, 7, 40, 32} sorting_w_prio(values, group) print values def generator(): ''' When we iterate over a list and then for every iteration we do, for instance, a squaring operation, then we have to store it to a variable... We can use instead generator expression so it iterates but does'nt necessarily stores the value (this makes a difference for huge iterations and saves memory. REMINDER: We could use a chain of generator expressions, which is quite fast as well. The output of one generator could feed the input of another! ''' print (" ") print "---- Generator Expression ----" # We store every squared value in the new list called sqd_value list = [1, 2, 3, 4, 5, 10 , 20] sqd_value = [x**2 for x in list] # Here we don't consume so much memory as above # But keep in mind that we end up actually using a stateful method, meaning it's only safe to use it once on our code gen = (x**2 for x in list) print next(gen) print next(gen) print next(gen) print gen print type(gen) def variable_positional_argument(self, x, y=1, *z): ''' Usually we have a function that takes for instance 2 values as arguments, let's say that this function actua- lly doesn't need the two values EVERY time it's called. And we want to pass just one argument... So we can use the so famous variable position argument VPA. In this function we use x,y,z as inputs for this func. But z is a VPA. Note that when printing the read value from z is contained in a tuple. Instead of using VPA for some variable that we don't always need to use we could use the keyword and setting it to a value that doesn't change the function! Only when set differently, so we set it to a fixed value like z=1. IMPORTANT: we use None as pre-defined value on a position argument that is mutable. ''' print (" ") print ("---- Variable Positional Argument ----") w = x + 10 print ("Value of x + 10 = "), w print ("Value of y:"), y if y != 1: print ("The user has given a different value for y: "), y print ("Value of z:"), z def keywordarguments_are_important(self, **kwargs): """ In this case our function doesn't require ANYTHING. But if we want to provide any value, we have then to use the keyword assign to the function, otherwise it will complain about it. """ print (" ") print ("---- Testing kwarg ----") print ("Printing the keyword arguments given by the user: \n"), kwargs def named_tuple(self): """ If we want to create a small container, instead of creating a Class we can use the function namedtuple(). """ Point = collections.namedtuple("Point", ["x","y"], verbose=True) def defaultdict(self): """ Works like a mini github where we can differentiate what has been changed! Super. """ default_list = [10, 20, 30, 40] def test_assert(self): """ assert is just for testing a condition in Python, if it's not satisfied (returns False) and then it raises an AssertError. A short way to validate if something is True or Not!""" print (" ") print ("---- Testing assert ----") print ("Will raise an AssertError!") x = 10 y = 20 assert x == y def main(): nc2 = NotesChapter2() nc2.trying_excepting() #test.handling_exception() nc2.variable_positional_argument(5,5,5) # Now we wish to give only ONE variable for it and even though the function doesn't complain about it. nc2.variable_positional_argument(3) nc2.keywordarguments_are_important(test1="Hello", test2=10) nc2.test_assert() main() if chapter == 3: print (" ") class NotesChapter3(object): class EasyClassCall(object): """ Using the __call__ function inside a Class makes easier to call the Class like a function! """ print ("---- __call__ function within a Class ----") def __call__(self, a, b): print (" The inner method of the class was easily called like calling a function!") print ("Values passed: "), a, b def main (): nc3 = NotesChapter3() ecc = nc3.EasyClassCall() # Realize how easy it is to actually pass the variables to the class and call the function. ecc(2,3) main() def parser(): # In order to run this function we have to execute the python file as: # python effectivepython.py -d alvar # Because -d is an optional argument and by not giving it to the program the parser parses nothing. class Parser(object): def __init__(self): parser = argparse.ArgumentParser(description="Aruco or Alvar") parser.add_argument("-d", "--detection", help="String to choose between Aruco or Alvar detection.") self.args = parser.parse_args() super(Parser, self).__init__() class TypeOfDetection(Parser): def __init__(self): print ("") print ("---- Parser Example with Class Inheritance ----") Parser.__init__(self) detection = self.args.detection if detection == "aruco": print ("Will run aruco") if detection == "alvar": print ("Will run alvar") TypeOfDetection() parser() def mult_class_inheritance(): print ("") print ("---- Inheritance between Classes ----") class A(object): def __init__(self): # Will be printed after B print ("This is A") self.x = 10 super(A, self).__init__() class B(A): def __init__(self): # Will be printed before A because we call the Class B, and B calls then A. print("This is B") A.__init__(self) # Inheriting variable from A print self.x # Calling B B() mult_class_inheritance() else: print("Not a valid option... Exiting the program.") quit()
78a6d536d99e93687260ae6b922f857efafbe0a7
Hyacinthe04/password
/password.py
1,157
3.765625
4
class User: """ Class that generates new instances of contacts. """ user_list = [] # Empty user list def __init__(self,username,password): # docstring removed for simplicity self.username = username self.password = password user_list = [] # Empty contact list # Init method up here def save_user(self): ''' save_user method saves contact objects into contact_list ''' User.user_list.append(self) def delete_user(self): ''' delete_contact method deletes a saved contact from the contact_list ''' User.user_list.remove(self) @classmethod def user_exist(cls,username): ''' Method that checks if a contact exists from the contact list. Args: number: Phone number to search if it exists Returns : Boolean: True or false depending if the contact exists ''' for user in cls.user_list: @classmethod def display_users(cls): ''' method that returns the contact list ''' return cls.user_list
16f01a8235ab764e57c56da1f30a6f83642495ea
MAHESHRAMISETTI/My-python-files
/exception.py
395
3.890625
4
# while 1: # a=int(input('enter a num in numerator')) # b=int(input('enter a num in denominator')) # try: # c=(a/b) # except ZeroDivisionError: # print('there is zero in denominator') # else: # print(c) # finally: # print('the code has been executed') #raise try: a=5 print(a) raise NameError('hi bro!!!!!!') except NameError as n: print('there is an exception') print(n)
5dae640ac1e42fd132d379a98c08ac44bfdd996b
ZaidanNur/PojectProjectan
/Knapsack/knap.py
1,409
3.65625
4
weight =[3,1,2,2,2] price = [100,100,150,180,250] capacity = 3 table = [[0 for col in range(capacity+1)] for row in range(len(weight)+1)] for row in range(len(weight)+1): for col in range(capacity+1): if row == 0 or col==0: table[row][col]=0 elif weight[row-1] <= col: table[row][col] = max(table[row-1][col],table[row-1][col-weight[row-1]]+price[row-1]) else: table[row][col] = table[row-1][col] for row in table: print(row) maks_value = table[len(weight)][capacity] things = [] for x in range(len(weight),0,-1): if maks_value >0: maks_value = maks_value - price[x-1] things.append(x) print(f"{things}") n = len(weight) for i in range(n, 0, -1): if maks_value <= 0: break # either the maks_valueult comes from the # top (K[i-1][w]) or from (val[i-1] # + K[i-1] [w-wt[i-1]]) as in Knapsack # table. If it comes from the latter # one/ it means the item is included. if maks_value == table[i - 1][capacity]: continue else: # This item is included. print(weight[i - 1]) # Since this weight is included # its value is deducted maks_value = maks_value - price[i - 1] capacity = capacity - weight[i - 1]
43cdcc4641af6f80bf1abfc4ccdd41fec09e1179
NallamilliRageswari/Python
/VC_Count.py
377
3.515625
4
''' vowel & Constants Count and both multiplied gives result. Input: 2 abcdefg scdegh Output: 2 5 10 1 5 5 ''' n=int(input()) for _ in range(n): s=input() c=0 v=0 for j in s: if('a'==j or 'e'==j or 'i'==j or 'o'==j or 'u'==j): v+=1 else: c+=1 print(v,c,v*c)
e2af2297021ebc769b4e56b93325ad965b744633
KristianMSchmidt/Fundamentals-of-computing--Rice-University-
/Interactive Programming/Andet/circle_timer.py
585
3.96875
4
# Expanding circle by timer ################################################### # Student should add code where relevant to the following. import simplegui WIDTH = 1000 HEIGHT = 1000 radius = 1 # Timer handler def tick(): global radius radius=radius+1 # Draw handler def draw_handler(canvas): canvas.draw_circle([WIDTH/2, HEIGHT/2], radius, 10, 'Yellow', 'Orange') # Create frame and timer frame = simplegui.create_frame("Home", WIDTH, HEIGHT) timer = simplegui.create_timer(100,tick) frame.set_draw_handler(draw_handler) # Start timer frame.start() timer.start()
fb2b58a0e656e0095ee33678a3158fe008e07f66
wls-admin/entrepot
/demo13.py
119
3.578125
4
b=0 h=0 while True: b=b+1 h+=3 if h==20: print("一共跳了",b,"天") break h -= 2
48208736b15af7a2c6c0bcf0a62a680f7ed974a3
crystalbai/Algorithm
/problems/quicksort.py
1,052
3.8125
4
import random import sys def quick_sort(nums, s,e): if s <e: pivot = part(nums, s,e) quick_sort(nums,s, pivot-1) quick_sort(nums, pivot+1, e) def part(nums, s,e): idx = random.randint(s, e) nums[idx], nums[s] = nums[s], nums[idx] pivot = nums[s] small = s for i in range(s+1,e+1): if nums[i] < pivot: small += 1 nums[small], nums[i] = nums[i], nums[small] nums[small], nums[s] = nums[s], nums[small] return small def quickSortVersion2(nums): if len(nums) == 0: return [] idx = random.randint(0, len(nums)-1) small = [i for i in nums if i < nums[idx]] equ = [i for i in nums if i == nums[idx]] large = [i for i in nums if i > nums[idx]] small = quickSortVersion2(small) large = quickSortVersion2(large) return small+equ+large def main(): nums = [10,1,2, 6,3,7,8,8,4,10] quick_sort(nums, 0, len(nums)-1) print nums nums2 = [10,1,2] print quickSortVersion2(nums) if __name__ == "__main__": main()
b431d4149d6101e062734e8f71a6fece6122fc63
keveleigh/espn-sftc
/props.py
4,060
3.5
4
#!/usr/bin/env python """ This scrapes Streak for the Cash information from ESPN and writes it to an Excel spreadsheet. It uses BeautifulSoup 4 and xlsxwriter. In order to use this, you will need to download bs4, lxml, and xlsxwriter. Prop array format: [Sport, League, Prop, Active Picks %, Winner, Winner %, Loser, Loser %] Command format: python props.py [number of days] """ import urllib.request import re import xlsxwriter import operator import collections import sys import ast import os from datetime import date, timedelta, datetime from bs4 import BeautifulSoup def _format_url(date): """Format ESPN link to scrape records from.""" link = ['http://streak.espn.go.com/en/entry?date=' + date] print(date) return link[0] def scrape_props(espn_page, allProps): """Scrape ESPN's pages for data.""" url = urllib.request.urlopen(espn_page) soup = BeautifulSoup(url.read(), 'lxml') props = soup.find_all('div', attrs={'class': 'matchup-container'}) for prop in props: propArray = [] time = prop.find('span', {'class': 'startTime'})['data-locktime'] time = time[:-4] format_time = datetime.strptime(time, '%B %d, %Y %I:%M:%S %p') sport = prop.find('div', {'class': 'sport-description'}) if sport: propArray.append(sport.text) else: propArray.append('Adhoc') title = prop.find( 'div', {'class': ['gamequestion', 'left']}).text.split(': ') propArray.append(title[0]) propArray.append(title[1]) overall_percentage = prop.find('div', {'class': 'progress-bar'}) propArray.append(overall_percentage['title'].split(' ')[3]) percentages = prop.find_all('span', {'class': 'wpw'}) info = prop.find_all('span', {'class': 'winner'}) temp = info[0].parent.find_all('span', {'id': 'oppAddlText'}) [rec.extract() for rec in temp] temp = info[1].parent.find_all('span', {'id': 'oppAddlText'}) [rec.extract() for rec in temp] if info[0].contents[0].name == 'img': propArray.append(info[0].parent.get_text()) propArray.append(percentages[0].text) propArray.append(info[1].parent.get_text()[1:]) propArray.append(percentages[1].text) else: propArray.append(info[1].parent.get_text()) propArray.append(percentages[1].text) propArray.append(info[0].parent.get_text()[1:]) propArray.append(percentages[0].text) # Prop array format: # [Sport, League, Prop, Active Picks %, Winner, Winner %, Loser, Loser %] allProps[format_time.date()].append(propArray) def write_to_excel(allProps): wb = xlsxwriter.Workbook('Streak.xlsx') ws = wb.add_worksheet('All Props') #ws.set_column(0, 0, 2.29) #ws.set_column(1, 1, 14.14) #ws.set_column(5, 5, 2.29) date_format = wb.add_format({'num_format': 'mm/dd/yy'}) format_percentage = wb.add_format({'num_format': '0.0"%"'}) format_percentage2 = wb.add_format({'num_format': '0.00"%"'}) i = 0 for date in allProps: for prop in allProps[date]: ws.write(i, 0, date, date_format) ws.write(i, 1, prop[0]) ws.write(i, 2, prop[1]) ws.write(i, 3, prop[2]) ws.write(i, 4, float(prop[3][:-1]), format_percentage2) ws.write(i, 5, prop[4]) ws.write(i, 6, float(prop[5][:-1]), format_percentage) ws.write(i, 7, prop[6]) ws.write(i, 8, float(prop[7][:-1]), format_percentage) i += 1 wb.close() def main(argv): allProps = collections.OrderedDict() for x in range(0, int(argv[0])): newDate = date.today() - timedelta(days=x + 1) allProps[newDate] = [] scrape_props(_format_url(newDate.strftime('%Y%m%d')), allProps) write_to_excel(allProps) if __name__ == '__main__': import time start = time.time() main(sys.argv[1:]) print(time.time() - start, 'seconds')
709bc3cba968663cf9a15e3958b1f2fbd67f172c
blaurensayshi/Curso_Topicos_Programacao_Python
/Aula3/Exercício 1.1.py
376
4.03125
4
""" Número de Fibonacci Fn = Fn-1 + Fn-2 F0 = 0 ; F1 = 1 """ def Fibonacci(numero): if numero == 0: return 0 if numero == 1: return 1 else: return Fibonacci (numero - 1) + Fibonacci (numero - 2) x = int(input("Digite um número para calcular: ")) res = Fibonacci(x) y = 0 while Fibonacci(y) <=res: print(Fibonacci(y)) y += 1
8f0b1a2ec5d31b3a74f450e449629bbe845248fb
lessunc/python-guanabara
/task075.py
1,107
4.0625
4
#coding: utf-8 #-------------------------------------------------------------------------- # Um programa que recebe 4 números em uma tupla e retorna: # • Quantos números 9| • Posição do 1º número 3|• Quais os números pares| #-------------------------------------------------------------------------- # Maior e menor valores em Tupla - Exercício #075 #-------------------------------------------------------------------------- pares = 0 valor = (int(input('Digite um número: ')), int(input('Digite outro número: ')), int(input('Digite mais número: ')), int(input('Digite o último número: '))) print('\033[2;35m====\033[m' *11) #linha colorida(not important) print(f'Você digitou os valores {valor}') print(f'O valor 9 apareceu {valor.count(9)} vezes') if 3 in valor: print(f'O valor 3 está na {valor.index(3)+1}ª posição') else: print('O valor 3 não foi digitado em nenhuma posição!') print('Os numeros pares digitados foram: ',end='') for v in valor: if v % 2 == 0: print(f'{v}', end=' ') print() print('\033[2;35m====\033[m' *11) #linha colorida(not important)
886b4ab1aea95167d41fec8e3f07c04235cb41d6
blankd/hacker-rank
/python/src/blankd/hackerrank/python/collections/counter.py
904
3.578125
4
from collections import Counter from blankd.hackerrank.main.hacker_rank_solution import HackerRankSolution # Solution for https://www.hackerrank.com/challenges/collections-counter/problem class CounterSolution(HackerRankSolution): def __init__(self, file_to_read): super().__init__(file_to_read) lines = self.file_to_read.read().split("\n") self.counter = dict(Counter(lines[1].split(" "))) self.customers = lines[3:] self.total = 0 def run_solution(self): for cust in self.customers: sale = cust.split(" ") self.handle_sale(sale[0], int(sale[1])) def print_results(self): print(self.total) def handle_sale(self, size, amt): if size in self.counter: self.total += amt self.counter[size] -= 1 if self.counter[size] < 1: del self.counter[size]
485dbd9c4ba0c62ff186237181bbb8473298aced
mamine2/My-First-Repository
/personality_MA.py
791
3.765625
4
name = "cus" state = "colorado" city = "New York City" game = "BF1" book = "martian" print(name + " likes to visit " + state + " and " + city) print("he also likes pwning on " + game + " or reading " + book) print("whats your favorite s00bJ") subject = input() if subject == "quick mafs": print("schwag big bro, 2+2 = 4 - 1 = 3 quick mafs") else: print(subject + " is schwag") print("wot is ur fav sp0t") sport = input() if sport == "quick mafs" or "kwick maphs": print("but mans not hot" + sport + "she said take off your jacket") else: print(sport + "is mans not 0t") print("favorite movie?") movie = input() if movie == "it": print("w0t") elif movie == "swag": print("nerd") else: print("ur a loser")
cbcbb03a13e3ad26c0462f3d1727a1e89984e829
modmeister/codesignal
/avoidObstacles.py3
280
3.515625
4
def avoidObstacles(inputArray): range = 2 inputArray.sort() position = range while (position <= inputArray[-1]): if position in inputArray: range += 1 position = range continue position += range return range
ddbf32f53d5f7e4bab6147cc7e1f03282b24d5c4
mrdonliu/Classification
/LogisticRegression.py
11,404
4.03125
4
import os import pickle import numpy as np from scipy import optimize from sklearn import datasets """ a dataset of features(X) or targets(Y), or theta(theta), are all represented as column vectors example: features = [ [ 2 , 3 , 5] [ 3 , 4 , 8] ] We have three datasets, each with two features. Dataset 1: [ 2 , 3 ] Dataset 2: [ 3 , 4 ] Dataset 3: [ 5 , 8 ] """ class logistic_regression: def __init__(self, learning_rate, lamb): self.learning_rate = learning_rate self.lamb = lamb def sigmoid(self, z): return 1.0 / (1.0 + np.exp(-z)) def cost(self, theta, X, Y): number_of_datasets = X.shape[1] hypothesis = self.sigmoid(theta.T * X) # row vector """ Logarithm of 0 is infinity, so to prevent this we take .0001 from all hypothesis values. """ for i in range(hypothesis.shape[1]): if (hypothesis[0, i] == 0): hypothesis[0, i] = hypothesis[0, i] + .0001 elif (hypothesis[0, i] == 1): hypothesis[0, i] = hypothesis[0, i] - .0001 cost_when_target_is_1 = np.log(hypothesis) * Y """ Since any hypothesis can be > 1 after adding .0001, we take absolute value of (1.0-hypothesis) to prevent taking the log of negative values. """ cost_when_target_is_0 = np.log(abs(1.0 - hypothesis)) * (1 - Y) cost = (-1 / number_of_datasets) * (cost_when_target_is_0 + cost_when_target_is_1) return cost[0, 0] def cost_regularized(self, theta, X, Y): number_of_datasets = X.shape[1] cost = self.cost(theta, X, Y) regularization_cost = self.lamb / (2 * number_of_datasets) * np.sum(np.power(theta, 2)) return cost + regularization_cost # work in progress def derivative_of_cost(self, theta, X, Y, theta_number): num_of_datasets = X.shape[1] hypothesis = self.sigmoid(theta.T * X) derivative = X[theta_number] * (hypothesis.T - Y) * (1 / num_of_datasets) return derivative def derivative_of_cost_regularized(self, theta, X, Y, theta_number): num_of_datasets = X.shape[1] hypothesis = self.sigmoid(theta.T * X) derivative = X[theta_number] * (hypothesis.T - Y) * (1 / num_of_datasets) + (self.lamb / num_of_datasets) * ( theta[theta_number]) return derivative def descent(self, theta, X, Y, iterations): X = np.matrix(X) Y = np.matrix(Y) theta = np.matrix(theta) num_of_features = len(theta) for i in range(1, iterations): # if (ask): # change_learning_rate_boolean = input("Do you want to change the learning rate? Y for yes , N for no:") # if (change_learning_rate_boolean == "y"): # change_learning_rate_to = input("Enter the new learning rate: ") cost = self.cost(theta, X, Y) # print("iteration = {:d} , cost = {:f}".format(i, cost)) error_terms = np.empty([num_of_features, 1]) # learning rate * derivative of error function for x in range(num_of_features): error_terms[x] = self.learning_rate * self.derivative_of_cost(theta, X, Y, x) theta = np.subtract(theta, error_terms) return theta def descent_regularized(self, theta, X, Y, iterations): X = np.matrix(X) Y = np.matrix(Y) theta = np.matrix(theta) num_of_features = len(theta) for i in range(1, iterations): # if (ask): # change_learning_rate_boolean = input("Do you want to change the learning rate? Y for yes , N for no:") # if (change_learning_rate_boolean == "y"): # change_learning_rate_to = input("Enter the new learning rate: ") cost = self.cost_regularized(theta, X, Y) #print("iteration = {:d} , cost = {:f}".format(i, cost)) error_terms = np.empty([num_of_features, 1]) # learning rate * derivative of error function for x in range(num_of_features): error_terms[x] = self.learning_rate * self.derivative_of_cost_regularized(theta, X, Y, x) theta = np.subtract(theta, error_terms) return theta def train(self, theta, X, Y): params0 = theta res = optimize.minimize(self.cost, params0, method='BFGS', args=(X, Y)) print(res) def training_results(self, theta, X_testing, Y_testing): theta = np.matrix(theta) X_testing = np.matrix(X_testing) Y_testing = np.matrix(Y_testing) incorrect = correct = 0; hypothesis = self.sigmoid(theta.T * X_testing) for i in range(hypothesis.shape[1]): if (hypothesis[0, i] >= .5): hypothesis[0, i] = 1 else: hypothesis[0, i] = 0 if (hypothesis[0, i] == Y_testing[i, 0]): correct += 1 else: incorrect += 1 print("correct: {:d} ".format(correct)) print("incorrect: {:d} ".format(incorrect)) def training_results1(self, theta, X_testing, Y_testing): theta = np.matrix(theta) X_testing = np.matrix(X_testing) Y_testing = np.matrix(Y_testing) incorrect = correct = 0; hypothesis = self.sigmoid(theta.T * X_testing) hyp = np.argmax(hypothesis,axis=0) hyp = hyp.T print(Y_testing.shape) print(hyp.shape) print(hyp[:,:100]) for i in range(Y_testing.shape[0]): if(hyp[i,0] == Y_testing[i,0]): correct = correct + 1 else: incorrect = incorrect + 1 print("correct: {:d} ".format(correct)) print("incorrect: {:d} ".format(incorrect)) def classify_iris(): theta = np.random.rand(4, 3) iris = datasets.load_iris() X = iris.data[:, :] Y = iris.target num_of_datasets = len(Y) Y = Y.reshape(num_of_datasets,1) length_of_each_fold = (int)(Y.shape[0] / 5) # each fold of cross validation, equally partitioned lr = logistic_regression(.01, .5) print(num_of_datasets) print(length_of_each_fold ) # for each iris type for a in range(3): # intial folds test_start_index = 0 test_end_index = length_of_each_fold train_start_index = test_end_index train_end_index = num_of_datasets # cross validation for g in range(5): print("iteration %d"%(g)) train_class1 = np.asmatrix( [X[i] for i in range(test_start_index) or range(train_start_index, train_end_index) if Y[i] == a]).T target_class1 = np.ones((train_class1.shape[1], 1)) train_class0 = np.asmatrix( [X[i] for i in range(test_start_index) or range(train_start_index, train_end_index) if Y[i] != a]).T target_class0 = np.zeros((train_class0.shape[1], 1)) test_class1 = np.asmatrix([X[i] for i in range(test_start_index, test_end_index) if Y[i] == a]).T test_target_class1 = np.ones((test_class1.shape[1], 1)) test_class0 = np.asmatrix([X[i] for i in range(test_start_index, test_end_index) if Y[i] != a]).T test_target_class0 = np.zeros((test_class0.shape[1], 1)) theta_a = np.asmatrix([row[a] for row in theta]).T theta_a = lr.descent_regularized(theta_a, train_class0, target_class0, 3) #theta_a = lr.descent_regularized(theta_a, train_class1, target_class1, 3) for d in range(0, 4): theta[d][a] = theta_a[d][0] test_start_index = test_end_index test_end_index = test_end_index + length_of_each_fold train_start_index = test_end_index # lr.training_results(theta_a, test_class0, test_target_class0) # lr.training_results(theta_a, test_class1, test_target_class1) lr.training_results1(theta, X.T, Y) def classify_digits(): # theta = np.zeros( # (64, 10)) # each column i , represents its respective digit. each digit has 64 weights initialized at zero theta = np.random.rand(64, 10) digits = datasets.load_digits() #X and Y are row datasets, and will be transposed during cross validation X = digits.images[:1795, :] Y = digits.target[:1795] X = (X.reshape(1795, -1)) # turn 3d features vector into 2d, by flattening 8x8 array to 64 array Y = Y.reshape(Y.shape[0], 1) length_of_each_fold = (int)(Y.shape[0] / 5) # each fold of cross validation, equally partitioned num_of_datasets = Y.shape[0] lr = logistic_regression(.01, .5) # for the weights of each digit for a in range(10): # intial folds test_start_index = 0 test_end_index = length_of_each_fold train_start_index = test_end_index train_end_index = num_of_datasets # cross validation for g in range(5): train_class1 = np.asmatrix( [X[i] for i in range(test_start_index) or range(train_start_index, train_end_index) if Y[i] == a]).T target_class1 = np.ones((train_class1.shape[1], 1)) train_class0 = np.asmatrix( [X[i] for i in range(test_start_index) or range(train_start_index, train_end_index) if Y[i] != a]).T target_class0 = np.zeros((train_class0.shape[1], 1)) test_class1 = np.asmatrix([X[i] for i in range(test_start_index, test_end_index) if Y[i] == a]).T test_target_class1 = np.ones((test_class1.shape[1], 1)) test_class0 = np.asmatrix([X[i] for i in range(test_start_index, test_end_index) if Y[i] != a]).T test_target_class0 = np.zeros((test_class0.shape[1], 1)) theta_a = np.asmatrix([row[a] for row in theta]).T theta_a = lr.descent_regularized(theta_a, train_class0, target_class0, 3) theta_a = lr.descent_regularized(theta_a, train_class1, target_class1, 3) for d in range(0, 64): theta[d][a] = theta_a[d][0] print(test_start_index) print(test_end_index) print(train_start_index) print(train_end_index) test_start_index = test_end_index test_end_index = test_end_index + length_of_each_fold train_start_index = test_end_index #train_end_index = test_start_index # lr.training_results(theta_a, test_class0, test_target_class0) # lr.training_results(theta_a, test_class1, test_target_class1) lr.training_results1(theta, X.T , Y) def classify_cifar(): cifar_10_dir = 'cifar-10-batches-py/' xs = [] ys = [] for i in range(1, 6): batch_dir = os.path.join(cifar_10_dir, 'data_batch_%d' % (i,)) with open(batch_dir, 'rb') as f: dict = pickle.load(f, encoding='latin1') X = dict['data'] X = np.matrix(X) print(X.shape) xs.append(X) Y = dict['labels'] Y = np.matrix(Y) ys.append(Y.T) Xtr = np.concatenate(xs).T Ytr = np.concatenate(ys) print(Xtr.shape) print(Ytr.shape) def main(): classify_iris() #classify_digits() # classify_cifar() if __name__ == "__main__": main()
f94d0dac682c14560f90a180e55f7a9f2712d8be
HelalChow/Data-Structures
/Homework/HW2/hc2324_hw2_q7.py
607
3.609375
4
def findChange(lst01): left = 0 right = len(lst01)-1 one = None index_found = False while(index_found==False): curr = (left+right)//2 if lst01[curr]==0 and lst01[curr+1]==1: one = curr+1 index_found=True elif lst01[curr]==0 and lst01[curr+1]!=1: left = curr+1 elif lst01[curr]==1 and lst01[curr-1]==0: one = curr index_found=True elif lst01[curr]==1 and lst01[curr-1]!=0: right = curr-1 return one def main(): print(findChange([0,0,0,0,0,0,1]))
28689ae1dafa864ac6e8700f569a0736e97aa93d
erickcarvalho1/ifpi-ads-algoritmos2020
/Fabio02_P01/F2_P1_Q4_DEZENAIGUALUNIDADE.py
336
3.859375
4
#Leia 1 (um) número de 2 (dois) dígitos, verifique e escreva se o algarismo da dezena é igual # ou diferente do algarismo da unidade. numero = int(input('Qual o número de dois digitos? ')) dezena = numero // 10 unidade = numero % 10 if dezena == unidade: print('São iguais') else: print('Não são iguais')
488e24d974de43c1d0be6bf28096450fee826fe6
samutrujillo/holbertonschool-higher_level_programming
/0x03-python-data_structures/9-max_integer.py
200
3.515625
4
#!/usr/bin/python3 def max_integer(my_list=[]): if len(my_list) == 0: return None count = my_list[0] for i in my_list: if i > count: count = i return count
ea9407fb750b96e24653a10183418ebf8aeb6808
tqphuc567/Word2vec
/Tich 2 ma tran.py
642
4.21875
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 8 02:55:05 2019 @author: Phuc123 """ # Program to multiply two matrices using nested loops # 4x3 matrix X = [[1,0,1], [1 ,0,0], [1 ,0,0], [1,1,0]] # 3x3 matrix Y = [[5,5,5], [5,5,5], [5,5,5]] # result is 4x3 result = [[0,0,0], [0,0,0], [0,0,0], [0,0,0]] # iterate through rows of X for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r)
3524655e414cb089f1cc3f258a5633f02332ec9e
estebantoso/curso_python_udemy
/34 - lists_comprehension.py
357
3.65625
4
nums = [1, 2, 3] print([x*10 for x in nums]) print([x/2 for x in nums]) name = "colt" print([char.upper() for char in name]) generic_list = ["", 0, [], 1] bool_list = [bool(val) for val in generic_list] print(bool_list) colors = ["orange", "yellow", "green", "blue", "red"] colors = [color[0].upper() + color[1:] for color in colors] print(colors)
7770c877ba29d2e6e8228df1abf6a7e8b61fa0ad
ajcepeda/Calculator
/test_12.1.py
2,632
3.78125
4
import unittest from exercise import Subject, Student class Test(unittest.TestCase): def test_subject(self): name = "Math" units = 1.5 grade = 87.2 s = Subject(name, units, grade) self.assertEqual(s.name, name) def test_subject_with_error_name(self): name = "" units = 1.5 grade = 87.2 self.assertRaises(Exception, Subject, name, units, grade) def test_one_subject_gwa(self): name = "Math" units = 1.5 grade = 87.2 s = Subject(name, units, grade) name = "Patrick Starfish" student = Student(name) student.add_subject(s) # the weighted average should be equal to the grade # since we are only dealine with one subject here self.assertEqual(student.solve_gwa(), grade) ### additional laurz ### def test_subject_with_error_name(self): name = 312312 units = 1.5 grade = 87.2 self.assertRaises(Exception, Subject, name, units, grade) def test_subject_with_error_grade(self): name = "Math" units = 1.5 grade = "87.2" self.assertRaises(Exception, Subject, name, units, grade) def test_subject_with_error_units(self): name = "Math" units = "1.5" grade = 87.2 self.assertRaises(Exception, Subject, name, units, grade) def test_student_name(self): name = "Math" units = 1.5 grade = 87.2 s = Subject(name, units, grade) name = "Patrick Starfish" student = Student(name) student.add_subject(s) self.assertEqual(student.name, name) def test_student_name_error(self): name = "Math" units = 1.5 grade = 87.2 s = Subject(name, units, grade) name = 12.4142 self.assertRaises(Exception, Student, name) def test_subjects_gwa(self): name = "Math" units = 1.5 grade = 87.2 s = Subject(name, units, grade) name = "Patrick Starfish" student = Student(name) student.add_subject(s) name = "Science" units = 3 grade = 99.2 s = Subject(name, units, grade) student.add_subject(s) name = "Physics" units = 2 grade = 70.2 s = Subject(name, units, grade) student.add_subject(s) # the weighted average should be equal to the grade # since we are only dealine with one subject here self.assertEqual(student.solve_gwa(), 87.50769230769232) if __name__ == "__main__": unittest.main()
d961a8a00bd53f6e74321eb68bdacfc340e3d418
mayukhrooj/Hackerrank
/chipher.py
823
4.0625
4
#!/usr/bin/env python3 def lower_en(char,k): ascii_char = ord(char) ascii_char += k % 26 if not ascii_char <= 122: distance = ascii_char - 122 position = 97 + (distance - 1) return chr(position) else: return chr(ascii_char) def upper_en(char,k): ascii_char = ord(char) ascii_char += k % 26 if not ascii_char <= 90: distance = ascii_char - 90 position = 65 + (distance - 1) return chr(position) else: return chr(ascii_char) def main(s, k): encrypted = "" for i in range (0,len(s)): en_char = "" char = s[i] if 65 <= ord(char) <= 90: en_char = upper_en(char, k) elif 97 <= ord(char) <= 122: en_char = lower_en(char, k) else: en_char = char encrypted += en_char return encrypted
b267c8f5a1de4dc17c958285e484704a7ee47eb9
jayg791/CA4_JamesGallagher_10028426
/Github_Commit Changes_Script.py
1,995
3.5625
4
# -*- coding: utf-8 -*- """ Created on Fri May 05 16:57:05 2017 @author: EliteBook """ # Github_Commit Changes_Script.py # code to open the file, read the lines and strip the spaces fhandle = open('Github Data.txt', 'r') data = [line.strip() for line in open('Github Data.txt', 'r')] # a variable to handle the txt separater sep = 72*'-' #create a 'Commit Class' that will hold all of elements of interest in the data class Commit(object): #class for commit def __init__(self, revision = None, author = None, date = None, line_count = None, changes = None, comment = None): self.revision = revision self.author = author self.date = date self.line_count = line_count self.changes = changes self.comment = comment def get_commit_day(self): day = self.date.split() return day[3].strip('(').strip(',') def get_author_names(self): return self.author commits = [] current_commit = None index = 0 authors = [] # start a loop to parse the information and retrurn it to the class while True: try: current_commit = Commit() details = data[index + 1].split('|') current_commit.revision = int(details[0].strip().strip('r')) current_commit.author = details[1].strip() current_commit.date = details[2].strip() current_commit.comment_line_count = int(details[3].strip().split(' ')[0]) current_commit.changes = data[index+2:data.index('',index+1)] index = data.index(sep, index + 1) current_commit.comment = data[index-current_commit.comment_line_count:index] commits.append(current_commit) author = data[index+1].split('|')[1].strip() if author not in authors: authors.append(author) except IndexError: break print authors for index, commit in enumerate(commits): print commit.get_commit_day()
a7024c68b0e96c24c8dbcbd6fa4cbbc490525328
mikebuss42/Dragon_Cave
/dragon.py
3,370
4.25
4
import random import time '''===================Functions===================''' def display_intro(): print('''\n***** You are in a land full of dragons! ***** You set out in search for treasure, guarded by a dragon. As you set forth on your adventure, you come to a mountain side. In front of you, you see two caves. * One cave will lead you towards a friendly dragon who will give you treasure. * The other dragon is greedy and hungry, and will eat you on sight.''') print() def choose_cave(): cave = '' while cave != '1' and cave != '2': print('Into which cave will you go (1 or 2)? ') cave = input() return cave def choose_path(): path = '' while path != '1' and path != '2': print('\nDo you go path (1 or 2)? ') path = input() return path def pause_for_dramatic_effect(seconds): while seconds > 0: print('.', end='') time.sleep(1) seconds -= 1 print() def check_cave(chosen_cave): print('You chose cave', chosen_cave, end='') random_val = random.randint(1,2) if chosen_cave == str(random_val): pause_for_dramatic_effect(3) print('You approach the cave.', end='') pause_for_dramatic_effect(3) print('It is dark and spooky.', end='') pause_for_dramatic_effect(3) print('You reach a fork in the tunnel.', end='') else: pause_for_dramatic_effect(3) print('You approach the cave.', end='') pause_for_dramatic_effect(3) print('It is warm and dimly lit.', end='') pause_for_dramatic_effect(3) print('You reach a fork in the tunnel.', end='') def cave_end_good(cave_path_taken): print('You chose path', cave_path_taken, end='') pause_for_dramatic_effect(3) friendly_cave = random.randint(1, 2) if cave_path == str(friendly_cave): print('A large dragon jumps out in front of you! He opens his jaws and.', end='') pause_for_dramatic_effect(3) print('Gives you his treasure! You are rich!') else: print('You come to a dead end. You leave and return to the start.') def cave_end_bad(cave_path_taken): print('You chose path', cave_path_taken, end='') pause_for_dramatic_effect(3) enemy_cave = random.randint(1, 2) if cave_path == str(enemy_cave): print('A large dragon jumps out in front of you! He opens his jaws and.', end='') pause_for_dramatic_effect(3) print('Gobbles you down in one bite! Ouch!') else: print('You come to a dead end. You leave and return to the start.') '''==============================================================''' proceed = 'yes' play_again = 'yes' while play_again == 'yes' or play_again == 'y': display_intro() '''Cave Choice''' cave_number = choose_cave() '''Cave Continue''' check_cave(cave_number) '''Path Choice''' if cave_number == 1: cave_path = choose_path() if cave_path == '1': cave_end_good(cave_path) else: cave_end_bad(cave_path) else: cave_path = choose_path() if cave_path == '1': cave_end_bad(cave_path) else: cave_end_good(cave_path) print('\nDo you want to play again (yes or no)?') play_again = input() print('\nThanks for playing!')
f96b745263e49d44f1852a38c1a49609f1d74ed3
AncauAdrian/FundamentalsOfProgramming
/Homework/Week1/P3.py
813
3.640625
4
#Problem 3 n = int(input("Enter the number: ")) def formlist(n): #This fuction takes the number n, splits it into seperate digits and forms a sorted list comprised of those digits l = [] while n != 0: x = n% 10 l.append(x) n = int(n / 10) l.sort() return l def formnumber(x): #This function forms the number equivalend to the digits in the list but before that it checks that the number meets certain conditions if x < 0: x = x*(-1) negative = True else: negative = False a = formlist(x) if negative: a.reverse() s = 0 for i in range(0, len(a)): s = s*10 + a[i] if negative: return s*(-1) else: return s a = formnumber(n) print(a)
069b6941256630b0dbd815fb3e1611eba62edbd5
joannalew/CTCI
/Python/dp-coin-change.py
1,891
4.09375
4
# LeetCode 322: Coin Change # You are given coins of different denominations # and a total amount of money amount. # Write a function to compute the fewest number of coins that # you need to make up that amount. # If that amount of money cannot be made up by any combination # of the coins, return -1. # Example: coins = [1, 2, 5], amount = 11 # Output: 3 # Explanation: 11 = 5 + 5 + 1 # Example: coins = [2], amount = 3 # Output: -1 def coinChange(coins, amount): rows = len(coins) cols = amount + 1 memo = [[amount + 1 for y in range(cols)] for x in range(rows)] memo[0][0] = 0 for i in range(rows): for j in range(cols): if j < coins[i] and i == 0: continue elif i == 0: memo[i][j] = memo[i][j - coins[i]] + 1 elif j < coins[i]: memo[i][j] = memo[i - 1][j] else: memo[i][j] = min(memo[i - 1][j], memo[i][j - coins[i]] + 1) res = -1 if memo[-1][-1] > amount else memo[-1][-1] return res def main(): print(coinChange([1, 2, 5], 11)) # => 3 print(coinChange([1, 5, 6, 8], 11)) # => 2 print(coinChange([2], 3)) # => -1 if __name__ == "__main__": main() # Solve it: # Make a chart to keep track of min coins # rows = coin values, cols = 0...amount # initialize all values to max (amount + 1), set memo[0][0] = 0 # fill out the first row # row element is min between (prev row, same column) # and ((same row, column - coin value) + 1) # Example: coinChange([1, 5, 6, 8], 11) # | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 # 1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 # 5 | 0 | 1 | 2 | 3 | 4 | 1 | 2 | 3 | 4 | 5 | 2 | 3 # 6 | 0 | 1 | 2 | 3 | 4 | 1 | 1 | 2 | 3 | 4 | 2 | 2 # 8 | 0 | 1 | 2 | 3 | 4 | 1 | 1 | 2 | 1 | 2 | 2 | 2 # Ref: https://www.youtube.com/watch?v=Y0ZqKpToTic
647801beaed1a1b0a9221dd96f8dc85bb7cfa00c
jayasri22/python
/leap.py
216
4.09375
4
y = int(input("Enter y: ")) if y % 4 == 0 and y % 100 != 0: print(y, "Leap Year") elif y % 100 == 0: print(y, " not Leap Year") elif y % 400 ==0: print(y, "Leap Year") else: print(y, "not Leap Year")
c51f75a63c6baaea19868113d81c96fc8bc19e09
alexandros-antonorsi/high-school-code
/Python/largebrowncow.py
476
3.5
4
file = open("nocow.in", "r") out = open("nocow.out", "w") line = file.readline().split(" ") n = int(line[0]) k = int(line[1]) line = file.readline() line = (line[(line.find("no")+3):].split(" "))[:-1] adj = [[] for i in range(0, len(line))] for x in range(0, len(line)): adj[x].append(line[x]) for x in range(1, n): line = file.readline() line = (line[(line.find("no")+3):].split(" "))[:-1] if line[x] not in adj[x]: adj[x].append(line[x]) print(adj)
0a6286c4c5ebf4ee5f27e5a0978930dc9df1b934
likohank/mianshiti_2020
/10.sort.py
789
3.953125
4
import os,sys def heap_sort(array): def heap_adjust(parent): child = 2 * parent + 1 # left child while child < len(heap): if child + 1 < len(heap): if heap[child + 1] > heap[child]: child += 1 # right child if heap[parent] >= heap[child]: break heap[parent], heap[child] = \ heap[child], heap[parent] parent, child = child, 2 * child + 1 heap, array = array.copy(), [] for i in range(len(heap) // 2, -1, -1): print(i) heap_adjust(i) while len(heap) != 0: heap[0], heap[-1] = heap[-1], heap[0] array.insert(0, heap.pop()) heap_adjust(0) return array aa=[5,3,1,7,9,7,0] print(heap_sort(aa))
121ebfb1454499442435975b1d64d6fa1f2a84c0
Demi0619/Alien-Invasion-Game
/bullets.py
664
3.640625
4
import pygame from pygame.sprite import Sprite class Bullets(Sprite): ''' a class to manage bullet fired from ship''' def __init__(self, ai_game): super().__init__() self.screen = ai_game.screen self.settings=ai_game.setting1 self.color=self.settings.bullet_color self.rect=pygame.Rect(0,0,self.settings.bullet_width,self.settings.bullet_height) self.rect.midtop=ai_game.ship.rect.midtop self.y=float(self.rect.y) def draw_bullet(self): pygame.draw.rect(self.screen,self.color,self.rect) def update(self): self.y -= self.settings.bullet_speed self.rect.y = self.y
faf9a7e9a4a7b74aa01bd79a93f4227418a5192d
Jigar710/Python_Programs
/numpy/list_intro/l2.py
84
3.625
4
lst = [] for i in range(5): x = input("Enter data : ") lst.append(x) print(lst)
0dd467f6ffe1457ce6bfbf9d6d80707d345150c2
untitledmind/scrape-macys
/macys.py
5,257
3.625
4
"""Macy's web scraper Author: Ethan Brady last updated Jan 16 2020 This script creates a database Macy's products by scraping their online website with BeautifulSoup and the requests module. Because the program makes http requests in a for-loop context, it's rather slow. Note: For speed reasons, the loop currently breaks at the first category; thus only the first category in the index is scraped for products. To speed up the script, next step is to implement multithreaded or asynchronous requests. """ import requests from bs4 import BeautifulSoup import re import json def call_soup(url, agent): """visits url and returns soup""" response = requests.get(url, headers=agent) soup = BeautifulSoup(response.text, 'html.parser') return soup def format_link(url): """ensures returned url starts with https://www.macys.com""" url = re.sub(r'^/shop/', 'https://www.macys.com/shop/', url) url = re.sub(r'^//www.', 'https://www.', url) if not re.search(r'^https://', url): url = ''.join(['https://', url]) return url def get_category_href(url, agent): """finds all category href from index page returns set of formatted urls with index page removed """ soup = call_soup(url, agent) hrefs = {format_link(i.get('href')) for i in soup.find_all('a', href=re.compile('/shop'))} hrefs.remove(url) return hrefs def get_product_href(url, agent): """finds all product href from category page returns set of formatted urls """ soup = call_soup(url, agent) hrefs = {format_link(i.get('href')) for i in soup.find_all('a', {'class': 'productDescLink'}, href=re.compile('/shop'))} return hrefs def get_product_data(url, agent): """reads json from product page soup""" soup = call_soup(url, agent) product = json.loads(soup.find('script', {'id': 'productMktData'}).text) # asset = json.loads(soup.find('script', {'type': 'text/javascript'}).text) return product #, asset def push_to_sql(products): """takes list of each product's data pushes to SQL table """ import sqlite3 with sqlite3.connect('macys_products.db') as conn: c = conn.cursor() c.execute( """CREATE TABLE IF NOT EXISTS products ( product_id INT, name VARCHAR(255), category VARCHAR(255), image VARCHAR(500), url VARCHAR(500), product_type VARCHAR(50), brand VARCHAR(255), description VARCHAR(500), currency VARCHAR(5), price FLOAT, sku VARCHAR(15), availability VARCHAR(100), price_valid_until VARCHAR(25) ); """ ) rows = [] for product in products: name = product.get('name') category = product.get('category') product_id = int(product.get('productID')) image = product.get('image') url = product.get('url') product_type = product.get('@type') brand = product.get('brand').get('name') description = product.get('description') currency = product.get('offers')[0].get('priceCurrency') price = float(product.get('offers')[0].get('price')) sku = product.get('offers')[0].get('SKU') availability = product.get('offers')[0].get('availability') price_valid_until = product.get('offers')[0].get('priceValidUntil') data = (product_id, name, category, image, url, product_type, brand, \ description, currency, price, sku, availability, price_valid_until) placeholders = ', '.join(['?'] * len(data)) print(data) rows.append(data) c.executemany(f'INSERT INTO products VALUES ({placeholders});', rows) print('Pushed data to SQL table') def main(): """begins function chain starting at Macy's index page in this order: 1. index 2. categories 3. product links 4. product data 5. to SQL Note: Currently the loop breaks at the first category; thus only the first category in the index is scraped for products. """ url = 'https://www.macys.com/shop/sitemap-index?id=199462' agent = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Safari/605.1.15'} categories = get_category_href(url, agent) print(f'{len(categories)} categories found') product_links = set() for i, url in enumerate(categories): product_links.update(get_product_href(url, agent)) print(f'clicked on category {i}...') break products = [] for i, url in enumerate(product_links): products.append(get_product_data(url, agent)) print(f'clicked on product {i}...') push_to_sql(products) if __name__ == '__main__': import time start = time.process_time() main() end = time.process_time() print(f'Script executed in {end - start} seconds')
daf995bc4a2df0f84e2e1391d5936355b784fbeb
jorge-alvarado-revata/code_educa
/python/week11/bubble.py
423
3.65625
4
# algoritmo de burbuja import random import time def bubble(lista): for j in range(len(lista)-1, 0, -1): for i in range(j): if lista[i] > lista[i+1]: lista[i], lista[i+1] = lista[i+1], lista[i] N = int(input()) lista = [] for i in range(N): lista.append(random.randint(-10000, 10000)) print(lista) t0 = time.time() bubble(lista) t1 = time.time() print(lista) print(t1-t0)
efe424671c3abd867038aea633d8e1dcdbcada40
Jorefice27/Voyant
/checkpassword_trie.py
724
4.15625
4
from trie import Trie t = Trie() passwords = open('passwords.txt') for password in passwords: t.add(password.strip()) print('Enter "checkpassword" followed by a password to see if it is a common password') print('Enter "Exit" to quit the program\n') while True: userInput = input('$').strip() if userInput.lower() == 'exit': break # expecting input with the form "checkpassword {password}" arr = userInput.split(' ') if len(arr) != 2: # doesn't match the above form print('Invalid input') elif arr[0].lower() != 'checkpassword': print('Invalid input') elif t.contains(arr[1]): print('Common password') else: print('Not common password')
540fffab644352f7a3d7a0fd2a9fb94a489f0d69
sdbaronc/taller_de_algoritmos
/algorimo_16.py
152
3.765625
4
t=float(input("ingrese el tiempo en segundos")) a=float(input("ingrese la aceleracion em m/s^2")) vel= t*a print("la velocidad final es de:",vel,"m/s")
001dd4e3991c0ff2377d437e1eacb5b17f0e974e
Ackermannn/PythonBase
/PythonBase/python基础/丰富的else语句.py
582
3.640625
4
#=====while 与 else 的配合 def showMaxFactor(num): count = num // 2 while count > 1: if num % count == 0: print('%d最大的约数是%d' % (num,count)) break # 如果没有break 就跑else count -= 1 else: print('%d是素数!' % num) num = int(input('请输入一个数:')) showMaxFactor(num) # try 可以与 else 配合 # 简洁的with的语句 try: with open('data.txt','w') as f #????????? for each_line in f print(each_line) except OSError as reason print('出错了'+str(reason))
0f80bd77bf4afa6175db6c79a133db869bca2f64
jobalouk/clean-code-notes
/playground.py
353
3.578125
4
def main(): some_record = {'name': 'John'} employee = CommissionedEmployee(record=some_record) employee.is_payday() class Pay: def __init__(self, record): self.record = record def is_payday(self): NotImplementedError class CommissionedEmployee(Pay): def is_payday(self): print(self.record) main()
5cdbc5df0efe1b90c628980ae5e600a5364c2d84
68Duck/Countdown
/checker.py
3,881
3.59375
4
class Checker(object): def __init__(self,startNumber,numbers,path=[],parentWindow=None): self.path = path self.parentWindow = parentWindow self.numbers = numbers self.startNumber = startNumber self.check() def check(self): for number in self.numbers: self.checkDivide(number) self.checkMinus(number) self.checkAdd(number) self.checkMultiply(number) def checkDivide(self,number): if number == 1: return newPath = self.path[:] if len(newPath) != 0: if newPath[len(newPath)-1][0:1] == "*": return newValue = self.startNumber/number newNumbers = self.numbers[:] newNumbers.remove(number) newPath.append("/"+str(number)) if newValue == 0: self.convertPath(newPath) else: self.newChecker = Checker(newValue,newNumbers,newPath,parentWindow = self.parentWindow) def checkMinus(self,number): newValue = self.startNumber-number newNumbers = self.numbers[:] newNumbers.remove(number) newPath = self.path[:] newPath.append("-"+str(number)) if newValue == 0: self.convertPath(newPath) else: self.newChecker = Checker(newValue,newNumbers,newPath,parentWindow = self.parentWindow) def checkAdd(self,number): newPath = self.path[:] if len(newPath) != 0: if newPath[len(newPath)-1][0:1] == "-": return elif newPath[len(newPath)-1][0:1] == "+": if number < int(newPath[len(newPath)-1][1:len(newPath)+1]): return newPath.append("+"+str(number)) newValue = self.startNumber+number newNumbers = self.numbers[:] newNumbers.remove(number) if newValue == 0: self.convertPath(newPath) else: # print(newPath) self.newChecker = Checker(newValue,newNumbers,newPath,parentWindow = self.parentWindow) def checkMultiply(self,number): if number == 1: return newPath = self.path[:] if len(newPath) != 0: if newPath[len(newPath)-1][0:1] == "*": if number < int(newPath[len(newPath)-1][1:len(newPath)+1]): return newValue = self.startNumber*number newNumbers = self.numbers[:] newNumbers.remove(number) newPath.append("*"+str(number)) if newValue == 0: self.convertPath(newPath) else: self.newChecker = Checker(newValue,newNumbers,newPath,parentWindow = self.parentWindow) def convertPath(self,path): correctOrder = [] for i in range(len(path)): symbol = path[len(path)-i-1][0:1] number = path[len(path)-i-1][1:len(path[len(path)-i-1])+1] if symbol == "+": newSymbol = "-" elif symbol == "-": newSymbol = "+" elif symbol == "*": newSymbol = "/" else: newSymbol = "*" correctOrder.append(newSymbol+str(number)) # print(correctOrder) if __name__ == "__main__": global combinations combinations.append(correctOrder) if self.parentWindow is None: pass else: self.parentWindow.combinations.append(correctOrder) if __name__ == "__main__": ## OPTIMIZED version bigNumber = int(input("enter big number")) numbers = [] for i in range(6): newNo = int(input("enter a small number")) numbers.append(newNo) # bigNumber = 315 # numbers = [75,100,25,1,6,9] combinations = [] numbers.sort() checker = Checker(bigNumber,numbers) print(len(combinations))
731f435ae8daa1880a43a0cff541f395c825eb32
carlosmaniero/ascii-engine
/ascii_engine/screen.py
2,565
3.84375
4
""" This module provide the screen representation. A screen is a where all to render elements should stay. """ from ascii_engine.pixel import BLANK_PIXEL from ascii_engine.coord import Coord, CoordinatedElement class Screen: """ This is the screen where elements should be rendered given a coordinate. You can get a screen by calling the render_interface.create_empty_screen. >>> from ascii_engine.interfaces.curses_interface.render import ( >>> CursesRender >>> ) >>> render = CursesRender() >>> render.create_empty_screen() """ def __init__(self, width, height): self.width = width self.height = height self.elements = [] def add_element(self, element, coord=Coord(0, 0, 0)): """ Add a element to the given position >>> screen = Screen(20, 10) >>> screen.add_element(Text("My Test"), Coord(0, 1)) >>> screen.add_element(Text("My Test"), Coord(0, 1)) """ self.elements.append(CoordinatedElement(coord, element)) def render(self): """ This method is called by interface to get the pixels to be rendered in the screen. """ fragment = _ScreenFragment(self.get_width(), self.get_height()) for coord, element in self.elements: fragment.add_element(element, coord) return fragment.to_pixels() def get_width(self): """ Return the screen width """ return self.width def get_height(self): """ Return the screen height """ return self.height class _ScreenFragment: def __init__(self, width, height): self.width = width self.height = height self.screen = self._create_blank_screen() def add_element(self, element, coords): render_height = self.height - coords.y render_width = self.width - coords.x pixels = element.to_pixels()[:render_height] for line_index, line in enumerate(pixels): for pixel_index, pixel in enumerate(line[:render_width]): pixel_coords = coords.add_y(line_index).add_x(pixel_index) self.add_pixel(pixel_coords, pixel) def add_pixel(self, coords, pixel): self.screen[coords.get_y()][coords.get_x()] = pixel def to_pixels(self): return self.screen def _create_empty_line(self): return [BLANK_PIXEL] * self.width def _create_blank_screen(self): return [self._create_empty_line() for _ in range(self.height)]
27ce397ca344134039439b54680da8a61fe717f4
zizhazhu/leetcode
/exercise/Binary-Search/222.完全二叉树的节点个数.py
1,118
3.609375
4
# # @lc app=leetcode.cn id=222 lang=python3 # # [222] 完全二叉树的节点个数 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def countNodes(self, root: TreeNode) -> int: if not root: return 0 level = 1 now = root while now.left: now = now.left level += 1 left = 2 ** (level - 1) right = 2 ** level - 1 def exist(num): mask = 1 << (level - 2) now = root while mask: if (mask & num) == 0: now = now.left else: now = now.right mask >>= 1 return now is not None while left < right: mid = (left + right) // 2 + 1 if exist(mid): left = mid else: right = mid - 1 return left # @lc code=end
93dc96bc4869f620af03aa0529f129f99fccb05f
heldaolima/Exercicios-CEV-Python
/ex059.py
1,114
4.0625
4
escolha = 0 n1 = float(input('Insira o primeiro valor: ')) n2 = float(input('Insira o segundo valor: ')) while escolha != 5: print('-----------------') print('''Opções: [1] SOMAR [2] MULTIPLICAR [3] DESCOBRIR QUAL É O MAIOR [4] INSERIR NOVOS NÚMEROS [5] SAIR DO PROGRAMA''') escolha = int(input('O que deseja fazer? ')) if escolha == 1: print(f'{n1} + {n2} = {n1 + n2}.') elif escolha == 2: print(f'{n1} * {n2} = {n1 * n2}') elif escolha == 3: if n1 != n2: print(f'Entre {n1} e {n2}, ', end='') if n1 > n2: print(f'{n1} é maior.') elif n2 > n1: print(f'{n2} é maior.') else: print('Os valores inseridos são iguais.') elif escolha == 4: print('Trabalhando nisso... ') n1 = float(input('Insira o novo primeiro valor: ')) n2 = float(input('Insira o novo segundo valor: ')) elif escolha == 5: print('Programa encerrado.') else: print('Insira uma opção válida: ') print('Até mais')
f70b19de43fdfe57e0e84d55c297b9456959711a
JoaoFiorelli/ExerciciosCV
/Ex020.py
239
3.546875
4
import random n1 = input('Aluno um: ') n2 = input('Aluno dois: ') n3 = input('Aluno três: ') n4 = input('Aluno quatro: ') lista = [n1, n2, n3, n4] random.shuffle(lista) print('A ordem de apresentação dos alunos será: ') print(lista)
757ad7a14b628492b3b36620361b6eb11d5c6c49
andresvanegas19/holbertonschool-higher_level_programming
/0x0A-python-inheritance/3-is_kind_of_class.py
289
3.53125
4
#!/usr/bin/python3 """Test if the object is inherent of a class""" def is_kind_of_class(obj, a_class): """function that validated if the object is a instace of a class in python""" try: return isinstance(type(obj), a_class) except TypeError: return False
a32289f4feb1125717c6ced9128ffdae6d9e5fac
ruyixuan/Python
/whiletest.py
217
3.890625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- var = 0 while var < 10: num = input(str(var)+"Enter a number:") var += 1 if num == "fuck": print ("请注意语言文明") break else: print ("超过限制!")
d0ecbd53be6f0dfee826ded405ee07d0535fde55
ankitdbst/Utilities
/ciphers/cipher.py
794
3.734375
4
#!/usr/bin/env python import sys class Cipher: mod = 26 def init(self): pass def encrypt(self): pass def decrypt(self): pass def modexponent(self, base, exp, m): result = 1 while exp > 0: if exp & 1 == 1: result = (result * base) % m base = (base * base) % m exp >>= 1 return result % m def egcd(self, a, b): if a == 0: return b, 0, 1 d, x1, y1 = self.egcd(b % a, a) x = y1 - (b / a) * x1 y = x1 return d, x, y def inversemod(self, a): g, x, y = self.egcd(a, self.mod) return x def case(self, ch): return (ch.isupper() and 'A') or 'a' # checks whether key char is upper/lower
90f9f9517b3a378073a865d96b4aaf701fa16d2d
DrMikeG/LegoEcho
/pythonBook/book_examples/chapter_05/5.1.py
511
3.78125
4
from datetime import datetime class Animal(object): """A class representing an arbitrary animal.""" def __init__(self, name): self.name = name def eat(self): pass def go_to_vet(self): pass class Cat(Animal): def meow(self): pass def purr(self): pass if __name__== "__main__": dr = DateRange(MyDate(2015, 1, 1), MyDate(2015, 12, 31)) print( MyDate(2015, 4, 21) in dr ) print( MyDate(2012, 4, 21) in dr )
34cb637d5f00ec75016f5a4f86f8a3ad74dd6498
mcmanutom/LCA
/LCAPython/src/LCA.py
1,533
3.640625
4
''' Created on 15 Oct 2020 @author: user ''' # A binary tree node class Node: def __init__(self, key): self.key = key self.left = None self.right = None def findPath( root, path, k): if root is None: return False # Store this node is path vector. The node will be # removed if not in path from root to k path.append(root.key) # See if the k is same as root's key if root.key == k : return True # Check if k is found in left or right sub-tree if ((root.left != None and findPath(root.left, path, k)) or (root.right!= None and findPath(root.right, path, k))): return True path.pop() return False # Returns LCA if node n1 , n2 are present in the given # binary tre otherwise return -1 def findLCA(root, n1, n2): path1 = [] path2 = [] if (not findPath(root, path1, n1) or not findPath(root, path2, n2)): return -1 i = 0 while(i < len(path1) and i < len(path2)): if path1[i] != path2[i]: break i += 1 return path1[i-1] root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) # This code is from by https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/ as i could not figure out python and have not used it before
a7b609d249b232989bcf46649c8318631ff0acaf
Phlank/ProjectEuler
/python/src/pje_0036.py
1,225
3.671875
4
#returns a list of digits of i def int_to_list(i): list = [int(x) for x in str(i).zfill(1000)] while list[0] == 0: list.remove(0) return list #reverses a list def reverse(l): reverse_list = [] x = len(l)-1 while x >= 0: reverse_list.append(l[x]) x -= 1 return reverse_list #returns an int from the digits in l def list_to_int(l): return int("".join(str(x) for x in l)) #returns 1 if i is palindromic and 0 otherwise def is_palindrome(i): i_list = int_to_list(i) if i_list == reverse(i_list): return 1 else: return 0 #returns i as a binary number binary_list = [524288, 262144, 131072, 65536, 32768, 16384, 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1] binary_list_length = len(binary_list) def to_binary(i): i_binary_list = [] i_started = 0 for x in range(0, binary_list_length): if i >= binary_list[x]: i_binary_list.append(1) i -= binary_list[x] if i_started == 0: i_started = 1 elif i_started == 1: i_binary_list.append(0) i_binary = list_to_int(i_binary_list) return i_binary out = 0 n = 1 while n < 1000000: if is_palindrome(n) == 1: if is_palindrome(to_binary(n)) == 1: out += n n += 2 print "%d" % (out)
2a3ef4bc7eba470e1a2629d56a0cd16167beb08d
samkit5495/data-visualization-matplotlib
/code.py
2,391
3.515625
4
# -------------- import pandas as pd import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') # Load the dataset and create column `year` which stores the year in which match was played df = pd.read_csv(path) df['year'] = df['date'].str[:4] match_data = df.drop_duplicates(subset='match_code',keep='first') # Plot the wins gained by teams across all seasons win_data = match_data['winner'].value_counts() print(win_data) win_data.plot(kind='bar', title='Total wins accross all seasons') plt.show() # Plot Number of matches played by each team through all seasons matches_played = pd.melt(match_data, id_vars=['match_code','years'],value_vars=['team1','team2']) print(matches_played.head()) matches_played = matches_played['value'].value_counts() matches_played.plot(kind='bar',title='Total matches played across all seasons') plt.show() # Top bowlers through all seasons df['wicket_kind'].value_counts() wicket_data = df[df['wicket_kind']!=''] bowlers_wickets_data = wicket_data.groupby(['bowler'])['wicket_kind'].count() bowlers_wickets_data.head() bowlers_wickets_data.sort_values(ascending=False, inplace=True) bowlers_wickets_data[:10].plot(kind='barh') plt.show() # How did the different pitches behave? What was the average score for each stadium? score_venue = df.groupby(['match_code','inning','venue'],as_index=False)['total'].sum() score_venue.head() avg_score_venue = df.groupby(['venue'])['total'].mean().sort_values(ascending=False) avg_score_venue.head() avg_score_venue[:10].plot(kind='barh') plt.show() # Types of Dismissal and how often they occur dismissal_types = df.groupby('wicket_kind')['match_code'].count() dismissal_types dismissal_types.plot.pie() plt.show() # Plot no. of boundaries across IPL seasons boundaries = df[df['runs']>=4] boundaries_by_season = boundaries.groupby('year')['runs'].count() boundaries_by_season boundaries_by_season.plot.line(title='no. of boundaries across IPL seasons') plt.show() # Average statistics across all seasons num_of_matches = df.groupby('year')['match_code'].nunique() num_of_matches num_of_matches.plot.bar(title='Matches per season') plt.show() runs_per_match = df.groupby(['year','match_code'],as_index=False)['runs'].sum() runs_per_match.head() avg_runs = runs_per_match.groupby(['year'])['runs'].mean() avg_runs avg_runs.plot.bar(title='average runs scored per season') plt.show()
0a5c62edddb0b2e944b8f1afa9b084dac368e90f
diogolimas/game-pygame
/game-parte1.py
752
3.71875
4
import pygame pygame.init() #locations variables x = 400 y = 300 velocity = 10 window = pygame.display.set_mode((600,600)) pygame.display.set_caption("Py Game test application") open_window = True while(open_window): pygame.time.delay(50) for event in pygame.event.get(): if event.type == pygame.QUIT: open_window = False commands = pygame.key.get_pressed() if(commands[pygame.K_UP]): y-= velocity if(commands[pygame.K_DOWN]): y+= velocity if(commands[pygame.K_RIGHT]): x+= velocity if(commands[pygame.K_LEFT]): x-= velocity window.fill((229, 244, 251)) pygame.draw.circle(window, (148, 216, 45), (x,y), 50 ) pygame.display.update() pygame.quit()
7860030c4ed7d870faf7416a348412c27a6e634d
xsr-e/pythonf
/13_tuples.py
132
3.953125
4
box1 = (4,4) box2 = (2,3) box3 = (2,8) boxes = [box1, box2, box3] for b in boxes: x,y = b print ("x:{}, y:{}".format(x,y))
d08e9d97afdcbea0eaa08c218378d72f3da68cab
jiangshen95/UbuntuLeetCode
/HouseRobberIII.py
959
3.5625
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def rob(self, root): """ :type root: TreeNode :rtype: int """ def rob(root): if not root: return 0 if root in m: return m[root] val = root.val if root.left: val += rob(root.left.left) + rob(root.left.right) if root.right: val += rob(root.right.left) + rob(root.right.right) return max(val, rob(root.left) + rob(root.right)) m = {} return rob(root) if __name__ == '__main__': a = TreeNode(3) b = TreeNode(4) c = TreeNode(5) d = TreeNode(1) e = TreeNode(3) f = TreeNode(1) a.left = b a.right = c b.left = d b.right = e c.right = f solution = Solution() print(solution.rob(a))
aab2f4a15cabff0def52f27cf990fa78e293032e
Crasti/Homework
/Lesson1/Task3.py
312
4.0625
4
"""Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369.""" digit = input("Введите число: ") print(int(digit) + int(digit * 2) + int(digit * 3))
ce32718e87d395fe10eb94bfa77cef43e403a097
Starefossen/euler
/problem 7.py
216
3.765625
4
from math import ceil, sqrt primes = [] i = 1 while (len(primes) < 10): isPrime = True for prime in primes: if (i%prime == 0): isPrime = False break if (isPrime): primes.append(i) i += 2 print primes
3456a0f06147b3344aee6baddf14dfdba710e16f
ittoyou/2-1807
/16day/3-生成器.py
233
3.75
4
''' def test(): a,b = 0,1 for i in range(10): a,b = b,a+b yield b t = test() for i in t: print(i) ''' def test(): a,b = 0,1 for i in range(10): a,b = b,a+b yield b t = test() for i in t: print(i)
67c595279a4371ca1d113588f49c4f142b94fbd7
hesham9090/Algorithms
/Insertion_Sort.py
816
4.46875
4
""" Insertion Sort is not fast algorithm because it uses nested loops to sort it can be used only for small data Check below image for more illustration about how insertion sort works https://github.com/hesham9090/Algorithms/blob/master/images/InsertionSort.png """ data = [100,12,90,19,22,8,12] data2 = [9] data3 = [10,9,8,7,6,5,4,3,2,1] def insertion_sort(data): for j in range(1, len(data)): key = data[j] i = j - 1 while (i >= 0) and (data[i] > key): data[i + 1] = data[i] i = i - 1 data[i + 1] = key return data test_case1 = insertion_sort(data) test_case2 = insertion_sort(data2) test_case3 = insertion_sort(data3) print(test_case1) print(test_case2) print(test_case3) """ Time Complexity Analysis O(n^2) """
4ce09b5c3934eb0054b71b65998b627db69ae207
Abis47/HH-PA2609-1
/24_LR/4LR.py
3,241
3.65625
4
#Topic: Linear Regression Stock Market Prediction #----------------------------- #libraries import pandas as pd import matplotlib.pyplot as plt Stock_Market = {'Year': [2017,2017,2017, 2017,2017,2017,2017,2017, 2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016, 2016,2016,2016], 'Month': [12, 11,10,9,8,7,6, 5,4,3, 2,1,12,11, 10,9,8,7,6,5,4,3,2,1], 'Interest_Rate': [2.75,2.5,2.5,2.5,2.5, 2.5,2.5,2.25,2.25, 2.25,2,2,2,1.75,1.75, 1.75,1.75, 1.75,1.75,1.75,1.75,1.75,1.75,1.75], 'Unemployment_Rate': [5.3,5.3, 5.3,5.3,5.4,5.6,5.5, 5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1, 5.9,6.2,6.2, 6.1],'Stock_Index_Price':[1464,1394,1357,1293,1256,1254,1234,1195, 1159,1167,1130,1075,1047,965, 943,958,971,949,884,866,876,822,704,719] } #dictionary format type(Stock_Market) df = pd.DataFrame(Stock_Market, columns=['Year','Month','Interest_Rate', 'Unemployment_Rate','Stock_Index_Price']) df.head() print (df) #check that a linear relationship exists between the: #Stock_Index_Price (dependent variable) and Interest_Rate (independent variable) #Stock_Index_Price (dependent variable) and Unemployment_Rate (independent variable) #run these lines together plt.scatter(df['Interest_Rate'], df['Stock_Index_Price'], color='red') plt.title('Stock Index Price Vs Interest Rate', fontsize=14) plt.xlabel('Interest Rate', fontsize=14) plt.ylabel('Stock Index Price', fontsize=14) plt.grid(True) plt.show(); # linear relationship exists between the Stock_Index_Price and the Interest_Rate. Specifically, when interest rates go up, the stock index price also goes up: plt.scatter(df['Unemployment_Rate'], df['Stock_Index_Price'], color='green') plt.title('Stock Index Price Vs Unemployment Rate', fontsize=14) plt.xlabel('Unemployment Rate', fontsize=14) plt.ylabel('Stock Index Price', fontsize=14) plt.grid(True) plt.show() ; #linear relationship also exists between the Stock_Index_Price and the Unemployment_Rate – when the unemployment rates go up, the stock index price goes down (here we still have a linear relationship, but with a negative slope): #Multiple Linear Regression from sklearn import linear_model #1st method from sklearn.linear_model import Ridge from sklearn.linear_model import LinearRegression X = df[['Interest_Rate','Unemployment_Rate']] # here we have 2 variables for multiple regression. If you just want to use one variable for simple linear regression, then use X = df['Interest_Rate'] for example. Alternatively, you may add additional variables within the brackets Y = df['Stock_Index_Price'] # with sklearn #regr = linear_model.LinearRegression() regr = Ridge(alpha=1.0) #regr = LinearRegression() regr.fit(X, Y) y_pred= regr.predict(X.values) y_pred Y from sklearn.metrics import r2_score regr.score(X,Y) New_Interest_Rate = 4.75 New_Unemployment_Rate = 3.3 print ('Predicted Stock Index Price: \n', regr.predict([[New_Interest_Rate ,New_Unemployment_Rate]])) data1=X data1['R']=Y data1 from statsmodels.formula.api import ols model2 = ols('R ~ Interest_Rate + Unemployment_Rate', data=data1).fit() model2.summary() import numpy as np from sklearn.linear_model import SGDRegressor X Y reg= SGDRegressor() reg.fit(X,Y) reg.score(X,Y)
ec2361923d5e994a210d0c3c612535181f2f6dea
JosephKheir/Bioinformatics
/LoopsAndDecisions/count_kmers.py
644
3.5625
4
#!/usr/bin/env python # count_kmers.py seq = 'GCCGGCCCTCAGACAGGAGTGGTCCTGGATGTGGATG' kmer_length = 6 # Initialize a k-mer dictionar kmer_dictionary = {} # Iterate over the positions for start in range(0, len(seq) - kmer_length): # Get the substring at a specific start and end position kmer = seq[start:start+ kmer_length] #see if it's in the dicitonary if kmer in kmer_dictionary: #Add one to the count kmer_dictionary[kmer] += 1 else: #It's not in the dictionary so add with a count of 1 kmer_dictionary[kmer] = 1 #Print the number of keys in the dictionary print(len(kmer_dictionary))
759906ca7de02a0523bdcb92493a639027a07bd1
dkumor/rtcbot
/rtcbot/subscriptions.py
8,014
3.5
4
import asyncio import numpy as np from functools import partial import logging from collections import deque class EventSubscription: """ This is a subscription that is fired once - upon the first insert. """ def __init__(self): self.__evt = asyncio.Event() self.__value = None def put_nowait(self, value): self.__value = value self.__evt.set() async def get(self): await self.__evt return self.__value def __await__(self): return self.get().__await__() class MostRecentSubscription: """ The MostRecentSubscription always returns the most recently added element. If you get an element and immediately call get again, it will wait until the next element is received, it will not return elements that were already processed. It is not threadsafe. """ def __init__(self): self._putEvent = asyncio.Event() self._element = None def put_nowait(self, element): """ Adds the given element to the subscription. """ self._element = element self._putEvent.set() async def get(self): """ Gets the most recently added element """ # Wait for the event marking a new element received await self._putEvent.wait() # Reset the event so we can wait for the next element self._putEvent.clear() return self._element class GetterSubscription: """ You might have a function which behaves like a get(), but it is just a function. The GetterSubscription is a wrapper that calls your function on get():: @GetterSubscription async def myfunction(): asyncio.sleep(1) return "hello!" await myfunction.get() # returns "hello!" """ def __init__(self, callback): self._callback = callback async def get(self): return await self._callback() class CallbackSubscription: """ Sometimes you don't want to await anything, you just want to run a callback upon an event. The CallbackSubscription allows you to do precisely that:: @CallbackSubscription async def mycallback(value): print(value) cam = CVCamera() cam.subscribe(mycallback) Note: This is no longer necessary: you can just pass a function to `subscribe`, and it will automatically be wrapped in a `CallbackSubscription`. """ def __init__(self, callback, loop=None, runDirect=False): self._callback = callback self._loop = loop self._runDirect = runDirect if self._loop is None: self._loop = asyncio.get_event_loop() def put_nowait(self, element): # We don't want to stall the event loop at this moment - we call it soon enough. if self._runDirect: self._callback(element) else: self._loop.call_soon(partial(self._callback, element)) class DelayedSubscription: """ In some instances, you want to subscribe to something, but don't actually want to start gathering the data until the data is needed. This is especially common in something like audio streaming: if you were to subscribe to an audio stream right now, and get() the data only after a certain time, then there would be a large audio delay, because by default the audio subscription queues data. This is common in the audio of an RTCConnection, where `get` is called only once the connection is established:: s = Microphone().subscribe() conn = RTCConnection() conn.audio.putSubscription(s) # Big audio delay! Instead, what you want to do is delay subscribing until `get` is called the first time, which would wait until the connection is ready to start sending data:: s = DelayedSubscription(Microphone()) conn = RTCConnection() conn.audio.putSubscription(s) # Calls Microphone.subscribe() on first get() One caveat is that calling `unsubscribe` will not work on the DelayedSubscription - you must use unsubscribe as given in the DelayedSubscription! That means:: m = Microphone() s = DelayedSubscription(m) m.unsubscribe(s) # ERROR! s.unsubscribe() # correct! Parameters ---------- SubscriptionWriter: BaseSubscriptionWriter An object with a subscribe method subscription: (optional) The subscription to subscribe. If given, calls `SubscriptionWriter.subscribe(subscription)` """ def __init__(self, SubscriptionWriter, subscription=None): self.SubscriptionWriter = SubscriptionWriter self.subscription = subscription self._wasInitialized = False def unsubscribe(self): if self.subscription is not None: self.SubscriptionWriter.unsubscribe(self.subscription) self._wasInitialized = True async def get(self): if not self._wasInitialized: self.subscription = self.SubscriptionWriter.subscribe(self.subscription) self._wasInitialized = True if self.subscription is None: raise AttributeError( "DelayedSubscription.subscription is None - this means that you did not pass a subscription object, and unsubscribed before one was created!" ) return await self.subscription.get() class RebatchSubscription: """ In certain cases, data comes with a suboptimal batch size. For example, audio coming from an `RTCConnection` is always of shape `(960,2)`, with 2 channels, and 960 samples per batch. This subscription allows you to change the frame size by mixing and matching batches. For example:: s = RebatchSubscription(samples=1024,axis=0) s.put_nowait(np.zeros((960,2))) # asyncio.TimeoutError - the RebatchSubscription does # not have enough data to create a batch of size 1024 rebatched = await asyncio.wait_for(s.get(),timeout=5) # After adding another batch of 960, get returns a frame of goal shape s.put_nowait(np.zeros((960,2))) rebatched = await s.get() print(rebatched.shape) # (1024,2) The RebatchSubscription takes samples from the second data frame's dimension 1 to create a new batch of the correct size. """ def __init__(self, samples, axis=0, subscription=None): assert samples > 0 if subscription is None: subscription = asyncio.Queue() self.subscription = subscription self._sampleQueue = deque() self._samples = samples self._axis = axis self._partialBatch = None # https://stackoverflow.com/questions/12116830/numpy-slice-of-arbitrary-dimensions if self._axis > 0: self._idxa = tuple([slice(None)] * (self._axis) + [slice(0, self._samples)]) self._idxb = tuple( [slice(None)] * (self._axis) + [slice(self._samples, None)] ) elif self._axis == -1: self._idxa = (Ellipsis, slice(self._samples)) self._idxb = (Ellipsis, slice(self._samples, None)) else: self._idxa = slice(self._samples) self._idxb = slice(self._samples, None) def put_nowait(self, data): self.subscription.put_nowait(data) async def get(self): while len(self._sampleQueue) == 0: data = await self.subscription.get() if self._partialBatch is not None: data = np.concatenate((self._partialBatch, data), axis=self._axis) while data.shape[self._axis] >= self._samples: self._sampleQueue.append(data[self._idxa]) data = data[self._idxb] if data.shape[self._axis] > 0: self._partialBatch = data else: self._partialBatch = None return self._sampleQueue.popleft()
ddb1225cae9bd158c9026e2e50d14c7e302e2376
YunsongZhang/lintcode-python
/VMWare/1357. Path Sum II.py
807
3.734375
4
class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param root: a binary tree @param sum: the sum @return: the scheme """ def pathSum(self, root, target): paths = [] self.dfs(root, [], target, paths) return paths def dfs(self, root, path, target, paths): if not root: return curt_path = path + [root.val] if root.left is None and root.right is None: if target - root.val == 0: paths.append(curt_path) return if root.left: self.dfs(root.left, curt_path, target - root.val, paths) if root.right: self.dfs(root.right, curt_path, target - root.val, paths)
75d310853bd7f0dc68f2b412e7583b2a4f241053
SSStanislau/CodeWars
/7 kyu/regexp_basics_is_it_a_letter.py
200
3.90625
4
''' Complete the code which should return true if the given object is a single ASCII letter (lower or upper case), false otherwise. ''' def is_letter(s): return s.isalpha() and len(s)==1
edf4de402f1c4539036f227ffec70c3fe8bf6d1c
Chen-Yiyang/Python
/Practical 1/Qn2.py
284
4.40625
4
# Computing the volume of a cylinder # by Yiyang 14/01/18 _radius = float(input("Radius of the cylinder = ")) _length = float(input("Length of the cylinder = ")) _area = (_radius ** 2) * 3.141593 _volume = _area * _length print("Volume of the cylinder = {0:.2f}".format( _volume))