blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
f4877ce87cdf4c457beab854a36410484b6fe6a7 | ignaciorosso/Practica-diaria---Ejercicios-Python | /Estructura secuencial/estr_secuencial4.py | 508 | 3.921875 | 4 | # Escribir un programa en el cual se ingresen cuatro números, calcular e informar la suma
# de los dos primeros y el producto del tercero y el cuarto
num1 = int(input('Ingrese el primer numero: '))
num2 = int(input('Ingrese el segundo numero: '))
num3 = int(input('Ingrese el tercero numero: '))
num4 = int(input('Ingrese el cuarto numero: '))
suma = num1 + num2
producto = num3 * num4
print('La suma de los dos primeros es: {}\nEl producto de los dos segundos es: {}'.format(suma, producto)) |
6f07bcca69bafd2a27fcfca940c3dfedd796479e | bandofcs/boilerplate-arithmetic-formatter | /arithmetic_arranger.py | 5,491 | 3.890625 | 4 | import re
#Enable checking by printing to console
DEBUG= False
def arithmetic_arranger(problems, count=None):
#Variables definition
#To be printed out
firstrow=list()
secondrow=list()
thirdrow=list()
forthrow=list()
#Length of each operand
firstlen=0
secondlen=0
thirdlen=0
maxlen=0
#Result variable
third=None
#Check that no more than 5 problems
if len(problems) > 5:
return "Error: Too many problems."
#Go through each problem
for problem in problems:
#Make sure that inputs are only digits
try:
first=int(''.join(re.findall("^([^\s]+)", problem)))
except:
if DEBUG:
print("regex is"+''.join(re.findall("^./S", problem)))
return "Error: Numbers must only contain digits."
#Make sure that operand cannot be more than 4 digits
if first > 9999:
return "Error: Numbers cannot be more than four digits."
if DEBUG:
print(first)
#Make sure that inputs are only digits
try:
second=int(''.join(re.findall("([^\s]+)$", problem)))
except:
return "Error: Numbers must only contain digits."
#Make sure that operand cannot be more than 4 digits
if second > 9999:
return "Error: Numbers cannot be more than four digits."
if DEBUG:
print(second)
#Make sure that operator is only +/-
operator=''.join(re.findall("[+-]", problem))
if operator != "+" and operator != "-":
return "Error: Operator must be '+' or '-'."
if DEBUG:
print(operator)
#print empty spaces for second problem and beyond
if maxlen>0:
firstrow.append(" ")
secondrow.append(" ")
thirdrow.append(" ")
if count==True and maxlen>0:
forthrow.append(" ")
#Find the number of digits in the first operand
if first>999:
firstlen=4
elif first>99:
firstlen=3
elif first>9:
firstlen=2
elif first<10:
firstlen=1
#Find the number of digits in the second operand
if second>999:
secondlen=4
elif second>99:
secondlen=3
elif second>9:
secondlen=2
elif second<10:
secondlen=1
#Find the bigger number of digits between the 2 operands
maxlen=max(secondlen,firstlen)+2
if count==True:
if operator =="+":
third=first+second
elif operator == "-":
third=first-second
if third>9999:
thirdlen=5
for i in range(maxlen-thirdlen):
forthrow.append(" ")
forthrow.append(str(third))
elif third>999:
thirdlen=4
for i in range(maxlen-thirdlen):
forthrow.append(" ")
forthrow.append(str(third))
elif third>99:
thirdlen=3
for i in range(maxlen-thirdlen):
forthrow.append(" ")
forthrow.append(str(third))
elif third>9:
thirdlen=2
for i in range(maxlen-thirdlen):
forthrow.append(" ")
forthrow.append(str(third))
elif third>-1:
thirdlen=1
for i in range(maxlen-thirdlen):
forthrow.append(" ")
forthrow.append(str(third))
elif third>-10:
thirdlen=2
for i in range(maxlen-thirdlen):
forthrow.append(" ")
forthrow.append(str(third))
elif third>-100:
thirdlen=3
for i in range(maxlen-thirdlen):
forthrow.append(" ")
forthrow.append(str(third))
elif third>-1000:
thirdlen=4
for i in range(maxlen-thirdlen):
forthrow.append(" ")
forthrow.append(str(third))
elif third>-10000:
thirdlen=5
for i in range(maxlen-thirdlen):
forthrow.append(" ")
forthrow.append(str(third))
#Append spaces followed by first operand
for i in range(maxlen-firstlen):
firstrow.append(" ")
firstrow.append(str(first))
#Append operator followed by spaces and second operand
secondrow.append(operator)
for i in range(maxlen-secondlen-1):
secondrow.append(" ")
secondrow.append(str(second))
#Append "-" equals to the bigger number of digits between the 2 operands +2
for i in range(maxlen):
thirdrow.append("-")
if DEBUG:
print(''.join(firstrow))
print(''.join(secondrow))
print(''.join(thirdrow))
print(''.join(forthrow))
firstrow.append("\n")
secondrow.append("\n")
if count==True:
thirdrow.append("\n")
arranged_problems=''.join(firstrow + secondrow + thirdrow + forthrow)
return arranged_problems
arranged_problems=''.join(firstrow + secondrow + thirdrow)
if DEBUG:
print(type(arranged_problems))
return arranged_problems |
52cc76357437997addea4a148547c42b0f457751 | daniel-reich/ubiquitous-fiesta | /MbPpxYWMRihFeaNPB_8.py | 123 | 3.734375 | 4 |
def sum_of_evens(lst):
total = 0
for el in lst:
total += sum([num for num in el if num % 2 == 0])
return total
|
3f8f0b0f1d28a1277fea3536766ec20b765c9e2b | phanhr/c4t-20 | /hack3/part3_2.py | 288 | 3.859375 | 4 | computer = {
"HP" : 20,
"Dell" : 50,
"Macbook" : 12,
"Asus" : 30
}
computer["Toshiba"] = 10
for k,v in computer.items():
print(k, ':', v)
computer["Fujitsu"] = 15
computer["Alienware"] = 5
Sum = 0
for eachItem in computer.values():
Sum = Sum + eachItem
print(Sum)
|
b8ca5e3e8c0a3a2616289f75cd14c45be22c7bf6 | AlbinoGazelle/TSTP | /Chapter2/challenge3.py | 164 | 4.0625 | 4 | x = 10
if x <= 10:
print("x is less than or equal to 10")
if x >= 25:
print("x is greater than or equal to 25")
if x > 25:
print("x is greater than 25") |
8b47c306f41b9b343b7c90e9e2a5bd8267cbf79b | rohit98077/pythonScripts | /dateDifference.py | 770 | 4.0625 | 4 | def date_diff(date1,date2):
dateLst=date1.split('/')
d1,m1,y1=int(dateLst[0]),int(dateLst[1]),int(dateLst[2])
dateLst=date2.split('/')
d2,m2,y2=int(dateLst[0]),int(dateLst[1]),int(dateLst[2])
if d2<d1:
if m2==3:
if y2%100 !=0 and y2%4==0 or y2%400==0:
d2+=29
else:
d2+=28
elif m2==5 or m2==7 or m2==10 or m2==12:
d2+=30
else:
d2+=31
m2-=1
if m2<m1:
m2+=12
y2-=1
y=y2-y1
m=m2-m1
d=d2-d1
print('Diff of two dates is : '+str(y)+' years '+str(m)+' months '+str(d)+' days')
return None
date1=input('Enter first date as dd/mm/yyyy :')
date2=input('Enter second date as dd/mm/yyyy :')
while date1 and date2:
date_diff(date1,date2)
print('Enter another date pair to check or just hit enter to leave.')
date1=input()
date2=input()
|
ad100ef069dcd0fd3a4a0a44a1c9fd451cc53efd | ledao/lufly-im | /scripts/segger.py | 889 | 3.6875 | 4 | from typing import List, Set
class Segger(object):
def __init__(self, words: Set[str], max_len: int=5):
super(Segger).__init__()
self.words: Set[str] = words
self.max_len: int = max_len
def cut(self, sent: str)-> List[str]:
index = 0
segments = []
while index < len(sent):
find = False
for l in range(self.max_len, 0, -1):
word = sent[index:index+l]
if word in self.words:
segments.append(word)
index += l
find = True
break
if not find:
segments.append(sent[index])
index += 1
return segments
if __name__ == "__main__":
segger = Segger(set(["abc", "de"]), 3)
print(segger.cut("abcde")) |
8eff17c354245e2833542f701211120bf3e0694b | mcfair/Algo | /Path Sum/437. Path Sum III.py | 3,201 | 3.96875 | 4 | # https://leetcode.com/problems/path-sum-iii/discuss/91892/Python-solution-with-detailed-explanation
"""
Double DFS - elegant
similar to the way we write preorder traversal
Time = O(nlogn) if balanced tree, else worst case O(n^2)
"""
#Find number of paths
class SolutionFindNumberOfPaths(object):
def find_paths(self, root, target):
if root:
return int(root.val == target) + \
self.find_paths(root.left, target-root.val) + \
self.find_paths(root.right, target-root.val)
return 0
def pathSum(self, root, sum):
if root:
return self.find_paths(root, sum) + \
self.pathSum(root.left, sum) + \
self.pathSum(root.right, sum)
return 0
#Find all possible paths
class SolutionFindAllPaths(object):
def find_paths(self, root, target, path):
if not root:
return
if root.val == target:
self.paths.append(path+[root.val])
self.find_paths(root.left, target-root.val, path+[root.val])
self.find_paths(root.right, target-root.val,path+[root.val])
def preorder(self, root, sum):
if root:
self.find_paths(root, sum, [])
self.preorder(root.left, sum)
self.preorder(root.right, sum)
def pathSum(self, root, sum):
self.paths = []
self.preorder(root, sum)
return self.paths
"""
Two Sum Method: Optimized Solution
- A more efficient implementation uses the Two Sum idea. It uses a hash table (extra memory of order N).
With more space, it gives us an O(N) complexity.
- As we traverse down the tree, at an arbitrary node N, we store the sum from root to this node N in hash-table.
prefixsum(root->N) = prefixsum(root->parent_of_N) + N.val
- Now at a grand-child of N, say G, we can compute the sum from the root until G since we have the prefix_sum until this grandchild available.
We pass in our recursive routine.
- How do we know if we have a path of target sum which ends at this grand-child G? Say there are multiple such paths that end at G and say they start at A, B, C where A,B,C are predecessors of G. Then sum(root->G) - sum(root->A) = target. Similarly sum(root->G)-sum(root>B) = target. Therefore we can compute the complement at G as sum_so_far+G.val-target and look up the hash-table for the number of paths which had this sum
- Now after we are done with a node and all its grandchildren, we remove it from the hash-table. This makes sure that the number of complement paths returned always correspond to paths that ended at a predecessor node.
"""
class Solution:
def pathSum(self, root, target):
self.ans = 0
cache = collections.defaultdict(int)
cache[0] = 1 #target = 0 has a least 1 path, which is [None]
def dfs(node, cur_sum):
if node:
cur_sum += node.val
self.ans += cache[cur_sum - target]
cache[cur_sum] += 1
dfs(node.left, cur_sum)
dfs(node.right, cur_sum)
cache[cur_sum] -= 1
dfs(root, 0)
return self.ans
|
4ece20b96c9b958a85ea76a960a2765a80a91680 | amakumi/Binus_TA_Session_Semester_1 | /QUIZ 1/QUIZ 1 - #1.py | 297 | 3.90625 | 4 | p = str(input("Input Symbol Character: "))
x = int(input("Input Number: "))
print("")
for row in range(0, x, 1):
for col in range(0, x, 1):
if row == col or (row == x - col - 1):
print(p, end = "")
else:
print(" ", end = "")
print("")
|
8b92c6f01c7ae5125e8075579c4ffc177eb6b87e | alexsidorenko/testing | /main.py | 99 | 3.625 | 4 | my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for i in my_list:
if i < 15:
print(i)
|
28e3996306992c7ee353f37863b18fa1da09d694 | YusiZhang/leetcode-python | /DFS_BackTrack/array_wordSearch.py | 1,316 | 3.640625 | 4 | __author__ = 'yusizhang'
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
if not board or not board[0]:
return False
n = len(board)
m = len(board[0])
visited = [[False for j in range(m)] for i in range(n)]
for i in range(n):
for j in range(m):
if self.findWord(board, visited, i, j, word, 0):
return True
return False
def findWord(self, board, visited, row, col, word, index):
if index == len(word):
return True
if row < 0 or col < 0 or row >= len(board) or col >= len(board[0]) or visited[row][col] or board[row][col] != word[index]:
return False
visited[row][col] = True
if self.findWord(board, visited, row-1, col, word, index+1): return True
if self.findWord(board, visited, row+1, col, word, index+1): return True
if self.findWord(board, visited, row, col-1, word, index+1): return True
if self.findWord(board, visited, row, col+1, word, index+1): return True
visited[row][col] = False
return False
if __name__ == '__main__':
print Solution().exist(["ABCE","SFCS","ADEE"], "ABCCED") |
de9481dc132ceee4e4d068ff3eb52f298b5fbf41 | DreamDZhu/python | /week-4/day29_tcp编程,粘包/tcp粘包/struct模块.py | 696 | 3.515625 | 4 | import struct
num1 = 2147483646
num2 = 138
num3 = 8
# struct.pack用于将Python的值根据格式符,转换为字符串(因为Python中没有字节(Byte)类型,可以把这里的字符串理解为字节流,或字节数组)。其函数原型为:struct.pack(fmt, v1, v2, ...),参数fmt是格式字符串,关于格式字符串的相关信息在下面有所介绍。v1, v2, ...表示要转换的python值。
ret1 = struct.pack('i', num1)
print(ret1)
ret2 = struct.pack('i',num2)
print(ret2)
ret3 = struct.pack('i',num3)
print(ret3)
res1 = struct.unpack('i',ret1)
res2 = struct.unpack('i',ret2)
res3 = struct.unpack('i',ret3)
print(res1)
print(res2)
print(res3)
|
90b661bbea71fe598c1cec93f2a55d50d5b19aac | wycleffsean/coursera-coding-the-matrix | /politics_lab.py | 6,515 | 4.25 | 4 | voting_data = list(open("voting_record_dump109.txt"))
## Task 1
def create_voting_dict():
"""
Input: None (use voting_data above)
Output: A dictionary that maps the last name of a senator
to a list of numbers representing the senator's voting
record.
Example:
>>> create_voting_dict()['Clinton']
[-1, 1, 1, 1, 0, 0, -1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, 1]
This procedure should return a dictionary that maps the last name
of a senator to a list of numbers representing that senator's
voting record, using the list of strings from the dump file (strlist). You
will need to use the built-in procedure int() to convert a string
representation of an integer (e.g. '1') to the actual integer
(e.g. 1).
You can use the split() procedure to split each line of the
strlist into a list; the first element of the list will be the senator's
name, the second will be his/her party affiliation (R or D), the
third will be his/her home state, and the remaining elements of
the list will be that senator's voting record on a collection of bills.
A "1" represents a 'yea' vote, a "-1" a 'nay', and a "0" an abstention.
The lists for each senator should preserve the order listed in voting data.
"""
voting = dict()
for row in voting_data:
cols = row.split()#for cols in row.split(' '):
#print(cols)
voting[cols[0]] = [ int(cols[i]) for i in range(3, len(cols)) ]
return voting
## Task 2
def policy_compare(sen_a, sen_b, voting_dict):
"""
Input: last names of sen_a and sen_b, and a voting dictionary mapping senator
names to lists representing their voting records.
Output: the dot-product (as a number) representing the degree of similarity
between two senators' voting policies
Example:
>>> voting_dict = {'Fox-Epstein':[-1,-1,-1,1],'Ravella':[1,1,1,1]}
>>> policy_compare('Fox-Epstein','Ravella', voting_dict)
-2
"""
sum = 0
for i in range(len(voting_dict[sen_a])):
sum += voting_dict[sen_a][i] * voting_dict[sen_b][i]
return sum
## Task 3
def most_similar(sen, voting_dict):
"""
Input: the last name of a senator, and a dictionary mapping senator names
to lists representing their voting records.
Output: the last name of the senator whose political mindset is most
like the input senator (excluding, of course, the input senator
him/herself). Resolve ties arbitrarily.
Example:
>>> vd = {'Klein': [1,1,1], 'Fox-Epstein': [1,-1,0], 'Ravella': [-1,0,0]}
>>> most_similar('Klein', vd)
'Fox-Epstein'
Note that you can (and are encouraged to) re-use you policy_compare procedure.
"""
comp = [(policy_compare(sen, x, voting_dict), x) for x in voting_dict if x != sen]
comp.sort()
comp.reverse()
return comp[0][1]
## Task 4
def least_similar(sen, voting_dict):
"""
Input: the last name of a senator, and a dictionary mapping senator names
to lists representing their voting records.
Output: the last name of the senator whose political mindset is least like the input
senator.
Example:
>>> vd = {'Klein': [1,1,1], 'Fox-Epstein': [1,-1,0], 'Ravella': [-1,0,0]}
>>> least_similar('Klein', vd)
'Ravella'
"""
comp = [(policy_compare(sen, x, voting_dict), x) for x in voting_dict if x != sen]
comp.sort()
return comp[0][1]
## Task 5
most_like_chafee = 'Jeffords'
least_like_santorum = 'Feingold'
# Task 6
def find_average_similarity(sen, sen_set, voting_dict):
"""
Input: the name of a senator, a set of senator names, and a voting dictionary.
Output: the average dot-product between sen and those in sen_set.
Example:
>>> vd = {'Klein': [1,1,1], 'Fox-Epstein': [1,-1,0], 'Ravella': [-1,0,0]}
>>> find_average_similarity('Klein', {'Fox-Epstein','Ravella'}, vd)
-0.5
"""
return sum([policy_compare(sen, i, voting_dict) for i in sen_set])/len(sen_set)
def avg_dem():
vd = create_voting_dict()
names = {row.split()[0] for row in voting_data if row.split()[1] == 'D'}
avgs = []
for name in names:
names_cop = names.copy()
names_cop.remove(name)
avgs.append((find_average_similarity(name, names_cop, vd),name))
avg = sum([ avgs[i][0] for i in range(len(avgs)) ])/len(avgs)
avgs = [ (abs(avg - sim), name) for (sim, name) in avgs ]
avgs.sort()
return avgs[0][1]
#avgs = [(find_average_similarity(sen, names))]
#print(len(names))
# 'Schumer', 'Feinstein', 'Kerry'
most_average_Democrat = avg_dem() #"Bayh" # give the last name (or code that computes the last name)
# Task 7
def find_average_record(sen_set, voting_dict):
"""
Input: a set of last names, a voting dictionary
Output: a vector containing the average components of the voting records
of the senators in the input set
Example:
>>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Ravella': [0,0,1]}
>>> find_average_record({'Fox-Epstein','Ravella'}, voting_dict)
[-0.5, -0.5, 0.0]
"""
#length = len(list(voting_dict.values())[0])
#v = []
#for i in range(length):
# v.append(sum([voting_dict[sen][i] for sen in sen_set])/ (len(sen_set)) )
#return v
sen_set_votes = [ voting_dict[senator] for senator in voting_dict if senator in sen_set]
return [ sum(votes)/len(votes) for votes in zip(*sen_set_votes) ]
raw_list = [line.split() for line in voting_data]
demograts = {line[0] for line in raw_list if line[1] == 'D'}
average_Democrat_record = find_average_record(demograts, create_voting_dict()) # (give the vector)
# Task 8
def bitter_rivals(voting_dict):
"""
Input: a dictionary mapping senator names to lists representing
their voting records
Output: a tuple containing the two senators who most strongly
disagree with one another.
Example:
>>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Ravella': [0,0,1]}
>>> bitter_rivals(voting_dict)
('Fox-Epstein', 'Ravella')
"""
comb = combinations(voting_dict, 2)
diff = {policy_compare(sen1, sen2, voting_dict): (sen1, sen2) for sen1, sen2 in comb}
return diff[min(diff)]
|
238203066fa834bab1978997aeaef3527c3c63d0 | sxxzin/Algorithm | /Algorithm04_Bit/Factorial.py | 289 | 3.515625 | 4 | import math
import sys
while(True):
n = sys.stdin.readline().strip()
if(n=='0'):
break
else:
length=len(n)
sum=0
for i in range(1,length+1):
n=int(n)
sum+=int(n%10)*(math.factorial(i))
n/=10
print(sum) |
bcdc7d5e10842d3f0fc699f98f11e7f94a0a7367 | AmitAps/python | /thinkpy/checktriangle.py | 406 | 4.3125 | 4 | first_side = int(input('Enter an integer as a side of tringle: '))
second_side = int(input('Enter an integer as a side of tringle: '))
third_side = int(input('Enter an integer as a side of tringle: '))
def is_triangle(a, b, c):
if ((a > (b + c)) or (b > (a +c)) or (c > (a +b))):
print("No")
else:
print("yes")
is_triangle(first_side, second_side, third_side)
|
d88e32dc9f105c5275ca8ac1c8b1f37cddb630ea | nicoleorfali/Primeiros-Passos-com-Python | /p33.py | 517 | 3.890625 | 4 | # Alistamento Militar
from datetime import date
ano = int(input('Informe o ano em que você nasceu: '))
ano_corrente = date.today().year # pega o ano da data de hoje
mes_corrente = date.today().month
idade = ano_corrente - ano
if idade < 18:
print(f'Você tem {idade} anos. Faltam {18 - idade} ano(s) para alistamento.')
elif idade > 18:
print(f'Você tem {idade} anos. Já passou do tempo para alistamento.')
else:
print(f'Você tem {idade} anos. Você deve ser alistar este ano!!!')
|
1840e1399a0d49a6cb2d153829856b8bdaf72387 | ffarhour/AlmostThere | /Backend/AlmostThere/Tests/UserTest.py | 1,895 | 3.5625 | 4 | import unittest
from User import User
from Stop import Stop
class Test_UserTest(unittest.TestCase):
def setUp(self):
self.user = User(-36.854134, 174.767841)
self.stop = Stop(-36.843574, 174.766931)
def test_Position(self):
position = self.user.position
# Tests the lattittude
self.assertEqual(-36.854134, position[0])
# Tests the longitude
self.assertEqual(174.767841, position[1])
def test_WalkingSpeed_Default(self):
"""
Tests the default activity of the user
"""
walkingSpeed = self.user.walkingSpeed
self.assertEqual(4 / 3.6, walkingSpeed)
def test_WalkingSpeed_Specified(self):
"""
Tests the creation part of the user
"""
user = User(-36.854134, 174.767841, 5)
self.assertEqual(5 / 3.6, user.walkingSpeed)
def test_calculate_distance_from_stop_at_starting_position(self):
stop = Stop(-36.854134, 174.767841)
distance = self.user.calculate_distance_from_stop(stop)
self.assertEqual(distance, self.user.distance)
self.assertEqual(distance, 0)
def test_Calculate_Distance_from_stop_stop(self):
expectedValue = 1178
actualValue = self.user.calculate_distance_from_stop(self.stop)
self.assertEqual(expectedValue, int(actualValue))
def test_calculate_walking_time_from_starting_position(self):
expectedValue = 0
stop = Stop(-36.854134, 174.767841)
actualValue = self.user.calculate_walking_time(stop)
self.assertEqual(expectedValue, actualValue)
def test_calculate_Walking_Time_from_stop(self):
expectedValue = 2121
actualValue = self.user.calculate_walking_time(self.stop)
self.assertEqual(expectedValue, round(actualValue))
if __name__ == '__main__':
unittest.main()
|
ac64d34e09543f173ac5f4da8fb5494937aadfc3 | Sandeep-Joshi/python_analytics | /Regression.py | 1,611 | 3.84375 | 4 | """
Using Logistic Regression to classify sentences into positive / negative
This script solves the assignment for Week 9 "Improving classification accuracy".
THERE ARE SEVERAL OTHER MODELS (i.e., CLASSIFIERS) THAT ACHIEVE AN ACCURACY SCORE OF > 60%
@author: george valkanas (gvalkana)
"""
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import accuracy_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
#read the reviews and their polarities from a given file
def loadData(fname):
reviews=[]
labels=[]
f=open(fname)
for line in f:
tokens=line.strip().split('\t')
reviews.append(tokens[0].lower())
if ( len( tokens ) == 2):
labels.append(int(tokens[1]))
else:
labels.append( 0 )
f.close()
return reviews,labels
rev_train,labels_train=loadData('train.txt')
rev_test,labels_test=loadData('test.txt')
#Build a counter based on the training dataset
counter = CountVectorizer()
counter.fit(rev_train)
#count the number of times each term appears in a document and transform each doc into a count vector
counts_train = counter.transform(rev_train)#transform the training data
counts_test = counter.transform(rev_test)#transform the testing data
logreg = LogisticRegression()
logreg.fit( counts_train,labels_train )
#use the classifier to predict
fw = open( 'predictions.txt', 'w' )
predicted=logreg.predict(counts_test)
for i in predicted:
fw.write( str(i) + '\n' )
fw.close()
#print the accuracy
print accuracy_score(predicted,labels_test) |
347dec8c1da84bfab6d2e16f67058b473e54c9a1 | Parz3val83/CSC-111 | /CSCI_2020/assignments/assignment2_pt1.py | 97 | 3.59375 | 4 | # solution 1
a = 2
b = 1
while a <= 102:
print(a, end=' ')
a += b
b = b + 2
|
5c1d425069eb32869f8093d34feb19d457b638f1 | srikarmee7/python-beginner-projects | /acronym.py | 393 | 4.40625 | 4 | #take the input from the user
user_input = input("Enter the value: ")
#split the input value using split funciton
phrase = user_input.split()
#create a empty variable
x = ''
#iterate through the below condition
for word in phrase:
x = x + word[0].upper() #converting the value to uppercase
#print the above output variable with print statement
print(f'Acronym of {user_input} is : {x} ')
|
36abbadd95cc5e37fa2c0dc5ceb528a78447ea2e | trac-hacks/ebs-trac | /py/ebstrac/ebs.py | 10,987 | 4.25 | 4 | '''
Evidence-based scheduling routines.
'''
from datetime import timedelta, date
import random
def count_workdays(dt0, dt1, daysoff=(5,6)):
'''
Return the all weekdays between and including the two dates.
>>> from datetime import date
>>> dt0 = date(2010, 9, 3) # Friday
>>> dt1 = date(2010, 9, 6) # Monday
>>> d = count_workdays(dt0, dt1)
>>> d.next()
datetime.date(2010, 9, 3)
>>> d.next()
datetime.date(2010, 9, 6)
'''
for n in range((dt1 - dt0).days + 1):
d = dt0 + timedelta(n)
if d.weekday() not in daysoff:
yield d
def advance_n_workdays(dt0, n, daysoff = (5,6)):
'''
Count forward n work days.
>>> from datetime import date
>>> dt0 = date(2010, 9, 3) # Friday
If we need one day of work, we return a date that is one
work day later than the date passed in.
>>> advance_n_workdays(dt0, 1)
datetime.date(2010, 9, 6)
If we need five days of work, we return a date that is
five work days later than the date passed in.
>>> advance_n_workdays(dt0, 5)
datetime.date(2010, 9, 10)
We can use this to advance to the first work day if the current
day falls on a weekend.
>>> dt0 = date(2010, 9, 4) # Saturday
>>> advance_n_workdays(dt0, 0)
datetime.date(2010, 9, 6)
Note that to be consistent, this means that if we want to
advance one work day from a Saturday, we end up on a Tuesday.
>>> dt0 = date(2010, 9, 4) # Saturday
>>> advance_n_workdays(dt0, 1)
datetime.date(2010, 9, 7)
'''
#
# We start counting on the first work day. If the start date
# passed in is not a work day, then advance to the first one.
#
looplimit = 8
i = 0
while dt0.weekday() in daysoff:
i += 1
dt0 += timedelta(1)
if i > looplimit:
raise ValueError("Logic error, looping forever.")
day_n = 1
workday_n = 0
while workday_n < n:
d = dt0 + timedelta(day_n)
if d.weekday() not in daysoff:
workday_n += 1
day_n += 1
return dt0 + timedelta(day_n - 1)
def availability_from_timecards(timecards):
'''
Compute average hours available per weekday per dev.
September 2010
Su Mo Tu We Th Fr Sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
>>> from datetime import date
>>> day1 = date(2010, 9, 3)
>>> day2 = date(2010, 9, 6)
>>> timecards = (
... ('mark', day1, 10.0),
... ('mark', day2, 8.0),
... ('paul', day1, 4.0),
... )
>>> d = availability_from_timecards(timecards)
>>> d['mark']
9.0
>>> d['paul']
4.0
'''
if not timecards:
return {}
totalhours = {}
firstday = {}
lastday = {}
for dev, dt, hours in timecards:
try:
if lastday[dev] < dt:
lastday[dev] = dt
except KeyError:
lastday[dev] = dt
try:
if dt < firstday[dev]:
firstday[dev] = dt
except KeyError:
firstday[dev] = dt
try:
totalhours[dev] += hours
except KeyError:
totalhours[dev] = hours
averages = {}
for dev in totalhours.keys():
dt0 = firstday[dev]
dt1 = lastday[dev]
n = len(list(count_workdays(dt0, dt1)))
if n > 0:
averages[dev] = totalhours[dev]/float(n)
return averages
def history_to_dict(history):
'''
Turn history tuples into a dictionary where we can lookup the
list of velocities for a given dev.
>>> history = (
... ('mark', 1, 1.0, 1.0, 1.0),
... )
>>> history_to_dict(history)
{'mark': [1.0]}
'''
if not history:
return {}
d = {}
for dev, ticket, est, act, velocity in history:
if not d.has_key(dev):
d[dev] = []
d[dev].append(velocity)
return d
def list_to_pdf(list):
'''
Given a list dates, return the probability density function.
The return value is (element, probability_density) tuples.
We represent the density as the closest integer percentage.
>>> list_to_pdf( (3, 1, 1, 2) )
((1, 50), (2, 75), (3, 100))
'''
trials_n = len(list)
count = {}
for x in list:
try:
count[x] += 1
except KeyError:
count[x] = 1
a = []
for x, n in count.items():
a.append( (x, n / float(trials_n)) )
a = sorted(a, key = lambda x: x[0])
pdf = []
density = 0.0
for x, probability in a:
density += probability
percentage = int(0.5 + density * 100.0)
pdf.append( (x, percentage) )
return tuple(pdf)
def percentile(a, p):
'''
Given a list of elements, return the percentile.
>>> percentile( (1,2,3), 0.50)
2
'''
n = len(a)
i = int(n * p)
if abs((n * p) - i) < 0.000001:
q = (a[i] + a[i - 1]) / 2.
else:
q = a[i]
return q
def quartiles(a):
'''
Given list of sorted items, return q1, median q3 tuple
If the list has an odd number of entries, the median is the
middle number.
>>> q = quartiles( (1, 2, 3, 4, 5, 6, 7) )
>>> q[1]
4
The first quartile is the element such that at least 25% of the
values are less than or equal to it.
>>> q[0]
2
Likewise, the third quartile is the element such that at least
75% of the values are less than or equal to it.
>>> q[2]
6
Note that 5 doesn't work, because 5/7. = 71%, and the criteria
is that at least 75% of the elements are less than or equal to q3.
Shorter lists also work.
>>> quartiles( (1,2,3,4,5) )
(2, 3, 4)
Even lists exercise a different logic flow.
>>> quartiles( (1,2,3,4,5,6) )
(2, 3.5, 5)
The first quartile and third quartile seem incorrect, but they are
consistent with the method we are using:
1. multiply length of list by percentile
q1 q2 q3
---------- ------- ----------
0.25*6=1.5 0.5*6=3 0.75*6=4.5
2. if result is a whole number, compute value half-way
between number at that position (one-based) and next
q1 q2 q3
---------- ------- ----------
n/a 3+4/2.=3.5 n/a
3. otherwise, round up to next int and take value at
that position (again, one-based indexing of list)
q1 q2 q3
---------- ------- ----------
a[2] = 2 n/a a[5] = 5
With a list of one entry, they should all come back the same.
>>> quartiles( (1,))
(1, 1, 1)
With a list of two entries, we should get three different values.
>>> quartiles( (1,2))
(1, 1.5, 2)
'''
return percentile(a, 0.25), percentile(a, 0.50), percentile(a, 0.75)
def devquartiles_from_labordays(dev_labordays, trials_n):
'''
Compute descriptive statistics for each developer's ship date.
Return value is
(
('a', min_a, q1_a, q2_a, q3_a, max_a),
('b', min_b, q1_b, q2_b, q3_b ,max_b),
)
where stats are on ship date:
q1 = first quartile (25'th percentile)
q2 = second quartile (50'th percentile, or median)
q3 = third quartile (75'th percentile)
Note that the input to this routine is labordays so we can
compute descriptive stats without worrying about days off.
Once we have the stats, we convert to working days.
'''
seconds_per_halfday = 60 * 60 * 24 / 2
rval = []
for dev, labordays in dev_labordays.items():
pdf = list_to_pdf(labordays)
min = pdf[0][0]
max = pdf[-1][0]
daysleft = [daysleft for daysleft, density in pdf]
td1, td2, td3 = map(timedelta, quartiles(daysleft))
#
# Adding a timedelta of 82,800 seconds (23 hours worth)
# to a date does not advance it by one day. We want to
# round to the closest day, so we can't just add the day
# delta's returned by quartiles(), as they may be floats.
#
if td1.seconds > seconds_per_halfday:
td1 = td1 + timedelta(1)
if td2.seconds > seconds_per_halfday:
td2 = td2 + timedelta(1)
if td3.seconds > seconds_per_halfday:
td3 = td3 + timedelta(1)
#
# Now that we have the number of labordays required to
# each quartile, we can convert to work days, to put in
# terms of shipping date.
#
today = date.today()
min = advance_n_workdays(today, min)
q1 = advance_n_workdays(today, td1.days)
q2 = advance_n_workdays(today, td2.days)
q3 = advance_n_workdays(today, td3.days)
max = advance_n_workdays(today, max)
rval.append( (dev, min, q1, q2, q3, max), )
return tuple(rval)
def history_to_plotdata(history, todo, dev_to_dailyworkhours):
'''
History is a list of
(dev, ticket, estimated_hours, actual_hours, velocity)
tuples.
Todo is a list of (dev, ticket, est_hrs, act_hrs, todo_hrs)
tuples.
Timecards is a list of (dev, date, total_hours) tuples. One
entry for each unique dev/date combination.
Given this data, we run 1,000 rounds of a Monte Carlo simulation.
Each round generates one ship date. We take all 1,000 ship dates,
and generate two sets of coordinates:
1. a probability density function for ship date, and
2. box and whisker plots for each developer's ship date.
We use the timecard data to get an estimate of how many hours
each developer is available per week.
XXX: To model vacations, available hours should be in DB.
See ebs.txt for the unit tests.
'''
dev_to_velocities = history_to_dict(history)
# How many Markov trials do we run.
trials_n = 1000
startdt = date.today()
shipdates = []
dev_to_daysleftlist = {}
for trial_i in range(trials_n):
# How many hours of work does each dev have? Use randomly
# selected velocity to estimate this.
dev_to_hrsleft = {}
for dev, ticket, est, act, left in todo:
# Skip tickets with no estimate. We have no
# way to handle them.
if est < 0.00001:
continue
# velocity = est/actual.
# new est. = est / v
v = random.choice(dev_to_velocities[dev])
hrsleft = (est - act)/v
#
# If someone has booked more time than estimated
# to an open ticket, we skip it. This was a tough
# call, and I considered getting things like trying
# to estimate how many hours are left based on this
# developer's history. But there really is no way
# to know for sure how many hours are left; they
# may be very close to done, or they may not. It's
# much simpler (and easier to explain) that we just
# skip these.
#
if hrsleft < 0.0:
continue
try:
dev_to_hrsleft[dev] += hrsleft
except KeyError:
dev_to_hrsleft[dev] = hrsleft
# How many days of work left does each dev have?
# Use number of hours per day each dev works on average.
dev_to_daysleft = {}
for dev, hrs in dev_to_hrsleft.items():
daysleft = hrs/dev_to_dailyworkhours[dev]
dev_to_daysleft[dev] = daysleft
if not dev_to_daysleftlist.has_key(dev):
dev_to_daysleftlist[dev] = []
dev_to_daysleftlist[dev].append(daysleft)
# Find max # of work days left across all devs.
labordays_till_done = max(dev_to_daysleft.values())
#
# Convert labor days to calendar days. This is ship date.
#
# We keep developer day in raw (that is, non-calendar)
# days because that what we need to compute median and
# other descriptive stats. Once the stats are computed,
# then we convert to calendar.
#
shipdate = advance_n_workdays(startdt, labordays_till_done)
shipdates.append(shipdate)
pdf = list_to_pdf(shipdates)
devs = devquartiles_from_labordays(dev_to_daysleftlist, trials_n)
return pdf, devs
if __name__ == '__main__':
import doctest
doctest.testmod()
doctest.testfile('ebs.txt')
|
ae767efb61ea884ad79d0c5cae59de2e2ca4fb7d | maxwellpettit/PythonRobot | /src/pursuit/path.py | 2,784 | 3.578125 | 4 | #!/usr/bin/python3
from pursuit import PathSegment
class Path():
COMPLETION_TOLERANCE = 0.98
segments = []
def addSegment(self, segment):
self.segments.append(segment)
def findGoalPoint(self, xv, yv, lookahead):
"""
Find the goal point on the path for the current vehicle position
"""
while (len(self.segments) > 0):
segment = self.segments[0]
# Find first path segment where d >= lookahead
d = PathSegment.getDistance(xv, yv, segment.x2, segment.y2)
if (d >= lookahead):
# Find closest point on path segment
(x, y, index) = segment.findClosestPoint(xv, yv)
# Check if vehicle closer to next segment
(x, y, index, segment) = self.checkNextSegment(xv, yv, x, y, index, segment)
# Check if segment is complete
self.checkSegmentComplete(index)
# print('Closest (x, y) = (' + str(x) + ', ' + str(y) + ') Index = ' + str(index))
# Find intersection between path and circle with radius = lookahead
return segment.findCircleIntersection(x, y, lookahead)
# If last segment, return the end of the segment
elif (len(self.segments) == 1):
# Find closest point on path segment
(x, y, index) = segment.findClosestPoint(xv, yv)
# Check if segment is complete
self.checkSegmentComplete(index)
# Goal point is the end of the segment
return (segment.x2, segment.y2)
# If too close to end of path, move to next segment
else:
print('Distance to path < lookahead. Removing segment.')
self.segments.pop(0)
# Done when all segments are removed
return (None, None)
def checkNextSegment(self, xv, yv, x, y, index, segment):
"""
Check if the next segment is closer to the vehicle
"""
if (len(self.segments) > 1):
(x2, y2, index2) = self.segments[1].findClosestPoint(xv, yv)
d1 = PathSegment.getDistance(xv, yv, x, y)
d2 = PathSegment.getDistance(xv, yv, x2, y2)
# Next segment is closer, so remove previous segment
if (d2 <= d1 and index2 > 0):
segment = self.segments[1]
(x, y, index) = (x2, y2, index2)
self.segments.pop(0)
print('Next Segment is closer. Removing previous segment.')
return (x, y, index, segment)
def checkSegmentComplete(self, index):
if (index >= self.COMPLETION_TOLERANCE):
self.segments.pop(0)
print('Segment Complete')
|
f7439d604c234e0aa26d3979cd35248726b9b717 | isabella232/sheet2docs | /sheet2docs | 1,906 | 3.65625 | 4 | #! /usr/bin/env python
import csv
import sys
import re
import argparse
parser = argparse.ArgumentParser(description='Convert a CSV of form responses into individual narrative documents.')
parser.add_argument('filename', help='the filename of the CSV to convert')
parser.add_argument('--title', help='the field, if any, to use for the document title')
def build_content(row, title_field):
'''
Builds the content
'''
response = ""
for entry in row:
if entry == title_field:
response = '<h1>' + row[entry] + '</h1><br>' + response
else:
response += '<h2>' + entry + '</h2><br>'
response += row[entry] + '<br>'
response = re.sub('[\n\r]', '<br>', response)
return response
def get_filename(row, index, title_field):
'''
Create a filename
If there's a specified title field, use that, but otherwise
just create separate files from the iterable index
'''
try:
return row[title_field] + '.html'
except KeyError:
return 'response{}.html'.format(str(index))
def convert(in_file, title_field):
with open(in_file, newline='') as responses:
r = csv.DictReader(responses)
for index, row in enumerate(r):
response = build_content(row, title_field)
# Create file for this response
filename = get_filename(row, index, title_field)
with open(filename, 'w') as output:
# Write to the file
output.write(response)
if __name__ == "__main__":
# Do a version check, since we need Python 3.6 or higher
try:
assert sys.version_info >= (3,6)
except AssertionError:
print('Error: Python 3.6 or higher is required.')
print('Please install a compatible version of Python.')
# Convert
args = parser.parse_args()
convert(args.filename, args.title)
|
47dcfe3237ad7c65149a28c84e680d7cca53efa7 | diolaoyeyele/virtual-learner | /rp.py | 670 | 3.65625 | 4 | class Employee:
empCount = 0
def __init__(self,name,salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def __repr__(self):
return self.name
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ",self.salary)
global emp1
global emp2
global n
global s
emp1 = ''
emp2 = ''
alist = [emp1,emp2]
alist_final =[]
for y in alist:
n = input()
s = input()
y = Employee(n,s)
alist_final.append(y)
y.displayEmployee()
print("Total Employee %d" % Employee.empCount)
print(alist_final) |
372093f9d5abcae4468f51b5dbc53cd3f86ade51 | Maxclayton/cs1400 | /main2.py | 532 | 3.859375 | 4 | name = input("What is your name? ")
flavor = input("What is your favorite flavor of ice cream? ")
th = int(input("What is the tub Height? "))
td = float(input("What is the tub Diamater? "))
sd = int(input("What is the scoop Diameter? "))
tr = (td/2) #tubRadius
tv = (th*(tr*tr)*3.14159265359) #tubVolume
sr = (sd/2) #scoopRadius
scoop = (4/3*3.14159265359*sr*sr*sr)
ss = (tv/scoop) #servingSize
print ("Name:",name,)
print ("Flavor:",flavor,)
print("Tub Volume",tv,)
print("Scoop Volume:",scoop,)
print("Serving Size:",ss,) |
7d258ed58547ce8fee962e7cfe8caa5663b903be | py-study-group/challenges | /February/amar771.py | 5,399 | 4.1875 | 4 | '''
Caesar cipher
'''
import argparse
import sys
from random import randint
ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
def encode(string, key=None):
'''Encodes the string with the key of choice.'''
randomized_key = False
if not key:
key = randint(1, 25)
randomized_key = True
try:
key = int(key)
except ValueError:
return ("Key needs to be numerical value.")
# Checks if the string will be the same after encoding
if key % len(ALPHABET) == 0:
return string
encoded = ''
for letter in string:
if letter not in ALPHABET:
encoded += letter
else:
encoded += ALPHABET[(ALPHABET.index(letter) + key) % len(ALPHABET)]
if randomized_key:
print("Your key has been randomized and it is --> {}".format(key))
return encoded
def decode_key(string, key=None):
'''Decodes the string you provide with the key you provide'''
if not key:
decode_bruteforce(string)
sys.exit()
try:
key = int(key)
except ValueError:
return ("Key needs to be numerical value.")
key = abs(key - len(ALPHABET))
return encode(string, key)
def decode_bruteforce(string):
'''Decodes the string by brute forcing all the results'''
for number in range(len(ALPHABET), 0, -1):
key = len(ALPHABET) - number
print("Key ({0:2d}) - {1}".format(key, encode(string, number)))
def help_description():
print("\nTool for encrypting and decrypting text with Caesar cipher.\n")
def read_from_file(link):
text = ''
with open(link, "r") as file:
for line in file:
text += line
return text
def ask_key(encode=False, decode=False):
if encode:
print("What key do you want to use [1-{}]? (RETURN for random key.)".
format(len(ALPHABET)))
elif decode:
print("What key do you want to use [1-{}]? (RETURN for brute-force)".
format(len(ALPHABET)))
key = input("--> ")
print()
return key
def ask_string(args):
if args.file:
args.string = str(input("Enter the name of the file --> "))
elif args.text:
args.string = str(input("Enter the string --> "))
def ask_input_type(args):
print("Do you want enter a string here or use a file?")
while not args.text and not args.file:
string = str(input("[text/file/quit] --> "))
string.lower()
if string in ['text', 't']:
args.text = True
elif string in ['file', 'f']:
args.file = True
elif string in ['quit', 'q']:
sys.exit()
def ask_mode_type(args):
print("Do you want to encode or decode?")
while not args.encode and not args.decode:
string = str(input("[encode/decode/quit] --> "))
string.lower()
if string in ['encode', 'e']:
args.encode = True
elif string in ['decode', 'd']:
args.decode = True
elif string in ['quit', 'q']:
sys.exit()
def args_actions(args):
if not args.text and not args.file:
ask_input_type(args)
if not args.string:
ask_string(args)
if not args.encode and not args.decode:
ask_mode_type(args)
if args.text:
text = args.string
if args.file:
text = read_from_file(args.string)
key = args.key
if not key:
key = ask_key(encode=args.encode, decode=args.decode)
if args.encode:
encoded = encode(text, key)
print(encoded)
elif args.decode:
print(decode_key(text, key))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=help_description())
parser.add_argument('-v', '--version',
action='version',
version='%(prog)s 1.2')
parser.add_argument('-s', '--string', type=str,
help="text or file to encode",
required=False)
parser.add_argument('-k', '--key', type=int,
help="key to encode or decode with",
required=False)
# Can't have -f and -t flags at the same time
input_group = parser.add_mutually_exclusive_group()
input_group.add_argument('-f', '--file',
action='store_true',
help='Add file to encode or decode',
required=False)
input_group.add_argument('-t', '--text',
action='store_true',
help='Type text to encode or decode',
required=False)
#
group = parser.add_argument_group
# You can encode or you can decode, can't do both
action_group = parser.add_mutually_exclusive_group()
action_group.add_argument('-e', '--encode',
action='store_true',
help='Encodes using a key or with random key',
required=False)
action_group.add_argument('-d', '--decode',
action='store_true',
help='Decodes using one of decode methods',
required=False)
args = parser.parse_args()
try:
args_actions(args)
# Used for CTRL-C
except KeyboardInterrupt:
print('')
|
bf2412b4b32dcc5a6f3ca5ab9e8e42e028ac3a21 | pravsingh/Algorithm-Implementations | /Binary_Search_Tree/Python/dalleng/bst_test.py | 2,451 | 3.71875 | 4 | import unittest
from bst import BinarySearchTree
class BinarySearchTreeTest(unittest.TestCase):
def test_insertion(self):
tree = BinarySearchTree()
tree.insert(8)
tree.insert(3)
tree.insert(10)
tree.insert(1)
tree.insert(6)
tree.insert(4)
tree.insert(7)
tree.insert(14)
tree.insert(13)
self.assertEquals(tree.root.value, 8)
self.assertEquals(tree.root.left.value, 3)
self.assertEquals(tree.root.left.left.value, 1)
self.assertEquals(tree.root.left.right.value, 6)
self.assertEquals(tree.root.left.right.left.value, 4)
self.assertEquals(tree.root.left.right.right.value, 7)
self.assertEquals(tree.root.right.value, 10)
self.assertEquals(tree.root.right.right.value, 14)
self.assertEquals(tree.root.right.right.left.value, 13)
def test_search(self):
# Emptry Tree
self.assertEquals(BinarySearchTree().search(8), None)
tree = BinarySearchTree()
tree.insert(8)
tree.insert(3)
tree.insert(10)
tree.insert(1)
tree.insert(6)
tree.insert(4)
tree.insert(7)
tree.insert(14)
tree.insert(13)
self.assertEquals(tree.search(6).value, 6)
self.assertEquals(tree.search(2), None)
self.assertEquals(tree.search(15), None)
self.assertEquals(tree.search(13).value, 13)
self.assertEquals(tree.search(1).value, 1)
def test_deletion(self):
tree = BinarySearchTree()
tree.insert(8)
tree.insert(3)
tree.insert(10)
tree.insert(1)
tree.insert(6)
tree.insert(4)
tree.insert(7)
tree.insert(14)
tree.insert(13)
tree.delete(1)
tree.delete(14)
tree.delete(6)
self.assertEquals(tree.root.value, 8)
self.assertEquals(tree.root.left.value, 3)
self.assertEquals(tree.root.left.left, None)
self.assertEquals(tree.root.left.right.value, 7)
self.assertEquals(tree.root.left.right.left.value, 4)
self.assertEquals(tree.root.left.right.right, None)
self.assertEquals(tree.root.right.value, 10)
self.assertEquals(tree.root.right.right.value, 13)
tree.delete(8)
self.assertEquals(tree.root.value, 10)
self.assertEquals(tree.root.right.value, 13)
if __name__ == '__main__':
unittest.main()
|
1d425b99503137eb3d2b8bd9bf313db5c4298a3e | arbwasisi/CSC110 | /decrypter.py | 1,969 | 4.3125 | 4 | # Author: Arsene Bwasisi
# Description: decrypter.py will take in an encrypted file as input along
# with a key file containing the index of the file, and it will
# organize the file into its original order and write it to
# decrypter.txt.
def read_file(text_file, index_file):
''' This functions will open and read the inputed files.'''
text_file = open(text_file, 'r')
index_file = open(index_file, 'r')
# Organize the data in both files into two seperate lists
texts = text_file.readlines()
indexes = []
for index in index_file:
indexes.append(int(index))
return texts, indexes
def decrypter(file_list, index_list):
'''
This function will organize the encrypted file back to its
original format.
'''
decrypted_list = []
# Sets a range similar to index_list
for num in range(1, len(file_list) + 1):
for index in range(len(index_list)): # loop through index_list
# check whether value in index_list equals to num value
# then append to decrypted_list.
if num == index_list[index]:
decrypted_list.append(file_list[index])
return decrypted_list
def write_to_file(decrypted_list):
''' This functions writes in the orginal form of the file into decrypted.txt.'''
decrypted_file = open('decrypted.txt', 'w') # open file in write mode
# Iterate through and write content grom decrypted_list
# into decrypted_file
for line in decrypted_list:
decrypted_file.write(line)
decrypted_file.close() # close file
def main():
encrypted_file = input("Enter the name of a mixed text file:\n")
index_file = input("Enter the mix index file:\n")
text_list, index_list = read_file(encrypted_file, index_file)
decrypted_list = decrypter(text_list, index_list)
write_to_file(decrypted_list)
main() |
ff354fc4527c17fb0752e53493167faf473dd9bc | betty29/code-1 | /recipes/Python/189745_Symmetric_datobfuscatiusing/recipe-189745.py | 1,786 | 3.84375 | 4 | class Obfuscator:
""" A simple obfuscator class using repeated xor """
def __init__(self, data):
self._string = data
def obfuscate(self):
"""Obfuscate a string by using repeated xor"""
out = ""
data = self._string
a0=ord(data[0])
a1=ord(data[1])
e0=chr(a0^a1)
out += e0
x=1
eprev=e0
while x<len(data):
ax=ord(data[x])
ex=chr(ax^ord(eprev))
out += ex
#throw some chaff
chaff = chr(ord(ex)^ax)
out += chaff
eprev = ex
x+=1
return out
def unobfuscate(self):
""" Reverse of obfuscation """
out = ""
data = self._string
x=len(data) - 2
while x>1:
apos=data[x]
aprevpos=data[x-2]
epos=chr(ord(apos)^ord(aprevpos))
out += epos
x -= 2
#reverse string
out2=""
x=len(out)-1
while x>=0:
out2 += out[x]
x -= 1
out=out2
#second character
e2=data[2]
a2=data[1]
a1=chr(ord(a2)^ord(e2))
a1 += out
out = a1
#first character
e1=out[0]
a1=data[0]
a0=chr(ord(a1)^ord(e1))
a0 += out
out = a0
return out
def main():
testString="Python obfuscator"
obfuscator = Obfuscator(testString)
testStringObf = obfuscator.obfuscate()
print testStringObf
obfuscator = Obfuscator(testStringObf)
testString = obfuscator.unobfuscate()
print testString
if __name__=="__main__":
main()
|
4cb4d424f23f64797b8f8754a593bacf61d1ef94 | AdamMC-GL/P3ML | /neuronnetwork.py | 3,863 | 4.5 | 4 | import neuronlayer
class Neuronnetwork:
"""A network of neurons, consists of multiple layers of neurons.
A layer consists out of a set of neurons. """
def __init__(self, layers):
"""Initializes all variables when the class is made.
Contains the list of layers (a set of neurons) which is the network itself"""
self.pnetwork = []
for layer in layers:
self.pnetwork.append(neuronlayer.Neuronlayer(layer))
def feed_forward(self, inputs):
"""Given an input, gives the output of the network.
The input is used to calculate the output of the first layer, and those
outputs are used as the input for the next until the last layer's output is calculated and returned"""
for layer in self.pnetwork:
inputs = layer.activate(inputs) # each input of a layer gives an output that becomes the input of the next layer
return inputs
def empty_network(self, layer_amounts, first_layer_inputs=2):
"""Creates an empty network, a network with all weights and biases set on 0.
The layer_amount parameter is a list of numbers, each number representing the amount of
neurons on each layer. [2, 3, 2] = 2 neurons on the first layer, 3 on the second and 2 on the last.
The first layer has 2 inputs by default, all other layers have inputs the same as the neuron amount of the previous layer."""
self.pnetwork = []
weights_amount = first_layer_inputs # Initial amount of inputs for the first layer
for amount in layer_amounts:
self.pnetwork.append(neuronlayer.Neuronlayer([[[0] * weights_amount, 0]] * amount))
weights_amount = amount
def __str__(self):
"""Returns a string that tells the information of the whole network.
Gives the bias and weights of each neuron of each layer and
shows which neuron of which layer it is"""
string = ""
count = 0
for layer in self.pnetwork:
count += 1
string += "Layer " + str(count) + ": \n"
string += str(layer)
return string
if __name__ == "__main__":
xor_port = Neuronnetwork([[[[-5, -5], 8], [[8, 8], -1.5]],
[[[6, 6], -9.5]]]) # nand, or, and
print("XOR port: ")
input_combinations = [[0, 0], [0, 1], [1, 0], [1, 1]]
for i in input_combinations:
print(xor_port.feed_forward(i)[0])
assert xor_port.feed_forward([0, 0])[0] < 0.1, "Should be below 0.1"
assert xor_port.feed_forward([0, 1])[0] > 0.9, "Should be above 0.9"
assert xor_port.feed_forward([1, 0])[0] > 0.9, "Should be above 0.9"
assert xor_port.feed_forward([1, 1])[0] < 0.1, "Should be below 0.1"
print("Half adder: ")
halfadder = Neuronnetwork([[[[-5, -5], 8], [[8, 8], -1.5]],
[[[6, 6], -9.5], [[-7, 2], 2]]]) # nand, or, and, custom neuron
for i in input_combinations:
print(halfadder.feed_forward(i))
assert halfadder.feed_forward([0, 0])[0] < 0.1 and halfadder.feed_forward([0, 0])[1] < 0.1, "Should be both below 0.1"
assert halfadder.feed_forward([0, 1])[0] > 0.9 and halfadder.feed_forward([0, 1])[1] < 0.1, "First should be above 0.9 and second should be below 0.1"
assert halfadder.feed_forward([1, 0])[0] > 0.9 and halfadder.feed_forward([1, 0])[1] < 0.1, "First should be above 0.9 and second should be below 0.1"
assert halfadder.feed_forward([1, 1])[0] < 0.1 and halfadder.feed_forward([1, 1])[1] > 0.9, "First should be below 0.1 and second should be above 0.9"
print("Empty network of 3 layers: ")
# showcasing empty_network() and __str__()
testnet = Neuronnetwork([])
testnet.empty_network([2, 3, 2])
print(testnet)
|
2ffe1b04a53c574fa71264bfe5d66bee1d80299b | drkndl/PH354-IISc | /Week 1/HW1_7_Catalan.py | 497 | 3.734375 | 4 | """
Author: Drishika Nadella
Date: 20th April 2021
Time: 16:09PM
Email: drishikanadella@gmail.com
"""
import numpy as np
import matplotlib.pyplot as plt
# Creating a list with the zeroth Catalan number
C = [1]
# Creating the counter
i = 0
# Calculating and printing Catalan numbers upto 1 billion
while C[-1] <= 10**9:
print(C[-1])
C.append((4*i + 2)/(i+2)*C[i])
i+=1
# Plotting the Catalan numbers
plt.plot(range(len(C)), C, marker='o')
plt.title("Visualizing the Catalan numbers upto 1 billion")
plt.show()
|
78f13b5c52c7f372091de631891b5c16afe1ae6e | shiv-konar/Python-GUI-Development | /1.BlankWindow.py | 192 | 3.859375 | 4 | import tkinter as tk
win = tk.Tk() #Create an instance of the Tk class
win.title("Python GUI") #Set the title of the window
win.mainloop() #The event which makes the window appear on screen |
fd5a37c63b819498b33c0d7f336682848477f599 | owenvvv/recommend_system_anime | /Data Processing/Category.py | 1,506 | 3.65625 | 4 | import pandas as pd
import numpy as np
import scipy as sp
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import CountVectorizer
anime = pd.read_excel("C:/Users/WU Shijun DD/Desktop/anime_common.xlsx")
anime = anime[:1000]
features = ['Genre','Studio']
def combination(row):
return row['Genre']+" "+row['Studio']
for feature in features:
anime[feature] = anime[feature].fillna('') #filling all NaNs with blank string
anime['combination'] = anime.apply(combination,axis=1)
count = CountVectorizer()
count_matrix = count.fit_transform(anime['combination'])
# Compute the Cosine Similarity matrix based on the count_matrix
cosine_sim2 = cosine_similarity(count_matrix)
print(cosine_sim2)
# Reset index of our main DataFrame and construct reverse mapping as before
anime = anime.reset_index()
def name(index):
return anime[anime.index == index]["Name"].values[0]
def studio(index):
return anime[anime.index == index]["Studio"].values[0]
def genre(index):
return anime[anime.index == index]["Genre"].values[0]
def index(Name):
return anime[anime.Name == Name]["index"].values[0]
user_input = "Nana"
index_match = index(user_input)
similar_animes = list(enumerate(cosine_sim2[index_match]))
final_list = sorted(similar_animes,key=lambda x:x[1],reverse=True)[1:]
i=0
print("Top 10 animes similar to '"+user_input+"' are:\n")
for x in final_list:
id = x[0]
print("No." + str(i+1) + ": " + name(id))
i=i+1
if i>9:
break |
f5f63a27adb1d446d01d8f2c323ed68e5e1119d9 | lucaslracz/ContadorPythonIniciante | /variaveis.py | 104 | 3.84375 | 4 | num=int(input("informe um numero: "))
while num<100:
print("\t"+str(num))
num=num+1
print("FIM") |
a62e361073d741582b8caa7358d31dfa23264a34 | cody9898/CS506-Spring2021 | /02-library/cs506/read.py | 673 | 3.9375 | 4 | def read_csv(csv_file_path):
"""
Given a path to a csv file, return a matrix (list of lists)
in row major.
"""
matrix = []
with open(csv_file_path, "r") as f:
lines = f.readlines()
for line in lines:
strings = line.strip('\n').split(",")
row = []
for s in strings:
try:
v = int(s)
except ValueError:
try:
v = float(s)
except ValueError:
v = str(s).strip('\"')
row.append(v)
matrix.append(row)
return matrix
|
fc5f676c32d73828d5293ce27ae89ab815c24f62 | Chencx901/leetcode | /problems/twosum_sorted.py | 783 | 4.03125 | 4 | # Given an array of integers that is already sorted in ascending order, find two
# numbers such that they add up to a specific target number.
# The function twoSum should return indices of the two numbers
# such that they add up to
# the target, where index1 must be less than index2.
# Example:
# Input: numbers = [2,7,11,15], target = 9
# Output: [1,2]
# Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for index,num in enumerate(numbers):
if target - num in dic:
return [dic[target-num]+1,index+1]
dic[num] = index |
38003e97dbef3959893767a7344036e8216b0c75 | j-scull/Python_Data_Structures | /array_stack.py | 1,072 | 4.1875 | 4 | from empty import Empty
class ArrayStack:
"""A python list based implementation of a Stack ADT"""
def __init__(self):
"""creates an empty stack"""
self._data = []
def __len__(self):
"""returns: the number of elements in the stack"""
return len(self._data)
def isEmpty(self):
"""returns: true if the stack is empty, false otherwise"""
return len(self._data) == 0
def push(self, e):
"""adds an element to the top of stack"""
self._data.append(e)
def pop(self):
"""
returns: the element remove from the top of the stack
raises: an Empty exception if the stack is empty
"""
if self.isEmpty():
raise Empty('Stack is empty')
return self._data.pop()
def top(self):
"""
returns: the element at the top of the stack without removing it
raises: an Empty exception if the stack is empty
"""
if self.isEmpty():
raise Empty('Stack is empty')
return self._data[-1]
|
cf8b38c0ba473254f2c6a7b62e6bc3d29fef235c | tannerbliss/Udacity | /fill-in-the-blanks.py | 6,073 | 4.25 | 4 | # IPND Stage 2 Final Project
# You've built a Mad-Libs game with some help from Sean.
# Now you'll work on your own game to practice your skills and demonstrate what you've learned.
# For this project, you'll be building a Fill-in-the-Blanks quiz.
# Your quiz will prompt a user with a paragraph containing several blanks.
# The user should then be asked to fill in each blank appropriately to complete the paragraph.
# This can be used as a study tool to help you remember important vocabulary!
# Note: Your game will have to accept user input so, like the Mad Libs generator,
# you won't be able to run it using Sublime's `Build` feature.
# Instead you'll need to run the program in Terminal or IDLE.
# Refer to Work Session 5 if you need a refresher on how to do this.
# To help you get started, we've provided a sample paragraph that you can use when testing your code.
# Your game should consist of 3 or more levels, so you should add your own paragraphs as well!
# sample = '''A ___1___ is created with the def keyword. You specify the inputs a ___1___ takes by
# adding ___2___ separated by commas between the parentheses. ___1___s by default return ___3___ if you
# don't specify the value to return. ___2___ can be standard data types such as string, number, dictionary,
# tuple, and ___4___ or can be more complicated such as objects and lambda functions.'''
# The answer for ___1___ is 'function'. Can you figure out the others?
# We've also given you a file called fill-in-the-blanks.pyc which is a working version of the project.
# A .pyc file is a Python file that has been translated into "byte code".
# This means the code will run the same as the original .py file, but when you open it
# it won't look like Python code! But you can run it just like a regular Python file
# to see how your code should behave.
# Hint: It might help to think about how this project relates to the Mad Libs generator you built with Sean.
# In the Mad Libs generator, you take a paragraph and replace all instances of NOUN and VERB.
# How can you adapt that design to work with numbered blanks?
# If you need help, you can sign up for a 1 on 1 coaching appointment: https://calendly.com/ipnd-1-1/20min/
s_model = '''Model ___1___ is designed from the ground up to be the safest,
most exhilarating sedan on the road. With unparalleled performance
delivered through ___2___'s unique, all-electric powertrain, Model
___1___ accelerates from 0 to ___3___ mph in as little as 2.5 seconds.
Model ___1___ comes with Autopilot capabilities designed to make your
highway driving not only safer, but stress free. The Model ___1___ is the
best sedan in the entire ___4___'''
x_model = '''Model ___1___ is the safest, quickest, and most capable sport
utility vehicle in history. Designed as a family car without compromise,
Model ___1___ comes standard with all-wheel drive, ample seating for up
to seven adults, standard active safety features, and up to ___2___ miles
of range on a single charge. And it's the quickest SUV in production,
capable of accelerating from zero to ___3___ miles per hour in 2.9
seconds. The Model ___1___ is the best utility vehicle in the entire
___4___'''
e_model = '''Designed to attain the highest safety ratings in every
category, Model ___1___ achieves ___2___ miles of range while starting
at only $___3___ before incentives. The Model ___1___ is the best
sedan in the entire ___4___'''
s_answers_list_that_uses_its_values_to_fill_in_the_blanks = ["s", 'tesla', "60", 'world']
x_answers_list_that_uses_its_values_to_fill_in_the_blanks = ["x", "295", "60", 'world']
e_answers_list_that_uses_its_values_to_fill_in_the_blanks = ["e", "220", "35000", 'world']
user_input = input("What car would you like to drive? Model X, S, or E? ")
# this is the start of the game and when the game begins this is the first operation
print(user_input)
# this is the function that does the parsing of the user answer and replaces the text of the blank with the actual answer
def play_game(ml_string, parts_of_speech, replaced_text):
"""
:param ml_string: this is the check space as it moves through the paragraph
:param parts_of_speech: the value that was provided from the user
:param replaced_text: once it is correct, this is what text is put into the return to the user
"""
replaced = []
ml_string = ml_string.split(' ')
for parse in ml_string:
parse = parse.replace(parts_of_speech, replaced_text)
replaced.append(parse)
replaced = " ".join(replaced)
return replaced
# this is the core operating function
def quiz_function(model, answers):
num_tries = 5
current_blank = 0
number_of_blanks = 4
new_paragraph = model
while num_tries != 0 and current_blank < number_of_blanks: # as long as the 5 tries have not run out, this code is run to prompt the user for the answer and the answer is checked to see if it is right
print (new_paragraph + "\nYou have " + str(num_tries) + " tries on each blank. \n Fill in the blanks!")
answer_input = input("What is the answer for blank number " + str(current_blank + 1) + "?")
if answer_input.lower() == answers[current_blank]:
print("That's right!")
new_paragraph = play_game(new_paragraph, "___" + str(current_blank + 1) + "___", answer_input)
num_tries = 5
current_blank += 1
else: # if all 5 tries are spent on the question the game is over and the user has to start all over again
num_tries -= 1
if num_tries == 0:
print("You ran out of tries. Game Over")
else:s_answers_list_that_uses_its_values_to_fill_in_the_blanks
print(new_paragraph + "\nCongratulations, you WON!!")
if user_input in 'Ss':
quiz_function(s_model, s_answers_list_that_uses_its_values_to_fill_in_the_blanks)
elif user_input in 'Xx':
quiz_function(x_model, x_answers_list_that_uses_its_values_to_fill_in_the_blanks)
elif user_input in 'Ee':
quiz_function(e_model, e_answers_list_that_uses_its_values_to_fill_in_the_blanks)
|
438fd1cc67ae5bc6e5d157c257672ebc34f23f91 | IuryBRIGNOLI/tarefas130921 | /1.py | 210 | 4.09375 | 4 | x = int(input("Digite um número"))
y = int(input("Digite outro número"))
if(x>y):
print("Seu primeiro número é maior que o segundo ")
else:
print("Seu segundo número é maior que o primeiro ") |
5c3c648325b2fcf351679a108b5b5c08737e165c | NustaCoder/DailyCodingProblems_solutions | /prb360.py | 184 | 3.671875 | 4 | lst1 = [1, 7, 3]
lst2 = [2, 1, 6, 7, 9]
lst3 = [3, 9, 5]
lst = [0 for i in range(1, 10)]
lst_or = [lst1, lst2, lst3]
for i in lst_or:
for j in i:
lst[j-1] += 1
print(lst)
|
62ea03a0bb5055985ba0d443d47f764a33f5ea32 | SaveTheRbtz/algo-class | /ex1/brute_force_itertools.py | 666 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from common import parse_file
import itertools
def brute_force(data):
"""
This function should return number of inversions of input stream
>>> brute_force([1,2,3,4,5,6])
0
>>> brute_force([1,3,5,2,4,6])
3
>>> brute_force([6,5,4,3,2,1])
15
"""
return sum(1 for a,b in itertools.combinations(data, 2) if a > b)
if __name__ == '__main__':
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", type="string", dest="file", default="IntegerArray.txt")
(options, args) = parser.parse_args()
print brute_force(parse_file(options.file))
|
371a737fe6bff80e7f91cb40d86cdf8f9caa9ece | SathvikPN/Joy-of-computing-using-Python-NPTEL | /interactive-calculator.py | 1,848 | 3.859375 | 4 | '''
Interactive Calculator
author: Sathvik PN
'''
#Print Instructions about Input
print('''I'm "Calculator"
I perform these operations:
Add[+] Subtract[-] Multiply[*] Divide[/]
Sample Expression input format:
a+b
[only two operands a,b which are real positive numbers]
''')
def feedCalculator(operator,a,b):
if(operator=='+'):
return a+b
elif(operator=='-'):
return a-b
elif(operator=='*'):
return a*b
elif(operator=='/'):
if(b==0):
return ("Undefined [Divide by zero error]")
else:
return a/b
else:
print("Invalid operator")
#Interactive Mode
while(True):
print('''
Enter the expression [press 'Q' to exit calculator]''')
rawInput = input("Feed ")
#Stop Interactive mode --> Exit
if ((rawInput=='q')or(rawInput=='Q')):
print("-"*50)
break
#Checking for Mathematical Operator
for i in rawInput:
if (i=='+'):
#splitting input into 2 items [a,b]
expression = list(rawInput.split('+'))
#preserving the operator
operator = i
#expression needs only one operator
break
elif(i=='-'):
expression = list(rawInput.split('-'))
operator = i
break
elif(i=='*'):
expression = list(rawInput.split('*'))
operator = i
break
elif(i=='/'):
expression = list(rawInput.split('/'))
operator = i
break
a = float(expression[0])
b = float(expression[1])
print("-"*50)
print("{}{}{} = {}".format(a,operator,b,feedCalculator(operator,a,b)))
print("-"*50)
print('''
Thanks for using the service.
Have a good-day.
[Calculator turning OFF...]
Program terminated.''')
|
1ba9c3805f64c2ee58662c816d4ae072c9d929cd | sailusm/LuminarPython | /flowcotrol/file/covid.py | 482 | 3.5625 | 4 | f=open("C:/Users/USER/PycharmProjects/project1/flowcotrol/file/complete.csv","r")
dict={}
for line in f:
word=line.rstrip("\n").split(",")
# print(word)
country=word[1]
state=int(word[4])
if state not in dict:
dict[state]= country
else:
dict[state]= country
# print(dict)
sortedlist=[]
for k,v in dict.items():g
sortedlist.append((v,k))
print(sortedlist)
sortedlst=sorted(sortedlist,reverse=True)
print(sortedlst[1:4])
|
239bbe36fc31c91ae8190345151513073275b518 | Prometheus1969/Freshman-Year2-Python | /list1.py | 1,103 | 3.796875 | 4 | #list.py
import random
list1 = list(range(10))
#建立数字列表
print(list1)
list2 = ["Jerry", "Jack111", "Peter"]
#建立字符串列表
print(list2)
list3 = list1
print(list3)
list4 = [ x for x in list2 ]
#利用遍历建立列表
print(list4)
list5 = [1, 2, 3, "a", "b", "c"]
if 10 in list5 :
print("10存在于list5中")
if "d" in list5 :
print("d存在于list5中")
#判断列表中的存在
list6 = list5 * 2
#列表元素×2
print(list6)
print(list5[3])
print(type(list5[3]))
list5 = list5 + ["d", "e" ,"f"]
#列表的连接
print(list5)
random.shuffle(list1)
#列表的乱序
print(list1)
print(max(list1))
print(min(list1))
print(len(list1))
#得到列表的最大值,最小值,和长度
list1 = list(range(10, 21 ,1))
list1.append(33)
#列表后追加新元素
print(list1)
list1.extend([44, 55, 66])
#列表后追加新列表
print(list1)
list1.reverse()
#列表逆序
print(list1)
list1.sort()
#列表排序,从小到大
print(list1)
list1.reverse()
print(list1)
list1[0:4] = ['a', 'b']
#列表部分替换
print(list1)
|
2604115e10aba3762f712ccbd5bfbf72cae40791 | javierllaca/strange-loops | /challenges/math/euler/44/main.py | 371 | 3.796875 | 4 | from math import sqrt
def is_pentagonal(n):
p = (sqrt(1 + 24 * n) + 1) / 6
return p == int(p)
def find():
i = 1
while True:
i += 1
n = i * (3 * i - 1) / 2
for j in range(i - 1, 0, -1):
m = j * (3 * j - 1) / 2
if is_pentagonal(n - m) and is_pentagonal(n + m):
return n - m
print find()
|
a535274ecb9b063b7785d91267840528afaf01ee | jaalorsa517/ADSI-SENA | /data/get_ciudades.py | 815 | 3.65625 | 4 | # -*- coding:utf-8 -*-
import sqlite3
from sqlite3 import Error
def load():
_CIUDADES = ('ANDES', 'BETANIA', 'HISPANIA', 'JARDIN', 'SANTA INES',
'SANTA RITA', 'TAPARTO')
_PATH_DB = '/home/jaalorsa/Proyectos/flutter/ventas/data/pedidoDB.db'
_ID = 1
print('INICIÓ PROCESO DE CIUDADES')
n = 0
try:
conexion = sqlite3.connect(_PATH_DB)
conexion.execute("DELETE FROM ciudad")
conexion.commit()
for ciudad in _CIUDADES:
conexion.execute("INSERT INTO ciudad VALUES({},'{}')".format(
_ID + n, ciudad))
conexion.commit()
n += 1
print('TERMINO PROCESO DE CIUDADES')
except Error:
print(type(Error).__name__)
conexion.close()
finally:
conexion.close() |
a74b57cfc00b45b578457560e4f544520702ad4a | lradebe/Practice-Python | /duplicate_char.py | 745 | 4.25 | 4 | def duplicate_char(input):
"""This function takes characters as input then displays its duplicates
and doesn't remove the first occurance while it removes the duplicated characters
into a new variable"""
input = str(input)
counter = 0
duplicate_char = ""
characters = ""
for char in input:
if not char in characters:
characters += char
else:
duplicate_char += char
counter += 1
print("Original input:",input)
print("First occurance Characters:",characters)
print("Duplicated characters:",duplicate_char)
print("Number of duplicated characters:",counter)
if __name__ == "__main__":
input = "Hello_Yellow_Fellow"
duplicate_char(input)
|
5da913420374dfdc708cd9f12a9619ceaf08df99 | Talk-To-Code/TalkToCode | /AST/output/program expected outputs/P Progs/BinarySearch.py | 573 | 4.09375 | 4 | def binarySearch(searchList, start, end, num):
if(length >= start):
mid = start + (end - start) / 2
if(searchList[mid] == num):
return mid
elif(searchList[mid] > num):
return binarySearch(searchList, start, mid - 1, num)
else:
return binarySearch(searchList, mid + 1, end, num)
else:
return -1
searchList = [2, 3, 4, 10, 40]
x = input("Enter number to search: ")
result = binarySearch(searchList, 0, len(searchList) - 1, x)
if(result != -1):
print("Element is present at index %d" % result)
else:
print("Element is not present in array")
|
f4fafdb4f708ad160e1c09075cbf4ac7859b04da | nk900600/Python | /week_1/Algorithm/FindYourNumber/YourNumberBL.py | 875 | 4.0625 | 4 | # ---------------------------------- prg-----------------------------------------------
# My_Number.py
# date : 26/08/2019
# find a number using binary search
def check(N):
i = 0
j = N - 1
while i <= j:
# take a middle number
m = i + (j - i) // 2
# Ask the user is this his number
print("Is this your number : ", m)
reply1 = int(input("Enter your answer if Yes then 1 else 0 : "))
if reply1 == 1:
print("Ab to thik h mil gaya na tumhara soch huaa number")
return
# if no then ask number is grater than or less then
else:
reply2 = int(input("If your number is grater than then Enter 1 else 0 : "))
if reply2 == 1:
i = m + 1
else:
j = m - 1
print("You are liar your number is not in this range")
|
2fbe670913a630c49f3ff1fe556bf55065552bcf | anmolparida/selenium_python | /zMiscellaneous/GeeksForGeeks_VMware/LongestCommonSubsequence.py | 1,340 | 4.0625 | 4 | # https://www.geeksforgeeks.org/printing-longest-common-subsequence/
# Dynamic programming implementation of LCS problem
# Returns length of LCS for X[0..m-1], Y[0..n-1]
def lcs(X, Y, m, n):
L = [[0 for x in range(n+1)] for x in range(m+1)]
# Following steps build L[m+1][n+1] in bottom up fashion. Note
# that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]
for i in range(m+1):
for j in range(n+1):
if i == 0 or j == 0:
L[i][j] = 0
elif X[i-1] == Y[j-1]:
L[i][j] = L[i-1][j-1] + 1
else:
L[i][j] = max(L[i-1][j], L[i][j-1])
# Following code is used to print LCS
index = L[m][n]
# Create a character array to store the lcs string
lcs = [""] * (index+1)
lcs[index] = ""
# Start from the right-most-bottom-most corner and
# one by one store characters in lcs[]
i = m
j = n
while i > 0 and j > 0:
# If current character in X[] and Y are same, then
# current character is part of LCS
if X[i-1] == Y[j-1]:
lcs[index-1] = X[i-1]
i-=1
j-=1
index-=1
# If not same, then find the larger of two and
# go in the direction of larger value
elif L[i-1][j] > L[i][j-1]:
i-=1
else:
j-=1
print ("LCS of " + X + " and " + Y + " is " + "".join(lcs))
# Driver program
X = "AGGTAB"
Y = "GXTXAYB"
m = len(X)
n = len(Y)
lcs(X, Y, m, n)
# This code is contributed by BHAVYA JAIN
|
5932d8103dfdc0b5bce26a51e5d5bf1b6f18a27e | catboost/catboost | /contrib/python/scipy/py3/scipy/sparse/linalg/_norm.py | 5,662 | 3.671875 | 4 | """Sparse matrix norms.
"""
import numpy as np
from scipy.sparse import issparse
from numpy import Inf, sqrt, abs
__all__ = ['norm']
def _sparse_frobenius_norm(x):
if np.issubdtype(x.dtype, np.complexfloating):
sqnorm = abs(x).power(2).sum()
else:
sqnorm = x.power(2).sum()
return sqrt(sqnorm)
def norm(x, ord=None, axis=None):
"""
Norm of a sparse matrix
This function is able to return one of seven different matrix norms,
depending on the value of the ``ord`` parameter.
Parameters
----------
x : a sparse matrix
Input sparse matrix.
ord : {non-zero int, inf, -inf, 'fro'}, optional
Order of the norm (see table under ``Notes``). inf means numpy's
`inf` object.
axis : {int, 2-tuple of ints, None}, optional
If `axis` is an integer, it specifies the axis of `x` along which to
compute the vector norms. If `axis` is a 2-tuple, it specifies the
axes that hold 2-D matrices, and the matrix norms of these matrices
are computed. If `axis` is None then either a vector norm (when `x`
is 1-D) or a matrix norm (when `x` is 2-D) is returned.
Returns
-------
n : float or ndarray
Notes
-----
Some of the ord are not implemented because some associated functions like,
_multi_svd_norm, are not yet available for sparse matrix.
This docstring is modified based on numpy.linalg.norm.
https://github.com/numpy/numpy/blob/master/numpy/linalg/linalg.py
The following norms can be calculated:
===== ============================
ord norm for sparse matrices
===== ============================
None Frobenius norm
'fro' Frobenius norm
inf max(sum(abs(x), axis=1))
-inf min(sum(abs(x), axis=1))
0 abs(x).sum(axis=axis)
1 max(sum(abs(x), axis=0))
-1 min(sum(abs(x), axis=0))
2 Not implemented
-2 Not implemented
other Not implemented
===== ============================
The Frobenius norm is given by [1]_:
:math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
References
----------
.. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
Examples
--------
>>> from scipy.sparse import *
>>> import numpy as np
>>> from scipy.sparse.linalg import norm
>>> a = np.arange(9) - 4
>>> a
array([-4, -3, -2, -1, 0, 1, 2, 3, 4])
>>> b = a.reshape((3, 3))
>>> b
array([[-4, -3, -2],
[-1, 0, 1],
[ 2, 3, 4]])
>>> b = csr_matrix(b)
>>> norm(b)
7.745966692414834
>>> norm(b, 'fro')
7.745966692414834
>>> norm(b, np.inf)
9
>>> norm(b, -np.inf)
2
>>> norm(b, 1)
7
>>> norm(b, -1)
6
"""
if not issparse(x):
raise TypeError("input is not sparse. use numpy.linalg.norm")
# Check the default case first and handle it immediately.
if axis is None and ord in (None, 'fro', 'f'):
return _sparse_frobenius_norm(x)
# Some norms require functions that are not implemented for all types.
x = x.tocsr()
if axis is None:
axis = (0, 1)
elif not isinstance(axis, tuple):
msg = "'axis' must be None, an integer or a tuple of integers"
try:
int_axis = int(axis)
except TypeError as e:
raise TypeError(msg) from e
if axis != int_axis:
raise TypeError(msg)
axis = (int_axis,)
nd = 2
if len(axis) == 2:
row_axis, col_axis = axis
if not (-nd <= row_axis < nd and -nd <= col_axis < nd):
raise ValueError('Invalid axis %r for an array with shape %r' %
(axis, x.shape))
if row_axis % nd == col_axis % nd:
raise ValueError('Duplicate axes given.')
if ord == 2:
raise NotImplementedError
#return _multi_svd_norm(x, row_axis, col_axis, amax)
elif ord == -2:
raise NotImplementedError
#return _multi_svd_norm(x, row_axis, col_axis, amin)
elif ord == 1:
return abs(x).sum(axis=row_axis).max(axis=col_axis)[0,0]
elif ord == Inf:
return abs(x).sum(axis=col_axis).max(axis=row_axis)[0,0]
elif ord == -1:
return abs(x).sum(axis=row_axis).min(axis=col_axis)[0,0]
elif ord == -Inf:
return abs(x).sum(axis=col_axis).min(axis=row_axis)[0,0]
elif ord in (None, 'f', 'fro'):
# The axis order does not matter for this norm.
return _sparse_frobenius_norm(x)
else:
raise ValueError("Invalid norm order for matrices.")
elif len(axis) == 1:
a, = axis
if not (-nd <= a < nd):
raise ValueError('Invalid axis %r for an array with shape %r' %
(axis, x.shape))
if ord == Inf:
M = abs(x).max(axis=a)
elif ord == -Inf:
M = abs(x).min(axis=a)
elif ord == 0:
# Zero norm
M = (x != 0).sum(axis=a)
elif ord == 1:
# special case for speedup
M = abs(x).sum(axis=a)
elif ord in (2, None):
M = sqrt(abs(x).power(2).sum(axis=a))
else:
try:
ord + 1
except TypeError as e:
raise ValueError('Invalid norm order for vectors.') from e
M = np.power(abs(x).power(ord).sum(axis=a), 1 / ord)
return M.A.ravel()
else:
raise ValueError("Improper number of dimensions to norm.")
|
aa7080fed277cfa8b403d5f5981ca6da1db92cda | Coder47890/102 | /imageCapture.py | 958 | 3.6875 | 4 | import shutil
import os
source_path = input("Pls give the path of a Folder you want to take Backup : ")
back_path = input(
"Pls give the path of a Folder where you want to store the Backup : ")
listOfItems = os.listdir(source_path)
for i in listOfItems:
FileName, Extension = os.path.splitext(i)
if(Extension == '' or Extension == 'pc'):
continue
path = source_path+'/'+i
dest_path = back_path+'/'
shutil.copy(path, dest_path)
print("Copied The Files and Sorting them!!")
listOfItems2 = os.listdir(back_path)
for i in listOfItems2:
FileName, Extension = os.path.splitext(i)
if(Extension == ''):
continue
finalPath = back_path + '/' + Extension
exist = os.path.exists(finalPath)
if(exist == False):
os.mkdir(finalPath)
shutil.move(back_path+'/'+i, finalPath+'/'+i)
print("Sorting Completed!!")
print("Congratulations !! All your files are Ready") |
b6a7eb93aeaecd64116880f2918e6c69a809f217 | amod26/DataStructuresPython | /Check if N and its double exists.py | 372 | 3.890625 | 4 | arr = [7, 1, 14, 11]
# Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).
def checkIfExist(arr):
tmp = set(arr)
if 0 in tmp and arr.count(0) > 1:
return True
for num in arr:
if num != 0 and 2 * num in tmp:
return True
return False
checkIfExist(arr)
|
3879dd42f57cb17ecefae227dac18d939e8a589b | charles9li/simulate-openmm | /simulate/utils/nested_parser.py | 3,535 | 3.546875 | 4 | from simulate.utils.line_deque import LineDeque
class NestedParser(object):
""" This class takes in a LineDeque instance and creates a new LineDeque
instance that is nested to reflect the nesting based on the specified
bounding characters. The input LineDeque instance should be already created
from the input file and cleaned of all comments.
Parameters
----------
line_deque : LineDeque
LineDeque instance without comments
begin_char : str
bounding character
end_char : str
bounding character
"""
# =========================================================================
def __init__(self, line_deque, begin_char, end_char):
self.begin_char = begin_char
self.end_char = end_char
self.parsed_lines = self._nested_parser(line_deque)
# =========================================================================
def _nested_parser(self, line_deque):
parsed_lines, current_level = self._nested_parser_helper(line_deque, 0)
if current_level != 0:
raise ValueError("Enclosing character mismatch.")
return parsed_lines
def _nested_parser_helper(self, line_deque, current_level):
parsed_lines = LineDeque()
while len(line_deque) > 0:
line = line_deque.popleft()
bounding_char = self._determine_bounding_character(line)
if bounding_char is not None:
line = line.split(bounding_char, 1)
parsed_lines.append(line[0].strip())
line_deque.appendleft(line[1].strip())
level_increment = self._determine_level_increment(bounding_char)
current_level += level_increment
if level_increment == -1:
inner_parsed_lines, current_level = self._nested_parser_helper(line_deque, current_level)
parsed_lines.append(inner_parsed_lines)
elif level_increment == 1:
break
else:
parsed_lines.append(line)
return parsed_lines, current_level
# =========================================================================
# Private helper methods for creating nested LineDeque
def _determine_bounding_character(self, line):
if self._has_only_begin_char(line):
return self.begin_char
elif self._has_only_end_char(line):
return self.end_char
elif self._has_both(line):
return self._first_bounding_char(line)
else:
return None
def _has_only_begin_char(self, line):
if self.end_char in line:
return False
return self.begin_char in line
def _has_only_end_char(self, line):
if self.begin_char in line:
return False
return self.end_char in line
def _has_both(self, line):
return self.begin_char in line and self.end_char in line
def _first_bounding_char(self, line):
if not self._has_both(line):
raise ValueError("Input line doesn't have both enclosing characters.")
begin_index = line.find(self.begin_char)
end_index = line.find(self.end_char)
min_index = min(begin_index, end_index)
return line[min_index]
def _determine_level_increment(self, bounding_char):
if bounding_char == self.begin_char:
return -1
elif bounding_char == self.end_char:
return 1
else:
return 0
|
6dfef00b519bf98d5782f4cac0bea939c39bfe95 | sam1208318697/Leetcode | /Leetcode_env/2019/6_21/Spiral_Matrix.py | 1,512 | 3.625 | 4 | # 54. 螺旋矩阵
# 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
# 示例 1:
# 输入:
# [
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ]
# ]
# 输出: [1,2,3,6,9,8,7,4,5]
# 示例 2:
# 输入:
# [
# [1, 2, 3, 4],
# [5, 6, 7, 8],
# [9,10,11,12]
# ]
# 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
class Solution:
def spiralOrder(self, matrix):
if not matrix:
return []
up_row = 0
down_row = len(matrix) - 1
left_col = 0
right_col = len(matrix[0]) - 1
res = []
while up_row <= down_row and left_col <= right_col:
# 从左到右
for i in range(left_col, right_col + 1):
res.append(matrix[up_row][i])
up_row += 1
if up_row > down_row:
break
# 从上到下
for i in range(up_row, down_row + 1):
res.append(matrix[i][right_col])
right_col -= 1
if left_col > right_col:
break
# 从右到左
for i in range(right_col, left_col - 1, -1):
res.append(matrix[down_row][i])
down_row -= 1
# 从下到上
for i in range(down_row, up_row - 1, -1):
res.append(matrix[i][left_col])
left_col += 1
return res
sol = Solution()
print(sol.spiralOrder([[1, 2, 3, 4],[5, 6, 7, 8],[9,10,11,12]])) |
c57f8c15480e748dc1690118ef81df4b858f0466 | teamclouday/Mooner | /DataProcess/json_to_csv.py | 519 | 3.5 | 4 | # Just found that the json file is difficult to view in vscode
# so convert it to a CSV
import os
import json
import pandas as pd
if __name__ == "__main__":
name = "tweets_200"
with open(name+".json", "r") as inFile:
data = json.load(inFile)
df = []
for userid in data.keys():
tweets = data[userid]
for tweet in tweets:
df.append([userid, tweet])
df = pd.DataFrame(df, columns=["User ID", "Tweet"])
df.to_csv(name+".csv", index=False)
print("Converted") |
05845337937003b283a8f7a918a372916b8d9f63 | emilypng/python-exercises | /Packt/act2.py | 131 | 3.828125 | 4 | """
Determining the pythagorean distance between 3 points.
"""
x, y, z = 2, 3, 4
result = (x**2 + y**2 + z**2)**0.5
print(result)
|
04517b8c252eac09be50353b3b2f111278b836d5 | jovit/mc906 | /project_2/genetic_algorithm.py | 3,597 | 3.65625 | 4 | import random
class Individual(object):
def __init__(self, chromossome_mutation_rate=0.):
"""
Generate a new individual
"""
self.chromossome_mutation_rate = chromossome_mutation_rate
pass
def fitness(self):
"""
Calculate self fitness value
:return: individual fitness
"""
pass
def clone(self):
"""
Creates a copy of self
:return: a copy of self
"""
pass
def breed(self, other):
"""
Mutates self based on another individual
:param other: mate partner
:return: its child
"""
pass
def mutate(self):
"""
Mutates self
:return: a new individual based on self
"""
pass
class Population(object):
def __init__(self, source, size=None, mutation_rate=0., crossover_rate=0.):
if isinstance(source, Population):
self.population = [ind.clone() for ind in source.population]
self.size = source.size
self.crossover_rate = source.crossover_rate
self.mutation_rate = source.mutation_rate
else:
self.size = size
self.mutation_rate = mutation_rate
self.crossover_rate = crossover_rate
if isinstance(source, list):
self.population = source
else:
self.population = [source() for _ in range(size)]
self.population.sort(key=lambda x: x.fitness(), reverse=True)
def select_breeding_pool(self):
pass
def select_next_gen(self):
self.population.sort(key=lambda x: x.fitness(), reverse=True)
self.population = self.population[:self.size]
def clone(self):
pass
def rank(self):
return self.population[0].fitness()
def best_individual(self):
return self.population[0]
def generate(self, mutate_function=lambda a: a.mutate(), crossover_function=lambda a, b: a.breed(b)):
offspring = self.clone()
parents = offspring.select_breeding_pool()
for i in range(1, len(parents) - 1, 2):
if random.random() < offspring.crossover_rate:
offspring.population.append(crossover_function(parents[i], parents[i + 1]))
offspring.population.append(crossover_function(parents[i + 1], parents[i]))
mutated_individuals = []
for ind in offspring:
if random.random() < offspring.mutation_rate:
mutated_individuals.append(mutate_function(ind))
offspring.population.extend(mutated_individuals)
offspring.select_next_gen()
return offspring
def __len__(self):
return len(self.population)
def __iter__(self):
return self.population.__iter__()
class Darwin(object):
@staticmethod
def genetic_algorithm(population, generations, mutation_function, crossover_function, should_end=None):
best = population.best_individual()
best.model = None
best_individuals = [best]
next_gen = population
for generation in range(generations):
print("Generation {} best {}".format(generation, best_individuals[generation]))
if should_end and should_end(best_individuals):
break
next_gen = next_gen.generate(mutate_function=mutation_function, crossover_function=crossover_function)
best = next_gen.best_individual()
best.model = None
best_individuals.append(best)
return best_individuals
|
d1b470a9bfe00fe8d695a1f97f7d15c89d7635fc | vqpv/stepik-course-58852 | /7 Циклы for и while/7.4 Цикл while/5.py | 101 | 3.90625 | 4 | num = int(input())
summa = 0
while num >= 0:
summa += num
num = int(input())
print(summa)
|
6cc04c765b5398cbc42805cad38252ccd2e64b40 | Alexander8807/Reposit | /Списки.py | 3,233 | 4.0625 | 4 | a_list = []
print(type(a_list))
a_tuple =()
print(type(a_tuple))
a_set = set()
print(type(a_set)) #типы список, кортеж#
some_list = [1243464, 123.00023, "Some string", True, None, [1234, "New string", False]]
print(some_list) #список внутри списка#
print(some_list[0:3]) #вывести список от 1 до 3 элемента#
courses = ["History", "Math", "Literature", "Physics", "Programming", [1, 2, 3, 4, 5]]
courses2 = ["Art", "Biology"]
print(courses[2][5:]) #сначала элемент, затем буква элемента#
print(courses)
courses[2] = "Art" #заменить 3й элемент на арт#
print(courses)
print(len(courses)) #посчитать элементы списка#
print(courses + courses2) #сложить списки#
courses.append("Art") #добавить слово арт в список, можно добавить так же другой список#
print(courses)
courses[5].append(courses2) #добавили список в шестой элемент#
print(courses)
courses.remove("Math") #удалить слово Math из списка#
print(courses)
popped_item = courses.pop()
courses.pop() #выкинуть последний элемент и принять его значение#
print(courses)
print(popped_item)
courses.insert(2, "Geometry") #Вставить на позицию 2го элемента слово Geometry#
print(courses)
courses.extend(courses2) #сложение списков (лучше просто +)#
print(courses)
numbers = [1, 45, 63, 34, 56, 78, 3]
print(numbers)
numbers.sort() #сортировка чисел по возрастанию#
print(numbers) #Смешанные списки нельзя сортировать#
courses.sort() #сортировка элементов по алфавиту#
print(courses)
courses.sort(reverse=True) #сортировка в обратном порядке#
print(courses)
print(sorted(courses)) #показать единожды сортировку по возрастанию#
print(min(numbers)) #показать минимальное число#
courses.sort(reverse=False) #вернуть сортировку в порядок#
print(max(numbers)) #показать максимальное число#
print(sum(numbers)) #суммировать числа в списке#
print(courses.index("History")) #индексация#
new_string = ", ".join(courses) #конвертировать список в строку, перечесляя элементы списка через запятую и пробел#
print(new_string)
list_1 = ["Math", "History", "Programming", "Physics"]
list_2 = list_1.copy() #копировать, но в дальнейшем может измениться#
print(list_1)
print(list_2)
list_1[2] = "Sports"
list_2[0] = "Art"
print(list_1)
print(list_2) |
539154f81534eb8e88423b8795f604b9ab28cea8 | pymft/mft-01 | /S05/files_and_with_block/read_lines_file.py | 195 | 3.765625 | 4 | f = open("input.txt", mode='r')
line = f.readline()
print(line)
# print("hello")
# print("salam\n")
# print("salut")
# EOF
while line != '':
line = f.readline()
print(line)
f.close() |
6c439d669bd1a90bc2f2355657931bad72dc03ec | SardulDhyani/MCA3_lab_practicals | /MCA3HLD/20711136 - Himanshu Chandola/Codes/Statistical_Concepts_and_Linear_Algebra/standard_deviation.py | 465 | 3.734375 | 4 | # Himanshu Chandola MCA 3 - HLD Campus STD ID-20711136
observation = [11,15,14,12,10]
sum=0
for i in range(len(observation)):
sum+=observation[i]
mean_of_observations = sum/len(observation)
sum_of_squared_deviation = 0
for i in range(len(observation)):
sum_of_squared_deviation+=(observation[i]- mean_of_observations)**2
Standard_Deviation = ((sum_of_squared_deviation)/len(observation))**0.5
print("Standard Deviation of sample is ",Standard_Deviation) |
c75c99ab983b2bffb8f1840a6f949e0c08053c00 | AntonOni/interview | /Solutions_P1_P2/String/S-P1_929_Unique_Email_Addresses.py | 474 | 3.546875 | 4 | emails = ["test.email+alex@leetcode.com",
"test.e.mail+bob.cathy@leetcode.com",
"testemail+david@lee.tcode.com"]
def solve():
result = []
for i in emails:
email = i.split("@")
left = email[0]
right = email[1]
if "." in left:
left = left.replace(".", "")
if "+" in left:
indx = left.index("+")
left = left[:indx]
final = left + "@" + right
result.append(final)
return set(result)
print(solve())
|
8fd95469f1d0dddaebbbaf9903ff4ba8db6101c8 | maarten1001/advent-of-code-2020 | /day08/part2.py | 1,160 | 3.59375 | 4 | # get the input file
f = open("input.txt")
entries = f.read().splitlines()
f.close()
for fix in range(len(entries)):
acc = 0
i = 0
executed = [False for x in range(len(entries))]
print("Fixing line " + str(fix + 1))
while True:
if i == len(entries):
print("Achieved termination by changing the instruction in line " + str(fix + 1))
print("Accumulator value is " + str(acc))
quit(0)
elif executed[i]:
print("Attempting to execute the instruction in line " + str(i + 1) + " for the second time")
print("")
break
else:
executed[i] = True
instr = entries[i].split()
# print(str(i + 1) + ": " + str(instr))
op = instr[0]
arg = instr[1]
if op == "acc":
acc += int(arg)
i += 1
elif (op == "jmp" and fix != i) or (op == "nop" and fix == i):
i += int(arg)
elif (op == "nop" and fix != i) or (op == "jmp" and fix == i):
i += 1
else:
print("invalid operation" + op)
|
830802e627fe7aaed1057d4ed66ccadf532bf357 | tanpv/awesome-blockchain | /algorithm_python/move_zeros_to_end.py | 378 | 4.25 | 4 | """
Write an algorithm that takes an array and moves all of the zeros to the end,
preserving the order of the other elements.
move_zeros([false, 1, 0, 1, 2, 0, 1, 3, "a"])
returns => [false, 1, 1, 2, 1, 3, "a", 0, 0]
The time complexity of the below algorithm is O(n).
"""
input_list = [false, 1, 0, 1, 2, 0, 1, 3, "a"]
def move_zeros(self, input_list):
|
07b76072b8d00f6f251c3f286ece31f522abe5d7 | rgj7/coding_challenges | /codeabb/Python/p28_body_mass_index.py | 497 | 3.75 | 4 | """
CodeAbbey, Problem 28
Coded by Raul Gonzalez
"""
def body_constitution(weight, height):
bmi = weight / (height**2)
if bmi < 25:
return "under" if bmi < 18.5 else "normal"
else:
return "over" if bmi < 30 else "obese"
def main():
n = int(input())
results = []
for _ in range(n):
weight, height = map(float, input().split())
results.append(body_constitution(weight, height))
print(" ".join(results))
if __name__ == '__main__':
main()
|
c9586a188539e51edd49dd9f38e05a15d1982dad | jsebastianrincon/curso_python | /Fundamentos/operadores_logicos.py | 558 | 4.1875 | 4 | # Variables
#a = int(input("Ingrese un valor: "))
a = 3
valorMinimo = 0
valorMaximo = 5
dentroRango = (a >= valorMinimo and a <= valorMaximo)
# Condicional If
if(dentroRango):
print("Esta en el rango")
else:
print("Esta fuera del rango")
vacaciones = True
diaDescanso = False
if(vacaciones or diaDescanso):
print("Se puede salir")
else:
print("Hoy no se puede salir")
# Invirte el valor de la variables
# print(not(vacaciones))
if(not(vacaciones or diaDescanso)):
print("Hoy no se puede salir")
else:
print("Se puede salir")
|
70599342ebfa288044941ee9ff5afab7eb59ee3c | MiyabiTane/myLeetCode_ | /30-Day_Challenge/25_Jump_Game.py | 337 | 3.6875 | 4 | def canJump(nums):
#その位置から最後のマスにたどり着けるのがGoodマス
Good_left = len(nums) - 1
for i in range(len(nums)-1, -1, -1):
if i + nums[i] >= Good_left:
Good_left = i
if Good_left == 0:
return True
return False
ans = canJump([3, 2, 1, 0, 4])
print(ans)
|
3953086c2492ace42a368e8a026935f2a7605621 | Airedyver/mars_data_scraping | /scrape_mars.py | 6,845 | 3.78125 | 4 | #NASA Mars News
#Scrape the NASA Mars News Site and collect the latest News https://mars.nasa.gov/news/
#Title and Paragragh Text. Assign the text to variables that you can reference later.
# import dependencies
# Dependencies
from os import getcwd
from os.path import join
from bs4 import BeautifulSoup as bs
import requests
from splinter import Browser
import pandas as pd
import numpy as np
from selenium import webdriver
def scrape():
print("scrape() started")
scrape_dict = {}
# URL of page to be scraped
url[0] = 'https://mars.nasa.gov/news/'
url[1] = 'https://twitter.com/marswxreport?lang=en'
url[2] = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'
url[3] = 'https://space-facts.com/mars/'
url[4] ='https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'
#Scrape the NASA Mars News Site and collect the latest News Title\
# and Paragragh Text. Assign the text to variables that you can reference later.
# Retrieve page with the requests module
response = requests.get(url[0])
# Create BeautifulSoup object; parse with 'html.parser'
soup = bs(response.text, 'html.parser')
#find all the headlines
# results are returned as an iterable list
headlines = soup.find_all('div', class_="slide")
# create a list to append your title and paragraph
news_title_list = []
news_p_list =[]
#create a for loop to loopthrough all the headlines
for headline in headlines:
try:
# Identify and return title of listing
news_title = headline.find('div', class_="content_title").text
#append to news_title_list
news_title_list.append(news_title)
# Identify and return price of listing
news_p = headline.find('div', class_="rollover_description_inner").text
news_p_list.append(news_p)
except Exception as e:
print(e)
scrape_dict["news_title"] = news_title_list[0]
scrape_dict["news_p"] = news_p_list[0]
#######################
#Visit the url for JPL's Featured Space Image here.
"""""
Use splinter to navigate the site and find the image url for the current Featured Mars Image
and assign the url string to a variable called featured_image_url.
Make sure to find the image url to the full size .jpg image.
Make sure to save a complete url string for this image.
"""
executable_path = {'executable_path': 'chromedriver.exe'}
browser = Browser('chrome', **executable_path, headless=False)
html = browser.html
soup = bs(html, 'html.parser')
browser.visit(url[2])
mars_img_list = []
pictures = soup.find_all('div', class_='img')
for picture in pictures:
mars_img_list.append(picture.img['src'])
scrape_dict["featured_image_url"] = print('https://www.jpl.nasa.gov'+ mars_img_list[0])
""""
Visit the Mars Weather twitter account here and scrape the latest Mars weather tweet
from the page. Save the tweet text for the weather report as a variable called mars_weather.
"""
# Retrieve page with the requests module
response = requests.get(url[1])
#find all the tweets
# results are returned as an iterable list
tweets = soup.find_all('div', class_="js-tweet-text-container")
# create a list to append your title and paragraph
weather_list = []
#create a for loop to loopthrough all the tweets
for tweet in tweets:
try:
# Identify and return tweet
weather_tweet = tweet.find('p', class_= "TweetTextSize TweetTextSize--normal js-tweet-text tweet-text").text
#append to weather_list
weather_list.append(weather_tweet)
except Exception as e:
print(e)
scrape_dict["mars_weather"] = weather_list[0]
""""
Mars Facts
Visit the Mars Facts webpage here and use Pandas to scrape the table containing facts about the
planet including Diameter, Mass, etc.
"""
tables = pd.read_html(url[3])
mars_df = tables[0]
mars_df.columns = ['Facts', 'Factoids']
mars_df.set_index('Facts', inplace=True)
scrape_dict["mars_html_table"] = mars_df.to_html('mars_facts_table.html')
""""
Mars Hemispheres
#Visit the USGS Astrogeology site here to obtain high resolution images for each of Mar's hemispheres.
#You will need to click each of the links to the hemispheres in order to find the image url to the full resolution image.
#Save both the image url string for the full resolution hemipshere image, and the Hemisphere title containing the hemisphere name. Use a Python dictionary to store the data using the keys img_url and title.
#Append the dictionary with the image url string and the hemisphere title to a list. This list will
#contain one dictionary for each hemisphere.
"""
browser.visit(url[4])
#make lists
hemisphere_image_urls = []
hem_url_list = []
#call soup
hemispheres = soup.find_all('div', class_='item')
for hemisphere in hemispheres:
partial_link = hemisphere.a['href']
hemi_link = ('https://astrogeology.usgs.gov' + partial_link)
hem_url_list.append(hemi_link)
#call the next url
hem_title_list = []
parhem_list = []
for x in range(0,4):
browser.visit(hem_url_list[x])
hem_title = soup.find('h2').text
hem_title_list.append(hem_title)
links = soup.find_all('div', class_='downloads')
for link in links:
parhem_link = link.a['href']
parhem_list.append(parhem_link)
hem_dict = dict(title = hem_title_list[x],img_url = parhem_list[x])
hemisphere_image_urls.append(hem_dict)
scrape_dict["hemisphere_image_urls"] = hemisphere_image_urls
return scrape_dict
""""
Step 2 - MongoDB and Flask Application
Use MongoDB with Flask templating to create a new HTML page that
displays all of the information that was scraped from the URLs above.
Start by converting your Jupyter notebook into a Python script called scrape_mars.py
with a function called scrape that will execute all of your scraping code from above
and return one Python dictionary containing all of the scraped data.
"""
"""
Next, create a route called /scrape that will import your scrape_mars.py script and call your scrape function.
Store the return value in Mongo as a Python dictionary.
Create a root route / that will query your Mongo database and pass the mars data into an HTML template to display the data.
Create a template HTML file called index.html that will take the mars data dictionary and
display all of the data in the appropriate HTML elements.
""" |
67ed844d101704d3872310eb55ef5019de88e339 | CateGitau/Python_programming | /Packt_Python_programming/Chapter_3/exercise41.py | 371 | 3.5625 | 4 | l = [2, 3, 5, 8, 11, 12, 18]
search_for = 11
slice_start = 0
slice_end = len(l) - 1
found = False
while slice_start <= slice_end and not found:
mid = (slice_start + slice_end)// 2
if l[mid] == search_for:
found = True
else:
if search_for > l[mid]:
slice_start = mid + 1
else:
slice_end = mid - 1
print(mid) |
deda61c674e0451af9837ea78a24d242249ac8f7 | jareiter/PHYS202-S14 | /SciPy/Differentiators.py | 1,113 | 3.796875 | 4 |
import numpy as np
def twoPtForwardDiff(x,y):
"""
Returns the derivative of y with respect to x using the forward
differentiation method
"""
dydx = np.zeros(y.shape,float)
dydx[0:-1] = np.diff(y)/np.diff(x)
dydx[-1] = (y[-1] - y[-2])/(x[-1] - x[-2])
return dydx
def twoPtCenteredDiff(x,y):
"""
Returns the derivative of y with respect to x using the center
differentiation method
"""
dydx = np.zeros(y.shape,float)
dydx[0] = (y[1]-y[0])/(x[1]-x[0])
dydx[1:-1] = (y[2:] - y[:-2])/(x[2:] - x[:-2])
dydx[-1] = (y[-1] - y[-2])/(x[-1] - x[-2])
return dydx
def fourPtCenteredDiff(x,y):
"""
Returns the derivative of y with respect to x using the center
differentiation method
"""
dydx = np.zeros(y.shape,float)
dydx[0] = (y[1]-y[0])/(x[1]-x[0])
dydx[1] = (y[2]-y[1])/(x[2]-x[1])
dydx[-1] = (y[-1] - y[-2])/(x[-1] - x[-2])
dydx[-2] = (y[-2] - y[-3])/(x[-2] - x[-3])
h = 0.1
for i in range(2,np.size(y)-2):
dydx[i] = ((y[i-2] - 8*y[i-1]) + 8*y[i+1] - y[i+2])/(12*h)
return dydx |
518d99a7efacd05e3ca56b246236bb400400a76a | brockryan2/Python_practice | /trying_out_classes.py | 1,593 | 3.515625 | 4 | # trying_out_classes
from pprint import pprint as pp
class Flight:
def __init__(self, number, aircraft):
if not number[:2].isalpha():
raise ValueError("No airline code in '{}'".format(number))
if not number[:2].isupper():
raise ValueError("Invalid airline code '{}'".format(number))
if not (number[2:].isdigit() and int(number[2:]) <= 9999):
raise ValueError("Invalid route number '{}'".format(number))
self._number = number
self._aircraft = aircraft
rows, seats = self._aircraft.seating_plan()
self._seating = [None] + [{letter: None for letter in seats} for _ in rows]
def number(self):
return self._number
def airline(self):
return self._number[:2]
def aircraft_model(self):
return self._aircraft.model()
class Aircraft:
def __init__(self, registration):
self._registration = registration
def registration(self):
return self._registration
def num_seats(self):
rows, row_seats = self.seating_plan()
return len(rows) * len(row_seats)
class AirbusA319(Aircraft):
def model(self):
return "Airbus A319"
def seating_plan(self):
return range(1, 23), "ABCDEF"
class Boeing777(Aircraft):
def model(self):
return "Boeing 777"
def seating_plan(self):
return range(1, 56), "ABCDEFGHJK"
a1 = AirbusA319("A-IFHS")
a2 = Boeing777("B-UGVA")
pp(a1.model())
pp(a1.seating_plan())
pp(a1.num_seats())
pp(a2.model())
pp(a2.seating_plan())
pp(a2.num_seats())
f1 = Flight("AB1234", a1)
f2 = Flight("BG9876", a2)
#pp(f1._number)
pp(f1.airline())
#pp(aircraft_model(f1))
|
8bdb89ee4cbd9a9038324697c3218efad8029dd5 | Lovely-Professional-University-CSE/int247-machine-learning-project-2020-kem031-sumant_42 | /work.py | 1,165 | 3.578125 | 4 | from sklearn import datasets
import pandas as pd
import numpy as np
context="""This dataset contains complete information about
various aspects of crimes happened in India from 2001.
There are many factors that can be analysed from this dataset. Over all,
I hope this dataset helps us to understand better about India."""
insp='''
There could be many things one can understand by analyzing this dataset. Few inspirations for you to start with.
1.What is the major reason people being kidnapped in each and every state?
2.Offenders relation to the rape victim
3.Juveniles family background, education and economic setup.
4.Which state has more crime against children and women?
5.Age group wise murder victim
6.Crime by place of occurrence.
7.Anti corruption cases vs arrests.
8.Which state has more number of complaints against police?
9.Which state is the safest for foreigners?'''
#loading data from our csv file
data_rape=pd.read_csv('data\Victims_of_rape.csv',delimiter=',')
#defining the functions to get the data from our files
def get_col_rape():
return data_rape.columns
def get_dataR_head():
return data_rape
|
70a4d0b0dc91e124d7bbf5add67c2f243576c86b | bssrdf/pyleet | /B/BullsandCows.py | 2,255 | 4.34375 | 4 | '''
-Medium-
*Hash Table*
You are playing the Bulls and Cows game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes
a guess, you provide a hint with the following info:
The number of "bulls", which are digits in the guess that are in the correct position.
The number of "cows", which are digits in the guess that are in your secret number but are located in
the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that
they become bulls.
Given the secret number secret and your friend's guess guess, return the hint for your friend's guess.
The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows.
Note that both secret and guess may contain duplicate digits.
Example 1:
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation: Bulls are connected with a '|' and cows are underlined:
"1807"
|
"7810"
Example 2:
Input: secret = "1123", guess = "0111"
Output: "1A1B"
Explanation: Bulls are connected with a '|' and cows are underlined:
"1123" "1123"
| or |
"0111" "0111"
Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can
only be rearranged to allow one 1 to be a bull.
Example 3:
Input: secret = "1", guess = "0"
Output: "0A0B"
Example 4:
Input: secret = "1", guess = "1"
Output: "1A0B"
Constraints:
1 <= secret.length, guess.length <= 1000
secret.length == guess.length
secret and guess consist of digits only.
'''
from collections import defaultdict
class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
sd, gd = defaultdict(int),defaultdict(int)
bulls,cows=0,0
for s,g in zip(secret, guess):
if s == g:
bulls += 1
else:
sd[s] += 1
gd[g] += 1
for k in sd:
cows += min(sd[k], gd[k] if k in gd else 0)
return str(bulls)+'A'+str(cows)+'B'
if __name__ == "__main__":
print(Solution().getHint( "1123", "0111")) |
ad65f94b48ed9de2763e68d73e2efb5d5e886410 | seanchen513/dcp | /linked_list/dcp078_merge_k_sorted_LLs.py | 6,271 | 3.984375 | 4 | """
dcp078
This problem was asked recently by Google.
Given k sorted singly linked lists, write a function to merge all the lists into one sorted singly linked list.
"""
import heapq
class Node():
def __init__(self, val=None, next=None):
self.val = val
self.next = next
def __repr__(self):
return f"{self.val}, {self.next.__repr__()}"
# Needed for sorted merge of k sorted linked lists.
def __lt__(self, other):
return self.val < other.val
"""
Build singly-linked list using values from given iterator "it".
Returns both head and tail.
"""
def build_ll(it) -> (Node, Node):
if it is None:
return None, None
# works for dict and set, but it's probably not well-defined behavior
if type(it) in [range, list]:
it = iter(it)
header = Node() # dummy header node
tail = header
val = next(it, None)
while val:
tail.next = Node(val)
tail = tail.next
val = next(it, None)
return header.next, tail
###############################################################################
"""
Solution #1:
Use min heap to store heads of each list.
Assume function __lt__() has been defined in class Node.
O(n log k) time, where n = total number of elements among all input lists.
O(nk log k) time if all atomic lists have approx. length n.
"""
def sorted_merge(lists = list) -> Node:
vals = []
for ll in lists:
if ll:
vals.append(ll)
#heapq.heappush(vals, ll)
heapq.heapify(vals) # O(k)
header = Node() # dummy header node
tail = header
while vals:
m = heapq.heappop(vals) # O(log k)
tail.next = m
tail = tail.next
if m.next:
heapq.heappush(vals, m.next) # O(log k)
return header.next, tail
"""
Solution #1b:
Same as solution #1 using min heap,
BUT don't assume function __lt__() has been defined in class Node.
Deal with this by using storing tuples (node value, index of lists, node)
in heap rather than nodes.
"""
def sorted_merge1b(lists = list) -> Node:
vals = []
for i in range(len(lists)):
if lists[i]:
#vals.append((lists[i].val, i, lists[i]))
heapq.heappush(vals, (lists[i].val, i, lists[i]))
#heapq.heapify(vals) # O(k)
header = Node() # dummy header node
tail = header
while vals:
_, index, m = heapq.heappop(vals) # O(log k)
tail.next = m
tail = tail.next
if m.next:
heapq.heappush(vals, (m.next.val, index, m.next)) # O(log k)
return header.next, tail
"""
Solution#2:
Use array to store heads of each list.
Assume __lt__() is defined in class Node, but don't have to if
store tuples (node value, index of lists, node) in array.
Can either (1) sort array vals and extract vals[0] each time,
or (2) don't sort, but find min(vals) and remove it from array
each time.
O(nk) time, where n = total number of elements among all input lists.
O(n * k^2) time if all atomic lists have approx. length n.
"""
def sorted_merge2(lists = list) -> Node:
vals = []
for ll in lists:
if ll:
vals.append(ll)
header = Node() # dummy node
tail = header
while vals:
# After first iteration, should be O(k) since we only appended one
# item to sorted list. First iteration is O(k log k).
vals = sorted(vals)
#m = min(vals)
m = vals[0]
tail.next = m
tail = tail.next
#vals.remove(m)
vals = vals[1:]
if m.next:
vals.append(m.next)
return header.next, tail
###############################################################################
"""
Sorted merge of l1 and l2, each of which is sorted.
Don't create a new list.
Iterative version.
O(n) time, O(1) space
"""
def merge_sorted(l1: Node, l2: Node) -> Node:
header = Node() # dummy header for merged list
node = header
while l1 and l2:
if l1.val <= l2.val:
node.next = l1
l1 = l1.next
else:
node.next = l2
l2 = l2.next
node = node.next
if l1:
node.next = l1
elif l2:
node.next = l2
return header.next
"""
Solution #3: recursively merge 2 linked lists at a time.
O(n * k^2) time if all atomic lists have approx. length n.
Assume each atomic list has length n.
Merging sorted lists of lengths a and b is O(a+b).
The first merge is None with a list, which is O(1).
2n + 3n + ... + kn = n (2 + 3 + ... + k) = n[k(k+1)/2 - 1] = O(n * k^2)
"""
def sorted_merge_rec(lists : list) -> Node:
merged = None
for lst in lists:
merged = merge_sorted(merged, lst)
return merged
###############################################################################
import random
if __name__ == "__main__":
# head1, _ = build_ll([1, 4, 7])
# head2, _ = build_ll([2, 5, 8])
# head3, _ = build_ll([3, 6, 9])
# head1, _ = build_ll([1, 2, 3, 23])
# head2, _ = build_ll([4, 5, 6])
# head3, _ = build_ll([7, 8])
head1, _ = build_ll(sorted([random.randint(1, 100) for _ in range(5)]))
head2, _ = build_ll(sorted([random.randint(1, 100) for _ in range(3)]))
head3, _ = build_ll(sorted([random.randint(1, 100) for _ in range(4)]))
head4, _ = build_ll([-5])
head5, _ = build_ll([999])
#lists = []
#lists = [None]
#lists = [head1]
#lists = [None, None]
#lists = [None, head1]
#lists = [head1, None]
#lists = [None, head1, None]
#lists = [head1, head2]
#lists = [head1, head1] # this will hang due to repeated list
#lists = [head1, head2, head3]
lists = [None, head5, head1, None, head2, head3, head4, None]
print("\nSorted linked lists:")
for ll in lists:
print(ll)
#head, tail = sorted_merge(lists) # min heap; __lt__() defined in Node
#head, tail = sorted_merge1b(lists) # min heap; don't assume __lt__()...
head, tail = sorted_merge2(lists) # use array instead of min heap
#head = sorted_merge_rec(lists) # recursively merge 2 lists at a time
print("\nSorted, merged linked list:")
print(head)
#print("\nVerify that it is actually sorted:")
|
e2f9621ffb1ae2a2e8f839c97645812677e7d698 | czh4/Python-Learning | /exercise/exercise2-1.py | 313 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 12 16:13:19 2018
@author: andychen
"""
y=int(input("Year:"))
if y%4==0:
print(y," is a leap year")
elif y%100==0:
print(y," is not a leap year")
elif y%400==0:
print(y," is a leap year")
else:
print(y," is not a leap year")
|
25cc8d1666af74edfa2b9ee471efc1ded8c2fb3f | prathamdesai13/SortsNsuch | /RandyDandyProblems.py | 19,093 | 3.796875 | 4 | import math
from collections import Counter, OrderedDict
from operator import itemgetter
from DataStructs import *
def minimumBribes(q):
n = len(q)
num_bribes = 0
bribes = [0] * n
i = 0
while i < n - 1:
if q[i] > q[i + 1]:
bribes[q[i] - 1] += 1
num_bribes += 1
swap(q, i, i + 1)
if bribes[q[i + 1] - 1] > 2:
print('Too chaotic')
return
if i > 0:
i -= 1
else:
i += 1
# print(q)
# print(bribes)
print(num_bribes)
def twoStrings(s1, s2):
"""
Given two strings s1 and s2, determine if they share a common substring
Note that a substring could be just one character
Solution:
Given that even one character will suffice as a common substring, clearly
any substring that contains more than one common character in sequence will
share a common character
"""
#brute force solution O(len(s1) * len(s2))
# for c1 in s1:
# for c2 in s2:
# if c1 == c2:
# return 'YES'
# return 'NO'
# set solution O(len(s1)) since 'in' keyword is O(1) time
all_chars = dict.fromkeys(set(s2), 1)
for c in s1:
if c in all_chars.keys():
return 'YES'
return 'NO'
def sherlockAndAnagrams(s):
"""
two strings are anagrams of each other if the letters of one string
can be rearranged to form the other string. Given a string, find the
number of pair of substrings of the string that are anagrams of each other
Ex. s = mom => angrammatic pairs : [m, m], [mo, om]
"""
substrings = {}
count = 0
n = len(s)
for i in range(1, n + 1):
for j in range(i):
sub = ''.join(sorted(s[j : i]))
if sub in substrings:
substrings[sub] += 1
else:
substrings[sub] = 0
count += substrings[sub]
return count
def coinChange(n, c):
"""
How many ways can you make change for a particular value n using
m coins of distinct denomination.
Ex. n = 10, c = [2, 5, 3, 6]
=> 5 ways : {2, 2, 2, 2, 2}, {2, 2, 3, 3}, {2, 2, 6}, {2, 3, 5}, {5, 5}
Solution:
# num ways to make change for n units with m coins =
# num ways to make change for n units not using the ith coin +
# num ways to make change for n units using the ith coin
The recursive solution has too many overlapping function calls, so
we use DP to make it more efficient
"""
# naive recursive method (exponential in len(c))
# if n < 0:
# return 0
# elif n == 0:
# return 1
# elif len(c) == 1:
# if n != c[0]:
# return 0
# return 1
# return getWays(n - c[0], c) + getWays(n, c[1:])
# dynamic programming way (quadratic)
m = len(c)
table = [[0 for _ in range(m + 1)] for _ in range(n + 1)]
table[0] = [1] * (m + 1)
for i in range(1, n + 1):
for j in range(m + 1):
if j == 0:
table[i][j] = 0
else:
if i - c[j - 1] < 0:
table[i][j] = table[i][j - 1]
else:
table[i][j] = table[i][j - 1] + table[i - c[j - 1]][j]
return table[n][m]
def weirdFib(t1, t2, n, memo=None):
"""
Given seed values t1, t2, find the nth weird fibonacci number
defined by t_n = t_(n - 2) + (t_(n - 1))^2
"""
# naive recursive
# if n == 1:
# return t1
# elif n == 2:
# return t2
# a = weirdFib(t1, t2, n - 1) ** 2
# b = weirdFib(t1, t2, n - 2)
# return a + b
# dp 1
# if not memo:
# memo = {1 : t1, 2 : t2}
# if n in memo:
# return memo[n]
# if (n - 1) not in memo:
# memo[n - 1] = weirdFib(t1, t2, n - 1, memo)
# if (n - 2) not in memo:
# memo[n - 2] = weirdFib(t1, t2, n - 2, memo)
# memo[n] = memo[n - 1] ** 2 + memo[n - 2]
# return memo[n]
# another dp (tableling)
table = {0 : t1, 1 : t2}
for i in range(2, n):
table[i] = table[i - 1] ** 2 + table[i - 2]
return table[n - 1]
def equal(arr):
"""
Still need to finish this function and add explanation for the code
"""
first = arr[0]
flag = True
for e in arr[1:]:
if e != first:
flag = False
break
if flag:
return 0
s = 0
for i in range(len(arr)):
a = arr[i]
for j in range(i + 1, len(arr)):
b = arr[j]
arr1 = arr[:i] + [a + 1] + arr[i+1:j] + [b + 1] + arr[j + 1:]
arr2 = arr[:i] + [a + 2] + arr[i+1:j] + [b + 2] + arr[j + 1:]
arr5 = arr[:i] + [a + 5] + arr[i+1:j] + [b + 5] + arr[j + 1:]
print(arr1, arr2, arr5)
s += 1 + min(equal(arr1), equal(arr2), equal(arr5))
return s
def maxSubsetSum(arr):
"""
Find the subset of non adjacent elements of given array
which results in the maximum sum, and return the sum
"""
pass
def matchingStrings(strings, queries):
freq = Counter(strings)
print(freq)
count = [0] * len(queries)
for i, q in enumerate(queries):
if q in freq.keys():
count[i] += freq[q]
return count
def minMaxRiddle(arr):
"""
Given an integer array of size n, find the maximum of the minimums of
every window size in the array, with window sizes ranging from 1 to n.
Ex. arr = [6, 3, 5, 1, 12], n = len(arr) = 5
Window size 1: (6), (3), (5), (1), (12) => max = 12
Window size 2: (6, 3), (3, 5), (5, 1), (1, 12) => max = 3
Window size 3: (6, 3, 5), (3, 5, 1), (5, 1, 12) => max = 3
Window size 4: (6, 3, 5, 1), (3, 5, 1, 12) => max = 1
Window size 5: (6, 3, 5, 1, 12) => max = 1
"""
# the most brutal brute force can get, i think cubic time:
# n = len(arr)
# window_maxs = []
# for w in range(1, n + 1):
# window_max = 0
# for i in range(n - w + 1):
# window = arr[i : i + w]
# window_min = min(window)
# if window_min > window_max:
# window_max = window_min
# window_maxs.append(window_max)
# return window_maxs
# little better, quyadratic time
n = len(arr)
mins = [[0 for _ in range(n)] for _ in range(n)]
mins[0] = arr
maxes = [max(mins[0])]
for i in range(1, n):
curr_max = 0
for j in range(n - i):
mins[i][j] = min(mins[i - 1][j], mins[i - 1][j + 1])
if mins[i][j] > curr_max:
curr_max = mins[i][j]
maxes.append(curr_max)
return maxes
def pairs(k, arr):
"""
return number of pairs of numbers in integer array arr
that have a difference of k
"""
# brute force solution:
# pairs = 0
# n = len(arr)
# for i in range(n):
# for j in range(i + 1, n):
# if abs(arr[i] - arr[j]) == k:
# pairs += 1
# return pairs
# efficient solution:
pairs = 0
arr = mergesort(arr)
j = 0
i = 1
while i < len(arr):
diff = arr[i] - arr[j]
if diff > k:
j += 1
elif diff == k:
i += 1
pairs += 1
else:
i += 1
return pairs
def luck_balance(k, contests):
# some hackerrank problem on luck (greedy i think)
# contests is a list of integer tuples and k is some int
# using min heap, quadratic time:
# total_luck = 0
# k_heap = MinHeap()
# for pair in contests:
# if pair[1] == 1:
# k_heap.insert(pair[0])
# k_heap.heapify()
# while len(k_heap.tree) - 1 > k:
# k_heap.delete_min()
# for pair in contests:
# if pair[1] == 0:
# total_luck += pair[0]
# else:
# if pair[0] in k_heap.tree:
# total_luck += pair[0]
# else:
# total_luck -= pair[0]
# return total_luck
# using itemgetter, nlogn + n time
total_luck = 0
contests = sorted(contests, key=itemgetter(0))
for pair in reversed(contests):
luck, importance = pair
if importance == 0:
total_luck += luck
else:
if k > 0:
total_luck += luck
k -= 1
else:
total_luck -= luck
return total_luck
def minimum_swaps(arr):
"""
Given an unordered array of size n with elements in
[1, 2, ..., n] with no duplicates, return the minimum
number of swaps required to go from the unordered array
to an ordered array.
Ex. [7, 1, 3, 2, 4, 5, 6]
=> Swap (0, 3) : [2, 1, 3, 7, 4, 5, 6]
=> Swap (0, 1) : [1, 2, 3, 7, 4, 5, 6]
=> Swap (3, 4) : [1, 2, 3, 4, 7, 5, 6]
=> Swap (4, 5) : [1, 2, 3, 4, 5, 7, 6]
=> Swap (5, 6) : [1, 2, 3, 4, 5, 6, 7]
5 total swaps took place to order the array
"""
# linear time, fastest solution i think
i = 0
n = len(arr)
num_swaps = 0
while i < n:
x = arr[i]
og_index = x - 1
if i != og_index:
swap(arr, i, og_index)
print("Swap:({}, {})".format(i, og_index))
num_swaps += 1
else:
i += 1
return num_swaps
def makeAnagrams(s1, s2):
"""
Given two strings, not necessarilly of equal length,
find minimum number of chars deleted from the strings
to make them anagrams.
Ex. s1 = 'cde', s2 = 'abc' => 4 removals : {'d', 'e', 'a', 'b'}
"""
# f1 = dict(Counter(s1))
# f2 = dict(Counter(s2))
# all_chars = set(list(f1.keys()) + list(f2.keys()))
# count = 0
# for c in all_chars:
# if c in f1 and c not in f2:
# count += f1[c]
# elif c not in f1 and c in f2:
# count += f2[c]
# else:
# if f1[c] != f2[c]:
# count += abs(f1[c] - f2[c])
# return count
# another sol:
all_chars = [0] * 26
for c in s1:
all_chars[ord(c) - ord('a')] += 1
for c in s2:
all_chars[ord(c) - ord('a')] -= 1
count = 0
for i in range(26):
count += abs(all_chars[i])
return count
def alternatingCharacters(s):
"""
Given a string containing only A's and B's, find
minimum number of deletions of characters in the string
such that the final string has no matching adjacent chars.
Ex. AABAAB -> ABAAB -> ABAB => 2 deletions
"""
pass
def sherlockIsValid(s):
"""
A string s is considered valid iff all the chars in s appear
the same number of times or it is possible to remove one char
at one index in s and then all the chars appear the same number
of times.
Ex. s = 'abc' => {a : 1, b : 1, c : 1} => s is valid
"""
freq = {}
for c in s:
if c in freq:
freq[c] += 1
else:
freq[c] = 1
m = min(freq.values())
M = max(freq.values())
# all chars appear the same amount of times
if m == M:
return 'YES'
else:
num_min = num_max = 0
for c in freq:
if freq[c] == m:
num_min += 1
elif freq[c] == M:
num_max += 1
else:
return 'NO'
if num_max == 1 and M - m == 1:
return 'YES'
elif num_min == 1 and m == 1:
return 'YES'
return 'NO'
def specialPalindromeSubstrings(n, s):
"""
String is said to be special palindromic if either of 2 conditions
are met:
1) all characters in string are the same
2) all characters except the middle one are the same
a special palindromic substring is any substring that is
a special palindromic string. Return total number
of special palindromic strings in string s of length n
"""
# brute force: cubic
# count = 0
# subs = []
# def check_all_and_middle(s):
# if len(s) % 2 == 0:
# c = s[0]
# for cc in s[1:]:
# if c != cc:
# return False
# return True
# else:
# c = s[0]
# mid = (len(s) - 1) // 2
# for i in range(len(s)):
# if i != mid and c != s[i]:
# return False
# return True
# for num_chars in range(1, n + 1):
# for i in range(n - num_chars + 1):
# flag = True
# substring = s[i : i + num_chars]
# if check_all_and_middle(substring):
# count += 1
# subs.append(substring)
# print(subs)
# return count
# better solution:
pass
def twoSum(nums, target):
"""
given a list of numbers, return the indices of the
numbers(distinct) that sum to target value
"""
# brute force (quadratic)
# for i in range(len(nums)):
# for j in range(i + 1, len(nums)):
# if nums[i] + nums[j] == target:
# return [i, j]
# return None
# not brute force: (nlogn + n)
# num_tups = [(nums[i], i) for i in range(len(nums))]
# num_tups = sorted(num_tups, key= lambda x : x[0])
# low = 0
# high = len(num_tups) - 1
# while low < high:
# s = num_tups[low][0] + num_tups[high][0]
# if s < target:
# low += 1
# elif s > target:
# high -= 1
# else:
# return [num_tups[low][1], num_tups[high][1]]
# return None
# better not brute force (linear)
indices = {nums[i] : i for i in range(len(nums))}
for i, nums in enumerate(nums):
diff = target - nums
if diff in indices:
if i != indices[diff]:
return [i, indices[diff]]
return None
def whatFlavors(cost, money):
"""
given amount of money you have, and the cost of flavours
of ice cream, return ID's of flavours.
Ex. money = 5, cost = [2, 1, 3, 5, 6]
=> ID's 1 and 3 : 2 + 3 = 5
"""
# quadratic
ids = {}
for i, c in enumerate(cost):
if c in ids:
ids[c].append(i + 1)
else:
ids[c] = [i + 1]
print(ids)
for i, c in enumerate(cost):
diff = money - c
if diff in ids:
index = 0
for j in ids[diff]:
if j != i + 1:
index = j
return (i + 1, index) if (i + 1) < index else (index, i + 1)
return None
def triplets(a, b, c):
"""
Gievn arrays a, b, c, find all triplets (p, q, r) with
p in a, q in b, r in c and p <= q and r <= q.
"""
# using multiplication principle of disjoint events (quadratic)
num_trips = 0
a.sort()
b.sort()
c.sort()
qs = OrderedDict()
for q in b:
if q not in qs:
qs[q] = True
index_a = index_c = 0
for q in qs:
while index_a < len(a):
if a[index_a] <= q:
index_a += 1
else:
break
while index_c < len(c):
if c[index_c] <= q:
index_c += 1
else:
break
num_trips += index_a * index_c
return num_trips
def reverseLinkedList(linky):
"""
Reverse a singly linked linked list
"""
# way numero uno: (iterative)
# nodes = []
# curr = linky.head
# while curr:
# nodes.append(curr.data)
# curr = curr.next
# rev_linky = LinkedList(nodes.pop())
# curr = rev_linky.head
# while nodes:
# curr.next = Node(nodes.pop())
# curr = curr.next
# return rev_linky
# lmao reverse linked list in place
curr_node = linky.head
prev_node = None
while curr_node:
next_node = curr_node.next
curr_node.next = prev_node
prev_node = curr_node
curr_node = next_node
rev_linky = LinkedList(None, node=prev_node)
return rev_linky
def lowestCommonAncestor(root, u, v):
"""
Find the lowest common ancestor to nodes u and v in bst
with root node at root
"""
if u == root.data or v == root.data:
return root
elif u < root.data and v < root.data:
return lowestCommonAncestor(root.left, u, v)
elif u > root.data and v > root.data:
return lowestCommonAncestor(root.right, u, v)
else:
return root
return None
def shortestReach(n, m, edges, s):
"""
Given an undirected graph with same edge weights (each edge has a weight of 6),
and each of the nodes are labelled consecutively. Given a starting node,
find the shortest distance to each of the other nodes from it.
Ex. n = 5, m = 3, edges = {[1, 2], [1, 3], [3, 4]}, s = 1
=> distances from node s = 1 to nodes 2, 3, 4, 5: [1, 1, 2, -1]
"""
nodes = [i for i in range(1, n + 1)]
graph = AdjacencyList(nodes, edges).graph
visited = {i : False for i in range(1, n + 1)}
distances = {i : -1 for i in range(1, n + 1)}
print(graph)
root_level = [s]
q = [root_level]
curr_dist = 0
while q:
print(visited)
level = q[0]
del q[0]
next_level = []
for node in level:
if not visited[node]:
next_level += graph[node]
visited[node] = True
distances[node] = curr_dist
if next_level:
q.append(next_level)
curr_dist += 6
dists = list(distances.values())
return dists[:s - 1] + dists[s : ]
def shortestReachPartTwo(n, edges, s):
"""
Given an undirected graph with non negative edge weights
and each of the nodes are labelled consecutively, find the length
of the shortest paths from a source node to all other nodes. Assign
-1 to any unreachable nodes.
Ex. n = 5, edges = [[1, 2, 5], [2, 3, 6], [3, 4, 2], [1, 3, 15]], s = 1
=> distances = [1 -> 2 : 5, 1 -> 3 : 11, 1 -> 4 : 13, 1 -> 5 : -1]
"""
nodes = [i for i in range(1, n + 1)]
q = [v for v in nodes]
visited = {v : False for v in nodes}
weights = {(e[0], e[1]) : e[2] for e in edges}
for edge in edges:
if (edge[1], edge[0]) not in weights:
weights[(edge[1], edge[0])] = weights[(edge[0], edge[1])]
graph = AdjacencyList(nodes, list(weights.keys())).graph
distances = {v : float('inf') for v in nodes}
distances[s] = 0
while q:
v = q[0]
del q[0]
if not visited[v]:
visited[v] = True
for u in graph[v]:
if distances[v] + weights[(v, u)] < distances[u]:
distances[u] = distances[v] + weights[(v, u)]
for v in distances:
if distances[v] == float('inf'):
distances[v] = -1
distances = list(distances.values())
return distances[:s - 1] + distances[s:]
pass
def smalllestRectangles(points):
"""
Given a list of 2D points, find the collection of 4 points
that result in the rectangle of smallest area in the grid
"""
pass
|
6461becb3ef2198b34feba0797459c22ec886e4c | OrSGar/Learning-Python | /FileIO/FileIO.py | 2,953 | 4.40625 | 4 | # Exercise 95
# In colts solution, he first read the contents of the first file with a with
# He the used another with and wrote to the new file
def copy(file1, file2):
"""
Copy contents of one file to another
:param file1: Path of file to be copied
:param file2: Path of destination file
"""
destination = open(file2, "w")
with open(file1, "r") as source:
destination.write(source.read())
destination.close()
# Exercise 96
# In Colts code, he didnt save the reverse - He just reversed it when we passed it in
def copy_and_reverse(file1, file2):
"""
Copy contents of a file to another in reverse
:param file1: Path of file ot be copied
:param file2: Path of destination file
"""
with open(file1, "r") as source:
data = source.read()
with open(file2, "w") as destination:
reverse_data = data[::-1]
destination.write(reverse_data)
# Exercise 97
def statistics_2(file):
"""
Print number of lines, words, and characters in a file
:param file: Path of file
"""
with open(file) as source:
lines = source.readlines()
return {"lines": len(lines),
"words": sum(len(line.split(" ")) for line in lines),
# Split every line on a space and count how many elements there are
"characters": sum(len(line) for line in lines)} # Count number of chars in each line
def statistics(file):
""" My original version of statistics_2 """
num_lines = 0
num_char = 0
num_words = 1
with open(file) as source:
line = source.readlines()
num_lines = len(line)
source.seek(0)
data = source.read()
num_char = len(data)
for char in data:
if char == " ":
num_words += 1
return {"lines": num_lines, "words": num_words, "characters": num_char}
# Exercise 98
# In Colts implementation, he just read the whole thing and replaced it
def find_and_replace(file, target, replacement):
"""
Find and replace a target word in a file
:param file: Path to the file
:param target: Word to be replaced
:param replacement: Replacement word
"""
with open(file, "r+") as source:
for line in source:
print(line)
if line == "":
break
elif line.replace(target, replacement) != line:
source.write(line.replace(target, replacement))
def f_n_r(file, target, replacement):
""" Another version of find_and_replace """
with open(file, "r+") as source:
text = file.read()
new_text = text.replace(target, replacement)
file.seek(0)
file.write(new_text)
file.truncate() # Delete everything after a certain position
find_and_replace("fileio.txt", "Orlando", "Ligma")
copy("fileio.txt", "fileio_copy.txt")
copy_and_reverse("fileio.txt", "fileio_copy.txt")
print(statistics_2("fileio.txt"))
|
48918109e3172f1dd5dfbd4bdc45fac38a5be7d8 | Aasthaengg/IBMdataset | /Python_codes/p04011/s047238137.py | 122 | 3.734375 | 4 | a = int(input())
b = int(input())
c = int(input())
d = int(input())
if a<= b:
print(a*c)
else:
print(c*b +(a-b)*d) |
180fb10c4fd193dbcd5b390d43061c1c2addf494 | srmchem/python-samples | /Python-code-snippets-201-300/216-Base64 encode and decode.py | 804 | 3.640625 | 4 | """Code snippets vol-44-snip-216
Base64 encode and decode a file.
By Steve Shambles
Feb 2020
stevepython.wordpress.com
Download all snippets so far:
https://wp.me/Pa5TU8-1yg
Requirements:
A text file called test.txt in current directory.
Base64 is part of the standard library.
"""
import base64
with open('test.txt', 'rb') as f:
encoded_str = base64.b64encode(f.read())
print('-' *79)
print('test.txt file encoded as:')
print('-' *79)
print(encoded_str)
print('-' *79)
with open('test-enc64.txt', 'wb') as f:
f.write(encoded_str)
with open('test-enc64.txt', 'rb') as f:
decoded_str = base64.b64decode(f.read())
print('test.txt file decoded back again:')
print('-' *79)
print(decoded_str)
with open('test-decoded.txt', 'wb') as f:
f.write(decoded_str)
|
50c7142cd513045f7dd6014b2df48fbbee3226b4 | SinghGauravKumar/Project-Euler-Python-Solutions | /euler_problem_092.py | 507 | 3.6875 | 4 |
import sys
if sys.version_info.major == 2:
range = xrange
def compute():
ans = 0
terminals = (1, 89)
for i in range(1, 10000000):
while i not in terminals:
i = square_digit_sum(i)
if i == 89:
ans += 1
return str(ans)
def square_digit_sum(n):
result = 0
while n > 0:
result += SQUARE_DIGITS_SUM[n % 1000]
n //= 1000
return result
SQUARE_DIGITS_SUM = [sum(int(c)**2 for c in str(i)) for i in range(1000)]
if __name__ == "__main__":
print(compute())
|
108fa1ed16d993bcec202d8923fc1a15afcf0ef1 | guoyuMao/python_study | /Function.py | 1,408 | 4.03125 | 4 | # def area(width,heigh):
# return heigh * width
#
# print("please input width:")
# w = int(input())
# print("please input height:")
# h = int(input())
# print("this area is : %d" %area(w,h))
'''不可变对象与可变对象'''
#不可变对象
# def changeInt(a):
# a = 10
# b = 2
# changeInt(b)
# print(b)
# #可变对象
# def changeme(list):
# list.append(['q','w',3,4])
# print("函数内部值:",list)
# # return
# mylist = [10,2,53]
# changeme(mylist)
# print("函数外不值:",mylist)
#
# def printinfo(arg,*vartuple):
# print("输出:")
# print(arg)
# for var in vartuple:
# print(var)
# return
#
# printinfo(10)
# printinfo(70,4,2,23,12)
# sum = lambda arg1,arg2,arg3:arg1 + arg2
# print(sum(2,34,5))
# print(sum(52,12,43))
# total = 0
# def sum(arg1,arg2):
# total = arg1+ arg2
# print("函数内饰局部变量:",total)
# return total
#
# sum(10,20)
# print("函数外是全局变量:",total)
# 当内部作用域想修改外部作用域的变量时,就要用到global和nonlocal关键字了。
# num = 1
# def fun1():
# global num #指定num是全部作用于的变量
# print(num)
# num = 123
# print(num)
# fun1()
# print(num)
# def outer():
# num = 10
# def inner():
# nonlocal num
# num = 100
# print(num)
# print(num)
# inner()
# print(num)
# outer()
|
3048d4dcc2111ea420cdf6d6ab6df488a9060eb6 | Rafaellinos/learning_python | /projects/email/email_test.py | 907 | 3.578125 | 4 | import smtplib
# smtp = simple mail transfer protocol
from email.message import EmailMessage
from string import Template # uses to substitute the $ in html file
from pathlib import Path # os.path
html = Template(Path('email.html').read_text())
print(html)
with open("mail_inform.txt", "r") as f:
user = f.readline() # get your email information
pwd = f.readline()
email = EmailMessage() # intanciate the email obj
email['from'] = 'LLIÈGE Suporte'
email['to'] = 'rafael.veloso.lino@hotmail.com'
email['subject'] = 'You won 1,000,000 dollars!'
email.set_content(html.substitute(name='TinTin'), 'html')
"""
html.substitute > get the $name from html and substitute for TinTin
"""
with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:
smtp.ehlo() # part of the protocol, like handshake
smtp.starttls() # encryption connection
smtp.login(user, pwd)
smtp.send_message(email)
print("all good")
|
043ffadcf4968b4e2c6612c9c46216bed3dccdfb | wangzhaozhao1028/Only-Al | /python_Matplotlib/Figure_1.py | 799 | 3.53125 | 4 | #coding=utf-8
import matplotlib.pyplot as plt
import numpy as np
"""
数据可视话 教程
http://study.163.com/course/courseLearn.htm?courseId=1003240004#/learn/video?lessonId=1003683066&courseId=1003240004
设置坐标轴
"""
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
# plt.figure()
# plt.plot(x,y1)
plt.figure(num=3,figsize=(8,5))
plt.plot(x,y2)
#linewidth 粗度, linestyle虚线
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
#取值范围
plt.xlim((-1,2))
plt.ylim((-2,3))
#x,y 描述
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1,2,5)
# print(new_ticks)
plt.xticks(new_ticks)
#r 和$ 为了字体好看 阿尔法 表示 \alpha
plt.yticks([-2,-1.8,-1,1.22,3,],
[r'$really\ bad$',r'$bad\ \alpha$',r'$normal$',r'$good$',r'$really\ good$'])
plt.show() |
40eb6136b39079f56f57f47ba86c5fc48ceed7eb | jmak24/CS50-2017 | /pset6/credit.py | 2,608 | 4.21875 | 4 | import cs50
# Initialize variables
digit_shifter = 10
even_digit_sum = 0
odd_digit_sum = 0
total_sum = 0
last_digit = 0
first_digit_is_even = False
even_final_digit = 0
odd_final_digit = 0
# Prompt user for Credit card Number
print("Number:", end="")
credit = cs50.get_float()
# Initialize digit shifter
i = 0
while (credit/digit_shifter) > 9:
# A multipler of 10 that shifts the position of the digits
digit_shifter = pow(10, i)
# Get the last digit (which is the remainder of credit/10 after shifting the value
last_digit = int(credit/digit_shifter) % 10
# Check the placement of the digit and perform task accordingly
# If placement of digit is Even
if i % 2 != 0:
# We must now check if (last_digit * 2) yeilds double digits
# If it is double digits, retrieve the sum of those 2 digits (The first digit is always 1)
if (last_digit * 2) > 9:
sum_dd = ((last_digit * 2) % 10) + 1
# Add the sum of the double digits to the total even_digit_sum
even_digit_sum += sum_dd
else:
# Add the last_digit to the total even_digit_sum
even_digit_sum += last_digit * 2
# Set first digit to be even as true
first_digit_is_even = True
# Keep storing most recent even last digit
even_final_digit = last_digit
# Else if placement of digit is Odd
else:
# Add the last_digit to the total even_digit_sum
odd_digit_sum += last_digit
# Set final digit to be odd as false
first_digit_is_even = False
# Keep storing most recent odd last digit
odd_final_digit = last_digit
# Iterate the digit_shifter
i += 1
# Get the first 2 digits by combining the final odd and even digits
if first_digit_is_even:
first_2_digits = (even_final_digit * 10) + odd_final_digit
else:
first_2_digits = (odd_final_digit * 10) + even_final_digit
# Store the card legnth into a variable
card_length = i
# Get the total sum
total_sum = even_digit_sum + odd_digit_sum
# Validate Check Sum
if (total_sum != 0) and (total_sum % 10 == 0):
# Validate Credit card vendor criteria (First 2 digits and Card Length)
if (first_2_digits == 34 or first_2_digits == 37) and (card_length == 15):
print("AMEX")
elif (first_2_digits >= 51 and first_2_digits <= 55) and (card_length == 16):
print("MASTERCARD")
elif (first_2_digits >= 40 and first_2_digits <= 49) and (card_length == 13 or card_length == 16):
print("VISA")
else:
print("INVALID")
|
f79c479f3863f4e14fa164dd18f862c012eae6fb | menghaoshen/python | /99.练习题/hello.py | 154 | 3.921875 | 4 | i='hello world'
print(i)
#利用循环依次对应list中的每个名字打印出hello,xxx
L = ['bart','Lisa','Adam']
for i in L:
print('hello',i)
|
cc9793102b4f0f9c6088622de6dd4a6a557d1a89 | sgriffin10/ProblemSolving | /Classwork/Sessions 1-10/Session 6/conditional-demo.py | 1,225 | 4.09375 | 4 | # 1.0
# age = int(input("Please enter ur age: "))
# print(f"Your age is {age}.")
# if age>=18:
# print(f'Your age is {age}.')
# print("You are an adult.")
# elif age>= 10:
# print("You are a teenager.")
# else:
# print("yung boi")
#2.0
# age = 20
# if age >= 6:
# print('teenager')
# elif age >= 18:
# print('adult')
# else:
# print('kid')
# 3.0
# if x == y:
# print('x and y are equal')
# else:
# if x < y:
# print('x is less than y')
# else:
# print('x is greater than y')
# def compare(a, b):
# if isinstance(a, str) or isinstance(b, str):
# print("string involved")
# else:
# if a > b:
# print("Bigger")
# if a == b:
# print("Equal")
# if a < b:
# print("Smaller")
# a = "hello"
# b = 3
# c = 5
# compare(a, b)
# # compare(b, c)
# def diff21(n):
# if n<=21:
# return abs(n - 21)
# else:
# return abs(n - 21) * 2
# print(diff21(19))
# print(diff21(10))
# print(diff21(21))
# def countdown(n):
# # import time
# # time.sleep(1)
# if n<=0:
# print("blastoff")
# else:
# print(n)
# countdown(n-1)
# countdown(1000)
|
2f721ea00749373444d7a40a36e57ec4bad83e0a | a01375832/Actividad_06 | /actividad06_1.py | 1,526 | 3.9375 | 4 | #Encoding: UTF-8
#Autor: Manuel Zavala Gmez
#Actividad 6
def encontrarMayor(num,lista):
print("El numero ms alto es: ", max(lista))
def recolectarInsectos(dia,insectos,acumlador):
while acumlador<30:
insectos=int(input("Numero de insectos recolectados de hoy"))
if insectos<=30:
dia=dia+1
acumlador=insectos+acumlador
oper=30-acumlador
print("Despues %.0f da(s)de recoleccion has recolectado %.0f insectos"%(dia,acumlador))
print("Te hace falta recolectar %.0f insectos"% oper)
elif acumlador==30:
print("Felicidades, has llegado a la meta")
elif insectos==30:
print("Felicidades, has llegado a la meta")
def main():
opcion=int(input("1.Encontrar Mayor\n2.Recolectar insectos \n3.Salir"))
while opcion!=3:
if opcion==1:
lista=[]
num=int(input("Teclea tu nmero"))
while num!=-1:
print(num)
num=int(input("Teclea otro número"))
lista.append(num)
encontrarMayor(num,lista)
elif opcion==2:
dia=0
acumlador=0
insectos=0
recolectarInsectos(dia,insectos,acumlador)
else:
print("Opcion incorrecta, intenta nuevamente")
opcion=int(input("1.Encontrar Mayor\n2.Recolectar insectos \n3.Salir"))
main() |
52887cedfd203834bd9da717ed73144bbbdfeb16 | HorusDjer/gitty | /find_unique_int.py | 466 | 3.609375 | 4 |
# fast attempt O(N)
def find_uniq(arr):
counts = {}
for num in arr:
if num in counts:
counts[num] += 1
else:
counts[num] = 1
for num in arr:
if counts[num] == 1:
return num
# bad attempt O(n^2)
def find_uniq_(arr):
for num in arr:
if arr.count(num):
return num
def find_unique(arr):
s = set(arr)
for e in s:
if arr.count(e) == 1:
return e |
640cc2582708584403f166c48d37c962df807b66 | daniel-reich/ubiquitous-fiesta | /pn7QpvW2fW9grvYYE_21.py | 308 | 3.671875 | 4 |
def find_fulcrum(lst):
for i in range(len(lst)):
sum_left = 0
sum_right = 0
for j in range(0, i):
sum_left += lst[j]
for j in range(i+1, len(lst)):
sum_right += lst[j]
if sum_left == sum_right:
return lst[i]
return -1
|
ce9ec1bcf55a61474cc31f04c8b32d2dbcf5d57d | SierraSike20/SuvatSorter | /suvat.py | 9,070 | 3.90625 | 4 | def one(v, u, a, t):
print(str(v + " = " + u + " + " + a + " * " + t))
def two(s, u, v, t):
print(str(s + " = " + " ( " + u + " + " + v + " ) " + " * " + " 1/2 " + " * " + t))
def three(v, u, a, s):
print(str(v + "^2 " + " = " + u + "^2 " + " + " + " 2 " + "*" + a + " * " + s))
def four(s, u, t, a):
print(str(s + " = " + u + " * " + t + " + " + a + " * " + t + "^2 " + "*" + " 1/2 "))
def five(s, v, t, a):
print(str(s + " = " + v + " * " + t + " - " + a + " * " + t + "^2 " + " * " + " 1/2 "))
print("SUVAT Calculator, assuming constant acceleration\n"
"a - acceleration\n"
"v - final velocity\n"
"u - initial velocity\n"
"s - displacement\n"
"t - time\n")
# 1 v = u + at
# 2 s = 1/2(u + v)t
# 3 v^2 = u^2 + 2as
# 4 s = ut + at^2 / 2
# 5 s = vt - at^2 / 2
goal = str(input("What are you trying to find?\n"))
while goal.strip().lower() != "s" \
and goal.strip().lower() != "a" \
and goal.strip().lower() != "t" \
and goal.strip().lower() != "v" \
and goal.strip().lower() != "u":
goal = str(input("Enter a valid input\nWhat are you trying to find?\n"))
#-----------------------------------------------------------------------------------------------------------------------
print("if you do not know the value, put none")
if goal.strip().lower() == "s":
a = str(input("What is the value of your acceleration?\n"))
t = str(input("What is the time period?\n"))
v = str(input("What is the final velocity?\n"))
u = str(input("What is the initial velocity?\n"))
s = "s"
if a == "none":
#take 2
two(s, u, v, t)
t = float(t)
v = float(v)
u = float(u)
s = ((u + v) * 0.5) * t
print("\n The displacement is: " + str(s) + "m")
elif t == "none":
#take 3
three(v, u, a, s)
a = float(a)
v = float(v)
u = float(u)
s = (((v**2) - u**2) / 2) / a
print("\n The displacement is: " + str(s) + "m")
elif v == "none":
#take 4
four(s, u, t, a)
a = float(a)
t = float(t)
u = float(u)
s = (u * t) + ((a * (t**2)) / 2)
print("\n The displacement is: " + str(s) + "m")
elif u == "none":
#take 5
five(s, v, t, a)
a = float(a)
t = float(t)
v = float(v)
s = (v * t) - ((a * (t**2)) / 2)
print("\n The displacement is: " + str(s) + "m")
else:
print("=======================================\n"
"You entered too few or too many values.\n"
"=======================================")
#-----------------------------------------------------------------------------------------------------------------------
if goal.strip().lower() == "a":
s = str(input("What is the value of the displacement?\n"))
t = str(input("What is the time period?\n"))
v = str(input("What is the final velocity?\n"))
u = str(input("What is the initial velocity?\n"))
a = "a"
if s == "none":
#take 1
one(v, u, a, t)
t = float(t)
v = float(v)
u = float(u)
a = (v - u) / t
print("\nThe acceleration is: " + str(a) + "m/s^2")
elif t == "none":
#take 3
three(v, u, a, s)
s = float(s)
v = float(v)
u = float(u)
a = ((v**2 - u**2) / 2) / a
print("\nThe acceleration is: " + str(a) + "m/s^2")
elif v == "none":
#take 4
four(s, u, t, a)
s = float(s)
t = float(t)
u = float(u)
a = ((s - (u * t)) * 2) / t**2
print("\nThe acceleration is: " + str(a) + "m/s^2")
elif u == "none":
#take 5
five(s, v, t, a)
s = float(s)
t = float(t)
v = float(v)
a = ((s - (v * t)) * -2) / t**2
print("\nThe acceleration is: " + str(a) + "m/s^2")
else:
print("=======================================\n"
"You entered too few or too many values.\n"
"=======================================")
#-----------------------------------------------------------------------------------------------------------------------
if goal.strip().lower() == "t":
s = str(input("What is the value of the displacement?\n"))
a = str(input("What is the value of your acceleration?\n"))
v = str(input("What is the final velocity?\n"))
u = str(input("What is the initial velocity?\n"))
t = "t"
if s == "none":
#take 1
one(v, u, a, t)
a = float(a)
v = float(v)
u = float(u)
t = (v - u) / a
print("\nThe time is: " + str(t) + "s")
elif a == "none":
#take 2
two(s, u, v, t)
s = float(s)
v = float(v)
u = float(u)
t = ((s * 2) / (u + v))
print("\nThe time is: " + str(t) + "s")
elif v == "none":
#take 4
four(s, u, t, a)
s = float(s)
a = float(a)
u = float(u)
if u == 0:
t = (s / (0.5 * a))**0.5
print("\nThe time is: " + str(t) + "s")
else:
print("\nYour equation is quadratic.")
elif u == "none":
#take 5
five(s, v, t, a)
s = float(s)
a = float(a)
v = float(v)
if v == 0:
t = (s / (-0.5 * a))**0.5
print("\nThe time is: " + str(t) + "s")
else:
print("\nYour equation is a quadratic.")
else:
print("=======================================\n"
"You entered too few or too many values.\n"
"=======================================")
#-----------------------------------------------------------------------------------------------------------------------
if goal.strip().lower() == "v":
s = str(input("What is the value of the displacement?\n"))
a = str(input("What is the value of your acceleration?\n"))
t = str(input("What is the time period?\n"))
u = str(input("What is the initial velocity?\n"))
v = "v"
if s == "none":
#take 1
one(v, u, a, t)
a = float(a)
t = float(t)
u = float(u)
v = u + (a * t)
print("\nThe final velocity is: " + str(v) + "m/s")
elif a == "none":
#take 2
two(s, u, v, t)
s = float(s)
t = float(t)
u = float(u)
v = ((s / t) * 2) - u
print("\nThe final velocity is: " + str(v) + "m/s")
elif t == "none":
#take 3
three(v, u, a, s)
s = float(s)
a = float(a)
u = float(u)
v = ((u**2) + (2 * a * s))**0.5
print("\nThe final velocity is: " + str(v) + "m/s")
elif u == "none":
#take 5
five(s, v, t, a)
s = float(s)
a = float(a)
t = float(t)
v = (s + (0.5 * a * t**2)) / t
print("\nThe final velocity is: " + str(v) + "m/s")
else:
print("=======================================\n"
"You entered too few or too many values.\n"
"=======================================")
#-----------------------------------------------------------------------------------------------------------------------
if goal.strip().lower() == "u":
s = str(input("What is the value of the displacement?\n"))
a = str(input("What is the value of your acceleration?\n"))
t = str(input("What is the time period?\n"))
v = str(input("What is the final velocity?\n"))
u = "u"
if s == "none":
#take 1
one(v, u, a, t)
a = float(a)
t = float(t)
v = float(v)
u = v - (a * t)
print("\nThe initial velocity is: " + str(u) + "m/s")
elif a == "none":
#take 2
two(s, u, v, t)
s = float(s)
t = float(t)
v = float(v)
u = ((s / t) * 2) - v
print("\nThe initial velocity is: " + str(u) + "m/s")
elif t == "none":
#take 3
three(v, u, a, s)
s = float(s)
a = float(a)
v = float(v)
u = ((v**2) - (2 * a * s))**0.5
print("\nThe initial velocity is: " + str(u) + "m/s")
elif v == "none":
#take 4
four(s, u, t, a)
s = float(s)
a = float(a)
t = float(t)
u = (s - (0.5 * a * t**2)) / t
print("\nThe initial velocity is: " + str(u) + "m/s")
else:
print("=======================================\n"
"You entered too few or too many values.\n"
"=======================================") |
84f2d8cf92d946aedba18b21ae6bc00e49018e30 | tymscar/Advent-Of-Code | /2020/Python/day10/part1.py | 511 | 3.671875 | 4 | def part_1():
file = open('input.txt', 'r')
jolts = [0]
highest = 0
one_jumps = 0
three_jumps = 0
for line in file:
line = line.strip("\n")
jolts.append(int(line))
highest = max(highest, int(line))
jolts.append(highest + 3)
jolts = sorted(jolts)
for i in range(len(jolts)-1):
if jolts[i+1] - jolts[i] == 1:
one_jumps += 1
else:
three_jumps += 1
return one_jumps * three_jumps
print(part_1()) |
d4a08e2ce6357d3904c0bf269f6b918526f6849d | afcarl/notebooks-1 | /dataset_specific/housing/preprocess.py | 8,027 | 3.515625 | 4 | import math
import pandas as pd
def combine_categories(df, col1, col2, name):
"""Combine categories if a row can have multiple categories of a certain type."""
# Find unique categories
uniques = set(pd.unique(df[col1])) | set(pd.unique(df[col2]))
# Merge different columns
all_dummies = pd.get_dummies(df[[col1, col2]], dummy_na=True)
for condition in uniques:
if type(condition) == float and math.isnan(condition):
continue
c1 = col1 + '_' + condition
c2 = col2 + '_' + condition
c_combined = name + condition
if c1 in all_dummies and c2 in all_dummies:
df[c_combined] = all_dummies[c1] | all_dummies[c2]
elif c1 in all_dummies:
df[c_combined] = all_dummies[c1]
elif c2 in all_dummies:
df[c_combined] = all_dummies[c2]
del df[col1]
del df[col2]
def preprocess(df, columns_needed=None):
if columns_needed is None:
columns_needed = []
### MSSubClass is integer but should be categorical (integer values don't have meaning)
df['MSSubClass'] = df['MSSubClass'].astype('int').astype('category')
# Alley has NaN variable that actually have meaning
df['Alley'].fillna('NoAlley', inplace=True)
assert df['Alley'].notnull().all()
# LotShape is an ordinal variable
assert df['LotShape'].notnull().all()
df['LotShape'].replace({'Reg': 0, 'IR1': 1, 'IR2': 2, 'IR3': 3}, inplace=True)
# Utilities is complex categorical
df['Utilities_Electricity'] = df['Utilities'].apply(
lambda x: 1 if x in ['ELO', 'NoSeWa', 'NoSewr', 'AllPub'] else 0)
df['Utilities_Gas'] = df['Utilities'].apply(
lambda x: 1 if x in ['NoSeWa', 'NoSewr', 'AllPub'] else 0)
df['Utilities_Water'] = df['Utilities'].apply(
lambda x: 1 if x in ['NoSewr', 'AllPub'] else 0)
df['Utilities_SepticTank'] = df['Utilities'].apply(
lambda x: 1 if x in ['AllPub'] else 0)
del df['Utilities']
# LandSlope is ordinal
assert df['LandSlope'].notnull().all()
df['LandSlope'].replace({'Gtl': 0, 'Mod': 1, 'Sev': 2}, inplace=True)
# Neighborhood is a categorical
assert df['Neighborhood'].notnull().all()
df['Neighborhood'] = df['Neighborhood'].astype('category')
# Condition1 and Condition2 are similar categoricals
combine_categories(df, 'Condition1', 'Condition2', 'Condition')
# Exterior1st and Exterior2nd are similar categoricals
combine_categories(df, 'Exterior1st', 'Exterior2nd', 'Exterior')
# ExterQual is an ordinal variable
df['ExterQual'].fillna(-1, inplace=True)
assert df['ExterQual'].notnull().all()
df['ExterQual'].replace({'Po': 0, 'Fa': 1, 'TA': 2, 'Gd': 3, 'Ex': 4}, inplace=True)
# ExterCond is an ordinal variable
df['ExterCond'].fillna(-1, inplace=True)
assert df['ExterCond'].notnull().all()
df['ExterCond'].replace({'Po': 0, 'Fa': 1, 'TA': 2, 'Gd': 3, 'Ex': 4}, inplace=True)
# BsmtQual is an ordinal variable
df['BsmtQual'].fillna('NA', inplace=True)
assert df['BsmtQual'].notnull().all()
df['BsmtQual'].replace({'NA':0 , 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}, inplace=True)
# BsmtCond is an ordinal variable
df['BsmtCond'].fillna('NA', inplace=True)
assert df['BsmtCond'].notnull().all()
df['BsmtCond'].replace({'NA':0 , 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}, inplace=True)
# BsmtExposure is an ordinal variable
df['BsmtExposure'].fillna('NA', inplace=True)
assert df['BsmtExposure'].notnull().all()
df['BsmtExposure'].replace({'NA':0 , 'No': 1, 'Mn': 2, 'Av': 3, 'Gd': 4}, inplace=True)
# BsmtFinType1 is an ordinal variable
df['BsmtFinType1'].fillna('NA', inplace=True)
assert df['BsmtFinType1'].notnull().all()
df['BsmtFinType1'].replace({'NA':0 , 'Unf': 1, 'LwQ': 2, 'Rec': 3, 'BLQ': 4, 'ALQ': 5, 'GLQ':6}, inplace=True)
# BsmtFinType2 is an ordinal variable
df['BsmtFinType2'].fillna('NA', inplace=True)
assert df['BsmtFinType2'].notnull().all()
df['BsmtFinType2'].replace({'NA':0 , 'Unf': 1, 'LwQ': 2, 'Rec': 3, 'BLQ': 4, 'ALQ': 5, 'GLQ':6}, inplace=True)
# HeatingQC is an ordinal variable
df['HeatingQC'].fillna(-1, inplace=True)
assert df['HeatingQC'].notnull().all()
df['HeatingQC'].replace({'Po': 0, 'Fa': 1, 'TA': 2, 'Gd': 3, 'Ex': 4}, inplace=True)
# CentralAir is a binary variable
df['CentralAir'].fillna(-1, inplace=True)
assert df['CentralAir'].notnull().all()
df['CentralAir'].replace({'N': 0, 'Y': 1}, inplace=True)
# KitchenQual is an ordinal variable
df['KitchenQual'].fillna(-1, inplace=True)
assert df['KitchenQual'].notnull().all()
df['KitchenQual'].replace({'Po': 0, 'Fa': 1, 'TA': 2, 'Gd': 3, 'Ex': 4}, inplace=True)
# Functional is an ordinal variable
df['Functional'].fillna(-1, inplace=True)
assert df['Functional'].notnull().all()
df['Functional'].replace(
{'Sal': 0, 'Sev': 1, 'Maj2': 2, 'Maj1': 3, 'Mod': 4, 'Min2': 5, 'Min1': 6, 'Typ': 7}, inplace=True)
# FireplaceQu is an ordinal variable
df['FireplaceQu'].fillna('NA', inplace=True)
assert df['FireplaceQu'].notnull().all()
df['FireplaceQu'].replace({'NA':0 , 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}, inplace=True)
# GarageFinish is an ordinal variable
df['GarageFinish'].fillna('NA', inplace=True)
assert df['GarageFinish'].notnull().all()
df['GarageFinish'].replace({'NA': 0, 'Unf': 1, 'RFn': 2, 'Fin': 3}, inplace=True)
# FireplaceQu is an ordinal variable
df['GarageQual'].fillna('NA', inplace=True)
assert df['GarageQual'].notnull().all()
df['GarageQual'].replace({'NA':0 , 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}, inplace=True)
# GarageCond is an ordinal variable
df['GarageCond'].fillna('NA', inplace=True)
assert df['GarageCond'].notnull().all()
df['GarageCond'].replace({'NA':0 , 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}, inplace=True)
# CentralAir is an ordinal variable
df['PavedDrive'].fillna(-1, inplace=True)
assert df['PavedDrive'].notnull().all()
df['PavedDrive'].replace({'N': 0, 'P': 1, 'Y': 2}, inplace=True)
# PoolQC is an ordinal variable
df['PoolQC'].fillna('NA', inplace=True)
assert df['PoolQC'].notnull().all()
df['PoolQC'].replace({'NA':0 , 'Fa': 1, 'TA': 2, 'Gd': 3, 'Ex': 4}, inplace=True)
# Fence is an ordinal variable
df['Fence'].fillna('NA', inplace=True)
assert df['Fence'].notnull().all()
df['Fence'].replace({'NA': 0, 'MnWw': 1, 'GdWo': 2, 'MnPrv': 3, 'GdPrv': 4}, inplace=True)
# Combine YrSold and MoSold into more or less continous variable
df['YrSold'] = df['YrSold'] + (df['MoSold'] - 1) / 12.
# Still convert MoSold to categorical to keep seasonality effect
# (note: to fully do this it should be encoded into a circular 2D variable)
df['MoSold'] = df['MoSold'].astype('int').astype('category')
# Assume that LotFrontage==NaN means there is no street connected directly
df['LotFrontage'].fillna(0, inplace=True)
# No veneer area when veneer is not present
df['MasVnrArea'].fillna(0, inplace=True)
# No Garage means no year build
df['GarageYrBlt'].fillna(0, inplace=True)
# No Basement
df['BsmtFinSF1'].fillna(0, inplace=True)
df['BsmtFinSF2'].fillna(0, inplace=True)
df['BsmtUnfSF'].fillna(0, inplace=True)
df['TotalBsmtSF'].fillna(0, inplace=True)
df['BsmtFullBath'].fillna(0, inplace=True)
df['BsmtHalfBath'].fillna(0, inplace=True)
# No Garage
df['GarageCars'].fillna(0, inplace=True)
df['GarageArea'].fillna(0, inplace=True)
df = pd.get_dummies(df, dummy_na=True)
missing_columns = set(columns_needed) - set(df.columns)
if missing_columns:
print('Columns {} are missing, adding them.'.format(missing_columns))
for col in missing_columns:
df[col] = 0
assert df.notnull().all().all(), 'Nan s in {}'.format(
df.columns[df.isnull().any()].tolist())
return df
|
288cd72507d3fab705319d939a851441342e5bc0 | melvinzhang/counter-machine | /mult.py | 1,984 | 3.75 | 4 | # Correctness verified by testing all tuples (i,j) where 0 <= i,j < 100
def odd(n):
return n % 2 == 1
def even(n):
return n % 2 == 0
def div3(n):
return n % 3 == 0
def div5(n):
return n % 5 == 0
# Implemention of Schroeppel's algorithm for multipling two numbers using a 3 counter machine
# Trick to use one counter to encode the input X and Y as 2^X * 3^Y
def mult1972(A, B):
X, Y = A, B
B = 2 * B + 1
assert B == 2*Y + 1
while A > 0:
B = 2 * B
A = A - 1
assert B == 2**X * (2*Y + 1)
A = 1
while even(B):
B = B // 2
A = A * 2
B = B // 2
assert A == 2**X and B == Y
while B > 0:
A = A * 3
B = B - 1
assert A == 2**X * 3**Y and B == 0
while even(A):
A = A // 2
while div3(A):
A = A // 3
A = A * 5
B = B + 1
while div5(A):
A = A // 5
A = A * 3
return B
# Implemention of Petersen's algorithm for multipling two numbers using a 3 counter machine
# input is stored in counter A and counter B, third counter used as scratch memory
# output is stored in counter B
def mult2018(A, B):
# special case: A * 0 = 0
if B == 0: return 0
# flag in lowest bit
A = 2 * A + 1
# loop 1
while B > 0:
A = 2 * A
if odd(B): A = A + 1
A = 2 * A
B = B // 2
B = A
A = A + 1
# loop 2
while even(B):
A = 2 * A
B = B // 4
B = B - 1
# loop 3
while even(A):
B = 8 * B
A = A // 2
A = A - 1
# loop 4
while even(A):
A = A // 2
B = B // 4
if odd(A): A = A + B
A = A // 2
B = B // 2
A = A - B
B = A
B = B // 2
return B
for i in range(100):
for j in range(100):
m2018 = mult2018(i,j)
m1972 = mult1972(i,j)
print(i, j, m2018)
assert i * j == m2018 == m1972
print("All tests passed")
|
62cf1a278e484a7a71633036d652d468c8491eaa | dmaynard24/hackerrank | /python/algorithms/implementation/grid_search/grid_search.py | 368 | 3.5625 | 4 | def grid_search(g, p):
for i in range(len(g) - len(p) + 1):
index = g[i].find(p[0], 0)
while index > -1:
for j in range(1, len(p)):
if g[i + j][index:index + len(p[j])] != p[j]:
break
elif j == len(p) - 1:
return 'YES'
# look for next index in same string
index = g[i].find(p[0], index + 1)
return 'NO' |
e779b88346043b39d7664abd59393a27b6e13926 | ArroyoBernilla/t07_Arroyo.Aguilar_ | /arroyo/iteracion_en_rango4.py | 407 | 3.703125 | 4 | import os
#declaracion de variables
m,n=0,0
#imprimir los numeros que se encuentran en cierto intervalo
#input
m=int(os.sys.argv[1])
n=int(os.sys.argv[2])
#ouput
print ("Despues de resolver la inecuacion racional ")
print("Dar como respuesta los numeros que hacen que la solucion exista")
print("Rpta: ")
#iterador_rang
for numeros_enteros in range(m,n):
print (numeros_enteros)
#fin_iterador_rang
|
2df665c759713eac344cc875d1fad930cd149693 | splice415/Python-stuff | /Python Scripts/List Comprehensions.py | 1,986 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 27 01:39:35 2015
@author: Tommy Guan
"""
"""Print even numbers
"""
evens_to_50 = [i for i in range(51) if i % 2 == 0]
print(evens_to_50)
"""Doubled numbers evenly divible by two, three, four
"""
doubles_by_3 = [x*2 for x in range(1,6) if (x*2) % 3 == 0] # divible by 3
# Complete the following line. Use the line above for help.
even_squares = [x**2 for x in range(1,12) if x%2 == 0] # divisible by 2
print(even_squares)
# Cubes of numbers 1 through 10 only if cube is evenly divisible by four.
cubes_by_four = [x**3 for x in range(1,11) if (x**3)%4 == 0]
print(cubes_by_four)
# Comprehension list into a filter with lambda function
squares = [x**2 for x in range(1,11)]
print(filter(lambda x: 30 <= x <= 70, squares ))
"""Slicing
"""
# Print out only odd numbers from 1-10
my_list = range(1, 11) # List of numbers 1 - 10
# Add your code below!
print my_list[::2]
#Reversing a list
my_list = range(1, 11)
backwards = my_list[1::-1]
# Reverse list by 10
to_one_hundred = range(101)
backwards_by_tens = to_one_hundred[::-10]
print backwards_by_tens
# odds and middle slices
to_21 = range(1,22) # 1 to 21
odds = to_21[::2] # 1,3,5,...,21
middle_third = to_21[(len(to_21)/3):((len(to_21)/3)*2)] # 8,9,...,14
# if with or
threes_and_fives = [i for i in range(1,16) if i%3==0 or i%5==0]
"""Lambdas. similar to function(x) of apply() in R.
"""
my_list = range(16)
print(filter(lambda x: x % 3 == 0, my_list)) # only takes mod 3 from 0-15.
#Backward and Remove X's
garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
message = filter(lambda x: x != "X", garbled)
print(message)
languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda x: x == "Python", languages) #returns only Python |
51455bdc12e92ef8e4fb604c3a60886b122d3cc6 | highing666/leaving | /src/leetcode/91lalg/implement_queue_using_stacks.py | 782 | 3.546875 | 4 | # -*- coding: utf-8 -*-
class MyQueue:
def __init__(self):
self.stk_a = []
self.stk_b = []
def push(self, x: int) -> None:
for i in range(len(self.stk_a)):
tmp = self.stk_a.pop()
self.stk_b.append(tmp)
i += 1
self.stk_a.append(x)
for j in range(len(self.stk_b)):
tmp = self.stk_b.pop()
self.stk_a.append(tmp)
j += 1
def pop(self) -> int:
return self.stk_a.pop()
def peek(self) -> int:
return self.stk_a[-1]
def empty(self) -> bool:
return True if len(self.stk_a) == 0 else False
if __name__ == '__main__':
obj = MyQueue()
obj.push(3)
param_2 = obj.pop()
param_3 = obj.peek()
param_4 = obj.empty()
|
26700ad634b2198e29456141802f32f9f8dd1e49 | mahmudandme/project | /get_feed.py | 2,904 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# the purpose of this file is to extract the text contents from blogs that are given in a list
# (either feedlist.txt or one supplied as an argument)
import os
import sys
import re
from datetime import datetime as dt
import json
import feedparser
from BeautifulSoup import BeautifulStoneSoup
from nltk import clean_html
import codecs
import link_extractor as le
import filename_munger as fm
# Example feed:
# http://feeds.feedburner.com/oreilly/radar/atom
def cleanHtml(html):
"""
Clean up any html
"""
return BeautifulStoneSoup(clean_html(html),
convertEntities=BeautifulStoneSoup.HTML_ENTITIES).contents
def get_feed(blogurl,bloglist):
"""
Get a blog and write its contents out to a json file
"""
try:
feed_url = le.extract_feed_link_from_url(blogurl)
fp = feedparser.parse(feed_url)
except:
"Unable to retrieve or parse %s" % blogurl
return
try:
print >> sys.stderr, "Fetched %s entries from '%s'" % (len(fp.entries[0].title.encode('ascii','ignore')), fp.feed.title.encode('ascii','ignore'))
except IndexError:
print >> sys.stderr, "Retrieved no entries from '%s'" % feed_url
return None
blog_data = {'blogurl':blogurl,'title': fp.feed.title, 'blogroll':le.extract_links_from_url(blogurl,bloglist)}
blog_posts = [blog_data]
for e in fp.entries:
try:
blog_posts.append({'blogtitle':fp.feed.title,
'content': cleanHtml(e.content[0].value),
'link': e.links[0].href,
'links':le.extract_links(e.content[0].value),
'bloglinks':le.extract_links_from_list(e.content[0].value,bloglist)
})
except AttributeError:
blog_posts.append({'blogtitle':fp.feed.title,
'content': cleanHtml(e.summary),
'link': e.links[0].href,
'links':le.extract_links(e.summary),
'bloglinks':le.extract_links_from_list(e.summary,bloglist)
})
if not os.path.isdir('out'):
os.mkdir('out')
#out_file = '%s__%s.json' % (fp.feed.title.replace("'","").replace("-",""), dt.utcnow())
out_file = '%s.json' % (fm.munge(fp.feed.title))
#out_file = 'foo.json'
f = codecs.open(os.path.join(os.getcwd(), 'out', out_file), 'w',encoding='iso-8859-1')
f.write(json.dumps(blog_posts))
f.close()
print >> sys.stderr, 'Wrote output file to %s' % (f.name, )
return f.name
def main():
if len(sys.argv)>1:
blog_file = sys.argv[1]
else:
# use a default if none supplied
blog_file='feedlist.txt'
apcount={}
wordcounts={}
bloglist=[line for line in file(blog_file)]
for blogurl in bloglist:
get_feed(blogurl,bloglist)
if __name__=="__main__":
main() |
d54cdca07bf6a7587f476ad03cb5f78e63219440 | CruzJeff/CS3612017 | /Python/Exercise11.py | 833 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 30 16:52:43 2017
@author: User
"""
'''Write two functions, one that uses iteration, and the other using recursion
that achieve the following:
The input of the function is a list with numbers.
The function returns the product of the numbers in the list. '''
def iterative_mul(List):
if len(List) == 0:
return 0
result = 1
for element in List:
result = result * element
return result
def recursive_mul(List):
if len(List) == 0:
return 0
if len(List) == 1:
return List[0]
else:
return recursive_mul([List[0]]) * recursive_mul(List[1:])
List = [1,2,3,4,5,6,7,8,9,10]
empty = []
iterative_mul(List)
recursive_mul(List)
iterative_mul(empty)
recursive_mul(empty) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.