blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8c7829300505a62d441d882dbeb92bb0353087a9
thomman/hackerrank
/bonAppetit.py
243
3.515625
4
n, k = (int(i) for i in input().split()) food = [int(i) for i in input().split()] price = int(input()) def op(n , k, food, price): anna = sum(food[i] for i in range(n) if i != k)//2 return 'Bon Appetit' if anna == price else (price - anna)
55cfc5125b3606b2483d165d950fcc87da67655b
Rishav78/Python
/enum.py
151
3.65625
4
def index(l,s): for x,y in enumerate(l): if y==s: return x return -1 l = list([1,2,3,4,5,6]) print(l,4) print(index(l,4))
70680ae6af18a5d6b809dd0c56800e582bb5b18e
kellyeschumann/comp110-21ss1-workspace
/exercises/ex01/numeric_operators.py
888
3.953125
4
"""This takes two numbers input from user and completes four mathematical equations.""" __author__: str = "730314660" left = "Left-hand side" right = "Right-hand side" numberOne: str = input("What is the first number? ") print("You entered: ") print(numberOne) numberTwo: str = input("What is the second number? ") print("You entered: ") print(numberTwo) print(left + ": " + numberOne) print(right + ": " + numberTwo) integerOne = int(numberOne) integerTwo = int(numberTwo) resultOne = integerOne ** integerTwo resultTwo = integerOne / integerTwo resultThree = integerOne // integerTwo resultFour = integerOne % integerTwo print(numberOne + " ** " + numberTwo + " is " + str(resultOne)) print(numberOne + " / " + numberTwo + " is " + str(resultTwo)) print(numberOne + " // " + numberTwo + " is " + str(resultThree)) print(numberOne + " % " + numberTwo + " is " + str(resultFour))
1256563bed6ccbc2749c3efb303eb609c242f41a
MaximilianoCaba/UADE-Programacion-Python
/programacion1/Clase4.py
801
3.546875
4
import random def buildMatriz(list, rows, colums): for i in range(rows): list.append([0] * colums) def generateRandomNumber(): number = random.randint(0, 999) return number * number def chargeMatriz(list): list_number_uniq = [] for (i, value) in enumerate(list): for (j, value2) in enumerate(value): number = generateRandomNumber() while number in list_number_uniq: number = generateRandomNumber() list_number_uniq.append(number) list[i][j] = number def printMatriz(list): for (i, value) in enumerate(list): for (j, value2) in enumerate(value): print("%3d" %list[i][j], end="") print() list = [] buildMatriz(list, 4, 4) chargeMatriz(list) printMatriz(list)
1af49ad65404348a3647a298416514ca41dec73d
JanikRitz/Python_Euler_Challenges
/Euler_010_other.py
755
3.78125
4
''' The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. ''' import datetime # Actual code # primes = deque([2, 3, 5, 7, 11, 13]) sieve = set() print("Sum of primes less than...?") i = int(input()) start_time = datetime.datetime.now() psum = (i * (i + 1)) / 2 def S(x): n = 2 m = 2 while n <= round(x ** .5): if m * n <= i: sieve.add(m * n) m += 1 else: m = 2 n += 1 S(i) print(sum(sieve)) psum = psum - sum(sieve) # End actual code end_time = datetime.datetime.now() print(f'Primenumbers below {i} sum is: {psum-1} ({(end_time - start_time)})') # Primenumbers below 2000000 sum is: 142913828922.0 (0:00:09.010722)
c90205c84bda64806a0b5ff323ed601b0ff2dac1
easycodescreator/rock-paper-scissors
/Rock-Paper-Scissors.py
1,106
4.21875
4
# The apps first takes your choice. p1 = input("Enter : ") p2 = input("Enter : ") a = "paper" b = "rock" c = "scissors" # check that p1 is equal p2. while p1 == p2: p1 = input("Enter again: ") p2 = input("Enter again: ") # if p1 and p2 not equal start loop. while p1 != p2: if p1 != p2: if p1 == a and p2 == b or p1 == b and p2 == c or p1 == c and p2 == a: print("p1 won!!") elif p2 == a and p1 == b or p2 == b and p1 == c or p2 == c and p1 == a: print("p2 won!!") # if user wants to continue input Enter otherwise # input quit print("If you want to continue press Enter otherwise enter 'quit' ") g = input("ENTER: ") if g == "": p1 = input("Enter again: ") p2 = input("Enter again: ") elif g == "quit": break # if user input p1 and p2 same thing takes again his/her choice # until he/she input p1 and p2 different. while p1 == p2: p1 = input("Enter, again: ") p2 = input("Enter, again: ") print("End Game!!")
e12e517d4ba3a6f505389728f3d9ec3279977685
Sway007/regex-python-test
/comma.py
132
3.765625
4
import re txt = input('give me an integer: ') pattern = r'(?<=\d)(?=(\d{3})+(?!\d))' p = re.compile(pattern) print(p.sub(',', txt))
583d7c4fe0c32ae782e51288e8e7e2d987225a33
hemangbehl/Data-Structures-Algorithms_practice
/session4/checkIfWordCanBeMadePalindrombyRearrangement.py
569
3.75
4
def checkPalin(s1): if len(s1) <= 1: return True dict1 = {} odd = 0 for ch in s1: if ch in dict1: dict1[ch] += 1 if dict1[ch] % 2 == 0: odd -= 1 else: #odd freq odd += 1 else: #not in dict dict1[ch] = 1 odd += 1 if len(s1) % 2 == 0 and odd != 0: return False if len(s1) % 2 == 1 and odd > 1: return False return True s1 = "geeksogeeks" s2 = "geeksforgeeks" print ( checkPalin(s1) ) print ( checkPalin(s2) )
0684d002da984962aae14acd8179eddf04a320a2
trungtruc123/NLP
/bai3_1_convertEncoding.py
89
3.515625
4
import pandas as pd text =" T Tan Trung Truc" print(pd.get_dummies(text.split()))
0dd397c9b432e46c645a734617d7b9dde8e35dbb
joestalker1/leetcode
/src/main/scala/SingleElementInSortedArray.py
763
3.609375
4
class Solution: def singleNonDuplicate(self, nums): lo = 0 hi = len(nums) - 1 #array shouldn't be sorted but should being pairing while lo < hi: # strict inequality m = lo + (hi-lo) // 2 halves_is_even = (hi - m) % 2 == 0 if nums[m] == nums[m+1]: # mid 's partner is to the right if halves_is_even: lo = m + 2 else: hi = m - 1 elif nums[m-1] == nums[m]: # mid partner is to the left if halves_is_even: hi = m - 2 else: lo = m + 1 else: return nums[m] return nums[lo]
8b7d2dd6d7aac713356a2591510a9cd12f7ec11c
jianjhihlai/FaceApp
/examples/02.schedulecheck.py
279
3.640625
4
todoList = ["掃地", "拖地", "煮飯"] notyet = [] for idx, task in enumerate(todoList): answer = input("您的第{}件事是{},您完成了嗎?Ans:".format(idx+1, task)) if answer != "done": notyet.append(task) print("您還剩下以下工作:") print(notyet)
e1640eeaf7d36d5d0aa90aa38031efde06835775
anjihye-4301/python
/ch05if/ch05_03findNum.py
597
3.890625
4
import random # 랜덤으로 발생된 숫자 10개를 저장하는 리스트 numbers = [] # range(시작번호, 끝번호+1) for num in range(0, 10): print(num) # random.randrage(발생시작 숫자, 발생 끝 숫자+1) numbers.append(random.randrange(0, 10)) print("생성된 리트스 : ", numbers) # 0 ~ 9 사이의 각각의 데이터가 있는지 확인해보자 for num in range(0, 10): if num in numbers: print("숫자 %d는(은) 리스트에 있습니다." % num) if num not in numbers: print("숫자 %d는(은) 리스트에 없습니다." % num)
6197ddb4085c38669106b2b59a5d67dee4fa61c9
HenryBalthier/Python-Learning
/Leetcode_easy/hash/204.py
438
3.640625
4
class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ if n < 3: return 0 res = [1] * n res[0] = res[1] = 0 for i in range(int(n ** 0.5)+1): if res[i]: res[i*i:n:i] = [0] * len(res[i*i:n:i]) return sum(res) if __name__ == '__main__': s = Solution() n = 100 print(s.countPrimes(n))
9020e978d036d06604c0aaaa9645b516c289d378
Disha-Shivale/Pythonset
/list2.py
430
3.859375
4
#Fetch value with Loop a = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'] for i in a: print(i) #Check value in list with loop a = ['Item 1', 'Felix', 'Item 3', 'Item 4', 'Item 5', 'Item 6'] print() if 'Felix' in a: print("Felix ITs System") print() else: print("Value is not available") print() #Check lenght of List print(len(a)) print() #Append() Method a.append("Felix 7") print(a) print()
078c560e437cb88872b480ebf6378406a4ad6c9e
hollisas/CSCI220
/triangle.py
831
4.09375
4
# triangle.py # Author: Zelle (pp. 103-04) # Modified by Pharr to eliminate coordinates from graphics import * def main(): winWidth = 400 winHeight = 400 win = GraphWin("Draw a Triangle", winWidth, winHeight) message = Text(Point(winWidth/2, winHeight-10), "Click on three points") message.draw(win) # Get and draw three vertices of a triangle p1 = win.getMouse() p1.draw(win) p2 = win.getMouse() p2.draw(win) p3 = win.getMouse() p3.draw(win) # Use Polygon object to draw the triangle triangle = Polygon(p1, p2, p3) triangle.setFill("peachpuff") triangle.setOutline("cyan") triangle.draw(win) # Wait for another click to exit message.setText("Click anywhere to quit") win.getMouse() win.close() main()
c86e75445908fd2c839b3542531f48d8811da9f8
domspad/text_viz_project
/texttools.py
2,989
3.6875
4
""" Tools and utility functions for working with text """ from __future__ import print_function, division import nltk from nltk import word_tokenize #, pos_tag import nltk.data import string from syllablecount import sylco, sylco_com from time import time import numpy as np SENTENCIZER = nltk.data.load('tokenizers/punkt/english.pickle') def segment(text,unit) : """ returns the text broken up and filtered according to the unit 'sents','words','sylls' (later add paragraphs) e.g. 'The quick brown fox runs. The turtle doesn\'t.', 'words' ('The', 'quick', 'brown', 'fox','runs', 'The', 'turtle','doesn\'t') """ # if unit == 'paragraphs' : # '\n\s' if unit == 'sents' : return SENTENCIZER.tokenize(text) elif unit == 'words' : return [word.strip(string.punctuation) for word in text.split()] elif unit == 'sylls' : print('not implemented yet') return None elif unit == 'book' : return [text] else : print("not valid input for unit") return None def get_lengths(text, unit='words', count_unit='chars') : """ returns the lengths of ___ words (in chars or sylls) sents (in chars or words) paragraphs (in sents, words, or chars) book (in sents, words, sylls or chars) """ print ("getting lengths of {} in terms of {}".format(unit,count_unit)) t0 = time() # break up into units tokens = segment(text,unit) # break units up into count units counts = [] for token in tokens : # breaking up token into chars would be waste if count_unit == 'chars' : counts.append(len(token)) # breaking up into sylls actually quite difficult... # instead trying to just call count_syl on each word elif count_unit == 'sylls' : # breaking each token into words if necessary # counting syllables if unit != 'words' : subtokens = segment(token,'words') sylcount = reduce(lambda agg,word : agg + sylco_com(word), subtokens, 0) else : sylcount = sylco_com(token) # appending value counts.append(sylcount) else : subtokens = segment(token, count_unit) counts.append(len(subtokens)) print ("finished in {} secs".format(str(round(time()-t0,1)))) # return count return np.array(counts) def get_unique_words(text) : """ returns the set of unique words in the text (modulo case) """ pass def unique_word_density(text) : """ returns the density of unique words in the text # unique words -------------- # words """ pass def pos_counts(text) : """ returns counts of each part of speech tag """ pass def flesch_reading_ease(text) : """ see https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests """ sylls = get_lengths(text,'book','sylls') words = get_lengths(text,'book','words') sents = get_lengths(text,'book','sents') print ("words / sent {}\nsylls / word {}".format(words/sents, sylls/words)) print("sylls {}\n words {}\n sents {}".format(sylls, words, sents)) return (206.835 - 1.015 * (words / sents) - 84.6 * (sylls / words))[0]
71cd767a7861ad91cc2d14d03a7af373a3c8a1c4
jgslunde/INF3331
/regex/regex_guide.py
835
3.796875
4
import re s = "asdf ASDF AsDf asdfbat ASDFbat A$DFbat asdfbatasdfbat Adfbat bat asdf" regex = r"asdf" # Use the r (raw) in fron of the string to tell python the string # should be interpreted as "raw" and string-commands like \n, \b, etc won't be executedself ### Finding stuff ### matches = re.findall(regex, s) # Returns a list of all mathces in string # If the regex contains capture-groups, those will be returned instead. ### Substituting ### new_s = re.sub(regex, "x", s) # Returns a new string with all matching values substituted # NOTES: # In the replace section, most RegEx syntax doesn't apply, so characters # like | $ { } etc doesn't need to be cancelled: re.sub("\[\]", "[]", s) # Back-refrences can be made both in the search, and the replace section: re.sub("([A-C])\1", "\1", s)
7e64c2dba14b83115c8c2a118e0852401fb0aae5
pvanh80/intro-to-programming
/round10/cellphone_test.py
343
4.03125
4
# Intro to programming # Classes and Objects # Phan Viet Anh # 256296 import cellphone def main(): man = input('What is your phone\'s manufacture? ') mod = input('What is your phone\'s model? ') price = float(input('What is your phone\'s price? ')) cellphone = cellphone.CellPhone(man, mod, price) #print(cellphone) main()
802dfb90515869606ba380d016b40fd9fe761ded
axellbrendow/python3-basic-to-advanced
/aula057-getters-e-setters/aula57.py
1,300
3.6875
4
class Produto: def __init__(self, nome, preco): self.nome = nome self.preco = preco def desconto(self, percentual): self.preco -= self.preco * (percentual / 100) # Getter @property def nome(self): return self._nome # O nome com underline é apenas uma convenção. Poderia ser outro. # Setter @nome.setter def nome(self, valor): self._nome = valor.title() # Getter @property def preco(self): return self._preco # Setter @preco.setter def preco(self, valor): if isinstance(valor, str): # Checa se valor é uma string valor = float(valor.replace('R$', '')) self._preco = valor # p1 = Produto('CAMISETA', 50) # p1.desconto(10) # print(p1.nome, p1.preco) # p2 = Produto('CANETA', 'R$15') # p2.desconto(10) # print(p2.nome, p2.preco) class test: def __init__(self, value): self.value = value def __get__(self, instance, owner): print('Get called') return self.value def __set__(self, instance, value): print('Set called for', value) self.value = value class descripted: value = test(77) d = descripted() print(d.value) d.value = 108 print(d.value) # https://rszalski.github.io/magicmethods/
fcaf61455c0c172d091f61fb79654d2915caa4a5
awoka333/python_practice
/python crash course 01-10/hisshuhen-sample/chapter07/rollercoaster.py
196
3.84375
4
height = input("身長は何センチ? ") height = int(height) if height >= 90: print("\n乗ってもいいですよ!") else: print("\nもうちょっと大きくなったらね。")
d719024ff107fe1c4b093f8d402d35c1a34340d4
po7a7o/Python1
/Microeconomia/test.py
887
3.5625
4
from sympy import * from matplotlib import pyplot import sympy as sy import numpy as np import matplotlib as plt #Función Lineal. def Qd(x): return asa print ("aa: ", Qd(x)) # return 5-0.1*x #En esta variable se genera una lista con valores del -10 al 10. #Todos estos valores serán los que tomara x. x = range(-100, 100) #Con el método plot especificamos que función graficaremos. #El primer argumento es la variable con los valores de x. #El segundo argumento le pasamos todos estos valares a la función con ayuda de un bucle. pyplot.plot(x, [f(i) for i in x]) #Establecemos el color de los ejes. pyplot.axhline(0, color="black") pyplot.axvline(0, color="black") #Especificamos los limites de los ejes. pyplot.xlim(-5, 60) pyplot.ylim(-5, 6) #Guardamos el grafico en una imagen "png". #pyplot.savefig("función_lineal.png") # Mostramos el gráfico. pyplot.show()
0bda26beb41e65a5623e575d3ac3348625d75a4f
jiarmy1125/Kata
/Pair_of_gloves.py
1,455
3.796875
4
# my_gloves = ["red","green","red","blue","blue"] # number_of_pairs(my_gloves) == 2;// red and blue # red_gloves = ["red","red","red","red","red","red"]; # number_of_pairs(red_gloves) == 3; // 3 red pairs # number_of_pairs(["red","red"]),1 # number_of_pairs(["red","green","blue"]),0 # number_of_pairs(["gray","black","purple","purple","gray","black"]),3 # number_of_pairs([]),0 # number_of_pairs(["red","green","blue","blue","red","green","red","red","red"]),4 def number_of_pairs(gloves): x=[] g2=0 for g1 in gloves: print(g1,gloves.count(g1)) if (gloves.count(g1))%2 == 0: # print(g1,gloves.count(g1)) g3=gloves.count(g1)//2 x.append(g1) if g3 != 1: for k in range(0,g3,2): k=str(k) x.append(g1+k) else: g2=(gloves.count(g1))//2 print(g1," ",g2) if g2 !=0: for k in range(g2): k=str(k) x.append(g1+k) # print(x) x=set(x) print(x) print(len(x)) return len(x) # number_of_pairs(["red","red"]),1 # number_of_pairs(["gray","black","purple","purple","gray","black"]),3 # number_of_pairs([]),0 number_of_pairs( ['Silver', 'White', 'Teal', 'White', 'Black', 'Olive', 'Navy', 'Red', 'Olive', 'Red', 'Red', 'Silver', 'Maroon', 'Black', 'Yellow', 'Red', 'Yellow']) 7
8f6a97395c9b71a6709b88137cbd4092deb72f8e
hariomhardy/Data-Structures-and-Algorithms
/DS/tree_try_first.py
838
3.671875
4
import random class Tree: def __init__(self,value): self.value = value self.left = None self.right = None def add(self,value): h = Tree(value) if value > self.value: if self.right != None: self.right.add(value) else: self.right = h else: if self.left != None: self.left.add(value) else: self.left = h def inorder(self): if self.left != None: self.left.inorder() print(self.value) if self.right != None: self.right.inorder() t = Tree(5) for i in range(10): r = random.randint(0,100) print(r) t.add(r) print("order") t.inorder()
9c10fac41f793ddcf1d8d88472c46d976f0caa38
topanitanw/Python_Library
/file.py
524
3.828125
4
import os def abspath(relative_path, filename): ''' Return a absolute path of a file in String. ''' # os.sep = directory separator relative_filepath = relative_path + os.sep + filename return os.path.abspath(relative_path) def listfile(dirpath): ''' Return a list of files in a directory in dirpath. ''' file_lst = [] path = "." for elem in os.listdir(dirpath): if os.path.isfile(os.path.join(dirpath, elem)): file_lst.append(elem) return file_lst
9e6611d4f69b2ffb5eb3b7ad2c39138812eac4a1
rbhim/Python-Tools
/SQLite v1.py
962
4.09375
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 09 21:44:54 2014 @author: RBhim """ import sqlite3 conn = sqlite3.connect("traffic1.sqlite") #connect or create traffic db curs = conn.cursor() curs.execute("""DROP TABLE IF EXISTS traffic""")#drop table if it exist #Create Table traffic with three columns Speed:Flow:LOS f = curs.execute("""CREATE TABLE traffic(Speed INT, Flow INT, LOS STRING)""") #Create a list of tuples. Remember tubles are ordered dataset so ideal for db Data = [ (40,400,"A"), (40,500,"B"), (50,600,"C"), (50,700,"C"), (60,800,"D"), (80,800,"D"), (90,1000,"E"), (100,2000,"F") ] #Insert many fiels as once. You can use the curs.execute to insert only onw row curs.executemany("INSERT INTO traffic VALUES (?,?,?)", Data) #Saving changes to traffic db conn.commit() conn.close()
13943c7e5849681461eb92dc38838c7cd8aa998c
hutanugeorge/Data-Structures-Python
/DoublyLinkedList.py
3,028
4.0625
4
class DoublyLinkedList: class node: def __init__(self, value = None): self.value = value self.next = None self.prev = None def __init__(self): self.head = None self.tail = self.head self.lenght = 0 def append(self, value): new_node = self.node(value) if self.head is None: self.head = new_node self.tail = new_node self.tail.prev = self.head self.lenght += 1 else: new_node.prev = self.tail self.tail.next = new_node self.tail = new_node self.lenght += 1 return self def prepend(self, value): new_node = self.node(value) if not self.head: print("You can't prepend on a empty list") return self.head.prev = new_node new_node.next = self.head self.head = new_node self.lenght += 1 return self def insert(self, index, value): if isinstance(index, int): if index >= self.lenght: return self.append(value) new_node = self.node(value) leader = self.traverse_to_index(index - 1) next_node = leader.next leader.next = new_node new_node.next = next_node new_node.prev = leader next_node.prev = new_node self.lenght += 1 return self else: print('Index must be an integer!') return def remove(self, index): if isinstance(index, int): if self.lenght <= index or index < 0: print('Index must be smaller than list lenght and greater than 0!') return elif index == 0: next_item = self.head.next next_item.prev = None self.head = next_item self.lenght -= 1 return self if index == self.lenght-1: prev_tail = self.tail.prev prev_tail.next = None self.tail = prev_tail self.lenght -= 1 return self item = self.traverse_to_index(index-1) remove_item = item.next item.next = remove_item.next item.next.prev = remove_item.prev self.lenght -= 1 return self def traverse_to_index(self, index): current_node = self.head counter = 0 while counter != index: current_node = current_node.next counter += 1 return current_node def __len__(self): return self.lenght def print(self): if self.head is None: print('Linked list is empty') return else: array = [] current_node = self.head while current_node: array.append(current_node.value) current_node = current_node.next print(array)
e5de1e99a8791c37e017abaa75e8556a93278242
hunar21/Stock-market-vs-Covid-19
/COVID-19 VS STOCK MARKET .py
13,952
3.65625
4
#!/usr/bin/env python # coding: utf-8 # # How did COVID in India impact stock market # Let us analyse the impact of covid cases and vaccination, either increase or decrease, on stock market. Although it is common sense to conclude that increase in covid cases results in lockdowns and the economy is stopped, the production output decreases and as a result, profitability of companies decrease, and hence the stock prices go down. But majorly the stock market goes down because the market reacts to positive and negative news(for our case, covid news) and this impacts the stock market's index. # # But given the increase in levels of stock market indexes even when cases were not declining, is covid really impacting the stock market? What role does vaccination play into the positive mood of the market? # I am using the Covid data from kaggle - https://www.kaggle.com/sudalairajkumar/covid19-in-india which has details of all the positive cases from 30th january 2020, to 7th July 2021. # I have downloaded the stock market data from https://www1.nseindia.com/products/content/equities/indices/historical_index_data.htm for the same time period. # # INITIAL TASKS :- # # #### 1. IMPORTING REQUIRED LIBRARIES # #### 2.Data Preparation and Cleaning # We need to format dates as we will be using more than one data sets so that it becomes easier to plot them on the same chart. We will also use MinMaxScaler to bring the range of value between 0-1 so that we can plot values on the same chart # In[1]: import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt import seaborn as sns import sklearn.preprocessing as preprocessing import matplotlib.dates as mdates get_ipython().run_line_magic('matplotlib', 'inline') sns.set_style('darkgrid') matplotlib.rcParams['font.size'] = 14 matplotlib.rcParams['figure.figsize'] = (14, 5) matplotlib.rcParams['figure.facecolor'] = '#00000000' # # Analysis of Covid Data India # # In[2]: covid_india_df = pd.read_csv('/Users/parveenkumar/Desktop/stock market vs covid 19/covid_19_india.csv') covid_india_df.head() # In[3]: covid_india_df['Date'].dtype # In[4]: #It is better to parse string dates to datetime format. It is useful when we have more than one data sources. covid_india_df['Date'] = pd.to_datetime(covid_india_df['Date'], format='%Y-%m-%d') covid_india_df['Date'].dtype # In[5]: #Since we have data for indiviudal states, let's combine them on a day basis confirmed_cases_cumulative = covid_india_df.groupby('Date').sum() #Set dates as index as that will be our x-axis always covid_india_df = covid_india_df.set_index('Date') # In[6]: covid_india_df.head() # In[7]: #Also, our data has cases on a cumulative basis i.e new cases + existing active cases, but we need the new cases daily for our analysis. So let us modify that. # df['salary'] = df['salary'].diff().fillna(df['salary'].iloc[0]) #confirmed_cases_cumulative['Confirmed'] = confirmed_cases_cumulative['Confirmed'].diff().fillna(confirmed_cases_cumulative['Confirmed'].iloc[0]) confirmed_cases_cumulative['Confirmed'] = confirmed_cases_cumulative['Confirmed'].diff().fillna(0) # In[8]: confirmed_cases_cumulative['Confirmed'].describe() # In[9]: ax = plt.gca() #Fetching axis details formatter = mdates.DateFormatter("%m-%Y") ax.xaxis.set_major_formatter(formatter) #Setting formatter for x-axis, so that the plot looks clean locator = mdates.MonthLocator() #Setting locator to a month, so that we get a good plot ax.xaxis.set_major_locator(locator) plt.plot(confirmed_cases_cumulative['Confirmed']) plt.xticks(rotation=90) #rotating the x-axis tick values by 90 to make it vertical plt.xlabel('Date') plt.ylabel('Daily New Cases') plt.title('New Covid Cases on a daily basis') # #As per the above chart, we can conclude that the Covid Case first peaked around mid September, and then in mid June # # # # Analysis of NSE Index Data # # In[10]: nse_df1 = pd.read_csv('/Users/parveenkumar/Desktop/stock market vs covid 19/data.csv') nse_df2 = pd.read_csv('/Users/parveenkumar/Desktop/stock market vs covid 19/data2.csv') # In[11]: nse_df=pd.concat([nse_df1,nse_df2]) # In[12]: nse_df.describe() nse_df.head() # In[13]: nse_df['Date'] = pd.to_datetime(nse_df['Date']) # In[14]: nse_df = nse_df.set_index('Date') #It is important to assign the output to a dataframe, as it always returns a new dataframe, or use inPlace=True # In[15]: nse_df # In[16]: ax = plt.gca() #Fetching axis details formatter = mdates.DateFormatter("%m-%Y") ax.xaxis.set_major_formatter(formatter) locator = mdates.MonthLocator() #Setting locator to a month, so that we get a good plot ax.xaxis.set_major_locator(locator) plt.plot(nse_df['Close']) plt.xticks(rotation=90) plt.xlabel('Date') plt.ylabel('Closing Value') plt.title('NSE Index Price') # #### It seems that the index falled from 12000 to below 8000 from February to mid March, and then bounced back to around 16000 in July 2020 # # # # ### Q1: What is the effect of covid cases on stock market? # # Let us now merge the two dataframe based on indexes. By default, it'll try to merge using index if the index name is same, and since we have same date index in both our dataframes, it will merge without any issue. Or else, we can also set left_index and right_index values to True to merge on indexes # # # # In[17]: merged_df = confirmed_cases_cumulative.merge(nse_df, left_index=True, right_index=True) # In[18]: merged_df.head() # In[19]: ax = plt.gca() formatter = mdates.DateFormatter("%m-%Y") ax.xaxis.set_major_formatter(formatter) locator = mdates.MonthLocator() ax.xaxis.set_major_locator(locator) plt.plot(merged_df['Close']) plt.xticks(rotation=90) plt.plot(merged_df['Confirmed']) plt.xlabel('Date') # This looks a bit strange, isn't it? That is because, our values of the two dataframes are very different in nature. For covid data, our value ranges from 0 to 414188, where as our nse data ranges from 7600 to 15890. Hence we need to bring both the data to the same scale in order to see the impact of covid on the index value. For that, let us use MinMaxScaler, a library from scikit-learn. # In[20]: min_max_scaler = preprocessing.MinMaxScaler() # In[21]: merged_df[["Confirmed", "Close"]] = min_max_scaler.fit_transform(merged_df[["Confirmed", "Close"]]) # In[22]: ax = plt.gca() formatter = mdates.DateFormatter("%m-%Y") ax.xaxis.set_major_formatter(formatter) locator = mdates.MonthLocator() ax.xaxis.set_major_locator(locator) plt.plot(merged_df['Close']) plt.xticks(rotation=90) plt.plot(merged_df['Confirmed']) plt.legend(['Close Price','Confirmed Cases']) plt.xlabel('Date') # Inference 1 - The stock market dipped when Covid-19 began in India. There are other various dips during the month on May and June. The market went down again after recovering after mid-september when the covid cases peaked. After that, overall market has been growing to higher levels excluding one fall in february 2021 and then a sluggish period from there till June as covid cases kept increasing. Overall, we can see that there is a relation between covid cases and stock market. During both the covid peaks, the market falled. We cannot conclude the reason as covid for other dips mainly in February 2021 and May 2020. # ### Q2: What is the effect of lockdowns on stock market? # # In[23]: lockdown_dates = pd.to_datetime(['2020-01-30','2020-02-04','2020-03-03','2020-03-10','2020-03-22','2020-03-25','2020-04-14','2020-05-01','2020-05-18'], format='%Y-%m-%d') lockdown_events = ['First Covid Case', 'Foreign Visa Cancelled', 'Narendra Modi tweeted','First 50 cases', 'Janta Curfew','Lockdown 1','Lockdown 2','Lockdown 3','Lockdown 4'] # In[25]: ax = plt.gca() formatter = mdates.DateFormatter("%m-%Y") ax.xaxis.set_major_formatter(formatter) locator = mdates.MonthLocator() ax.xaxis.set_major_locator(locator) plt.xlabel('Date') # plt.plot(merged_df['Close'][:'2020-12-31']) # plt.plot(merged_df['Confirmed'][:'2020-12-31']) plt.plot(merged_df['Close']) plt.xticks(rotation=90) plt.plot(merged_df['Confirmed']) plt.legend(['Close Price','Confirmed Cases']) for date, event in zip(lockdown_dates, lockdown_events): plt.axvline(date ,color = 'r', alpha = 0.5) plt.text(date, 0.4, event, rotation = 90, alpha =0.5) # Inference 2 - We can see that after each lockdown announcement, there is a small dip in the market, but soon the market recovered from that point. We can also observe, that the major fall was after the tweet and first 50 cases were detected in India. Although, a tweet and first 50 cases does not seem to be that of a negative news, which can bring a fall of almost 40%. Two factors which i can think of is, global activity stopped during that time as other countries were in lockdown and future lockdown expectations # ### Q3: What is the effect of removing lockdown restrictions on stock market? # # In[26]: reopening_dates = pd.to_datetime(['2020-06-08','2020-07-01','2020-08-01','2020-09-01','2020-10-01','2020-11-01'], format='%Y-%m-%d') reopening_events = ['Unlock 1', 'Unlock 2', 'Unlock 3', 'Unlock 4', 'Unlock 5', 'Unlock 6'] # In[27]: ax = plt.gca() formatter = mdates.DateFormatter("%m-%Y") ax.xaxis.set_major_formatter(formatter) locator = mdates.MonthLocator() ax.xaxis.set_major_locator(locator) plt.xlabel('Date') # plt.plot(merged_df['Close'][:'2020-12-31']) # plt.plot(merged_df['Confirmed'][:'2020-12-31']) plt.plot(merged_df['Close']) plt.xticks(rotation=90) plt.plot(merged_df['Confirmed']) plt.legend(['Close Price','Confirmed Cases']) for date, event in zip(lockdown_dates, lockdown_events): plt.axvline(date ,color = 'r', alpha = 0.5) plt.text(date, 0.4, event, rotation = 90, alpha =0.5) for date, event in zip(reopening_dates, reopening_events): plt.axvline(date ,color = 'g', alpha = 0.5) plt.text(date, 0.4, event, rotation = 90, alpha = 0.5) # Inference 3 - After every unlock, there is a rise seen in the index value, except unlock 1 and unlock 4. In unlock 1, the market recovered soon after a dip and rose to better levels overall. After unlock 4, the market went up, but it fell down soon. The reason for this could be the first covid peak level that was reached during the same period. # ### Q4: What is the effect of vaccination on stock market? # # In[37]: vaccination_df = pd.read_csv('/Users/parveenkumar/Desktop/stock market vs covid 19/covid_vaccine_statewise.csv') vaccination_df.State.unique() # #### This data has India + other states data, let us check if the values match or not # Let us first format the date to a common format using pd.to_datetime() # In[38]: vaccination_df['Updated On'] = pd.to_datetime(vaccination_df['Updated On'], format='%d/%m/%Y') vaccination_df.head() # In[39]: #Also, our data has cases on a cumulative basis i.e new cases + existing active cases, but we need the new cases daily for our analysis. So let us modify that. vaccination_df['Total Individuals Vaccinated'] = vaccination_df['Total Individuals Vaccinated'].diff().fillna(0) # In[40]: #This stores data where state=India country_vaccination_df = vaccination_df[vaccination_df['State']=='India'][['State','Total Individuals Vaccinated']] country_vaccination_df.describe() # In[41]: #Updating the main df to exclude fields that has state = India vaccination_df = vaccination_df[vaccination_df['State']!='India'] vaccination_df.State.unique() # In[42]: #Let us add all the doses administered in various states to calculate the total doses administered on a single day. vaccination_df = vaccination_df.groupby('Updated On').sum() vaccination_df['Total Individuals Vaccinated'].describe() # In[43]: ax = plt.gca() formatter = mdates.DateFormatter("%d-%m-%Y") ax.xaxis.set_major_formatter(formatter) locator = mdates.DayLocator(interval = 15) ax.xaxis.set_major_locator(locator) plt.xticks(rotation=90) plt.plot(vaccination_df['Total Individuals Vaccinated']) plt.xlabel('Date') plt.xlabel('Total Individuals Vaccinated') # In[51]: #Now to plot it against the previous charts that had NSE index and Covid Cases data, we need to scale the values of Total Doses Adminstered to 0-1 vaccination_df[['Total Individuals Vaccinated']] = min_max_scaler.fit_transform(vaccination_df[['Total Individuals Vaccinated']]) # In[57]: ax = plt.gca() formatter = mdates.DateFormatter("%m-%Y") ax.xaxis.set_major_formatter(formatter) locator = mdates.MonthLocator() ax.xaxis.set_major_locator(locator) plt.xlabel('Date') plt.xticks(rotation=90) # plt.plot(merged_df['Close'][:'2020-12-31']) # plt.plot(merged_df['Confirmed'][:'2020-12-31']) plt.plot(merged_df['Close']) plt.plot(merged_df['Confirmed']) plt.plot(vaccination_df['Total Individuals Vaccinated'][:172]) plt.legend(['Close Price','Confirmed Cases','Total Individuals Vaccinated']) for date, event in zip(lockdown_dates, lockdown_events): plt.axvline(date ,color = 'r', alpha = 0.5) plt.text(date, 0.4, event, rotation = 90, alpha =0.5) for date, event in zip(reopening_dates, reopening_events): plt.axvline(date ,color = 'g', alpha = 0.5) plt.text(date, 0.4, event, rotation = 90, alpha = 0.5) # Inference 4 - In the initial stages of vaccination, the market rose to higher levels. But after that, even though the vaccinations were increasing on a daily basis, the market kept going down, probably because of the rise in covid cases. After the second covid peak, the vaccination count kept increasing and market also recovered with 2 positive news, i.e decreasing covid cases and increasing vaccination. Overall, vaccination number does not seem to be affecting the market much when compared to covid cases. # # References and Future Work # We can use other information like GDP growth, repo rates and information around curfews that were in place during second peak which again slowed down the economy.
e00801a735a5d5223ade8b90e2a47131b4fdf7a6
zhanghuaisheng/mylearn
/Python基础/day010/02 昨日回顾.py
1,038
3.5
4
# 1.函数的初始 # 函数的作用,封装代码,大量减少重复代码,提重用性 # 函数的定义: # def 函数名(): #函数体 # 函数名:遵循变量命名规则 # 函数调用 func() # 作用:调用函数+接收返回值 # return # 将返回值返回给函数调用者 # 函数执行完后自动销毁函数体中开辟的空间 # 终止当前函数,return下方代码不执行 # 不写return默认返回None,写return不写返回值也是None # 可以返回任意、多个数据类型(以元组的形式存储) # 可以写多个return ,只执行一个 # 函数体中存放的是代码,只有函数被调用时,函数体中的代码才会被执行 # 函数的参数 # 形参:函数定义阶段的参数 # 位置参数:必须一一对应 # 默认参数:可传(覆盖默认值)可不传(使用默认值) # 位置参数 > 默认参数 # 实参:函数调用阶段的参数 # 位置参数:必须一一对应 # 关键字参数:指定关键字传参 # 位置参数 > 关键字参数
a21d794823409b59053330696bf8bbde696eb947
Aqoolare/Python
/lesson9/test_rectangle.py
1,473
3.609375
4
import sys sys.path.append('../Lessons/lesson8') import task2 class TestRectangle: def test_rectangle_area(self): r = task2.Rectangle(2, 3) assert r.area() == 6 def test_rectangle_print_with_negative_parameters(self): assert str(task2.Rectangle(-2, -3)) == 'Прямоугольник: (2, 3)' def test_rectangle_perimeter(self): r = task2.Rectangle(2, 3) assert r.perimeter() == 10 r1 = task2.Rectangle(1, 2) r2 = task2.Rectangle(3, 3) def test_eq(self): assert (self.r1 == self.r2) == False def test_eq(self): assert (self.r1 == self.r2) == False def test_lt(self): assert (self.r1 < self.r2) == True def test_le(self): assert (self.r1 <= self.r2) == True def test_ne(self): assert (self.r1 != self.r2) == True def test_gt(self): assert (self.r1 > self.r2) == False def test_ge(self): assert (self.r1 >= self.r2) == False def test_add(self): assert str(self.r1 + self.r2) == 'Прямоугольник: (4, 5)' def test_sub(self): assert str(self.r1 - self.r2) == 'Прямоугольник: (0, 0)' def test_iadd(self): self.r1 += self.r2 assert str(self.r1) == 'Прямоугольник: (4, 5)' def test_isub(self): self.r2 = task2.Rectangle(10, 10) self.r1 -= self.r2 assert str(self.r1) == 'Прямоугольник: (0, 0)'
38cdcac8fc8f8062630c62fa954a27d6d90eba8d
KosmX/quiz-to-moodle.xml
/quester.py
5,364
3.5
4
def formatQuestion(quest, answers, answer): #quest:description of the question, answers: string containing answers, answer:string containing the answer letter e.g. "D" return ''' <question type="multichoice"> <name> <text>{}</text> </name> <questiontext format="html"> <text><![CDATA[{}]]></text> </questiontext> <shuffleanswers>true</shuffleanswers> <answernumbering>none</answernumbering> {} </question> '''.format(quest.split('\n')[0], '&nbsp;'.join('&emsp;'.join('<br>'.join(quest.split('\n')).split('\t')).split(' ')), answers)[1:] #remove first \n #asd #will run on every answer, answer:answer text, isCorrect: is this the correct answer def formatAnswer(answer, isCorrect): #answer if isCorrect: a = '100' else: a = '0' return ''' <answer fraction="{}"> <text>{}</text> </answer>'''.format(a, answer)[1:] #asd def save(filename, l): x = open(filename, mode='w', encoding='utf-8') x.write('''<?xml version="1.0" ?> <quiz> {} </quiz>'''.format(''.join(l))) x.close() def isNumber(c): return(c == '0' or c == '1' or c == '2' or c == '3' or c == '4' or c == '5' or c == '6' or c == '7' or c == '8' or c == '9') def isNumEnd(text, i): return(text[i] == '.' and (text[i+1] == '\t' or text[i+1] == ' ')) def isNewQuestion(text, i, q): if (text[i] == '\n' and i+4 < len(text)): try: if(q < 10): if(int(text[i+1]) == q and isNumEnd(text, i+2)): return(4) else: if(int(text[i+1:i+3]) == q and isNumEnd(text, i+3)): return(5) except: return(0) return(0) def isAnswerLetter(l): return(l == 'A' or l == 'B' or l == 'C' or l == 'D') #def isAnswerNext(item, i): class AnswerLetterCounter: def __init__(self): self.letter = "D" def next(self): if (self.letter == "D"): self.letter = 'C' return(True) elif (self.letter == 'C'): self.letter = 'B' return(True) elif (self.letter == 'B'): self.letter = 'A' return(True) else: return(False) def __str__(self): return('({})'.format(self.letter)) def get(self): return(self.letter) def isAnswer(self, item, i): if(item[i-3: i] == str(self)): #print(item[i]) i -= 4 while (item[i] == ' ' or item[i] == '\t'): i -= 1 return(item[i] == '\n') return(False) def processItem(item): i = len(item)-1 answer = 'X' while(i != 0 and not isAnswerLetter(item[i])): i -= 1 if (isAnswerLetter(item[i])): answer = item[i] i -= 1 answerLetter = AnswerLetterCounter() answers = [] while True: while(item[i] == ' ' or item[i] == '\n' or item[i] == '\t'): #print('debug: ' + item[i]) i -= 1 answerEnd = i + 1 while not(answerLetter.isAnswer(item, i)): if item[i] == '\n': item = '{} {}'.format(item[:i], item[i+1]) i -= 1 if answerLetter.get() == "X": print('WARNING, cannot find correct answer:\n{}'.format(item)) answers = [formatAnswer(item[i+1:answerEnd], answerLetter.get() == answer)] + answers #answers = ['{}. {}'.format(answerLetter.get(), item[i+1:answerEnd])] + answers i -= 4 if not answerLetter.next(): break while (item[i] == ' ' or item[i] == '\t' or item[i] == '\n'): i -= 1 return(formatQuestion(item[:i+1], '\n'.join(answers), answer)) #return('{}\n\n{}\nANSWER: {}'.format(item[:i+1], '\n'.join(answers), answer)) def process(text): text = '\n' + text while text[1] == '\n': text = text[1:] l = [] currentItem = '' step = 0 q = 1 while step < len(text): if(bool(isNewQuestion(text, step, q))): if (len(currentItem) != 0): l = l + [processItem(currentItem)] currentItem = '' step += isNewQuestion(text, step, q) q += 1 else: currentItem = currentItem + text[step] step += 1 l = l + [processItem(currentItem)] return l def printl(): #just a debug method print('\n--------------------------------\n'.join(l)) def openfile(filename): x = open(filename ,mode = "r", encoding = 'utf-8') text = x.read() x.close() return text if __name__ == "__main__": sc = True while sc: try: x = open(input("UTF-8 encoded file name with extension e.g. quests.txt\n"), mode = 'r', encoding = 'utf-8') t = x.read() x.close() sc = False except: print('wrong filename or encoding') l = process(t) sc = True while sc: try: save(input('export file name e.g. quests.xml\nWARNING, this file will be owerwrited\n'), l) sc = False except: print('unexcepted error')
6f6f0acb87547dff21e7f45cb2e2ddded9892585
khw5123/Algorithm
/SWExpert/2058. 자릿수 더하기.py
66
3.5
4
answer = 0 for n in input(): answer += int(n) print(answer)
6f231efd3f92e97497d47d7e70a5a2f3ee65622d
Jackson201325/Python
/Python Crash Course/Chapter 8 Functions/8-9 Magicians.py
295
3.921875
4
def show_magician(): magician_list = [] while True: magician = input("Name of the magician: ") if magician == 'q': break else: magician_list.append(magician) for magicians in magician_list: print(magicians) show_magician()
44656d1cd01720b7cd60be69c9e7573e65262fdf
vivangkumar/project-euler
/problem4.py
561
4.3125
4
__author__ = 'vivan' ''' A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99. Find the largest palindrome made from the product of two 3-digit numbers. ''' def largest_palindrome(): palindrome = [] for x in range(100, 999): for y in range(100, 999): number = x * y reverse = str(number)[::-1] if str(number) == reverse: palindrome.append(number) return max(palindrome) print largest_palindrome()
10f5e521f7422b87628153e887c1595f76f0e438
BermondSmoothStack/python-exercise
/daytwo/main.py
2,020
3.515625
4
import string def trim_hello_world(): return "Hello World"[8] def slice_string(): return "thinker"[2:5] def sammy(): return "Sammy"[2:] def to_set(): return set("Mississippi") def palindrome(inputs): response = list() for str_input in inputs: str_input = ''.join(c for c in str_input if c not in string.punctuation).lower() result = 'Y' if (str_input == str_input[::-1]) else 'N' response.append(result) return response def my_list(): return [1, "my word", 0.5] def my_nested_list(): return [2, my_list()] def list_slice(): return ['a', 'b', 'c'][1:] def dict_week(): my_dict = { "monday": 1, "tuesday": 2, "wednesday": 3, "thursday": 4, "friday": 5, "saturday": 6, "sunday": 7, } return my_dict def list_in_dict(): D = { 'k1': [1, 2, 3] } return D def add_to_set(): my_set = to_set() my_set.add("X") return my_set def dup_in_set(): return set([1, 1, 2, 3]) def div_by_7_not_5(): my_set = set() for num in range(2000, 3200): if num % 5 == 0: continue if num % 7 == 0: my_set.add(num) return my_set def get_factorial(num): if num == 0: return 1 return num * get_factorial(num - 1) def my_factorials(nums): result = list() for num in nums: result.append(get_factorial(num)) return result def my_integrals(num): return {i: i ** 2 for i in range(1, num + 1)} if __name__ == "__main__": print(trim_hello_world()) print(slice_string()) print(sammy()) print(to_set()) print(palindrome({"tacoca't", "tacocan't"})) print(my_list()) print(my_nested_list()) print(list_slice()) print(dict_week()) print(list_in_dict()['k1'][1]) print(to_set().add("X")) print(add_to_set()) print(dup_in_set()) print(div_by_7_not_5()) print(my_factorials({8, 7, 6})) print(my_integrals(8))
0cc813ed5b7991c3079b41ad302914956201a832
megalphian/Uncertainity-Based-POMDP-Planner
/Simulator/pomdp_control.py
13,784
3.625
4
import numpy as np class BeliefDynamicsData: """ Data class to store the Belief Dynamics Data linearized about the optimal trajectory """ def __init__(self): self.F = list() self.Fi_1 = list() self.Fi_2 = list() self.G = list() self.Gi_1 = list() self.Gi_2 = list() self.ei_1 = list() self.ei_2 = list() class QuadratizedValueData: """ Data class to store the quadratized value functions required to compute cost and calculate a new path """ def __init__(self): self.L = list() self.l = list() class iLQGController: """ The Controller for the iLQG problem of minimizing the cost of accruing uncertainity along an inital optimal trajectory. This class computes the linearized belief dynamics for a given trajectory, obtains the matrices to compute the quadratized value function using the dynamics and creates a new path using the gradients computed for the value function. """ def __init__(self, environment, steps, cost_config, estimator): self.environment = environment self.estimator = estimator terminal_cost_multiplier = cost_config.terminal_cost_multiplier stage_cost_multiplier = cost_config.stage_cost_multiplier # Initialize the matrices to compute the stage and terminal costs for the LQG problem. self.Q_t = stage_cost_multiplier * np.identity(6) self.R_t = stage_cost_multiplier * np.identity(2) self.Q_l = terminal_cost_multiplier * steps * np.identity(6) # Symmetric step size for numerical differentiation self.h = 0.1 def calculate_linearized_belief_dynamics(self, beliefs, inputs): # Linearize belief dynamics by calculating the gradients of the system dynamics wrt to changes in # the belief and input at each point of the trajectory linearized_dynamics = BeliefDynamicsData() for i in range(len(inputs)): belief = beliefs[i] input_i = inputs[i] Ft, Fit_1, Fit_2 = self._calculate_belief_gradients(belief, input_i, i) Gt, Git_1, Git_2 = self._calculate_input_gradients(belief, input_i, i) linearized_dynamics.F.append(Ft) linearized_dynamics.Fi_1.append(Fit_1) linearized_dynamics.Fi_2.append(Fit_2) linearized_dynamics.G.append(Gt) linearized_dynamics.Gi_1.append(Git_1) linearized_dynamics.Gi_2.append(Git_2) linearized_dynamics.ei_1.append(self.estimator.W1[i].reshape((6,1))) linearized_dynamics.ei_2.append(self.estimator.W2[i].reshape((6,1))) return linearized_dynamics def calculate_value_matrices(self, belief_dynamics, beliefs, inputs): # Calculate the quadratized value function matrix and gradient vector for the terminal belief # This uses the linearized belief dynamics along the optimal trajectory valueData = QuadratizedValueData() S_tplus1 = self.Q_l belief_l = beliefs[-1] s_tplus1_vec = self._calculate_terminal_cost_gradient(belief_l) for t in reversed(range(len(inputs))): belief = beliefs[t] input_i = inputs[t] # Calculate Dt D_t = self.R_t + (np.transpose(belief_dynamics.G[t]) @ S_tplus1 @ belief_dynamics.G[t]) + (np.transpose(belief_dynamics.Gi_1[t]) @ S_tplus1 @ belief_dynamics.Gi_1[t]) + (np.transpose(belief_dynamics.Gi_2[t]) @ S_tplus1 @ belief_dynamics.Gi_2[t]) r_t = self._calculate_gradient_input_stage_cost(belief, input_i) # Calculate d_t (gradient of value wrt input) d_t = r_t + (np.transpose(belief_dynamics.G[t]) @ s_tplus1_vec) # Ignoring Gi as it is just 0 # Calculate Et E_t = (np.transpose(belief_dynamics.G[t]) @ S_tplus1 @ belief_dynamics.F[t]) + (np.transpose(belief_dynamics.Gi_1[t]) @ S_tplus1 @ belief_dynamics.Fi_1[t]) + (np.transpose(belief_dynamics.Gi_2[t]) @ S_tplus1 @ belief_dynamics.Fi_2[t]) # Calculate L_t and l_t (value wrt input and belief) L_t = - (np.linalg.inv(D_t) @ E_t) valueData.L.insert(0, L_t) l_t = - (np.linalg.inv(D_t) @ d_t) valueData.l.insert(0, l_t) q_t = self._calculate_gradient_belief_stage_cost(belief, input_i) # Calculate Ct and c_t (value wrt belief changes) C_t = self.Q_t + (np.transpose(belief_dynamics.F[t]) @ S_tplus1 @ belief_dynamics.F[t]) + (np.transpose(belief_dynamics.Fi_1[t]) @ S_tplus1 @ belief_dynamics.Fi_1[t]) + (np.transpose(belief_dynamics.Fi_2[t]) @ S_tplus1 @ belief_dynamics.Fi_2[t]) c_t = q_t + (np.transpose(belief_dynamics.F[t]) @ s_tplus1_vec) + (np.transpose(belief_dynamics.Fi_1[t]) @ S_tplus1 @ belief_dynamics.ei_1[t]) + (np.transpose(belief_dynamics.Fi_2[t]) @ S_tplus1 @ belief_dynamics.ei_2[t]) # Calculate quadratized value matrix and gradient for the next iteration S_t = C_t - (np.transpose(E_t) @ (np.linalg.inv(D_t) @ E_t)) s_tplus1_vec = c_t - (np.transpose(E_t) @ (np.linalg.inv(D_t) @ d_t)) S_tplus1 = S_t return valueData def calculate_trajectory_cost(self, beliefs, inputs, belief_dynamics, valueData, goal): # Given a trajectory (beliefs and inputs) and its belief dynamics and value matrices, calculate the expected cost of # the trajectory. The cost is given by the stage costs at each time step and the terminal cost of reaching the goal. # Calculate terminal cost S_tplus1 = self.Q_l terminal_belief = beliefs[-1] s_tplus1 = self._calculate_terminal_cost(terminal_belief, goal) for i in reversed(range(len(inputs))): belief = beliefs[i] input_i = inputs[i] cost = self._calculate_stage_cost(belief, input_i) ei_1 = belief_dynamics.ei_1[i] ei_2 = belief_dynamics.ei_2[i] # Calculate stage cost and update the expected cost value matrix stage_addition = np.real((cost + ((1/2) * ((np.transpose(ei_1) @ S_tplus1 @ ei_1) + (np.transpose(ei_2) @ S_tplus1 @ ei_2)))))[0][0] s_tplus1 += stage_addition L_t = valueData.L[i] mat_1 = (belief_dynamics.F[i] + (belief_dynamics.G[i] @ L_t)) mat_2 = (belief_dynamics.Fi_1[i] + (belief_dynamics.Gi_1[i] @ L_t)) mat_3 = (belief_dynamics.Fi_2[i] + (belief_dynamics.Gi_2[i] @ L_t)) S_tplus1 = self.Q_t + (np.transpose(L_t) @ self.R_t @ L_t) + (np.transpose(mat_1) @ S_tplus1 @ mat_1) + (np.transpose(mat_2) @ S_tplus1 @ mat_2) + (np.transpose(mat_3) @ S_tplus1 @ mat_3) return np.real(s_tplus1) def get_new_path(self, beliefs, old_u, step_size, valueData): # Given a trajectory (beliefs and inputs) and the value gradients computed at each stage, compute a new path that can # minimize the uncertainity along the path. This is done be applying gradient descent. # The step size is an input to this method! new_u = list() new_path = list() new_path.append(beliefs[0]) cur_belief = beliefs[0] for i in range(len(old_u)): u_bar = old_u[i] b_bar = beliefs[i] C = self.estimator.C[i] A = self.estimator.A[i] M = self.estimator.M[i] x = cur_belief[0:2].reshape((2,1)) cov = cur_belief[2:] cov = cov.reshape((2,2)) measurement, N = self.environment.get_measurement(x.flatten()) new_u_val = u_bar + ((valueData.L[i] @ (cur_belief - b_bar)) + (step_size * valueData.l[i])) new_u.append(new_u_val) new_b, _, _, _, _, _ = self.estimator.apply_dynamics_and_estimate_tplus1(A, C, M, N, cov, x, measurement, new_u_val) new_path.append(new_b) cur_belief = new_b new_path = np.real(new_path) new_u = np.real(new_u) return [new_path, new_u] """ Private Functions """ def _calculate_terminal_cost(self, terminal_belief, goal): # Calculate terminal cost using the terminal belief of a given path and the intended goal ideal_end_belief = np.zeros((6,1)) ideal_end_belief[0] = goal[0] ideal_end_belief[1] = goal[1] belief_diff = terminal_belief - ideal_end_belief cost = (np.transpose(belief_diff) @ self.Q_l @ belief_diff) return cost[0][0] def _calculate_stage_cost(self, belief, input_i): # Calculate stage cost using a given belief in a path and the input at that time step cov = belief[2:] trace = (np.transpose(cov) @ cov) # Ignoring Q_t as it is identity cost = trace + (np.transpose(input_i) @ self.R_t @ input_i) return cost[0][0] def _calculate_gradient_input_stage_cost(self, belief, input_i): # Calculate gradient of the stage cost wrt the input effort h = self.h r_t = [] for j in range(len(input_i)): input_1 = input_i.copy() input_2 = input_i.copy() input_1[j] += h input_2[j] -= h cost_1 = self._calculate_stage_cost(belief, input_1) cost_2 = self._calculate_stage_cost(belief, input_2) cost_diff = (cost_1 - cost_2) / (2*h) r_t.append(cost_diff) r_t = np.hstack(r_t).reshape((len(input_i),1)) return r_t def _calculate_gradient_belief_stage_cost(self, belief, input_i): # Calculate gradient of the stage cost wrt the belief of the robot h = self.h q_t = [] for j in range(len(belief)): belief_1 = belief.copy() belief_2 = belief.copy() belief_1[j] += h belief_2[j] -= h cost_1 = self._calculate_stage_cost(belief_1, input_i) cost_2 = self._calculate_stage_cost(belief_2, input_i) cost_diff = (cost_1 - cost_2) / (2*h) q_t.append(cost_diff) q_t = np.hstack(q_t).reshape((len(belief),1)) return q_t def _calculate_terminal_cost_gradient(self, belief_l): # Calculate gradient of the terminal cost at the last belief state h = self.h s_tplus1_vec = [] for j in range(len(belief_l)): b_1 = belief_l.copy() b_2 = belief_l.copy() b_1[j] += h b_2[j] -= h c1 = self._calculate_terminal_cost(b_1, belief_l) c2 = self._calculate_terminal_cost(b_2, belief_l) c_diff = (c1 - c2) / (2*h) s_tplus1_vec.append(c_diff) s_tplus1_vec = np.vstack(s_tplus1_vec) return s_tplus1_vec def _calculate_belief_gradients(self, belief, input_i, i): # Calculate gradient of the belief dynamics wrt changes to the beliefs at a given time step h = self.h C = self.estimator.C[i] A = self.estimator.A[i] M = self.estimator.M[i] Ft = [] Fit_1 = [] Fit_2 = [] for j in range(len(belief)): b_1 = belief.copy() b_2 = belief.copy() b_1[j] += h b_2[j] -= h x_1 = b_1[0:2].reshape((2,1)) cov_1 = b_1[2:] cov_1 = cov_1.reshape((2,2)) x_2 = b_2[0:2].reshape((2,1)) cov_2 = b_2[2:] cov_2 = cov_2.reshape((2,2)) measurement_1, N_1 = self.environment.get_measurement(x_1.flatten()) measurement_2, N_2 = self.environment.get_measurement(x_2.flatten()) g_1, w1_1, w1_2, _, _, _ = self.estimator.apply_dynamics_and_estimate_tplus1(A, C, M, N_1, cov_1, x_1, measurement_1, input_i) g_2, w2_1, w2_2, _, _, _ = self.estimator.apply_dynamics_and_estimate_tplus1(A, C, M, N_2, cov_2, x_2, measurement_2, input_i) g_diff = (g_1 - g_2) / (2*h) w1_diff = (w1_1 - w2_1) / (2*h) w2_diff = (w1_2 - w2_2) / (2*h) Fit_1.append(w1_diff) Fit_2.append(w2_diff) Ft.append(g_diff) Ft = np.hstack(Ft) Fit_1 = np.hstack(Fit_1) Fit_2 = np.hstack(Fit_2) return (Ft, Fit_1, Fit_2) def _calculate_input_gradients(self, belief, input_i, i): # Calculate gradient of the belief dynamics wrt changes to the inputs at a given time step h = self.h C = self.estimator.C[i] A = self.estimator.A[i] M = self.estimator.M[i] Gt = [] Git_1 = [] Git_2 = [] for j in range(len(input_i)): input_1 = input_i.copy() input_2 = input_i.copy() input_1[j] += h input_2[j] -= h x = belief[0:2].reshape((2,1)) cov = belief[2:] cov = cov.reshape((2,2)) measurement, N = self.environment.get_measurement(x.flatten()) g_1, w1_1, w1_2, _, _, _ = self.estimator.apply_dynamics_and_estimate_tplus1(A, C, M, N, cov, x, measurement, input_1) g_2, w2_1, w2_2, _, _, _= self.estimator.apply_dynamics_and_estimate_tplus1(A, C, M, N, cov, x, measurement, input_2) g_diff = (g_1 - g_2) / (2*h) w1_diff = (w1_1 - w2_1) / (2*h) w2_diff = (w1_2 - w2_2) / (2*h) Git_1.append(w1_diff) Git_2.append(w2_diff) Gt.append(g_diff) Gt = np.hstack(Gt) Git_1 = np.hstack(Git_1) Git_2 = np.hstack(Git_2) return (Gt, Git_1, Git_2)
e119214e28f7bcbb0d98506c99c76340c88ac6ef
HuangJing0/Data-Structure-and-Algorithm
/SelectionSort.py
234
3.6875
4
#!/usr/bin/env python3 -*- coding: UTF-8 -*- class SelectionSort: def selectionSort(self, A, n): for i in range(0, n-1): for j in range(i+1, n): if A[j] < A[i]: temp = A[j] A[j] = A[i] A[i] = temp return A
fe4ed3d9ef4322d87d150b9d9228ac329b4a3b67
1642195610/backup_data
/old-zgd/汉明重量(位1的个数).py
978
3.8125
4
# 191.位1的个数 # 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。 # # # # 示例1: # # 输入:00000000000000000000000000001011 # 输出:3 # 解释:输入的二进制串 # 00000000000000000000000000001011中,共有三位为'1'。 # 示例2: # # 输入:00000000000000000000000010000000 # 输出:1 # 解释:输入的二进制串 # 00000000000000000000000010000000中,共有一位为'1'。 # 示例3: # # 输入:11111111111111111111111111111101 # 输出:31 # 解释:输入的二进制串 # 11111111111111111111111111111101中,共有31位为'1'。 class Solution: def hammingWeight(self, n: int) -> int: t = 0 while n != 0: n = n & (n - 1) t += 1 return t if __name__ == '__main__': j = Solution() c = 11 # 二进制转成十进制的数字 a = j.hammingWeight(c) print(a)
5968c8db1baeafc133a5f7751a7e72c69c612bc0
Jatinmotwani-195/pyprograms
/array reverse.py
92
3.859375
4
from array import * arr=array("i",[10,11,12,13,14]) arr.reverse() for a in arr: print(a)
5fddd6fbef902ee95c0a59e086706c5f4d05f8e0
ChangxingJiang/LeetCode
/LCCI_程序员面试金典/面试17.12/面试17.12_Python_1.py
805
3.53125
4
from LeetTool import TreeNode from LeetTool import build_TreeNode class Solution: def convertBiNode(self, root: TreeNode, bigger=None) -> TreeNode: if root: # 处理当前节点 left, right = root.left, root.right root.left = None # 处理当前节点的右侧节点 if right: root.right = self.convertBiNode(right, bigger) else: root.right = bigger if left: return self.convertBiNode(left, root) else: return root if __name__ == "__main__": # [] print(Solution().convertBiNode(None)) # [0,None,1,None,2,None,3,None,4,None,5,None,6] print(Solution().convertBiNode(build_TreeNode([4, 2, 5, 1, 3, None, 6, 0])))
3929fbee9038fbb0764eb05b93a8e64e1f94d42a
vaishnavi2810-code/Regex
/regex_methods.py
180
3.53125
4
import re pattern=r"pam" match=re.search(pattern,"eggsspamsausagespam") if match: print(match.group()) print(match.start()) print(match.end()) print(match.span())
ee666cc786dfbcfc7136ad37110232a191ab0517
monty0157/Bank-Customer-ANN
/ann.py
771
3.75
4
import numpy as np import keras #IMPORT PREPROCESSED DATA from data_processing import data_preprocessing X_train, X_test, X, y, y_train, y_test = data_preprocessing() #BUILDING ANN MODEL from keras.models import Sequential from keras.layers import Dense model = Sequential() #TWO HIDDEN LAYERS AND OUTPUT LAYER model.add(Dense(units = 6, activation = 'relu', kernel_initializer='uniform', input_shape = (11,))) model.add(Dense(units = 6, activation = 'relu', kernel_initializer='uniform')) model.add(Dense(units = 1, activation = 'sigmoid', kernel_initializer='uniform')) #GRADIENT DESCENT model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) #DEPLOY ANN ON TRAINING SET model.fit(X_train, y_train, batch_size = 10, epochs = 100)
e78adda6d134be97ccee9774721efb6e7d9e5948
flamesapphire/python-programming
/lists.py
203
3.875
4
#lists players=[1,2,2,4,5,6] players.append(10) players[1:-3]=[10,10] y = players print y if players[1]is players[2]: print("yes") elif players[3]is players[4]: print ("no") else : print ("!")
ce520b2f6df69f9b741ea4d20283212d7e2e733a
Silocean/Codewars
/7ku_length_of_the_line_segment.py
566
4.25
4
''' Description: Find the length between 2 co-ordinates. The co-ordinates are made of integers between -20 and 20 and will be given in the form of a 2D array: (0,0) and (5,-7) would be [ [ 0 , 0 ] , [ 5, -7 ] ] The function must return the answer rounded to 2 decimal places in the form of a string. length_of_line([[0, 0], [5, -7]]) => "8.60" If the 2 given co-ordinates are the same, the returned length should be "0.00" ''' def length_of_line(array): import math return '%.2f' % (math.sqrt((array[1][0]-array[0][0])**2 + (array[1][1]-array[0][1])**2))
f5e9debd1ca21762a8784685a3a270ae411ce317
syedrafayhashmi/Web-Mobile-App-Development
/SMIT/Firebase DB/Firebase/public/file.py
113
3.671875
4
# a=10 # def foo(): # a=a+10 # foo() # print(a) # x = {10:'aa',11:'bb',12:'cc'} # for i in x: # print(i)
4f1493348b9e7fb79cac6daded121cdbba1c78a5
limetree-indigo/allForAlgolithmWithPython
/Part2 재귀 호출/05 최대공약수 구하기/p05-2-gcd.py
743
3.984375
4
# 최대공약수 구하기 # 입력: a, b # 출력: a와 b의 최대공약수 """ -유클리드 알고리즘 -수학자 유클리드가 발견한 초대공약수의 성질 1. a와 b의 최대굥약수는 'b'와 'a를 나눈 나머지'의 최대공약수와 같다. 즉, gcd(a, b) = gcd(b, a%b) 2. 어떤 수와 0의 최대 공약수는 자기 자신이다. 즉, gcd(n, 0) = n 예를 들면 gcd(60, 24) = gcd(24, 60%24) = gcd(24, 12) = gcd(12, 24%12) = gcd(12, 0) = 12 gcd(81, 27) = gcd(27, 81%27) = gcd(27, 0) = 27 """ def gcd(a,b): if b==0: # 종료 조건 return a return gcd(b, a % b) # 좀 더 작은 값으로 자기 자신을 호출 print(gcd(1, 5)) print(gcd(3, 6)) print(gcd(60, 24)) print(gcd(81, 27))
1e7f8c287b2414f6d4cd8cdb93e096d67d1bae84
wangquan-062/wq
/pythontest/day03-01.py
413
3.640625
4
#if/else #a = 16 # a = input("请输入一个年龄:") # a = int(a) # if a > 17: # print("成年人") # 缩进 # else: # print("未成年人") # 缩进 hege = [] buhege = [] grade = {"张三":58,"张四":90,"张五":88,"张六":59} for i in grade: if int(grade[i]) >= 60: hege.append(i) else: buhege.append(i) print(hege) print(buhege)
c52109ce3879dc1df4e27344a90a791df020952c
osomat123/LN379_Sampravah
/prediction.py
915
3.625
4
from datetime import datetime, timedelta def floodPredict(data, timestamp): # Converting Passed Objects into Arrays with key enumerate(data) enumerate(timestamp) h = 53 # Height of Dam in cm x, y, x2, n, xy = 0, 0, 0, 0, 0 d0 = timestamp[0] # Base Time ie of first Water Level Data for i in range(0, 50): level = data[i] # Manipulating variables used for calculation of reression n += 1 d1 = timestamp[i] t = d1 - d0 time = int(t.total_seconds()) y += level x += time x2 += time*time xy += time*level d = n*x2 - x*x c = (y*x2 - x*xy)/d m = (n*xy - x*y)/d # rem1 is the time after which water level will reach 100% FRL rem1 = int((h-c)/m - time) # rem2 is the time after which water level will reach 75% FRL rem2 = int((0.75*h-c)/m - time) return(level, rem1, rem2)
cea293dc384f10663f412e5b8ba1ea223ebd9d11
ashishvista/geeks
/leetcode/LRU Cache.py
2,050
3.734375
4
class Node: next = None prev = None def __init__(self, key, value): self.key = key self.value = value class LRUCache: def __init__(self, capacity: int): self.h = {} self.capacity = capacity self.front = None self.last = None def get(self, key: int) -> int: if key in self.h: node = self.h[key] self.deleteNode(node) self.putNodeAtFront(node) return node.value else: return -1 def printDeque(self): node = self.front while node: print("pp", node.value) node = node.next def put(self, key: int, value: int) -> None: if key in self.h: self.h[key].value = value node = self.h[key] self.deleteNode(node) self.putNodeAtFront(node) else: if len(self.h) == self.capacity: del self.h[self.last.key] self.deleteNode(self.last) node = Node(key, value) self.putNodeAtFront(node) self.h[key] = node def deleteNode(self, node): if self.front == node: if self.front.next is None: self.front = None self.last = None else: self.front = self.front.next self.front.prev = None elif self.last == node: tmp = self.last.prev tmp.next = None self.last = tmp else: tmp1 = node.prev tmp2 = node.next tmp1.next = tmp2 tmp2.prev = tmp1 node.prev = node.next = None def putNodeAtFront(self, node): if not self.front: self.last = self.front = node else: node.next = self.front self.front.prev = node self.front = node # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
76ba561a0721c8568c26c5dce8b19b469a9dc674
prava-d/Databases
/projectBplustree.py
2,905
3.59375
4
''' B+ Tree implementation ''' class BPlusNode: order = 3 def __init__(self, iL): self.isLeaf = iL self.parent = None self.keys = [] self.pointers = [None,None,None,None] self.nextNode = None self.nodeIdx = None self.numKeys = 0 def printKeys(self): for key in self.keys(): print("\n",key def splitIncludeMedian(self): #splitting the node when the node has the maximum number of keys. if numKeys = 3: medianIndex = 1 splitNode1 = BPlusNode(self.il) splitNode1.parent = self.parent splitNode1.keys = self.keys[0:1] splitNode2 = BPlusNode(self.il) splitNode1.parent = self.parent splitNode1.keys = self.keys[2] return splitNode1, splitNode2 def splitExcludeMedian(self): #splitting the node when the node has the maximum number of keys. if numKeys = 3: medianIndex = 1 splitNode1 = BPlusNode(self.il) splitNode1.parent = self.parent splitNode1.keys = self.keys[0] splitNode2 = BPlusNode(self.il) splitNode1.parent = self.parent splitNode1.keys = self.keys[2] return splitNode1, splitNode2 def add(self, inputval): if self.keys is None: self.keys.append(inputval) return #if the node is already full then the node has to be split to accomodate the key value that is being added. if len(self.keys) == self.order: leftNode, rightNode = self.split(self) if self.isLeaf: minOfRightNode = rightNode[0] parent = self.parent parent.add(minOfRightNode) else: if inputval > keys[2]: promote(keys[2]) else: promote(inputval) return index = 0 for key in self.keys: if index == self.numKeys - 1: self.keys.append(inputval) return if inputval > key: self.keys = self.keys[index:] + [key] + self.keys[:index] return index++ numKeys++ def promote(self, inputval): if self.parent: self.parent.add(inputval) return 1 else: return 0 #deal with this in the tree class class Tree: self.store = Storage() def __init__(self): self.root = BPlusNode(0) self.i0 = BPlusNode(1) self.i1 = BPlusNode(1) self.i2 = BPlusNode(1) self.root.nodeIdx = self.store.addNode(self.root) self.i0.nodeIdx = self.store.addNode(self.i0) self.i1.nodeIdx = self.store.addNode(self.i1) self.i2.nodeIdx = self.store.addNode(self.i2) self.i0.nextNode = self.i1 self.i1.nextNode = self.i2 def findPosForInsert(self,inputval): pass def create(self, inputval): pass def read(self, inputval): pass def update(self, inputval, newinputval): pass def delete(self, inputval): pass class Storage: self.data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] self.treeNodes = [] def __init__(self): pass def addNode(n): self.treeNodes.append(n) return len(treeNodes) - 1 root = Node(10) print(root)
5a3670c7faabdc8727852bcdee6afadc207cd332
fruitbox12/CS1260
/tworoots.py
266
4.1875
4
from math import sqrt a = int(input("Enter int for a: ")) b = int(input("Enter int for b: ")) c = int(input("Enter int for c: ")) addSQRT = (-b + sqrt(b**2 - 4*a*c))/(2*a) minusSQRT = (-b - sqrt(b**2 - 4*a*c))/(2*a) print(addSQRT) print(minusSQRT)
021d88158ad6cca189c16b2610f328c9015eb5ec
BinXu-UW/basic-pythoncode
/Xu_Final Exam/list.py
594
3.6875
4
import random def prim(): for n in range(2, 1000): for x in range(2, n): if n % x == 0: break; else: return True def get_list(): n=int(raw_input("Enter the range of the list:")) nums=[] for i in range(n): a=random.randint(1,1000) nums.append(a) return nums aa = get_list() for i in aa: if(i == 1): print i, "is 1"; elif((i%7==0 )or(i%11==0)or(i%13==0)): print i, "is the multiple of 7 or 11 or 13 " elif(prim() == True): print i ,"is prime"
869849c1654fc4e0818b84e550d13b65f7522e6d
1stthomas/ht7-py-util
/utils-01.py
762
4.125
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 11 16:20:46 2018 @author: 1stthomas """ def module_exists(module_name): """ Checks if the submitted Module is installed. This Function prints the Result of the check. Parameters ---------- module_name : The name of the module to be checked. Returns ------- is_installed : boolean True if the submitted module is installed Example ------- >>> module_exists("csv") true """ try: __import__(module_name) except ImportError: print("Module \"" + module_name + "\" is NOT installed") return False else: print("Module \"" + module_name + "\" is installed") return True module_exists("csv")
7b901b1b746cb14f80ba165d6ce9db37e9e7bbec
Satily/leetcode_python_solution
/solutions/solution67.py
658
3.5
4
from itertools import zip_longest class Solution: def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ result = list(map(sum, zip_longest(map(int, reversed(a)), map(int, reversed(b)), fillvalue=0))) for index in range(len(result) - 1): result[index + 1] += result[index] >> 1 result[index] &= 1 if result[-1] > 1: result[-1] &= 1 result.append(1) return ''.join((map(str, reversed(result)))) if __name__ == '__main__': print(Solution().addBinary('11', '1')) print(Solution().addBinary('1010', '1011'))
18f01a8a71306e59073944a5251810cb8737b689
chengbindai1984/python_learning
/stringProcess_adjust.py
743
3.6875
4
print ('Hello'.rjust(20)) print ('Hello World'.rjust(20)) print ('Hello'.ljust(20)) print ('Hello World'.ljust(20)) print ('Hello'.center(20)) print ('Hello World'.center(20)) print ('Hello'.rjust(20, '>')) print ('Hello World'.rjust(20, '>')) print ('Hello'.ljust(20, '<')) print ('Hello World'.ljust(20, '<')) print ('Hello'.center(20, '=')) print ('Hello World'.center(20, '=')) def printPicnic(itemsDict, leftWidth, rightWidth): print ("PICNIC ITEMS".center(leftWidth + rightWidth, '-')) for k, v in itemsDict.items(): print (k.ljust(leftWidth, '.') + str(v).rjust(rightWidth)) picnicItems = {'sandwiches': 4, 'apples': 5, 'oranges': 900} printPicnic(picnicItems, 10, 10) printPicnic(picnicItems, 20, 6)
c66a662f237859b6bfe95a36daa77de10ee6201b
ag1548/Parla.py
/examples/overhead_test/threading_test.py
1,007
3.640625
4
import threading import time from sleep.core import sleep, bsleep exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print("Starting " + self.name) print_time(self.name, 5, self.counter) print("Exiting " + self.name) def print_time(threadName, counter, delay): while counter: if exitFlag: threadName.exit() t = time.time() bsleep(1000) t = time.time() - t print("%s: %s" % (threadName, t)) counter -= 1 print("Running Main Thread") t = time.time() bsleep(1000) t = time.time() - t print("Main Thread Bsleep Time: ", t) # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 1) thread3 = myThread(3, "Thread-3", 1) # Start new Threads thread1.start() thread2.start() #thread3.start() print("Exiting Main Thread")
38b514165e56d26124b89391d5afb781a314f8fa
myasul/log-analysis
/log_analyzer.py
1,816
3.625
4
#!/usr/bin/env python3 import psycopg2 DBNAME = "news" def main(): # Open a file. This is where we will write the # data that we will fetch from the database. output_file = open("analysis.txt", "w") final_output = "" # Create a connection with the database conn = psycopg2.connect(database=DBNAME) cursor = conn.cursor() # Fetch all the needed data from the database cursor.execute("select * from top_authors limit 3") top_authors = cursor.fetchall() cursor.execute("select * from top_articles limit 3") top_articles = cursor.fetchall() cursor.execute("select * from error_perc_log where perc > 1") errors = cursor.fetchall() conn.close() # Close connection after we have fetched all the needed data. # Format the data that we have fetched in the database output_authors = "The Most Popular Article Authors of All Time:\n" for author in top_authors: output_authors += "* {} - {} views\n".format(author[0], author[1]) output_authors += "\n\n" output_articles = "The Most Popular Articles of All Time:\n" for article in top_articles: output_articles += "* \"{}\" - {} views\n".format( article[0], article[1]) output_articles += "\n\n" output_errors = "Days where more than 1% of requests led to errors:\n" for error in errors: output_errors += "* {0:'%B %d, %Y'} - {1}% errors\n".format( error[0], error[1]) final_output = '''******************** * Log Analyzer * ******************** {}{}{} *** END ***'''.format(output_articles, output_authors, output_errors) # Write the formatted data in the file # Close the file after writing the data. output_file.write(final_output) output_file.close() if __name__ == '__main__': main()
58c3317b8c1bad2eda8ef4bdd7324086f3baf4cb
counterjack/Python
/move_zero_to_last.py
1,574
3.640625
4
# - List of numbers (including 0) # Input: # Output: [1, 2, 4, 3, 5, 0,0,0,] # - No extra space # _input = [0, 2, 0, 4, 3, 0, 5, 0] # # _input = [0,0,0,0,1] # index_of_zero = 0 # zero_present = False # zero_at_first_place = _input[0] == 0 # for idx, item in enumerate(_input): # print (index_of_zero) # if item != 0 and index_of_zero > idx: # continue # elif item != 0 and index_of_zero < idx and (zero_present or zero_at_first_place): # print ("Did i come here") # _input[idx] = 0 # _input[index_of_zero] = item # index_of_zero = idx # zero_present = True # elif item == 0 and index_of_zero == 0 and not zero_at_first_place : # print ("I am here?", idx) # index_of_zero = idx # zero_present = True # print (_input) # a = "I am Vinay. I am working in Bluestacks. I work here as full stack developer." a = "I am Vinay. I am working in Bluestacks. Vinay works in Bluestacks as full stack developer." a = a.replace(".", "").split(" ") # output = "am" # - 2nd highest frequency dic = {} for item in a: try: dic[item] += 1 except: dic[item] = 1 print (dic) all_frequencies = dic.values() highest = all_frequencies[0] second_highest = all_frequencies[0] for item in all_frequencies: if (item > highest ): highest = item if item < highest and item > second_highest: second_highest = item sorted_freq = sorted(all_frequencies, reverse=True) for item in dic: if dic[item] == second_highest: print (item)
06a46acd3f9229e5c41d45f9552648c49f4fc8a0
yuchun921/CodeWars_python
/8kyu/Remove_string_spaces.py
165
3.671875
4
def no_space(x): char = '' for i in range(len(x)): if x[i] == ' ': continue else: char = char + x[i] return char
4d1d8bbc5839d8276b3fd7e110a4ae3d847fc630
arduzj/NSA_COMP3321
/Lesson_03/03_13.py
289
4.5
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- '''Lecture 03, Exercise 13 Write a for loop that prints out a numbered list of your grocery items. ''' shopping_list = ['milk', 'eggs', 'bread', 'apples', 'tea'] i = 1 for item in shopping_list: print(str(i) + ': ' + item) i += 1
12bd432929e96bf7395c18d802f8ae87815eb509
ruidazeng/online-judge
/Kattis/whatdoesthefoxsay.py
286
3.578125
4
T = int(input()) for _ in range(T): sound = input().split() while True: case = input() if case == 'what does the fox say?': break case = case.split() if case[2] in sound: while case[2] in sound: sound.remove(case[2]) print(*sound)
1d2067b493ddd5b50af4eed8d6913b43653cb84c
mahfuzar07/learn_python
/4_area.py
517
4.09375
4
#Traiangle (Area = 1/2 * base * Vertical height) #Rectangle (Area = Width * height) #Square (Area = Length of side ^2 ) #Parallelogram (Area = base * Vertical height) #Trapezoid (Area = 1/2 (a.base + b.base) * Vertical height) #circle (Area = Pie * radius ^2) #Ellipse (Area = Pie * a.base * b.base ) #Sector (Area = 1/2 * Radius ^2 * angle in radians) base = float(input("Enter Base : ")) height = float(input("Enter Vertical Height : ")) area = 0.5 * base * height print("Traiangle Area: %.4f"%area )
57269169f37ce820574a7d5573b02d0c429ac8a6
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/practicepython/PracticePython-master/ch11/03/Answer_a.py
230
3.828125
4
## Fibonacci number ## 0 1 1 2 3 5 8 13 21 34 55 89 144... F_len = int(input("請輸入要印出的費氏數列個數:\n")) a = 0 b = 1 temp = 0 for i in range(F_len): print(a) temp = a a = a + b b = temp
5335fdd3312fbed2c38f8bc32212bdc91f68cd67
matheisson/ccoolstuff
/systemhello.py
502
4.03125
4
# This is my first Codecool project, the Hello World program # It shall ask for a name, then write 'Hello XY' # OR if no name give simply output 'Hello World' # =================================================== # -=By: Csányi Levente, Codecool BP 1st semester=- import sys def HelloSys(): #With the len() function I can check how many arguments #the commanline has, then it can decide what it's gonna print. if len(sys.argv) > 1: print("Hello",sys.argv[1]) else: print("Hello World") HelloSys()
c268bf704438be5a8d346d22e9a2401c41e310cf
poojataksande9211/python_data
/python_tutorial/excercise/step_argument.py
787
4.1875
4
#syntax [start argument:stop argument:step argument] lang="python" print ("pooja" [1:3]) print ("harshit" [1:5:1]) #(it will print full string starting from a to h) print ("harshit" [0:5:2]) #(it will print character after 2 step) print (lang[0:6:3]) print("sudhakar" [1:8:3]) print ("harshit" [0::2]) #(stop argumentbis not given) print ("harshit" [::3]) print ("mangala" [5::-1]) #(start argument from 5 means l...-1 is for reverse step argument) print ("rajashree" [-1::-1]) #(start argument with -1 means last no of string with reverse 1 step) print ("rajashree" [::-1]) print ("rajashree" [-1::-2]) print ("rajashree" [-1::2]) print (lang[1:5:2]) print ("rajashreemoon" [0:13:5]) print("rajashreemoon" [::4]) print(lang[1::2]) print("pooja" [4::-1]) print("rajashreemoon" [12::-2])
f6ca1b8a7f7857fb1c54f8299dace8957bc4de77
harshgoel183/Practice-Python
/NewBoston/range.py
220
3.859375
4
for x in range(10):#by default starts from 0 and increment by 1 print(x) for i in range(5,12): print(i) for x in range(10,40,5): print(x) butcher = 5; while butcher < 10: print("ttt") butcher += 1
3ed3b4abda3495cade1cf500abb75247c7f24c12
m1dlace/Labs_Python
/1 Лаба/11..py
148
3.75
4
def frange(X, Y, Z): while X <= (Y - Z): yield float('{:.1f}'.format(X + Z)) X = X + Z for x in frange(1, 5, 0.1): print(x)
b5184a81feb2565d9eb40b238ab9e9fce7244a82
Putind/Aca
/exerclse07.py
1,267
3.984375
4
# 死循环 循环条件永远满足 # while True: # season = input('请输入一个季度') # if season == '春': # print('1月2月3月') # elif season == '夏': # print('4月5月6月') # elif season == '秋': # print('7月8月9月') # elif season == '冬': # print('10月11月12月') # if input('按e退出') == 'e': # break # 规定次数的循环 # count = 0 # while count<10: # dol = int(input('请输入美元')) # print(dol*6.9) # count += 1 # 在控制台输出0 2 3 4 5 # count = 0 # while count<6: # print(count) # count += 1 # 在控制台输出02468 # count = 1 # while count <= 20: # if count % 2 == 0: # print(count) # count += 1 # 在控制台获取月份 显示对应的季度 # 在控制台获取年龄 # 如果小于0 打印错误 # 如果小于2 打印是婴儿 # 如果 小于2-13 儿童 # 13-20 青年 # 20-65 成年人 # 65-130 老年人 # 超过130 不可能 # 3 根据身高和体重 参照BMI 返回身体状况 # BMI 体重(Kg)/身高(m)**2 # 中国参考标准
6adf59bbd039c929b35ccd75ca88105739e8db13
lanestevens/aoc2016
/day07/part1.py
658
3.71875
4
# -*- coding: utf-8 -*- import re import sys def abba(segment): for i in range(1, len(segment) - 2): if segment[i] == segment[i + 1] and segment[i - 1] == segment[i + 2] and segment[i - 1] != segment[i]: return True return False def valid(ip): out = True is_abba = False for segment in re.findall('([a-z]+)', ip): if not out and abba(segment): return False if out and abba(segment): is_abba = True out = not out return is_abba count = 0 for line in sys.stdin.readlines(): line = line.strip() if valid(line): count += 1 print count
e9607178a941f68f2b50a9add12e47540ab95c60
moshnar/Maktabsharif
/Maktab_42_HW_02_Mojtaba_Najafi/02_Combination.py
322
4.03125
4
def Combination(n, k): if n == 0 or n < 0: return elif k == 0 or n == k: return 1 else: # checking combination recursivly return Combination(n - 1, k - 1) + Combination(n - 1, k) n = int(input("Please enter n : ")) k = int(input("Please enter k : ")) print(Combination(n, k))
ab8091357552dd32f8e420c35aa14a97a658529c
xiaoyaohu0325/chess_deeplearning
/util/actions.py
8,372
3.75
4
import chess def move_to_index(move: chess.Move, current_player): """ A move in chess may be described in two parts: selecting the piece to move, and then selecting among the legal moves for that piece. We represent the policy π(a|s) by a 8 × 8 × 73 stack of planes encoding a probability distribution over 4,672 possible moves. Each of the 8 × 8 positions identifies the square from which to “pick up” a piece. 0~56 The first 56 planes encode possible ‘queen moves’ for any piece: a number of squares [1..7] in which the piece will be moved, along one of eight relative compass directions {N,NE,E,SE,S,SW,W,NW}. 1st plane: Move north 1 square 2nd plane: Move north 2 squares ... 56th plane: Move north-west 7 squares 56~64 The next 8 planes encode possible knight moves for that piece. 1st plane: knight move two squares up and one square right, (rank+2, file+1) 2nd plane: knight move one square up and two squares right, (rank+1, file+2) 3rd plane: knight move one square down and two squares right, (rank-1, file+2) 4th plane: knight move two squares down and one square right, (rank-2, file+1) 5th plane: knight move two squares down and one square left, (rank-2, file-1) 6th plane: knight move one square down and two squares left, (rank-1, file-2) 7th plane: knight move one square up and two squares left, (rank+1, file-2) 8th plane: knight move two squares up and one square left, (rank+2, file-1) 64~73 The final 9 planes encode possible underpromotions for pawn moves or captures in two possible diagonals, to knight, bishop or rook respectively. Other pawn moves or captures from the seventh rank are promoted to a queen. 1st plane: move forward, promote to rook 2nd plane: move forward, promote to bishop 3rd plane: move forward, promote to knight 4th plane: capture up left, promote to rook 5th plane: capture up left, promote to bishop 6th plane: capture up left, promote to knight 7th plane: capture up right, promote to rook 8th plane: capture up right, promote to bishop 9th plane: capture up right, promote to knight :param move: :param current_player: :return: """ rank_dist = chess.square_rank(move.to_square) - chess.square_rank(move.from_square) file_dist = chess.square_file(move.to_square) - chess.square_file(move.from_square) if current_player == chess.BLACK: # From black orientation, flip up down rank_dist *= -1 file_dist *= -1 if move.promotion: if file_dist == 0: if move.promotion == chess.ROOK: plane_index = 64 return plane_index * 64 + move.from_square elif move.promotion == chess.BISHOP: plane_index = 65 return plane_index * 64 + move.from_square elif move.promotion == chess.KNIGHT: plane_index = 66 return plane_index * 64 + move.from_square if file_dist == -1: if move.promotion == chess.ROOK: plane_index = 67 return plane_index * 64 + move.from_square elif move.promotion == chess.BISHOP: plane_index = 68 return plane_index * 64 + move.from_square elif move.promotion == chess.KNIGHT: plane_index = 69 return plane_index * 64 + move.from_square if file_dist == 1: if move.promotion == chess.ROOK: plane_index = 70 return plane_index * 64 + move.from_square elif move.promotion == chess.BISHOP: plane_index = 71 return plane_index * 64 + move.from_square elif move.promotion == chess.KNIGHT: plane_index = 72 return plane_index * 64 + move.from_square """ 56~64 The next 8 planes encode possible knight moves for that piece. 1st plane: knight move two squares up and one square right, (rank+2, file+1) 2nd plane: knight move one square up and two squares right, (rank+1, file+2) 3rd plane: knight move one square down and two squares right, (rank-1, file+2) 4th plane: knight move two squares down and one square right, (rank-2, file+1) 5th plane: knight move two squares down and one square left, (rank-2, file-1) 6th plane: knight move one square down and two squares left, (rank-1, file-2) 7th plane: knight move one square up and two squares left, (rank+1, file-2) 8th plane: knight move two squares up and one square left, (rank+2, file-1) """ if rank_dist == 2 and file_dist == 1: plane_index = 56 return plane_index * 64 + move.from_square elif rank_dist == 1 and file_dist == 2: plane_index = 57 return plane_index * 64 + move.from_square elif rank_dist == -1 and file_dist == 2: plane_index = 58 return plane_index * 64 + move.from_square elif rank_dist == -2 and file_dist == 1: plane_index = 59 return plane_index * 64 + move.from_square elif rank_dist == -2 and file_dist == -1: plane_index = 60 return plane_index * 64 + move.from_square elif rank_dist == -1 and file_dist == -2: plane_index = 61 return plane_index * 64 + move.from_square elif rank_dist == 1 and file_dist == -2: plane_index = 62 return plane_index * 64 + move.from_square elif rank_dist == 2 and file_dist == -1: plane_index = 63 return plane_index * 64 + move.from_square """ 0~56 The first 56 planes encode possible ‘queen moves’ for any piece: a number of squares [1..7] in which the piece will be moved, along one of eight relative compass directions {N,NE,E,SE,S,SW,W,NW}. 1st plane: Move north 1 square 2nd plane: Move north 2 squares ... 56th plane: Move north-west 7 squares """ if file_dist == 0 and rank_dist > 0: # move north, from plane [0,7) plane_index = rank_dist - 1 return plane_index * 64 + move.from_square elif file_dist > 0 and rank_dist > 0: # move north east, from plane [7,14) assert file_dist == rank_dist, "Invalid move {0}".format(move.uci()) plane_index = (rank_dist - 1) + 7 return plane_index * 64 + move.from_square elif rank_dist == 0 and file_dist > 0: # move east, from plane [14,21) plane_index = (file_dist - 1) + 14 return plane_index * 64 + move.from_square elif rank_dist < 0 < file_dist: # move south east, from plane [21,28) assert file_dist == -rank_dist, "Invalid move {0}".format(move.uci()) plane_index = (file_dist - 1) + 21 return plane_index * 64 + move.from_square elif file_dist == 0 and rank_dist < 0: # move south, from plane [28,35) plane_index = (-rank_dist - 1) + 28 return plane_index * 64 + move.from_square elif file_dist < 0 and rank_dist < 0: # move south west, from plane [35,42) assert file_dist == rank_dist, "Invalid move {0}".format(move.uci()) plane_index = (-rank_dist - 1) + 35 return plane_index * 64 + move.from_square elif rank_dist == 0 and file_dist < 0: # move west, from plane [42,49) plane_index = (-file_dist - 1) + 42 return plane_index * 64 + move.from_square elif file_dist < 0 < rank_dist: # move north west, from plane [49,56) assert -file_dist == rank_dist, "Invalid move {0}".format(move.uci()) plane_index = (rank_dist - 1) + 49 return plane_index * 64 + move.from_square raise ValueError("Move {0} can not be converted to action plane".format(move.uci())) # # def index_to_move(index: int, board: chess.Board, current_player): # plane_index, from_square = divmod(index, 64) # """ # 0~56 # The first 56 planes encode possible ‘queen moves’ for any piece: a number of squares [1..7] # in which the piece will be moved, along one of eight relative compass directions # {N,NE,E,SE,S,SW,W,NW}. # 1st plane: Move north 1 square # 2nd plane: Move north 2 squares # ... # 56th plane: Move north-west 7 squares # """ # if -1 < plane_index < 7: # # move north
f0b69132b521bdc1b88c1be4bbef52dd9f06165d
cunghaw/Elements-Of-Programming
/5.1 The Dutch national flag problem/main.py
1,391
4.09375
4
# -*- coding: utf-8 -*- """ Quick sort implementation @author: Ronny """ def quickSort ( array, low, high ): if ( low < high ): pi = partition ( array, low, high ) quickSort ( array, low, pi - 1 ) quickSort ( array, pi + 1, high ) return array def swap ( array, idx1, idx2 ): temp = array [ idx2 ] array [ idx2 ] = array [ idx1 ] array [ idx1 ] = temp def partition ( array, low, high ): # Use last element for pivot pivot = array [ high ] i = low - 1 while ( low < high ): if array [ low ] < pivot: i += 1 swap ( array, i, low ) low += 1 i += 1 swap ( array, i, high ) return i if __name__ == '__main__': # Test partition assert( partition( [ 1, 2, 3, 4, 5 ], 0, 4 ) == 4 ) assert( partition( [ 5, 4, 3, 2, 1 ], 0, 4 ) == 0 ) assert( partition( [ 5, 1, 4, 2, 3 ], 0, 4 ) == 2 ) assert( partition( [ 1, 1, 4, 2, 3 ], 0, 4 ) == 3 ) # Test quickSort assert( quickSort( [ 1, 2, 3, 4, 5 ], 0, 4 ) == [ 1, 2, 3, 4, 5 ] ) assert( quickSort( [ 5, 4, 3, 2, 1 ], 0, 4 ) == [ 1, 2, 3, 4, 5 ] ) assert( quickSort( [ 5, 1, 4, 2, 3 ], 0, 4 ) == [ 1, 2, 3, 4, 5 ] ) assert( quickSort( [ 1, 1, 4, 2, 3 ], 0, 4 ) == [ 1, 1, 2, 3, 4 ] ) assert( quickSort( [ 3, 1, 3, 1, 3 ], 0, 4 ) == [ 1, 1, 3, 3, 3 ] ) assert( quickSort( [ 4, 3, 2, 1 ], 0, 3 ) == [ 1, 2, 3, 4 ] ) print "All unit tests are passed"
9495ddb11e4c7e44043f368e2d33cee6157651dc
bukvicfilip/new_repo
/udemy2.py
555
4.28125
4
def reverse_vowels(word): _list=[] word2=[] n=-1 vowels="aeiouAEIOU" for w in word: if w in vowels: _list.append(w) _list1=_list[::-1] for letter in word: if letter not in _list: word2.append(letter) elif letter in _list: word2.append(_list[n]) n-=1 return("".join(word2)) print(reverse_vowels("Hello!")) # "Holle!" reverse_vowels("Tomatoes") # "Temotaos" reverse_vowels("Reverse Vowels In A String") # "RivArsI Vewols en e Streng" reverse_vowels("aeiou") # "uoiea" reverse_vowels("why try, shy fly?") # "why try, shy fly?"
0784d6e485772f226d1de0956b6e42b956ea8749
mendigali/Good-Samaritan
/some-python/rama.py
2,261
4
4
# Task 1 # Inheritance is when one class can copy all the properties and methods # of another class and add its own new methods and properties. class Person: def __init__(self, name="Ramazan", age="17"): self.name = name self.age = age def showName(self): return self.name def showAge(self): return self.age class Sportsmen(Person): def __init__(self, sport_type="Football", experience="2 years"): Person.__init__(self) self.sport_type = sport_type self.experience = experience def showInformation(self): answer = "Name: " + self.name + "\n" answer += "Age: " + self.age + "\n" answer += "Sport type: " + self.sport_type + "\n" answer += "Experience: " + self.experience return answer ramazan = Sportsmen() print(ramazan.showInformation()) # Result: # Name: Ramazan # Age: 17 # Sport type: Football # Experience: 2 years # Task 2 class Animal: def __init__(self, age): self.hungry_level = 50 self.age = age def isHungry(self): if self.hungry_level > 30: return "I'm hungry" else: return "I'm not hungry" def showAge(self): return self.age def feed(self, meal): self.hungry_level -= meal if self.hungry_level < 0: self.hungry_level = 0 class Pet(Animal): def __init__(self, name, pet_type): Animal.__init__(self, 3) self.name = name self.type = pet_type def saySomething(self): if self.type == "Cat": return "Meow" elif self.type == "Dog": return "Bark" else: return "Aaaaa" myPet = Pet("Barsik", "Cat") print(myPet.isHungry()) myPet.feed(40) print(myPet.isHungry()) print(myPet.showAge()) print(myPet.saySomething()) # Result: # I'm hungry # I'm not hungry # 3 # Meow Task 3 Multilevel inheritance is when one class inherits from another and the third class inherits from the first. For example, this is how I inherit from my father, and my father inherits from my grandfather. The inheritance hierarchy is when several classes are inherited from one class. For example, if a father has several sons, then they all inherit from him.
00093fc453fbabe6141b0b11f22dac2258e0bb85
AnkitM18-tech/Data-Structures-And-Algorithms
/Algorithms/Sorting Algorithms/Merge Sort.py
998
4.28125
4
def merge_sort(arr): if len(arr)>1: mid=len(arr)//2 left=arr[:mid] right=arr[mid:] merge_sort(left) merge_sort(right) i,j,k=0,0,0 while i<len(left) and j<len(right): if left[i]<right[j]: arr[k]=left[i] i+=1 k+=1 else: arr[k]=right[j] j+=1 k+=1 while i<len(left): arr[k]=left[i] i+=1 k+=1 while j<len(right): arr[k]=right[j] j+=1 k+=1 return arr if __name__=="__main__": arr=input("Enter the array of numbers (separated by space):") list1=list(map(int,arr.split(sep=" "))) print("The Sorted array is :",merge_sort(list1)) #split unsorted list #compare each of the elements and group them #repeat step 2 until whole list is merged and sorted #O(nlog(n))---->average time complexity. #split and merge continuously.
8ab7078b162be693006612de7b6cb48cc5f4266e
Andru-filit/andina
/Clase # - copia (8)/ejercicio6.py
205
3.796875
4
loteria=[] for i in range(5): numero=int(input("ingrese los numeros ganadores"+ str(i) +"de la loteria: ")) loteria.append(numero) print("Los numero de la loteria ganadores son:", sorted(loteria))
0fbb742459e3d78771e8e8eca6c7c9983508ea76
nararodriguess/programacaoempython1
/ex004.py
507
3.78125
4
n = (input('Digite algo: ')) print(f'O tipo primitivo de {n} é {(type(n))}') print(f'Esse valor é numerico? {n.isnumeric()}') print(f'Esse valor é alfabetico? {n.isalpha()}') print(f'Esse vaor é alfanumerico: {n.isalnum()}') print(f'Esse valor está em maiúsculo? {n.isupper()}') print(f'Esse valor esta minúsculo? {n.islower()}') print(f'Esse valor é decimal? {n.isdecimal()}') print(f'Esse valor é composto so por espaços? {n.isspace()}') print(f'Esse valor esta capitalizado? {n.istitle()}')
42b150ade92ca4e7d2c92d3bdc10d799fd746569
suryasr007/algorithms
/Daily Coding Problem/12.py
881
4.3125
4
""" There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters. For example, if N is 4, then there are 5 unique ways: 1, 1, 1, 1 2, 1, 1 1, 2, 1 1, 1, 2 2, 2 What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time. """ def countWaysUtil(n,m): res = [0]*n # Creates list res witth all elements 0 res[0],res[1] = 1,1 for i in range(2,n): j = 1 while j<=m and j<=i: res[i] = res[i] + res[i-j] j = j + 1 return res[n-1] def run(s, m): print(countWaysUtil(s+1, m)) if __name__ == "__main__": run(4, 4)
7357d59ea8fccfafd879829bce972b711b8a7856
masterxlp/The-Method-of-Programming
/string_exercises/1_习题_14.py
1,518
3.640625
4
def GenerateSuffixArray(string, length): # Generate Suffix Array, store it to list suf_array = list() start = len(string) - length end = len(string) while start >= 0: suffix = string[start:end] suf_array.append(suffix) start -= 1 end -= 1 return suf_array def isExist(long_suf_str, short_suf_str): check_result = list() # Check whether the Map is success for long_char in long_suf_str: if long_char in short_suf_str: check_result.append(long_char) return check_result def longestCommonSubstr(strA, strB): min_len = min(len(strA), len(strB)) # Initialize the length to min length in strA and strB length length = min_len # Rest longest string and shortest string if len(strA) >= len(strB): long_str = strA[:] short_str = strB[:] else: long_str = strB[:] short_str = strA[:] while length >= 1: # Gets the suffix array long_suf_array = GenerateSuffixArray(long_str, length) short_suf_array = GenerateSuffixArray(short_str, length) # Checks whether elements in the longest suffix array exist in # the shortest suffix array check_result = isExist(long_suf_array, short_suf_array) if len(check_result) == 0: length -= 1 else: print(check_result[len(check_result)-1]) break if __name__ == '__main__': longestCommonSubstr('abcdabc', 'vabcdcfdabc')
2f5b5702c4a1bb126337df64a0f37548e5b69249
poonamangne/Programming-Exercises-1
/Chapter13_12.py
2,599
4.0625
4
# 13.12 Modify the Triangle class to throw a TriangleError exception # if the three given sides cannot form a triangle # Sample Inputs [10, 9, 8] [3, 2, 1] from GeometricObject import GeometricObject class Triangle(GeometricObject): def __init__(self, side1 = 1.0, side2 = 1.0, side3 = 1.0): if (side1 + side2 > side3) and (side2 + side3 > side1) and (side3 + side1 > side2): super().__init__() self.__side1 = side1 self.__side2 = side2 self.__side3 = side3 else: raise TriangleError(side1, side2, side3) def getSide1(self): return self.__side1 def setSide1(self, side1): self.__side1 = side1 def getSide2(self): return self.__side2 def setSide2(self, side2): self.__side2 = side2 def getSide3(self): return self.__side3 def setSide3(self, side3): self.__side3 = side3 def getArea(self): s = (self.__side1 + self.__side2 + self.__side3) / 2 area = (s * (s - self.__side1) * (s - self.__side2) * (s - self.__side3)) ** 0.5 return area def getPerimeter(self): return self.getSide1() + self.getSide2() + self.getSide3() def __str__(self): return "Triangle: side1 = " + str(self.__side1) + " side2 = " + str(self.__side2) + \ " side3 = " + str(self.__side3) class TriangleError(RuntimeError): def __init__(self, side1, side2, side3): super().__init__() self.side1 = side1 self.side2 = side2 self.side3 = side3 def getSide1(self): return self.side1 def getSide2(self): return self.side2 def getSide3(self): return self.side3 def main(): try: # Prompt user for inputs side1, side2, side3 = eval(input("Enter the three sides of the triangle: ")) t1 = Triangle(side1, side2, side3) color = input("Enter a color: ") filled = eval(input("Is the triangle filled? Enter 1 or 0: ")) t1.setColor(color) t1.setFilled(filled) # Display Area, Perimeter, color, is filled for the triangle print() print("Area of the Triangle:", format(t1.getArea(), ".2f")) print("Perimeter of the Triangle:", t1.getPerimeter()) print("Triangle color:", t1.getColor(), "and filled:", bool(t1.isFilled())) except TriangleError as ex: print("The sides " + str(ex.getSide1()) + ", " + str(ex.getSide2()) + ", " \ +str(ex.getSide3()) + " cannot form a triangle") main() # Call the main function
a3f7f0c33f0527a0cfbb5ff836868f90776dc58a
hoanghalc/hoangha-fundamental-c4e18
/Session 5/bai_1.py
808
3.984375
4
# person = ["Quý",20,0,"Vĩnh Phúc",2,["manga","coding"],3,20] # dictionary #Create person = { "name": "Quý", "age": 20, "ex": 0, "fav": ["Manga", "Coding"] } # print(person) # name = person["name"] # print(name) #Add more # person["length"] = 20 # print(person) #Update # person["length"] = 10 # print(person) #Delete # del person["length"] # key = "length" # if key in person: #Kiểm tra phần tử có trong dict hay ko # print(person[key]) # else: # print("làm gì có mà tìm") #Duyệt các phần tử trong dict for k in person: #Duyệt theo key print(k) for k in person: print(k, person[k]) for v in person.values(): #Duyệt theo value print(v) for k, v in person.items(): #Duyệt theo cả key và value print(k, v)
d423317847288756cff0af3d70b8ccdd8edae6e5
chenwu054/Leetcode
/Anagrams.py
479
3.5625
4
class Solution: def anagrams(self, strs): map, result = {}, [] if len(strs) >= 1: for str in strs: sorted_str = "".join(sorted(str)) if sorted_str not in map: map[sorted_str] = [str] else: map[sorted_str].append(str) for word in map: if len(map[word]) > 1: result += map[word] return result
118acd0bccc3fe1a71a7fda77de6a215c1f8a5d9
dale-nelson/IFT-101-Lab5
/Lab05P3.py
220
3.8125
4
str1 = "spam" str2 = "ni ! " print(" The Knights who say, " + str2) print(3 * str1 + 2 * str2) print(str1[1]) print(str1[1:3]) print(str1[2] + str2[:2]) print(str1 + str2[-1]) print(str1.upper()) print(str2.upper() * 3)
d85e7a8e39fad91bce44ceebe5e08624441880bc
roshnet/enleren
/utils/validate.py
762
3.625
4
def validate(name='', uname='', passwd=''): # Performs basic checks on user input. # Use regular expressions in production version. # Applying very basic checks just for testing sake. if len(name) < 4 or len(uname) < 4 or len(passwd) < 8: return 0 return 1 ''' In future versions, validation features will include :- : presence of chars other that alphabets in `name` ; : `uname` is to be checked as :- :: first place should be an alphabet, not a number or a special char. :: composed of alphanumeric chars, underbars, periods only. :: max length to be set. : Email address validator (either built-in or custom) : Hash generator (custom hash being feeded to a standard encryption algo) '''
75683e9f0a6308f2c300b3e187886a8075773a52
MallikarjunH4/python-training
/PRACTICE SET 02-05-2021.py
1,048
3.609375
4
#1 l1=[1,2,3,4] l2=['a','b','c','d'] d=dict(zip(l1,l2)) print(d) #2 n=input() l1=[] l2=[] for i in n: if 97<=ord(i)<=122 or 65<=ord(i)<=90: l1.append(i) elif i in """0123456789""": l2.append(i) print("Letters : ",len(l1)) print("Digits : ",len(l2)) #3 n=input() n=n.split() print(n) f=0 count=len(n[0]) for i in range(1,len(n)): if len(n[i])>=count: count=len(n[i]) print('length of longest word is : ',n[i],':',len(n[i]));f=1 if f==0: print('length of longest word is : ',n[0],':',len(n[0])) #4 n=int(input()) for i in range(1,n+1): for j in range(i): print(i,end='') print() #5 RUSSIAN PRIME def isprime(n,f): c=0 for i in range(2,n+1): if n%i==0: c=c+1 if c==1 and n!=0: print('prime',n) f=1 n=n//10 print(f) return isprime(n,1) else: return f n=int(input()) s=isprime(n,0) if s==0: print("NOT A RUSIAN PRIME") else: print("ITS A RUSSIAN PRIME",n )
c148d72685b03b00b077b5a7a0279f06c0934f3c
TQCAI/Algorithm
/python/linklist/s148.py
1,784
3.71875
4
from structure import ListNode def merge(h1: ListNode, h2: ListNode): p1, p2, dummy = h1, h2, ListNode(0) dp = dummy while p1 and p2: if p1.val < p2.val: dp.next = p1 p1 = p1.next else: dp.next = p2 p2 = p2.next dp = dp.next dp.next = p1 if p1 else p2 return dummy.next class Solution: def sortList(self, head: ListNode) -> ListNode: dummy = ListNode(0, head) p = head length = 0 while p: p = p.next length += 1 sub_len = 1 while sub_len < length: pre, cur = dummy, dummy.next while cur: h1 = cur for _ in range(sub_len - 1): if cur and cur.next: cur = cur.next else: break h2 = cur.next cur.next = None # h1 结扎 cur = h2 # 恢复 cur for _ in range(sub_len - 1): if cur and cur.next: cur = cur.next else: break suc = None if cur: # 构造新的【cur】 suc = cur.next cur.next = None # h2 结扎 cur = suc # merged = merge(h1, h2) pre.next = merged # 构造新的【pre】 (merged的最后一个结点) while pre.next: pre = pre.next sub_len *= 2 return dummy.next print(Solution().sortList(ListNode.fromList([4, 2, 1, 3]))) # # print(merge(ListNode.fromList([1, 3, 5]), ListNode.fromList([2, 4, 6, 7])))
52884097dbfb7b73f1b6798cabe2ad5d1b548781
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_2/387.py
2,791
3.546875
4
#!/usr/bin/python import sys; import re; def schedule_trains(trips_A, trips_B, T): available_A = []; available_B = []; nA = 0; nB = 0; while( (len(trips_A)>0) or (len(trips_B)> 0) ): # find next trip # A -> B if((len(trips_B) == 0 ) or ((len(trips_A) > 0 ) and (trips_A[0] < trips_B[0]))): trip = trips_A.pop(0); # print "A->B: " + str(trip[0]) + " :: " + str(trip[1]) + "::" + str(trip[1] + T); # print "\tavailable trains: " + str(available_A); # look at first available train if((len(available_A) > 0) and (trip[0] >= available_A[0])): # print "\tusing " + str(available_A[0]); available_A.pop(0); # if nothing is available, add a train else: # print "\tno trains available at " + str(trip[0]) + ", creating one"; nA += 1; # make this train available in B T minutes after it arrives available_B.append(trip[1] + T); available_B.sort(); # print "\ttrain placed in availableB: " + str(available_B); # B-> A else: trip = trips_B.pop(0); # print "B->A: " + str(trip[0]) + " :: " + str(trip[1]) + "::" + str(trip[1] + T); # print "\tavailable trains: " + str(available_B); # look at first available train if((len(available_B) > 0) and (trip[0] >= available_B[0])): # print "\tusing " + str(available_B[0]); available_B.pop(0); # if nothing is available, add a train else: # print "\tno trains available at " + str(trip[0]) + ", creating one"; nB += 1; # make this train available in A T minutes after it arrives available_A.append(trip[1] + T); available_A.sort(); # print "\ttrain placed in availableA: " + str(available_A); return nA, nB; # read in file file = open(sys.argv[1], "r"); N = int(file.readline()); for i in range(N): T = int(file.readline()); # read NA and NB line = file.readline(); m = re.search(r"(?P<NA>\d+) (?P<NB>\d+)", line); NA = int(m.group("NA")); NB = int(m.group("NB")); trips_A = []; trips_B = []; for j in range(NA): line = file.readline(); m = re.search(r"(?P<dh>\d{2}):(?P<dm>\d{2}) (?P<ah>\d{2}):(?P<am>\d{2})", line); dh = int(m.group("dh")); dm = int(m.group("dm")); ah = int(m.group("ah")); am = int(m.group("am")); trips_A.append( (dm+dh*60, am+ah*60) ); for j in range(NB): line = file.readline(); m = re.search(r"(?P<dh>\d{2}):(?P<dm>\d{2}) (?P<ah>\d{2}):(?P<am>\d{2})", line); dh = int(m.group("dh")); dm = int(m.group("dm")); ah = int(m.group("ah")); am = int(m.group("am")); trips_B.append( (dm+dh*60, am+ah*60) ); trips_A.sort(); trips_B.sort(); nA, nB = schedule_trains(trips_A, trips_B, T); print "Case #" + str(i+1) + ": " + str(nA) + " " + str(nB);
1be7627bd75bce03e83b918e7359440e87f4f070
shankarapailoor/Project-Euler
/Project Euler/p21-p30/p25.py
1,019
3.609375
4
from math import * from copy import deepcopy import time def calculate_Fibonnaci(): fn = 0 n = 10 while len(str(fn)) < 1000: fn = 1/sqrt(5)*((2/(-1 + sqrt(5)))**(n+1) - (2/(-1-sqrt(5)))**(n+1)) n += 1 return int(fn) def addtwoarrays(a, b): c = [0]*len(a) rem = 0 if len(a) != len(b): print "Array Lengths not compatible" else: for i in range(0, len(a)): temp = a[i] + b[i] + rem y = getmodulo(temp) c[i] = y[0] rem = y[1] return c def getmodulo(n): x = str(n) y = list(x) g = '' if n > 10: t = int(y.pop()) else: return n, 0 for i in y: g += i g = int(g) return t, g def fibonnaci_numbers(): a = [] for i in range(0, 1000): a.append(0) a[0] = 1 b = [] b = deepcopy(a) c = deepcopy(a) x = 1 while b[999] == 0: x += 1 c = addtwoarrays(a,b) a = deepcopy(b) b = deepcopy(c) return x if __name__=='__main__': a = [5, 9, 2, 0, 0, 0] b = [9, 9, 0, 0, 0, 0] start = time.time() x = fibonnaci_numbers() end = time.time() - start print x, end
3a4ebd71af5f0894d0d9aadcbae342abb0d0adba
vlad0337187/different_helpful_programs
/for_backup/создать папки для монтирования fstab.py
3,109
4.375
4
#! /usr/bin/python3 import os, os.path import sys # for exiting from program import shutil # for removing directories with all it's folders def create_folder(folder): """Creates passed to it folder if it's absent, if it's present - asks user, what to do. """ print('') if os.path.exists(folder) and (os.listdir(folder) != []): print('Folder {0} already exists.'.format(folder)) print('Remove it and create an empty one?') print("L - view the list of files in it, Y - yes, N - don't remove and pass, Q - quit.") while True: # needs for case, when user wrote wrong symbol inp = input() if inp == 'Y': #recursively_remove_folder(folder) shutil.rmtree(folder) os.makedirs(folder) print('Folder "{0}" was successfully created'.format(folder)) break elif inp == 'N': print("Passing, we didn't remove '{0}' directory".format(folder)) break elif inp == 'L': files_list = os.listdir(folder) if files_list == []: print('Directory contains no files.') else: print('Directory "{0}" contains next files:'.format(folder)) for i in os.listdir(folder): print(i) print('What will we do with it?') elif inp == 'Q': sys.exit() else: print('Command not found. Please, try again.') continue elif os.path.exists(folder): print('Folder is already present and is empty. All is well. ({0})'.format(folder)) else: os.makedirs(folder) print('Folder was successfully created. ({0})'.format(folder)) def recursively_remove_folder(item): # not needed any more, shutil module is used if os.path.isdir(item): for i in os.listdir(item): recursively_remove_folder(os.path.join(item, i)) os.rmdir(item) else: os.remove(item) print('Program loaded.') print('Now we will create all needed folders.') create_folder('/home/vlad/Видео') create_folder('/home/vlad/Документы') create_folder('/home/vlad/Загрузки') create_folder('/home/vlad/Изображения') create_folder('/home/vlad/Музыка') create_folder('/home/vlad/Шаблоны') create_folder('/home/vlad/Рабочий стол') create_folder('/home/vlad/.fonts') create_folder('/home/vlad/.themes') create_folder('/home/vlad/.icons') create_folder('/home/vlad/for_Programs') create_folder('/home/vlad/Programs') create_folder('/home/vlad/lmms') create_folder('/home/vlad/makehuman') create_folder('/home/vlad/.mozilla') create_folder('/home/vlad/.thunderbird') create_folder('/home/vlad/.moonchild productions') create_folder('/home/vlad/.Skype') create_folder('/home/vlad/.ssh') create_folder('/home/vlad/.config/blender') create_folder('/home/vlad/.config/hexchat') create_folder('/home/vlad/.config/Slack') create_folder('/home/vlad/.config/supertuxkart') create_folder('/home/vlad/.config/transmission') print('') while True: if os.path.exists('/media/vlad/Storm'): if os.path.ismount('/media/vlad/Storm'): print("Before we will create /media/vlad/Storm, please unmount it.") input("Press any key to try again.") continue break else: break create_folder('/media/vlad/Storm')
39169b0bab3c83ebfecb996329ad040f55836308
gokarna123/Gokarna
/word.py
276
4.1875
4
words=input("Enter the words;") length=len(words) string="" counter=-1 while counter>(length-1): string1=words[counter] string1=string+string1 counter=counter-1 if string==words: print("the number is palindrome") else: print("The number is not palindrome")
dd714ffd18f4c3d4a49f2a51b1148202eea3acf7
Computer-engineering-FICT/Computer-engineering-FICT
/II семестр/Дискретна математика/Лаби/2016-17/Братун 6305/Lab_1_backup_4/Lab_1/4ernetka.py
240
3.546875
4
#My function def differencexz(a, b): res = [] for i in a: for j in b: if i != j: res.append(i) return set(res) x = {1,2,3,4,5,6,7,8,9,10} c = {1,2,3,4,5} print(differencexz(x,c))
c8eb75a55cb15bf82b74785ea7104b6f7bb137ab
rafaelperazzo/programacao-web
/moodledata/vpl_data/215/usersdata/271/113863/submittedfiles/av2_p2_m2.py
325
3.8125
4
# -*- coding: utf-8 -*- #ENTRADA n = int(input('Digite a quantidade de portas : ')) a = [] #PROCESSAMENTO for i in range (0,n,1) : v = int(input('Vidas : ')) a.append(v) x = int(input('Porta de Entrada : ')) y = int(input('Porta de Saída : ')) soma = 0 for i in range (x,y+1,1) : soma = soma + a[i] print(soma)
cc226c3f494edcad86a5b765a55accce32c28912
StevePaget/StacksAndQueues
/stacks.py
872
3.953125
4
# Stacks Demo class Stack(): def __init__(self, maxsize): self.maxsize = maxsize self.contents = [ None for i in range(maxsize)] self.top = -1 def push(self, newItem): if self.top == self.maxsize-1: print("The Stack is full") else: self.top += 1 self.contents[self.top] = newItem def printAll(self): for item in self.contents: print(item) def pop(self): if self.top == -1: print("The Stack is Empty") else: itemtoreturn = self.contents[self.top] self.top -= 1 return itemtoreturn myStack = Stack(5) # myStack.push("Harry") # myStack.push("Maggy") # myStack.push("Lenny") # myStack.push("Wendy") # myStack.push("Bobby") print( myStack.pop() )
0a61af99b6121ef69568e1231dce79fc6c0b6c37
twickatwk/codingchallenges
/Leetcode/Easy/242ValidAnagram.py
923
3.53125
4
# Time: O(N Log N) - because of the sorting | Space: O(1) def isAnagram(s, t): """ :type s: str :type t: str :rtype: bool """ s = list(s) t = list(t) s.sort() t.sort() return s == t # Time: O(N) | Space: O(N) def isAnagram2(s, t): """ :type s: str :type t: str :rtype: bool """ if len(s) != len(t): return False visitedLetters = {} for c in s: if c in visitedLetters: visitedLetters[c] += 1 else: visitedLetters[c] = 1 for c in t: if c in visitedLetters: visitedLetters[c] -= 1 if visitedLetters[c] < 0: return False else: return False return True
6a2ef1ab884837f51ca1a8570da0c9c113d92565
abhishekbisneer/Python_Code
/Exercise-14.py
799
4.15625
4
#List Remove Duplicates #Exercise 14 (and Solution) ''' Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates. Extras: Write two different functions to do this - one using a loop and constructing a list, and another using sets. Go back and do Exercise 5 using sets, and write the solution for that in a different function. ''' x=[2,1,2,1,4,5,6,7] z=[] for i in range(0,len(x)): if x[i] not in z: z.append(x[i]) print(z) print("----------------------------------------------------") # there is some error # Application throws error "list object cannot be called" #this one uses sets def dedupe_v2(x): return list(set(x)) a = [1,2,3,4,3,2,1] print (a) print (dedupe_v2(a))
15be3acd9ae5d233fb9d4919ff70a7c255676019
Yogesh-Singh-Gadwal/YSG_Python
/Core_Python/Day-10/26.py
313
3.78125
4
# loops # patterns ''' 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 ''' ''' v1 = int(input('Enter user value : ')) a = 1 for x in range(v1): print('1 '*a) a +=1 ''' v1 = int(input('Enter user value : ')) for x in range(v1): for y in range(x+1): print(y+1,end=" ") print()
9ba81dae1bd08ded810345cf6d70953243d7e8ad
LES0915/korea_subway_dataset
/src/make_csv.py
706
3.703125
4
import csv def write_csv(line_data, city_name): file = open(f"dataset/{city_name}/{line_data['line_name']}.csv", mode="w") writer = csv.writer(file) if city_name == "pusan": writer.writerow(["number", "line", "name", "english_name", "japanese_name", "chinese_name", "hanja_name", "transfer", "distance", "cumulative_distance", "location"]) else: writer.writerow(["number", "line", "name", "english_name", "hanja_name", "transfer", "distance", "cumalative_distance", "location"]) for d in line_data['station_data']: writer.writerow(d.values()) print(f"Created {line_data['line_name']}.csv file") return
d656994d3677e257b228a86f573a38b5723cbcf8
luxuguang-leo/everyday_leetcode
/00_leetcode/438.find-all-anagrams-in-a-string.py
880
3.5
4
# # @lc app=leetcode id=438 lang=python # # [438] Find All Anagrams in a String # # @lc code=start class Solution(object): def findAnagrams(self, s, p): """ :type s: str :type p: str :rtype: List[int] """ #和#76相同的思路! if not s or not p: return [] m = collections.Counter(p) l, cnt = 0, 0 wanted = len(p) ret = [] for r in range(len(s)): if s[r] in m: m[s[r]] -=1 if m[s[r]] >=0: cnt +=1 while cnt == wanted: if r - l + 1 == len(p): ret.append(l) if s[l] in m: m[s[l]] +=1 if m[s[l]] > 0: cnt -=1 l +=1 return ret # @lc code=end
d22797d5a0f4a204507f4a08b09d8f9f136633ce
LukeBreezy/Python3_Curso_Em_Video
/IDLE/desafio03.py
231
3.96875
4
print('''======= D E S A F I O 0 3 ======= Siga as instruções e veja a soma dos números.''') num1 = input('Digite um número: ') num2 = input('Digite outro número: ') print(num1, '+', num2, '=', int(num1)+int(num2))
1c9026b22d60bb38de26b521ae501ebb815208d2
Jayesh97/programmming
/special/139_WordBreak.py
511
3.59375
4
s = "leetcode" wordDict = ["leet", "code"] def recurse(s,seen,wordset,lengths): if s=="": return True if s in seen: return seen[s] for length in lengths: if s[:length] in wordset and recurse(s[length:],seen,wordset,lengths): #print(s[:length]) seen[s]=True return True seen[s]=False return False seen = {} wordset = set(wordDict) lengths = sorted(set(len(x) for x in wordDict)) print(lengths) print(recurse(s,seen,wordset,lengths))
c7290853dd16254d90c4b01ca1f9f4126db38df9
romanbondarev/2048
/logic.py
7,666
3.796875
4
import os import time from random import * class Game: """2048 game.""" def __init__(self): """Gamemap and variable initialization.""" self.game_map = {0: '', 1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '', 8: '', 9: '', 10: '', 11: '', 12: '', 13: '', 14: '', 15: ''} self.clear_mode = 'cls' self.win = False self.add_four = False self.score = 0 self.load_game() def clear(self): """Clears the console.""" os.system(self.clear_mode) def run_game(self): """Main game loop.""" self.print_game_map() while True: user_input = input().lower() while not self.check_user_input(user_input): self.print_game_map() user_input = input().lower() # Start the new game if user_input == 'n': self.clear() reset = input('Reset Progress & Start New Game? y/n: ').lower() if reset == 'y': self.start_new_game() self.save_game() self.print_game_map() continue # Quit game elif user_input == 'q': self.clear() self.save_game() print('Quiting game...') time.sleep(3) break # Load saved game elif user_input == 'l': self.load_game() self.print_game_map() continue # Shift tiles self.shift(user_input) self.print_game_map() time.sleep(0.2) # Check for the winning position and try to add a new tile if self.win is False and self.has_won() or self.add_random_tile(): self.clear() self.save_game() print('Quiting game...') time.sleep(3) break # Save game self.save_game() # Print game self.print_game_map() def shift(self, direction): """Tile shifting.""" moves = {'w': ([4, 8, 12], -4, range(4)), 's': ([8, 4, 0], 4, range(4)), 'a': ([1, 2, 3], -1, range(0, 13, 4)), 'd': ([2, 1, 0], 1, range(0, 13, 4))} for c in moves[direction][2]: # 'w': range(4) counter = 0 shifts = self.possible_shifts(c, direction) for i in moves[direction][0] * 3: # 'w': [4, 8, 12] current = c + i # If next tile is empty if self.game_map[current + moves[direction][1]] == '': self.game_map[current + moves[direction][1]] = self.game_map[current] self.game_map[current] = '' # If next tile and current tile are the same elif self.game_map[current + moves[direction][1]] == self.game_map[current] and counter < shifts and \ self.game_map[current + moves[direction][1]] == str(int(self.game_map[current])): # Multiply next tile by 2 self.game_map[current + moves[direction][1]] = str(int(self.game_map[current]) * 2) # Update score self.score += int(self.game_map[current]) * 2 # Remove number from current tile self.game_map[current] = '' counter += 1 def possible_shifts(self, row, direction): """Gets the amount of possible shifts for given direction at given column/row.""" moves = {'w': ([0, 4, 8, 12], -4), 's': ([12, 8, 4, 0], 4), 'a': ([0, 1, 2, 3], -1), 'd': ([3, 2, 1, 0], 1)} values_to_compare = [] for l in moves[direction][0]: values_to_compare.append(self.game_map[row + l]) shifts = self.count_similar(sorted(values_to_compare)) if shifts > 2: shifts = 2 return shifts @staticmethod def count_similar(n): """Gets the amount of similar pairs.""" if len(n) < 2: return 0 elif n[0] == n[1]: return 1 + Game.count_similar(n[2:]) else: return 0 + Game.count_similar(n[1:]) def add_random_tile(self): """Adds a new tile at the random place.""" if self.add_four is False: for i in range(16): if self.game_map[i] == '4': self.add_four = True break choices = ['2', '2', '2', '2'] n = randint(0, 15) counter = 0 # If tile is not empty at random value place, generate a new random value # Timeout after 200 tries while len(self.game_map[n]) > 0: if counter > 200: return True counter += 1 n = randint(0, 15) if self.add_four: choices += ['4', '4'] self.game_map[n] = choice(choices) return False def has_won(self): """Checks for the winning position.""" for i in range(16): if self.game_map[i] == '2048': self.win = True self.clear() print(" __ __ __ __ _ \n" " \ \ / /__ _ _ \ \ / /__ _ _ | |\n" " \ V / _ \ || | \ \/\/ / _ \ ' \ |_|\n" " |_|\___/\_,_| \_/\_/\___/_||_| (_)\n") ui = input("Do you want to continue? y/n: ").lower() if ui == 'n': return True return False @staticmethod def check_user_input(user_input): """Checks if user's input is correct.""" return user_input in ['w', 'a', 's', 'd', 'q', 'l', 'n'] def print_game_map(self): """Prints out map.""" self.clear() print('PLAY 2048 GAME v1.0\n' 'Join the numbers and get to the 2048 tile!\n\n' 'HOW TO PLAY:\n' ' - Use your WASD keys to move the tiles.\n' ' - When two tiles with the same number touch, they merge into one!\n' ' - Press "q" to quit game.\n' ' - Press "n" to start a new game.\n') m = self.game_map print(' SCORE: {} '.format(self.score).center(24, '=')) for i in range(0, 16): if i % 4 == 0 and i != 0: print('\n-----+-----+-----+------') if i % 4 == 3: print('{}'.format(m[i].center(5)), end='') else: print('{}|'.format(m[i].center(5)), end='') print("\n========================") def start_new_game(self): """Starts a new game.""" self.win, self.add_four, self.score = False, False, 0 for c in range(16): self.game_map[c] = '' for i in range(2): self.add_random_tile() def save_game(self): """Saves game into txt file.""" f = open('save.txt', 'w') f.write('Score:\n' + str(self.score) + '\n\nSaved game:\n') for i in range(16): f.write(self.game_map[i] + '\n') f.write('\n' + str(self.win)) f.close() def load_game(self): """Loads saved game from txt file.""" try: file = open('save.txt', 'r').readlines() except FileNotFoundError: self.start_new_game() else: self.score = int(file[1].strip('\n')) self.win = file[21] for i in range(16): self.game_map[i] = file[i + 4].strip('\n') if __name__ == '__main__': Game().run_game()