blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
130cf717ee5f3b2dfdb24a4131ae09b04fd9ae02 | DarrenZheng/python3_base | /fifthday/raise_except.py | 470 | 3.828125 | 4 | class ShortException(Exception):
def __init__(self, length, atleast):
Exception.__init__(self)
self.length=length
self.atleast=atleast
def __str__(self):
return "是什么"
try:
s = input("enter something:")
if len(s) < 3:
raise ShortException(len(s), 3)
except EOFError:
print('why did you do an EOF to me?')
except ShortException as x :
print('ShortException', 'the input was', x.length)
print(x) |
a77ec46f2cf8c1b7982bf2df970e11e581699731 | xchmiao/Leetcode | /Data Structure/Implement Trie.py | 1,471 | 4.0625 | 4 | """
https://leetcode.com/problems/implement-trie-prefix-tree/
"""
class TrieNode:
def __init__(self):
self.children = {} # mapping char to TrieNode, i.e. char: TrieNode()
self.is_word = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def find(self, word: str) -> TrieNode:
node = self.root
for c in word:
if c not in node.children:
return None
node = node.children[c]
return node
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.root
for c in word:
# if c is not a child of current node, then create a new TrieNode for c
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
# at the end, set the is_word = True, i.e. flag it is word
node.is_word = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self.find(word)
return node is not None and node.is_word
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self.find(prefix)
return node is not None
|
fc2007a6da1d388c3099b69518e3728d24ae6ca4 | eronekogin/leetcode | /2020/robot_bounded_in_circle.py | 1,129 | 3.96875 | 4 | """
https://leetcode.com/problems/robot-bounded-in-circle/
"""
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
"""
After one round of all the instructions:
1. If the robot goes back to the original point, it will still be
at the original point after the next round's instructions.
2. If the robot goes to a new point:
2.1 If the robot faces to the same direction as the original
one, it will go toward the same direction and move further
after the next round's instructions.
2.2 If the robot faces to a different direction, then it means
it will eventually go back to the original point.
"""
x, y, dx, dy = 0, 0, 0, 1
for c in instructions:
if c == 'G':
x += dx
y += dy
elif c == 'L':
dx, dy = -dy, dx
elif c == 'R':
dx, dy = dy, -dx
return (x, y) == (0, 0) or (dx, dy) != (0, 1)
print(Solution().isRobotBounded('GL'))
|
9f76b757395a2b062f7fcf2072a3f314752af614 | SaloniGandhi/leetcode | /876. Middle of the Linked List.py | 778 | 3.828125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
count=1
if not head:
return
#compute the len of ll
temp=head
while(temp.next!=None):
count+=1
temp=temp.next
print(count)
if count%2==0:
midindex=((count-1)//2)+1
else:
midindex=(count-1)//2
print(midindex)
temp=head
cntindex=0
while(temp.next!=None):
if cntindex == midindex:
break
else:
cntindex+=1
temp=temp.next
return temp
|
147f17d7d8e28d7c2009b8b395f3212140ff4a24 | meghanathmacha/Ad-Safe | /contentanalyzer/build/lib.linux-x86_64-2.6/contentanalyzer.py | 22,490 | 3.5625 | 4 | """ Adsafe
About the Program : The program has two mode Basic(Gives the result as True or False for a particular class) and Advanced(Gives a rating of 1 to 5 (5 being very bad)
How do i use it ? : You can send 3 arguments (<url name>,<html of the url>,<list of the links on the url>) to any of the functions (Basic or Advanced) and the program will return you a json array with the result.(A csv is also generated)
Parsing a list of links : Pass the json file to the perform function in "chisafe.py"(bean.py uses beanstalk to process the links)"""
from nltk.stem import PorterStemmer
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import RegexpTokenizer
from Numeric import *
from sys import argv
import cPickle as pickle
import nltk.util
import pycurl
import socket
import numpy
import time
import csv
from numpy import *
import directory
class Bayesian:
def __init__(self,count,c):
global C
global word_list_all
self.count = count
self.c = c
if (self.count == 0):
word_list,A = Bucket_Processing().return_()
self.word_list = word_list
self.word_list_all = []
self.A = A
if not(self.count == 0):
self.word_list = word_list_all
self.A = self.normalise(C)
def learning(self):
global C
global word_list_all
ini_length_word_list = len(self.word_list)
length_link_text,length_list_link_text =0,0
region_text = zeros([7],Int)
region_link = zeros([7],Int)
i,site_value_text,site_value_link=0,0.0,0.0
word_list_text = self.word_list
word_list_link = self.word_list
text = pickle.load(open('pfile_text.p'))
link_text = str(text).lower().split(None)
last = link_text[-1].strip(']')
last = last + ','
link_text.remove(link_text[-1])
link_text.append(last)
length_link_text = len(link_text)
text = pickle.load(open('pfile_link.p'))
list_link_text = str(text).lower().split(None)
last = list_link_text[-1].strip(']')
last = last + ','
list_link_text.remove(list_link_text[-1])
list_link_text.append(last)
length_list_link_text = len(list_link_text)
for word in link_text:
if word in word_list_text:
ind = word_list_text.index(word)
for i in range(2,9):
if self.A[ind][i]==1 and self.A[ind][9]==0:
region_text[i-2]+=1
elif self.A[ind][i]==1 and self.A[ind][9]==1:
num = self.A[ind][10]
region_text[num-2]+=10
site_value_text = site_value_text + self.A[ind][1]
self.A[ind][0]+=1
site_class_text = self.find_max(region_text)+2
mini_text,maxim_text,mini_link,maxim_link=0,0,0,0
text_limit_good,text_limit_bad,link_limit_good,link_limit_bad =0.25*length_link_text,-0.25*length_link_text,0.1*length_list_link_text,-0.1*length_list_link_text
if (site_value_text > text_limit_good ):
for ind,word in enumerate(self.word_list):
if word in link_text:
if(mini_text > self.A[ind][1]):
mini_text = self.A[ind][1]
if (site_value_text <=text_limit_bad ):
for ind,word in enumerate(self.word_list):
if word in link_text:
if(maxim_text < self.A[ind][1]):
maxim_text = self.A[ind][1]
for word in list_link_text:
if word in word_list_link:
ind = word_list_link.index(word)
for i in range(2,9):
if self.A[ind][i]==1 and self.A[ind][9]==0:
region_link[i-2]+=1
elif self.A[ind][i]==1 and self.A[ind][9]==1:
num = self.A[ind][10]
region_link[num-2]+=10
site_value_link = site_value_link + self.A[ind][1]
self.A[ind][0]+=1
site_class_link = self.find_max(region_link)+2
if (site_value_link > link_limit_good ):
for ind,word in enumerate(self.word_list):
if word in list_link_text:
if(mini_link > self.A[ind][1]):
mini_link = self.A[ind][1]
if (site_value_link <=link_limit_bad ):
for ind,word in enumerate(self.word_list):
if word in list_link_text:
if(maxim_link < self.A[ind][1]):
maxim_link = self.A[ind][1]
text_limit_good,text_limit_bad,link_limit_good,link_limit_bad =0.25*length_link_text,-0.25*length_link_text,0.1*length_list_link_text,-0.1*length_list_link_text
if (site_value_text > text_limit_good):
for word in link_text:
if word not in word_list_link:
word_list_link.append(word)
ind = self.word_list.index(word)
if((site_value_text > text_limit_good)and(site_value_link > link_limit_good)):
self.A[ind][1] = abs(min(mini_link,mini_text))
else:
self.A[ind][1] = -max(maxim_link,maxim_text,site_value_text,site_value_link)
f=0
for i in range(1,7):
if (region_text[i]>=1):
f=1
self.A[ind][i+2]=1
if (f==0):
self.A[ind][2]=1
if (site_value_text <= text_limit_bad):
for word in link_text:
if word not in word_list_link:
word_list_link.append(word)
ind = self.word_list.index(word)
if((site_value_text > text_limit_good)and(site_value_link > link_limit_good)):
self.A[ind][1] = abs(min(mini_link,mini_text))
else:
self.A[ind][1] = -max(maxim_link,maxim_text,site_value_text,site_value_link)
f=0
for i in range(1,7):
if (region_text[i]>=1):
f=1
self.A[ind][i+2]=1
if (f==0):
self.A[ind][2]=1
if (site_value_link > link_limit_good):
for word in list_link_text:
if word not in word_list_text:
word_list_text.append(word)
ind = self.word_list.index(word)
if((site_value_text > text_limit_good)and(site_value_link > link_limit_good)):
self.A[ind][1] = abs(min(mini_link,mini_text))
else:
self.A[ind][1] = -max(maxim_link,maxim_text,site_value_text,site_value_link)
f=0
for i in range(1,7):
if (region_link[i]>=1):
f=1
self.A[ind][i+2]=1
if (f==0):
self.A[ind][2]=1
if (site_value_link <= link_limit_bad):
for word in list_link_text:
if word not in word_list_text:
word_list_text.append(word)
ind = self.word_list.index(word)
if((site_value_text > text_limit_good)and(site_value_link > link_limit_good)):
self.A[ind][1] = abs(min(mini_link,mini_text))
else:
self.A[ind][1] = -max(maxim_link,maxim_text,site_value_text,site_value_link)
f=0
for i in range(1,7):
if (region_link[i]>=1):
f=1
self.A[ind][i+2]=1
if (f==0):
self.A[ind][2]=1
word_list_all = self.word_list
C = self.A
return region_text,region_link,length_list_link_text,length_link_text
def find_max(self,a):
maxi=0
max_index=0
for i in range(6):
if(maxi < a[i]):
maxi=a[i]
max_index = i
return max_index
def normalise(self,B):
norm_fac=0.0
for ind,word in enumerate(self.word_list):
norm_fac = norm_fac + B[ind][0]
for ind,word in enumerate(self.word_list):
B[ind][1] = (B[ind][1])/norm_fac
return B
class Bucket_Processing:
def __init__(self):
self.word_list = []
self.A = zeros([1000000,11],Float)
self.i = 0
def return_(self):
self.perform()
return self.word_list,self.A
def frequency(self,text,freq,num,factor):
word_list_temp ,word_list_tempo,links_list,word_list_temporary=[],[],[],[]
word_list_temp = str(text).lower().split(None)
for word in word_list_temp:
if word not in self.word_list:
self.word_list.append(word)
for word in word_list_temp:
freq[word] = freq.get(word, 0) + 1
keys = freq.keys()
for ind,word in enumerate(self.word_list):
try:
self.A[ind][0]= self.A[ind][0] + int(freq[word])
except Exception as e:
continue
norm_f =0.0
p=0.0
for word in freq:
norm_f = norm_f + freq[word]
for word in freq:
p= freq[word]/norm_f
freq[word]=p
for word in word_list_temp:
ind = self.word_list.index(word)
if(self.A[ind][2] == 1):
self.A[ind][2] = 0
self.A[ind][num] = 1
elif(self.A[ind][2]!=1):
self.A[ind][num] = 1
if (factor == 1):
if(self.A[ind][2]!=1):
self.A[ind][9]=1
self.A[ind][10]=num
for ind,word in enumerate(self.word_list):
try:
if(self.A[ind][2]==1):
self.A[ind][1] = self.A[ind][1] + float(freq[word])
elif(self.A[ind][2]!=1) and (self.A[ind][9]==1):
self.A[ind][1] = self.A[ind][1] - 10*float(freq[word])
elif(self.A[ind][2]!=1) and (self.A[ind][9]==0):
self.A[ind][1] = self.A[ind][1] - float(freq[word])
except Exception as e:
continue
return self.A
def perform(self):
good_word_freq,bad_porn_freq,bad_violence_freq,bad_racism_freq,bad_drugs_freq,bad_alcohol_freq,bad_tobacco_freq = {},{},{},{},{},{},{}
bad_porn,bad_violence,bad_racism,bad_drugs,bad_alcohol,bad_tobacco = {},{},{},{},{},{}
good_text,porn_text,violence_text,racism_text,drugs_text, alcohol_text,tobacco_text = [],[],[],[],[],[],[]
bad_porn_text,bad_violence_text,bad_racism_text,bad_drugs_text, bad_alcohol_text,bad_tobacco_text = [],[],[],[],[],[]
good_text = self.openandstem('good_temp.txt')
self.frequency(good_text,good_word_freq,2,0)
porn_text = self.openandstem('porn_temp.txt')
self.frequency(porn_text,bad_porn_freq,3,0)
violence_text = self.openandstem('violence_temp.txt')
self.frequency(violence_text,bad_violence_freq,4,0)
racism_text = self.openandstem('racism_temp.txt')
self.frequency(racism_text,bad_racism_freq,5,0)
drugs_text = self.openandstem('drugs_temp.txt')
self.frequency(drugs_text,bad_drugs_freq,6,0)
alcohol_text = self.openandstem('alcohol_temp.txt')
self.frequency(alcohol_text,bad_alcohol_freq,7,0)
tobacco_text = self.openandstem('tobacco_temp.txt')
self.frequency(tobacco_text,bad_tobacco_freq,8,0)
bad_porn_text = self.openandstem('porn_bad.txt')
self.frequency(bad_porn_text,bad_porn,3,1)
bad_violence_text = self.openandstem('violence_bad.txt')
self.frequency(bad_violence_text,bad_violence,4,1)
bad_racism_text = self.openandstem('racism_bad.txt')
self.frequency(bad_racism_text,bad_racism,5,1)
bad_drugs_text = self.openandstem('drugs_bad.txt')
self.frequency(bad_drugs_text,bad_drugs,6,1)
bad_alcohol_text = self.openandstem('alcohol_bad.txt')
self.frequency(bad_alcohol_text,bad_alcohol,7,1)
bad_tobacco_text = self.openandstem('tobacco_bad.txt')
self.frequency(bad_tobacco_text,bad_tobacco,8,1)
return True
def openandstem(self,file1):
path = directory.path()
doc = open(path+'/text/'+file1, 'r').read()
return Stemming().stem(doc)
class Content_Classifier_2:
def __init__(self,region_text,region_link,length_list_link_text,length_link_text):
self.region_text,self.region_link,self.length_list_link_text,self.length_link_text = region_text,region_link,length_list_link_text,length_link_text
def classify_text(self,i):
if self.length_link_text <= 800 :
if(self.region_text[i]>float(self.length_link_text)/4):
return 5
elif ((self.region_text[i]>float(self.length_link_text)/6 and self.region_text[i]<=float(self.length_link_text)/4 + 1)):
return 4
elif((self.region_text[i]<=float(self.length_link_text)/6 + 1 and self.region_text[i]>float(self.length_link_text)/8)):
return 3
elif((self.region_text[i]<=float(self.length_link_text)/8 + 1 and self.region_text[i]>float(self.length_link_text)/10)):
return 2
elif(self.region_text[i]<=float(self.length_link_text)/10 + 1):
return 1
elif self.length_link_text >800 :
if(self.region_text[i]>133):
return 5
elif (self.region_text[i]>100 and self.region_text[i]<=133):
return 4
elif(self.region_text[i]<=100 and self.region_text[i]>80):
return 3
elif(self.region_text[i]<=80 and self.region_text[i]>66):
return 2
elif(self.region_text[i]<=66):
return 1
def classify_link(self,i):
if self.length_list_link_text <=800:
if (self.region_link[i]>float(self.length_list_link_text)/4):
return 5
elif((self.region_link[i]>float(self.length_list_link_text)/6 and self.region_link[i]<=float(self.length_list_link_text)/4 + 1)):
return 4
elif((self.region_link[i]<=float(self.length_list_link_text)/6 + 1 and self.region_link[i]>float(self.length_list_link_text)/8)):
return 3
elif((self.region_link[i]<=float(self.length_list_link_text)/8 + 1 and self.region_link[i]>float(self.length_list_link_text)/10)):
return 2
elif(self.region_link[i]<=float(self.length_list_link_text)/10 + 1):
return 1
elif self.length_list_link_text >800:
if (self.region_link[i]>133):
return 5
elif(self.region_link[i]>100 and self.region_link[i]<=133):
return 4
elif(self.region_link[i]<=100 and self.region_link[i]>80):
return 3
elif(self.region_link[i]<=80 and self.region_link[i]>66):
return 2
elif(self.region_link[i]<=66):
return 1
class ContentAnalyzer_Utils:
def __init__(self,string,html,links):
self.string = string
self.html = html
self.links = links
self.k = 0
self.timeout =10
socket.setdefaulttimeout(self.timeout)
def read_text(self):
seed_list = []
pure_text = nltk.util.clean_html(self.html)
stemmed_text = Stemming().stem(pure_text)
seed_list = self.links
link_stemmed_text = Stemming().stem(self.fetch_page())
return stemmed_text,link_stemmed_text,self.k
def fetch_page(self):
link_pure_text = []
for seed in self.links:
if 'http://' or 'https://'or 'www'in seed:
seed = seed
elif len(seed)<15:
seed = str(self.string.strip('\n'))+'/'+str(seed)
try:
self.k = self.k + 1
if self.k==3:
self.k = 0
break
t = Test()
c = pycurl.Curl()
c.setopt(pycurl.MAXREDIRS, 3)
c.setopt(pycurl.CONNECTTIMEOUT, 5)
c.setopt(pycurl.TIMEOUT, 5)
c.setopt(pycurl.HEADER, 1)
c.setopt(pycurl.NOSIGNAL, 1)
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.URL,seed)
c.setopt(pycurl.WRITEFUNCTION,t.body_callback)
c.perform()
c.close()
link_pure_text.append(nltk.util.clean_html(t.contents))
except Exception as e:
continue
return link_pure_text
class Test:
def __init__(self):
self.contents = ''
def body_callback(self, buf):
self.contents = self.contents + buf
class Stemming:
def __init__(self):
pass
def stem(self,input_text):
tokenizer = RegexpTokenizer('\s+', gaps=True)
stemmed_text=[]
lemmatizer = WordNetLemmatizer()
stemmer = PorterStemmer()
text = tokenizer.tokenize(str(input_text))
filtered_text = self.stopword(text)
for word in filtered_text:
if word.isalpha():
if len(word)>4:
stemmed_text.append(stemmer.stem_word(word).lower())
else:
stemmed_text.append(word.lower())
for word in stemmed_text:
if len(word) < 3 :
stemmed_text.remove(word)
' '.join(stemmed_text)
return stemmed_text
def stopword(self,text):
filtered_text = text[:]
stopset = set(stopwords.words('english'))
for word in text:
if len(word) < 3 or word.lower() in stopset:
filtered_text.remove(word)
return filtered_text
class ContentAnalyzer:
def __init__(self):
global data1,data2,i,class1,class2
data2 = zeros([12],int)
class2 = zeros([12],int)
i = 0
def Advanced(self,string,html,link):
start_time = time.time()
global i
global j
global data2
global class2
if(i==0):
stemmed_text,link_stemmed_text,c = ContentAnalyzer_Utils(string,html,link).read_text()
path = directory.path()
doc = open(path+'/text/'+'news.txt', 'r').read()
self.news_list = Stemming().stem(doc)
doc = open(path+'/text/'+'games.txt', 'r').read()
self.games_list = Stemming().stem(doc)
doc = open(path+'/text/'+'medicine.txt', 'r').read()
self.med_list = Stemming().stem(doc)
pickle.dump(stemmed_text, open('pfile_text.p','wb'))
pickle.dump(link_stemmed_text,open('pfile_link.p','wb'))
region_text,region_link,length_list_link_text,length_link_text = Bayesian(i,c).learning()
p = Content_Classifier_2(region_text,region_link,length_list_link_text,length_link_text)
k = 0
sitecounter = 0
for u in range(1,7):
data2[k] = p.classify_text(u)
k = k + 1
data2[k] = p.classify_link(u)
k = k + 1
i = 1
elif(i==1):
stemmed_text,link_stemmed_text,c = ContentAnalyzer_Utils(string,html,link).read_text()
pickle.dump(stemmed_text, open('pfile_text.p','wb'))
pickle.dump(link_stemmed_text,open('pfile_link.p','wb'))
region_text,region_link,length_list_link_text,length_link_text = Bayesian(i,c).learning()
p = Content_Classifier_2(region_text,region_link,length_list_link_text,length_link_text )
k = 0
sitecounter = 0
for u in range(1,7):
data2[k] = p.classify_text(u)
k = k + 1
data2[k] = p.classify_link(u)
k = k + 1
s = []
s[:] = data2
value = self.check_advanced(data2,stemmed_text)
if(sum(data2) !=12):
value = value + ' ' +self.reason(data2)
elif(sum(data2) == 12):
value = 'SAFE'
if sum(data2)==0 and len(stemmed_text) <=20: value = "Not-Enough-Text-on-Site"
elif len(stemmed_text)==0 : value = "ERROR"
return s, value
def check_advanced(self,data,stemmed_text):
news,games,med=0,0,0
if data[2]>2 and sum(data)==11+data[2]:
for word in self.news_list:
if word in stemmed_text:
news+=1
for word in self.games_list:
if word in stemmed_text:
games+=1
if(news >=15):
return "News-Site"
elif(games >=15):
return "Games-Site"
elif (data[6]>2 or data[7]>2) and (sum(data)==10+data[6]+data[7] or sum(data)==11+data[6]):
for word in self.med_list:
med+=1
if(med >=15):
return "Medicines"
else:
return "No-Remark"
def find_max(self,a):
maxi=0
max_index=0
for i in range(12):
if(maxi < a[i]):
maxi=a[i]
max_index = i
return max_index
def reason(self,data):
class_bad = ['Porn','Violence','Racism','Drugs/Medicine','Alcohol','Tobacco']
max_ind = self.find_max(data)
return class_bad[int(max_ind)/2]
|
36a351dac11e166e8618ac602a3e7494029a1e90 | ckidckidckid/leetcode | /LeetCodeSolutions/775.global-and-local-inversions.python3.py | 2,859 | 3.625 | 4 | #
# [790] Global and Local Inversions
#
# https://leetcode.com/problems/global-and-local-inversions/description/
#
# algorithms
# Medium (33.05%)
# Total Accepted: 5.8K
# Total Submissions: 17.6K
# Testcase Example: '[0]'
#
# We have some permutation A of [0, 1, ..., N - 1], where N is the length of
# A.
#
# The number of (global) inversions is the number of i < j with 0 <= i < j < N
# and A[i] > A[j].
#
# The number of local inversions is the number of i with 0 <= i < N and A[i] >
# A[i+1].
#
# Return true if and only if the number of global inversions is equal to the
# number of local inversions.
#
# Example 1:
#
#
# Input: A = [1,0,2]
# Output: true
# Explanation: There is 1 global inversion, and 1 local inversion.
#
#
# Example 2:
#
#
# Input: A = [1,2,0]
# Output: false
# Explanation: There are 2 global inversions, and 1 local inversion.
#
#
# Note:
#
#
# A will be a permutation of [0, 1, ..., A.length - 1].
# A will have length in range [1, 5000].
# The time limit for this problem has been reduced.
#
#
from bisect import bisect_left, insort
class Solution:
def isIdealPermutation(self, A):
"""
:type A: List[int]
:rtype: bool
"""
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Idea : to check if local inversions can keep up with global inversion
# Extremely fast solution at
# https://leetcode.com/problems/global-and-local-inversions/discuss/113651/Python-easy-understanding-solution!
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
n = len(A)
for i in range(n):
if abs(i-A[i]) > 1:
return False
return True
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Generalized solution; O(n) time https://leetcode.com/problems/global-and-local-inversions/discuss/113661/Generalize-to-any-integer-array-(not-necessarily-a-0-greaterN-permutation)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# n = len(A)
# if n <= 1:
# return True
# i=1
# while i < n:
# if A[i-1] > A[i]:
# A[i-1], A[i] = A[i], A[i-1]
# i+=1
# i+=1
# for i in range(1,n):
# if A[i] < A[i-1]:
# return False
# return True
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# O(nlogn) solution
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# n = len(A)
# A.append(n)
# li = gi = 0
# seen = [n]
# for i in range(n-1,-1,-1):
# li += A[i] > A[i+1]
# gi += bisect_left(seen, A[i])
# insort(seen, A[i])
# return li == gi
|
7af9fce1d6e929f46ac252eee91ed59a53cf63fe | ArunkumarRamanan/CLRS-1 | /ProgrammingInterviewQuestions/34_HeapMax.py | 6,098 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 02 21:24:40 2016
@author: Rahul Patni
"""
# heap sort
import random
class HeapMin():
def __init__(self):
self.array = [None] * 30
self.start = 0
self.end = 0
def insert(self, val):
self.array[self.end] = val
self.end += 1
currIndex = self.end
parentIndex = currIndex / 2
#print "out", currIndex, parentIndex
parent = self.array[parentIndex - 1]
#print val, parent
while val < parent and parentIndex > 0:
#print "parent", "child", parentIndex - 1, currIndex - 1
#print self.array[parentIndex - 1], self.array[currIndex - 1]
self.array[parentIndex - 1], self.array[currIndex - 1] = self.array[currIndex - 1], self.array[parentIndex - 1]
currIndex = parentIndex
parentIndex = currIndex / 2
parent = self.array[parentIndex - 1]
return
def checkHeapProperty(self):
currIndex = self.end
parentIndex = currIndex / 2
while parentIndex > 0:
if self.array[parentIndex - 1] > self.array[currIndex - 1]:
print "not equal at", parentIndex - 1, currIndex - 1, "values", self.array[parentIndex - 1], self.array[currIndex - 1]
currIndex -= 1
parentIndex = currIndex / 2
return
def extractMin(self):
if self.end == 0:
return None
toRemove = self.array[0]
self.end -= 1
self.array[0] = self.array[self.end]
self.array[self.end] = None
currIndex = 1
child1Index = currIndex * 2
child2Index = currIndex * 2 + 1
while child1Index <= self.end:
#while child1Index <= self.end and (self.array[currIndex - 1] > self.array[child1Index - 1] or self.array[currIndex - 1] > self.array[child2Index - 1]):
if child2Index > self.end:
child2Index = child1Index
if (self.array[currIndex - 1] > self.array[child1Index - 1] or self.array[currIndex - 1] > self.array[child2Index - 1]):
if self.array[child1Index - 1] <= self.array[child2Index - 1]:
self.array[child1Index - 1], self.array[currIndex - 1] = self.array[currIndex - 1], self.array[child1Index - 1]
currIndex = child1Index
child1Index = currIndex * 2
child2Index = currIndex * 2 + 1
else:
self.array[child2Index - 1], self.array[currIndex - 1] = self.array[currIndex - 1], self.array[child2Index - 1]
currIndex = child2Index
child1Index = currIndex * 2
child2Index = currIndex * 2 + 1
else:
child1Index = self.end + 1
self.checkHeapProperty()
return toRemove
class HeapMax():
def __init__(self):
self.array = [None] * 30
self.start = 0
self.end = 0
def insert(self, val):
self.array[self.end] = val
self.end += 1
currIndex = self.end
parentIndex = currIndex / 2
#print "out", currIndex, parentIndex
parent = self.array[parentIndex - 1]
#print val, parent
while val > parent and parentIndex > 0:
#print "parent", "child", parentIndex - 1, currIndex - 1
#print self.array[parentIndex - 1], self.array[currIndex - 1]
self.array[parentIndex - 1], self.array[currIndex - 1] = self.array[currIndex - 1], self.array[parentIndex - 1]
currIndex = parentIndex
parentIndex = currIndex / 2
parent = self.array[parentIndex - 1]
return
def checkHeapProperty(self):
currIndex = self.end
parentIndex = currIndex / 2
while parentIndex > 0:
if self.array[parentIndex - 1] < self.array[currIndex - 1]:
print "not equal at", parentIndex - 1, currIndex - 1, "values", self.array[parentIndex - 1], self.array[currIndex - 1]
currIndex -= 1
parentIndex = currIndex / 2
return
def extractMax(self):
if self.end == 0:
return None
toRemove = self.array[0]
self.end -= 1
self.array[0] = self.array[self.end]
self.array[self.end] = None
currIndex = 1
child1Index = currIndex * 2
child2Index = currIndex * 2 + 1
while child1Index <= self.end:
#while child1Index <= self.end and (self.array[currIndex - 1] > self.array[child1Index - 1] or self.array[currIndex - 1] > self.array[child2Index - 1]):
if child2Index > self.end:
child2Index = child1Index
if (self.array[currIndex - 1] < self.array[child1Index - 1] or self.array[currIndex - 1] < self.array[child2Index - 1]):
if self.array[child1Index - 1] >= self.array[child2Index - 1]:
self.array[child1Index - 1], self.array[currIndex - 1] = self.array[currIndex - 1], self.array[child1Index - 1]
currIndex = child1Index
child1Index = currIndex * 2
child2Index = currIndex * 2 + 1
else:
self.array[child2Index - 1], self.array[currIndex - 1] = self.array[currIndex - 1], self.array[child2Index - 1]
currIndex = child2Index
child1Index = currIndex * 2
child2Index = currIndex * 2 + 1
else:
child1Index = self.end + 1
self.checkHeapProperty()
return toRemove
def main():
h = HeapMax()
for i in range(20):
val = random.randint(10, 90)
print val
h.insert(val)
print h.array
h.checkHeapProperty()
print h.array
while h.end != 0:
val = h.extractMax()
print val
print h.array
main() |
dd38832fca9b24df5e41102af6cc2417e8cf93fe | jordanvtskier12/Picture | /picture.py | 1,860 | 3.96875 | 4 | """
picture.py
Author: Jordan Gottlieb
Credit: None
Assignment: Picture
Use the ggame library to "paint" a graphical picture of something (e.g. a house, a face or landscape).
Use at least:
1. Three different Color objects.
2. Ten different Sprite objects.
3. One (or more) RectangleAsset objects.
4. One (or more) CircleAsset objects.
5. One (or more) EllipseAsset objects.
6. One (or more) PolygonAsset objects.
See:
https://github.com/HHS-IntroProgramming/Standards-and-Syllabus/wiki/Displaying-Graphics
for general information on how to use ggame.
See:
http://brythonserver.github.io/ggame/
for detailed information on ggame.
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset
# add your code here \/ \/ \/
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
thinline = LineStyle(1, black)
#sky
rectangle2=RectangleAsset(1000,1000, thinline, blue)
Sprite(rectangle2)
#Grass
rectangle3=RectangleAsset(1000,500,thinline,green)
Sprite(rectangle3,(0,300))
#house
rectangle = RectangleAsset(500, 200, thinline, red)
Sprite(rectangle, (100, 200))
#roof
triangle=PolygonAsset([(300,50),(550,200),(50,200)], thinline, green)
Sprite(triangle, (100, 50))
#window
circle=CircleAsset(30,thinline,black)
Sprite(circle,(200,280))
#window2
ellipse=EllipseAsset(30,30,thinline,black)
Sprite(ellipse,(450,280))
#door
rectangle4=RectangleAsset(50,100,thinline,black)
Sprite(rectangle4,(330,300))
#wall
wall=PolygonAsset([(200,500),(550,400),(550,200),(200,300)], thinline, red)
Sprite(wall,(600,100))
#roof
roof2=PolygonAsset([(0,50),(250,200),(600,100),(400,0),(230,0)], thinline, green)
Sprite(roof2,(350,0))
#window top
windowtop=EllipseAsset(50,30,thinline,black)
Sprite(windowtop,(300,120))
# add your code here /\ /\ /\
myapp = App()
myapp.run()
|
9cc0e4dac8a70502d3e0e707e62f93a86c96600e | crisrm96/Python-ejercicios1 | /while.py | 89 | 3.890625 | 4 | count = 0
while count <=3:
print ("I love learning Python!")
count = count + 1 |
cc2b401fd164dbf299a922f2533fbdf510f3796f | RenaldoDaVinci/SwitchNE | /Switch/TestFolders/testnormal.py | 966 | 3.6875 | 4 | import numpy as np
Output = np.random.rand(8,8)
F = 0
#Tolerance. if set 0.5, it considers any output that has more than 50% of the highest current as "non-distinguishable"
threshold = 0.5
#Criteria 1
TransOutput = np.transpose(Output)
for a in range(len(Output)):
count = 0
tempout = TransOutput[a]
maxi = max(tempout)
for b in range(len(Output[a])):
#If the read current is higher than the threshold, add 1 to the count
if (TransOutput[a,b]/maxi) > threshold:
count = count + 1
#if only one output was HIGH for the given input, that's success!
if count == 1:
F = F + 3
#if more than 1 output was HIGH for the given input, we give -1 for the number of outputs that were HIGH
elif count > 1:
F = F+ -1*count
#if no output was HIGH for a particular input, we either have to lower the threshold, or just punish the fitness score
elif count == 0:
F = F - 10
print(F) |
16db71161221cd94621a8eccb856afe745134390 | ianlaiky/SITUniPython1002 | /Lab4/Task1/SumCalculator.py | 349 | 3.984375 | 4 | import sys
a = int(sys.argv[1])
def sum_recursive(x):
if x == 0:
return x
else:
return sum_recursive(x-1)+x
def sum_iterative(x):
out = 0
for i in range(x):
out += i+1
return out
print "The SUM value calculated by recursive is "+str(sum_recursive(a))+" and by iterative is "+str(sum_iterative(a)) +"." |
0a66b9c47d91a975af3269b06a2e830d41671010 | kyousuke-s/PythonTraining | /day0204/code6_3.py | 965 | 3.84375 | 4 | userinfo = input('名前と血液型をカンマで区切って1行で入力>>')
[name,blood]=userinfo.split(',')
blood=blood.upper().strip()
print('{}さんは{}型なので大吉です'.format(name,blood))
#小数点の桁
print('{:.1f}'.format(2.342))
#リストの中身を指定した文字で連結
l1=['1','2','3']
print('&'.join(l1))
#指定した文字が何回含まれているか
str='abacadaeafag'
print(str.count('a'))
#左側で指定した文字を右側の文字に置き換え
print(str.replace('a','&'))
#文字列もシーケンスの為for文で回せる
for s in 'hello': #一文字ずつ書き出し
print(s)
#シーケンスの内容をインデックス付きで取り出す
for i,s in enumerate('hello',1):
print('{}文字目は{}です'.format(i,s))
s1='hello'
#リストに一文字ずつ逆順に格納
s2=list(reversed(s1))
print(s2)
print(''.join(s2))
#文字列を逆順にする
s3=s1[::-1]
print(s3)
print(len(s1))
|
24f7713059fe1b7d4b6c32b5973a22c69d93cfeb | justinegwudo/Turtle_Projects | /turtle race.py | 838 | 3.859375 | 4 | import turtle
import random
justin = turtle.Turtle()
justin.color("black")
justin.pensize(10)
justin.shape("turtle")
colors = ["red", "blue", "green", "yellow", "black"]
def left():
justin.setheading(180)
justin.forward(100)
def right():
justin.setheading(0)
justin.forward(100)
def up():
justin.setheading(90)
justin.forward(100)
def down():
justin.setheading(270)
justin.forward(100)
def clickleft(x, y):
justin.color(random.choice(colors))
def clickright(x, y):
justin.stamp()
# listen for user input
turtle.listen()
# listen for click
turtle.onscreenclick(clickleft, 1)
turtle.onscreenclick(clickright, 3)
# listen, we are looking for arrow key input
turtle.onkey(left, "Left")
turtle.onkey(right, "Right")
turtle.onkey(up, "Up")
turtle.onkey(down, "Down")
turtle.mainloop()
|
26f4b411c7906aa7da91e145e8f5f7ac5c089d62 | SoumendraM/GeekForGeeksDSA5 | /Mathematics/PrimeFactors.py | 753 | 3.796875 | 4 | def PrimeFactors(num):
if num == 1:
return 1
i = 2
while i*i <= num:
while num%i == 0:
print(i, end = ' ')
num = int(num/i)
i += 1
if num > 1:
print(num)
def PrimeFactorsEff(num):
if num == 1:
return 1
for i in (2, 3):
while num % i == 0:
print(i, end=' ')
num = int(num/i)
i = 5
while i*i <= num:
while num%i == 0:
print(i, end = ' ')
num = int(num/i)
while num%(i+2) == 0:
print(i+2, end = ' ')
num = int(num/(i+2))
i += 6
if num > 1:
print(num)
if __name__ == '__main__':
PrimeFactorsEff(1749150) |
812d34a3b9c4bc4b927776ce2172071aeb361592 | gabrielavirna/python_data_structures_and_algorithms | /my_work/ch5_hashing_and_symbol_tables/hashing.py | 2,602 | 3.71875 | 4 | """
Hashing and Symbol Tables
-------------------------
Lists vs Dictionary
-> Lists:
- items are stored in sequence and accessed by index number
- Index numbers work well for computers; They are integers so they are fast and easy to manipulate.
However - If we have an address book entry, with index number 56, that number doesn't tell us much. There is nothing to
link a particular contact with number 56. It just happens to be the next available position in the list.
-> Dictionary
- a similar structure; a dictionary uses a keyword instead of an index number. So, if that contact was called James,
we would probably use the keyword James to locate the contact. That is, instead of accessing the contact by calling
contacts [56], we would use contacts ["james"].
- often built using hash tables; hash tables rely on a concept called hashing
Hashing
-------
- the concept of converting data of arbitrary size into data of fixed size:
used this to turn strings (or possibly other data types) into integers
E.g. hash the expression hello world <=> get a numeric value that represents the string
- ord() function: get the ordinal value of any character
To get the hash of the whole string, sum the ordinal numbers of each character in the string:
(If the order of the characters in the string is changed, we still get the same hash for both different strings)
sum(map(ord, 'world hello')) => 1116 (same as sum(map(ord, 'hello world')))
since >>> ord('f') => 102; ord('g') => 103; ord('w') => 119; ord('x') => 120
sum(map(ord, 'hello world')) => 116 (same as sum(map(ord, 'gello xorld')
Perfect hashing functions
-------------------------
- one function in which each string is guaranteed to be unique
In practice, hashing functions need to be very fast => creating a function that will give each string a unique
hash value is normally not possible. Instead, we sometimes get collisions (2/more strings having the same hash value).
We need a strategy for resolving collisions. To avoid some of the collisions: Add a multiplier => see myhash() function.
"""
def my_hash(s):
multiplier = 1
hash_value = 0
for ch in s:
# hash value for each character becomes the multiplier value * the ordinal value of the character
hash_value += multiplier * ord(ch)
# The multiplier then increases as we progress through the string
multiplier += 1
return hash_value
# This time we get different hash values for our strings
for item in ('hello world', 'world hello', 'gello xord'):
print("{}: {}".format(item, my_hash(item)))
|
51e6c8e600365aef7e1f7a91e7d3af4e5ae4d991 | aafonya/Code-Python-Java | /Code/codecool/python basics/100Doors2.py | 523 | 3.734375 | 4 | #Create a list#
doors = []
#Fullfill the list#
#False - Door is closed#
for i in range(0,101):
doors.append(False)
# j - number of the cycle - e.g. in the 2nd cycle every second door will change#
# i - index of the door#
for j in range(1,101):
for i in range(1,101):
if i%j == 0:
doors[i] = not doors[i]
print(doors)
#searching every True element (opened door) in the list and print their indexes#
for i in range(1,101):
if doors[i] == True:
print(i)
|
2030a4bc2d4ffa4dff5f954eb4e5f527c9819511 | giselachen/Boston-OpenStreetMap-data | /check_file_size.py | 870 | 3.515625 | 4 | import os
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
reference: http://stackoverflow.com/questions/2104080/how-to-check-file-size-in-python
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0
print "boston_massachusetts.osm: " + convert_bytes(os.path.getsize('boston_massachusetts.osm'))
print "small_sample.osm: " + convert_bytes(os.path.getsize('small_sample.osm'))
print "nodes.csv: " + convert_bytes(os.path.getsize('nodes.csv'))
print "nodes_tags.csv: " + convert_bytes(os.path.getsize('nodes_tags.csv'))
print "ways.csv: " + convert_bytes(os.path.getsize('ways.csv'))
print "ways_tags.csv: " + convert_bytes(os.path.getsize('ways_tags.csv'))
print "ways_nodes.csv: " + convert_bytes(os.path.getsize('ways_nodes.csv'))
|
3cccbcf4d4a007a7a0512d6ab3f01c9ed5a2e664 | macd/rogues | /rogues/matrices/comp.py | 1,429 | 3.9375 | 4 | import numpy as np
def comp(a, k=0):
"""
COMP Comparison matrices.
comp(a) is diag(b) - tril(b,-1) - triu(b,1), where b = abs(a).
comp(a, 1) is a with each diagonal element replaced by its
absolute value, and each off-diagonal element replaced by minus
the absolute value of the largest element in absolute value in
its row. however, if a is triangular comp(a, 1) is too.
comp(a, 0) is the same as comp(a).
comp(a) is often denoted by m(a) in the literature.
Reference (e.g.):
N.J. Higham, A survey of condition number estimation for
triangular matrices, SIAM Review, 29 (1987), pp. 575-596.
"""
m, n = a.shape
p = min(m, n)
if k == 0:
# This code uses less temporary storage than the `high level'
# definition above. (well, maybe... not clear that this is so
# in numpy as opposed to m*lab)
c = -abs(a)
for j in range(p):
c[j, j] = np.abs(a[j, j])
elif k == 1:
c = a.T
for j in range(p):
c[k, k] = 0
mx = np.empty(p)
for j in range(p):
mx[j] = max(abs(c[j, :]))
c = -np.outer(mx * np.ones(n))
for j in range(p):
c[j, j] = abs(a[j, j])
if (a == np.tril(a)).all():
c = np.tril(c)
if (a == np.triu(a)).all():
c = np.triu(c)
return c
|
0d350c6c0ff12df5a052f2a865fbe61119f15167 | BlerinaAliaj/coding-challenges | /largest_sub_zig_zag.py | 1,687 | 4.15625 | 4 | """A sequence of integers is called a zigzag sequence if each of its elements is either strictly less than both neighbors or strictly greater than both neighbors. For example, the sequence 4 2 3 1 5 3 is a zigzag, but 7 3 5 5 2 and 3 8 6 4 5 aren't.
For a given array of integers return the length of its longest contiguous sub-array that is a zigzag sequence.
Example
For a = [9, 8, 8, 5, 3, 5, 3, 2, 8, 6], the output should be
zigzag(a) = 4.
The longest zigzag sub-arrays are [5, 3, 5, 3] and [3, 2, 8, 6] and they both have length 4.
Input/Output
[time limit] 4000ms (py)
[input] array.integer a
Guaranteed constraints:
2 <= a.length <= 25,
0 <= a[i] <= 100.
[output] integer
"""
def longest_sub(arr):
"""Return the length of the longest zig-zag sub array"""
if not arr:
return 0
longest = 1
sub_arr = [arr[0]]
if len(arr) == 2 and arr[0] != arr[-1]:
return len(arr)
for i in range(1, len(arr)-1):
if (arr[i] > arr[i-1] and arr[i] > arr[i+1]) or (arr[i] < arr[i-1] and arr[i] < arr[i+1]):
if i == len(arr)-2:
sub_arr.append(arr[i])
sub_arr.append(arr[i+1])
else:
sub_arr.append(arr[i])
longest = len(sub_arr)
else:
sub_arr.append(arr[i])
longest = max(longest, len(sub_arr))
sub_arr = [arr[i]]
return longest
def test():
assert longest_sub([9, 8, 8, 5, 3, 5, 3, 2, 8, 6]) == 4
assert longest_sub([1, 2, 0, 3, 2, 1, 3, 2, 4, 0]) == 6
assert longest_sub([1, 2, 1]) == 3
assert longest_sub([1, 2]) == 2
assert longest_sub([1, 1]) == 1
assert longest_sub([]) == 0
test()
|
96c84ac477f88335f6a640d2eb423191f35625cb | 2016JTM2098/jtm162098_7 | /ps2.py | 795 | 3.78125 | 4 | #----------------------------------- PROBLEM STATEMENT 2 -------------------------------------------
import random
ic=0
oc=0
#----------------------------------- RANDOM NUMBER GENERATOR -----------------------------------------
for i in range(10):
(x,y)=(random.random()*2-1, random.random()*2- 1)
print x,y
if (x*x + y*y) < 1:
print "Inside circle"
ic+=1
else:
print "Outside Circle"
oc+=1
#------------------------------------- CALCULATING INSIDE/OUTSIDE POINTS --------------------------------
print "*********************************"
print "Number of points inside circle",ic
print "Number of points outside circle",oc
print "**********************************"
#-------------------------------------- END OF SCRIPT ----------------------------------------------------
|
51f1284ce136e87ebfacef65ca88e9597e166f3a | teddy4445/covid-19-data-science-sample-project | /data_getter.py | 2,270 | 3.578125 | 4 | # library imports
import os
import json
import requests
from datetime import datetime
# project imports
class DataGetter:
"""
What this class does
"""
api_domain = "https://api.covid19api.com"
def __init__(self):
pass
@staticmethod
def get_all_data() -> dict:
"""
:return: summery of the data as json
"""
return DataGetter._save_load_data(path="data/summery_json.json",
url=DataGetter.api_domain + '/summary')
@staticmethod
def get_country_data(country_code: str,
from_date: datetime,
to_date: datetime) -> dict:
"""
:return: the data of a specific country between two dates
"""
print("Get Country data for: {}".format(country_code))
return DataGetter._save_load_data(path="data/country_{}.json".format(country_code),
url="{}/country/{}?from={}T00:00:00Z&to={}T00:00:00Z".format(DataGetter.api_domain,
country_code,
from_date.strftime("%Y-%m-%d"),
to_date.strftime("%Y-%m-%d")))
@staticmethod
def _save_load_data(path: str,
url: str) -> dict:
"""
:param path: the path of the file to save \ load data
:param url: the url to get the data from
:return: the data from the file or the api call
"""
if os.path.exists(path):
with open(path, "r") as data_file:
answer_json_summery = json.load(data_file)
else:
# get data from api
answer_json_summery = json.loads(requests.get(url=url).text)
# save it for later use
with open(path, "w") as data_file:
json.dump(answer_json_summery, data_file, indent=4, sort_keys=True)
# return the data
return answer_json_summery
|
9868cff52a463c4d7136a48b8439adea34141ae0 | smmvalan/Python-Learning | /W3resource_Exc/avg.py | 358 | 3.96875 | 4 |
def average ():
total = 0
count = 0
while True :
inp = float(input('Enter a number: '))
if inp == 'done' :
break
value = inp
total = total + value
count = count + 1
avg = total / count
print ("Average {}\nCount {}".format(avg,count))
def main():
average()
main()
|
0bb96f28961e335573bc018f4ac04d2e58b282a5 | irajdeep/DSALearnings | /Trie/trie.py | 1,399 | 3.859375 | 4 | class TrieNode:
def __init__(self):
self.isLeaf = False
self.children = [None] * 26
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
nav = self.root
lens = len(word)
for pos, ch in enumerate(word):
index = ord(ch) - ord('a')
if nav.children[index] is None:
nav.children[index] = TrieNode()
nav = nav.children[index]
if pos == lens - 1:
nav.isLeaf = True
return False
def search(self, word: str) -> bool:
nav = self.root
lens = len(word)
for pos, ch in enumerate(word):
index = ord(ch) - ord('a')
if nav.children[index] is None:
return False
nav = nav.children[index]
if pos == lens - 1:
if nav.isLeaf == True:
return True
return False
def startsWith(self, prefix: str) -> bool:
nav = self.root
for ch in prefix:
index = ord(ch) - ord('a')
if nav.children[index] is None:
return False
nav = nav.children[index]
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
|
f0e332383d74471fbcaa58cf7add5ec67eb06d3e | guipw2/python_exercicios | /ex059.py | 1,431 | 4.0625 | 4 | n1 = float(input('Primeiro valor:'))
n2 = float(input('Segundo valor:'))
opçao = 0
maior = 0
menor = 0
while opçao != 7:
print(''' [ 1 ] somar
[ 2 ] multiplicar
[ 3 ] maior
[ 4 ] menor
[ 5 ] novos números
[ 6 ] elevar o numero
[ 7 ] sair do programa''')
opçao = int(input('>>>>> Qual é a sua opção?'))
if opçao == 1:
print(f'A soma entre {n1} + {n2} é {n1 + n2}')
print(10 * '=-=')
elif opçao == 2:
print(f'O resultado de {n1} x {n2} é {n1 * n2}')
print(10 * '=-=')
elif opçao == 3:
if n1 > n2:
maior = n1
elif n2 > n1:
maior = n2
print(f'Entre {n1} e {n2} o maior é {maior}')
print(10 * '=-=')
elif opçao == 4:
if n1 < n2:
menor = n1
elif n2 < n1:
menor = n2
print(f'Entre {n1} e {n2} o menor é {menor}')
print(10 * '=-=')
elif opçao == 5:
print('Informe os número novamente:')
n1 = float(input('Primeiro valor:'))
n2 = float(input('Segundo valor:'))
print(10 * '=-=')
elif opçao == 6:
print(f'{n1} elevado a {n2} é igual a {pow(n1, n2)}')
elif opçao == 7:
print('Finalizando...')
sleep(1.5)
print(10 * '=-=')
else:
print('Opção inválida. Tente novamente!')
print(10 * '=-=')
print('Fim do programa! Volte sempre!')
|
7e5f1a8de34fde5f9dbdc8970afe6af6764914f5 | OskarJermakowicz/DailyProgrammer | /src/321e/talking_clock.py | 1,083 | 3.90625 | 4 | import time
hrs = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve"]
mins = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fiveteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "thirty", "fourty", "fifty"]
hrs.extend(hrs)
def clock(in_time):
out_time = "It's "
out_time += hrs[int(in_time[:2])-1] + " "
if int(in_time[3:]) % 10 == 0 and in_time[3:] != "00":
out_time += mins[17 + int(in_time[3])] + " "
elif int(in_time[3:]) % 10 != 0 and int(in_time[3:]) > 0:
out_time += "oh "
if int(in_time[3]) > 1:
out_time += mins[17 + int(in_time[3])] + " "
out_time += mins[int(in_time[4:]) - 1] + " "
out_time += "am" if int(in_time[:2]) < 12 else "pm"
return out_time
def main():
start_time = time.time()
print("Enter a time:")
print(clock(input()))
print("\nExecution time: %s seconds" % (time.time() - start_time))
if __name__ == "__main__":
main() |
3446ebd596dbc5a14f98563899e47d7507aae56b | ZJU-PLP/learnPythonHardWay4th | /exercise/exercise40.py | 883 | 4.15625 | 4 |
# -*- coding: utf-8 -*-
# @Time : 2018/7/4 0004 15:51
# @Author : Lingpeng Peng
# @FileName: exercise40.py
# @Description: dictionary or dict
# @GitHub :https://github.com/ZJU-PLP
# @Comment : Tab == 4 spaces
cities = {'CA': 'San Fransisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
def find_city(themap, state):
if state in themap:
return themap[state]
else:
return "Not found."
# add for-loop
for key in cities:
print(key, cities[key])
print(cities.items())
# print(cities[key].items())
# ok pay attention!
cities['_find'] = find_city
while True:
print("State?(Enter to quit)",)
state = input("> ")
if not state: break
# this line is most important ever! study!
city_found = cities['_find'](cities, state)
print(city_found)
# print(cities[1])
|
a4b9a52bb30134ef4f9c9a5fecd1abec4387e7fb | tiandiyijian/CTCI-6th-Edition | /08.05.py | 457 | 3.625 | 4 | class Solution:
def multiply(self, A: int, B: int) -> int:
def mul(small, big):
if small == 1:
return big
s = small >> 1
half = mul(s, big)
if small & 1 == 1:
return big + half + half
else:
return half + half
if A > B:
A, B = B, A
return mul(A, B)
if __name__ == "__main__":
s = Solution()
print()
|
57e0b8bd4f8a897a615a1c4c01effdae679412d8 | Sohamthesupercoder/Project-149 | /project 149.py | 757 | 3.796875 | 4 | from tkinter import *
root = Tk()
root.title("Project 148")
root.geometry("400x400")
import random
text_1 = Label(root)
text_1.place(relx = 0.5 , rely = 0.5 , anchor = CENTER)
def makeword():
alpha = ["A" , "B" , "C" , "D" , "E" , "F" , "G" , "H" , "I" , "J" , "L" , "M" , "N" , "O" , "P" , "Q" , "R" , "S" , "T" , "U" , "V" , "W" , "X" , "Y" , "Z"]
rand1 = random.randint(0 , 25)
rand2 = random.randint(0 , 25)
rand3 = random.randint(0 , 25)
rand4 = random.randint(0 , 25)
rand5 = random.randint(0 , 25)
alpha1 = alpha[rand1]
alpha2 = alpha[rand2]
alpha3 = alpha[rand3]
alpha4 = alpha[rand4]
alpha5 = alpha[rand5]
button = Button(root , text = "Generate Random Word" , command = makeword)
root.mainloop() |
2ee87a2df272bf9d632163b8106cc0fd3870ddbb | ujn7843/AlgorithmQIUZHAO | /Week_06/select_sort.py | 375 | 3.578125 | 4 | import sys
def selectsort(nums):
max_ind = 0
n = len(nums)
for i in range(n):
_max = -sys.maxsize - 1
for j in range(0, n - i):
if nums[j] > _max:
_max = nums[j]
max_ind = j
nums[n - i - 1], nums[max_ind] = _max, nums[n - i - 1]
a = [3, 9, 0, 2, 6, 8, 1, 7, 4, 5]
selectsort(a)
print(a) |
979fbb4974d987c6d9d737927cf9f877f4b23a0e | zzh730/LeetCode | /Tree/Flatten Binary Tree to Linked List.py | 1,779 | 3.9375 | 4 | __author__ = 'drzzh'
'''
中序遍历,先把右树移到左树下,然后把左树翻转到右树
Time:O(n)
Space:O(n)
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
tree = TreeNode(1)
tree.left = TreeNode(2)
tree.right = TreeNode(3)
tree.left.right = TreeNode(4)
tree.left.right.left = TreeNode(7)
tree.left.right.right = TreeNode(8)
tree.right.left = TreeNode(5)
tree.right.right = TreeNode(6)
tree.right.left.left = TreeNode(9)
tree.right.left.right = TreeNode(10)
def printtree(root):
if not root:
return
printtree(root.left)
print(root.val)
printtree(root.right)
class Solution:
# @param root, a tree node
# @return nothing, do it in place
def flatten(self, root):
if not root:
return None
cur = root
last = root
stack = []
while cur or stack:
if cur:
if cur.left:
stack.append(cur)
last = cur #record the node that right child should attach
cur = cur.left
else:
last = cur #easy to forget about this case
last.left = cur.right
cur.right = None
cur = last.left
else:
temp = stack.pop()
last.left = temp.right
temp.right = None
cur = last.left
self.leftToRight(root)
return root
def leftToRight(self, root):
while root:
root.right = root.left
root.left = None
root = root.right
a = Solution()
root = a.flatten(tree)
printtree(root)
|
afc945a155e7f9f2841c5df77c13dc3d78c875d5 | Sergeynonnisnon/test_itunes_search_bio | /src/main.py | 4,414 | 3.53125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Part 1
link: https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/
Using the itunes open API (link above), you need to implement
a script that will return all songs (and information about them)
that are included in this album by the parameters "artist" + "song title".
Input format: any (config file, inside a script, input(), cli)
Output format: .csv file (see attachment)
Part 2
Using the parameters from the previous part ("artist" + "song title"),
find the page with the chords of the song (take the first results from the search results),
parse the text + chords and save them to a .txt file
If there are no results, leave the final file empty.
Input format: any (config file, inside a script, input(), cli)
Output format: .txt file
"""
from settings import input_song, input_artist
import pandas as pd
import requests
from bs4 import BeautifulSoup as BS
def first_part(input_song, input_artist):
"""first part of task """
BASE_URL = 'https://itunes.apple.com/search?'
if input_song == '' or input_artist == '':
raise ValueError('Need give artist and song')
elif type(input_song) != str or type(input_artist) != str:
raise TypeError('input_song, input_artist must be str')
path = f"results/{input_artist}_track_{input_song}.csv"
term = input_artist.replace(' ', '+') + '+' + input_song.replace(' ', '+')
response = requests.get(BASE_URL + 'term=' + term + '&entity=song')
if response.status_code != 200:
raise requests.exceptions.RequestException('bad query or internet connection')
response = response.json()['results']
if len(response) == 0:
return None
else:
print(f'count {len(response)} results')
#######
# get name albums +author
#######
albums = {}
for track in response:
if input_song.lower() in str(track['trackName']).lower() \
and input_artist.lower() in str(track['artistName']).lower():
albums[track['artistName'] + '+' + str(track['collectionName']).replace(' ', '+')] = track['collectionId']
artist_id = track['artistId']
print(f'count albums with song is {len(albums)}')
#######
# get song from albums
#######
result = []
for album in albums.keys():
response = requests.get(BASE_URL + 'term' + '=' + album + '&entity=song')
response.encoding = response.apparent_encoding
json_resp = response.json()
json_resp = json_resp['results']
# check if album and artist correct
for i in json_resp:
if i['artistId'] != artist_id or i['collectionId'] not in albums.values():
json_resp.remove(i)
result += json_resp
print(f'count {len(result)} tracks')
df = pd.DataFrame(result)
df = df[['artistId', 'collectionId', 'trackId', 'artistName', 'collectionName',
'trackName', 'collectionCensoredName', 'trackCensoredName', 'artistViewUrl',
'collectionViewUrl', 'trackViewUrl', 'previewUrl', 'collectionPrice',
'trackPrice', 'releaseDate', 'discCount', 'discNumber', 'trackCount',
'trackNumber', 'trackTimeMillis', 'country', 'currency', 'primaryGenreName']]
df.set_index('artistId', inplace=True)
open(path, 'w').close()
return df.to_csv(path)
#####################################################
def second_part(input_song, input_artist):
"""second part of task """
path = f"results/{''.join(e for e in input_artist if e.isalnum())}" \
f"_track_{''.join(e for e in input_song if e.isalnum())}.csv"
response = requests.get('https://searx.roughs.ru/search',
params={'q': f'{input_song} - {input_artist} lyrics chords', 'format': 'json',
'safesearch': 1})
print(f" first entry link {response.json()['results'][0]['pretty_url']}")
try:
lyrics_chords = requests.get(response.json()['results'][0]['pretty_url'])
soup = BS(lyrics_chords.content, 'lxml', ).body.get_text()
with open(path, 'w', encoding='utf-8') as f:
f.write(soup)
except IndexError:
open(path, 'w').close()
if __name__ == '__main__':
first_part(input_song, input_artist)
#second_part(input_song, input_artist)
|
8ef6d703a1fd627ad895bd7a03ced8bfa8e6b72b | IvanWoo/coding-interview-questions | /puzzles/rotate_image.py | 1,604 | 4.09375 | 4 | # https://leetcode.com/problems/rotate-image/
"""
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
Example 2:
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
Constraints:
n == matrix.length == matrix[i].length
1 <= n <= 20
-1000 <= matrix[i][j] <= 1000
"""
def rotate(matrix: list[list[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for layer in range(n // 2):
# print(f"{layer=}")
for step in range(n - layer * 2 - 1):
# print(f"{step=}")
e0, e1, e2, e3 = (
(layer, layer + step),
(layer + step, n - layer - 1),
(n - layer - 1, n - layer - 1 - step),
(n - layer - 1 - step, layer),
)
# print(e0, e1, e2, e3)
(
matrix[e0[0]][e0[1]],
matrix[e1[0]][e1[1]],
matrix[e2[0]][e2[1]],
matrix[e3[0]][e3[1]],
) = (
matrix[e3[0]][e3[1]],
matrix[e0[0]][e0[1]],
matrix[e1[0]][e1[1]],
matrix[e2[0]][e2[1]],
)
if __name__ == "__main__":
rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
8c2e64b1864f7e184a971893411e9c70444e230d | scaleapi/scaleapi-python-client | /scaleapi/files.py | 520 | 3.515625 | 4 | class File:
"""File class, containing File information."""
def __init__(self, json, client):
self._json = json
self.id = json["id"]
self.attachment_url = json["attachment_url"]
self._client = client
def __hash__(self):
return hash(self.id)
def __str__(self):
return f"File(id={self.id})"
def __repr__(self):
return f"File({self._json})"
def as_dict(self):
"""Returns all attributes as a dictionary"""
return self._json
|
b89c508f280d0482c0c0741007d3e16a7d615499 | cliodhnaharrison/interview-prep | /print_ancestors.py | 828 | 3.890625 | 4 | # Time Complexity: O(n) worst case
class Node:
def __init__(self, value, left=None, right=None, parent=None):
self.value = value
self.left = left
self.right = right
self.parent = parent
def get_node(root, value):
if not root:
raise KeyError("Key {} not found in tree.".format(value))
if root.value == value:
return root
try:
left_result = get_node(root.left, value)
return left_result
except KeyError:
return get_node(root.right, value)
def ancestors(root, value):
try:
node = get_node(root, value)
except KeyError:
return []
else:
node_ancestors = []
while node.parent:
node_ancestors.append(node.parent.value)
node = node.parent
return node_ancestors
|
fe754855b074e267a220bdb2d0347157e2a486c1 | NicolasKun/PythonLearnTest | /test7.py | 323 | 3.84375 | 4 | n=23
flag=True
while flag:
guess=int(input('Enter Integer: '))
if guess==n:
print 'Congratulations!You find it!'
flag=False
elif guess<n:
print 'No,it is a little Lower'
else:
print 'No,it is a little Higher'
else:
print '---This While Is Over---'
print 'Done'
|
7e5210896f8933dc610f29454664d6ad2ff26490 | turbo00j/python_programming | /exeptopn test.py | 294 | 4.0625 | 4 | try:
a=int(input("Enter a integer:"))
b=int(input("Enter b integer:"))
print("Division:",a/b) #execption causing line or problematic line
except:
print("Plz enter valid input")
print("Addition:",a+b)
print("Substraction:",a-b)
print("multiplication:",a*b)
print("Power:",a**b)
|
a4847b445aaf00d496a113a4d7789c28e9d75d35 | forrest0402/machine_learning | /src/mnist/siamese_train.py | 2,401 | 3.703125 | 4 | # -*- coding: utf-8 -*-
""" Siamese implementation using Tensorflow with MNIST example.
This siamese network embeds a 28x28 image (a point in 784D)
into a point in 2D.
By Youngwook Paul Kwon (young at berkeley.edu)
https://github.com/ywpkwon/siamese_tf_mnist
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from builtins import input
import numpy as np
import tensorflow as tf
# import system things
from tensorflow.examples.tutorials.mnist import input_data # for data
# import helpers
import siamese_inference as inference
import siamese_visualize as visualize
# prepare data and tf.session
mnist = input_data.read_data_sets("../data/mnist_data", one_hot=False)
sess = tf.InteractiveSession()
# setup siamese network
siamese = inference.siamese()
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(siamese.loss)
saver = tf.train.Saver()
tf.initialize_all_variables().run()
# if you just want to load a previously trainmodel?
load = False
model_ckpt = './model/siamese.meta'
if os.path.isfile(model_ckpt):
input_var = None
while input_var not in ['yes', 'no']:
input_var = input("We found model files. Do you want to load it and continue training [yes/no]?")
if input_var == 'yes':
load = True
# start training
if load:
saver.restore(sess, './model/siamese')
for step in range(50000):
batch_x1, batch_y1 = mnist.train.next_batch(128)
batch_x2, batch_y2 = mnist.train.next_batch(128)
batch_y = (batch_y1 == batch_y2).astype('float')
_, loss_v = sess.run([train_step, siamese.loss], feed_dict={
siamese.x1: batch_x1,
siamese.x2: batch_x2,
siamese.y_: batch_y})
if np.isnan(loss_v):
print('Model diverged with loss = NaN')
quit()
if step % 10 == 0:
print('step %d: loss %.3f' % (step, loss_v))
if step % 100 == 0 and step > 0:
saver.save(sess, './model/siamese')
# 相当于对于test中10000个数据的每个数据,用当前模型转成一个二维向量,后面画图可以看出,相同图片向量基本在一起,有明显聚类特性
embed = siamese.o1.eval({siamese.x1: mnist.test.images})
embed.tofile('./model/embed.txt')
# visualize result
x_test = mnist.test.images.reshape([-1, 28, 28])
y_test = mnist.test.labels
visualize.visualize(embed, x_test, y_test)
|
7b0eb38ff8f31c2b5210994ed1690ccbb9c8494a | 666sempron999/Abramyan-tasks- | /Integer(30)/20.py | 318 | 3.59375 | 4 | '''
Integer20 ◦ . С начала суток прошло N секунд (N — целое). Найти количество
полных часов, прошедших с начала суток.
'''
N = int(input("Введите N: "))
hours, minutes = divmod(N,3600)
print('Chislo', N)
print(hours)
|
6716f47560158c1c66373fadf4593c1dedc4a4c9 | szabgab/slides | /python/examples/dictionary/change_in_loop.py | 413 | 3.578125 | 4 | user = {
'fname': 'Foo',
'lname': 'Bar',
}
for k in user.keys():
user['email'] = 'foo@bar.com'
print(k)
print('-----')
for k in user:
user['birthdate'] = '1991'
print(k)
# lname
# fname
# -----
# lname
# Traceback (most recent call last):
# File "examples/dictionary/change_in_loop.py", line 13, in <module>
# for k in user:
# RuntimeError: dictionary changed size during iteration
|
bbf770eca067fe5b6b7c93521f0f06ec2cd67021 | kolathee/Poker | /poker.py | 3,932 | 3.984375 | 4 | def numhand(hand):
"""
(hand) --> list of rank
Return ranks of a hand
"""
rank = ['--23456789TJQKA'.index(r) for r,s in hand]
rank.sort(reverse=True)
return rank
def dokhand(hand):
'''
(hand) --> list of suits
Return suits of a hand
'''
suit=['-CDHS'.index(s)/10.0 for r,s in hand]
return suit
def is_flush(hand):
'''
(hand) --> bool
Return True if hand is flush, else False
'''
suit=dokhand(hand)
return len(set(suit)) == 1
def is_straight(hand):
'''
(hand) --> bool
Return True if hand is straight, else False
'''
num=numhand(hand)
num.sort()
for i in xrange(3):
if num[i]+1!=num[i+1]:
return False
return True
def is_royal(hand):
'''
(hand) --> bool
Return True if hand is royal flush, else False
'''
if sum(numhand(hand))== 60 and len(set(dokhand(hand)))==1:
return True
return False
def is_straightflush(hand):
'''
(hand) --> bool
Return True if hand is straight flush, else False
'''
return is_straight(hand) and is_flush(hand)
def is_three_of_kind(hand):
'''
(hand) --> bool
Return True if hand is three of a kind, else False
'''
num=numhand(hand)
numset=list(set(num))
for each in numset:
if num.count(each)==3:
return True
return False
def is_four_of_kind(hand):
'''
(hand) --> bool
Return True if hand is four of a kind, else False
'''
num=numhand(hand)
numset=list(set(num))
for each in numset:
if num.count(each)==4:
return True
return False
def is_two_pair(hand):
'''
(hand) --> bool
Return True if hand is two pair, else False
'''
count=0
num=numhand(hand)
numset=list(set(num))
for each in numset:
if num.count(each)==2:
count+=1
if count == 2:
return True
return False
def is_one_pair(hand):
'''
(hand) --> bool
Return True if hand is one pair, else False
'''
count=0
num=numhand(hand)
numset=list(set(num))
for each in numset:
if num.count(each)==2:
count+=1
if count == 1:
return True
return False
def is_fullhouse(hand):
'''
(hand) --> bool
Return True if hand is full house, else False
'''
num=numhand(hand)
numset=list(set(num))
if len(numset)!=2:
return False
return (num.count(numset[0])==3 and num.count(numset[1])==2) or (num.count(numset[0])==2 and num.count(numset[1])==3)
def handrank(hand):
"""
(hand) --> tuple
Return rank of a hand
"""
if is_royal(hand):
return 10,0
elif is_straightflush(hand):
return 9,max(numhand(hand))
elif is_four_of_kind(hand):
num=numhand(hand)
numset=list(set(num))
if num.count(numset[0])==4:
return 8,numset[0]
return 8,numset[1]
elif is_fullhouse(hand):
num=numhand(hand)
numset=list(set(num))
if num.count(numset[0])==3:
return 7,numset[0],numset[1]
return 7,numset[1],numset[0]
elif is_flush(hand):
return 6,max(numhand(hand))
elif is_straight(hand):
return 5,max(numhand(hand))
elif is_three_of_kind(hand):
num=numhand(hand)
numset=list(set(num))
for each in numset:
if num.count(each)==3:
cha=numset.pop(numset.index(each))
return 4,cha,max(numset),min(numset)
elif is_two_pair(hand):
num=numhand(hand)
numset=list(set(num))
liTwo=[]
for each in numset:
if num.count(each)==2:
liTwo.append(each)
remain=[]
for each in numset:
if each not in liTwo:
remain.append(each)
return 3,max(liTwo),min(liTwo),remain[0]
elif is_one_pair(hand):
num=numhand(hand)
numset=list(set(num))
numset.sort(reverse=True)
liTwo=[]
for each in numset:
if num.count(each)==2:
liTwo.append(each)
numset.remove(each)
return 2,liTwo[0],numset[0],numset[1],numset[2]
else:
num=numhand(hand)
num.sort(reverse=True)
return 1,num[0],num[1]
def whowin(hands):
"""
([hand, hand, ..., hand]) --> hand
Return the best hand from a list of hands
"""
winner=max(hands,key=handrank)
maxrank=handrank(winner)
out=[]
for hand in hands:
if handrank(hand)==maxrank:
out.append(hand)
return out
hands=input()
print whowin(hands) |
3736229c0bc804f85f8846d7549871bb5d328fdd | rishitbhojak/python-programs | /Chapter 4/04_tuples.py | 234 | 4.25 | 4 | #Creating a tuple using parenthesis
t = (1,2,4,5)
# Printing the elements of a tuple
print(t[0])
#Note : Tuples cannot be updated
#A tuple with a single element is denoted by a single element followed by a comma
t1 = (1,)
print(t1) |
98ea0b22b3288145b167a5db843e2162069ef367 | madaniel/json | /json_parser.py | 7,454 | 3.609375 | 4 | import urllib2
import json
import os
# # # Functions # # #
def get_all_values(json_dict, target_key):
# Helper function for get_all_values_dict()
if isinstance(json_dict, dict):
return get_all_values_dict(json_dict, target_key)
values_list = []
if isinstance(json_dict, list):
for item in json_dict:
result = get_all_values_dict(item, target_key)
if result:
values_list.extend(result)
return values_list
def get_all_values_dict(json_dict, target_key, values_list=None):
"""
:param json_dict: JSON object
:param target_key: key to find
:param values_list: list to be values of target key
:return: list of all the values found
"""
if values_list is None:
values_list = []
assert isinstance(json_dict, dict), "Can handle only dict as JSON root"
# Getting deep into the JSON tree first using recursion
for key, value in json_dict.iteritems():
# Handling dictionary
if isinstance(value, dict):
get_all_values_dict(value, target_key, values_list)
# Handling list
if isinstance(value, list):
# Check if list contains dict
for item in value:
# If so, send it to get_value for searching
if isinstance(item, dict):
get_all_values_dict(item, target_key, values_list)
# Search for the target key
if target_key in json_dict:
values_list.append(json_dict)
# Return the list [if not empty] to the function caller
if values_list:
return values_list
def count_keys(json_dict, target_key):
# Helper function to count_keys_dict()
if isinstance(json_dict, dict):
return count_keys_dict(json_dict, target_key)
count = 0
if isinstance(json_dict, list):
for item in json_dict:
count += count_keys_dict(item, target_key)
return count
def count_keys_dict(json_dict, target_key, count=0):
"""
:param json_dict: JSON object [dict only]
:param target_key: key to find
:param count: number of target key instances
:return: number of instances found
"""
assert isinstance(json_dict, dict), "can handle only dict as JSON root"
for key, value in json_dict.iteritems():
# Handling dictionary
if isinstance(value, dict):
# Accumulating the count from all function call
count += count_keys(value, target_key)
# Handling list
if isinstance(value, list):
# Check if list contains dict
for item in value:
# If so, send it to get_value for searching
if isinstance(item, dict):
# Accumulating the count from all function call
count += count_keys(item, target_key)
# Count the key
if target_key in json_dict:
count += 1
return count
def get_value(json_dict, target_key, get_all=False):
"""
:param json_dict: JSON object
:param target_key: key to find
:param get_all: Search on all JSONs on list
:return: value or list of values found on JSON
"""
# Helper function to get_value_dict()
if isinstance(json_dict, dict):
return get_value_dict(json_dict, target_key)
if isinstance(json_dict, list):
found = []
for item in json_dict:
value = get_value_dict(item, target_key)
if value:
if not get_all:
return value
else:
found.append(value)
return found
def get_value_dict(json_dict, target_key):
"""
:param json_dict: JSON object
:param target_key: key to find
:return: value of the target key
In case of multiple instances, the 1st key value found will be returned
"""
assert isinstance(json_dict, dict), "can handle only dict as JSON root"
# The key found on the current dict
if target_key in json_dict:
return json_dict[target_key]
# The key not found
for key, value in json_dict.iteritems():
# Current key is a dict
if isinstance(value, dict):
result = get_value(value, target_key)
if result is not None:
return result
# Current key is a list
if isinstance(value, list):
# Check if the list contains dict
for item in value:
# If so, send it to get_value for searching
if isinstance(item, dict):
result = get_value(item, target_key)
if result is not None:
return result
def get_json(url):
# Read the Json from web
req = urllib2.urlopen(url)
# Transfer object into python dictionary
return json.load(req)
def print_json(dict_data):
# Transfer dictionary into json format [None -> null]
if isinstance(dict_data, dict) or isinstance(dict_data, list):
print json.dumps(dict_data, sort_keys=True, indent=4, separators=(',', ': '))
else:
print "Error - no data given"
def write_json(json_data, filename, json_path="C:\\"):
"""
:param json_data: JSON object / python dictionary
:param filename: string of the filename
:param json_path: default path to save the file
:return: filename with its path
"""
# Setting the path to JSON folder
json_filename = os.path.join(json_path, filename)
# Writing JSON data
with open(json_filename, 'w') as f:
json.dump(json_data, f, sort_keys=True, indent=4, separators=(',', ': '))
return json_filename
def read_json(filename, json_path):
"""
:param filename: string of the filename
:param json_path: path to the filename
:return: dictionary of JSON
"""
# Setting the path to JSON folder
json_filename = os.path.join(json_path, filename)
# Reading JSON data
with open(json_filename, 'r') as f:
return json.load(f)
# Compare 2 JSONs line by line
def compare_json(source, target, excluded=None):
"""
:param source: Baseline recorded JSON
:param target: JSON under test
:param excluded: List of strings which should not be checked
:return: True if equals or empty list if equals without excluded list
"""
if source == target:
return True
# List for adding the diff lines
diff = []
# Writing JSONs to files
tmp_source_json = write_json(source, "tmp_source.json")
tmp_target_json = write_json(target, "tmp_target.json")
# Reading the files into lists
with open(tmp_source_json) as src:
source_content = src.readlines()
with open(tmp_target_json) as tar:
target_content = tar.readlines()
# Comparing each line
for source_line, target_line in zip(source_content, target_content):
if not source_line == target_line:
# removing spaces and extra chars from string
target_line = target_line.strip().split(":")[0].strip('"')
if target_line not in excluded:
diff.append(target_line)
# Removing JSONs files
src.close()
tar.close()
try:
os.remove(tmp_source_json)
os.remove(tmp_target_json)
# In case the file does not exists
except WindowsError:
print "\n\n! ! !failed to delete tmp JSON files ! ! !\n"
return diff
|
921839ebce2072a8f43876bea821af7395e0d408 | kenie/myTest | /100/example_005.py | 248 | 3.703125 | 4 | #!/usr/bin/env python
#-*- coding:UTF-8 -*-
'''题目:输入三个整数x,y,z,请把这三个数由小到大输出'''
L = []
for i in range(3):
x = int(raw_input('integer:\n'))
L.append(x)
L.sort()
for j in range(len(L)):
print L[j] |
a136080c8571186f3de8e448073981257456dfe2 | jdf/processing.py | /mode/examples/Topics/Image Processing/LinearImage/LinearImage.pyde | 936 | 3.53125 | 4 | """
Linear Image.
Click and drag mouse up and down to control the signal.
Press and hold any key to watch the scanning.
"""
img = loadImage("sea.jpg")
direction = 1
signal = 0.0
def setup():
global img
img = loadImage("sea.jpg")
size(640, 360)
stroke(255)
img.loadPixels()
loadPixels()
def draw():
global signal, direction
if signal > img.height - 1 or signal < 0:
direction = direction * -1
if mousePressed:
signal = abs(mouseY % img.height)
else:
signal += (0.3 * direction)
if keyPressed:
set(0, 0, img)
line(0, signal, img.width, signal)
else:
signalOffset = int(signal) * img.width
for y in range(img.height):
listCopy(img.pixels, signalOffset, pixels, y * width, img.width)
updatePixels()
def listCopy(src, srcPos, dst, dstPos, length):
dst[dstPos:dstPos + length] = src[srcPos:srcPos + length]
|
44181dcdd51af7ecc64e7858c73a4bbf0b92570b | Ali-Oufi/sca_pi | /python_excercise_2 | 383 | 3.96875 | 4 | #!/usr/bin/env python
x = raw_input("Enter the first number: ")
y = raw_input("Enter the second number: ")
if int(x) > int(y):
print "The maximum number is ", x
print "The minimum number is ", y
print "Maximum - minimum = ", int(x)-int(y)
else:
print "The maximum number is ", y
print "The minimum number is ", x
print "Maximum - minimum = ", int(y)-int(x)
|
fa22ef0e0b73af8b185ef6bad5bce84454cc7d44 | alu0100099010/prct05 | /prct05.py~ | 1,693 | 4 | 4 | #!/usr/bin/env python
# -⁻- coding: UTF-8 -*-
import sys
argumentos =sys.argv[1:]
print argumentos
for k in argumentos:
if (len(argumentos)==1):
n=int(argumentos[k])
else: # 2. O que el usuario, introduzca el intervalo por teclado.
print "Introduzca el intervalo (n>0)"
n=int(raw_input())
if (n>=0):
valor_pi= 3.1415926535897931159979634685441852
sumatorio=0.0
ini=0
intervalo= 1.0 / float(n)
print "**********************Calculo iterativo de PI***************************"
print "************************************************************************"
for i in range (n):
x_i= ((i+1) - 1.0 / 2.0) /n # así lo hacemos ahora
#x_i=calcular_xi (n,i+1) # así, si utilizáramos la función definida aal principio.
fx_i= 4.0/(1.0+ x_i * x_i)
print " " ,i+1,". Subintervalo:[", ini,"," ,ini+intervalo,"] x_",i+1,":" ,x_i,"f(x_",i+1,"):",fx_i
ini += intervalo #Incrementamos ini con el valor de intervalo.
sumatorio += fx_i #Incrementamos el sumatorio con cada pasada por fx_i
pi=sumatorio / n #calculamos la aproximación de π (notar que tiene que estar fuera del for¡¡)
print "************************************************************************"
print "El valor aproximado de PI es: %10.35f " % pi
print "El valor de PI con 35 decimales es: %10.35f" % valor_pi # el % le indica que tiene formato¡¡
print "El error de aproximación es de: ", abs(valor_pi - pi)
print "*********************************************************"
else:
print "El valor del numero de intervalos debe ser positivo."
|
d24d9a5dae888729890f372050f77b16711af213 | gschen/sctu-ds-2020 | /1906101053-熊赟/0407/笔记2.py | 699 | 3.828125 | 4 | class Queue :
#初始化队列
def_init_ (se1f):
seIf .que=[]
self . size=8#列表的长度
#判断队列是否为空
def is empty(self):
if self . sIze==0:
return True
return False
#返回队列的长度
def que_ size(self):
return self .size
#列表添加元素
def enqueue(self,value):
self. size+=1
self. que . append(value)
#删除队列元素s、
def dequeue(self):
if self.size--B:
print("没东西,不能删“)
return
else:
self . size-=1
self .que . pop(e)
queue=Queue()
|
26dfa26156fd5eb83724d4de9c31518494d02d0b | karpmage/Job-Application | /MeanFilter.py | 1,935 | 3.65625 | 4 | """
I perform a mean filter on the data using 1 adjacent data point on each side.
A median filter would work better for removing outliers, but this data set
doesn't seem to have any.
I attained the data from:
https://machinelearningmastery.com/time-series-datasets-for-machine-learning/
and it is the "Shampoo Sales Dataset".
"""
import json
import matplotlib.pyplot as plt
import statistics
# Loads in the json data
with open('distros.json', 'r') as f:
distros_dict = json.load(f)
# I put the original sales values in a list
value_list = []
for key in distros_dict:
value_list += [float(key['Value'])]
# I compute the mean values and put them in a new list
new_value_list = []
new_value_list += [(value_list[0]+value_list[1])/2]
for i in range(1,len(value_list)-1):
new_value = (value_list[i-1]+value_list[i]+value_list[i+1])/3
new_value_list += [new_value]
new_value_list += [(value_list[-2]+value_list[-1])/2]
# The unfiltered graph is black
# The filtered graph is red
plt.plot(value_list, 'black')
plt.plot(new_value_list, 'red')
plt.ylabel('Sales')
plt.xlabel('Month')
plt.show()
minimum = min(new_value_list)
print("minimum:", "{:.1f}".format(minimum))
total = 0
n = 0
for element in new_value_list:
total += element
n += 1
mean = total/n
print("mean:", "{:.1f}".format(mean))
#By "average", I assume you mean "median"
median = statistics.median(new_value_list)
print("median:", "{:.1f}".format(median))
"""
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product",
"description": "A graph of Shampoo product sales over time",
"type": "object",
"properties": {
"Date": {
"description": "Gives the month and year",
"type": "string"
},
"Value": {
"description": "Shampoo product sales",
"type": "float"
}
}
}
"""
|
4c93b651a70ce03e756f992adedea8a3357d3b6b | qkzk/portes_ouvertes | /sudoku/sudoku.py | 7,101 | 4 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
solve a sudoku
'''
'''
1 à 9 en ligne
1 à 9 en colonne
1 à 9 ds chaque sous carré 3x3
0 si on ne connait pas la valeur
'''
'''
La méthode la plus rapide pour un ordinateur consiste à essayer systématiquement, l’un après l’autre, tous les candidats restants. Appliquée récursivement, elle peut résoudre tous les puzzles
'''
'''
A brute force algorithm visits the empty cells in some order, filling in digits sequentially, or backtracking when the number is found to be not valid.
Briefly, a program would solve a puzzle by placing the digit "1" in the first cell and checking if it is allowed to be there.
If there are no violations (checking row, column, and box constraints) then the algorithm advances to the next cell, and places a "1" in that cell.
When checking for violations, if it is discovered that the "1" is not allowed, the value is advanced to "2".
If a cell is discovered where none of the 9 digits is allowed, then the algorithm leaves that cell blank and moves back to the previous cell.
The value in that cell is then incremented by one.
This is repeated until the allowed value in the last (81st) cell is discovered.
'''
'''
backtracking avec recursion minimale
'''
import time
import numpy as np
import pygame
from pygame.locals import *
CASE = 80
WINDOWHEIGHT = CASE * 9 + 5 # hauteur de la fenetre
WINDOWWIDTH = WINDOWHEIGHT # LARGEUR de la fenetre
TRAIT = 5
BLACK = (0, 0, 0) # black
WHITE = (255, 255, 255) # white
CYAN = (0, 255, 255) # cyan
ORANGE = (255, 200, 0) # yellow
FPS = 100
def isValid(grille, n, valeur):
'''
renvoie True si on peut mettre "valeur" en position "n"
'''
# coordonnées des elements
# exemple n = 37
i = n // 9 # ligne : 4
j = n % 9 # colonne : 1
k = n // 27 * 3 # ligne de debut de bloc : 3
l = (n % 9) // 3 * 3 # colonne de debut de bloc : 0
# reunion des elements deja presents ds ligne, col, bloc
valeurs_presentes = (
set(grille[i].A1) |
set(grille.T[j].A1) |
set(grille[k:k+3, l:l+3].A1)
)
if valeur in valeurs_presentes:
# la valeur proposee est deja presente, la grille est fausse
return False
else:
# la valeur proposee n'apparait pas encore, la grille est tjrs valide
return True
def sudoku(grille, n=0):
assert type(n) == int
global windowSurface
global mainClock
# prochain element et test de victoire
while grille.A1[n] != 0:
n += 1
if n >= 81:
return True
# coordonnées des elements
# exemple n = 37
i = n // 9 # ligne : 4
j = n % 9 # colonne : 1
k = n // 27 * 3 # ligne de debut de bloc : 3
l = (n % 9) // 3 * 3 # colonne de debut de bloc : 0
# candidats possibles pour la cellule en cours
# {0,...,9} - valeurs des lignes, colonnes, bloc
valeurs_possibles = set(range(1, 10)) - (
set(grille[i].A1) |
set(grille.T[j].A1) |
set(grille[k:k+3, l:l+3].A1)
)
# # affichages intermédiaires
# print("\n" * 10)
# print(grille)
# print("i: {} - j: {} - valeurs possibles {}".format(i, j, valeurs_possibles))
# time.sleep(10)
# # fin des affichages intermédiaires
for valeur in valeurs_possibles:
if isValid(grille, n, valeur): # la grille est possible
grille[i, j] = valeur
# # affichages intermédiaires
print(n)
print("ligne {0} colonne {1} - valeur {2}\n".format(i, j, valeur))
print(grille)
draw_grid(grille)
# time.sleep(1)
# # fin des affichages intermédiaires
if sudoku(grille, n):
return True
else:
# on n'arrive ici que si aucune valeur de i j ne peut correspondre
grille[i, j] = 0
return False
def draw_grid(grille):
windowSurface.fill(BLACK)
draw_border()
for i in range(9):
for j in range(9):
if grille[i, j] != 0:
drawText(str(grille[i, j]), font,
windowSurface, i * CASE + CASE / 3 + 5,
j * CASE + CASE / 3 - 2)
if entree[i, j] != 0:
drawText(str(grille[i, j]), font,
windowSurface, i * CASE + CASE / 3 + 5,
j * CASE + CASE / 3 - 2,
ORANGE)
mainClock.tick(FPS)
pygame.display.update()
def draw_border():
for k in range(10):
draw_horizontal(k)
draw_vertical(k)
for k in range(4):
draw_square(k)
def draw_square(k):
line_rect = pygame.Rect(0, 3 * k * CASE, WINDOWWIDTH - 5, 2 * TRAIT)
pygame.draw.rect(windowSurface, WHITE, line_rect)
line_rect = pygame.Rect(3 * k * CASE - 5, 0, 2 * TRAIT, WINDOWHEIGHT)
pygame.draw.rect(windowSurface, WHITE, line_rect)
def draw_horizontal(k):
line_rect = pygame.Rect(0, k * CASE, WINDOWWIDTH, TRAIT)
pygame.draw.rect(windowSurface, WHITE, line_rect)
def draw_vertical(k):
line_rect = pygame.Rect(k * CASE, 0, TRAIT, WINDOWHEIGHT)
pygame.draw.rect(windowSurface, WHITE, line_rect)
def terminate():
# permet de quitter le jeu
pygame.quit()
sys.exit()
def drawText(text, font, surface, x, y, color=WHITE):
# permet d'ecrire
textobj = font.render(text, 1, color)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
def run_sudoku(debut):
global windowSurface
global mainClock
global font
global entree
# print(isValid(entree1, 1, 8))
entree = debut
print(entree)
grille = entree.copy()
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption("Résolution automatique d'un Sudoku")
# taille et type de la fonte
font = pygame.font.SysFont(None, 64)
# Draw the game world on the window.
windowSurface.fill(BLACK)
sudoku(grille)
def start(compteur):
if compteur == 0:
return np.matrix("""
8 0 0 1 0 9 0 7 0;
0 9 0 0 0 0 8 0 0;
5 0 3 0 4 0 0 0 0;
0 0 0 0 0 0 7 9 0;
0 0 7 2 6 5 3 0 0;
0 3 8 0 0 0 0 0 0;
0 0 0 0 9 0 4 0 1;
0 0 6 0 0 0 0 2 0;
0 5 0 4 0 2 0 0 3
""")
else:
return np.matrix(
[[5, 1, 7, 6, 0, 0, 0, 3, 4],
[2, 8, 9, 0, 0, 4, 0, 0, 0],
[3, 4, 6, 2, 0, 5, 0, 9, 0],
[6, 0, 2, 0, 0, 0, 0, 1, 0],
[0, 3, 8, 0, 0, 6, 0, 4, 7],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 9, 0, 0, 0, 0, 0, 7, 8],
[7, 0, 3, 4, 0, 0, 5, 6, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]]
)
def main():
compteur = 0
while True:
debut = start(compteur)
run_sudoku(debut)
time.sleep(5)
compteur = (compteur + 1) % 2
if __name__ == '__main__':
main()
|
d4ef5b56cffd54a77f784481b9133c8a2394df37 | StaticallyTypedRice/recursive-extract | /modules/extract.py | 182 | 3.65625 | 4 | class ExtractionError(Exception):
'''The exception that is raised when there is an error when extracting.'''
def extract_7z(path:str):
'''Extract a file using 7zip.
''' |
aaca793293e1b90b190ee79f85a3d33304116bb9 | sas0112/chapter_10 | /storing_data/favorite_number/favorite_number.py | 757 | 4.03125 | 4 | import json
def add_favorite_number():
"""this function adds the number in the file"""
file_name = "favorite_number_list.json"
with open(file_name, "a") as file_object:
favorite_number = input("please enter your favorite number: ")
json.dump(favorite_number, file_object)
return favorite_number
def get_favorite_number():
"""this function gets the number from the file"""
file_name = "favorite_number_list.json"
try:
with open(file_name) as file_object:
favorite_number = json.load(file_object)
except FileNotFoundError:
print("it seems that you haven't a list of favorite number yet.")
add_favorite_number()
else:
print(favorite_number)
get_favorite_number() |
6e260f074dcfb414777ef6ec6f28998f7d5526e7 | blumek/TicTacToe-Minimax | /TicTacToeAI.py | 3,195 | 3.765625 | 4 | import math
from TicTacToe import TicTacToe
class TicTacToeAI(TicTacToe):
def __init__(self, board=None):
super().__init__()
if board is not None:
self._board = board
def move(self, row, col):
if self._turn != self._Board.PLAYER_TWO:
raise Exception("Currently it is computer's turn. Player cannot make a move now.")
super().move(row, col)
def ai_move(self):
if self._turn != self._Board.PLAYER_ONE:
raise Exception("Currently it is player's turn. Computer cannot make a move now.")
row, col = self.__get_next_move_cell()
super().move(row, col)
def __get_next_move_cell(self):
max_weight = -math.inf
pos = None
alpha = -math.inf
beta = math.inf
for row in range(self._board_size):
for col in range(self._board_size):
if not self._is_empty_cell(row, col):
continue
self._board[row][col] = self._Board.PLAYER_ONE
weight = self.__minimizing_player(alpha, beta)
self._board[row][col] = self._Board.EMPTY_CELL
if weight > max_weight:
max_weight = weight
pos = row, col
alpha = max(alpha, weight)
if beta <= alpha:
return pos
return pos
def __maximizing_player(self, alpha, beta):
if self._is_game_finished():
return self.__get_weight()
max_weight = -math.inf
for row in range(self._board_size):
for col in range(self._board_size):
if not self._is_empty_cell(row, col):
continue
self._board[row][col] = self._Board.PLAYER_ONE
weight = self.__minimizing_player(alpha, beta)
self._board[row][col] = self._Board.EMPTY_CELL
max_weight = max(max_weight, weight)
alpha = max(alpha, weight)
if beta <= alpha:
return max_weight
return max_weight
def __get_weight(self):
return self._get_winner() * self.__count_empty_cells()
def __count_empty_cells(self):
empty_cells = 0
for row in range(self._board_size):
for col in range(self._board_size):
if self._is_empty_cell(row, col):
empty_cells += 1
return empty_cells
def __minimizing_player(self, alpha, beta):
if self._is_game_finished():
return self.__get_weight()
min_weight = math.inf
for row in range(self._board_size):
for col in range(self._board_size):
if not self._is_empty_cell(row, col):
continue
self._board[row][col] = self._Board.PLAYER_TWO
weight = self.__maximizing_player(alpha, beta)
self._board[row][col] = self._Board.EMPTY_CELL
min_weight = min(min_weight, weight)
beta = min(beta, weight)
if beta <= alpha:
return min_weight
return min_weight
|
532dd7978b50062a0e4a567fd60a016a01c35168 | wagnersistemalima/Mundo-1-Python-Curso-em-Video | /pacote dawload/projetos progamas em Python/desafio007 Média Aritimetica.py | 314 | 3.78125 | 4 | # desafio 007-Média Aritimetica/ desenvolva um progama que leia as duas notas de um aluno,
# calcule e mostre a sua média.
nota1 = float(input('Primeira nota:'))
nota2 = float(input('Segunda nota:'))
media = (nota1 + nota2) / 2
print('A media entre a nota {:.1f} e {:.1f} é {:.1f}'.format(nota1, nota2, media))
|
040983a69eb065b0ca565d797e705a049a18d71e | vatsalnayak895/Rosalind | /rosa1.py | 286 | 4.03125 | 4 | def sqr_hypo(a,b):
if a > 1000:
print("invalid number")
return False
elif b > 1000:
print("invalid number")
return False
else:
b=a*a+b*b
return b
a=int(input("enter 1st number:"))
b=int(input("enter 2nd number:"))
res=(sqr_hypo(a,b))
print(res)
|
6863ba2157f8eb1147a447308adb59083e5ee6b3 | Frankiee/leetcode | /min_heap/703_kth_largest_element_in_a_stream.py | 1,644 | 3.875 | 4 | # https://leetcode.com/problems/kth-largest-element-in-a-stream/
# 703. Kth Largest Element in a Stream
# History:
# Facebook
# 1.
# Sep 7, 2019
# 2.
# Mar 18, 2020
# 3.
# May 4, 2020
# Design a class to find the kth largest element in a stream. Note that it
# is the kth largest element in the sorted order, not the kth distinct element.
#
# Your KthLargest class will have a constructor which accepts an integer k
# and an integer array nums, which contains initial elements from the
# stream. For each call to the method KthLargest.add, return the element
# representing the kth largest element in the stream.
#
# Example:
#
# int k = 3;
# int[] arr = [4,5,8,2];
# KthLargest kthLargest = new KthLargest(3, arr);
# kthLargest.add(3); // returns 4
# kthLargest.add(5); // returns 5
# kthLargest.add(10); // returns 5
# kthLargest.add(9); // returns 8
# kthLargest.add(4); // returns 8
# Note:
# You may assume that nums' length ≥ k-1 and k ≥ 1.
import heapq
class KthLargest(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.k = k
self.hp = nums
heapq.heapify(self.hp)
while len(self.hp) > k:
heapq.heappop(self.hp)
def add(self, val):
"""
:type val: int
:rtype: int
"""
if len(self.hp) < self.k:
heapq.heappush(self.hp, val)
elif val > self.hp[0]:
heapq.heapreplace(self.hp, val)
return self.hp[0]
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
|
91f522ce1e96136174236e3a02c686afd1c470ea | sarthak268/Spring_Mass_Damper-Control_Theory | /signalGenerator.py | 1,369 | 3.71875 | 4 | import numpy as np
class signalGenerator:
'''
This class inherits the Signal class. It is used to organize
1 or more signals of different types: square_wave,
sawtooth_wave, triangle_wave, random_wave.
'''
def __init__(self, amplitude=1, frequency=1, y_offset=0):
'''
amplitude - signal amplitude. Standard deviation for random.
frequency - signal frequency
y_offset - signal y-offset
'''
self.amplitude = amplitude
self.frequency = frequency
self.y_offset = y_offset
def square(self, t):
if t % (1.0/self.frequency) <= 0.5/self.frequency:
out = self.amplitude + self.y_offset
else:
out = - self.amplitude + self.y_offset
return [out]
# returns a list of length 1
def sawtooth(self, t):
tmp = t % (0.5/self.frequency)
out = 4*self.amplitude*self.frequency*tmp - self.amplitude + self.y_offset
return [out]
# returns a list of length 1
def random(self, t):
out = np.sqrt(self.amplitude)*np.random.rand() + self.y_offset
return [out]
# returns a list of length 1
def sin(self, t):
out = self.amplitude*np.sin(2*np.pi*self.frequency*t) + self.y_offset
return [out]
# returns a list of length 1
|
03bc861a5b9405c8ae642849b87216406a001dd2 | MarianDanaila/Competitive-Programming | /LeetCode_30days_challenge/2020/December/Remove Duplicates from Sorted Array II.py | 734 | 3.59375 | 4 | # Approach 1
# Time Complexity: O(N^2) where N is length of the array
class Solution:
def removeDuplicates(self, nums):
deleted = 0
n = len(nums)
cnt = 1
for i in range(1, n):
if nums[i-deleted] == nums[i-deleted-1]:
cnt += 1
if cnt > 2:
nums.pop(i-deleted)
deleted += 1
else:
cnt = 1
return len(nums)
# Approach 2
# Time Complexity: O(N) where N is length of the array
class Solution2:
def removeDuplicates(self, nums):
i = 0
for num in nums:
if i < 2 or num > nums[i-2]:
nums[i] = num
i += 1
return i
|
04a91d660d213b0295663574208beb42a22afdf7 | seoul-ssafy-class-2-studyclub/GaYoung_SSAFY | /Baekjoon/17070_파이프 옮기기1.py | 1,257 | 3.609375 | 4 | def game(x, y, place):
global cnt
if (x, y) == (N - 1, N - 1):
cnt += 1
return 0
else:
if place == 0:
if y + 1 < N:
if board[x][y + 1] == 0:
game(x, y + 1, 0)
if x + 1 < N and y + 1 < N:
if board[x][y + 1] == 0 and board[x + 1][y] == 0 and board[x +1][y + 1] == 0:
game(x + 1, y + 1, 2)
elif place == 1:
if x + 1 < N:
if board[x + 1][y] == 0:
game(x + 1, y, 1)
if x + 1 < N and y + 1 < N:
if board[x][y + 1] == 0 and board[x + 1][y] == 0 and board[x +1][y + 1] == 0:
game(x + 1, y + 1, 2)
if place == 2:
if y + 1 < N:
if board[x][y + 1] == 0:
game(x, y + 1, 0)
if x + 1 < N:
if board[x + 1][y] == 0:
game(x + 1, y, 1)
if x + 1 < N and y + 1 < N:
if board[x][y + 1] == 0 and board[x + 1][y] == 0 and board[x +1][y + 1] == 0:
game(x + 1, y + 1, 2)
N = int(input())
board = [list(map(int, input().split())) for _ in range(N)]
cnt = 0
i = 0
j = 1
game(i, j, 0)
print(cnt) |
04966e3dc0cd843509ffe271aa2def84020f8cdc | Mintakai/python_misc | /regex_training_continued.py | 81 | 3.71875 | 4 | import re
word = input("Enter a string: ")
print(re.sub(r"-?\d+", "XXX", word)) |
ad07c5e4d0ee5541beffc37923eeacd5afa5d30c | Alish26/PP2 | /TSIS 5/9.py | 236 | 3.625 | 4 | import re
def Sol(s):
p = 'a.*?b$'
if re.search(p, s):
return 'Found a match!'
else:
return('Not matched!')
print(Sol("aabbbbd"))
print(Sol("aabAbbbc"))
print(Sol("accddbbjjjb")) |
38d963c6c5ac4810fa84fed1eeccfa7e145b444e | sirken/coding-practice | /codewars/6 kyu/build-tower.py | 979 | 4.21875 | 4 | from Test import Test, Test as test
'''
Build Tower
Build Tower by the following given argument:
number of floors (integer and always greater than 0).
Tower block is represented as *
for example, a tower of 3 floors looks like below
[
' * ',
' *** ',
'*****'
]
and a tower of 6 floors looks like below
[
' * ',
' *** ',
' ***** ',
' ******* ',
' ********* ',
'***********'
]
'''
# Initial
def tower_builder(n_floors):
total_len = n_floors * 2 - 1
l = []
for x in range(1, n_floors+1):
a = '*' * (x * 2 - 1)
a = a.center(total_len, ' ')
l.append(a)
return l
# Condensed
def tower_builder(n_floors):
return [('*' * (x*2-1)).center(n_floors*2-1) for x in range(1, n_floors+1)]
test.describe("Tests")
test.it("Basic Tests")
test.assert_equals(tower_builder(1), ['*', ])
test.assert_equals(tower_builder(2), [' * ', '***'])
test.assert_equals(tower_builder(3), [' * ', ' *** ', '*****'])
|
e85c3285c04a66fcfcc0527518882c1aef7a8964 | holynova-SD/MachineLearningCodes | /GMM/main.py | 1,546 | 3.625 | 4 | from EM import *
import numpy as np
# Suppose here are two Gaussian distribution, and the variance is known.
def init_data(sigma, mu_1, mu_2, n):
"""
Generate data that is a mixture of two Gaussian distribution.
:param sigma: the variance of the Gaussian distribution. Suppose it is same for those two distribution.
:param mu_1: the mean value of one Gaussian distribution.
:param mu_2: the mean value of another Gaussian distribution.
:param n: number of data.
:return: the data set and the initialized Expectation matrix.
"""
data = np.zeros((1, n))
gamma = np.zeros((n, 2))
for j in range(0, n):
if np.random.random(1) > 0.5:
data[0, j] = np.random.normal() * sigma + mu_1
else:
data[0, j] = np.random.normal() * sigma + mu_2
return data, gamma
if __name__ == '__main__':
# the variance of these two Gaussian distribution
Sigma = 5
# the mean value of these Gaussian distribution
Mu = np.zeros(2) + [20, 30]
# number of different Gaussian distributions
K = 2
# number of data
N = 1000
# allowable error
epsilon = 0.00001
Data, Gamma = init_data(Sigma, Mu[0], Mu[1], N)
Mu_test = np.random.random(2)
# the EM algorithm
for i in range(0, N):
Mu_test_before = Mu_test.copy()
Gamma = e_step(Sigma, Gamma, Mu_test, K, N, Data)
Mu_test = m_step(Gamma, Mu_test, K, N, Data)
print(Mu_test)
if sum(abs(Mu_test - Mu_test_before)) < epsilon:
break
|
f6485ab6cb845a6d14b081bffce5597820a45eed | php3397/mycode | /python_scripts/deep.py | 446 | 3.734375 | 4 | class person:
def __init__(self,name,age):
self.name=name
self.age=age
def display(self):
print("name",self.name)
print("age",self.age)
class student(person):
def __init__(self,rollno,name,age,per):
self.rollno=rollno
person.__init__(self,name,age)
self.per=per
def display(self):
print("rollno per",self.rollno,self.per)
print(person.display(self))
s1=student(101,'Hema',21,75.50)
print("stuent details")
s1.display()
|
de45b30cd191da44a1f5c5edd681ee190ed798f6 | babe18/python_six_course | /lesson3/p64.py | 311 | 3.5625 | 4 | from random import randint
rnum=randint(1,100)
flag=True
while(flag):
_input=int(input("請猜一個1~99的整數:"))
if(_input>rnum):
print("比",_input,"小")
elif(_input<rnum):
print("比",_input,"大")
elif(_input==rnum):
print("猜對了!")
flag=0 |
c27b2a719a927ca3d7196a123c69d660926ba1d5 | akshat-harit/matasano-crypto-challenges | /set1/challenge5.py | 685 | 3.515625 | 4 | #!/usr/bin/env python
''' Functions for repeating-key XOR'''
def hex_byte(byte):
out = hex(byte)
out = out[2:]
if len(out) == 1:
out = '0' + out
return out
def hex_text(inp):
out = []
for byte in inp:
out.append(hex_byte(byte))
return ''.join(out)
def encrypt(key, inp):
key_len = len(key)
out = []
for i in range(0, len(inp)):
out.append(ord(inp[i]) ^ ord(key[i%key_len]))
return hex_text(out)
def test():
inp = "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal"
key = "ICE"
out = encrypt(key=key, inp=inp)
assert out == "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f"
if __name__ == "__main__":
test()
|
314261fa97f65dbe284cf414cc76996793399fb9 | SarahLewk/Python_Challenge | /PyBank/Resources/Main.py | 2,572 | 3.5 | 4 | import os
import csv
#csvpath = os.path.join('..',"Resources","budget_data.csv")
reading_file = os.path.join('..',"Resources","budget_data.csv")
output_file = "Analysis/budget_analysis_1.txt"
#My list of variables for my output:
month_list = 0
prev_profit_loss = 0
month_of_change = []
profit_loss_change_list = []
greatest_increase_profits = ["", 0]
greatest_decrease_loss = ["", 99999999999]
total_profit_loss = 0
# Chris told me he didn't know what DictReader was and told me no to use it...
# so I find it interesting that the solved video shows them using DictReader.
# I decided to incorporate it back into my code since I think it is a very useful tool.
with open(reading_file) as revenue_data:
reader=csv.DictReader(revenue_data)
prev_profit_loss = 0
for row in reader:
#Tracking my total months and net total amount of "Profit/Losses"
month_list = month_list +1
total_profit_loss = total_profit_loss + int(row["Profit/Losses"])
#Tracking the "Profit/Losses" changes
profit_loss_change = int(row["Profit/Losses"]) - prev_profit_loss
prev_profit_loss = int(row["Profit/Losses"])
profit_loss_change_list = profit_loss_change_list + [profit_loss_change]
month_of_change = month_of_change + [row["Date"]]
#Calculating the greatest increase in profits
if (profit_loss_change > greatest_increase_profits[1]):
greatest_increase_profits[0] = row["Date"]
greatest_increase_profits[1] = profit_loss_change
#Calculating the greatest decrease in losses
if (profit_loss_change < greatest_decrease_loss[1]):
greatest_decrease_loss[0] = row["Date"]
greatest_decrease_loss[1] = profit_loss_change
#Calculating the average profit/loss change
profit_loss_avg = sum(profit_loss_change_list)/len(profit_loss_change_list)
#I'm not getting the same number value as the answer in the homework example...
#but everything else printed the same. Did I write my calculation wrong?
# Creating my output summary
Output= (
f"\nFinancial Analysis\n"
f"Total Months: {month_list}\n"
f"Total: ${total_profit_loss}\n"
f"Average Change: ${profit_loss_avg}\n"
f"Greatest Increase in Profits: {greatest_increase_profits[0]} (${greatest_increase_profits[1]})\n"
f"Greatest Decrease in Revenue: {greatest_decrease_loss[0]} (${greatest_decrease_loss[1]})\n"
)
#Printing my output
print(Output)
#Exporting my results to a text file
with open(output_file,"w") as txt_file:
txt_file.write(Output) |
ddcccaa656f1a4ea3e6ba50b1fcb2d9bcb631e06 | nikcbg/Begin-to-Code-with-Python | /13. Python and Graphical User Interfaces/EG13-07 Drawing program/Drawing.py | 1,211 | 3.96875 | 4 | '''
Provides a simple drawing app
Hold down the left button to draw
Provides some single key commands:
R-red G-green B-blue
C-clear
'''
from tkinter import *
class Drawing(object):
def display(self):
root = Tk()
canvas = Canvas(root, width=500, height=500)
canvas.grid(row=0, column=0)
draw_color = 'red'
def mouse_move(event):
'''
Draws a 10 pixel rectangle centered about the mouse
position
'''
canvas.create_rectangle(event.x-5, event.y-5,
event.x+5, event.y+5, fill=draw_color, outline=draw_color)
canvas.bind('<B1-Motion>', mouse_move)
def key_press(event):
nonlocal draw_color
ch = event.char.upper()
if ch == 'C':
canvas.delete("all")
elif ch == 'R':
draw_color = 'red'
elif ch == 'G':
draw_color = 'green'
elif ch == 'B':
draw_color = 'blue'
canvas.bind('<KeyPress>', key_press)
canvas.focus_set()
root.mainloop()
if __name__ == '__main__':
app = Drawing()
app.display() |
6414816c533401375ba23d330b845998112aa727 | brunocenteno/TensorFlow-Neural_Network | /Neural_Network.py | 1,225 | 3.546875 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500
n_classes = 10
size_batches = 100
x = tf.placeholder('float', [None, 784])
y = tf.placeholder('float')
def neural_network_model(data):
hl1 = {'W': tf.Variable(tf.random_normal([784, n_nodes_hl1])), 'B': tf.Variable(tf.random_normal([n_nodes_hl1]))}
hl2 = {'W': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 'B': tf.Variable(tf.random_normal([n_nodes_hl2]))}
hl3 = {'W': tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), 'B': tf.Variable(tf.random_normal([n_nodes_hl3]))}
ol = {'W': tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])), 'B': tf.Variable(tf.random_normal([n_classes]))}
l1 = tf.add(tf.matmul(data, hl1['W']), hl1['B'])
l1 = tf.nn.relu(l1)
l2 = tf.add(tf.matmul(l1, hl2['W']), hl2['B'])
l2 = tf.nn.relu(l2)
l3 = tf.add(tf.matmul(l2, hl3['W']), hl3['B'])
l3 = tf.nn.relu(l3)
ol = tf.matmul(l3, ol['W']), ol['B']
return output
def train_nn(x):
prediction = neural_network_model(x)
cost = tf.reduce_mean(tf.nn.sofmax_cross_entropy_with_logits(prediction, y)),
|
d5572f9bdfb89c82b1098875a16ac33d9905f2a3 | cgroves3/leetcode-practice | /easy/reverse-linked-list/solution.py | 340 | 3.625 | 4 | class Solution(object):
def reverseList(self, head):
if head == None:
return head
current = None
while head.next != None:
temp = head.next
head.next = current
current = head
head = temp
head.next = current
return head
|
0c34a4ef724a5844f4ad999b63478f3866dc3e74 | caitaozhan/LeetCode | /stack/22.generate-parentheses.py | 1,257 | 3.5625 | 4 | #
# @lc app=leetcode id=22 lang=python3
#
# [22] Generate Parentheses
#
from typing import List
# @lc code=start
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
def dfs(stack, path, left_count, n):
if len(path) == 2*n:
ans.append(path)
return
if not stack:
path += '('
left_count += 1
dfs(stack + ['('], path, left_count, n)
else:
if left_count == n: # '(' is full
path += ')'
dfs(stack[:-1], path, left_count, n)
else:
# put '('
path += '('
left_count += 1
dfs(stack + ['('], path, left_count, n)
path = path[:-1]
left_count -= 1
# put ')'
path += ')'
dfs(stack[:-1], path, left_count, n)
stack = []
path = ''
left_count = 0 # counter of the left parentheses
ans = []
dfs(stack, path, left_count, n)
return ans
n = 3
s = Solution()
print(s.generateParenthesis(n))
# @lc code=end
|
a06110036a078f90cfe14a2f45ec40cec67a13a2 | SLilit/Competitive-programming | /add_two_numbers.py | 1,993 | 3.59375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
num = head = ListNode(0)
l_sum = 0
while l1 or l2:
if l1:
l_sum += l1.val
l1 = l1.next
if l2:
l_sum += l2.val
l2 = l2.next
head.next = ListNode(l_sum % 10)
head = head.next
l_sum //= 10
if l_sum:
head.next = ListNode(l_sum)
return num.next
def helper(l, s):
head = l
l_sum = l.val + s
if l_sum < 10:
l.val = l_sum
else:
while l_sum == 10 and l.next:
l.val = 0
l = l.next
l_sum = l.val + s
if l_sum < 10:
l.val = l_sum
else:
l.val = 0
l.next = ListNode(1)
return head
l_remaining = 0
num = head = ListNode(None)
while l1 and l2:
l_sum = l1.val + l2.val + l_remaining
l1 = l1.next
l2 = l2.next
if l_sum < 10:
head.next = ListNode(l_sum)
head = head.next
l_remaining = 0
else:
head.next = ListNode(l_sum % 10)
head = head.next
l_remaining = 1
if l1:
head.next = helper(l1, l_remaining)
elif l2:
head.next = helper(l2, l_remaining)
elif l_remaining:
head.next = ListNode(1)
return num.next
|
425f08fddbdcedab131083548c7ffafeb24b24a7 | bigguozi/ball_game | /velocity.py | 3,342 | 4 | 4 | import math
class Velocity():
''' 该类实现二维速度类 '''
def __init__(self,amp=0,rad=0,angle=0,max_speed=10):
# 速度模值
self.amp = amp
# 速度角度(如果传入angle不为0则以angle作为角度,单位为度,若为0则以rad为角度,单位为弧度)
self.rad = rad if angle == 0 else math.radians(angle) ;
self.max_speed = max_speed
def __add__(self,other):
''' 运算符重载,直接加于该速度类中,不返回新的实体 '''
# 获取当前速度的分解值,存储于x,y中
x_v,y_v = self.velocity_decompose()
# 获取另一运算速度类的x,y速度
other_x_v,other_y_v =other.velocity_decompose()
# 将速度向量求和,并计算新的模值与角度
x_v += other_x_v
y_v += other_y_v
return Velocity(math.hypot(y_v,x_v),math.atan2(y_v,x_v))
def velocity_vector_add(self,other):
'''该函数接受另外一个速度类并与该类相加'''
# 获取当前速度的分解值,存储于x,y中
x_v,y_v = self.velocity_decompose()
# 获取另一运算速度类的x,y速度
other_x_v,other_y_v =other.velocity_decompose()
# 将速度向量求和,并计算新的模值与角度
x_v += other_x_v
y_v += other_y_v
# 最大速度受限制
x_v = x_v if math.fabs(x_v) < self.max_speed else math.copysign(self.max_speed,x_v)
y_v = y_v if math.fabs(y_v) < self.max_speed else math.copysign(self.max_speed,y_v)
self.amp =math.hypot(y_v,x_v)
self.rad =math.atan2(y_v,x_v)
#print('速度值为{{{},{}}}'.format(x_v,y_v))
def velocity_reflect(self,norm_vec_rad):
''' 该函数根据传入的法线向量角度反射该速度 '''
# 求解角度关于某一角度的反射角度,可以先法线与输入角度的角度差,然后将法线加上该角度差再加pi即可
# 需要注意的是最后结果要关于2pi取余
#print('当前速度角度值为:{}°'.format(math.degrees(self.rad)))
#print('输入法线角度为:{}°'.format(math.degrees(norm_vec_rad)))
delta = norm_vec_rad - self.rad
new_rad = ( delta + norm_vec_rad + math.pi ) % ( 2 * math.pi )
self.rad = new_rad
#print('反射后的速度角度为:{}°'.format(math.degrees(new_rad)))
self.velocity_loss(1)
def velocity_decompose(self):
''' 该函数将函数由向量模式分解为x,y向量模式的形式 '''
# 返回二维元组作为
x_v = self.amp * math.cos(self.rad)
y_v = self.amp * math.sin(self.rad)
return (x_v,y_v)
def velocity_loss(self,ratio):
''' 该函数将会根据传入的比例对速度进行衰减 '''
self.amp *= ratio
def velocity_add(self,amp):
''' '''
self.amp += amp
def velocity_map(self,rad):
''' 该函数将速度值映射到rad方向,其余方向分量清0 '''
self.rad = rad
self.amp = self.amp*cos(self.rad-rad)
#v1 = Velocity(1,0)
#v2 = Velocity(1,angle = 90)
#v3 = v1+v2
#v1.velocity_reflect(math.radians(45))
#v2.velocity_reflect(math.radians(45))
|
920557063e265c342d717aab8006280a4915274b | redkad/100-Days-Of-Code | /Day 8/Exercises/PaintsCalc.py | 230 | 3.953125 | 4 | import math
h = int(input('Enter height of wall: '))
w = int(input('Enter width of wall: '))
def calc(height, width):
coverage = math.ceil((height * width) / 5)
print(f'You will need {coverage} cans of paint')
calc(h,w) |
3c705aa273728a63f52475e67fdc9e2e37a661e3 | AaronCHH/jb_-Excel-Python- | /_build/jupyter_execute/Ch8.py | 2,552 | 3.921875 | 4 | # Ch08 資料運算
## 算術運算
import pandas as pd
data = {"C1":[1,4],"C2":[2,5],"C3":[3,6]}
df = pd.DataFrame(data,index = ["S1","S2"])
df
df["C1"] + df["C2"]
df["C1"] - df["C2"]
df["C1"] * df["C2"]
df["C1"] / df["C2"]
df["C1"] + 2
df["C1"] - 2
df["C1"] * 2
df["C1"] / 2
## 比較運算
df
df["C1"] > df["C2"]
df["C1"] != df["C2"]
df["C1"] < df["C2"]
## 彙總運算
### 非空格計數
df
df.count()
df.count(axis = 1)
df["C1"].count()
### sum求和
df
df.sum()
df.sum(axis = 1)
### mean求均值
df
df.mean()
df.mean(axis = 1)
df["C1"].mean()#對C1欄求均值
### max求最大值
df
df.max()
df.max(axis = 1)
df["C1"].max()#對C1欄求最大值
### min求最小值
df
df.min()
#求取每一列的最小值
df.min(axis = 1)
#求取C1欄的最小值
df["C1"].min()
### median求中位數
data = {"C1":[1,4,7],"C2":[2,5,8],"C3":[3,6,9]}
df = pd.DataFrame(data,index = ["S1","S2","S3"])
df
df.median()
#求取每一列的中位數
df.median(axis = 1)
#求取C1欄的中位數
df["C1"].median()
### mode求眾數
data = {"C1":[1,4,1],"C2":[4,4,6],"C3":[1,1,3]}
df = pd.DataFrame(data,index = ["S1","S2","S3"])
df
df.mode()
#求取每一列的眾數
df.mode(axis=1)
#求取C1欄的眾數
df["C1"].mode()
### var求變異數
data = {"C1":[1,4,7],"C2":[2,5,8],"C3":[3,6,9]}
df = pd.DataFrame(data,index = ["S1","S2","S3"])
df
df.var()
#求取每一列的變異數
df.var(axis = 1)
#求取C1欄的變異數
df["C1"].var()
### std求標準差
df
df.std()
#求取每一列的標準差
df.std(axis = 1)
#求取C1欄的標準差
df["C1"].std()
### quantile求分位數
data = {"C1":[1,4,7,10,13],"C2":[2,5,8,11,14],"C3":[3,6,9,12,15]}
df = pd.DataFrame(data,index = ["S1","S2","S3","S4","S5"])
df
df.quantile(0.25)#求四分之一分位數
df.quantile(0.75)#求四分之三分位數
#求取每一列的四分之一分位數
df.quantile(0.25, axis = 1)
#求取C1欄的四分之一分位數
df["C1"].quantile(0.25)
## 相關性運算
data = {"col1":[1,3,5,7,9],"col2":[2,4,6,8,10]}
df = pd.DataFrame(data,index = [0,1,2,3,4])
df
df["col1"].corr(df["col2"]) #求取col1欄與col2欄的相關係數
data = {"col1":[1,4,7,10,13],
"col2":[2,5,8,11,14],
"col3":[3,6,9,12,15]}
df = pd.DataFrame(data,index = [0,1,2,3,4])
df
#計算欄位col1、col2、col3兩兩之間的相關性
df.corr()
|
0c9840afd1456a0932563895a50e80fab74501f1 | gwolf/clase-sistop-2017-01 | /tareas/03/Gerardmc95/RR.py | 2,585 | 3.6875 | 4 | from collections import deque
import random
letra = ord('a')
b=0
totalEjecucion = 0
casillas = 0
RR = deque([])
lista = []
listaZ = []
#Diccionarios para guardar tiempos y tabla de tiempos
tiempoLlegada = {}
tiempoDuracion = {}
tiempoDuracionDos = {}
titulo = ['Proceso', 'Llegada', 'Duracion']
# Agregando elementos a RR
RR.appendleft('a')
RR.appendleft('b')
RR.appendleft('c')
RR.appendleft('d')
RR.appendleft('e')
#Damos duracion a cada proceso
for i in reversed(RR):
if i == 'a':
tiempoLlegada[i] = 0
tiempoDuracion[i] = random.randint(1,10)
tiempoDuracionDos[i] = tiempoDuracion[i]
totalEjecucion += tiempoDuracion[i]
else:
tiempoLlegada[i] = random.randint(1,3)
tiempoDuracion[i] = random.randint(1,10)
tiempoDuracionDos[i] = tiempoDuracion[i]
totalEjecucion += tiempoDuracion[i]
lista.append(tiempoLlegada[i])
#Ordenacion de los valores por tamano de duracion del diccionario 'tiempoLlegada' para dar una porcion equitativa
ordenada = tiempoDuracion.items()
ordenada.sort(key=lambda x : x[1])
#Una porcion justa en este caso seria la del procesos mas pequeno
listaAux = ordenada[b]
porcion = listaAux[1]
#Impresion de la tabla de tiempo
for i in titulo:
print i,"\t",
print
for i in range(5):
print chr(i+65),"\t\t",tiempoLlegada[chr(i+97)],"\t\t",tiempoDuracionDos[chr(i+97)]
print
#Funcion que coloca los segmentos de los procesos en forma de lista para simular los pedazos de los mismos
def cortador(let, diccionarioLet, porcionLet,listaLet):
tam = diccionarioLet[let]
#Si "tam >= porcion" da a entender que ese proceso tendra una longitud mayor a cero despues de quitarle un pedazo
if tam >= porcion:
for i in range(porcion-1):
print chr(ord(let)-32),
listaLet.append(let)
diccionarioLet[let] = tam - porcionLet
return porcionLet
#Si "tam < porcion" da a entender que ese proceso tendra una longitud igual a cero despues de quitarle un pedazo
elif (tam < porcionLet) and (tam > 0):
for i in range(tam-1):
print chr(ord(let)-32),
listaLet.append(let)
diccionarioLet[let] = 0
return tam
#Si no hay nada de proceso, simplemente no agregamos nada a la listaZ
else:
return 0
#While que se asegura los procesos se formen debidamente
while casillas < totalEjecucion:
#casillas cortara el while, y cortador es la funcion que recibe nombre de proceso, duracion, porcion a cortar y listaZ donde se guardaran
#los pedazos de cada proceso
casillas += cortador(chr(letra), tiempoDuracion, porcion, listaZ)
if letra < 101:
letra += 1
else:
letra = 97 |
37f1cfc126f1285231cfc0772dbb97fa20f03edd | kajal1301/python | /rec.py | 493 | 4.3125 | 4 | #recursion in python
num1= int(input("Enter a number: "))
#factorial using iterative method
def factorial_iterative(n):
fac=1
for i in range(n):
fac= fac*(i+1)
return fac
#factorial using recursive method
def factorial_rec(n):
fac= n
if n==1:
return 1
else:
return n*factorial_rec(n-1)
print("Factorial using iterative method:", factorial_iterative(num1))
print("Factorial using recursive method:", factorial_rec(num1))
|
bd6ac18c8d3385f4d9fb68cd1425a53c8c319c1f | mohab22/Mohab-ashraf | /Bank/main.py | 364 | 3.8125 | 4 | from Banker import Banker
from User import User
print("Welcome to Our bank\n")
while True:
user_or_banker = input("please choose are you ...?\n"+" 1 - User\n"+ " 2 - Banker\n"+" 3 - Exit\n")
if user_or_banker == "1":
User.main_user_function()
elif user_or_banker == "2":
Banker.main_banker_function()
else:
break
|
ec321c0a0628b3d9fa36b78e5c767455197d30ba | Blank1611/guvi_codekata | /vowel_consonant.py | 263 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 10 19:11:50 2019
@author: GRENTOR
"""
a = (input().lower())
vowel='aeiou'
if a.isalpha():
if a in vowel:
print("Vowel",end = "")
else:
print("Consonant",end = "")
else:
print("invalid")
|
f161bdc05402c49cd733d471b8b3e82f84c34c81 | akshat-max/Udacity-DSA-programs | /project1/Task1.py | 884 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 1:
How many different telephone numbers are there in the records?
Print a message:
"There are <count> different telephone numbers in the records."
"""
def count_uniq_phone_numbers(texts_and_calls):
uniq_num = set()
for info in texts_and_calls:
n1 = info[0]
n2 = info[1]
uniq_num.add(n1)
uniq_num.add(n2)
return len(uniq_num)
def print_answer():
data = texts + calls
count = count_uniq_phone_numbers(data)
print(F"There are {count} different telephone numbers in the records.")
print_answer()
|
14c8d36d0632b152511f1e714823794d6b89d333 | yesIamHasi/Python | /ArithmeticAnalysis/DiceMonteCarlo.py | 675 | 3.734375 | 4 | # Monte Carlo Simulation of Dice
import random
def dice(side, rolls): # rolls can't be zero.
''' Returns probability of a side in sample space of dice'''
sample_space = []
for i in range(1, rolls):
sample_space.append( random.randint(0, rolls) )
return float(sample_space.count(side)*100)/float(len(sample_space))
def average(_list):
''' Returns average of an integer/float list '''
counter = 0
for i in _list:
counter += i
return float(counter)/len(_list)
if __main__ == '__name__':
event = []
for i in range(10000):
# Find the probability of 1
event.append(dice(1, 57))
print average(event)
|
816bea9f13070a69ca9a1a4869c0e03e913771d3 | geekcomputers/Python | /create_dir_if_not_there.py | 937 | 3.953125 | 4 | # Script Name : create_dir_if_not_there.py
# Author : Craig Richards
# Created : 09th January 2012
# Last Modified : 22nd October 2015
# Version : 1.0.1
# Modifications : Added exceptions
# : 1.0.1 Tidy up comments and syntax
#
# Description : Checks to see if a directory exists in the users home directory, if not then create it
import os # Import the OS module
MESSAGE = "The directory already exists."
TESTDIR = "testdir"
try:
home = os.path.expanduser(
"~"
) # Set the variable home by expanding the user's set home directory
print(home) # Print the location
if not os.path.exists(
os.path.join(home, TESTDIR)
): # os.path.join() for making a full path safely
os.makedirs(
os.path.join(home, TESTDIR)
) # If not create the directory, inside their home directory
else:
print(MESSAGE)
except Exception as e:
print(e)
|
713a208d432f91963d0c113d75a70c49b015f1e4 | peeush-the-developer/computer-vision-learning | /OpenCV-102/05.opencv-thresholding/thresholding.py | 2,585 | 3.71875 | 4 | # Usage
# python thresholding.py -i ../../Data/Input/coins01.png
# Import libraries
import cv2
import argparse
# Add arguments from command line
ap = argparse.ArgumentParser()
ap.add_argument('-i', '--input', type=str, required=True, help="Input image")
args = vars(ap.parse_args())
# Load the image
image = cv2.imread(args["input"])
cv2.imshow("Original", image)
# To apply any thresholding, it is best practice to convert it to grayscale and blur it slightly
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (7, 7), 0)
cv2.imshow('Grayscale Blurred', blurred)
# Simple thresholding
# We are checking different threshold values to see the perfect value to define ROI for coins.
# And it looks like 200, 250 were the best to have ROI for coins.
# THRESH_BINARY_INV will set white (255) if pixel value < threshold_check value
# THRESH_BINARY will set white (255) if pixel value > threshold_check value
thresh_checks = [50, 100, 150, 200, 250]
for check in thresh_checks:
(T, thresh) = cv2.threshold(blurred, check, 255, cv2.THRESH_BINARY_INV)
print('Threshold Inv check={}'.format(check))
cv2.imshow(f"Thresholded Inv {check}", thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imshow('Grayscale Blurred', blurred)
thresh_checks = [50, 100, 150, 200, 250]
for check in thresh_checks:
(T, thresh) = cv2.threshold(blurred, check, 255, cv2.THRESH_BINARY)
print('Threshold check={}'.format(check))
cv2.imshow(f"Thresholded {check}", thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imshow('Grayscale Blurred', blurred)
# We can use thresh_inv as a mask and then bitwise_and with original image to segment coins out
_, thresh_inv = cv2.threshold(blurred, 200, 255, cv2.THRESH_BINARY_INV)
result = cv2.bitwise_and(image, image, mask=thresh_inv)
cv2.imshow("Segmented", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imshow('Grayscale Blurred', blurred)
# Otsu's thresholding
# As in Simple thresholding, we had to manually adjust the Threshold check value in order work with different images.
# With Otsu, we don't have to provide Threshold check value, it automatically finds the value for thresholding.
(T, thresh_inv) = cv2.threshold(blurred, 0,
255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
# It gives Threshold check value as 191.0
cv2.imshow(f"Otsu Thresholded w/ {T}", thresh_inv)
cv2.waitKey(0)
# Similarly, we can use this for segmentation
result = cv2.bitwise_and(image, image, mask=thresh_inv)
cv2.imshow("Segmented", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
5aa096a47e0f47e746e933a13680bd1986ac688d | aline-paille/BuZzleGame | /src/LettersGenerator.py | 1,765 | 3.578125 | 4 | #!/usr/bin/python3.1
from random import *
from Variables import *
# TODO : variable pour choisir si on prend l'alpha Francais ou anglais
VAR_LANGAGE = "Anglais"
class LettersGenerator:
def __init__(self, language):
self.lettersList = self.lettersHexagon(language)
def couple_probability(self, file):
""" fonction qui lit le fichier et retourne le couple dans lequel on a mit probas = valeur correspondant aux sommes des pourcentages associés a chaque lettre et alpha = lettre de l'alphabet """
probas = []
alpha = []
fic = open(file, 'r')
line = fic.readlines()
for i,e in enumerate(line) :
l1 = line[i].split()
probas.append(int(l1[1]))
alpha.append(l1[0])
fic.close()
return (probas, alpha)
def lettersHexagon(self, language):
"""fonction qui créer la liste de lettres utiles pour l'hexagone en majuscules """
if language == FRENCH_LANGUAGE:
file = "../probas_Alphabets/PourcentAlphaF.txt"
elif language == ENGLISH_LANGUAGE:
file = "../probas_Alphabets/PourcentAlphaA.txt"
else:
print("error : bad language")
return
res = self.couple_probability(file)
list1 = res[0]
list2 = res[1]
return [self.letter_alea(list1, list2).upper() for e in range(0,24)]
def letter_alea(self, probas, alphabet):
""" fonction qui choisit une lettre aleatoirement parmi un alphabet et en fonction de la proba de chaque lettre """
val = randint(0,probas[len(probas)-1]-1)
for i in range(0, len(probas)-1):
if val<=probas[i] and val<probas[i+1]:
return alphabet[i]
return "error"
|
4f087e372da3769d73c4de12a92d6170a9c132f0 | arkch99/CodeBucket | /CSE_Lab_Bucket/IT Workshop-Python/Day 09/prog7.py | 83 | 3.59375 | 4 | f=open("myfile.txt","r")
reader=f.readline().split()
for r in reader:
print(r)
|
957e297fbd283b8acda6324e6a399b6d8c2c98d1 | Alex0Blackwell/python-projects | /decisiveTest.py | 1,354 | 3.96875 | 4 | # Decisive test
import time as t
def length(time):
res = ''
if(time < 1):
res = f"{time} seconds is extremely fast."
elif(time < 3):
res = f"{time} seconds is pretty fast."
elif(time < 5):
res = f"{time} seconds is kind of fast."
elif(time < 10):
res = f"{time} seconds is pretty slow."
else:
res = f"{time} seconds is really slow."
return res
def main():
InvalidInput = True
while InvalidInput:
t0 = t.time()
yORn = input("Are you decisive?\n(y / n)\n(e to exit)\n")
yOrnClean = yORn.lower()
t1 = t.time()
totalTime = round(t1 - t0, 2)
if(yOrnClean == 'y' or yOrnClean == 'n'):
message = length(totalTime)
if(yOrnClean == 'y'):
if(totalTime < 5):
print(f"Maybe, {message}")
else:
print(f"I don't know, {message}")
else:
if(totalTime < 5):
print(f"I don't know, {message}")
else:
print(f"Maybe, {message}")
InvalidInput = False
else:
if(yOrnClean == 'e'):
print('Goodbye!')
InvalidInput = False
else:
print("Try inputting Y or N. Idiot.\n")
main()
|
4d423683645b1144b37c6f60a1faaee1e29ba430 | nataliab9910/Tic-Tac-Toe | /game.py | 12,954 | 3.890625 | 4 | """Część konsolowa projektu, określa logikę gry."""
import time
import random
BOARD = [' ', ' ', ' ',
' ', ' ', ' ',
' ', ' ', ' ']
HUMAN, COMPUTER, HUMAN_WIN, COMPUTER_WIN = range(4)
EMPTY = ' '
NO_WINNER = -1
ERROR = -1
SUCCESS = 'SUCCESS'
MAX_WAITING_SEC = 5
WIN_SCORE = 100
LOSE_SCORE = -100
INFINITY = 10000
FIELDS_IN_ROW = 3
FIELDS_IN_BOARD = 9
class Waiting:
"""Zapisuje czasy oczekiwania."""
# pylint: disable=too-few-public-methods
def __init__(self):
"""Inicjalizuje zerami wartości oczekiwania."""
self.expected = 0 # oczekiwany przyszły czas oczekiwania
self.all = 0 # sumaryczny czas oczekiwania
self.current = 0 # aktualny (ostatni) czas oczekiwania
self.previous = 0 # poprzedni czas oczekiwania
class Game:
"""Przeprowadza rozgrywkę w konsoli."""
def __init__(self):
"""Tworzy tablicę rozgrywki w konsoli i główne okno gry."""
self.board = BOARD[:]
self.current_player = COMPUTER
def print_board(self):
"""Rysuje planszę w konsoli."""
for i in range(FIELDS_IN_ROW):
print(f' {self.board[FIELDS_IN_ROW * i]} | '
f'{self.board[1 + FIELDS_IN_ROW * i]} | '
f'{self.board[2 + FIELDS_IN_ROW * i]}')
if i < 2:
print('---+---+---')
def flip_player(self):
"""Zmienia gracza, który wykonuje ruch."""
if self.current_player in (HUMAN, COMPUTER):
self.current_player = {COMPUTER: HUMAN, HUMAN: COMPUTER}[
self.current_player]
def humans_move(self, position):
"""Wykonuje ruch gracza."""
print('Gracz')
if Game.count_checkers(self.board, HUMAN) >= FIELDS_IN_ROW:
Game.remove_checker(self.board, position)
return
if Game.add_checker(self.board, position) == ERROR:
return
for i in range(0, FIELDS_IN_BOARD):
if self.board[i] == 'r':
self.board[i] = EMPTY
break
self.print_board()
win = Game.check_winner(self.board)
if win != NO_WINNER:
self.current_player = HUMAN_WIN
print('Wygrywasz!')
return
self.flip_player()
@staticmethod
def remove_checker(board, position):
"""Usuwa pionek gracza z wskazanej pozycji na planszy.
Jeśli na danej pozycji planszy nie ma właściwego pionka, wypisuje
informację o źle wybranej pozycji i nie zmienia stanu planszy.
:param board: plansza gry,
:param position: pozycja, z której chcemy usunąć pionek.
"""
if board[position] == HUMAN:
board[position] = 'r'
else:
print("Brak właściwego pionka do usunięcia na wybranej pozycji.")
@staticmethod
def add_checker(board, position):
"""Stawia pionek na pozycji na planszy wskazanej przez gracza.
Jeśli wybrana pozycja nie jest pusta lub w tym samym ruchu gracz usunął
z niej pionek, wypisuje informację o źle wybranej pozycji, zwraca błąd
i nie zmienia stanu planszy.
:param board: plansza gry,
:param position: pozycja, na której chcemy ustawić pionek,
:return: jeśli wybrano właściwą pozycję - SUCCESS, jeśli nie - ERROR.
"""
if board[position] == 'r':
print('Nie możesz postawić pionka w to samo miejsce, '
'z którego go usunąłęś.')
return_val = ERROR
elif board[position] == EMPTY:
board[position] = HUMAN
return_val = SUCCESS
else:
print("Nie możesz postawić pionka na zajętym miejscu.")
return_val = ERROR
return return_val
def computers_move(self):
"""Wykonuje ruch komputera."""
print('Komputer')
depth = 0
best_score = -INFINITY
best_remove_pos = best_add_pos = -1
waiting = Waiting()
# tablica do sprawdzania kolejnych ustawień pionków
copy_board = self.board[:]
if Game.count_checkers(copy_board, COMPUTER) >= FIELDS_IN_ROW:
# usuwa pionek i przestawia go w inne miejsce
while (waiting.all + waiting.expected < MAX_WAITING_SEC
and best_score < WIN_SCORE):
waiting.previous = waiting.current
waiting.current = time.time()
for remove_pos in [pos for pos in range(FIELDS_IN_BOARD) if
copy_board[pos] == COMPUTER]:
copy_board[remove_pos] = EMPTY
empty_positions = [pos for pos in range(FIELDS_IN_BOARD) if
(copy_board[pos] == EMPTY
and pos != remove_pos)]
random.shuffle(empty_positions)
for add_pos in empty_positions:
copy_board[add_pos] = COMPUTER
score = Game.minimax(depth, copy_board, HUMAN) + depth
if score > best_score:
best_score = score
best_remove_pos = remove_pos
best_add_pos = add_pos
copy_board[add_pos] = EMPTY
copy_board[remove_pos] = COMPUTER
waiting.current = time.time() - waiting.current
waiting.all += waiting.current
waiting.expected = Game.waiting_evaluate(waiting.previous,
waiting.current)
depth += 1
self.board[best_remove_pos] = EMPTY
self.board[best_add_pos] = COMPUTER
else:
# tylko dodaje pionek
while (waiting.all + waiting.expected < MAX_WAITING_SEC
and best_score < WIN_SCORE):
waiting.previous = waiting.current
waiting.current = time.time()
empty_positions = [pos for pos in range(FIELDS_IN_BOARD) if
copy_board[pos] == EMPTY]
random.shuffle(empty_positions)
for add_pos in empty_positions:
copy_board[add_pos] = COMPUTER
score = Game.minimax(depth, copy_board, HUMAN) + depth
if score > best_score:
best_score = score
best_add_pos = add_pos
copy_board[add_pos] = EMPTY
waiting.current = time.time() - waiting.current
waiting.all += waiting.current
waiting.expected = Game.waiting_evaluate(waiting.previous,
waiting.current)
depth += 1
self.board[best_add_pos] = COMPUTER
del waiting
print(f'Głębokość = {depth}')
self.print_board()
if Game.check_winner(self.board) != NO_WINNER:
self.current_player = COMPUTER_WIN
print('Wygrywa komputer!')
return
self.flip_player()
@staticmethod
def waiting_evaluate(previous, current):
"""Przybliża kolejnego wykonania pętli na podstawie dwóch poprzednich.
:param previous: czas przedostatniego wykonania pętli,
:param current: czas ostatniego wykonania pętli,
:return:
"""
if previous == 0:
expected = current
else:
expected = current * (current / previous)
return expected
@staticmethod
def minimax(depth, board, next_player):
"""Ocenia możliwe ruchy komputera tak, aby móc wyłonić ten najlepszy.
:param depth: maksymalna głębokość przewidywania ruchów,
:param board: plansza gry,
:param next_player: gracz, który będzie wykonywał następny ruch,
:return: ocena ruchu komputera.
"""
if depth == 0 or Game.check_winner(board) != NO_WINNER:
return Game.evaluate(board)
if next_player == COMPUTER:
evaluation = -INFINITY
else:
evaluation = INFINITY
if Game.count_checkers(board, next_player) >= FIELDS_IN_ROW:
for remove_pos in [pos for pos in range(FIELDS_IN_BOARD) if
board[pos] == next_player]:
board[remove_pos] = EMPTY
evaluation = Game.minimax_add(depth, board, next_player,
evaluation, remove_pos)
board[remove_pos] = next_player
else:
evaluation = Game.minimax_add(depth, board, next_player, evaluation)
return evaluation
@staticmethod
def minimax_add(depth, board, next_player, evaluation, remove_pos=-1):
"""Szuka najlepszego miejsca na planszy na dodanie pionka komputera.
:param depth: maksymalna głębokość przewidywania ruchów,
:param board: plansza gry,
:param next_player: gracz, który będzie wykonywał następny ruch,
:param evaluation: aktualna ocena ruchu,
:param remove_pos: miejsce, z którego w tym samym ruchu usunięto pionek,
:return: uaktualniona ocena ruchu.
"""
for add_pos in [pos for pos in range(FIELDS_IN_BOARD) if
board[pos] == EMPTY and pos != remove_pos]:
board[add_pos] = next_player
if next_player == COMPUTER:
score = Game.minimax(depth - 1, board, HUMAN)
if score > evaluation:
evaluation = score
else:
score = Game.minimax(depth - 1, board, COMPUTER)
if score < evaluation:
evaluation = score
board[add_pos] = EMPTY
return evaluation
@staticmethod
def evaluate(board):
"""Ocenia aktualny stan gry z punktu widzenia komputera.
:param board: plansza z aktualnym stanem gry,
:return: informacja o wygranej: WIN_SCORE - komputer,
LOSE_SCORE - człowiek,
NO_WINNER - nikt.
"""
if Game.check_winner(board) == COMPUTER:
score = WIN_SCORE
elif Game.check_winner(board) == HUMAN:
score = LOSE_SCORE
else:
score = NO_WINNER
return score
@staticmethod
def count_checkers(board, checker):
"""Liczy pionki danego gracza.
:param board: plansza gry,
:param checker: jakie pionki liczyć,
:return: liczba pionków danego gracza.
"""
number_of_checkers = 0
for i in range(0, FIELDS_IN_BOARD):
if board[i] == checker:
number_of_checkers += 1
return number_of_checkers
@staticmethod
def check_winner(board):
"""Sprawdza, czy ktoś ułożył zwycięską kombinację.
:param board: plansza gry,
:return: zwycięzca - ktoś wygrał, NO_WINNER - brak wygranej.
"""
winner = Game.check_columns(board)
if winner == NO_WINNER:
winner = Game.check_rows(board)
if winner == NO_WINNER:
winner = Game.check_diagonals(board)
return winner
@staticmethod
def check_columns(board):
"""Sprawdza, czy w kolumnie została ułożona zwycięska kombinacja.
:param board: plansza gry,
:return: zwycięzca - ktoś wygrał, NO_WINNER - brak wygranej.
"""
for i in range(0, FIELDS_IN_ROW):
if board[i] == board[FIELDS_IN_ROW + i] == board[6 + i] != EMPTY:
return board[i]
return NO_WINNER
@staticmethod
def check_rows(board):
"""Sprawdza, czy w rzędzie została ułożona zwycięska kombinacja.
:param board: plansza gry,
:return: zwycięzca - ktoś wygrał, NO_WINNER - brak wygranej.
"""
for i in range(0, FIELDS_IN_ROW):
if board[FIELDS_IN_ROW * i] == board[1 + FIELDS_IN_ROW * i] == \
board[2 + FIELDS_IN_ROW * i] != EMPTY:
return board[FIELDS_IN_ROW * i]
return NO_WINNER
@staticmethod
def check_diagonals(board):
"""Sprawdza czy na przekątnej została ułożona zwycięska kombinacja.
:param board: plansza gry,
:return: zwycięzca - ktoś wygrał, NO_WINNER - brak wygranej.
"""
if board[0] == board[4] == board[8] != EMPTY:
return board[0]
if board[2] == board[4] == board[6] != EMPTY:
return board[2]
return NO_WINNER
def reset(self):
"""Resetuje grę, aby rozgrywka mogła zacząć się od nowa."""
self.board = BOARD[:]
print('Nowa gra')
|
0db98c3e7d35d0b46d522b3d76443e6734c6cb68 | GabrielSuzuki/Daily-Interview-Question | /2020-12-30-Interview.py | 958 | 4.125 | 4 | #Hi, here's your problem today. This problem was recently asked by Amazon:
#Given a binary tree, return all values given a certain height h.
#Here's a starting point:
class Node():
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def valuesAtHeight(root, height):
#check if the left and right are None
#if so
values = []
if(root == None):
return values
if(height == 1):
values.append(root.value)
height -= 1
if(root.left != None):
left = (valuesAtHeight(root.left,height))
for i in left:
values.append(i)
if(root.right != None):
right = (valuesAtHeight(root.right,height))
for j in right:
values.append(j)
return values
# 1
# / \
# 2 3
# / \ \
# 4 5 7
a = Node(1)
a.left = Node(2)
a.right = Node(3)
a.left.left = Node(4)
a.left.right = Node(5)
a.right.right = Node(7)
print(valuesAtHeight(a, 3))
# [4, 5, 7]
|
13b1e7e7f146f81850f65f4903315ffe7b8cc389 | GrahamJamesKeane/CreditCalculator | /Problems/Particles/task.py | 597 | 3.703125 | 4 | spin = input()
charge = input()
particles = ["Strange", "Charm", "Electron", "Muon", "Photon"]
strange = ["Quark", "1/2", "-1/3"]
charm = ["Quark", "1/2", "2/3"]
electron = ["Lepton", "1/2", "-1"]
muon = ["Lepton", "1/2", "0"]
photon = ["Boson", "1", "0"]
if spin in strange and charge in strange:
print("Strange Quark")
elif spin in charm and charge in charm:
print("Charm Quark")
elif spin in electron and charge in electron:
print("Electron Lepton")
elif spin in muon and charge in muon:
print("Muon Lepton")
elif spin in photon and charge in photon:
print("Photon Boson") |
27d8dd42067af62bf1726ad49554df18232d19e6 | vaishakik/College | /Python_Assignments/P5-Cramers_rule.py | 1,888 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 22 12:46:43 2019
@author: vaishak
"""
#Cramer's rule
import numpy as np
print('Enter the number of unknown variables: ')
n=int(input())
#define a coefficient matrix of order n*n since we have n unknowns and n equations.
coeff_matrix=np.zeros([n,n])
#define a value matrix of order n*1 since we have n equations
value_matrix=np.zeros(n)
print('Enter the value of a,b,c,.......d of the equation of the form ax+by+cz+.........=d')
for i in range(n):
print('Enter the ',i,'th equation: ')
print('Enter the ',n,' coefficients: ')
for j in range(n):
coeff_matrix[i,j]=float(input())
print('Enter the value of the constant for ',i,' th equatuion: ')
value_matrix[i]=float(input())
#declare a temporary matrix to change the columns with the value matrix to find value of the unknowns.
temp_matrix=np.zeros([n,n])
#to copy all the rows and columns of coefficient matrix to the temp_matrix
temp_matrix[:,:]=coeff_matrix[:,:]
#determinant of the coefficient matrix.
coeff_det=np.linalg.det(temp_matrix)
#to take the determinant of the temp_matrix to see that we have unique solutions.
if(coeff_det==0):
print('The system of linear equations do not have unique solution.')
else:
#to declare a matrix to store the value of the unknowns. Since we have n unknowns the size of the matrix is n.
res=np.zeros(n)
for i in range(n):
#to copy the coefficient matrix into the temporary matrix.
temp_matrix[:,:]=coeff_matrix[:,:]
temp_matrix[:,i]=value_matrix
unknown_det=np.linalg.det(temp_matrix)
res[i]=unknown_det/coeff_det
print('The value of the unknowns from the given system of linear equations using Cramer\'s rule is: ')
for i in range(n):
print('Unknown variable',i,' value : ',res[i]) |
80f25bfb4ca94a4094ad2262484e59292d31eb1f | AlbertLZG/AlbertLZG_Lintcode | /aplusb_1.py | 506 | 3.59375 | 4 | class Solution:
"""
@param a: The first integer
@param b: The second integer
@return: The sum of a and b
"""
def aplusb(self, a, b):
# write your code here, try to do it without arithmetic operators.
import ctypes
a = ctypes.c_int32(a).value
b = ctypes.c_int32(b).value
while b != 0:
carry = ctypes.c_int32(a & b).value
a = ctypes.c_int32(a ^ b).value
b = ctypes.c_int32(carry << 1).value
return a |
64e51067968e75cfefdeffbcafb484e8983a1864 | Gagan-453/Python-Practicals | /GUI/Frame/Spinbox Widget.py | 2,366 | 4.28125 | 4 | # SPINBOX WIDGET
# Spinbox widget allows the user to select values from a given set of values
# Spinbox appears as a long rectangle attached with arrowheads pointing towards up and down, the user can click on arrowheads to see the next value or previous value
from tkinter import *
class MySpinbox:
# constructor
def __init__(self, root):
self.f = Frame(root, height=350, width=500)
#Let the frame will not shrink
self.f.propagate(0)
#Attach the frame to the root window
self.f.pack()
# These are control variables for spinboxes
self.val1 = IntVar()
self.val2 = StringVar()
# Create Spinbox with numbers 5 to 15
# option 'from_' represents the starting of the range, 'to' represents the ending of range, 'textvariable' shows the control vaariable.i.e val1 that is created as an object of IntVar class
self.s1 = Spinbox(self.f, from_= 5, to=15, textvariable=self.val1, width=15, fg='black', bg='LightGreen', font=('Arial', 14, 'bold'))
# Create Spinbox with a tuple of strings
# The fixed strings that are displayed in the spin box are mentioned in 'values' option as a tuple, the 'textvariable' option indicates the control variable value 'val2' that is created as an object of StringVar class
self.s2 = Spinbox(self.f, values=('Hyderabad', 'Tirupati', 'Bangalore', 'Delhi'), textvariable=self.val2, width=15, fg='blue', bg='yellow', font=('Arial', 14, 'bold italic'))
# Create a button and bind it with display() method
self.b = Button(self.f, text='Get values from spin boxes', command=self.display)
# Place the spin boxes and button widgets in the frame
self.s1.place(x=50, y=50)
self.s2.place(x=50, y=100)
self.b.place(x=50, y=150)
def display(self):
#retrieve the values from spin box widgets
a = self.val1.get()
s = self.val2.get()
#Display the values using labels
lbl = Label(text='Selected value is: '+str(a)).place(x=50, y=200)
lbl2 = Label(text='Selected city is: '+s).place(x=50, y=220)
# Create root window
root = Tk()
#Create an object to MySpinbox class
mr = MySpinbox(root)
#The root window handles the mouse click event
root.mainloop() |
1b668fa6a2be367a61df12818573e9f805c566b0 | JUNGSUNWOO/Algorithm_study | /acmicpc/21년 1월/20210124/같은숫자는싫어.py | 366 | 3.859375 | 4 | arr= [3,2,6]
divisior = 10
def solution(arr, divisor):
answer = []
for i in arr:
if i % divisor == 0:
answer.append(i)
answer.sort()
if len(answer) == 0:
answer = -1
return answer
res = solution(arr, divisior)
print(res)
'''
def solution(arr, divisor): return sorted([n for n in arr if n%divisor == 0]) or [-1]
''' |
4651d633d54cb07a450fa4eaea49af2fa6304bfc | danielfess/Think-Python | /rotate.py | 674 | 4.0625 | 4 | def rotate_word(word,int):
"""Encrypts (word) using a Caesar cypher, rotating word by the integer (int).
"""
new_word = ''
for letter in word:
if 97 <= ord(letter.lower()) <= 122 :
new_letter = chr((int + ord(letter.lower())-ord('a'))%26 + ord('a'))
else:
new_letter = letter
new_word = new_word + new_letter
return new_word
encrypted_joke = "Uv gurer. Guvf vf abg ernyyl wbxr. Whfg univat fbzr sha jvgu gubfr jub pna'g ebg13 na negvpyr. Gb or ernyyl zrna, sbyybj-hc gb guvf negvpyr jvgu fbzrguvat yvxr 'Obl, gung jnf gur shaavrfg wbxr V rire urneq!' Stush"
print(rotate_word(encrypted_joke,-13))
|
31b137034e1c74ae3965a0e5d3c893b047c3c1eb | rwardman/advent-of-code | /2020/day3/day3.py | 800 | 3.75 | 4 | data = open("day3.txt", "r").read().splitlines()
openSquare = data[0][0]
tree = data[0][6]
def howManyTrees(right, down):
position = right
iterator = down
trees = 0
openSquares = 0
for rowIterator in range(0, int((len(data))/down) - 1):
row = data[iterator]
res_row = row * 100
obstacle = res_row[position]
position += right
if obstacle == openSquare:
openSquares += 1
elif obstacle == tree:
trees += 1
iterator += down
print("Trees encountered for right ", right, " down ", down, " is ", trees)
return trees
first = howManyTrees(1,1)
second = howManyTrees(3,1)
third = howManyTrees(5,1)
fourth = howManyTrees(7,1)
fifth = howManyTrees(1,2)
finalResult = first * second * third * fourth * fifth
print("Multiplied trees", finalResult) |
f17520c1c7f59d1ee66d8ea7c2dacc027963c1e0 | e-gautier/daily-coding-problem | /8-12_23_2018.py | 1,050 | 4.21875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
""" This problem was asked by Google.
A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
0
/ \
1 0
/ \
1 0
/ \
1 1
"""
class Node:
def __init__(self, value, left = None, right = None):
self.left = left
self.right = right
self.value = value
c1 = Node("1")
c2 = Node("1")
b1 = Node("1", c1, c2)
b2 = Node("0")
a1 = Node("1")
a2 = Node("0", b1, b2)
root = Node("root", a1, a2)
def is_unival_subtree(tree):
if (tree.left and tree.left.value != tree.value):
return False
if (tree.right and tree.right.value != tree.value):
return False
return True
def count(node):
amount = 0
amount += count(node.left) if node.left else 0
amount += count(node.right) if node.right else 0
if (is_unival_subtree(node)):
return amount + 1
return amount
print count(root) |
85b46f689925d816fbb5081ebc5d3db7b6f4d66a | brianboring/Treehouse-Python-Track | /1_2_Basics_Collections/slices.py | 465 | 3.640625 | 4 | def first_4(iterable):
word1 = iterable[:4]
print(word1)
def first_and_last_4(iterable):
first4 = iterable[:4]
last4 = iterable[-4:]
print(first4)
print(last4)
new_word = first4 + last4
print(new_word)
def odds(iterable):
word1 = iterable[1::2]
print(word1)
def reverse_evens(iterable):
even1 = iterable[::2]
print(even1)
reverse1 = even1[::-1]
print(reverse1)
reverse_evens([1, 2, 3, 4, 5])
|
9d7ffd33bd383f11710d2cc3a31109bbd595a2ce | isai-samir/Clase-Archivo | /archivo.py | 6,587 | 3.546875 | 4 | from sys import exit
class Archivo:
def __init__(self,nombre):
try:
self.archivo = open(nombre,'r')
self.nonbre = nombre
self.copia = open("copia.txt",'w')
#El nombre de la excepcion es la siguiente
except FileNotFoundError:
print("No se puede abir el archivo ",nombre)
exit()
def muestra(self):
i = 1
for linea in self.archivo:
print("{:3}:{}".format(i,linea),end = "")
i += 1
#cada vez que se lee el archivo se tiene que pocicionar el puntero al inicio para que no apunte al final del archivo
self.archivo.seek(0)
#Funcion encontrar,recibe 2 cadenas la primera es el conjunto donde se buscara, y el segundo es lo que se buscara
@staticmethod
def encuentra(cadena,conjunto):
contador = 0
for i in range(len(cadena)):
if cadena[i] in conjunto:
contador += 1
#se retorna la cantidad de veces que aparece en la cadena
return contador
def cuentaVocales(self):
contador = 0
# con el for se lee linea por linea
for linea in self.archivo:
#para cada linea se busca las vocales com acento y sin acento y mayusculas y minusculas.
contador += Archivo.encuentra(linea,"aeiouAEIOUáéíóúÁÉÍÓÚ")
self.archivo.seek(0)
return contador
def cuentaConsonantes(self):
contador = 0
for linea in (self.archivo):
contador += Archivo.encuentra(linea,"bcdfghjklmnñpqrstvwxyzBCDFGHJKLMNÑPQRSTVWXYZćǵḱĺḿńṕŕśẃýźĆǴḰĹḾŃṔŔŚǗẂÝŹ")
self.archivo.seek(0)
return contador
def cuentaSignosPuntuacion(self):
contador = 0
for linea in self.archivo:
contador += Archivo.encuentra(linea,".:,;\'\"¿?!¡-ćǵḱĺḿńṕŕśẃýźĆǴḰĹḾŃṔŔŚǗẂÝŹáéíóúÁÉÍÓÚ")
self.archivo.seek(0)
return contador
def cuentaEspacios(self):
contador = 0
for linea in self.archivo:
contador += Archivo.encuentra(linea," ")
self.archivo.seek(0)
return contador
def cuentaPalabras(self):
palabras = 0
for linea in self.archivo:
i = 0
if len(linea) != 0 and linea[0] != " ":
palabras += 1
#se tiene que recorrer todos los espacios en blanco por que pueden que hayan 2 o mas y eso no seria una palabra
while i < len(linea):
if linea[i] == " ":
while i < len(linea) and linea[i] == " ":
i += 1
palabras += 1
i += 1
self.archivo.seek(0)
return palabras
def cuentaLineas(self):
contador = 0
for linea in self.archivo:
contador += 1
self.archivo.seek(0)
return contador
def cuentaMayusculas(self):
contador = 0
for linea in self.archivo:
contador += Archivo.encuentra(linea,"ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁĆÉǴÍḰĹḾŃÓṔŔŚÚǗẂÝŹ")
self.archivo.seek(0)
return contador
def cuentaMayusculas2(self):
contador = 0
for linea in self.archivo:
for i in range(len(linea)):
if ord(linea[i]) >= 65 and ord(linea[i]) <= 90:
contador += 1
self.archivo.seek(0)
return contador
def cuentaMinusculas(self):
contador = 0
for linea in self.archivo:
contador += Archivo.encuentra(linea,"abcdefghijklmnñopqrstuvwxyzáćéǵíḱĺḿńóṕŕśúǘẃýź")
self.archivo.seek(0)
return contador
def cuentaMinusculas2(self):
contador = 0
for linea in self.archivo:
for i in range(len(linea)):
if ord(linea[i]) >= 97 and ord(linea[i]) <= 122:
contador += 1
self.archivo.seek(0)
return contador
def copiaArchivo(self):
try:
#se usa la funcion write para escribir por lineas la copia del archivo
for linea in self.archivo:
self.copia.write(linea)
self.archivo.seek(0)
#al terminar de usarse se cierran los archivos
self.copia.close()
print("Se creo una copia de su archivo, su nombre es copia.txt\nSu contenido es")
for linea in self.archivo:
print(" ",linea,end = "")
self.archivo.seek(0)
except FileNotFoundError:
print("No se puede crear el archivo ",nombre)
def convierteAMayusculas(self):
print("La cadena convertida a mayusculas es ")
for linea in self.archivo:
#para convertir a mayusculas se usa la funcion upper
print(" ",linea.upper(),end = "")
self.archivo.seek(0)
def convierteAMinusculas(self):
print("La cadena convertida a minusculas es ")
for linea in self.archivo:
#para convertir a minusculas se usa la funcion lower
print(" ",linea.lower(),end = "")
self.archivo.seek(0)
def muestraHexadecimal(self):
print("La cadena convertida a hexadecimal es ")
for linea in self.archivo:
print(" ",linea,end = "")
for i in range(len(linea)):
#para mostrar a hexadecimal se usa la funcion hex y la funcion ord
print(hex(ord(linea[i])),end = "")
print("")
self.archivo.seek(0)
nombre = input("Da el nombre del archivo ")
archivo = Archivo(nombre)
archivo.muestra()
print("El total de vocales es ",archivo.cuentaVocales())
print("El total de consonantes es ",archivo.cuentaConsonantes())
print("El numero de signos de puntuacion es ",archivo.cuentaSignosPuntuacion())
print("El numero de espacios en blanco es ",archivo.cuentaEspacios())
print("El total de palabras es ",archivo.cuentaPalabras())
print("El total de lineas es ",archivo.cuentaLineas())
print("El total de mayusculas es ",archivo.cuentaMayusculas())
print("El total de minusculas es ",archivo.cuentaMinusculas())
archivo.copiaArchivo()
archivo.convierteAMayusculas()
archivo.convierteAMinusculas()
archivo.muestraHexadecimal()
#es importante cerrar el archivo al final para evitar errores
archivo.archivo.close()
|
2cb628e21d6e192f2bc50a8276e692fbd2b12dbb | ilante/exercises_python_lpthw | /ex15.py | 762 | 4.03125 | 4 | from sys import argv # uses argv to get a filename
script, filename = argv
txt = open(filename) #opens file
print(f"Here's your file {filename}: ")
print(txt.read())
print("Type the filename again: ")
fileagain = input("> ")
txtagain = open(fileagain)
print(txtagain.read())
# What we want to do is "open" that file in
# our script and print it out. However, we
# do not want to just "hard code" the name
# ex15_sample.txt into our script. "Hard
# coding" means putting some bit of
# information that should come from the user
# as a string directly in our source code.
# That's bad because we want it to load other
# files later. The solution is to use argv or
# input to ask the user what file to open
# instead of "hard coding" the file's name.
|
2687a04cfdb6ca141cdd809e49034532093aa8c5 | CrazyCoder4Carrot/leetcode | /algorithm/Python/Missing Number.py | 346 | 3.703125 | 4 | class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = len(nums)
expectedsum = (0+count)*(count+1)/2
inputsum = sum(nums)
return expectedsum - inputsum
solution = Solution()
nums = [0,1,2,4]
print solution.missingNumber(nums) |
e8b2f0900a0bd5b31fb91c1061452fececa1b6aa | BokiceLee/python_code_in_cookbook | /chapter3/3_08.py | 407 | 4.28125 | 4 | #分数运算
from fractions import Fraction
#fractions模块用来执行包含分数的数学计算
a=Fraction(5,4)
b=Fraction(7,16)
print(a+b)
print(a*b)
print(a.numerator)#分子
print(a.denominator)#坟墓
print(float(a))
#通过限制分母获得一个被覆盖的分数
print(b.limit_denominator(16))
#小数转化为分数
x=3.75
print(x.as_integer_ratio())
y=Fraction(*x.as_integer_ratio())
print(y) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.